class CreateXrayImagingWidget(CreateTaskBase):
    """Widget used to create xray imaging method
    """

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

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

        # Hardware objects ----------------------------------------------------
 
        # Internal variables --------------------------------------------------
        self._xray_imaging_parameters = None
        self._processing_parameters = None
        self.init_models()

        # Graphic elements ----------------------------------------------------
        self._xray_imaging_parameters_widget = XrayImagingParametersWidget(\
             self, 'xray_imaging_widget',
             xray_imaging_params=self._xray_imaging_parameters)

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

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

        # Layout --------------------------------------------------------------
        _main_vlayout = QVBoxLayout(self)
        _main_vlayout.addWidget(self._xray_imaging_parameters_widget)
        _main_vlayout.addWidget(self._acq_widget)
        _main_vlayout.addWidget(self._data_path_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)

        # Other ---------------------------------------------------------------
        self._acq_widget.use_osc_start(False)
        self._acq_widget.use_kappa(False)
        self._acq_widget.acq_widget_layout.max_osc_range_cbx.setVisible(False)
        self._acq_widget.acq_widget_layout.first_image_label.setVisible(False)
        self._acq_widget.acq_widget_layout.first_image_ledit.setVisible(False)
        self._acq_widget.acq_widget_layout.detector_roi_mode_label.setVisible(False)
        self._acq_widget.acq_widget_layout.detector_roi_mode_combo.setVisible(False)
        self._acq_widget.acq_widget_layout.energies_combo.setVisible(False)
        self._acq_widget.acq_widget_layout.mad_cbox.setVisible(False)
        self._acq_widget.acq_widget_layout.energy_label.setVisible(False)
        self._acq_widget.acq_widget_layout.energy_ledit.setVisible(False)
        self._acq_widget.acq_widget_layout.transmission_label.setVisible(False)
        self._acq_widget.acq_widget_layout.transmission_ledit.setVisible(False)
        self._acq_widget.acq_widget_layout.resolution_label.setVisible(False)
        self._acq_widget.acq_widget_layout.resolution_ledit.setVisible(False)
        self._acq_widget.acq_widget_layout.kappa_label.setVisible(False)
        self._acq_widget.acq_widget_layout.kappa_ledit.setVisible(False)
        self._acq_widget.acq_widget_layout.kappa_phi_label.setVisible(False)
        self._acq_widget.acq_widget_layout.kappa_phi_ledit.setVisible(False)
        self._acq_widget.acq_widget_layout.shutterless_cbx.setVisible(False)

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

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

        self._xray_imaging_parameters = queue_model_objects.XrayImagingParameters()

        if self._beamline_setup_hwobj is not None:
            self._acquisition_parameters = self._beamline_setup_hwobj.\
                get_default_acquisition_parameters("default_imaging_values")
            self._path_template.suffix = 'tiff'

    def set_beamline_setup(self, bl_setup_hwobj):
        """
        In plate mode osciallation is start is in the middle of grid
        """
        CreateTaskBase.set_beamline_setup(self, bl_setup_hwobj)
        #self._xray_imaging_parameters_widget.set_beamline_setup(bl_setup_hwobj)

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

        if isinstance(tree_item, Qt4_queue_item.SampleQueueItem):
            self.setDisabled(False)
        elif isinstance(tree_item, Qt4_queue_item.BasketQueueItem):
            self.setDisabled(False)
        elif isinstance(tree_item, Qt4_queue_item.XrayImagingQueueItem):
            data_model= tree_item.get_model()

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

            self._acquisition_parameters = data_model.acquisition.acquisition_parameters
            self._acq_widget.update_data_model(self._acquisition_parameters,
                                               self._path_template)

            self._xray_imaging_parameters = data_model.xray_imaging_parameters
            self._xray_imaging_parameters_widget.update_data_model(data_model)
    

            self.setDisabled(False)

    # 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. :
        """
        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()

        #self._path_template.run_number += 1

        acq = self._create_acq(sample)
        acq.acquisition_parameters.centred_position = cpos
        dc = queue_model_objects.XrayImaging(self._xray_imaging_parameters.copy(),
                                             acq,
                                             sample.crystals[0])
        dc.set_name(acq.path_template.get_prefix())
        dc.set_number(acq.path_template.run_number)
        dc.experiment_type = queue_model_enumerables.EXPERIMENT_TYPE.IMAGING

        return [dc]
class AdvancedParametersWidget(QtGui.QWidget):
    def __init__(self, parent = None, name = "advanced_parameters_widget"):
        QtGui.QWidget.__init__(self, parent)

        # Hardware objects ----------------------------------------------------
        self._queue_model_hwobj = None
        self._beamline_setup_hwobj = None

        # Internal values -----------------------------------------------------
        self._data_collection = None
        self._tree_view_item = None

        # Properties ----------------------------------------------------------

        # Signals -------------------------------------------------------------

        # Slots ---------------------------------------------------------------

        # Graphic elements ----------------------------------------------------
        _dc_parameters_widget = QtGui.QWidget(self)
        self._data_path_widget = DataPathWidget(_dc_parameters_widget)
        self._acq_widget = AcquisitionWidget(_dc_parameters_widget,
                                            layout = 'horizontal')
        #self._acq_widget.setFixedHeight(170)
        _snapshot_widget = QtGui.QWidget(self)
        self.position_widget = uic.loadUi(os.path.join(os.path.dirname(__file__),
                                          'ui_files/Qt4_snapshot_widget_layout.ui'))

        # Layout --------------------------------------------------------------
        _dc_parameters_widget_layout = QtGui.QVBoxLayout(_dc_parameters_widget)
        _dc_parameters_widget_layout.addWidget(self._data_path_widget)
        _dc_parameters_widget_layout.addWidget(self._acq_widget)
        _dc_parameters_widget_layout.setSpacing(2)
        _dc_parameters_widget_layout.addStretch(10)
        _dc_parameters_widget_layout.setContentsMargins(0, 0, 0, 0)

        _snapshots_vlayout = QtGui.QVBoxLayout(_snapshot_widget)
        _snapshots_vlayout.addWidget(self.position_widget)
        _snapshots_vlayout.setContentsMargins(0, 0, 0, 0)
        _snapshots_vlayout.setSpacing(2)
        _snapshots_vlayout.addStretch(10)

        _main_hlayout = QtGui.QHBoxLayout(self)
        _main_hlayout.addWidget(_dc_parameters_widget)
        _main_hlayout.addWidget(_snapshot_widget)
        _main_hlayout.setSpacing(2)
        _main_hlayout.setContentsMargins(2, 2, 2, 2)
        _main_hlayout.addStretch(0)

        # 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._acq_widget.madEnergySelectedSignal.connect(\
             self.mad_energy_selected)
        self._acq_widget.acqParametersChangedSignal.connect(\
             self.handle_path_conflict)

        # Ohter ---------------------------------------------------------------
        self._acq_widget.use_osc_start(False)
        self._acq_widget.acq_widget_layout.mad_cbox.hide()
        self._acq_widget.acq_widget_layout.energies_combo.hide()
        self._acq_widget.acq_widget_layout.num_images_ledit.setEnabled(False)
        self._acq_widget.acq_widget_layout.inverse_beam_cbx.hide()
        self._acq_widget.acq_widget_layout.shutterless_cbx.hide()
        self._acq_widget.acq_widget_layout.subwedge_size_label.hide()
        self._acq_widget.acq_widget_layout.subwedge_size_ledit.hide()

    def set_beamline_setup(self, bl_setup):
        self._beamline_setup_hwobj = bl_setup
        self._acq_widget.set_beamline_setup(bl_setup)

    def _prefix_ledit_change(self, new_value):
        prefix = self._data_collection.acquisitions[0].\
                 path_template.get_prefix()
        self._data_collection.set_name(prefix)
        self._tree_view_item.setText(0, self._data_collection.get_name())

    def _run_number_ledit_change(self, new_value):
        if str(new_value).isdigit():
            self._data_collection.set_number(int(new_value))
            self._tree_view_item.setText(0, self._data_collection.get_name())

    def handle_path_conflict(self):
        if self._tree_view_item:
            dc_tree_widget = self._tree_view_item.listView().parent()
            dc_tree_widget.check_for_path_collisions()
            path_template = self._data_collection.acquisitions[0].path_template
            path_conflict = self.queue_model_hwobj.\
                        check_for_path_collisions(path_template)

            if path_conflict:
                logging.getLogger("user_level_log").\
                    error('The current path settings will overwrite data' +\
                          ' from another task. Correct the problem before collecting')
                Qt4_widget_colors.set_widget_color(widget, Qt4_widget_colors.LIGHT_RED)
            else:
                Qt4_widget_colors.set_widget_color(widget, Qt4_widget_colors.LIGHT_WHITE)

    def mad_energy_selected(self, name, energy, state):
        path_template = self._data_collection.acquisitions[0].path_template

        if state:
            path_template.mad_prefix = name
        else:
            path_template.mad_prefix = ''

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

        self._data_path_widget.set_run_number(run_number)
        self._data_path_widget.set_prefix(path_template.base_prefix)
        model = self._tree_view_item.get_model()
        model.set_name(path_template.get_prefix())
        self._tree_view_item.setText(0, model.get_name())

    def tab_changed(self):
        if self._tree_view_item:
            self.populate_widget(self._tree_view_item)

    def populate_widget(self, tree_view_item):
        self._tree_view_item = tree_view_item
        advanced_model = tree_view_item.get_model()
        self._data_collection = advanced_model.reference_image_collection
        executed = self._data_collection.is_executed()

        self._acq_widget.setEnabled(not executed)
        self._data_path_widget.setEnabled(not executed)


        image = advanced_model.grid_object.get_snapshot()
        try:
           image = image.scaled(427, 320, QtCore.Qt.KeepAspectRatio)
           self.position_widget.svideo.setPixmap(QtGui.QPixmap(image))
        except:
           pass 

        self._acquisition_mib = DataModelInputBinder(self._data_collection.\
             acquisitions[0].acquisition_parameters)

        # The acq_widget sends a signal to the path_widget, and it relies
        # on that both models upto date, we need to refactor this part
        # so that both models are set before taking ceratin actions.
        # This workaround, works for the time beeing.
        self._data_path_widget._data_model = self._data_collection.\
             acquisitions[0].path_template
        self._data_path_widget.update_data_model(self._data_collection.\
              acquisitions[0].path_template)

        self._acq_widget.update_data_model(\
             self._data_collection.acquisitions[0].acquisition_parameters,
             self._data_collection.acquisitions[0].path_template)
        #self._acq_widget.use_osc_start(False)
        invalid = self._acquisition_mib.validate_all()
        if invalid:
            msg = "This data collection has one or more incorrect parameters,"+\
                  " correct the fields marked in red to solve the problem."
            logging.getLogger("user_level_log").\
                warning(msg)
예제 #3
0
class CreateAdvancedWidget(CreateTaskBase):
    """Widget used to create advanced collection methods
    """

    def __init__(self, parent=None,name=None, fl=0):
        CreateTaskBase.__init__(self, parent, name, 
            QtCore.Qt.WindowFlags(fl), 'Advanced')

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

        # Hardware objects ----------------------------------------------------
 
        # Internal variables --------------------------------------------------
        self.init_models()
        self._advanced_methods = None
        self._grid_map = {}

        # Graphic elements ----------------------------------------------------
        self._advanced_methods_widget = uic.loadUi(os.path.join(\
            os.path.dirname(__file__), "ui_files/Qt4_advanced_methods_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')

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

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

        # Qt signal/slot connections ------------------------------------------
        self._acq_widget.acqParametersChangedSignal.\
             connect(self.acq_parameters_changed)
        self._acq_widget.madEnergySelectedSignal.\
             connect(self.mad_energy_selected)
        self._acq_widget.acq_widget_layout.set_max_osc_range_button.clicked.\
             connect(self.set_max_osc_range_clicked)

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

        self._advanced_methods_widget.grid_treewidget.itemSelectionChanged.\
             connect(self.grid_treewidget_item_selection_changed)
        self._advanced_methods_widget.draw_grid_button.clicked.\
             connect(self.draw_grid_button_clicked)
        self._advanced_methods_widget.remove_grid_button.clicked.\
             connect(self.remove_grid_button_clicked)
        self._advanced_methods_widget.hor_spacing_ledit.textChanged.\
             connect(self.spacing_changed)
        self._advanced_methods_widget.ver_spacing_ledit.textChanged.\
             connect(self.spacing_changed)

        self._advanced_methods_widget.move_right_button.clicked.\
             connect(lambda : self.move_grid("right"))
        self._advanced_methods_widget.move_left_button.clicked.\
             connect(lambda : self.move_grid("left"))
        self._advanced_methods_widget.move_up_button.clicked.\
             connect(lambda : self.move_grid("up"))
        self._advanced_methods_widget.move_down_button.clicked.\
             connect(lambda : self.move_grid("down"))        
      
        self._advanced_methods_widget.overlay_cbox.toggled.\
             connect(self.overlay_toggled)
        self._advanced_methods_widget.overlay_slider.valueChanged.\
             connect(self.overlay_alpha_changed) 
        self._advanced_methods_widget.overlay_color_button.clicked.\
             connect(self.overlay_change_color)
        self._advanced_methods_widget.move_to_grid_button.clicked.\
             connect(self.move_to_grid)

        # Other ---------------------------------------------------------------
        self._acq_widget.use_osc_start(False)
        self._acq_widget.use_kappa(False) 
        self._acq_widget.acq_widget_layout.num_images_label.setEnabled(False)
        self._acq_widget.acq_widget_layout.num_images_ledit.setEnabled(False)
        for col in range(self._advanced_methods_widget.\
                         grid_treewidget.columnCount()):
            self._advanced_methods_widget.grid_treewidget.\
                 resizeColumnToContents(col)
        self._acq_widget.acq_widget_layout.\
             set_max_osc_range_button.setEnabled(False)

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

    def _init_models(self):
        """
        Descript. :
        """
        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_advanced_values")

            if not self._advanced_methods:
                self._advanced_methods = self._beamline_setup_hwobj.get_advanced_methods()            
                if self._advanced_methods:
                   for method in self._advanced_methods:
                       self._advanced_methods_widget.method_combo.addItem(method)
                else:
                   self.setEnabled(False)    

            self.grid_treewidget_item_selection_changed()

    def set_beamline_setup(self, bl_setup_hwobj):
        """
        In plate mode osciallation is start is in the middle of grid
        """
        CreateTaskBase.set_beamline_setup(self, bl_setup_hwobj)

        self._acq_widget.acq_widget_layout.osc_start_label.\
             setText("Oscillation middle:")
        self._acq_widget.acq_widget_layout.set_max_osc_range_button.setVisible(\
             self._beamline_setup_hwobj.diffractometer_hwobj.in_plate_mode())

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

        if len(self._advanced_methods_widget.\
           grid_treewidget.selectedItems()) == 0:
            msg = "No grid selected. Continuing with automatic grid."
            logging.getLogger("GUI").info(msg)
        return result
            
    def update_processing_parameters(self, crystal):
        """
        Descript. :
        """
        return

    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._acq_widget.update_data_model(self._acquisition_parameters,
                                                self._path_template)            
        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 tree_item.get_model().is_executed():
                self.setDisabled(True)
            else:
                self.setDisabled(False)

            # sample_data_model = self.get_sample_item(tree_item).get_model()
            #self._acq_widget.disable_inverse_beam(True)
            #self._graphics_manager_hwobj.de_select_all()
            self._graphics_manager_hwobj.select_shape(data_collection.grid)

            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
            self._acq_widget.update_data_model(self._acquisition_parameters,
                                               self._path_template)
            self.get_acquisition_widget().use_osc_start(True)
        else:
            self.setDisabled(True)
        self.grid_treewidget_item_selection_changed()
  
    def _create_task(self,  sample, shape):
        """Creates tasks based on selected grids

        :param sample: selected sample object
        :type sample: SampleQueueItem
        :param shape: selected shape
        :type shape: Qt4_GraphicsLib.GraphicsItem
        """
        tasks = []
        selected_grids = self.get_selected_grids() 

        if len(selected_grids) == 0:
            selected_grids.append(self._graphics_manager_hwobj.\
                update_auto_grid()) 

        for grid in selected_grids:
            grid.set_snapshot(self._graphics_manager_hwobj.\
                  get_scene_snapshot(grid))

            grid_properties = grid.get_properties()

            acq = self._create_acq(sample)
            acq.acquisition_parameters.centred_position = \
                grid.get_centred_position()
            acq.acquisition_parameters.mesh_range = \
                [grid_properties["dx_mm"], grid_properties["dy_mm"]]
            acq.acquisition_parameters.num_lines = \
                grid_properties["num_lines"]
            acq.acquisition_parameters.num_images = \
                grid_properties["num_lines"] * \
                grid_properties["num_images_per_line"]
            grid.set_osc_range(acq.acquisition_parameters.osc_range)

            processing_parameters = 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.set_experiment_type(EXPERIMENT_TYPE.MESH)
            dc.set_requires_centring(False)
            dc.grid = grid

            exp_type = str(self._advanced_methods_widget.\
                method_combo.currentText())
            if exp_type == "MeshScan":
                dc.run_processing_parallel = "MeshScan"
                tasks.append(dc)
            elif exp_type == "XrayCentering":
                xray_centering = queue_model_objects.XrayCentering(\
                   dc, sample.crystals[0])
                dc.run_processing_parallel = "XrayCentering"
                tasks.append(xray_centering)
            self._path_template.run_number += 1

            return tasks

    def shape_created(self, shape, shape_type):
        """If a grid is created then adds it to the treewidget.
           A binding between graphical grid and treewidget item is based
           on the self._grid_map

        :param shape: graphics object
        :type shape: Qt4_GraphicsLib.GraphicsItem
        :param shape_type: type of the object (point, line, grid)
        :type shape_type: str 
        """
        if shape_type == "Grid":
            self._advanced_methods_widget.grid_treewidget.clearSelection()
            grid_properties = shape.get_properties()
            info_str_list = []
            info_str_list.append(grid_properties["name"])
            info_str_list.append("%d" % (grid_properties["beam_x_mm"] * 1000.0))
            info_str_list.append("%d" % (grid_properties["beam_y_mm"] * 1000.0))
            info_str_list.append("%d" % grid_properties["num_lines"])
            info_str_list.append("%d" % grid_properties["num_images_per_line"])

            grid_treewidget_item = QtGui.QTreeWidgetItem(\
                self._advanced_methods_widget.grid_treewidget,
                info_str_list)
            grid_treewidget_item.setSelected(True)
            self._grid_map[shape] = grid_treewidget_item
            self.grid_treewidget_item_selection_changed()
            
    def shape_deleted(self, shape, shape_type):
        """Removes shape from QTreeWidget and self._grid_map

        :param shape: graphics object
        :type shape: QtGraphicsLib.GraphicsItem
        :param shape_type: type of the object (point, line, grid)
        :type shape_type: str 
        """
        if self._grid_map.get(shape):
            treewidget_item_modelindex = self._advanced_methods_widget.\
                 grid_treewidget.indexFromItem(self._grid_map[shape])
            self._advanced_methods_widget.grid_treewidget.takeTopLevelItem(\
                 treewidget_item_modelindex.row())
            self._grid_map.pop(shape) 

    def grid_treewidget_item_selection_changed(self):
        """Updates acquisition parameters based on the selected grid.
        """
        self.enable_grid_controls(False)
      
        osc_dynamic_limits = None
        if self._beamline_setup_hwobj.diffractometer_hwobj.in_plate_mode():
            osc_dynamic_limits = self._beamline_setup_hwobj.\
                diffractometer_hwobj.get_osc_dynamic_limits()
        self._acq_widget.acq_widget_layout.\
             set_max_osc_range_button.setEnabled(False)

        for item in self._grid_map.items():
            grid = item[0]
            treewidget_item = item[1]
  
            if treewidget_item.isSelected():
                grid_properties = grid.get_properties() 
                cell_count = grid_properties["num_lines"] * \
                             grid_properties["num_images_per_line"]
                self._acq_widget.acq_widget_layout.num_images_ledit.setText(\
                     "%d" % cell_count)
                self._acq_widget.acq_widget_layout.first_image_ledit.setText(\
                     "%d" % grid_properties["first_image_num"])
                centred_point = grid.get_centred_position()
                self._acq_widget.acq_widget_layout.osc_start_ledit.setText(\
                     "%.2f" % float(centred_point.phi))
                self._acq_widget.acq_widget_layout.kappa_ledit.setText(\
                     "%.2f" % float(centred_point.kappa))
                self._acq_widget.acq_widget_layout.kappa_phi_ledit.setText(\
                     "%.2f" % float(centred_point.kappa_phi))
                self._advanced_methods_widget.hor_spacing_ledit.setText(\
                     "%.2f" % (float(grid_properties["xOffset"]) * 1000))
                self._advanced_methods_widget.ver_spacing_ledit.setText(\
                     "%.2f" % (float(grid_properties["yOffset"]) * 1000))

             
                if osc_dynamic_limits:
                    osc_range_limits = \
                        (0, 
                         min(abs(centred_point.phi - osc_dynamic_limits[0]),
                             abs(osc_dynamic_limits[1] - centred_point.phi)) /\
                         float(grid_properties["num_images_per_line"]))

                    self._acq_widget.update_osc_range_limits(osc_range_limits)
                    self._acq_widget.update_num_images_limits(\
                         grid_properties["num_lines"] * \
                         grid_properties["num_images_per_line"])

                grid.setSelected(True) 
                self.enable_grid_controls(True)
                self._acq_widget.acq_widget_layout.\
                     set_max_osc_range_button.setEnabled(True)
            else:
                grid.setSelected(False)

    def get_selected_grids(self):
        """Returns selected grids
        
        :returns: list with grid objects
        """
        selected_grids = [] 
        for grid, grid_treewidget_item in self._grid_map.iteritems():
            if grid_treewidget_item.isSelected():
                selected_grids.append(grid)
        return selected_grids

    def draw_grid_button_clicked(self):
        """Starts grid drawing
        """
        self._graphics_manager_hwobj.create_grid(self.get_spacing())

    def remove_grid_button_clicked(self):
        """Removes selected grid
        """
        grid_to_delete = None 
        for grid, treewidget_item in self._grid_map.iteritems():
            if treewidget_item.isSelected():
                grid_to_delete = grid
                break

        if grid_to_delete:
            self._graphics_manager_hwobj.delete_shape(grid_to_delete)
            self._advanced_methods_widget.move_to_grid_button.setEnabled(False)           

    def get_spacing(self):
        """Returns spacing in microns

        :returns: list of two floats
        """
        spacing = [0, 0]
        try:
           spacing[0] = float(self._advanced_methods_widget.\
               hor_spacing_ledit.text()) / 1000.0
        except:
           pass
        try:
           spacing[1] = float(self._advanced_methods_widget.\
               ver_spacing_ledit.text()) / 1000.0
        except:
           pass
        return spacing

    def spacing_changed(self, value):
        """Updates spacing of the selected grid
        """
        spacing = self.get_spacing()
        for grid_object, treewidget_item in self._grid_map.iteritems():
            if treewidget_item.isSelected():
                grid_object.set_spacing(spacing)
                #self._graphics_manager_hwobj.\
                #     update_grid_motor_positions(grid_object)
                break

    def move_to_grid(self):
        """Moves diffractometer to the center of the grid
        """
        for grid_object, treewidget_item in self._grid_map.iteritems():
            if treewidget_item.isSelected():
                self._beamline_setup_hwobj.diffractometer_hwobj.\
                     move_to_centred_position(grid_object.get_centred_position())
                break

    def overlay_toggled(self, state):
        """Toggles (on/off) overlay
        """
        for grid_object, treewidget_item in self._grid_map.iteritems():
            if treewidget_item.isSelected():
                grid_object.set_display_overlay(state)
                break
           
    def overlay_alpha_changed(self, alpha_value):
        """Changes the transperency of the grid
        """
        for grid_object, treewidget_item in self._grid_map.iteritems():
            if treewidget_item.isSelected():
                grid_object.set_fill_alpha(alpha_value)
                break

    def overlay_change_color(self):
        """Changes the default color (blue) of overlay
        """
        color = QtGui.QColorDialog.getColor()
        if color.isValid():
            for grid_object, treewidget_item in self._grid_map.iteritems():
                if treewidget_item.isSelected():
                    grid_object.set_base_color(color)
                    break

    def move_grid(self, direction):
        """Moves grid by one pix in selected direction

        :param direction: direction to move (right, left, up, down)
        :type direction: str
        """
        for grid_object, treewidget_item in self._grid_map.iteritems():
            if treewidget_item.isSelected():
                grid_object.move_by_pix(direction)
                self._graphics_manager_hwobj.\
                     update_grid_motor_positions(grid_object)
                break

    def enable_grid_controls(self, state):
        """Enables grid controls if a grid is selectd
        """
        self._advanced_methods_widget.overlay_cbox.setEnabled(state)
        self._advanced_methods_widget.overlay_slider.setEnabled(state)
        self._advanced_methods_widget.overlay_color_button.setEnabled(state)
        self._advanced_methods_widget.move_to_grid_button.setEnabled(state)
        self._advanced_methods_widget.remove_grid_button.setEnabled(state)        

        self._advanced_methods_widget.move_right_button.setEnabled(state)
        self._advanced_methods_widget.move_left_button.setEnabled(state)
        self._advanced_methods_widget.move_up_button.setEnabled(state)
        self._advanced_methods_widget.move_down_button.setEnabled(state)

    def set_max_osc_range_clicked(self, state):
        """Sets the osc range based on grid (number of images per line
           and osc in the middle of the grid)        
        """
        for grid_object, treewidget_item in self._grid_map.iteritems():
            if treewidget_item.isSelected():
                grid_properties = grid_object.get_properties()
                self._acq_widget.acq_widget_layout.osc_range_ledit.setText(\
                     "%.4f" % (self._acq_widget.osc_range_validator.top() - 0.0001))
                self._acq_widget.update_num_images_limits(\
                     grid_properties["num_lines"] * \
                     grid_properties["num_images_per_line"])
                break
class CreateAdvancedWidget(CreateTaskBase):
    """
    Descript. :
    """

    def __init__(self, parent = None,name = None, fl = 0):
        CreateTaskBase.__init__(self, parent, name, QtCore.Qt.WindowFlags(fl), 'Advanced')

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

        # Hardware objects ----------------------------------------------------
 
        # Internal variables --------------------------------------------------
        self.init_models()
        self._advanced_methods = None
        self._grid_map = {}

        # Graphic elements ----------------------------------------------------
        self._advanced_methods_widget = uic.loadUi(os.path.join(\
            os.path.dirname(__file__), "ui_files/Qt4_advanced_methods_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')

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

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

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

        self._advanced_methods_widget.grid_treewidget.itemSelectionChanged.\
             connect(self.grid_treewidget_item_selection_changed)
        self._advanced_methods_widget.draw_grid_button.clicked.\
             connect(self.draw_grid_button_clicked)
        self._advanced_methods_widget.remove_grid_button.clicked.\
             connect(self.remove_grid_button_clicked)
        self._advanced_methods_widget.hor_spacing_ledit.textChanged.\
             connect(self.spacing_changed)
        self._advanced_methods_widget.ver_spacing_ledit.textChanged.\
             connect(self.spacing_changed)

        self._advanced_methods_widget.move_right_button.clicked.\
             connect(lambda : self.move_grid("right"))
        self._advanced_methods_widget.move_left_button.clicked.\
             connect(lambda : self.move_grid("left"))
        self._advanced_methods_widget.move_up_button.clicked.\
             connect(lambda : self.move_grid("up"))
        self._advanced_methods_widget.move_down_button.clicked.\
             connect(lambda : self.move_grid("down"))        
      
        self._advanced_methods_widget.overlay_cbox.toggled.\
             connect(self.overlay_toggled)
        self._advanced_methods_widget.overlay_slider.valueChanged.\
             connect(self.overlay_alpha_changed) 
        self._advanced_methods_widget.overlay_color_button.clicked.\
             connect(self.overlay_change_color)
        self._advanced_methods_widget.move_to_grid_button.clicked.\
             connect(self.move_to_grid)

        # Other ---------------------------------------------------------------
        self._acq_widget.use_osc_start(False)
        self._acq_widget.use_kappa(False) 
        self._acq_widget.acq_widget_layout.num_images_label.setEnabled(False)
        self._acq_widget.acq_widget_layout.num_images_ledit.setEnabled(False)
        for col in range(self._advanced_methods_widget.\
                         grid_treewidget.columnCount()):
            self._advanced_methods_widget.grid_treewidget.\
                 resizeColumnToContents(col)

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

    def _init_models(self):
        """
        Descript. :
        """
        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_advanced_values")

            if not self._advanced_methods:
                self._advanced_methods = self._beamline_setup_hwobj.get_advanced_methods()            
                if self._advanced_methods:
                   for method in self._advanced_methods:
                       self._advanced_methods_widget.method_combo.addItem(method)
                else:
                   self.setEnabled(False)    
            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

            self.grid_treewidget_item_selection_changed()
        else:
            self._acquisition_parameters = queue_model_objects.AcquisitionParameters()

    def set_beamline_setup(self, bl_setup_hwobj):
        """
        In plate mode osciallation is start is in the middle of grid
        """
        CreateTaskBase.set_beamline_setup(self, bl_setup_hwobj)

        if bl_setup_hwobj.diffractometer_hwobj.in_plate_mode():
            self._acq_widget.acq_widget_layout.osc_start_label.\
                 setText("Oscillation middle:")

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

        if len(self._advanced_methods_widget.\
           grid_treewidget.selectedItems()) == 0:
            msg = "No grid selected. Continuing with automatic grid."
            logging.getLogger("GUI").info(msg)
        return result
            
    def update_processing_parameters(self, crystal):
        """
        Descript. :
        """
        return

    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._acq_widget.update_data_model(self._acquisition_parameters,
                                                self._path_template)            
        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 tree_item.get_model().is_executed():
                self.setDisabled(True)
            else:
                self.setDisabled(False)

            # sample_data_model = self.get_sample_item(tree_item).get_model()
            #self._acq_widget.disable_inverse_beam(True)
            #self._graphics_manager_hwobj.de_select_all()
            self._graphics_manager_hwobj.select_shape(data_collection.grid)

            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
            self._acq_widget.update_data_model(self._acquisition_parameters,
                                               self._path_template)
            self.get_acquisition_widget().use_osc_start(True)
        else:
            self.setDisabled(True)
  
    def _create_task(self,  sample, shape):
        """
        Descript. :
        """
        tasks = []
        selected_grids = self.get_selected_grids() 

        if len(selected_grids) == 0:
            selected_grids.append(self._graphics_manager_hwobj.\
                update_auto_grid()) 

        for grid in selected_grids:
            grid.set_snapshot(self._graphics_manager_hwobj.\
                  get_scene_snapshot(grid))

            grid_properties = grid.get_properties()

            acq = self._create_acq(sample)
            acq.acquisition_parameters.centred_position = \
                grid.get_centred_position()
            acq.acquisition_parameters.mesh_range = \
                [grid_properties["dx_mm"], grid_properties["dy_mm"]]
            acq.acquisition_parameters.num_lines = \
                grid_properties["num_lines"]
            acq.acquisition_parameters.num_images = \
                grid_properties["num_lines"] * \
                grid_properties["num_images_per_line"]
            grid.set_osc_range(acq.acquisition_parameters.osc_range)

            processing_parameters = 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.set_experiment_type(EXPERIMENT_TYPE.MESH)
            dc.set_requires_centring(False)
            dc.grid = grid

            exp_type = str(self._advanced_methods_widget.\
                method_combo.currentText())
            if exp_type == "Mesh":
                dc.run_processing_parallel = "MeshScan"
                tasks.append(dc)
            elif exp_type == "XrayCentering":
                xray_centering = queue_model_objects.XrayCentering(\
                   dc, sample.crystals[0])
                dc.run_processing_parallel = "XrayCentering"
                tasks.append(xray_centering)
            self._path_template.run_number += 1

            return tasks

    def shape_created(self, shape, shape_type):
        if shape_type == "Grid":
            self._advanced_methods_widget.grid_treewidget.clearSelection()
            grid_properties = shape.get_properties()
            info_str_list = []
            info_str_list.append(grid_properties["name"])
            info_str_list.append("%d" % (grid_properties["beam_x_mm"] * 1000.0))
            info_str_list.append("%d" % (grid_properties["beam_y_mm"] * 1000.0))
            info_str_list.append("%d" % grid_properties["num_lines"])
            info_str_list.append("%d" % grid_properties["num_images_per_line"])

            grid_treewidget_item = QtGui.QTreeWidgetItem(\
                self._advanced_methods_widget.grid_treewidget,
                info_str_list)
            grid_treewidget_item.setSelected(True)
            self._grid_map[shape] = grid_treewidget_item
            self.grid_treewidget_item_selection_changed()
            
    def shape_deleted(self, shape, shape_type):
        if self._grid_map.get(shape):
            treewidget_item_modelindex = self._advanced_methods_widget.\
                 grid_treewidget.indexFromItem(self._grid_map[shape])
            self._advanced_methods_widget.grid_treewidget.takeTopLevelItem(\
                 treewidget_item_modelindex.row())
            self._grid_map.pop(shape) 

    def grid_treewidget_item_selection_changed(self):
        self.enable_grid_controls(False)
      
        osc_dynamic_limits = None
        if self._beamline_setup_hwobj.diffractometer_hwobj.in_plate_mode():
            osc_dynamic_limits = self._beamline_setup_hwobj.\
                diffractometer_hwobj.get_osc_dynamic_limits()

        for item in self._grid_map.items():
            grid = item[0]
            treewidget_item = item[1]
  
            if treewidget_item.isSelected():
                grid_properties = grid.get_properties() 
                cell_count = grid_properties["num_lines"] * \
                             grid_properties["num_images_per_line"]
                self._acq_widget.acq_widget_layout.num_images_ledit.setText(\
                     "%d" % cell_count)
                self._acq_widget.acq_widget_layout.first_image_ledit.setText(\
                     "%d" % grid_properties["first_image_num"])
                centred_point = grid.get_centred_position()
                self._acq_widget.acq_widget_layout.osc_start_ledit.setText(\
                     "%.2f" % float(centred_point.phi))
                self._acq_widget.acq_widget_layout.kappa_ledit.setText(\
                     "%.2f" % float(centred_point.kappa))
                self._acq_widget.acq_widget_layout.kappa_phi_ledit.setText(\
                     "%.2f" % float(centred_point.kappa_phi))
                self._advanced_methods_widget.hor_spacing_ledit.setText(\
                     "%.2f" % (float(grid_properties["xOffset"]) * 1000))
                self._advanced_methods_widget.ver_spacing_ledit.setText(\
                     "%.2f" % (float(grid_properties["yOffset"]) * 1000))

             
                if osc_dynamic_limits:
                    osc_range_limits = \
                        (0, 
                         abs(osc_dynamic_limits[1] - osc_dynamic_limits[0]) /\
                         float(grid_properties["num_images_per_line"]))
                    self._acq_widget.update_osc_range_limits(osc_range_limits)
                    self._acq_widget.acq_widget_layout.osc_range_ledit.\
                         setText("%.2f" % (abs(osc_range_limits[1] -\
                                               osc_range_limits[0]))) 

                grid.setSelected(True) 
                self.enable_grid_controls(True)
            else:
                grid.setSelected(False)

    def get_selected_grids(self):
        selected_grids = [] 
        for grid, grid_treewidget_item in self._grid_map.iteritems():
            if grid_treewidget_item.isSelected():
                selected_grids.append(grid)
        return selected_grids

    def draw_grid_button_clicked(self):
        self._graphics_manager_hwobj.create_grid(self.get_spacing())

    def remove_grid_button_clicked(self):
        grid_to_delete = None 
        for grid, treewidget_item in self._grid_map.iteritems():
            if treewidget_item.isSelected():
                grid_to_delete = grid
                break
        if grid_to_delete:
            self._graphics_manager_hwobj.delete_shape(grid_to_delete)
            self._advanced_methods_widget.move_to_grid_button.setEnabled(False)           

    def get_spacing(self):
        spacing = [0, 0]
        try:
           spacing[0] = float(self._advanced_methods_widget.\
               hor_spacing_ledit.text()) / 1000.0
        except:
           pass
        try:
           spacing[1] = float(self._advanced_methods_widget.\
               ver_spacing_ledit.text()) / 1000.0
        except:
           pass
        return spacing

    def spacing_changed(self, value):
        spacing = self.get_spacing()
        for grid_object, treewidget_item in self._grid_map.iteritems():
            if treewidget_item.isSelected():
                grid_object.set_spacing(spacing)
                #self._graphics_manager_hwobj.\
                #     update_grid_motor_positions(grid_object)

    def move_to_grid(self):
        for grid_object, treewidget_item in self._grid_map.iteritems():
            if treewidget_item.isSelected():
                self._beamline_setup_hwobj.diffractometer_hwobj.\
                     move_to_centred_position(grid_object.get_centred_position())

    def overlay_toggled(self, state):
        for grid_object, treewidget_item in self._grid_map.iteritems():
            if treewidget_item.isSelected():
                grid_object.set_display_overlay(state)
           
    def overlay_alpha_changed(self, alpha_value):
        for grid_object, treewidget_item in self._grid_map.iteritems():
            if treewidget_item.isSelected():
                grid_object.set_fill_alpha(alpha_value)

    def overlay_change_color(self):
        color = QtGui.QColorDialog.getColor()
        if color.isValid():
            for grid_object, treewidget_item in self._grid_map.iteritems():
                if treewidget_item.isSelected():
                    grid_object.set_base_color(color)

    def move_grid(self, direction):
        for grid_object, treewidget_item in self._grid_map.iteritems():
            if treewidget_item.isSelected():
                grid_object.move_by_pix(direction)
                self._graphics_manager_hwobj.\
                     update_grid_motor_positions(grid_object)

    def enable_grid_controls(self, state):
        self._advanced_methods_widget.overlay_cbox.setEnabled(state)
        self._advanced_methods_widget.overlay_slider.setEnabled(state)
        self._advanced_methods_widget.overlay_color_button.setEnabled(state)
        self._advanced_methods_widget.move_to_grid_button.setEnabled(state)
        self._advanced_methods_widget.remove_grid_button.setEnabled(state)        

        self._advanced_methods_widget.move_right_button.setEnabled(state)
        self._advanced_methods_widget.move_left_button.setEnabled(state)
        self._advanced_methods_widget.move_up_button.setEnabled(state)
        self._advanced_methods_widget.move_down_button.setEnabled(state)
class CreateAdvancedWidget(CreateTaskBase):
    """
    Descript. :
    """

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

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

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

        # Internal variables --------------------------------------------------
        self.init_models()
        self._advanced_methods = None
        self._grid_map = {}

        # Graphic elements ----------------------------------------------------
        self._advanced_methods_widget = uic.loadUi(
            os.path.join(os.path.dirname(__file__), "ui_files/Qt4_advanced_methods_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"
        )

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

        # 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._advanced_methods_widget.grid_treewidget.itemSelectionChanged.connect(
            self.grid_treewidget_item_selection_changed
        )
        self._advanced_methods_widget.draw_grid_button.clicked.connect(self.draw_grid_button_clicked)
        self._advanced_methods_widget.remove_grid_button.clicked.connect(self.remove_grid_button_clicked)
        self._advanced_methods_widget.hor_spacing_ledit.textChanged.connect(self.spacing_changed)
        self._advanced_methods_widget.ver_spacing_ledit.textChanged.connect(self.spacing_changed)

        self._advanced_methods_widget.move_right_button.clicked.connect(lambda: self.move_grid("right"))
        self._advanced_methods_widget.move_left_button.clicked.connect(lambda: self.move_grid("left"))
        self._advanced_methods_widget.move_up_button.clicked.connect(lambda: self.move_grid("up"))
        self._advanced_methods_widget.move_down_button.clicked.connect(lambda: self.move_grid("down"))

        self._advanced_methods_widget.overlay_cbox.toggled.connect(self.overlay_cbox_toggled)
        self._advanced_methods_widget.overlay_alpha_progressbar.valueChanged.connect(self.overlay_alpha_changed)
        self._advanced_methods_widget.move_to_grid_button.clicked.connect(self.move_to_grid)

        # Other ---------------------------------------------------------------
        self._acq_widget.use_osc_start(False)
        self._acq_widget.use_kappa(False)
        self._acq_widget.use_kappa_phi(False)
        self._acq_widget.acq_widget_layout.num_images_label.setEnabled(False)
        self._acq_widget.acq_widget_layout.num_images_ledit.setEnabled(False)
        for col in range(self._advanced_methods_widget.grid_treewidget.columnCount()):
            self._advanced_methods_widget.grid_treewidget.resizeColumnToContents(col)

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

    def _init_models(self):
        """
        Descript. :
        """
        self._advanced = queue_model_objects.Advanced()
        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_advanced_values"
            )

            if not self._advanced_methods:
                self._advanced_methods = self._beamline_setup_hwobj.get_advanced_methods()
                if self._advanced_methods:
                    for method in self._advanced_methods:
                        self._advanced_methods_widget.method_combo.addItem(method)
                else:
                    self.setEnabled(False)
            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

            self.grid_treewidget_item_selection_changed()
        else:
            self._acquisition_parameters = queue_model_objects.AcquisitionParameters()

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

        if len(self._advanced_methods_widget.grid_treewidget.selectedItems()) == 0:
            msg = "No grid selected. Automatic grid will be used."
            logging.getLogger("user_level_log").info(msg)
        return result

    def update_processing_parameters(self, crystal):
        """
        Descript. :
        """
        return

    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._acq_widget.update_data_model(self._acquisition_parameters, self._path_template)
        elif isinstance(tree_item, Qt4_queue_item.BasketQueueItem):
            self.setDisabled(False)
        elif isinstance(tree_item, Qt4_queue_item.AdvancedQueueItem):
            advanced = tree_item.get_model()
            if tree_item.get_model().is_executed():
                self.setDisabled(True)
            else:
                self.setDisabled(False)

            # sample_data_model = self.get_sample_item(tree_item).get_model()
            # self._acq_widget.disable_inverse_beam(True)

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

            data_collection = advanced.reference_image_collection

            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)
        else:
            self.setDisabled(True)
        # if self._advanced_methods_widget.grid_treewidget.count() > 0:
        #    self._advanced_methods_widget.grid_treewidget.clearSelection()

    def _create_task(self, sample, shape):
        """
        Descript. :
        """
        data_collections = []
        selected_grids = self.get_selected_grids()

        if len(selected_grids) == 0:
            selected_grids.append(self._graphics_manager_hwobj.create_automatic_grid())

        for shape in selected_grids:
            shape.set_snapshot(self._graphics_manager_hwobj.get_snapshot(shape))

            grid_properties = shape.get_properties()

            acq = self._create_acq(sample)
            acq.acquisition_parameters.centred_position = shape.get_centred_position()
            acq.acquisition_parameters.mesh_range = [grid_properties["dx_mm"], grid_properties["dy_mm"]]
            acq.acquisition_parameters.num_lines = grid_properties["num_lines"]
            acq.acquisition_parameters.num_images = (
                grid_properties["num_lines"] * grid_properties["num_images_per_line"]
            )

            processing_parameters = 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.set_experiment_type(EXPERIMENT_TYPE.MESH)

            exp_type = str(self._advanced_methods_widget.method_combo.currentText()).title().replace(" ", "")
            advanced = queue_model_objects.Advanced(exp_type, dc, shape, sample.crystals[0])

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

            return data_collections

    def shape_created(self, shape, shape_type):
        if shape_type == "Grid":
            self._advanced_methods_widget.grid_treewidget.clearSelection()
            grid_properties = shape.get_properties()
            info_str_list = QtCore.QStringList()
            info_str_list.append(grid_properties["name"])
            info_str_list.append("%d" % grid_properties["beam_x"])
            info_str_list.append("%d" % grid_properties["beam_y"])
            info_str_list.append("%d" % grid_properties["num_lines"])
            info_str_list.append("%d" % grid_properties["num_images_per_line"])

            grid_treewidget_item = QtGui.QTreeWidgetItem(self._advanced_methods_widget.grid_treewidget, info_str_list)
            grid_treewidget_item.setSelected(True)
            self._grid_map[shape] = grid_treewidget_item
            self.grid_treewidget_item_selection_changed()

    def shape_deleted(self, shape, shape_type):
        if self._grid_map.get(shape):
            treewidget_item_modelindex = self._advanced_methods_widget.grid_treewidget.indexFromItem(
                self._grid_map[shape]
            )
            self._advanced_methods_widget.grid_treewidget.takeTopLevelItem(treewidget_item_modelindex.row())
            self._grid_map.pop(shape)

    def grid_treewidget_item_selection_changed(self):
        self._advanced_methods_widget.remove_grid_button.setEnabled(False)
        for grid_object, treewidget_item in self._grid_map.iteritems():
            if treewidget_item.isSelected():
                grid_properties = grid_object.get_properties()
                cell_count = grid_properties["num_lines"] * grid_properties["num_images_per_line"]
                self._acq_widget.acq_widget_layout.num_images_ledit.setText("%d" % cell_count)
                self._acq_widget.acq_widget_layout.first_image_ledit.setText("%d" % grid_properties["first_image_num"])
                centred_point = grid_object.get_centred_position()
                self._acq_widget.acq_widget_layout.osc_start_ledit.setText("%.2f" % float(centred_point.phi))
                self._acq_widget.acq_widget_layout.kappa_ledit.setText("%.2f" % float(centred_point.kappa))
                self._acq_widget.acq_widget_layout.kappa_phi_ledit.setText("%.2f" % float(centred_point.kappa_phi))
                self._advanced_methods_widget.hor_spacing_ledit.setText("%.2f" % float(grid_properties["xOffset"]))
                self._advanced_methods_widget.ver_spacing_ledit.setText("%.2f" % float(grid_properties["yOffset"]))
                grid_object.setSelected(True)
                self._advanced_methods_widget.remove_grid_button.setEnabled(True)
            else:
                grid_object.setSelected(False)
        self._advanced_methods_widget.move_to_grid_button.setEnabled(True)

    def get_selected_grids(self):
        selected_grids = []
        for grid, grid_treewidget_item in self._grid_map.iteritems():
            if grid_treewidget_item.isSelected():
                selected_grids.append(grid)
        return selected_grids

    def draw_grid_button_clicked(self):
        self._graphics_manager_hwobj.create_grid(self.get_spacing())

    def remove_grid_button_clicked(self):
        grid_to_delete = None
        for grid, treewidget_item in self._grid_map.iteritems():
            if treewidget_item.isSelected():
                grid_to_delete = grid
                break
        if grid_to_delete:
            self._graphics_manager_hwobj.delete_shape(grid_to_delete)
            self._advanced_methods_widget.move_to_grid_button.setEnabled(False)

    def get_spacing(self):
        spacing = [0, 0]
        try:
            spacing[0] = float(self._advanced_methods_widget.hor_spacing_ledit.text())
        except:
            pass
        try:
            spacing[1] = float(self._advanced_methods_widget.ver_spacing_ledit.text())
        except:
            pass
        return spacing

    def spacing_changed(self, value):
        spacing = self.get_spacing()
        for grid_object, treewidget_item in self._grid_map.iteritems():
            if treewidget_item.isSelected():
                grid_object.set_spacing(spacing)

    def move_to_grid(self):
        for grid_object, treewidget_item in self._grid_map.iteritems():
            if treewidget_item.isSelected():
                self._beamline_setup_hwobj.diffractometer_hwobj.move_to_centred_position(
                    grid_object.get_centred_position()
                )

    def overlay_cbox_toggled(self, state):
        for grid_object, treewidget_item in self._grid_map.iteritems():
            if treewidget_item.isSelected():
                grid_object.set_display_overlay(state)

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

    def move_grid(self, direction):
        for grid_object, treewidget_item in self._grid_map.iteritems():
            if treewidget_item.isSelected():
                grid_object.move_by_pix(direction)
                self._graphics_manager_hwobj.update_grid_motor_positions(grid_object)
class AdvancedParametersWidget(QWidget):
    def __init__(self, parent = None, name = "advanced_parameters_widget"):
        QWidget.__init__(self, parent)

        # Hardware objects ----------------------------------------------------
        self._queue_model_hwobj = None
        self._beamline_setup_hwobj = None

        # Internal values -----------------------------------------------------
        self._data_collection = None
        self._tree_view_item = None

        # Properties ----------------------------------------------------------

        # Signals -------------------------------------------------------------

        # Slots ---------------------------------------------------------------

        # Graphic elements ----------------------------------------------------
        _dc_parameters_widget = QWidget(self)
        self._data_path_widget = DataPathWidget(_dc_parameters_widget)
        self._acq_widget = AcquisitionWidget(_dc_parameters_widget,
                                            layout = 'horizontal')

        # Layout --------------------------------------------------------------
        _dc_parameters_widget_layout = QVBoxLayout(_dc_parameters_widget)
        _dc_parameters_widget_layout.addWidget(self._data_path_widget)
        _dc_parameters_widget_layout.addWidget(self._acq_widget)
        _dc_parameters_widget_layout.setSpacing(2)
        _dc_parameters_widget_layout.addStretch(10)
        _dc_parameters_widget_layout.setContentsMargins(0, 0, 0, 0)

        _main_hlayout = QHBoxLayout(self)
        _main_hlayout.addWidget(_dc_parameters_widget)
        _main_hlayout.setSpacing(2)
        _main_hlayout.setContentsMargins(2, 2, 2, 2)
        _main_hlayout.addStretch(0)

        # 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)

        # Ohter ---------------------------------------------------------------
        self._acq_widget.use_osc_start(False)
        self._acq_widget.acq_widget_layout.mad_cbox.hide()
        self._acq_widget.acq_widget_layout.energies_combo.hide()
        self._acq_widget.acq_widget_layout.shutterless_cbx.hide()

    def set_beamline_setup(self, bl_setup):
        self._beamline_setup_hwobj = bl_setup
        self._acq_widget.set_beamline_setup(bl_setup)

    def mad_energy_selected(self, name, energy, state):
        path_template = self._data_collection.acquisitions[0].path_template

        if state:
            path_template.mad_prefix = name
        else:
            path_template.mad_prefix = ''

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

        self._data_path_widget.set_run_number(run_number)
        self._data_path_widget.set_prefix(path_template.base_prefix)
        model = self._tree_view_item.get_model()
        model.set_name(path_template.get_prefix())
        self._tree_view_item.setText(0, model.get_name())

    def tab_changed(self):
        if self._tree_view_item:
            self.populate_widget(self._tree_view_item)

    def populate_widget(self, tree_view_item, data_collection):
        self._tree_view_item = tree_view_item
        self._data_collection = data_collection

        #if isinstance(tree_view_item, Qt4_queue_item.XrayCenteringQueueItem):
        #    self._data_collection = tree_view_item.get_model().reference_image_collection
        #else:
        #    self._data_collection = tree_view_item.get_model()
        executed = self._data_collection.is_executed()

        self._acq_widget.setEnabled(not executed)
        self._data_path_widget.setEnabled(not executed)

        self._acquisition_mib = DataModelInputBinder(self._data_collection.\
             acquisitions[0].acquisition_parameters)

        # The acq_widget sends a signal to the path_widget, and it relies
        # on that both models upto date, we need to refactor this part
        # so that both models are set before taking ceratin actions.
        # This workaround, works for the time beeing.
        self._data_path_widget._data_model = self._data_collection.\
             acquisitions[0].path_template
        self._data_path_widget.update_data_model(self._data_collection.\
              acquisitions[0].path_template)

        self._acq_widget.update_data_model(\
             self._data_collection.acquisitions[0].acquisition_parameters,
             self._data_collection.acquisitions[0].path_template)
        #self._acq_widget.use_osc_start(False)

        self._acq_widget.acq_widget_layout.num_images_ledit.setDisabled(data_collection.is_mesh())
        invalid = self._acquisition_mib.validate_all()
        if invalid:
            msg = "This data collection has one or more incorrect parameters,"+\
                  " correct the fields marked in red to solve the problem."
            logging.getLogger("GUI").warning(msg)
class DCParametersWidget(QtGui.QWidget):
    def __init__(self, parent = None, name = "parameter_widget"):

        QtGui.QWidget.__init__(self, parent)
        if name is not None:
            self.setObjectName(name) 

        # Properties ----------------------------------------------------------

        # Signals ------------------------------------------------------------

        # Slots ---------------------------------------------------------------

        # Hardware objects ----------------------------------------------------
        self._beamline_setup_hwobj = None

        # Internal variables --------------------------------------------------
        self._data_collection = None
        self.add_dc_cb = None
        self._tree_view_item = None

        # Graphic elements ----------------------------------------------------
        _dc_parameters_widget = QtGui.QWidget(self)
        self._data_path_widget = DataPathWidget(_dc_parameters_widget)
        self._acq_widget = AcquisitionWidget(_dc_parameters_widget, 
                                            layout = 'horizontal')
        self._processing_widget = ProcessingWidget(_dc_parameters_widget)
        
        # Layout --------------------------------------------------------------
        _dc_parameters_widget_layout = QtGui.QVBoxLayout(_dc_parameters_widget)
        _dc_parameters_widget_layout.addWidget(self._data_path_widget)
        _dc_parameters_widget_layout.addWidget(self._acq_widget)
        _dc_parameters_widget_layout.addWidget(self._processing_widget)
        _dc_parameters_widget_layout.setContentsMargins(0, 0, 0, 0)
        _dc_parameters_widget_layout.setSpacing(2)
        _dc_parameters_widget_layout.addStretch(10)

        _main_hlayout = QtGui.QHBoxLayout(self)
        _main_hlayout.addWidget(_dc_parameters_widget)
        _main_hlayout.setContentsMargins(0, 0, 0, 0)
        _main_hlayout.setSpacing(2)
        _main_hlayout.addStretch(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._acq_widget.madEnergySelectedSignal.\
             connect(self.mad_energy_selected)
        self._acq_widget.acqParametersChangedSignal.\
             connect(self.acq_parameters_changed)

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

    def set_beamline_setup(self, bl_setup):
        self._acq_widget.set_beamline_setup(bl_setup)
        self._beamline_setup_hwobj = bl_setup

    def _prefix_ledit_change(self, new_value):
        prefix = self._data_collection.acquisitions[0].\
                 path_template.get_prefix()
        self._data_collection.set_name(prefix)
        self._tree_view_item.setText(0, self._data_collection.get_name())

    def _run_number_ledit_change(self, new_value):
        if str(new_value).isdigit():
            self._data_collection.set_number(int(new_value))
            self._tree_view_item.setText(0, self._data_collection.get_name())

    def acq_parameters_changed(self):
        if self._tree_view_item is None:
            #TODO fix this
            return 
        dc_tree_widget = self._tree_view_item.listView().parent()
        dc_tree_widget.check_for_path_collisions()
        path_template = self._data_collection.acquisitions[0].path_template
        path_conflict = self.queue_model_hwobj.\
                        check_for_path_collisions(path_template)

    def __add_data_collection(self):
        return self.add_dc_cb(self._data_collection, self.collection_type)
    
    def mad_energy_selected(self, name, energy, state):
        path_template = self._data_collection.acquisitions[0].path_template

        if state:
            path_template.mad_prefix = name
        else:
            path_template.mad_prefix = ''

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

        self._data_path_widget.set_run_number(run_number)
        self._data_path_widget.set_prefix(path_template.base_prefix)
        model = self._tree_view_item.get_model()
        model.set_name(path_template.get_prefix())
        self._tree_view_item.setText(0, model.get_name())
        
    def tab_changed(self):
        if self._tree_view_item:
            self.populate_parameter_widget(self._tree_view_item)

    def set_enabled(self, state):
        self._acq_widget.setEnabled(state)
        self._data_path_widget.setEnabled(state)
        self._processing_widget.setEnabled(state)

    def populate_widget(self, item):
        data_collection = item.get_model()
        self._tree_view_item = item
        self._data_collection = data_collection
        self._acquisition_mib = DataModelInputBinder(self._data_collection.\
                                                         acquisitions[0].acquisition_parameters)

        # The acq_widget sends a signal to the path_widget, and it relies
        # on that both models upto date, we need to refactor this part
        # so that both models are set before taking ceratin actions.
        # This workaround, works for the time beeing.
        self._data_path_widget._data_model = data_collection.acquisitions[0].path_template

        self._acq_widget.set_energies(data_collection.crystal.energy_scan_result)
        self._acq_widget.update_data_model(data_collection.acquisitions[0].\
                                          acquisition_parameters,
                                          data_collection.acquisitions[0].\
                                          path_template)
        self._data_path_widget.update_data_model(data_collection.\
                                           acquisitions[0].path_template)
        self._processing_widget.update_data_model(data_collection.\
                                                 processing_parameters)

        invalid = self._acquisition_mib.validate_all()
        if invalid:
            msg = "This data collection has one or more incorrect parameters,"+\
                " correct the fields marked in red to solve the problem."

            logging.getLogger("GUI").warning(msg)
class CreateAdvancedWidget(CreateTaskBase):
    """Widget used to create advanced collection methods
    """

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

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

        # Hardware objects ----------------------------------------------------
 
        # Internal variables --------------------------------------------------
        self.init_models()
        self._advanced_methods = None
        self._grid_map = {}
        self.spacing = [0, 0]
        self.dc_selected = False

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

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

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

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

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

        # Qt signal/slot connections ------------------------------------------
        self._acq_widget.acqParametersChangedSignal.\
             connect(self.acq_parameters_changed)
        self._acq_widget.madEnergySelectedSignal.\
             connect(self.mad_energy_selected)

        self._acq_widget.acq_widget_layout.osc_range_ledit.textEdited.connect(\
             self.grid_osc_range_ledit_changed)
        self._acq_widget.acq_widget_layout.osc_total_range_ledit.textEdited.connect(\
             self.grid_osc_total_range_ledit_changed)
        self._acq_widget.acq_widget_layout.set_max_osc_range_button.clicked.\
             connect(self.set_max_osc_total_range_clicked)

        self._data_path_widget.pathTemplateChangedSignal.\
             connect(self.path_template_changed)

        self._advanced_methods_widget.grid_treewidget.itemSelectionChanged.\
             connect(self.grid_treewidget_item_selection_changed)
        self._advanced_methods_widget.draw_grid_button.clicked.\
             connect(self.draw_grid_button_clicked)
        self._advanced_methods_widget.remove_grid_button.clicked.\
             connect(self.remove_grid_button_clicked)
        self._advanced_methods_widget.hor_spacing_ledit.textEdited.\
             connect(self.hor_spacing_changed)
        self._advanced_methods_widget.ver_spacing_ledit.textEdited.\
             connect(self.ver_spacing_changed)

        self._advanced_methods_widget.move_right_button.clicked.\
             connect(lambda : self.move_grid("right"))
        self._advanced_methods_widget.move_left_button.clicked.\
             connect(lambda : self.move_grid("left"))
        self._advanced_methods_widget.move_up_button.clicked.\
             connect(lambda : self.move_grid("up"))
        self._advanced_methods_widget.move_down_button.clicked.\
             connect(lambda : self.move_grid("down"))        
      
        self._advanced_methods_widget.overlay_cbox.toggled.\
             connect(self.overlay_toggled)
        self._advanced_methods_widget.overlay_slider.valueChanged.\
             connect(self.overlay_alpha_changed) 
        self._advanced_methods_widget.overlay_color_button.clicked.\
             connect(self.overlay_change_color)
        self._advanced_methods_widget.move_to_grid_button.clicked.\
             connect(self.move_to_grid)

        # Other ---------------------------------------------------------------
        self._acq_widget.use_osc_start(False)
        self._acq_widget.use_kappa(False) 
        self._acq_widget.acq_widget_layout.num_images_label.setEnabled(False)
        self._acq_widget.acq_widget_layout.num_images_ledit.setEnabled(False)
        for col in range(self._advanced_methods_widget.\
                         grid_treewidget.columnCount()):
            self._advanced_methods_widget.grid_treewidget.\
                 resizeColumnToContents(col)

        self._acq_widget.acq_widget_layout.osc_total_range_label.setText(\
            "Total osc. range per line")

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

    def _init_models(self):
        """
        Descript. :
        """
        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_advanced_values")

            if not self._advanced_methods:
                self._advanced_methods = self._beamline_setup_hwobj.get_advanced_methods()            
                if self._advanced_methods:
                   for method in self._advanced_methods:
                       self._advanced_methods_widget.method_combo.addItem(method)
                else:
                   self.setEnabled(False)    

            self.grid_treewidget_item_selection_changed()

    def set_beamline_setup(self, bl_setup_hwobj):
        """
        In plate mode osciallation is start is in the middle of grid
        """
        CreateTaskBase.set_beamline_setup(self, bl_setup_hwobj)

        self._acq_widget.acq_widget_layout.osc_start_label.\
             setText("Oscillation middle:")

        hor_size, ver_size = bl_setup_hwobj.beam_info_hwobj.get_beam_size()
        self.spacing = [hor_size, ver_size] 
        self._advanced_methods_widget.hor_spacing_ledit.setText(\
             "%.1f" % (hor_size * 1000))
        self._advanced_methods_widget.ver_spacing_ledit.setText(\
             "%.1f" % (ver_size * 1000))

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

        if not selected_grid:
            msg = "No grid selected. Please select a grid to continue!"
            logging.getLogger("GUI").warning(msg)
            result = False
        else:
            grid_properties = selected_grid.get_properties()
            exp_time = float(self._acq_widget.\
                acq_widget_layout.exp_time_ledit.text())
            speed = grid_properties["yOffset"] / exp_time
            if speed >= 0.8:
                logging.getLogger("GUI").error(\
                    "Translation speed " + \
                    "%.3f is above the limit 0.8" % speed)
                return False
            osc_range_per_frame = float(self._acq_widget.\
                acq_widget_layout.osc_range_ledit.text())
            speed = osc_range_per_frame / exp_time
            if speed >= 166:
                logging.getLogger("GUI").error(\
                    "Rotation speed per frame " + \
                    "%.3f is above the limit 166" % speed)
                return False
            result = True

        return result
            
    def update_processing_parameters(self, crystal):
        """
        Descript. :
        """
        return

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

        if isinstance(tree_item, Qt4_queue_item.SampleQueueItem):
            pass
        elif isinstance(tree_item, Qt4_queue_item.BasketQueueItem):
            pass
            #self.setDisabled(False)
        elif isinstance(tree_item, Qt4_queue_item.DataCollectionQueueItem) or \
             isinstance(tree_item, Qt4_queue_item.XrayCenteringQueueItem):

            if isinstance(tree_item, Qt4_queue_item.XrayCenteringQueueItem):
                data_collection = tree_item.get_model().reference_image_collection                 
            else:
                data_collection = tree_item.get_model()

            if tree_item.get_model().is_executed():
                self.setDisabled(True)
            else:
                self.setDisabled(False)

            if data_collection.is_mesh():
                # sample_data_model = self.get_sample_item(tree_item).get_model()
                #self._acq_widget.disable_inverse_beam(True)
                #self._graphics_manager_hwobj.de_select_all()
                self._graphics_manager_hwobj.select_shape(data_collection.grid)
                self._advanced_methods_widget.grid_treewidget.setCurrentItem(\
                     self._grid_map[data_collection.grid])

                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
                self._acq_widget.update_data_model(self._acquisition_parameters,
                                                   self._path_template)
                self.get_acquisition_widget().use_osc_start(True)
            self.dc_selected = True
        else:
            self.setDisabled(True)
        self.grid_treewidget_item_selection_changed()
  
    def _create_task(self,  sample, shape):
        """Creates tasks based on selected grids

        :param sample: selected sample object
        :type sample: SampleQueueItem
        :param shape: selected shape
        :type shape: Qt4_GraphicsLib.GraphicsItem
        """
        tasks = []
        selected_grid = self.get_selected_grid()

        mesh_dc = self._create_dc_from_grid(sample, selected_grid)

        exp_type = str(self._advanced_methods_widget.method_combo.currentText())
        if exp_type == "MeshScan":
            tasks.append(mesh_dc)
        elif exp_type == "XrayCentering":
            xray_centering = queue_model_objects.XrayCentering(mesh_dc)
            tasks.append(xray_centering)
        else:
            logging.getLogger("GUI").\
                warning("Method %s does not exist in queue_model_objects" % exp_type)
        mesh_dc.run_processing_parallel = exp_type

        return tasks

    def shape_created(self, shape, shape_type):
        """If a grid is created then adds it to the treewidget.
           A binding between graphical grid and treewidget item is based
           on the self._grid_map

        :param shape: graphics object
        :type shape: Qt4_GraphicsLib.GraphicsItem
        :param shape_type: type of the object (point, line, grid)
        :type shape_type: str 
        """
        if shape_type == "Grid":
            self._advanced_methods_widget.grid_treewidget.clearSelection()
            grid_properties = shape.get_properties()
            info_str_list = []
            info_str_list.append(grid_properties["name"])
            info_str_list.append("%d" % grid_properties["num_lines"])
            info_str_list.append("%d" % grid_properties["num_images_per_line"])

            if not self.dc_selected:
                exp_time = max(float(grid_properties["yOffset"] / 0.795),
                      self._acq_widget.exp_time_validator.bottom()+0.00001)
                self._acq_widget.acq_widget_layout.exp_time_ledit.setText("%.6f" % exp_time)
 
            grid_treewidget_item = QTreeWidgetItem(\
                self._advanced_methods_widget.grid_treewidget,
                info_str_list)
            self._grid_map[shape] = grid_treewidget_item

            if not self.dc_selected:
                grid_treewidget_item.setSelected(True)
                self.grid_treewidget_item_selection_changed()
                self.update_grid_osc_total_range()
            
    def shape_deleted(self, shape, shape_type):
        """Removes shape from QTreeWidget and self._grid_map

        :param shape: graphics object
        :type shape: QtGraphicsLib.GraphicsItem
        :param shape_type: type of the object (point, line, grid)
        :type shape_type: str 
        """
        if self._grid_map.get(shape):
            treewidget_item_modelindex = self._advanced_methods_widget.\
                 grid_treewidget.indexFromItem(self._grid_map[shape])
            self._advanced_methods_widget.grid_treewidget.takeTopLevelItem(\
                 treewidget_item_modelindex.row())
            self._grid_map.pop(shape) 

    def grid_treewidget_item_selection_changed(self):
        """Updates acquisition parameters based on the selected grid.
        """
        self.enable_grid_controls(False)
      
        for item in self._grid_map.items():
            grid = item[0]
            treewidget_item = item[1]
  
            if treewidget_item.isSelected():
                grid_properties = grid.get_properties() 
                cell_count = grid_properties["num_lines"] * \
                             grid_properties["num_images_per_line"]
                self._acq_widget.acq_widget_layout.num_images_ledit.setText(\
                     "%d" % cell_count)
                self._acq_widget.acq_widget_layout.first_image_ledit.setText(\
                     "%d" % grid_properties["first_image_num"])
                centred_point = grid.get_centred_position()
                self._acq_widget.acq_widget_layout.kappa_ledit.setText(\
                     "%.2f" % float(centred_point.kappa))
                self._acq_widget.acq_widget_layout.kappa_phi_ledit.setText(\
                     "%.2f" % float(centred_point.kappa_phi))
                self._advanced_methods_widget.hor_spacing_ledit.setText(\
                     "%.2f" % (float(grid_properties["xOffset"]) * 1000))
                self._advanced_methods_widget.ver_spacing_ledit.setText(\
                     "%.2f" % (float(grid_properties["yOffset"]) * 1000))

                treewidget_item.setText(3, str(grid_properties["num_lines"]))
                treewidget_item.setText(4, str(grid_properties["num_images_per_line"]))
            
                grid.setSelected(True) 
                self.enable_grid_controls(True)
            else:
                grid.setSelected(False)

    def get_selected_grid(self):
        """Returns selected grids
        
        :returns: selected grid objects
        """
        for grid, grid_treewidget_item in self._grid_map.iteritems():
            if grid_treewidget_item.isSelected():
                return grid

    def get_selected_grid_properties(self):
        """Returns properties of the selected grid

        :returns: dict with properties
        """

        for grid, grid_treewidget_item in self._grid_map.iteritems():
            if grid_treewidget_item.isSelected():
                return grid.get_properties()

    def draw_grid_button_clicked(self):
        """Starts grid drawing
        """
        self._graphics_manager_hwobj.create_grid(self.spacing)

    def remove_grid_button_clicked(self):
        """Removes selected grid
        """
        grid_to_delete = self.get_selected_grid()

        if grid_to_delete:
            self._graphics_manager_hwobj.delete_shape(grid_to_delete)
            self._advanced_methods_widget.move_to_grid_button.setEnabled(False)           

    def hor_spacing_changed(self, value):
        """Updates spacing of the selected grid
        """
        try:
            self.spacing[0] = float(self._advanced_methods_widget.hor_spacing_ledit.text()) / 1000
            self.set_spacing()
        except:
            pass

    def ver_spacing_changed(self, value):
        """Updates spacing of the selected grid
        """
        try:
            self.spacing[1] = float(self._advanced_methods_widget.ver_spacing_ledit.text()) / 1000
            self.set_spacing()
        except:
            pass

    def set_spacing(self):
        if 0 in self.spacing:
            return

        for grid, treewidget_item in self._grid_map.iteritems():
            if treewidget_item.isSelected():
                grid.set_spacing(self.spacing, adjust_size=\
                   self._advanced_methods_widget.adjust_size_cbox.isChecked())
                grid_properties = grid.get_properties()

                
                treewidget_item.setText(1, str(grid_properties["num_lines"]))
                treewidget_item.setText(2, str(grid_properties["num_images_per_line"]))
                cell_count = grid_properties["num_lines"] * \
                             grid_properties["num_images_per_line"]
                self._acq_widget.acq_widget_layout.num_images_ledit.setText(\
                     str(grid_properties["num_lines"] * \
                         grid_properties["num_images_per_line"]))

    def move_to_grid(self):
        """Moves diffractometer to the center of the grid
        """
        grid = self.get_selected_grid()

        if grid:
            self._beamline_setup_hwobj.diffractometer_hwobj.\
                move_to_centred_position(grid.get_centred_position())

    def overlay_toggled(self, state):
        """Toggles (on/off) overlay
        """
        grid = self.get_selected_grid()

        if grid:
            grid.set_display_overlay(state)
           
    def overlay_alpha_changed(self, alpha_value):
        """Changes the transperency of the grid
        """
        grid = self.get_selected_grid()

        if grid:
            grid.set_fill_alpha(alpha_value)

    def overlay_change_color(self):
        """Changes the default color (blue) of overlay
        """
        color = QColorDialog.getColor()
        grid = self.get_selected_grid()

        if color.isValid() and grid:
            grid.set_base_color(color)

    def move_grid(self, direction):
        """Moves grid by one pix in selected direction

        :param direction: direction to move (right, left, up, down)
        :type direction: str
        """
        grid = self.get_selected_grid()

        if grid:
            grid.move_by_pix(direction)
            self._graphics_manager_hwobj.\
                 update_grid_motor_positions(grid)

    def enable_grid_controls(self, state):
        """Enables grid controls if a grid is selectd
        """
        self._advanced_methods_widget.overlay_cbox.setEnabled(state)
        self._advanced_methods_widget.overlay_slider.setEnabled(state)
        self._advanced_methods_widget.overlay_color_button.setEnabled(state)
        self._advanced_methods_widget.move_to_grid_button.setEnabled(state)
        self._advanced_methods_widget.remove_grid_button.setEnabled(state)        

        self._advanced_methods_widget.move_right_button.setEnabled(state)
        self._advanced_methods_widget.move_left_button.setEnabled(state)
        self._advanced_methods_widget.move_up_button.setEnabled(state)
        self._advanced_methods_widget.move_down_button.setEnabled(state)

        self._acq_widget.acq_widget_layout.set_max_osc_range_button.setEnabled(\
             state and self._in_plate_mode)

    def grid_osc_range_ledit_changed(self, new_value):
        """Osc range per frame changed

        :param new_value: new value
        :type new_value: str
        """
        
        self.update_grid_osc_total_range() 

    def grid_osc_total_range_ledit_changed(self, new_value):
        """Updates osc range per frame


        :param new_value: new value
        :type new_value: str
        """

        grid_properties = self.get_selected_grid_properties()
        if grid_properties:
            try:
                self._acq_widget.acq_widget_layout.osc_range_ledit.setText(\
                     "%.4f" % (float(new_value) / grid_properties["num_images_per_line"] - 1e-5))
            except:
                pass

    def update_grid_osc_total_range(self):
        """Updates osc range per line
        """

        grid_properties = self.get_selected_grid_properties()
        if grid_properties:
            self._acq_widget.acq_widget_layout.osc_total_range_ledit.setText(str(\
                float(self._acq_widget.acq_widget_layout.osc_range_ledit.text()) * \
                grid_properties["num_images_per_line"]))

    def set_max_osc_total_range_clicked(self, state):
        """Sets the osc range based on grid (number of images per line
           and osc in the middle of the grid)        
        """
        grid_properties = self.get_selected_grid_properties()
        if grid_properties:
            exposure_time = float(self._acq_widget.acq_widget_layout.exp_time_ledit.text())
            (lower, upper), result_exp_time = self._acq_widget.update_osc_total_range_limits(\
                 calc_by_speed=False,
                 num_images=grid_properties["num_images_per_line"],
                 exp_time=exposure_time)
            self._acq_widget.acq_widget_layout.osc_start_ledit.setText(\
                 "%.4f" % ((lower + upper) / 2))
            self._acq_widget.acq_widget_layout.osc_total_range_ledit.setText(\
                 "%.4f" % (abs(upper - lower) - 1e-4))
            self._acq_widget.acq_widget_layout.osc_range_ledit.setText(\
                 "%.4f" % (abs(lower - upper) / grid_properties["num_images_per_line"]))
            self._acq_widget.acq_widget_layout.exp_time_ledit.setText(\
                 "%.5f" % (result_exp_time))
class AdvancedParametersWidget(QtGui.QWidget):
    def __init__(self, parent=None, name="advanced_parameters_widget"):
        QtGui.QWidget.__init__(self, parent)

        # Hardware objects ----------------------------------------------------
        self._queue_model_hwobj = None
        self._beamline_setup_hwobj = None

        # Internal values -----------------------------------------------------
        self._data_collection = None
        self._tree_view_item = None

        # Properties ----------------------------------------------------------

        # Signals -------------------------------------------------------------

        # Slots ---------------------------------------------------------------

        # Graphic elements ----------------------------------------------------
        _dc_parameters_widget = QtGui.QWidget(self)
        self._data_path_widget = DataPathWidget(_dc_parameters_widget)
        self._acq_widget = AcquisitionWidget(_dc_parameters_widget,
                                             layout='horizontal')
        #self._acq_widget.setFixedHeight(170)
        _snapshot_widget = QtGui.QWidget(self)
        self.position_widget = uic.loadUi(
            os.path.join(os.path.dirname(__file__),
                         'ui_files/Qt4_snapshot_widget_layout.ui'))

        # Layout --------------------------------------------------------------
        _dc_parameters_widget_layout = QtGui.QVBoxLayout(_dc_parameters_widget)
        _dc_parameters_widget_layout.addWidget(self._data_path_widget)
        _dc_parameters_widget_layout.addWidget(self._acq_widget)
        _dc_parameters_widget_layout.setSpacing(2)
        _dc_parameters_widget_layout.addStretch(10)
        _dc_parameters_widget_layout.setContentsMargins(0, 0, 0, 0)

        _snapshots_vlayout = QtGui.QVBoxLayout(_snapshot_widget)
        _snapshots_vlayout.addWidget(self.position_widget)
        _snapshots_vlayout.setContentsMargins(0, 0, 0, 0)
        _snapshots_vlayout.setSpacing(2)
        _snapshots_vlayout.addStretch(10)

        _main_hlayout = QtGui.QHBoxLayout(self)
        _main_hlayout.addWidget(_dc_parameters_widget)
        _main_hlayout.addWidget(_snapshot_widget)
        _main_hlayout.setSpacing(2)
        _main_hlayout.setContentsMargins(2, 2, 2, 2)
        _main_hlayout.addStretch(0)

        # 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._acq_widget.madEnergySelectedSignal.connect(\
             self.mad_energy_selected)
        self._acq_widget.acqParametersChangedSignal.connect(\
             self.handle_path_conflict)

        # Ohter ---------------------------------------------------------------
        self._acq_widget.use_osc_start(False)
        self._acq_widget.acq_widget_layout.mad_cbox.hide()
        self._acq_widget.acq_widget_layout.energies_combo.hide()
        self._acq_widget.acq_widget_layout.num_images_ledit.setEnabled(False)
        self._acq_widget.acq_widget_layout.inverse_beam_cbx.hide()
        self._acq_widget.acq_widget_layout.shutterless_cbx.hide()
        self._acq_widget.acq_widget_layout.subwedge_size_label.hide()
        self._acq_widget.acq_widget_layout.subwedge_size_ledit.hide()

    def set_beamline_setup(self, bl_setup):
        self._beamline_setup_hwobj = bl_setup
        self._acq_widget.set_beamline_setup(bl_setup)

    def _prefix_ledit_change(self, new_value):
        prefix = self._data_collection.acquisitions[0].\
                 path_template.get_prefix()
        self._data_collection.set_name(prefix)
        self._tree_view_item.setText(0, self._data_collection.get_name())

    def _run_number_ledit_change(self, new_value):
        if str(new_value).isdigit():
            self._data_collection.set_number(int(new_value))
            self._tree_view_item.setText(0, self._data_collection.get_name())

    def handle_path_conflict(self):
        if self._tree_view_item:
            dc_tree_widget = self._tree_view_item.listView().parent()
            dc_tree_widget.check_for_path_collisions()
            path_template = self._data_collection.acquisitions[0].path_template
            path_conflict = self.queue_model_hwobj.\
                        check_for_path_collisions(path_template)

            if path_conflict:
                logging.getLogger("user_level_log").\
                    error('The current path settings will overwrite data' +\
                          ' from another task. Correct the problem before collecting')
                Qt4_widget_colors.set_widget_color(widget,
                                                   Qt4_widget_colors.LIGHT_RED)
            else:
                Qt4_widget_colors.set_widget_color(
                    widget, Qt4_widget_colors.LIGHT_WHITE)

    def mad_energy_selected(self, name, energy, state):
        path_template = self._data_collection.acquisitions[0].path_template

        if state:
            path_template.mad_prefix = name
        else:
            path_template.mad_prefix = ''

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

        self._data_path_widget.set_run_number(run_number)
        self._data_path_widget.set_prefix(path_template.base_prefix)
        model = self._tree_view_item.get_model()
        model.set_name(path_template.get_prefix())
        self._tree_view_item.setText(0, model.get_name())

    def tab_changed(self):
        if self._tree_view_item:
            self.populate_widget(self._tree_view_item)

    def populate_widget(self, tree_view_item):
        self._tree_view_item = tree_view_item
        advanced_model = tree_view_item.get_model()
        self._data_collection = advanced_model.reference_image_collection
        executed = self._data_collection.is_executed()

        self._acq_widget.setEnabled(not executed)
        self._data_path_widget.setEnabled(not executed)

        image = advanced_model.grid_object.get_snapshot()
        try:
            image = image.scaled(427, 320, QtCore.Qt.KeepAspectRatio)
            self.position_widget.svideo.setPixmap(QtGui.QPixmap(image))
        except:
            pass

        self._acquisition_mib = DataModelInputBinder(self._data_collection.\
             acquisitions[0].acquisition_parameters)

        # The acq_widget sends a signal to the path_widget, and it relies
        # on that both models upto date, we need to refactor this part
        # so that both models are set before taking ceratin actions.
        # This workaround, works for the time beeing.
        self._data_path_widget._data_model = self._data_collection.\
             acquisitions[0].path_template
        self._data_path_widget.update_data_model(self._data_collection.\
              acquisitions[0].path_template)

        self._acq_widget.update_data_model(\
             self._data_collection.acquisitions[0].acquisition_parameters,
             self._data_collection.acquisitions[0].path_template)
        #self._acq_widget.use_osc_start(False)
        invalid = self._acquisition_mib.validate_all()
        if invalid:
            msg = "This data collection has one or more incorrect parameters,"+\
                  " correct the fields marked in red to solve the problem."
            logging.getLogger("user_level_log").\
                warning(msg)
예제 #10
0
class CreateAdvancedScanWidget(CreateTaskBase):
    """
    Descript. :
    """

    def __init__(self, parent = None,name = None, fl = 0):
        CreateTaskBase.__init__(self, parent, name, QtCore.Qt.WindowFlags(fl), 'Advanced')

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

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

        self.__current_motor_positions = {}
        self.__list_items = {}
        self.__grid_list = []

        self.__beam_info = {}
        self.__spacing = [0, 0]

        # Graphic elements ----------------------------------------------------
        self.mesh_widget = uic.loadUi(os.path.join(os.path.dirname(__file__),
                               'ui_files/Qt4_mesh_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_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')

        # 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)

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

        # 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.connect(self._data_path_widget,
                     QtCore.SIGNAL("pathTemplateChanged"),
                     self.handle_path_conflict)

        self.mesh_widget.draw_button.clicked.connect(self.draw_button_clicked)
        self.mesh_widget.remove_button.clicked.connect(self.delete_drawing_clicked)
        self.mesh_widget.hor_spacing_ledit.textChanged.connect(self.set_hspace)
        self.mesh_widget.ver_spacing_ledit.textChanged.connect(self.set_vspace)
        self.mesh_widget.mesh_treewidget.currentItemChanged.connect(\
             self.mesh_treewidget_current_item_changed)
        self.mesh_widget.visibility_button.clicked.\
             connect(self.toggle_visibility_grid)

    def init_models(self):
        """
        Descript. :
        """
        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_advanced_values")
            self.__mini_diff_hwobj = self._beamline_setup_hwobj.\
                                     diffractometer_hwobj
        else:
            self._acquisition_parameters = queue_model_objects.AcquisitionParameters()
            self._path_template = queue_model_objects.PathTemplate()

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

        treewidget_item = self.mesh_widget.mesh_treewidget.currentItem()
        if treewidget_item is not None:
            drawing_mgr = self.__list_items[treewidget_item]
            key = str(treewidget_item.text(0))
            selected_grid = drawing_mgr._get_grid(key)[0]
        else:
            logging.getLogger("user_level_log").\
                warning("No grid selected, please select a grid.")
            selected_grid = None
        return result and selected_grid
            
    def update_processing_parameters(self, crystal):
        """
        Descript. :
        """
        return

    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 = sample_model.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.MESH:
                if tree_item.get_model().is_executed():
                    self.setDisabled(True)
                else:
                    self.setDisabled(False)

                sample_data_model = self.get_sample_item(tree_item).get_model()
                self._acq_widget.disable_inverse_beam(True)

                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
                self._acq_widget.update_data_model(self._acquisition_parameters,
                                                    self._path_template)
                self.get_acquisition_widget().use_osc_start(True)
            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):
        """
        Descript. :
        """
        data_collections = []

        selected_grid_info = None
        treewidget_item = self.mesh_widget.mesh_treewidget.selectedItem()
        if treewidget_item is not None:
            drawing_mgr = self.__list_items[treewidget_item]
            key = str(treewidget_item.text(0))
            selected_grid_info = drawing_mgr._get_grid(key)[0]

        if selected_grid_info:
            snapshot = self._graphics_manager.get_snapshot([])
            acq = self._create_acq(sample)
            cpoint = selected_grid_info.get("centred_point")
            #cpos = self._beamline_setup_hwobj.diffractometer_hwobj.convert_from_obj_to_name(cpoint)
            acq.acquisition_parameters.centred_position = cpoint
            acq.acquisition_parameters.mesh_steps = [selected_grid_info.get("steps_x"),
                                                     selected_grid_info.get("steps_y")]
            acq.acquisition_parameters.mesh_range = [selected_grid_info.get("dy_mm"),
                                                     selected_grid_info.get("dx_mm")]
            acq.acquisition_parameters.num_images = selected_grid_info.get("steps_x") * \
                                                    selected_grid_info.get("steps_y")
            
            processing_parameters = 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.set_grid_id(selected_grid_info.get("id"))
            dc.set_experiment_type(EXPERIMENT_TYPE.MESH)

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

        return data_collections            

    def set_beam_info(self, beam_info_dict):
        """
        Descript. :
        """
        self.__beam_info = beam_info_dict
        
        """if self.__drawing_mgr is not None:
            vspace, hspace = self.get_cell_dim()
            self.__drawing_mgr.set_beam_position(0, 0, self.__beam_size_x, self.__beam_size_y)
            self.__drawing_mgr.set_cell_width(self.__beam_size_x + hspace)
            self.__drawing_mgr.set_cell_height(self.__beam_size_y + vspace)
            self.__drawing_mgr.set_cell_shape(self.__beam_shape == "ellipse")"""

    def draw_button_clicked(self):
        """
        Descript. :
        """
        self.__spacing = self.get_cell_spacing()
        self._graphics_manager_hwobj.start_mesh_draw(self.__beam_info, self.__spacing)

    def mesh_created(self, mesh):
        """
        Descript. :
        """
        mesh_properties = mesh.get_properties()
        num_lines = mesh_properties.get("num_lines")
        num_images_per_line = mesh_properties.get("num_images_per_line")
        info_str_list = QtCore.QStringList()
        info_str_list.append(mesh_properties.get("name"))
        info_str_list.append(str(mesh_properties.get("beam_hor") * 1000))
        info_str_list.append(str(mesh_properties.get("beam_ver") * 1000))
        info_str_list.append(str(num_lines))
        info_str_list.append(str(num_images_per_line))
        treewidget_item = QtGui.QTreeWidgetItem(self.mesh_widget.mesh_treewidget,
                                                info_str_list)
        self.__list_items[treewidget_item] = mesh
        self._acq_widget.acq_widget.num_images_ledit.setText(str(num_lines * num_images_per_line))

        grid_coordinates = mesh.get_corner_coord()
        self.update_corner_coord(grid_coordinates, mesh)
        treewidget_item.setSelected(True)
        self.mesh_widget.mesh_treewidget.setCurrentItem(treewidget_item) 

    def update_corner_coord(self, coordinates, grid=None):
        """ 
        Descript. : updates corner points and center point of a grid
                    if no grid obejct is passed then currently selected grid is updated
        """
        if not grid:
            treewidget_item = self.mesh_widget.mesh_treewidget.selectedItem()
            grid = self.__list_items[treewidget_item]
        #if drawing_mgr.in_projection_mode():
        if grid:
            # Grid is moved from the drawing position. 
            # Grid coordinates are updated via corner points

            corner_points = []
            temp_motor_pos = self.__mini_diff_hwobj.\
               get_centred_point_from_coord(coordinates[0][0],
                                            coordinates[0][1], True)
            corner_points.append(queue_model_objects.CentredPosition(temp_motor_pos))

            temp_motor_pos = self.__mini_diff_hwobj.\
               get_centred_point_from_coord(coordinates[1][0],
                                            coordinates[1][1], True)
            corner_points.append(queue_model_objects.CentredPosition(temp_motor_pos))

            temp_motor_pos = self.__mini_diff_hwobj.\
               get_centred_point_from_coord(coordinates[2][0],
                                            coordinates[2][1], True)
            corner_points.append(queue_model_objects.CentredPosition(temp_motor_pos))

            temp_motor_pos = self.__mini_diff_hwobj.\
               get_centred_point_from_coord(coordinates[3][0],
                                            coordinates[3][1], True)
            corner_points.append(queue_model_objects.CentredPosition(temp_motor_pos))
            grid.set_motor_pos_corner(corner_points)
            # Grid is in drawing position, we have to move 

            temp_motor_pos = self.__mini_diff_hwobj.\
                   get_centred_point_from_coord(abs((coordinates[0][0] +
                                                     coordinates[1][0]) / 2),
                                                abs((coordinates[0][1] +
                                                     coordinates[2][1]) / 2))

            #cpos = self.__mini_diff_hwobj.convert_from_obj_to_name(temp_motor_pos)
            cpos = queue_model_objects.CentredPosition(temp_motor_pos)
            grid.set_motor_pos_center(cpos)


    def delete_drawing_clicked(self):
        """
        Descript. :
        """
        if len(self.__list_items):
            treewidget_item = self.mesh_widget.mesh_treewidget.currentItem()

            self._graphics_manager_hwobj.delete_shape(self.__list_items[treewidget_item])
            self.mesh_widget.mesh_treewidget.takeTopLevelItem(\
                 self.mesh_widget.mesh_treewidget.indexOfTopLevelItem(treewidget_item))

            self._acq_widget.acq_widget.num_images_ledit.setText("0")

    def get_cell_spacing(self):
        hspace = self.mesh_widget.hor_spacing_ledit.text()
        vspace = self.mesh_widget.ver_spacing_ledit.text()
        try:
            vspace = float(vspace)
        except ValueError:
            vspace = 0
        try:
            hspace = float(hspace)
        except ValueError:
            hspace = 0

        return ((hspace/1000, (vspace)/1000))

    def set_vspace(self, vspace):
        vspace, hspace = self.get_cell_spacing()
        #self._graphics_manager

    def set_hspace(self, hspace):
        vspace, hspace = self.get_cell_spacing()

    def set_beam_position(self, beam_c_x, beam_c_y, beam_size_x, beam_size_y):
        self.__cell_height = int(beam_size_x * self.__y_pixel_size)
        self.__cell_width = int(beam_size_y * self.__x_pixel_size)

        try:
            vspace, hspace = self.get_cell_spacing()
            self.__drawing_mgr.set_cell_width(self.__beam_size_x + hspace)
            self.__drawing_mgr.set_cell_height(self.__beam_size_y + vspace)

            self.__drawing_mgr.set_beam_position(0, 0, beam_size_x, beam_size_y)
            #for drawing_mgr in self.__list_items.itervalues():
            #    drawing_mgr.set_beam_position(beam_c_x, beam_c_y)
        except:
            # Drawing manager not set when called
            pass

    def mesh_treewidget_current_item_changed(self, item, prev_item):
        for index, current_item in enumerate(self.__list_items.iterkeys()):
            mesh = self.__list_items[current_item]
            if current_item == item:
                print "set_selected" 
                if mesh.isVisible():
                    self.mesh_widget.visibility_button.setText("Hide")
                else:
                    self.mesh_widget.visibility_button.setText("Show")

                grid_properties = mesh.get_properties()
                cell_count = grid_properties.get("num_lines") * \
                             grid_properties.get("num_images_per_line")
                self._acq_widget.acq_widget.num_images_ledit.setText("%d" % cell_count)
                self.mesh_widget.hor_spacing_ledit.\
                     setText("%.2f" % float(grid_properties.get("spacing_hor") * 1000))
                self.mesh_widget.ver_spacing_ledit.\
                     setText("%.2f" % float(grid_properties.get("spacing_ver") * 1000)) 
                self._acq_widget.acq_widget.first_image_ledit.\
                     setText("%d" % grid_properties.get("first_image_num"))

                centred_point = mesh.get_motor_pos_center()
                self._acq_widget.acq_widget.osc_start_ledit.setText(\
                     "%.2f" % float(centred_point.phi))
                self._acq_widget.acq_widget.kappa_ledit.setText(\
                     "%.2f" % float(centred_point.kappa))
                self._acq_widget.acq_widget.kappa_phi_ledit.setText(\
                     "%.2f" % float(centred_point.kappa_phi))

            else:
                mesh.setSelected(False)


    def toggle_visibility_grid(self):
        item = self.mesh_widget.mesh_treewidget.currentItem()

        for current_item in self.__list_items.iterkeys():
            mesh = self.__list_items[current_item]
            if current_item == item:
                if mesh.isVisible():
                    mesh.hide()
                    self.mesh_widget.visibility_button.setText("Show")
                else:
                    mesh.show()
                    self.mesh_widget.visibility_button.setText("Hide")

    def display_grids(self, display):
        for drawing_mgr in self.__list_items.values():
            drawing_mgr.show() if display else drawing_mgr.hide()

    def set_motor_pos(self, motor_pos):
        for drawing_mgr in self.__list_items.values():
            drawing_mgr.set_motor_pos_actual(motor_pos)
        self.current_motor_positions = motor_pos

    def update_grid_corner_points(self):
        for drawing_mgr in self.__list_items.values():
            grid_corner_points = drawing_mgr.get_grid_corner_points()[0]
            grid_coordinates = []
            for grid_corner_point in grid_corner_points:
                grid_coordinates.append(self.__mini_diff_hwobj.motor_positions_to_screen(grid_corner_point))
            drawing_mgr.set_grid_coordinates(grid_coordinates)[0]

    def move_to_center_point(self):
        treewidget_item = self.mesh_widget.mesh_treewidget.selectedItem()
        drawing_mgr = self.__list_items[treewidget_item]
        cpos = drawing_mgr.get_grid_center_point()[0]
        self.__mini_diff_hwobj.moveToMotorsPositions(cpos)

    def _get_grid_info(self, grid_dict):
        treewidget_item = self.mesh_widget.mesh_treewidget.selectedItem()
        if treewidget_item is not None:
            drawing_mgr = self.__list_items[treewidget_item]
            key = str(treewidget_item.text(0))
            grid_dict.update(drawing_mgr._get_grid(key)[0])

    def _set_grid_data(self, key, result_data):
        for treewidget_item in self.__list_items.keys():
            if key == str(treewidget_item.text(0)):
                drawing_mgr = self.__list_items[treewidget_item]
                drawing_mgr.set_data(result_data)
                break
예제 #11
0
class CreateAdvancedWidget(CreateTaskBase):
    """Widget used to create advanced collection methods
    """

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

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

        # Hardware objects ----------------------------------------------------
 
        # Internal variables --------------------------------------------------
        self.init_models()
        self._advanced_methods = None
        self._grid_map = {}
        self.spacing = [0, 0]
        self.dc_selected = False

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

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

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

        # Layout --------------------------------------------------------------
        _main_vlayout = QVBoxLayout(self) 
        _main_vlayout.addWidget(self._advanced_methods_widget)
        _main_vlayout.addWidget(self._acq_widget)
        _main_vlayout.addWidget(self._data_path_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._acq_widget.madEnergySelectedSignal.\
             connect(self.mad_energy_selected)

        self._acq_widget.acq_widget_layout.osc_range_ledit.textEdited.connect(\
             self.grid_osc_range_ledit_changed)
        self._acq_widget.acq_widget_layout.osc_total_range_ledit.textEdited.connect(\
             self.grid_osc_total_range_ledit_changed)

        self._data_path_widget.pathTemplateChangedSignal.\
             connect(self.path_template_changed)

        self._advanced_methods_widget.grid_treewidget.itemSelectionChanged.\
             connect(self.grid_treewidget_item_selection_changed)
        self._advanced_methods_widget.draw_grid_button.clicked.\
             connect(self.draw_grid_button_clicked)
        self._advanced_methods_widget.remove_grid_button.clicked.\
             connect(self.remove_grid_button_clicked)
        self._advanced_methods_widget.hor_spacing_ledit.textEdited.\
             connect(self.hor_spacing_changed)
        self._advanced_methods_widget.ver_spacing_ledit.textEdited.\
             connect(self.ver_spacing_changed)

        self._advanced_methods_widget.move_right_button.clicked.\
             connect(lambda : self.move_grid("right"))
        self._advanced_methods_widget.move_left_button.clicked.\
             connect(lambda : self.move_grid("left"))
        self._advanced_methods_widget.move_up_button.clicked.\
             connect(lambda : self.move_grid("up"))
        self._advanced_methods_widget.move_down_button.clicked.\
             connect(lambda : self.move_grid("down"))        
      
        self._advanced_methods_widget.overlay_cbox.toggled.\
             connect(self.overlay_toggled)
        self._advanced_methods_widget.overlay_slider.valueChanged.\
             connect(self.overlay_alpha_changed) 
        self._advanced_methods_widget.overlay_color_button.clicked.\
             connect(self.overlay_change_color)
        self._advanced_methods_widget.move_to_grid_button.clicked.\
             connect(self.move_to_grid)

        # Other ---------------------------------------------------------------
        self._acq_widget.use_osc_start(False)
        self._acq_widget.use_kappa(False) 
        self._acq_widget.acq_widget_layout.num_images_label.setEnabled(False)
        self._acq_widget.acq_widget_layout.num_images_ledit.setEnabled(False)
        for col in range(self._advanced_methods_widget.\
                         grid_treewidget.columnCount()):
            self._advanced_methods_widget.grid_treewidget.\
                 resizeColumnToContents(col)

        self._acq_widget.acq_widget_layout.osc_total_range_label.setText(\
            "Total osc. range per line")
        #self.enable_widgets(False)

    def enable_widgets(self, state):
        return
        self._acq_widget.setEnabled(state)
        self._data_path_widget.setEnabled(state)

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

    def _init_models(self):
        """
        Descript. :
        """
        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_advanced_values")

            if not self._advanced_methods:
                self._advanced_methods = self._beamline_setup_hwobj.get_advanced_methods()            
                if self._advanced_methods:
                   for method in self._advanced_methods:
                       self._advanced_methods_widget.method_combo.addItem(method)
                else:
                   self.setEnabled(False)    

            self.grid_treewidget_item_selection_changed()

    def set_beamline_setup(self, bl_setup_hwobj):
        """
        In plate mode oscillation start is in the middle of the grid
        """
        CreateTaskBase.set_beamline_setup(self, bl_setup_hwobj)

        self._acq_widget.acq_widget_layout.osc_start_label.\
             setText("Oscillation middle:")

        hor_size, ver_size = bl_setup_hwobj.beam_info_hwobj.get_beam_size()
        self.spacing[0] = hor_size
        self.spacing[1] = ver_size
        self._advanced_methods_widget.hor_spacing_ledit.setText(\
             "%.1f" % (hor_size * 1000))
        self._advanced_methods_widget.ver_spacing_ledit.setText(\
             "%.1f" % (ver_size * 1000))

    def set_beam_info(self, beam_info):
        self.spacing[0] = beam_info["size_x"]
        self.spacing[1] = beam_info["size_y"]
        self._advanced_methods_widget.hor_spacing_ledit.setText(\
             "%.1f" % (beam_info["size_x"] * 1000))
        self._advanced_methods_widget.ver_spacing_ledit.setText(\
             "%.1f" % (beam_info["size_x"] * 1000))

    def approve_creation(self):
        """
        Descript. :
        """
        result = CreateTaskBase.approve_creation(self)
        selected_grid = self.get_selected_shapes()[0]

        if not selected_grid:
            msg = "No grid selected. Please select a grid to continue!"
            logging.getLogger("GUI").warning(msg)
            result = False
            #selected_grid = self._graphics_manager_hwobj.get_auto_grid()
        else:
            grid_properties = selected_grid.get_properties()
            exp_time = float(self._acq_widget.acq_widget_layout.exp_time_ledit.text())
            speed = grid_properties["yOffset"] / exp_time
            if speed >= 2.25:
                logging.getLogger("GUI").error("Translation speed %.3f is above the limit 2.25" % speed)
                return False
            osc_range_per_frame = float(self._acq_widget.acq_widget_layout.osc_range_ledit.text())
            speed = osc_range_per_frame / exp_time
            if speed >= 300:
                logging.getLogger("GUI").error("Rotation speed per frame %.3f is above the limit 300" % speed)
                return False
        return result
            
    def update_processing_parameters(self, crystal):
        """
        Descript. :
        """
        return

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

        if isinstance(tree_item, Qt4_queue_item.SampleQueueItem):
            pass
        elif isinstance(tree_item, Qt4_queue_item.BasketQueueItem):
            pass
            #self.setDisabled(False)
        elif isinstance(tree_item, Qt4_queue_item.DataCollectionQueueItem) or \
             isinstance(tree_item, Qt4_queue_item.XrayCenteringQueueItem):

            if isinstance(tree_item, Qt4_queue_item.XrayCenteringQueueItem):
                data_collection = tree_item.get_model().reference_image_collection                 
            else:
                data_collection = tree_item.get_model()

            if tree_item.get_model().is_executed():
                self.setDisabled(True)
            else:
                self.setDisabled(False)

            if data_collection.is_mesh():
                # sample_data_model = self.get_sample_item(tree_item).get_model()
                #self._acq_widget.disable_inverse_beam(True)
                #self._graphics_manager_hwobj.de_select_all()
                self._graphics_manager_hwobj.select_shape(data_collection.grid)
                self._advanced_methods_widget.grid_treewidget.setCurrentItem(\
                     self._grid_map[data_collection.grid])

                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
                self._acq_widget.update_data_model(self._acquisition_parameters,
                                                   self._path_template)
                #self.get_acquisition_widget().use_osc_start(True)
            self.dc_selected = True
        else:
            self.setDisabled(True)
        self.grid_treewidget_item_selection_changed()
  
    def _create_task(self,  sample, shape):
        """Creates tasks based on selected grids

        :param sample: selected sample object
        :type sample: SampleQueueItem
        :param shape: selected shape
        :type shape: Qt4_GraphicsLib.GraphicsItem
        """
        tasks = []
        selected_grid = self.get_selected_shapes()[0]
        mesh_dc = self._create_dc_from_grid(sample, selected_grid)

        exp_type = str(self._advanced_methods_widget.method_combo.currentText())
        if exp_type == "MeshScan":
            tasks.append(mesh_dc)
        elif exp_type == "XrayCentering":
            xray_centering = queue_model_objects.XrayCentering(mesh_dc)
            tasks.append(xray_centering)
        else:
            logging.getLogger("GUI").\
                warning("Method %s does not exist in queue_model_objects" % exp_type)
        mesh_dc.run_processing_parallel = exp_type

        return tasks

    def shape_created(self, shape, shape_type):
        """If a grid is created then adds it to the treewidget.
           A binding between graphical grid and treewidget item is based
           on the self._grid_map

        :param shape: graphics object
        :type shape: Qt4_GraphicsLib.GraphicsItem
        :param shape_type: type of the object (point, line, grid)
        :type shape_type: str 
        """
        if shape_type == "Grid":
            self._advanced_methods_widget.grid_treewidget.clearSelection()
            grid_properties = shape.get_properties()
            info_str_list = []
            info_str_list.append(grid_properties["name"])
            info_str_list.append("%d" % grid_properties["num_lines"])
            info_str_list.append("%d" % grid_properties["num_images_per_line"])

            if not self.dc_selected:
                exp_time = max(float(grid_properties["yOffset"] / 2.245),
                      self._acq_widget.exp_time_validator.bottom()+0.00001)
                self._acq_widget.acq_widget_layout.exp_time_ledit.setText("%.6f" % exp_time)
 
            grid_treewidget_item = QTreeWidgetItem(\
                self._advanced_methods_widget.grid_treewidget,
                info_str_list)
            self._grid_map[shape] = grid_treewidget_item

            if not self.dc_selected:
                grid_treewidget_item.setSelected(True)
                self.grid_treewidget_item_selection_changed()
                if self._acq_widget.acq_widget_layout.max_osc_range_cbx.isChecked():
                    self._acq_widget.update_osc_total_range_limits(grid_properties["num_images_per_line"])
                else:
                    self.update_grid_osc_total_range()
            
    def shape_deleted(self, shape, shape_type):
        """Removes shape from QTreeWidget and self._grid_map

        :param shape: graphics object
        :type shape: QtGraphicsLib.GraphicsItem
        :param shape_type: type of the object (point, line, grid)
        :type shape_type: str 
        """
        if self._grid_map.get(shape):
            treewidget_item_modelindex = self._advanced_methods_widget.\
                 grid_treewidget.indexFromItem(self._grid_map[shape])
            self._advanced_methods_widget.grid_treewidget.takeTopLevelItem(\
                 treewidget_item_modelindex.row())
            self._grid_map.pop(shape) 

    def grid_treewidget_item_selection_changed(self):
        """Updates acquisition parameters based on the selected grid.
        """
        self.enable_grid_controls(False)
      
        for item in self._grid_map.items():
            grid = item[0]
            treewidget_item = item[1]
  
            if treewidget_item.isSelected():
                grid_properties = grid.get_properties() 
                cell_count = grid_properties["num_lines"] * \
                             grid_properties["num_images_per_line"]
                self._acq_widget.acq_widget_layout.num_images_ledit.setText(\
                     "%d" % cell_count)
                self._acq_widget.acq_widget_layout.first_image_ledit.setText(\
                     "%d" % grid_properties["first_image_num"])
                centred_point = grid.get_centred_position()
                self._acq_widget.acq_widget_layout.kappa_ledit.setText(\
                     "%.2f" % float(centred_point.kappa))
                self._acq_widget.acq_widget_layout.kappa_phi_ledit.setText(\
                     "%.2f" % float(centred_point.kappa_phi))
                self._advanced_methods_widget.hor_spacing_ledit.setText(\
                     "%.2f" % (float(grid_properties["xOffset"]) * 1000))
                self._advanced_methods_widget.ver_spacing_ledit.setText(\
                     "%.2f" % (float(grid_properties["yOffset"]) * 1000))

                treewidget_item.setText(3, str(grid_properties["num_lines"]))
                treewidget_item.setText(4, str(grid_properties["num_images_per_line"]))
            
                grid.setSelected(True) 
                self.enable_grid_controls(True)
            else:
                grid.setSelected(False)

    def get_selected_shapes(self):
        """Returns selected grids
        
        :returns: selected grid objects
        """
        shapes = []
        for grid, grid_treewidget_item in self._grid_map.iteritems():
            if grid_treewidget_item.isSelected():
                shapes.append(grid)
        return shapes

    def get_selected_grid_properties(self):
        """Returns properties of the selected grid

        :returns: dict with properties
        """

        for grid, grid_treewidget_item in self._grid_map.iteritems():
            if grid_treewidget_item.isSelected():
                return grid.get_properties()

    def draw_grid_button_clicked(self):
        """Starts grid drawing
        """
        self._graphics_manager_hwobj.create_grid(self.spacing)

    def remove_grid_button_clicked(self):
        """Removes selected grid
        """
        grid_to_delete = self.get_selected_shapes()[0]

        if grid_to_delete:
            self._graphics_manager_hwobj.delete_shape(grid_to_delete)
            self._advanced_methods_widget.move_to_grid_button.setEnabled(False)           

    def hor_spacing_changed(self, value):
        """Updates spacing of the selected grid
        """
        try:
            self.spacing[0] = float(self._advanced_methods_widget.hor_spacing_ledit.text()) / 1000
            self.set_spacing()
        except:
            pass

    def ver_spacing_changed(self, value):
        """Updates spacing of the selected grid
        """
        try:
            self.spacing[1] = float(self._advanced_methods_widget.ver_spacing_ledit.text()) / 1000
            self.set_spacing()
        except:
            pass

    def set_spacing(self):
        if 0 in self.spacing:
            return

        for grid, treewidget_item in self._grid_map.iteritems():
            if treewidget_item.isSelected():
                grid.set_spacing(self.spacing, adjust_size=\
                   self._advanced_methods_widget.adjust_size_cbox.isChecked())
                grid_properties = grid.get_properties()

                
                treewidget_item.setText(1, str(grid_properties["num_lines"]))
                treewidget_item.setText(2, str(grid_properties["num_images_per_line"]))
                cell_count = grid_properties["num_lines"] * \
                             grid_properties["num_images_per_line"]
                self._acq_widget.acq_widget_layout.num_images_ledit.setText(\
                     str(grid_properties["num_lines"] * \
                         grid_properties["num_images_per_line"]))

    def move_to_grid(self):
        """Moves diffractometer to the center of the grid
        """
        grid = self.get_selected_shapes()[0]

        if grid:
            self._beamline_setup_hwobj.diffractometer_hwobj.\
                move_to_centred_position(grid.get_centred_position())

    def overlay_toggled(self, state):
        """Toggles (on/off) overlay
        """
        grid = self.get_selected_shapes()[0]

        if grid:
            grid.set_display_overlay(state)
           
    def overlay_alpha_changed(self, alpha_value):
        """Changes the transperency of the grid
        """
        grid = self.get_selected_shapes()[0]

        if grid:
            grid.set_fill_alpha(alpha_value)

    def overlay_change_color(self):
        """Changes the default color (blue) of overlay
        """
        color = QColorDialog.getColor()
        grid = self.get_selected_shapes()[0]

        if color.isValid() and grid:
            grid.set_base_color(color)

    def move_grid(self, direction):
        """Moves grid by one pix in selected direction

        :param direction: direction to move (right, left, up, down)
        :type direction: str
        """
        grid = self.get_selected_shapes()[0]

        if grid:
            grid.move_by_pix(direction)
            self._graphics_manager_hwobj.\
                 update_grid_motor_positions(grid)

    def enable_grid_controls(self, state):
        """Enables grid controls if a grid is selectd
        """
        self._advanced_methods_widget.overlay_cbox.setEnabled(state)
        self._advanced_methods_widget.overlay_slider.setEnabled(state)
        self._advanced_methods_widget.overlay_color_button.setEnabled(state)
        self._advanced_methods_widget.move_to_grid_button.setEnabled(state)
        self._advanced_methods_widget.remove_grid_button.setEnabled(state)        

        self._advanced_methods_widget.move_right_button.setEnabled(state)
        self._advanced_methods_widget.move_left_button.setEnabled(state)
        self._advanced_methods_widget.move_up_button.setEnabled(state)
        self._advanced_methods_widget.move_down_button.setEnabled(state)

        self._acq_widget.acq_widget_layout.max_osc_range_cbx.setEnabled(\
             state and self._in_plate_mode)

        self.enable_widgets(state)
        self._acq_widget.emit_acq_parameters_changed()

    def grid_osc_range_ledit_changed(self, new_value):
        """Osc range per frame changed

        :param new_value: new value
        :type new_value: str
        """
        
        self.update_grid_osc_total_range() 

    def grid_osc_total_range_ledit_changed(self, new_value):
        """Updates osc range per frame


        :param new_value: new value
        :type new_value: str
        """

        grid_properties = self.get_selected_grid_properties()
        if grid_properties:
            try:
                self._acq_widget.acq_widget_layout.osc_range_ledit.setText(\
                     "%.4f" % (float(new_value) / grid_properties["num_images_per_line"] - 1e-5))
                self._acq_widget.emit_acq_parameters_changed()
            except:
                pass

    def update_grid_osc_total_range(self):
        """Updates osc range per line
        """

        grid_properties = self.get_selected_grid_properties()
        if grid_properties:
            self._acq_widget.acq_widget_layout.osc_total_range_ledit.setText(str(\
                float(self._acq_widget.acq_widget_layout.osc_range_ledit.text()) * \
                grid_properties["num_images_per_line"]))

    def set_osc_total_range(self, num_images=None, mesh=False):
        grid_properties = self.get_selected_grid_properties()
        if grid_properties:
            CreateTaskBase.set_osc_total_range(self, grid_properties["num_images_per_line"], mesh=True)    
class CreateAdvancedScanWidget(CreateTaskBase):
    """
    Descript. :
    """

    def __init__(self, parent = None,name = None, fl = 0):
        CreateTaskBase.__init__(self, parent, name, QtCore.Qt.WindowFlags(fl), 'Advanced')

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

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

        self.__current_motor_positions = {}
        self.__cell_width = 0
        self.__cell_height = 0
        self.__list_items = {}
        self.__item_counter = 0
        self.__grid_list = []

        self.__canvas = None
        self.__matrix = None
        self.__event_mgr = None
        self.__drawing_object_layer = None
        self.__drawing_mgr = None
        self.__x_pixel_size = 1
        self.__y_pixel_size = 1
        self.__beam_size_x = 0
        self.__beam_size_y = 0
        self.__angle_active = 0

        # Graphic elements ----------------------------------------------------
        self.mesh_widget = uic.loadUi(os.path.join(os.path.dirname(__file__),
                               'ui_files/Qt4_mesh_widget_layout.ui'))

        self._acq_gbox = QtGui.QGroupBox('Acquisition', self)
        self._acq_gbox.setObjectName('acq_gbox')
        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_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')

        # Layout --------------------------------------------------------------
        self._acq_gbox_layout = QtGui.QVBoxLayout(self)
        self._acq_gbox_layout.addWidget(self._acq_widget)
        self._acq_gbox_layout.setSpacing(0)
        self._acq_gbox_layout.setContentsMargins(0,0,0,0)
        self._acq_gbox.setLayout(self._acq_gbox_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)

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

        # 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.connect(self._data_path_widget,
                     QtCore.SIGNAL("pathTemplateChanged"),
                     self.handle_path_conflict)

        self.mesh_widget.draw_button.clicked.connect(self.draw_button_clicked)
      
        self.mesh_widget.add_button.clicked.connect(self.add_drawing_clicked)

        self.mesh_widget.remove_button.clicked.connect(self.delete_drawing_clicked)

        self.mesh_widget.hor_spacing_ledit.textChanged.\
             connect(self.set_hspace)

        self.mesh_widget.ver_spacing_ledit.textChanged.\
             connect(self.set_vspace)

        QtCore.QObject.connect(self.mesh_widget.mesh_treewidget,
                               QtCore.SIGNAL("itemSelectionChanged()"),
                               self.mesh_treewidget_selection_changed)

        self.mesh_widget.visibility_button.clicked.\
             connect(self.toggle_visibility_grid)

        #TODO somehow make this better
        for child in self._acq_widget.children(): 
            if child.children():
                for child_child in child.children():
                    if hasattr(child_child, 'hide'):
                        child_child.hide()
         
        self._acq_widget.findChild(QtGui.QLabel, "osc_range_label").show()
        self._acq_widget.findChild(QtGui.QLineEdit, "osc_range_ledit").show()
        #self._acq_widget.findChild(QtGui.QLabel, "detector_mode_label").show()
        #self._acq_widget.findChild(QtGui.QComboBox, "detector_mode_combo").show()
        self._acq_widget.findChild(QtGui.QLabel, "exp_time_label").show()
        self._acq_widget.findChild(QtGui.QLineEdit, "exp_time_ledit").show()
        self._acq_widget.findChild(QtGui.QLabel, "energy_label").show()
        self._acq_widget.findChild(QtGui.QLineEdit, "energy_ledit").show()
        self._acq_widget.findChild(QtGui.QLabel, "resolution_label").show()
        self._acq_widget.findChild(QtGui.QLineEdit,"resolution_ledit").show()
        #self._acq_widget.transmission_label.show()
        #self._acq_widget.transmission_ledit.show()
        #self._acq_widget.setFixedHeight(185)

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

        return  
        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_advanced_values")
            self.__mini_diff_hwobj = self._beamline_setup_hwobj.\
                                     diffractometer_hwobj
        else:
            self._acquisition_parameters = queue_model_objects.AcquisitionParameters()
            self._path_template = queue_model_objects.PathTemplate()

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

        list_view_item = self.mesh_widget.mesh_treewidget.currentItem()
        if list_view_item is not None:
            drawing_mgr = self.__list_items[list_view_item]
            key = str(list_view_item.text(0))
            selected_grid = drawing_mgr._get_grid(key)[0]
        else:
            logging.getLogger("user_level_log").\
                warning("No grid selected, please select a grid.")
            selected_grid = None
        return result and selected_grid
            
    def update_processing_parameters(self, crystal):
        """
        Descript. :
        """
        return

    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 = sample_model.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.MESH:
                if tree_item.get_model().is_executed():
                    self.setDisabled(True)
                else:
                    self.setDisabled(False)

                sample_data_model = self.get_sample_item(tree_item).get_model()
                self._acq_widget.disable_inverse_beam(True)

                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
                self._acq_widget.update_data_model(self._acquisition_parameters,
                                                    self._path_template)
                self.get_acquisition_widget().use_osc_start(True)
            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):
        """
        Descript. :
        """
        data_collections = []

        selected_grid_info = None
        list_view_item = self.mesh_widget.mesh_treewidget.selectedItem()
        if list_view_item is not None:
            drawing_mgr = self.__list_items[list_view_item]
            key = str(list_view_item.text(0))
            selected_grid_info = drawing_mgr._get_grid(key)[0]

        if selected_grid_info:
            snapshot = self._graphics_manager.get_snapshot([])
            acq = self._create_acq(sample)
            cpoint = selected_grid_info.get("centred_point")
            #cpos = self._beamline_setup_hwobj.diffractometer_hwobj.convert_from_obj_to_name(cpoint)
            acq.acquisition_parameters.centred_position = cpoint
            acq.acquisition_parameters.mesh_steps = [selected_grid_info.get("steps_x"),
                                                     selected_grid_info.get("steps_y")]
            acq.acquisition_parameters.mesh_range = [selected_grid_info.get("dy_mm"),
                                                     selected_grid_info.get("dx_mm")]
            acq.acquisition_parameters.num_images = selected_grid_info.get("steps_x") * \
                                                    selected_grid_info.get("steps_y")
            
            processing_parameters = 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.set_grid_id(selected_grid_info.get("id"))
            dc.set_experiment_type(EXPERIMENT_TYPE.MESH)

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

        return data_collections            

    def connectToView(self, view_dict):
        """
        Descript. :
        """
        qub_image = view_dict.get("drawing")
        if qub_image is not None:
            self.__canvas = qub_image.canvas()
            self.__matrix = qub_image.matrix()
            self.__event_mgr = qub_image
            #self.__drawing_mgr = Qub2PointSurfaceDrawingMgr(self.__canvas, self.__matrix)

    def set_kappa(self, new_value):
        """
        Descript. :
        """
        self.kappa_position = new_value
        self.mesh_widget.findChild(QtGui.QLineEdit, "kappa_ledit").\
             setText("%.2f" % float(new_value))

    def set_kappa_phi(self, new_value):
        """
        Descript. :
        """
        self.kappa_phi_position = new_value
        self.mesh_widget.findChild(QtGui.QLineEdit, "kappa_phi_ledit").\
             setText("%.2f" % float(new_value))

    def update_osc_start(self, new_value):
        """
        Descript. :
        """
        self.omega_position = new_value
        self.mesh_widget.findChild(QtGui.QLineEdit, "omega_ledit").\
             setText("%.2f" % float(new_value))

    def set_beam_info(self, beam_info_dict):
        """
        Descript. :
        """
        self.__beam_size_x = beam_info_dict.get("size_x", 0)
        self.__beam_size_y = beam_info_dict.get("size_y", 0)
        self.__beam_shape = beam_info_dict.get("shape", 0)

        if self.__drawing_mgr is not None:
            vspace, hspace = self.get_cell_dim()
            self.__drawing_mgr.set_beam_position(0, 0, self.__beam_size_x, self.__beam_size_y)
            self.__drawing_mgr.set_cell_width(self.__beam_size_x + hspace)
            self.__drawing_mgr.set_cell_height(self.__beam_size_y + vspace)
            self.__drawing_mgr.set_cell_shape(self.__beam_shape == "ellipse")

    def draw_button_clicked(self):
        """
        Descript. :
        """
        self._graphics_manager_hwobj.start_mesh_draw()


        return 

        if self.__mini_diff_hwobj is not None:
            (self.__x_pixel_size, self.__y_pixel_size) = \
                    self.__mini_diff_hwobj.get_pixels_per_mm()
        self.__drawing_mgr = Qub2PointSurfaceDrawingMgr(self.__canvas, self.__matrix)
        self.__drawing_mgr.setAutoDisconnectEvent(False)
        drawing_object = graphics_manager.CanvasGrid(self.__canvas)
        self.__drawing_mgr.addDrawingObject(drawing_object)
        self.__event_mgr.addDrawingMgr(self.__drawing_mgr)
        vspace, hspace = self.get_cell_dim()
        self.__drawing_mgr.set_cell_width(self.__beam_size_x + hspace)
        self.__drawing_mgr.set_cell_height(self.__beam_size_y + vspace)
        self.__drawing_mgr.set_cell_shape(self.__beam_shape == "ellipse")
        self.__drawing_mgr.set_x_pixel_size(self.__x_pixel_size)
        self.__drawing_mgr.set_y_pixel_size(self.__y_pixel_size)
        self.__drawing_mgr.set_beam_position(0, 0, self.__beam_size_x, self.__beam_size_y)
        self.__drawing_mgr.startDrawing()
        self.__drawing_mgr.setEndDrawCallBack(self.end_surface_drawing)
        self.__drawing_mgr.setColor(qt.Qt.darkGreen)

    def end_surface_drawing(self, drawing_mgr = None):
        """
        Descript. :
        """
        drawing_mgr.reshape()

    def add_drawing_clicked(self):
        """
        Descript. :
        """
        self._graphics_manager_hwobj.save_current_mesh()

        return

        if self.__drawing_mgr.isVisible()[0]:
            self.__item_counter += 1
            name = ("Grid - %i" % self.__item_counter)
            beam_width = str(self.__beam_size_x * 1000)
            beam_height = str(self.__beam_size_y * 1000)
            vspace, hspace = self.get_cell_dim()
            vspace = vspace * 1000
            hspace = hspace * 1000
            list_view_item = qt.QListViewItem(self.mesh_widget.mesh_treewidget, name,
                beam_width,  beam_height, str(hspace), str(vspace))
            self.__list_items[list_view_item] = self.__drawing_mgr
            self.__drawing_mgr.stopDrawing()
            self.__drawing_mgr.set_label(name)
            self.__drawing_mgr.set_angles(self.omega_position,
                                          self.kappa_position,
                                          self.kappa_phi_position)[0]
            cell_count = self.__drawing_mgr.get_total_steps()[0]
            self.mesh_widget.findChild(QtGui.QLineEdit, "num_images_ledit").\
                 setText("%d" % cell_count)

            self.__drawing_mgr.set_motor_pos_created(deepcopy(self.current_motor_positions))[0]
            self.__drawing_mgr.set_motor_pos_actual(self.current_motor_positions)[0]
            grid_coordinates = self.__drawing_mgr.get_grid_coordinates()[0]

            corner_points = []
            temp_motor_pos = self.__mini_diff_hwobj.\
               get_centred_point_from_coord(grid_coordinates[0][0],
                                            grid_coordinates[0][1], True)
            corner_points.append(temp_motor_pos)
            temp_motor_pos = self.__mini_diff_hwobj.\
               get_centred_point_from_coord(grid_coordinates[1][0],
                                            grid_coordinates[1][1], True)
            corner_points.append(temp_motor_pos)
            temp_motor_pos = self.__mini_diff_hwobj.\
               get_centred_point_from_coord(grid_coordinates[2][0],
                                            grid_coordinates[2][1], True)
            corner_points.append(temp_motor_pos)
            temp_motor_pos = self.__mini_diff_hwobj.\
               get_centred_point_from_coord(grid_coordinates[3][0],
                                            grid_coordinates[3][1], True)
            corner_points.append(temp_motor_pos)
            self.__drawing_mgr.set_grid_corner_points(corner_points)[0]

            temp_motor_pos = self.__mini_diff_hwobj.\
               get_centred_point_from_coord(abs((grid_coordinates[0][0] +
                                                 grid_coordinates[1][0]) / 2),
                                            abs((grid_coordinates[0][1] +
                                                grid_coordinates[2][1]) / 2), False)

            #self.__drawing_mgr.set_grid_center_point(temp_motor_pos)[0]

            cpos = self.__mini_diff_hwobj.convert_from_obj_to_name(temp_motor_pos)
            cpos = queue_model_objects.CentredPosition(cpos)
            self.__drawing_mgr.set_grid_center_point(cpos)[0]

            self.mesh_widget.mesh_treewidget.setSelected(list_view_item, True)
            self.__drawing_mgr = Qub2PointSurfaceDrawingMgr(self.__canvas, self.__matrix)
            self.draw_button_clicked()

    def delete_drawing_clicked(self):
        """
        Descript. :
        """
        if len(self.__list_items):
            list_view_item = self.mesh_widget.mesh_treewidget.selectedItem()
            del self.__list_items[list_view_item]
            self.mesh_widget.mesh_treewidget.takeItem(list_view_item)

            list_view_item = self.mesh_widget.mesh_treewidget.lastItem()
            self.mesh_widget.findChild(QtGui.QLineEdit, "num_images_ledit").setText("")
            self.mesh_widget.mesh_treewidget.setSelected(list_view_item, True)

    def get_cell_dim(self):
        hspace = self.mesh_widget.findChild(QtGui.QLineEdit, "hor_spacing_ledit").text()
        vspace = self.mesh_widget.findChild(QtGui.QLineEdit, "ver_spacing_ledit").text()
        try:
            vspace = float(vspace)
        except ValueError:
            vspace = 0
        try:
            hspace = float(hspace)
        except ValueError:
            hspace = 0

        return ((vspace)/1000, (hspace)/1000)

    def set_vspace(self, vspace):
        vspace, hspace = self.get_cell_dim()
        self.__drawing_mgr.set_cell_height(self.__beam_size_y + vspace)

    def set_hspace(self, hspace):
        vspace, hspace = self.get_cell_dim()
        self.__drawing_mgr.set_cell_width(self.__beam_size_x + hspace)

    def set_x_pixel_size(self, x_size):
        x_size = 1e-3/x_size

        if self.__x_pixel_size != x_size:
            zoom_factor = x_size / self.__x_pixel_size
            beam_width_mm =  self.__beam_size_x
            self.__x_pixel_size = x_size
            self.__cell_width = int(beam_width_mm * self.__x_pixel_size)
            try:
                if self.__drawing_mgr:
                    self.__drawing_mgr.set_x_pixel_size(x_size)
                for drawing_mgr in self.__list_items.values():
                    drawing_mgr.set_x_pixel_size(x_size)
                    drawing_mgr.reposition(scale_factor_x = zoom_factor)
            except AttributeError:
                # Drawing manager not set when called
                pass

    def set_y_pixel_size(self, y_size):
        y_size = 1e-3/y_size

        if self.__y_pixel_size != y_size:
            zoom_factor = y_size / self.__y_pixel_size
            beam_height_mm =  self.__beam_size_y
            self.__y_pixel_size = y_size
            self.__cell_height = int(beam_height_mm * self.__y_pixel_size)

            try:
                if self.__drawing_mgr:
                    self.__drawing_mgr.set_y_pixel_size(y_size)
                    self.__drawing_mgr.reshape()

                for drawing_mgr in self.__list_items.values():
                    drawing_mgr.set_y_pixel_size(y_size)
                    drawing_mgr.reshape()
                    drawing_mgr.reposition(scale_factor_y = zoom_factor)
            except:
                # Drawing manager not set when called
                pass

    def set_beam_position(self, beam_c_x, beam_c_y, beam_size_x, beam_size_y):
        self.__cell_height = int(beam_size_x * self.__y_pixel_size)
        self.__cell_width = int(beam_size_y * self.__x_pixel_size)

        try:
            vspace, hspace = self.get_cell_dim()
            self.__drawing_mgr.set_cell_width(self.__beam_size_x + hspace)
            self.__drawing_mgr.set_cell_height(self.__beam_size_y + vspace)

            self.__drawing_mgr.set_beam_position(0, 0, beam_size_x, beam_size_y)
            #for drawing_mgr in self.__list_items.itervalues():
            #    drawing_mgr.set_beam_position(beam_c_x, beam_c_y)
        except:
            # Drawing manager not set when called
            pass

    def mesh_treewidget_selection_changed(self, item):
        for index, current_item in enumerate(self.__list_items.iterkeys()):
            drawing_mgr = self.__list_items[current_item]
            if current_item == item:
                drawing_mgr.highlight()
                key = str(current_item.text(0))
                if drawing_mgr.isVisible()[0]:
                    self.mesh_widget.visibility_button.setText("Hide")
                else:
                    self.mesh_widget.visibility_button.setText("Show")
                cell_count = drawing_mgr.get_total_steps()[0]
                self.mesh_widget.findChild(QtGui.QLineEdit, "num_images_ledit").\
                     setText("%d" % cell_count)
                (omega_pos, kappa_pos, kappa_phi_pos) = drawing_mgr.get_angles()[0]

                self.mesh_widget.findChild(QtGui.QLineEdit, "omega_ledit").\
                     setText("%.2f" % float(omega_pos))
                self.mesh_widget.findChild(QtGui.QLineEdit, "kappa_ledit").\
                     setText("%.2f" % float(kappa_pos))
                self.mesh_widget.findChild(QtGui.QLineEdit, "kappa_phi_ledit").\
                     setText("%.2f" % float(kappa_phi_pos))
            else:
                drawing_mgr.unhighlight()

    def toggle_visibility_grid(self):
        item = self.mesh_widget.mesh_treewidget.currentItem()

        for current_item in self.__list_items.iterkeys():
            drawing_mgr = self.__list_items[current_item]
            if current_item == item:
                if drawing_mgr.isVisible()[0]:
                    drawing_mgr.hide()
                    self.mesh_widget.visibility_button.setText("Show")
                else:
                    drawing_mgr.show()
                    self.mesh_widget.visibility_button.setText("Hide")

    def display_grids(self, display):
        for drawing_mgr in self.__list_items.values():
            drawing_mgr.show() if display else drawing_mgr.hide()

    def set_motor_pos(self, motor_pos):
        for drawing_mgr in self.__list_items.values():
            drawing_mgr.set_motor_pos_actual(motor_pos)
        self.current_motor_positions = motor_pos

    def update_grid_corner_points(self):
        for drawing_mgr in self.__list_items.values():
            grid_corner_points = drawing_mgr.get_grid_corner_points()[0]
            grid_coordinates = []
            for grid_corner_point in grid_corner_points:
                grid_coordinates.append(self.__mini_diff_hwobj.motor_positions_to_screen(grid_corner_point))
            drawing_mgr.set_grid_coordinates(grid_coordinates)[0]

    def move_to_center_point(self):
        list_view_item = self.mesh_widget.mesh_treewidget.selectedItem()
        drawing_mgr = self.__list_items[list_view_item]
        #motors_positions = drawing_mgr.get_grid_center_point()[0]
        #self.__mini_diff_hwobj.move_to_motors_positions(motors_positions)
        cpos = drawing_mgr.get_grid_center_point()[0]
        self.__mini_diff_hwobj.moveToMotorsPositions(cpos)

    def _get_grid_info(self, grid_dict):
        list_view_item = self.mesh_widget.mesh_treewidget.selectedItem()
        if list_view_item is not None:
            drawing_mgr = self.__list_items[list_view_item]
            key = str(list_view_item.text(0))
            grid_dict.update(drawing_mgr._get_grid(key)[0])

    def _set_grid_data(self, key, result_data):
        for list_view_item in self.__list_items.keys():
            if key == str(list_view_item.text(0)):
                drawing_mgr = self.__list_items[list_view_item]

               #  num_cells = drawing_mgr.get_nummer_of_cells()[0]
#                 result_data = {}

#                 for cell in range(1, num_cells + 1):
#                     random.seed()
#                     result_data[cell] = (cell, (255, random.randint(0, 255), 0))

                drawing_mgr.set_data(result_data)
                break
예제 #13
0
class CreateAdvancedWidget(CreateTaskBase):
    """Widget used to create advanced collection methods
    """

    def __init__(self, parent=None,name=None, fl=0):
        CreateTaskBase.__init__(self, parent, name, 
            QtCore.Qt.WindowFlags(fl), 'Advanced')

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

        # Hardware objects ----------------------------------------------------
 
        # Internal variables --------------------------------------------------
        self.init_models()
        self._advanced_methods = None
        self._grid_map = {}

        # Graphic elements ----------------------------------------------------
        self._advanced_methods_widget = uic.loadUi(os.path.join(\
            os.path.dirname(__file__), "ui_files/Qt4_advanced_methods_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')

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

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

        # Qt signal/slot connections ------------------------------------------
        self._acq_widget.acqParametersChangedSignal.\
             connect(self.acq_parameters_changed)
        self._acq_widget.madEnergySelectedSignal.\
             connect(self.mad_energy_selected)
        self._acq_widget.acq_widget_layout.set_max_osc_range_button.clicked.\
             connect(self.set_max_osc_range_clicked)

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

        self._advanced_methods_widget.grid_treewidget.itemSelectionChanged.\
             connect(self.grid_treewidget_item_selection_changed)
        self._advanced_methods_widget.draw_grid_button.clicked.\
             connect(self.draw_grid_button_clicked)
        self._advanced_methods_widget.remove_grid_button.clicked.\
             connect(self.remove_grid_button_clicked)
        self._advanced_methods_widget.hor_spacing_ledit.textChanged.\
             connect(self.spacing_changed)
        self._advanced_methods_widget.ver_spacing_ledit.textChanged.\
             connect(self.spacing_changed)

        self._advanced_methods_widget.move_right_button.clicked.\
             connect(lambda : self.move_grid("right"))
        self._advanced_methods_widget.move_left_button.clicked.\
             connect(lambda : self.move_grid("left"))
        self._advanced_methods_widget.move_up_button.clicked.\
             connect(lambda : self.move_grid("up"))
        self._advanced_methods_widget.move_down_button.clicked.\
             connect(lambda : self.move_grid("down"))        
      
        self._advanced_methods_widget.overlay_cbox.toggled.\
             connect(self.overlay_toggled)
        self._advanced_methods_widget.overlay_slider.valueChanged.\
             connect(self.overlay_alpha_changed) 
        self._advanced_methods_widget.overlay_color_button.clicked.\
             connect(self.overlay_change_color)
        self._advanced_methods_widget.move_to_grid_button.clicked.\
             connect(self.move_to_grid)

        # Other ---------------------------------------------------------------
        self._acq_widget.use_osc_start(False)
        self._acq_widget.use_kappa(False) 
        self._acq_widget.acq_widget_layout.num_images_label.setEnabled(False)
        self._acq_widget.acq_widget_layout.num_images_ledit.setEnabled(False)
        for col in range(self._advanced_methods_widget.\
                         grid_treewidget.columnCount()):
            self._advanced_methods_widget.grid_treewidget.\
                 resizeColumnToContents(col)
        self._acq_widget.acq_widget_layout.\
             set_max_osc_range_button.setEnabled(False)

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

    def _init_models(self):
        """
        Descript. :
        """
        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_advanced_values")

            if not self._advanced_methods:
                self._advanced_methods = self._beamline_setup_hwobj.get_advanced_methods()            
                if self._advanced_methods:
                   for method in self._advanced_methods:
                       self._advanced_methods_widget.method_combo.addItem(method)
                else:
                   self.setEnabled(False)    

            self.grid_treewidget_item_selection_changed()

    def set_beamline_setup(self, bl_setup_hwobj):
        """
        In plate mode osciallation is start is in the middle of grid
        """
        CreateTaskBase.set_beamline_setup(self, bl_setup_hwobj)

        self._acq_widget.acq_widget_layout.osc_start_label.\
             setText("Oscillation middle:")
        self._acq_widget.acq_widget_layout.set_max_osc_range_button.setVisible(\
             self._beamline_setup_hwobj.diffractometer_hwobj.in_plate_mode())

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

        if len(self._advanced_methods_widget.\
           grid_treewidget.selectedItems()) == 0:
            msg = "No grid selected. Please select a grid to continue!"
            logging.getLogger("GUI").error(msg)
            result = False

        return result
            
    def update_processing_parameters(self, crystal):
        """
        Descript. :
        """
        return

    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._acq_widget.update_data_model(self._acquisition_parameters,
            #                                    self._path_template)            
            pass
        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 tree_item.get_model().is_executed():
                self.setDisabled(True)
            else:
                self.setDisabled(False)

            # sample_data_model = self.get_sample_item(tree_item).get_model()
            #self._acq_widget.disable_inverse_beam(True)
            #self._graphics_manager_hwobj.de_select_all()
            self._graphics_manager_hwobj.select_shape(data_collection.grid)

            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
            self._acq_widget.update_data_model(self._acquisition_parameters,
                                               self._path_template)
            self.get_acquisition_widget().use_osc_start(True)
        else:
            self.setDisabled(True)
        self.grid_treewidget_item_selection_changed()
  
    def _create_task(self,  sample, shape):
        """Creates tasks based on selected grids

        :param sample: selected sample object
        :type sample: SampleQueueItem
        :param shape: selected shape
        :type shape: Qt4_GraphicsLib.GraphicsItem
        """
        tasks = []
        selected_grids = self.get_selected_grids() 

        if len(selected_grids) == 0:
            selected_grids.append(self._graphics_manager_hwobj.\
                update_auto_grid()) 

        for grid in selected_grids:
            grid.set_snapshot(self._graphics_manager_hwobj.\
                  get_scene_snapshot(grid))

            grid_properties = grid.get_properties()

            acq = self._create_acq(sample)
            acq.acquisition_parameters.centred_position = \
                grid.get_centred_position()
            acq.acquisition_parameters.mesh_range = \
                [grid_properties["dx_mm"], grid_properties["dy_mm"]]
            acq.acquisition_parameters.num_lines = \
                grid_properties["num_lines"]
            acq.acquisition_parameters.num_images = \
                grid_properties["num_lines"] * \
                grid_properties["num_images_per_line"]
            grid.set_osc_range(acq.acquisition_parameters.osc_range)

            processing_parameters = 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.set_experiment_type(EXPERIMENT_TYPE.MESH)
            dc.set_requires_centring(False)
            dc.grid = grid

     
            exp_type = str(self._advanced_methods_widget.\
                method_combo.currentText())
            print exp_type
            if exp_type == "MeshScan":
                tasks.append(dc)
            elif exp_type == "XrayCentering":
                xray_centering = queue_model_objects.XrayCentering(\
                   dc, sample.crystals[0])
                tasks.append(xray_centering)

            dc.run_processing_parallel = exp_type
            self._path_template.run_number += 1

            return tasks

    def shape_created(self, shape, shape_type):
        """If a grid is created then adds it to the treewidget.
           A binding between graphical grid and treewidget item is based
           on the self._grid_map

        :param shape: graphics object
        :type shape: Qt4_GraphicsLib.GraphicsItem
        :param shape_type: type of the object (point, line, grid)
        :type shape_type: str 
        """
        if shape_type == "Grid":
            self._advanced_methods_widget.grid_treewidget.clearSelection()
            grid_properties = shape.get_properties()
            info_str_list = []
            info_str_list.append(grid_properties["name"])
            info_str_list.append("%d" % (grid_properties["beam_x_mm"] * 1000.0))
            info_str_list.append("%d" % (grid_properties["beam_y_mm"] * 1000.0))
            info_str_list.append("%d" % grid_properties["num_lines"])
            info_str_list.append("%d" % grid_properties["num_images_per_line"])

            grid_treewidget_item = QtGui.QTreeWidgetItem(\
                self._advanced_methods_widget.grid_treewidget,
                info_str_list)
            grid_treewidget_item.setSelected(True)
            self._grid_map[shape] = grid_treewidget_item
            self.grid_treewidget_item_selection_changed()
            
    def shape_deleted(self, shape, shape_type):
        """Removes shape from QTreeWidget and self._grid_map

        :param shape: graphics object
        :type shape: QtGraphicsLib.GraphicsItem
        :param shape_type: type of the object (point, line, grid)
        :type shape_type: str 
        """
        if self._grid_map.get(shape):
            treewidget_item_modelindex = self._advanced_methods_widget.\
                 grid_treewidget.indexFromItem(self._grid_map[shape])
            self._advanced_methods_widget.grid_treewidget.takeTopLevelItem(\
                 treewidget_item_modelindex.row())
            self._grid_map.pop(shape) 

    def grid_treewidget_item_selection_changed(self):
        """Updates acquisition parameters based on the selected grid.
        """
        self.enable_grid_controls(False)
      
        osc_dynamic_limits = None
        if self._beamline_setup_hwobj.diffractometer_hwobj.in_plate_mode():
            osc_dynamic_limits = self._beamline_setup_hwobj.\
                diffractometer_hwobj.get_osc_dynamic_limits()
        self._acq_widget.acq_widget_layout.\
             set_max_osc_range_button.setEnabled(False)

        for item in self._grid_map.items():
            grid = item[0]
            treewidget_item = item[1]
  
            if treewidget_item.isSelected():
                grid_properties = grid.get_properties() 
                cell_count = grid_properties["num_lines"] * \
                             grid_properties["num_images_per_line"]
                self._acq_widget.acq_widget_layout.num_images_ledit.setText(\
                     "%d" % cell_count)
                self._acq_widget.acq_widget_layout.first_image_ledit.setText(\
                     "%d" % grid_properties["first_image_num"])
                centred_point = grid.get_centred_position()
                self._acq_widget.acq_widget_layout.osc_start_ledit.setText(\
                     "%.2f" % float(centred_point.phi))
                self._acq_widget.acq_widget_layout.kappa_ledit.setText(\
                     "%.2f" % float(centred_point.kappa))
                self._acq_widget.acq_widget_layout.kappa_phi_ledit.setText(\
                     "%.2f" % float(centred_point.kappa_phi))
                self._advanced_methods_widget.hor_spacing_ledit.setText(\
                     "%.2f" % (float(grid_properties["xOffset"]) * 1000))
                self._advanced_methods_widget.ver_spacing_ledit.setText(\
                     "%.2f" % (float(grid_properties["yOffset"]) * 1000))

                treewidget_item.setText(3, str(grid_properties["num_lines"]))
                treewidget_item.setText(4, str(grid_properties["num_images_per_line"]))
             
                if osc_dynamic_limits:
                    osc_range_limits = \
                        (0, 
                         min(abs(centred_point.phi - osc_dynamic_limits[0]),
                             abs(osc_dynamic_limits[1] - centred_point.phi)) /\
                         float(grid_properties["num_images_per_line"]))

                    self._acq_widget.update_osc_range_limits(osc_range_limits)
                    self._acq_widget.update_num_images_limits(\
                         grid_properties["num_lines"] * \
                         grid_properties["num_images_per_line"])

                grid.setSelected(True) 
                self.enable_grid_controls(True)
                self._acq_widget.acq_widget_layout.\
                     set_max_osc_range_button.setEnabled(True)
            else:
                grid.setSelected(False)

    def get_selected_grids(self):
        """Returns selected grids
        
        :returns: list with grid objects
        """
        selected_grids = [] 
        for grid, grid_treewidget_item in self._grid_map.iteritems():
            if grid_treewidget_item.isSelected():
                selected_grids.append(grid)
        return selected_grids

    def draw_grid_button_clicked(self):
        """Starts grid drawing
        """
        self._graphics_manager_hwobj.create_grid(self.get_spacing())

    def remove_grid_button_clicked(self):
        """Removes selected grid
        """
        grid_to_delete = None 
        for grid, treewidget_item in self._grid_map.iteritems():
            if treewidget_item.isSelected():
                grid_to_delete = grid
                break

        if grid_to_delete:
            self._graphics_manager_hwobj.delete_shape(grid_to_delete)
            self._advanced_methods_widget.move_to_grid_button.setEnabled(False)           

    def get_spacing(self):
        """Returns spacing in microns

        :returns: list of two floats
        """
        spacing = [0, 0]
        try:
           spacing[0] = float(self._advanced_methods_widget.\
               hor_spacing_ledit.text()) / 1000.0
        except:
           pass
        try:
           spacing[1] = float(self._advanced_methods_widget.\
               ver_spacing_ledit.text()) / 1000.0
        except:
           pass
        return spacing

    def spacing_changed(self, value):
        """Updates spacing of the selected grid
        """
        spacing = self.get_spacing()
        for grid_object, treewidget_item in self._grid_map.iteritems():
            if treewidget_item.isSelected():
                grid_object.set_spacing(spacing, adjust_size=\
                     self._advanced_methods_widget.adjust_size_cbox.isChecked())
                break
        #self.grid_treewidget_item_selection_changed()

    def move_to_grid(self):
        """Moves diffractometer to the center of the grid
        """
        for grid_object, treewidget_item in self._grid_map.iteritems():
            if treewidget_item.isSelected():
                self._beamline_setup_hwobj.diffractometer_hwobj.\
                     move_to_centred_position(grid_object.get_centred_position())
                break

    def overlay_toggled(self, state):
        """Toggles (on/off) overlay
        """
        for grid_object, treewidget_item in self._grid_map.iteritems():
            if treewidget_item.isSelected():
                grid_object.set_display_overlay(state)
                break
           
    def overlay_alpha_changed(self, alpha_value):
        """Changes the transperency of the grid
        """
        for grid_object, treewidget_item in self._grid_map.iteritems():
            if treewidget_item.isSelected():
                grid_object.set_fill_alpha(alpha_value)
                break

    def overlay_change_color(self):
        """Changes the default color (blue) of overlay
        """
        color = QtGui.QColorDialog.getColor()
        if color.isValid():
            for grid_object, treewidget_item in self._grid_map.iteritems():
                if treewidget_item.isSelected():
                    grid_object.set_base_color(color)
                    break

    def move_grid(self, direction):
        """Moves grid by one pix in selected direction

        :param direction: direction to move (right, left, up, down)
        :type direction: str
        """
        for grid_object, treewidget_item in self._grid_map.iteritems():
            if treewidget_item.isSelected():
                grid_object.move_by_pix(direction)
                self._graphics_manager_hwobj.\
                     update_grid_motor_positions(grid_object)
                break

    def enable_grid_controls(self, state):
        """Enables grid controls if a grid is selectd
        """
        self._advanced_methods_widget.overlay_cbox.setEnabled(state)
        self._advanced_methods_widget.overlay_slider.setEnabled(state)
        self._advanced_methods_widget.overlay_color_button.setEnabled(state)
        self._advanced_methods_widget.move_to_grid_button.setEnabled(state)
        self._advanced_methods_widget.remove_grid_button.setEnabled(state)        

        self._advanced_methods_widget.move_right_button.setEnabled(state)
        self._advanced_methods_widget.move_left_button.setEnabled(state)
        self._advanced_methods_widget.move_up_button.setEnabled(state)
        self._advanced_methods_widget.move_down_button.setEnabled(state)

    def set_max_osc_range_clicked(self, state):
        """Sets the osc range based on grid (number of images per line
           and osc in the middle of the grid)        
        """
        for grid_object, treewidget_item in self._grid_map.iteritems():
            if treewidget_item.isSelected():
                grid_properties = grid_object.get_properties()
                self._acq_widget.acq_widget_layout.osc_range_ledit.setText(\
                     "%.4f" % (self._acq_widget.osc_range_validator.top() - 0.0001))
                self._acq_widget.update_num_images_limits(\
                     grid_properties["num_lines"] * \
                     grid_properties["num_images_per_line"])
                break
예제 #14
0
class DCParametersWidget(QtGui.QWidget):
    def __init__(self, parent=None, name="parameter_widget"):

        QtGui.QWidget.__init__(self, parent)
        if name is not None:
            self.setObjectName(name)

        # Properties ----------------------------------------------------------

        # Signals ------------------------------------------------------------

        # Slots ---------------------------------------------------------------

        # Hardware objects ----------------------------------------------------
        self._beamline_setup_hwobj = None

        # Internal variables --------------------------------------------------
        self._data_collection = None
        self.add_dc_cb = None
        self._tree_view_item = None

        # Graphic elements ----------------------------------------------------
        _dc_parameters_widget = QtGui.QWidget(self)
        self.caution_pixmap = Qt4_Icons.load("Caution2.png")
        self.path_widget = DataPathWidget(_dc_parameters_widget)
        self.acq_widget = AcquisitionWidget(_dc_parameters_widget,
                                            layout='horizontal')
        #self.acq_widget.setFixedHeight(170)
        self.processing_widget = ProcessingWidget(_dc_parameters_widget)
        self.position_widget = uic.loadUi(
            os.path.join(os.path.dirname(__file__),
                         'ui_files/Qt4_snapshot_widget_layout.ui'))
        #self.position_widget.setMinimumSize(310, 210)

        # Layout --------------------------------------------------------------
        _dc_parameters_widget_layout = QtGui.QVBoxLayout(self)
        _dc_parameters_widget_layout.addWidget(self.path_widget)
        _dc_parameters_widget_layout.addWidget(self.acq_widget)
        _dc_parameters_widget_layout.addWidget(self.processing_widget)
        _dc_parameters_widget_layout.setSpacing(2)
        _dc_parameters_widget_layout.addStretch(0)
        _dc_parameters_widget_layout.setContentsMargins(0, 0, 0, 0)
        _dc_parameters_widget.setLayout(_dc_parameters_widget_layout)

        _main_hlayout = QtGui.QHBoxLayout(self)
        _main_hlayout.addWidget(_dc_parameters_widget)
        _main_hlayout.addWidget(self.position_widget)
        _main_hlayout.setSpacing(2)
        _main_hlayout.setContentsMargins(0, 0, 0, 0)
        _main_hlayout.addStretch(0)
        self.setLayout(_main_hlayout)

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

        # Qt signal/slot connections ------------------------------------------
        self.path_widget.data_path_layout.prefix_ledit.textChanged.connect(
            self._prefix_ledit_change)
        self.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("path_template_changed"),
                     self.handle_path_conflict)

        #QtCore.QObject.connect(QtGui.QApplication, QtCore.SIGNAL('tab_changed'),
        #                       self.tab_changed)

        # Other ---------------------------------------------------------------
        Qt4_widget_colors.set_widget_color(self.path_widget,
                                           Qt4_widget_colors.GROUP_BOX_GRAY)
        Qt4_widget_colors.set_widget_color(self.acq_widget,
                                           Qt4_widget_colors.GROUP_BOX_GRAY)
        Qt4_widget_colors.set_widget_color(self.processing_widget,
                                           Qt4_widget_colors.GROUP_BOX_GRAY)
        Qt4_widget_colors.set_widget_color(self.position_widget,
                                           Qt4_widget_colors.GROUP_BOX_GRAY)

    def set_beamline_setup(self, bl_setup):
        self.acq_widget.set_beamline_setup(bl_setup)
        self._beamline_setup_hwobj = bl_setup

    def _prefix_ledit_change(self, new_value):
        prefix = self._data_collection.acquisitions[0].\
                 path_template.get_prefix()
        self._data_collection.set_name(prefix)
        self._tree_view_item.setText(0, self._data_collection.get_name())

    def _run_number_ledit_change(self, new_value):
        if str(new_value).isdigit():
            self._data_collection.set_number(int(new_value))
            self._tree_view_item.setText(0, self._data_collection.get_name())

    def handle_path_conflict(self, widget, new_value):
        if self._tree_view_item is None:
            #TODO fix this
            return

        dc_tree_widget = self._tree_view_item.listView().parent()
        dc_tree_widget.check_for_path_collisions()
        path_template = self._data_collection.acquisitions[0].path_template
        path_conflict = self.queue_model_hwobj.\
                        check_for_path_collisions(path_template)

        if new_value != '':
            if path_conflict:
                logging.getLogger("user_level_log").\
                    error('The current path settings will overwrite data' +\
                          ' from another task. Correct the problem before collecting')

                widget.setPaletteBackgroundColor(widget_colors.LIGHT_RED)
            else:
                widget.setPaletteBackgroundColor(widget_colors.WHITE)

    def __add_data_collection(self):
        return self.add_dc_cb(self._data_collection, self.collection_type)

    def mad_energy_selected(self, name, energy, state):
        path_template = self._data_collection.acquisitions[0].path_template

        if state:
            path_template.mad_prefix = name
        else:
            path_template.mad_prefix = ''

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

        self.path_widget.set_run_number(run_number)
        self.path_widget.set_prefix(path_template.base_prefix)
        model = self._tree_view_item.get_model()
        model.set_name(path_template.get_prefix())
        self._tree_view_item.setText(0, model.get_name())

    def tab_changed(self):
        if self._tree_view_item:
            self.populate_parameter_widget(self._tree_view_item)

    def set_enabled(self, state):
        self.acq_widget.setEnabled(state)
        self.path_widget.setEnabled(state)
        self.processing_widget.setEnabled(state)

    def populate_widget(self, item):
        data_collection = item.get_model()
        self._tree_view_item = item
        self._data_collection = data_collection
        self._acquisition_mib = DataModelInputBinder(self._data_collection.\
                                                         acquisitions[0].acquisition_parameters)

        # The acq_widget sends a signal to the path_widget, and it relies
        # on that both models upto date, we need to refactor this part
        # so that both models are set before taking ceratin actions.
        # This workaround, works for the time beeing.
        self.path_widget._data_model = data_collection.acquisitions[
            0].path_template

        self.acq_widget.set_energies(
            data_collection.crystal.energy_scan_result)
        self.acq_widget.update_data_model(data_collection.acquisitions[0].\
                                          acquisition_parameters,
                                          data_collection.acquisitions[0].\
                                          path_template)
        self.acq_widget.use_osc_start(True)

        self.path_widget.update_data_model(data_collection.\
                                           acquisitions[0].path_template)

        self.processing_widget.update_data_model(data_collection.\
                                                 processing_parameters)

        if data_collection.acquisitions[0].acquisition_parameters.\
                centred_position.snapshot_image:
            image = data_collection.acquisitions[0].\
                acquisition_parameters.centred_position.snapshot_image
            ration = image.height() / float(image.width())
            image = image.scaled(400, 400 * ration, QtCore.Qt.KeepAspectRatio)
            self.position_widget.svideo.setPixmap(QtGui.QPixmap(image))

        invalid = self._acquisition_mib.validate_all()

        if invalid:
            msg = "This data collection has one or more incorrect parameters,"+\
                " correct the fields marked in red to solve the problem."

            logging.getLogger("user_level_log").\
                warning(msg)
예제 #15
0
class CreateAdvancedWidget(CreateTaskBase):
    """
    Descript. :
    """
    def __init__(self, parent=None, name=None, fl=0):
        CreateTaskBase.__init__(self, parent, name, QtCore.Qt.WindowFlags(fl),
                                'Advanced')

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

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

        # Internal variables --------------------------------------------------
        self.init_models()
        self._advanced_methods = None
        self._grid_map = {}

        # Graphic elements ----------------------------------------------------
        self._advanced_methods_widget = uic.loadUi(os.path.join(\
            os.path.dirname(__file__), "ui_files/Qt4_advanced_methods_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')

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

        # 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._advanced_methods_widget.grid_treewidget.itemSelectionChanged.\
             connect(self.grid_treewidget_item_selection_changed)
        self._advanced_methods_widget.draw_grid_button.clicked.\
             connect(self.draw_grid_button_clicked)
        self._advanced_methods_widget.remove_grid_button.clicked.\
             connect(self.remove_grid_button_clicked)
        self._advanced_methods_widget.hor_spacing_ledit.textChanged.\
             connect(self.spacing_changed)
        self._advanced_methods_widget.ver_spacing_ledit.textChanged.\
             connect(self.spacing_changed)

        self._advanced_methods_widget.move_right_button.clicked.\
             connect(lambda : self.move_grid("right"))
        self._advanced_methods_widget.move_left_button.clicked.\
             connect(lambda : self.move_grid("left"))
        self._advanced_methods_widget.move_up_button.clicked.\
             connect(lambda : self.move_grid("up"))
        self._advanced_methods_widget.move_down_button.clicked.\
             connect(lambda : self.move_grid("down"))

        self._advanced_methods_widget.overlay_cbox.toggled.\
             connect(self.overlay_toggled)
        self._advanced_methods_widget.overlay_slider.valueChanged.\
             connect(self.overlay_alpha_changed)
        self._advanced_methods_widget.move_to_grid_button.clicked.\
             connect(self.move_to_grid)

        # Other ---------------------------------------------------------------
        self._acq_widget.use_osc_start(False)
        self._acq_widget.use_kappa(False)
        self._acq_widget.use_kappa_phi(False)
        self._acq_widget.acq_widget_layout.num_images_label.setEnabled(False)
        self._acq_widget.acq_widget_layout.num_images_ledit.setEnabled(False)
        for col in range(self._advanced_methods_widget.\
                         grid_treewidget.columnCount()):
            self._advanced_methods_widget.grid_treewidget.\
                 resizeColumnToContents(col)

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

    def _init_models(self):
        """
        Descript. :
        """
        self._advanced = queue_model_objects.Advanced()
        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_advanced_values")

            if not self._advanced_methods:
                self._advanced_methods = self._beamline_setup_hwobj.get_advanced_methods(
                )
                if self._advanced_methods:
                    for method in self._advanced_methods:
                        self._advanced_methods_widget.method_combo.addItem(
                            method)
                else:
                    self.setEnabled(False)
            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

            self.grid_treewidget_item_selection_changed()
        else:
            self._acquisition_parameters = queue_model_objects.AcquisitionParameters(
            )

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

        if len(self._advanced_methods_widget.grid_treewidget.\
            selectedItems()) == 0:
            msg = "No grid selected. Automatic grid will be used."
            logging.getLogger("user_level_log").info(msg)
        return result

    def update_processing_parameters(self, crystal):
        """
        Descript. :
        """
        return

    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._acq_widget.update_data_model(self._acquisition_parameters,
                                               self._path_template)
        elif isinstance(tree_item, Qt4_queue_item.BasketQueueItem):
            self.setDisabled(False)
        elif isinstance(tree_item, Qt4_queue_item.AdvancedQueueItem):
            advanced = tree_item.get_model()
            if tree_item.get_model().is_executed():
                self.setDisabled(True)
            else:
                self.setDisabled(False)

            # sample_data_model = self.get_sample_item(tree_item).get_model()
            #self._acq_widget.disable_inverse_beam(True)

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

            data_collection = advanced.reference_image_collection

            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)
        else:
            self.setDisabled(True)
        #if self._advanced_methods_widget.grid_treewidget.count() > 0:
        #    self._advanced_methods_widget.grid_treewidget.clearSelection()

    def _create_task(self, sample, shape):
        """
        Descript. :
        """
        data_collections = []
        selected_grids = self.get_selected_grids()

        if len(selected_grids) == 0:
            selected_grids.append(self._graphics_manager_hwobj.\
                create_automatic_grid())

        for shape in selected_grids:
            shape.set_snapshot(self._graphics_manager_hwobj.\
                  get_scene_snapshot(shape))

            grid_properties = shape.get_properties()

            acq = self._create_acq(sample)
            acq.acquisition_parameters.centred_position = \
                shape.get_centred_position()
            acq.acquisition_parameters.mesh_range = \
                [grid_properties["dx_mm"], grid_properties["dy_mm"]]
            acq.acquisition_parameters.num_lines = \
                grid_properties["num_lines"]
            acq.acquisition_parameters.num_images = \
                grid_properties["num_lines"] * \
                grid_properties["num_images_per_line"]

            processing_parameters = 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.set_experiment_type(EXPERIMENT_TYPE.MESH)

            exp_type = str(self._advanced_methods_widget.method_combo.\
                currentText())
            advanced = queue_model_objects.Advanced(exp_type, dc, shape,
                                                    sample.crystals[0])

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

            return data_collections

    def shape_created(self, shape, shape_type):
        if shape_type == "Grid":
            self._advanced_methods_widget.grid_treewidget.clearSelection()
            grid_properties = shape.get_properties()
            info_str_list = QtCore.QStringList()
            info_str_list.append(grid_properties["name"])
            info_str_list.append("%d" % grid_properties["beam_x"])
            info_str_list.append("%d" % grid_properties["beam_y"])
            info_str_list.append("%d" % grid_properties["num_lines"])
            info_str_list.append("%d" % grid_properties["num_images_per_line"])

            grid_treewidget_item = QtGui.QTreeWidgetItem(\
                self._advanced_methods_widget.grid_treewidget,
                info_str_list)
            grid_treewidget_item.setSelected(True)
            self._grid_map[shape] = grid_treewidget_item
            self.grid_treewidget_item_selection_changed()

    def shape_deleted(self, shape, shape_type):
        if self._grid_map.get(shape):
            treewidget_item_modelindex = self._advanced_methods_widget.\
                 grid_treewidget.indexFromItem(self._grid_map[shape])
            self._advanced_methods_widget.grid_treewidget.takeTopLevelItem(\
                 treewidget_item_modelindex.row())
            self._grid_map.pop(shape)

    def grid_treewidget_item_selection_changed(self):
        self._advanced_methods_widget.remove_grid_button.setEnabled(False)
        for grid_object, treewidget_item in self._grid_map.items():
            if treewidget_item.isSelected():
                grid_properties = grid_object.get_properties()
                cell_count = grid_properties["num_lines"] * \
                             grid_properties["num_images_per_line"]
                self._acq_widget.acq_widget_layout.num_images_ledit.setText(\
                     "%d" % cell_count)
                self._acq_widget.acq_widget_layout.first_image_ledit.setText(\
                     "%d" % grid_properties["first_image_num"])
                centred_point = grid_object.get_centred_position()
                self._acq_widget.acq_widget_layout.osc_start_ledit.setText(\
                     "%.2f" % float(centred_point.phi))
                self._acq_widget.acq_widget_layout.kappa_ledit.setText(\
                     "%.2f" % float(centred_point.kappa))
                self._acq_widget.acq_widget_layout.kappa_phi_ledit.setText(\
                     "%.2f" % float(centred_point.kappa_phi))
                self._advanced_methods_widget.hor_spacing_ledit.setText(\
                     "%.2f" % float(grid_properties["xOffset"]))
                self._advanced_methods_widget.ver_spacing_ledit.setText(\
                     "%.2f" % float(grid_properties["yOffset"]))
                grid_object.setSelected(True)
                self._advanced_methods_widget.remove_grid_button.setEnabled(
                    True)
            else:
                grid_object.setSelected(False)
        self._advanced_methods_widget.move_to_grid_button.setEnabled(True)

    def get_selected_grids(self):
        selected_grids = []
        for grid, grid_treewidget_item in self._grid_map.items():
            if grid_treewidget_item.isSelected():
                selected_grids.append(grid)
        return selected_grids

    def draw_grid_button_clicked(self):
        self._graphics_manager_hwobj.create_grid(self.get_spacing())

    def remove_grid_button_clicked(self):
        grid_to_delete = None
        for grid, treewidget_item in self._grid_map.items():
            if treewidget_item.isSelected():
                grid_to_delete = grid
                break
        if grid_to_delete:
            self._graphics_manager_hwobj.delete_shape(grid_to_delete)
            self._advanced_methods_widget.move_to_grid_button.setEnabled(False)

    def get_spacing(self):
        spacing = [0, 0]
        try:
            spacing[0] = float(self._advanced_methods_widget.\
                hor_spacing_ledit.text())
        except:
            pass
        try:
            spacing[1] = float(self._advanced_methods_widget.\
                ver_spacing_ledit.text())
        except:
            pass
        return spacing

    def spacing_changed(self, value):
        spacing = self.get_spacing()
        for grid_object, treewidget_item in self._grid_map.items():
            if treewidget_item.isSelected():
                grid_object.set_spacing(spacing)
                #self._graphics_manager_hwobj.\
                #     update_grid_motor_positions(grid_object)

    def move_to_grid(self):
        for grid_object, treewidget_item in self._grid_map.items():
            if treewidget_item.isSelected():
                self._beamline_setup_hwobj.diffractometer_hwobj.\
                     move_to_centred_position(grid_object.get_centred_position())

    def overlay_toggled(self, state):
        for grid_object, treewidget_item in self._grid_map.items():
            if treewidget_item.isSelected():
                grid_object.set_display_overlay(state)

    def overlay_alpha_changed(self, alpha_value):
        for grid_object, treewidget_item in self._grid_map.items():
            if treewidget_item.isSelected():
                grid_object.set_fill_alpha(alpha_value)

    def move_grid(self, direction):
        for grid_object, treewidget_item in self._grid_map.items():
            if treewidget_item.isSelected():
                grid_object.move_by_pix(direction)
                self._graphics_manager_hwobj.\
                     update_grid_motor_positions(grid_object)
class CreateXrayImagingWidget(CreateTaskBase):
    """Widget used to create xray imaging method
    """
    def __init__(self, parent=None, name=None, fl=0):
        CreateTaskBase.__init__(self, parent, name, Qt.WindowFlags(fl),
                                'XrayImaging')

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

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

        # Internal variables --------------------------------------------------
        self._xray_imaging_parameters = None
        self._processing_parameters = None
        self.init_models()

        # Graphic elements ----------------------------------------------------
        self._xray_imaging_parameters_widget = XrayImagingParametersWidget(\
             self, 'xray_imaging_widget',
             xray_imaging_params=self._xray_imaging_parameters)

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

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

        # Layout --------------------------------------------------------------
        _main_vlayout = QVBoxLayout(self)
        _main_vlayout.addWidget(self._xray_imaging_parameters_widget)
        _main_vlayout.addWidget(self._acq_widget)
        _main_vlayout.addWidget(self._data_path_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)

        # Other ---------------------------------------------------------------
        self._acq_widget.use_osc_start(False)
        self._acq_widget.use_kappa(False)

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

        self._xray_imaging_parameters = queue_model_objects.XrayImagingParameters(
        )

        if self._beamline_setup_hwobj is not None:
            self._acquisition_parameters = self._beamline_setup_hwobj.\
                get_default_acquisition_parameters("default_imaging_values")

    def set_beamline_setup(self, bl_setup_hwobj):
        """
        In plate mode osciallation is start is in the middle of grid
        """
        CreateTaskBase.set_beamline_setup(self, bl_setup_hwobj)
        self._xray_imaging_parameters_widget.set_beamline_setup(bl_setup_hwobj)

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

        if isinstance(tree_item, Qt4_queue_item.SampleQueueItem):
            self.setDisabled(False)
        elif isinstance(tree_item, Qt4_queue_item.BasketQueueItem):
            self.setDisabled(False)
        elif isinstance(tree_item, Qt4_queue_item.XrayImagingQueueItem):
            data_model = tree_item.get_model()

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

            self._acquisition_parameters = data_model.acquisitions[
                0].acquisition_parameters
            self._acq_widget.update_data_model(self._acquisition_parameters,
                                               self._path_template)

            self._xray_imaging_parameters = data_model.xray_imaging_parameters
            self._xray_imaging_parameters_widget.update_data_model(
                self._xray_imaging_parameters)

            self.setDisabled(False)

    # 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. :
        """
        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(
            )

        self._path_template.run_number += 1

        acq = self._create_acq(sample)
        acq.acquisition_parameters.centred_position = cpos
        dc = queue_model_objects.XrayImaging(
            self._xray_imaging_parameters.copy(), [acq], sample.crystals[0])
        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

        return [dc]
예제 #17
0
class DCParametersWidget(QtGui.QWidget):
    def __init__(self, parent = None, name = "parameter_widget"):

        QtGui.QWidget.__init__(self, parent)
        if name is not None:
            self.setObjectName(name) 

        # Properties ----------------------------------------------------------

        # Signals ------------------------------------------------------------

        # Slots ---------------------------------------------------------------

        # Hardware objects ----------------------------------------------------
        self._beamline_setup_hwobj = None

        # Internal variables --------------------------------------------------
        self._data_collection = None
        self.add_dc_cb = None
        self._tree_view_item = None

        # Graphic elements ----------------------------------------------------
        _dc_parameters_widget = QtGui.QWidget(self)
        self._data_path_widget = DataPathWidget(_dc_parameters_widget)
        self._acq_widget = AcquisitionWidget(_dc_parameters_widget, 
                                            layout = 'horizontal')
        #self._acq_widget.setFixedHeight(170)
        self._processing_widget = ProcessingWidget(_dc_parameters_widget)
        _snapshot_widget = QtGui.QWidget(self)
        self.position_widget = uic.loadUi(os.path.join(os.path.dirname(__file__),
                                          'ui_files/Qt4_snapshot_widget_layout.ui'))
        
        # Layout --------------------------------------------------------------
        _dc_parameters_widget_layout = QtGui.QVBoxLayout(_dc_parameters_widget)
        _dc_parameters_widget_layout.addWidget(self._data_path_widget)
        _dc_parameters_widget_layout.addWidget(self._acq_widget)
        _dc_parameters_widget_layout.addWidget(self._processing_widget)
        _dc_parameters_widget_layout.setContentsMargins(0, 0, 0, 0)
        _dc_parameters_widget_layout.setSpacing(2)
        _dc_parameters_widget_layout.addStretch(0)

        _snapshots_vlayout = QtGui.QVBoxLayout(_snapshot_widget)
        _snapshots_vlayout.addWidget(self.position_widget)
        _snapshots_vlayout.setContentsMargins(0, 0, 0, 0)
        _snapshots_vlayout.setSpacing(2)
        _snapshots_vlayout.addStretch(10)

        _main_hlayout = QtGui.QHBoxLayout(self)
        _main_hlayout.addWidget(_dc_parameters_widget)
        _main_hlayout.addWidget(_snapshot_widget)
        _main_hlayout.setContentsMargins(0, 0, 0, 0)
        _main_hlayout.setSpacing(2)
        _main_hlayout.addStretch(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._acq_widget.madEnergySelectedSignal.connect(self.mad_energy_selected)
        self._acq_widget.acqParametersChangedSignal.connect(\
             self.acq_parameters_changed)

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

    def set_beamline_setup(self, bl_setup):
        self._acq_widget.set_beamline_setup(bl_setup)
        self._beamline_setup_hwobj = bl_setup

    def _prefix_ledit_change(self, new_value):
        prefix = self._data_collection.acquisitions[0].\
                 path_template.get_prefix()
        self._data_collection.set_name(prefix)
        self._tree_view_item.setText(0, self._data_collection.get_name())

    def _run_number_ledit_change(self, new_value):
        if str(new_value).isdigit():
            self._data_collection.set_number(int(new_value))
            self._tree_view_item.setText(0, self._data_collection.get_name())

    def acq_parameters_changed(self):
        if self._tree_view_item is None:
            #TODO fix this
            return 
        dc_tree_widget = self._tree_view_item.listView().parent()
        dc_tree_widget.check_for_path_collisions()
        path_template = self._data_collection.acquisitions[0].path_template
        path_conflict = self.queue_model_hwobj.\
                        check_for_path_collisions(path_template)
        if new_value != '':
            if path_conflict:
                logging.getLogger("user_level_log").\
                    error('The current path settings will overwrite data' +\
                          ' from another task. Correct the problem before collecting')

                widget.setPaletteBackgroundColor(widget_colors.LIGHT_RED)
            else:
                widget.setPaletteBackgroundColor(widget_colors.WHITE)

    def __add_data_collection(self):
        return self.add_dc_cb(self._data_collection, self.collection_type)
    
    def mad_energy_selected(self, name, energy, state):
        path_template = self._data_collection.acquisitions[0].path_template

        if state:
            path_template.mad_prefix = name
        else:
            path_template.mad_prefix = ''

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

        self._data_path_widget.set_run_number(run_number)
        self._data_path_widget.set_prefix(path_template.base_prefix)
        model = self._tree_view_item.get_model()
        model.set_name(path_template.get_prefix())
        self._tree_view_item.setText(0, model.get_name())
        
    def tab_changed(self):
        if self._tree_view_item:
            self.populate_parameter_widget(self._tree_view_item)

    def set_enabled(self, state):
        self._acq_widget.setEnabled(state)
        self._data_path_widget.setEnabled(state)
        self._processing_widget.setEnabled(state)

    def populate_widget(self, item):
        data_collection = item.get_model()
        self._tree_view_item = item
        self._data_collection = data_collection
        self._acquisition_mib = DataModelInputBinder(self._data_collection.\
                                                         acquisitions[0].acquisition_parameters)

        # The acq_widget sends a signal to the path_widget, and it relies
        # on that both models upto date, we need to refactor this part
        # so that both models are set before taking ceratin actions.
        # This workaround, works for the time beeing.
        self._data_path_widget._data_model = data_collection.acquisitions[0].path_template

        self._acq_widget.set_energies(data_collection.crystal.energy_scan_result)
        self._acq_widget.update_data_model(data_collection.acquisitions[0].\
                                          acquisition_parameters,
                                          data_collection.acquisitions[0].\
                                          path_template)
        self._data_path_widget.update_data_model(data_collection.\
                                           acquisitions[0].path_template)
        
        self._processing_widget.update_data_model(data_collection.\
                                                 processing_parameters)

        if data_collection.acquisitions[0].acquisition_parameters.\
                centred_position.snapshot_image:
            image = data_collection.acquisitions[0].\
                acquisition_parameters.centred_position.snapshot_image
            ration = image.height() / float(image.width())
            image = image.scaled(400, 400 * ration, QtCore.Qt.KeepAspectRatio)
            self.position_widget.svideo.setPixmap(QtGui.QPixmap(image))

        invalid = self._acquisition_mib.validate_all()

        if invalid:
            msg = "This data collection has one or more incorrect parameters,"+\
                " correct the fields marked in red to solve the problem."

            logging.getLogger("user_level_log").\
                warning(msg)
예제 #18
0
class DCParametersWidget(QWidget):
    def __init__(self, parent=None, name="parameter_widget"):

        QWidget.__init__(self, parent)
        if name is not None:
            self.setObjectName(name)

        # Properties ----------------------------------------------------------

        # Signals ------------------------------------------------------------

        # Slots ---------------------------------------------------------------

        # Hardware objects ----------------------------------------------------
        self._beamline_setup_hwobj = None

        # Internal variables --------------------------------------------------
        self._data_collection = None
        self.add_dc_cb = None
        self._tree_view_item = None

        # Graphic elements ----------------------------------------------------
        _dc_parameters_widget = QWidget(self)
        self._data_path_widget = DataPathWidget(_dc_parameters_widget)
        self._acq_widget = AcquisitionWidget(_dc_parameters_widget,
                                             layout='horizontal')
        self._processing_widget = ProcessingWidget(_dc_parameters_widget)

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

        _main_hlayout = QHBoxLayout(self)
        _main_hlayout.addWidget(_dc_parameters_widget)
        _main_hlayout.setContentsMargins(0, 0, 0, 0)
        _main_hlayout.setSpacing(2)
        _main_hlayout.addStretch(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._acq_widget.madEnergySelectedSignal.\
             connect(self.mad_energy_selected)
        self._acq_widget.acqParametersChangedSignal.\
             connect(self.acq_parameters_changed)

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

    def set_beamline_setup(self, bl_setup):
        self._acq_widget.set_beamline_setup(bl_setup)
        self._beamline_setup_hwobj = bl_setup

    def _prefix_ledit_change(self, new_value):
        prefix = self._data_collection.acquisitions[0].\
                 path_template.get_prefix()
        self._data_collection.set_name(prefix)
        self._tree_view_item.setText(0, self._data_collection.get_name())

    def _run_number_ledit_change(self, new_value):
        if str(new_value).isdigit():
            self._data_collection.set_number(int(new_value))
            self._tree_view_item.setText(0, self._data_collection.get_name())

    def acq_parameters_changed(self):
        if self._tree_view_item is None:
            #TODO fix this
            return

        #TODO  get tree view in another way
        dc_tree_widget = self._tree_view_item.listView().parent().parent()
        dc_tree_widget.check_for_path_collisions()
        path_template = self._data_collection.acquisitions[0].path_template
        path_conflict = self.queue_model_hwobj.\
                        check_for_path_collisions(path_template)

    def __add_data_collection(self):
        return self.add_dc_cb(self._data_collection, self.collection_type)

    def mad_energy_selected(self, name, energy, state):
        path_template = self._data_collection.acquisitions[0].path_template

        if state:
            path_template.mad_prefix = str(name)
        else:
            path_template.mad_prefix = ''

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

        self._data_path_widget.set_run_number(run_number)
        self._data_path_widget.set_prefix(path_template.base_prefix)
        model = self._tree_view_item.get_model()
        model.set_name(path_template.get_prefix())
        self._tree_view_item.setText(0, model.get_name())

    def tab_changed(self):
        if self._tree_view_item:
            self.populate_parameter_widget(self._tree_view_item)

    def set_enabled(self, state):
        self._acq_widget.setEnabled(state)
        self._data_path_widget.setEnabled(state)
        self._processing_widget.setEnabled(state)

    def populate_widget(self, item):
        data_collection = item.get_model()
        self._tree_view_item = item
        self._data_collection = data_collection
        self._acquisition_mib = DataModelInputBinder(self._data_collection.\
                                                         acquisitions[0].acquisition_parameters)

        # The acq_widget sends a signal to the path_widget, and it relies
        # on that both models upto date, we need to refactor this part
        # so that both models are set before taking ceratin actions.
        # This workaround, works for the time beeing.
        self._data_path_widget._data_model = data_collection.acquisitions[
            0].path_template

        self._acq_widget.set_energies(
            data_collection.crystal.energy_scan_result)
        self._acq_widget.update_data_model(data_collection.acquisitions[0].\
                                          acquisition_parameters,
                                          data_collection.acquisitions[0].\
                                          path_template)
        self._data_path_widget.update_data_model(data_collection.\
                                           acquisitions[0].path_template)
        self._processing_widget.update_data_model(data_collection.\
                                                 processing_parameters)

        invalid = self._acquisition_mib.validate_all()
        if invalid:
            msg = "This data collection has one or more incorrect parameters,"+\
                " correct the fields marked in red to solve the problem."

            logging.getLogger("GUI").warning(msg)
class AdvancedParametersWidget(QWidget):
    def __init__(self, parent = None, name = "advanced_parameters_widget"):
        QWidget.__init__(self, parent)

        # Hardware objects ----------------------------------------------------
        self._queue_model_hwobj = None
        self._beamline_setup_hwobj = None

        # Internal values -----------------------------------------------------
        self._data_collection = None
        self._tree_view_item = None

        # Properties ----------------------------------------------------------

        # Signals -------------------------------------------------------------

        # Slots ---------------------------------------------------------------

        # Graphic elements ----------------------------------------------------
        _dc_parameters_widget = QWidget(self)
        self._data_path_widget = DataPathWidget(_dc_parameters_widget)
        self._acq_widget = AcquisitionWidget(_dc_parameters_widget,
                                            layout = 'horizontal')

        # Layout --------------------------------------------------------------
        _dc_parameters_widget_layout = QVBoxLayout(_dc_parameters_widget)
        _dc_parameters_widget_layout.addWidget(self._data_path_widget)
        _dc_parameters_widget_layout.addWidget(self._acq_widget)
        _dc_parameters_widget_layout.setSpacing(2)
        _dc_parameters_widget_layout.addStretch(10)
        _dc_parameters_widget_layout.setContentsMargins(0, 0, 0, 0)

        _main_hlayout = QHBoxLayout(self)
        _main_hlayout.addWidget(_dc_parameters_widget)
        _main_hlayout.setSpacing(2)
        _main_hlayout.setContentsMargins(2, 2, 2, 2)
        _main_hlayout.addStretch(0)

        # 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)

        # Ohter ---------------------------------------------------------------
        self._acq_widget.use_osc_start(False)
        self._acq_widget.acq_widget_layout.mad_cbox.hide()
        self._acq_widget.acq_widget_layout.energies_combo.hide()
        self._acq_widget.acq_widget_layout.num_images_ledit.setEnabled(False)
        self._acq_widget.acq_widget_layout.shutterless_cbx.hide()

    def set_beamline_setup(self, bl_setup):
        self._beamline_setup_hwobj = bl_setup
        self._acq_widget.set_beamline_setup(bl_setup)

    def mad_energy_selected(self, name, energy, state):
        path_template = self._data_collection.acquisitions[0].path_template

        if state:
            path_template.mad_prefix = name
        else:
            path_template.mad_prefix = ''

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

        self._data_path_widget.set_run_number(run_number)
        self._data_path_widget.set_prefix(path_template.base_prefix)
        model = self._tree_view_item.get_model()
        model.set_name(path_template.get_prefix())
        self._tree_view_item.setText(0, model.get_name())

    def tab_changed(self):
        if self._tree_view_item:
            self.populate_widget(self._tree_view_item)

    def populate_widget(self, tree_view_item):
        self._tree_view_item = tree_view_item

        if isinstance(tree_view_item, Qt4_queue_item.XrayCenteringQueueItem):
            self._data_collection = tree_view_item.get_model().reference_image_collection
        else:
            self._data_collection = tree_view_item.get_model()
        executed = self._data_collection.is_executed()

        self._acq_widget.setEnabled(not executed)
        self._data_path_widget.setEnabled(not executed)

        self._acquisition_mib = DataModelInputBinder(self._data_collection.\
             acquisitions[0].acquisition_parameters)

        # The acq_widget sends a signal to the path_widget, and it relies
        # on that both models upto date, we need to refactor this part
        # so that both models are set before taking ceratin actions.
        # This workaround, works for the time beeing.
        self._data_path_widget._data_model = self._data_collection.\
             acquisitions[0].path_template
        self._data_path_widget.update_data_model(self._data_collection.\
              acquisitions[0].path_template)

        self._acq_widget.update_data_model(\
             self._data_collection.acquisitions[0].acquisition_parameters,
             self._data_collection.acquisitions[0].path_template)
        #self._acq_widget.use_osc_start(False)
        invalid = self._acquisition_mib.validate_all()
        if invalid:
            msg = "This data collection has one or more incorrect parameters,"+\
                  " correct the fields marked in red to solve the problem."
            logging.getLogger("GUI").warning(msg)
예제 #20
0
class CreateAdvancedScanWidget(CreateTaskBase):
    """
    Descript. :
    """
    def __init__(self, parent=None, name=None, fl=0):
        CreateTaskBase.__init__(self, parent, name, QtCore.Qt.WindowFlags(fl),
                                'Advanced')

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

        # Hardware objects ----------------------------------------------------
        self.__mini_diff_hwobj = None

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

        self.__current_motor_positions = {}
        self.__list_items = {}
        self.__grid_list = []

        self.__beam_info = {}
        self.__spacing = [0, 0]

        # Graphic elements ----------------------------------------------------
        self.mesh_widget = uic.loadUi(
            os.path.join(os.path.dirname(__file__),
                         'ui_files/Qt4_mesh_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_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')

        # 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)

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

        # 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.connect(self._data_path_widget,
                     QtCore.SIGNAL("pathTemplateChanged"),
                     self.handle_path_conflict)

        self.mesh_widget.draw_button.clicked.connect(self.draw_button_clicked)
        self.mesh_widget.remove_button.clicked.connect(
            self.delete_drawing_clicked)
        self.mesh_widget.hor_spacing_ledit.textChanged.connect(self.set_hspace)
        self.mesh_widget.ver_spacing_ledit.textChanged.connect(self.set_vspace)
        self.mesh_widget.mesh_treewidget.currentItemChanged.connect(\
             self.mesh_treewidget_current_item_changed)
        self.mesh_widget.visibility_button.clicked.\
             connect(self.toggle_visibility_grid)

    def init_models(self):
        """
        Descript. :
        """
        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_advanced_values")
            self.__mini_diff_hwobj = self._beamline_setup_hwobj.\
                                     diffractometer_hwobj
        else:
            self._acquisition_parameters = queue_model_objects.AcquisitionParameters(
            )
            self._path_template = queue_model_objects.PathTemplate()

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

        treewidget_item = self.mesh_widget.mesh_treewidget.currentItem()
        if treewidget_item is not None:
            drawing_mgr = self.__list_items[treewidget_item]
            key = str(treewidget_item.text(0))
            selected_grid = drawing_mgr._get_grid(key)[0]
        else:
            logging.getLogger("user_level_log").\
                warning("No grid selected, please select a grid.")
            selected_grid = None
        return result and selected_grid

    def update_processing_parameters(self, crystal):
        """
        Descript. :
        """
        return

    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 = sample_model.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.MESH:
                if tree_item.get_model().is_executed():
                    self.setDisabled(True)
                else:
                    self.setDisabled(False)

                sample_data_model = self.get_sample_item(tree_item).get_model()
                self._acq_widget.disable_inverse_beam(True)

                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
                self._acq_widget.update_data_model(
                    self._acquisition_parameters, self._path_template)
                self.get_acquisition_widget().use_osc_start(True)
            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):
        """
        Descript. :
        """
        data_collections = []

        selected_grid_info = None
        treewidget_item = self.mesh_widget.mesh_treewidget.selectedItem()
        if treewidget_item is not None:
            drawing_mgr = self.__list_items[treewidget_item]
            key = str(treewidget_item.text(0))
            selected_grid_info = drawing_mgr._get_grid(key)[0]

        if selected_grid_info:
            snapshot = self._graphics_manager.get_snapshot([])
            acq = self._create_acq(sample)
            cpoint = selected_grid_info.get("centred_point")
            #cpos = self._beamline_setup_hwobj.diffractometer_hwobj.convert_from_obj_to_name(cpoint)
            acq.acquisition_parameters.centred_position = cpoint
            acq.acquisition_parameters.mesh_steps = [
                selected_grid_info.get("steps_x"),
                selected_grid_info.get("steps_y")
            ]
            acq.acquisition_parameters.mesh_range = [
                selected_grid_info.get("dy_mm"),
                selected_grid_info.get("dx_mm")
            ]
            acq.acquisition_parameters.num_images = selected_grid_info.get("steps_x") * \
                                                    selected_grid_info.get("steps_y")

            processing_parameters = 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.set_grid_id(selected_grid_info.get("id"))
            dc.set_experiment_type(EXPERIMENT_TYPE.MESH)

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

        return data_collections

    def set_beam_info(self, beam_info_dict):
        """
        Descript. :
        """
        self.__beam_info = beam_info_dict
        """if self.__drawing_mgr is not None:
            vspace, hspace = self.get_cell_dim()
            self.__drawing_mgr.set_beam_position(0, 0, self.__beam_size_x, self.__beam_size_y)
            self.__drawing_mgr.set_cell_width(self.__beam_size_x + hspace)
            self.__drawing_mgr.set_cell_height(self.__beam_size_y + vspace)
            self.__drawing_mgr.set_cell_shape(self.__beam_shape == "ellipse")"""

    def draw_button_clicked(self):
        """
        Descript. :
        """
        self.__spacing = self.get_cell_spacing()
        self._graphics_manager_hwobj.start_mesh_draw(self.__beam_info,
                                                     self.__spacing)

    def mesh_created(self, mesh):
        """
        Descript. :
        """
        mesh_properties = mesh.get_properties()
        num_lines = mesh_properties.get("num_lines")
        num_images_per_line = mesh_properties.get("num_images_per_line")
        info_str_list = QtCore.QStringList()
        info_str_list.append(mesh_properties.get("name"))
        info_str_list.append(str(mesh_properties.get("beam_hor") * 1000))
        info_str_list.append(str(mesh_properties.get("beam_ver") * 1000))
        info_str_list.append(str(num_lines))
        info_str_list.append(str(num_images_per_line))
        treewidget_item = QtGui.QTreeWidgetItem(
            self.mesh_widget.mesh_treewidget, info_str_list)
        self.__list_items[treewidget_item] = mesh
        self._acq_widget.acq_widget.num_images_ledit.setText(
            str(num_lines * num_images_per_line))

        grid_coordinates = mesh.get_corner_coord()
        self.update_corner_coord(grid_coordinates, mesh)
        treewidget_item.setSelected(True)
        self.mesh_widget.mesh_treewidget.setCurrentItem(treewidget_item)

    def update_corner_coord(self, coordinates, grid=None):
        """ 
        Descript. : updates corner points and center point of a grid
                    if no grid obejct is passed then currently selected grid is updated
        """
        if not grid:
            treewidget_item = self.mesh_widget.mesh_treewidget.selectedItem()
            grid = self.__list_items[treewidget_item]
        #if drawing_mgr.in_projection_mode():
        if grid:
            # Grid is moved from the drawing position.
            # Grid coordinates are updated via corner points

            corner_points = []
            temp_motor_pos = self.__mini_diff_hwobj.\
               get_centred_point_from_coord(coordinates[0][0],
                                            coordinates[0][1], True)
            corner_points.append(
                queue_model_objects.CentredPosition(temp_motor_pos))

            temp_motor_pos = self.__mini_diff_hwobj.\
               get_centred_point_from_coord(coordinates[1][0],
                                            coordinates[1][1], True)
            corner_points.append(
                queue_model_objects.CentredPosition(temp_motor_pos))

            temp_motor_pos = self.__mini_diff_hwobj.\
               get_centred_point_from_coord(coordinates[2][0],
                                            coordinates[2][1], True)
            corner_points.append(
                queue_model_objects.CentredPosition(temp_motor_pos))

            temp_motor_pos = self.__mini_diff_hwobj.\
               get_centred_point_from_coord(coordinates[3][0],
                                            coordinates[3][1], True)
            corner_points.append(
                queue_model_objects.CentredPosition(temp_motor_pos))
            grid.set_motor_pos_corner(corner_points)
            # Grid is in drawing position, we have to move

            temp_motor_pos = self.__mini_diff_hwobj.\
                   get_centred_point_from_coord(abs((coordinates[0][0] +
                                                     coordinates[1][0]) / 2),
                                                abs((coordinates[0][1] +
                                                     coordinates[2][1]) / 2))

            #cpos = self.__mini_diff_hwobj.convert_from_obj_to_name(temp_motor_pos)
            cpos = queue_model_objects.CentredPosition(temp_motor_pos)
            grid.set_motor_pos_center(cpos)

    def delete_drawing_clicked(self):
        """
        Descript. :
        """
        if len(self.__list_items):
            treewidget_item = self.mesh_widget.mesh_treewidget.currentItem()

            self._graphics_manager_hwobj.delete_shape(
                self.__list_items[treewidget_item])
            self.mesh_widget.mesh_treewidget.takeTopLevelItem(\
                 self.mesh_widget.mesh_treewidget.indexOfTopLevelItem(treewidget_item))

            self._acq_widget.acq_widget.num_images_ledit.setText("0")

    def get_cell_spacing(self):
        hspace = self.mesh_widget.hor_spacing_ledit.text()
        vspace = self.mesh_widget.ver_spacing_ledit.text()
        try:
            vspace = float(vspace)
        except ValueError:
            vspace = 0
        try:
            hspace = float(hspace)
        except ValueError:
            hspace = 0

        return ((hspace / 1000, (vspace) / 1000))

    def set_vspace(self, vspace):
        vspace, hspace = self.get_cell_spacing()
        #self._graphics_manager

    def set_hspace(self, hspace):
        vspace, hspace = self.get_cell_spacing()

    def set_beam_position(self, beam_c_x, beam_c_y, beam_size_x, beam_size_y):
        self.__cell_height = int(beam_size_x * self.__y_pixel_size)
        self.__cell_width = int(beam_size_y * self.__x_pixel_size)

        try:
            vspace, hspace = self.get_cell_spacing()
            self.__drawing_mgr.set_cell_width(self.__beam_size_x + hspace)
            self.__drawing_mgr.set_cell_height(self.__beam_size_y + vspace)

            self.__drawing_mgr.set_beam_position(0, 0, beam_size_x,
                                                 beam_size_y)
            #for drawing_mgr in self.__list_items.itervalues():
            #    drawing_mgr.set_beam_position(beam_c_x, beam_c_y)
        except:
            # Drawing manager not set when called
            pass

    def mesh_treewidget_current_item_changed(self, item, prev_item):
        for index, current_item in enumerate(self.__list_items.iterkeys()):
            mesh = self.__list_items[current_item]
            if current_item == item:
                print "set_selected"
                if mesh.isVisible():
                    self.mesh_widget.visibility_button.setText("Hide")
                else:
                    self.mesh_widget.visibility_button.setText("Show")

                grid_properties = mesh.get_properties()
                cell_count = grid_properties.get("num_lines") * \
                             grid_properties.get("num_images_per_line")
                self._acq_widget.acq_widget.num_images_ledit.setText(
                    "%d" % cell_count)
                self.mesh_widget.hor_spacing_ledit.\
                     setText("%.2f" % float(grid_properties.get("spacing_hor") * 1000))
                self.mesh_widget.ver_spacing_ledit.\
                     setText("%.2f" % float(grid_properties.get("spacing_ver") * 1000))
                self._acq_widget.acq_widget.first_image_ledit.\
                     setText("%d" % grid_properties.get("first_image_num"))

                centred_point = mesh.get_motor_pos_center()
                self._acq_widget.acq_widget.osc_start_ledit.setText(\
                     "%.2f" % float(centred_point.phi))
                self._acq_widget.acq_widget.kappa_ledit.setText(\
                     "%.2f" % float(centred_point.kappa))
                self._acq_widget.acq_widget.kappa_phi_ledit.setText(\
                     "%.2f" % float(centred_point.kappa_phi))

            else:
                mesh.setSelected(False)

    def toggle_visibility_grid(self):
        item = self.mesh_widget.mesh_treewidget.currentItem()

        for current_item in self.__list_items.iterkeys():
            mesh = self.__list_items[current_item]
            if current_item == item:
                if mesh.isVisible():
                    mesh.hide()
                    self.mesh_widget.visibility_button.setText("Show")
                else:
                    mesh.show()
                    self.mesh_widget.visibility_button.setText("Hide")

    def display_grids(self, display):
        for drawing_mgr in self.__list_items.values():
            drawing_mgr.show() if display else drawing_mgr.hide()

    def set_motor_pos(self, motor_pos):
        for drawing_mgr in self.__list_items.values():
            drawing_mgr.set_motor_pos_actual(motor_pos)
        self.current_motor_positions = motor_pos

    def update_grid_corner_points(self):
        for drawing_mgr in self.__list_items.values():
            grid_corner_points = drawing_mgr.get_grid_corner_points()[0]
            grid_coordinates = []
            for grid_corner_point in grid_corner_points:
                grid_coordinates.append(
                    self.__mini_diff_hwobj.motor_positions_to_screen(
                        grid_corner_point))
            drawing_mgr.set_grid_coordinates(grid_coordinates)[0]

    def move_to_center_point(self):
        treewidget_item = self.mesh_widget.mesh_treewidget.selectedItem()
        drawing_mgr = self.__list_items[treewidget_item]
        cpos = drawing_mgr.get_grid_center_point()[0]
        self.__mini_diff_hwobj.moveToMotorsPositions(cpos)

    def _get_grid_info(self, grid_dict):
        treewidget_item = self.mesh_widget.mesh_treewidget.selectedItem()
        if treewidget_item is not None:
            drawing_mgr = self.__list_items[treewidget_item]
            key = str(treewidget_item.text(0))
            grid_dict.update(drawing_mgr._get_grid(key)[0])

    def _set_grid_data(self, key, result_data):
        for treewidget_item in self.__list_items.keys():
            if key == str(treewidget_item.text(0)):
                drawing_mgr = self.__list_items[treewidget_item]
                drawing_mgr.set_data(result_data)
                break