Exemple #1
0
 def compute(self, name, func, param=None, suffix=None, interactive=True):
     try:
         result = self.start_compute(name, func, param, suffix, interactive)
         return self.end_compute(result)
     except ComputationError, msg:
         print _("Computation error: %s") % msg
         return
Exemple #2
0
    def histogram(self, data, bins=None, logscale=None,
                  title="", color=None, xaxis="bottom", yaxis="left"):
        """
        Make 1D Histogram `plot item` 
        (:py:class:`guiqwt.histogram.HistogramItem` object)

            * data (1D NumPy array)
            * bins: number of bins (int)
            * logscale: Y-axis scale (bool)
        """
        basename = _("Histogram")
        histparam = HistogramParam(title=basename, icon='histogram.png')
        curveparam = CurveParam(_("Curve"), icon='curve.png')
        curveparam.read_config(CONF, "histogram", "curve")
        if not title:
            global HISTOGRAM_COUNT
            HISTOGRAM_COUNT += 1
            title = make_title(basename, HISTOGRAM_COUNT)
        curveparam.label = title
        if color is not None:
            curveparam.line.color = color
        if bins is not None:
            histparam.n_bins = bins
        if logscale is not None:
            histparam.logscale = logscale
        return self.phistogram(data, curveparam, histparam, xaxis, yaxis)
Exemple #3
0
 def setup_actions(self):
     CrossSectionWidget.setup_actions(self)
     self.peritem_ac = create_action(
         self,
         _("Per image cross-section"),
         icon=get_icon("csperimage.png"),
         toggled=self.cs_plot.toggle_perimage_mode,
         tip=_(
             "Enable the per-image cross-section mode, "
             "which works directly on image rows/columns.\n"
             "That is the fastest method to compute "
             "cross-section curves but it ignores "
             "image transformations (e.g. rotation)"
         ),
     )
     self.applylut_ac = create_action(
         self,
         _("Apply LUT\n(contrast settings)"),
         icon=get_icon("csapplylut.png"),
         toggled=self.cs_plot.toggle_apply_lut,
         tip=_(
             "Apply LUT (Look-Up Table) contrast settings.\n"
             "This is the easiest way to compare images "
             "which have slightly different level ranges.\n\n"
             "Note: LUT is coded over 1024 levels (0...1023)"
         ),
     )
     self.peritem_ac.setChecked(True)
     self.applylut_ac.setChecked(False)
 def about(self):
     QMessageBox.about( self, _("About ")+APP_NAME,
           """<b>%s</b> v%s<p>%s Matt Nottingham
           <br>Copyright &copy; 2015 Matt Nottingham
           <p>Python %s, Qt %s, PyQt %s %s %s""" % \
           (APP_NAME, VERS, _("Developped by"), platform.python_version(),
            QT_VERSION_STR, PYQT_VERSION_STR, _("on"), platform.system()) )
Exemple #5
0
    def set_slice_value(self, value):
        """Set the current slice to a given value. If the value is not in the
        measured discrete scale, it will interpolate data between the adjacent
        slices.
            \arg value a float within scale.min() and scale.max()
        """
        assert isinstance(value,
                          (int, float)), _('Slice value has to be a float')
        scale = self.measurement.param.axis3.get_scale()
        if not scale.min() <= value <= scale.max():
            raise ValueError, _('Slice value out of range')

        if value in scale:
            # get the index with value nearest to v
            index = where(scale == value)[0][0]
            self.set_data(self.measurement.rawdata[index, :, :])
        else:
            # get the lowest index with value nearest to v
            index = where(scale > value)[0][0]
            coef = (value - scale[index]) / (scale[index + 1] - scale[index])
            rawdata = self.measurement.rawdata
            interpolated_data = rawdata[index,:,:] * (1 - coef) \
                    + rawdata[index+1,:,:] * coef
            self.set_data(interpolated_data)
        self.current_index = index
Exemple #6
0
def exec_image_open_dialog(parent,
                           basedir='',
                           app_name=None,
                           to_grayscale=True,
                           dtype=None):
    """
    Executes an image open dialog box (QFileDialog.getOpenFileName)
        * parent: parent widget (None means no parent)
        * basedir: base directory ('' means current directory)
        * app_name (opt.): application name (used as a title for an eventual 
          error message box in case something goes wrong when saving image)
        * to_grayscale (default=True): convert image to grayscale
    
    Returns (filename, data) tuple if dialog is accepted, None otherwise
    """
    saved_in, saved_out, saved_err = sys.stdin, sys.stdout, sys.stderr
    sys.stdout = None
    filename, _filter = getopenfilename(
        parent, _("Open"), basedir,
        io.iohandler.get_filters('load', dtype=dtype))
    sys.stdin, sys.stdout, sys.stderr = saved_in, saved_out, saved_err
    filename = to_text_string(filename)
    try:
        data = io.imread(filename, to_grayscale=to_grayscale)
    except Exception as msg:
        import traceback
        traceback.print_exc()
        QMessageBox.critical(parent,
             _('Error') if app_name is None else app_name,
             (_("%s could not be opened:") % osp.basename(filename))+\
             "\n"+str(msg))
        return
    return filename, data
Exemple #7
0
 def get_infos(self):
     """Return formatted string with informations on current shape"""
     return "<br>".join([
         _("Center:") + " " + self.get_tr_center_str(),
         _("Size:") + " " + self.get_tr_size_str(),
         _("Angle:") + " %.1f°" % self.get_tr_angle(),
     ])
Exemple #8
0
 def about(self):
     QMessageBox.about( self, _("About ")+APP_NAME,
           """<b>%s</b> v%s<p>%s Pierre Raybaut
           <br>Copyright &copy; 2009-2010 CEA
           <p>Python %s, Qt %s, PyQt %s %s %s""" % \
           (APP_NAME, VERSION, _("Developped by"), platform.python_version(),
            QT_VERSION_STR, PYQT_VERSION_STR, _("on"), platform.system()) )
Exemple #9
0
    def create_window(self, items):
        if not isinstance(items, (tuple, list)):
            items = (items,)
        for item in items:
            if isinstance(item, ThothCurveItem):
                window = self._create_curve_window(item)
            elif isinstance(item, ThothImageItem):
                window = self._create_image_window(item)
            elif isinstance(item, ThothMapItem):
                window = self._create_map_window(item)
            else:
                raise ValueError, _('Not supported measurement type')
            other_tools = window.addToolBar(_("Other tools"))
            window.add_toolbar(other_tools,
                               toolbar_id="other_tools")
            for toolklass in (LabelTool, HRangeTool,
                              VCursorTool, HCursorTool, XCursorTool,
                              SegmentTool, RectangleTool, ObliqueRectangleTool,
                              CircleTool, EllipseTool,
                              MultiLineTool, FreeFormTool, PlaceAxesTool,
                              AnnotatedRectangleTool,
                              AnnotatedObliqueRectangleTool,
                              AnnotatedCircleTool, AnnotatedEllipseTool,
                              AnnotatedSegmentTool, AnnotatedPointTool,
                              WeightTool,
                              SelectPointTool,
                              ExtractCurveTool,
                              ):
                window.add_tool(toolklass, toolbar_id="other_tools")

            self.register_window(window)
Exemple #10
0
 def about(self):
     QMessageBox.about( self, _("About ")+APP_NAME,
           """<b>%s</b> v%s<p>%s Pierre Raybaut
           <br>Copyright &copy; 2009-2010 CEA
           <p>Python %s, Qt %s, PyQt %s %s %s""" % \
           (APP_NAME, VERSION, _("Developped by"), platform.python_version(),
            QT_VERSION_STR, PYQT_VERSION_STR, _("on"), platform.system()) )
Exemple #11
0
def exec_image_open_dialog(parent, basedir='', app_name=None,
                           to_grayscale=True, dtype=None):
    """
    Executes an image open dialog box (QFileDialog.getOpenFileName)
        * parent: parent widget (None means no parent)
        * basedir: base directory ('' means current directory)
        * app_name (opt.): application name (used as a title for an eventual 
          error message box in case something goes wrong when saving image)
        * to_grayscale (default=True): convert image to grayscale
    
    Returns (filename, data) tuple if dialog is accepted, None otherwise
    """
    saved_in, saved_out, saved_err = sys.stdin, sys.stdout, sys.stderr
    sys.stdout = None
    filename, _filter = getopenfilename(parent, _("Open"), basedir,
                                io.iohandler.get_filters('load', dtype=dtype))
    sys.stdin, sys.stdout, sys.stderr = saved_in, saved_out, saved_err
    filename = to_text_string(filename)
    try:
        data = io.imread(filename, to_grayscale=to_grayscale)
    except Exception as msg:
        import traceback
        traceback.print_exc()
        QMessageBox.critical(parent,
             _('Error') if app_name is None else app_name,
             (_("%s could not be opened:") % osp.basename(filename))+\
             "\n"+str(msg))
        return
    return filename, data
Exemple #12
0
    def compute_ifft(self):
        """Compute iFFT"""
        import numpy.fft
        from numpy import absolute

        def func(data):
            return array([
                numpy.fft.fftshift(absolute(numpy.fft.ifft2(slice_)))
                for slice_ in data
            ])

        result = self.start_compute(_('Fourrier transform'), func)
        new_x = numpy.fft.fftshift(
            numpy.fft.fftfreq(self['axis1']['length'],
                              d=self['axis1']['increment']))
        new_y = numpy.fft.fftshift(
            numpy.fft.fftfreq(self['axis2']['length'],
                              d=self['axis2']['increment']))
        result['unit'] = _('a.u.')
        result['axis1']['start'] = new_x[0]
        result['axis1']['increment'] = new_x[1] - new_x[0]
        result['axis1']['unit'] = '1/%s' % result['axis1']['unit']
        result['axis2']['start'] = new_y[0]
        result['axis2']['increment'] = new_y[1] - new_y[0]
        result['axis2']['unit'] = '1/%s' % result['axis2']['unit']
        return self.end_compute(result)
Exemple #13
0
 def __floordiv__(self, a):
     if not isinstance(a, (int, float)):
         raise TypeError, _('Unsupported operand type')
     new_param = self.param.copy()
     new_param.processing += _('divided by %2.3g') % (a, ) + '\n'
     new_data = self.rawdata // a
     return Measurement(new_data, new_param)
Exemple #14
0
    def compute_spline_derivative(self, param=None, interactive=True):
        """ Compute the derivative of the curve basde on spline
            interpolation"""
        from scipy.interpolate import splrep, splev

        class SplineParam(DataSet):
            s = FloatItem(_("s"),
                          default=0.1,
                          min=0,
                          help=_('''Larger s means more smoothing while
smaller values of s indicate less smoothing. 0 is no smoothing.'''))

        if param is None:
            param = SplineParam(_("Spline smoothing"))

        def func(y, p):
            tck = splrep(arange(len(y)), y, s=p.s)  # get spline coef tuple
            return splev(arange(len(y)), tck, der=1)  # compute 1st derivative

        result = self.start_compute(_("Spline derivative"), func, param,
                                    lambda p: u"s=%i" % p.s, interactive)
        if result['type'] == 'ivcurve':
            result['type'] = 'didvcurve'
            result['unit'] = _('a.u.')
        else:
            result['type'] == 'unknowncurve'
        return self.end_compute(result)
Exemple #15
0
    def compute_savitzky(self, param=None, interactive=True):
        """Linewise smoothing of data based on the Savitzky-Golay
           algorithm"""
        import sgfilter

        class SGParam(DataSet):
            num_points = IntItem(_("Number of points"), default=8, min=2)
            poly_degree = IntItem(_("Polynom degree"), default=4, min=1)
            diff_order = 0

        if param is None:
            param = SGParam(_("Savitzky-Golay filter"))

        def func(data, p):
            return array([
                sgfilter.savitzky(line, p.num_points, p.poly_degree,
                                  p.diff_order) for line in data
            ])
        return self.compute(_('Smoothed with Savitzky-Golay'),
                            func,
                            param,
                            lambda p: _("""%i points, polynom degree %i, differential order %i""") % \
                                        (p.poly_degree, p.num_points,
                                         p.diff_order),
                            interactive=interactive)
Exemple #16
0
    def add_buttons_to_layout(self, layout):
        """Add tool buttons to layout"""
        # Image orientation
        angle_label = QLabel(_("Angle (°):"))
        layout.addWidget(angle_label)
        self.angle_combo = QComboBox(self)
        self.angle_combo.addItems(self.ROTATION_ANGLES)
        self.angle_combo.setCurrentIndex(1)
        self.angle_combo.currentIndexChanged.connect(
            lambda index: self.apply_transformation())
        layout.addWidget(self.angle_combo)
        layout.addSpacing(10)

        # Image flipping
        flip_label = QLabel(_("Flip:"))
        layout.addWidget(flip_label)
        hflip = create_toolbutton(
            self,
            text="",
            icon=get_icon("hflip.png"),
            toggled=lambda state: self.apply_transformation(),
            autoraise=False)
        self.hflip_btn = hflip
        layout.addWidget(hflip)
        vflip = create_toolbutton(
            self,
            text="",
            icon=get_icon("vflip.png"),
            toggled=lambda state: self.apply_transformation(),
            autoraise=False)
        self.vflip_btn = vflip
        layout.addWidget(vflip)
        layout.addSpacing(15)

        self.add_reset_button(layout)
Exemple #17
0
    def compute_savitzky(self, param=None, interactive=True):
        """Smooth or derivate data based on the Savitzky-Golay algorithm"""
        import sgfilter

        class SGParam(DataSet):
            num_points = IntItem(_("Number of points"), default=8, min=2)
            poly_degree = IntItem(_("Polynom degree"), default=4, min=1)
            diff_order = IntItem(_("Differential order"), default=0, min=0)

        if param is None:
            param = SGParam(_("Savitzky-Golay filter"))

        def func(y, p):
            return sgfilter.savitzky(y, p.num_points, p.poly_degree,
                                     p.diff_order)

        try:
            result = self.start_compute(_('Smoothed with Savitzky-Golay'),
                                func,
                                param,
                                lambda p: _("""%i points, polynom degree %i, differential order %i""") % \
                                            (p.poly_degree, p.num_points,
                                            p.diff_order),
                                interactive)
            if param.diff_order == 1 and result['type'] == 'ivcurve':
                result['type'] = 'didvcurve'
                result['unit'] = _('a.u.')
            else:
                result['type'] == 'unknowncurve'
            return self.end_compute(result)
        except ComputationError, msg:
            print msg
Exemple #18
0
    def __init__(self, parent=None):
        super(LevelsHistogram, self).__init__(parent=parent,
                                              title="",
                                              section="histogram")
        self.antialiased = False

        # a dict of dict : plot -> selected items -> HistogramItem
        self._tracked_items = {}
        self.curveparam = CurveParam(_("Curve"), icon="curve.png")
        self.curveparam.read_config(CONF, "histogram", "curve")

        self.histparam = HistogramParam(_("Histogram"), icon="histogram.png")
        self.histparam.logscale = False
        self.histparam.n_bins = 256

        self.range = XRangeSelection(0, 1)
        self.range_mono_color = self.range.shapeparam.sel_line.color
        self.range_multi_color = CONF.get("histogram", "range/multi/color",
                                          "red")

        self.add_item(self.range, z=5)
        self.SIG_RANGE_CHANGED.connect(self.range_changed)
        self.set_active_item(self.range)

        self.setMinimumHeight(80)
        self.setAxisMaxMajor(self.Y_LEFT, 5)
        self.setAxisMaxMinor(self.Y_LEFT, 0)

        if parent is None:
            self.set_axis_title("bottom", "Levels")
Exemple #19
0
 def __init__(self, parent=None, section="plot"):
     super(BasePlot, self).__init__(parent)
     self._start_autoscaled = True
     self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
     self.manager = None
     self.plot_id = None  # id assigned by it's manager
     self.filter = StatefulEventFilter(self)
     self.items = []
     self.active_item = None
     self.last_selected = {
     }  # a mapping from item type to last selected item
     self.axes_styles = [
         AxeStyleParam(_("Left")),
         AxeStyleParam(_("Right")),
         AxeStyleParam(_("Bottom")),
         AxeStyleParam(_("Top")),
     ]
     self._active_xaxis = self.DEFAULT_ACTIVE_XAXIS
     self._active_yaxis = self.DEFAULT_ACTIVE_YAXIS
     self.read_axes_styles(section, self.AXIS_CONF_OPTIONS)
     self.font_title = get_font(CONF, section, "title")
     canvas = self.canvas()
     canvas.setFocusPolicy(Qt.StrongFocus)
     canvas.setFocusIndicator(QwtPlotCanvas.ItemFocusIndicator)
     self.SIG_ITEM_MOVED.connect(self._move_selected_items_together)
     self.legendDataChanged.connect(
         lambda item, _legdata: item.update_item_parameters())
Exemple #20
0
 def add_buttons_to_layout(self, layout):
     """Add tool buttons to layout"""
      # Image orientation
     angle_label = QLabel(_("Angle (°):"))
     layout.addWidget(angle_label)
     self.angle_combo = QComboBox(self)
     self.angle_combo.addItems(self.ROTATION_ANGLES)
     self.angle_combo.setCurrentIndex(1)
     self.angle_combo.currentIndexChanged.connect(
                              lambda index: self.apply_transformation())
     layout.addWidget(self.angle_combo)
     layout.addSpacing(10)
     
     # Image flipping
     flip_label = QLabel(_("Flip:"))
     layout.addWidget(flip_label)
     hflip = create_toolbutton(self, text="", icon=get_icon("hflip.png"),
                       toggled=lambda state: self.apply_transformation(),
                       autoraise=False)
     self.hflip_btn = hflip
     layout.addWidget(hflip)
     vflip = create_toolbutton(self, text="", icon=get_icon("vflip.png"),
                       toggled=lambda state: self.apply_transformation(),
                       autoraise=False)
     self.vflip_btn = vflip
     layout.addWidget(vflip)
     layout.addSpacing(15)
     
     self.add_reset_button(layout)
Exemple #21
0
    def histogram(
        self,
        data,
        bins=None,
        logscale=None,
        title="",
        color=None,
        xaxis="bottom",
        yaxis="left",
    ):
        """
        Make 1D Histogram `plot item` 
        (:py:class:`guiqwt.histogram.HistogramItem` object)

            * data (1D NumPy array)
            * bins: number of bins (int)
            * logscale: Y-axis scale (bool)
        """
        basename = _("Histogram")
        histparam = HistogramParam(title=basename, icon="histogram.png")
        curveparam = CurveParam(_("Curve"), icon="curve.png")
        curveparam.read_config(CONF, "histogram", "curve")
        if not title:
            global HISTOGRAM_COUNT
            HISTOGRAM_COUNT += 1
            title = make_title(basename, HISTOGRAM_COUNT)
        curveparam.label = title
        if color is not None:
            curveparam.line.color = color
        if bins is not None:
            histparam.n_bins = bins
        if logscale is not None:
            histparam.logscale = logscale
        return self.phistogram(data, curveparam, histparam, xaxis, yaxis)
Exemple #22
0
 def setup_actions(self):
     CrossSectionWidget.setup_actions(self)
     self.peritem_ac = create_action(
         self,
         _("Per image cross-section"),
         icon=get_icon("csperimage.png"),
         toggled=self.cs_plot.toggle_perimage_mode,
         tip=_(
             "Enable the per-image cross-section mode, "
             "which works directly on image rows/columns.\n"
             "That is the fastest method to compute "
             "cross-section curves but it ignores "
             "image transformations (e.g. rotation)"
         ),
     )
     self.applylut_ac = create_action(
         self,
         _("Apply LUT\n(contrast settings)"),
         icon=get_icon("csapplylut.png"),
         toggled=self.cs_plot.toggle_apply_lut,
         tip=_(
             "Apply LUT (Look-Up Table) contrast settings.\n"
             "This is the easiest way to compare images "
             "which have slightly different level ranges.\n\n"
             "Note: LUT is coded over 1024 levels (0...1023)"
         ),
     )
     self.peritem_ac.setChecked(True)
     self.applylut_ac.setChecked(False)
Exemple #23
0
 def get_infos(self):
     """Return formatted string with informations on current shape"""
     return "<br>".join([
                         _("Center:") + " " + self.get_tr_center_str(),
                         _("Size:") + " " + self.get_tr_size_str(),
                         _("Angle:") + " %.1f°" % self.get_tr_angle(),
                         ])
Exemple #24
0
def exec_image_save_dialog(parent, data, template=None,
                           basedir='', app_name=None):
    """
    Executes an image save dialog box (QFileDialog.getSaveFileName)
        * parent: parent widget (None means no parent)
        * data: image pixel array data
        * template: image template (pydicom dataset) for DICOM files
        * basedir: base directory ('' means current directory)
        * app_name (opt.): application name (used as a title for an eventual 
          error message box in case something goes wrong when saving image)
    
    Returns filename if dialog is accepted, None otherwise
    """
    saved_in, saved_out, saved_err = sys.stdin, sys.stdout, sys.stderr
    sys.stdout = None
    filename, _filter = getsavefilename(parent, _("Save as"), basedir,
        io.iohandler.get_filters('save', dtype=data.dtype, template=template))
    sys.stdin, sys.stdout, sys.stderr = saved_in, saved_out, saved_err
    if filename:
        filename = to_text_string(filename)
        kwargs = {}
        if osp.splitext(filename)[1].lower() == '.dcm':
            kwargs['template'] = template
        try:
            io.imwrite(filename, data, **kwargs)
            return filename
        except Exception as msg:
            import traceback
            traceback.print_exc()
            QMessageBox.critical(parent,
                 _('Error') if app_name is None else app_name,
                 (_("%s could not be written:") % osp.basename(filename))+\
                 "\n"+str(msg))
            return
Exemple #25
0
 def about( self ):
     QMessageBox.about( self, _("About ")+APP_NAME,
           """<b>%s</b> v%s<p>%s Darko Petrovic
           <br>(Lisence goes here)
           <p>Python %s, Qt %s, PyQt %s %s %s""" % \
           (APP_NAME, VERSION, _("Developped by"), platform.python_version(),
            QT_VERSION_STR, PYQT_VERSION_STR, _("on"), platform.system()) )
Exemple #26
0
    def __init__(self, parent=None):
        super(LevelsHistogram, self).__init__(parent=parent, title="",
                                              section="histogram")
        self.antialiased = False

        # a dict of dict : plot -> selected items -> HistogramItem
        self._tracked_items = {}
        self.curveparam = CurveParam(_("Curve"), icon="curve.png")
        self.curveparam.read_config(CONF, "histogram", "curve")
        
        self.histparam = HistogramParam(_("Histogram"), icon="histogram.png")
        self.histparam.logscale = False
        self.histparam.n_bins = 256

        self.range = XRangeSelection(0, 1)
        self.range_mono_color = self.range.shapeparam.sel_line.color
        self.range_multi_color = CONF.get("histogram",
                                          "range/multi/color", "red")
        
        self.add_item(self.range, z=5)
        self.connect(self, SIG_RANGE_CHANGED, self.range_changed)
        self.set_active_item(self.range)

        self.setMinimumHeight(80)
        self.setAxisMaxMajor(self.Y_LEFT, 5)
        self.setAxisMaxMinor(self.Y_LEFT, 0)

        if parent is None:
            self.set_axis_title('bottom', 'Levels')
Exemple #27
0
 def setup_actions(self):
     self.export_ac = self.export_tool.action
     self.lockscales_ac = create_action(
         self,
         _("Lock scales"),
         icon=get_icon('axes.png'),
         toggled=self.cs_plot.toggle_lockscales,
         tip=_("Lock scales to main plot axes"))
     self.lockscales_ac.setChecked(self.cs_plot.lockscales)
     self.autoscale_ac = create_action(
         self,
         _("Auto-scale"),
         icon=get_icon('csautoscale.png'),
         toggled=self.cs_plot.toggle_autoscale)
     self.autoscale_ac.toggled.connect(self.lockscales_ac.setDisabled)
     self.autoscale_ac.setChecked(self.cs_plot.autoscale_mode)
     self.refresh_ac = create_action(
         self,
         _("Refresh"),
         icon=get_icon('refresh.png'),
         triggered=lambda: self.cs_plot.update_plot())
     self.autorefresh_ac = create_action(
         self,
         _("Auto-refresh"),
         icon=get_icon('autorefresh.png'),
         toggled=self.cs_plot.toggle_autorefresh)
     self.autorefresh_ac.setChecked(self.cs_plot.autorefresh_mode)
Exemple #28
0
 def __add__(self, a):
     if isinstance(a, self.__baseclass__):
         return self.__baseclass__(self.measurement + a.measurement)
     elif isinstance(a, (int, float)):
         return self.__baseclass__(self.measurement + a)
     else:
         raise TypeError, _('Unsupported operand type')
Exemple #29
0
 def extract_curve(self, shape):
     for item in self.get_active_plot().get_items():
         if isinstance(item, ThothMapItem):
             try:
                 item.compute_get_curve_at_position(*shape.get_pos())
             except IndexError:
                 print _("Outside of image bound.")
             break
Exemple #30
0
 def extract_curve(self, shape):
     for item in self.get_active_plot().get_items():
         if isinstance(item, ThothMapItem):
             try:
                 item.compute_get_curve_at_position(*shape.get_pos())
             except IndexError:
                 print _("Outside of image bound.")
             break
Exemple #31
0
    def __init__(self, *args, **kwargs):
        super(ROISelectTool, self).__init__(*args, **kwargs)

        self.name = "ROI"
        self.rect.label_txt = self.name
        self.TIP = _("Select ROI")
        self.TITLE = _("ROI")
        '''
Exemple #32
0
    def compute_shift(self, param=None, interactive=True):
        """Shift the curve by the given amount"""
        class ShiftParam(DataSet):
            shift = FloatItem(_("Shift by"), default=1)

        if param is None:
            param = ShiftParam(_("Shift"))
        return self.compute(_("Shifted"), lambda y, p: y + p.shift, param,
                            lambda p: _("shift = %.3f") % p.shift, interactive)
Exemple #33
0
 def __init__(self, parent):
     QSplitter.__init__(self, parent)
     self.parent = parent
     self.Controlvalues = DataSetEditGroupBox(_("Control panel"),
                                              Controlwidget,
                                              show_button=False)
     self.addWidget(self.Controlvalues)
     self.HKvalues = DataSetShowGroupBox(_("Housekeeping"), HKwidget)
     self.addWidget(self.HKvalues)
     self.setSizes([2000, 1])
class SampleParameters(DataSet):  #Sample parameters
    index_medium = FloatItem(_("Medium index"), default=1.33, min=1.)
    index_chamber = FloatItem(_("Chamber index closing the chamber"),
                              default=1.52,
                              min=1.)
    index_sample = FloatItem(_("Sample index"), default=1., min=1.)
    max_displacement = FloatItem(_("Max Displacement"),
                                 default=20,
                                 min=1.,
                                 unit='pixels')
class RemoteParameters(ActivableDataSet):  #Sequence parameters
    #read database to know default directory
    db = SqliteDB.DBReader()
    directoryPath = DirectoryItem("Seq. dir.", default=db.DefaultDirectory)
    first_holo_seq = IntItem(_("First hologram"), default=0, min=0)
    #last holo seq is defined with framesNumberProp that is modified when a new directory is choose
    last_holo_seq = IntItem(_("Last hologram"), default=framesNumberprop)
    saveAllStack = ChoiceItem(_("Save All stacks"), [(True, 'Yes'),
                                                     (False, 'False')],
                              default=False)
Exemple #36
0
    def create_plot(self, options):
        self.filter_gbox = DataSetEditGroupBox(_("Filter parameters"), FilterParam)
        self.filter_gbox.setEnabled(False)
        self.filter_gbox.SIG_APPLY_BUTTON_CLICKED.connect(self.apply_filter)
        self.plot_layout.addWidget(self.filter_gbox, 0, 0)
        self.param_gbox = DataSetShowGroupBox(_("Image parameters"), ImageParam)
        self.plot_layout.addWidget(self.param_gbox, 0, 1)

        options = dict(title=_("Image title"), zlabel=_("z-axis scale label"))
        ImageDialog.create_plot(self, options, 1, 0, 1, 0)
Exemple #37
0
    def compute_scale(self, param=None, interactive=True):
        """Multiply the curve by the given factor"""
        class ScaleParam(DataSet):
            factor = FloatItem(_("Scaling factor"), default=1)

        if param is None:
            param = ScaleParam(_("Scaling"))
        return self.compute(_("Scaled"), lambda y, p: y * p.factor, param,
                            lambda p: _("factor = %.3f") % p.factor,
                            interactive)
Exemple #38
0
 def edit_axis_parameters(self, axis_id):
     """Edit axis parameters"""
     if axis_id in (self.Y_LEFT, self.Y_RIGHT):
         title = _("Y Axis")
     else:
         title = _("X Axis")
     param = AxisParam(title=title)
     param.update_param(self, axis_id)
     if param.edit(parent=self):
         param.update_axis(self, axis_id)
         self.replot()
Exemple #39
0
 def create_plot(self, options):
     self.filter_gbox = DataSetEditGroupBox(_("Filter parameters"),
                                            FilterParam)
     self.filter_gbox.setEnabled(False)
     self.filter_gbox.SIG_APPLY_BUTTON_CLICKED.connect(self.apply_filter)
     self.plot_layout.addWidget(self.filter_gbox, 0, 0)
     self.param_gbox = DataSetShowGroupBox(_("Image parameters"), ImageParam)
     self.plot_layout.addWidget(self.param_gbox, 0, 1)
     
     options = dict(title=_("Image title"), zlabel=_("z-axis scale label"))
     ImageDialog.create_plot(self, options, 1, 0, 1, 0)
Exemple #40
0
 def edit_axis_parameters(self, axis_id):
     """Edit axis parameters"""
     if axis_id in (self.Y_LEFT, self.Y_RIGHT):
         title = _("Y Axis")
     else:
         title = _("X Axis")
     param = AxisParam(title=title)
     param.update_param(self, axis_id)
     if param.edit(parent=self):
         param.update_axis(self, axis_id)
         self.replot()
Exemple #41
0
 def __getitem__(self, key):
     if 'physical length' == key:
         return self.get_physical_length()
     elif 'length' == key:
         return self.get_length()
     elif 'scale' == key:
         return self.get_scale()
     else:
         try:
             return getattr(self, key)
         except AttributeError:
             raise KeyError, _("They are no such attributes %s.") % key
Exemple #42
0
    def setup(self):
        """Setup window parameters"""
        self.setWindowIcon(get_icon("python.png"))
        self.setWindowTitle(APP_NAME)
        self.resize(QSize(600, 800))

        # Welcome message in statusbar:
        status = self.statusBar()
        status.showMessage(_("Welcome to guiqwt application example!"), 5000)

        # File menu
        file_menu = self.menuBar().addMenu(_("File"))
        new_action = create_action(
            self,
            _("New..."),
            shortcut="Ctrl+N",
            icon=get_icon("filenew.png"),
            tip=_("Create a new image"),
            triggered=self.new_image,
        )
        open_action = create_action(
            self,
            _("Open..."),
            shortcut="Ctrl+O",
            icon=get_icon("fileopen.png"),
            tip=_("Open an image"),
            triggered=self.open_image,
        )
        quit_action = create_action(
            self,
            _("Quit"),
            shortcut="Ctrl+Q",
            icon=get_std_icon("DialogCloseButton"),
            tip=_("Quit application"),
            triggered=self.close,
        )
        add_actions(file_menu, (new_action, open_action, None, quit_action))

        # Help menu
        help_menu = self.menuBar().addMenu("?")
        about_action = create_action(
            self,
            _("About..."),
            icon=get_std_icon("MessageBoxInformation"),
            triggered=self.about,
        )
        add_actions(help_menu, (about_action, ))

        main_toolbar = self.addToolBar("Main")
        add_actions(main_toolbar, (
            new_action,
            open_action,
        ))

        # Set central widget:
        toolbar = self.addToolBar("Image")
        self.mainwidget = CentralWidget(self, toolbar)
        self.setCentralWidget(self.mainwidget)
Exemple #43
0
 def register_measurement(self, measurements):
     if not isinstance(measurements, (tuple, list)):
         measurements = (measurements,)
     for measurement in measurements:
         type_ = measurement.param.type
         if type_ in ('ivcurve', 'didvcurve'):
             self.register_item(ThothCurveItem(measurement))
         elif type_ in ('topo','topofft'):
             self.register_item(ThothImageItem(measurement))
         elif type_ in ('ivmap','ivmapfft','didvmap','didvmapfft'):
             self.register_item(ThothMapItem(measurement))
         else:
             raise ValueError, _('Not supported measurement type')
Exemple #44
0
 def setup_actions(self):
     fullrange_ac = create_action(self, _("Full range"),
                                  icon=get_icon("full_range.png"),
                                  triggered=self.histogram.set_full_range,
                                  tip=_("Scale the image's display range "
                                        "according to data range") )
     autorange_ac = create_action(self, _("Eliminate outliers"),
                                  icon=get_icon("eliminate_outliers.png"),
                                  triggered=self.eliminate_outliers,
                                  tip=_("Eliminate levels histogram "
                                        "outliers and scale the image's "
                                        "display range accordingly") )
     add_actions(self.toolbar, [fullrange_ac, autorange_ac])
Exemple #45
0
 def setup_actions(self):
     self.export_ac = self.export_tool.action
     self.autoscale_ac = create_action(self, _("Auto-scale"),
                                icon=get_icon('csautoscale.png'),
                                toggled=self.cs_plot.toggle_autoscale)
     self.autoscale_ac.setChecked(self.cs_plot.autoscale_mode)
     self.refresh_ac = create_action(self, _("Refresh"),
                                icon=get_icon('refresh.png'),
                                triggered=lambda: self.cs_plot.update_plot())
     self.autorefresh_ac = create_action(self, _("Auto-refresh"),
                                icon=get_icon('autorefresh.png'),
                                toggled=self.cs_plot.toggle_autorefresh)
     self.autorefresh_ac.setChecked(self.cs_plot.autorefresh_mode)
Exemple #46
0
 def configure_panel(self):
     """Configure panel"""
     self.min_select_tool = self.manager.add_tool(SelectPointTool,
                                    title=_("Minimum level"),
                                    on_active_item=True, mode="create",
                                    tip=_("Select minimum level on image"),
                                    toolbar_id="contrast",
                                    end_callback=self.apply_min_selection)
     self.max_select_tool = self.manager.add_tool(SelectPointTool,
                                    title=_("Maximum level"),
                                    on_active_item=True, mode="create",
                                    tip=_("Select maximum level on image"),
                                    toolbar_id="contrast",
                                    end_callback=self.apply_max_selection)        
Exemple #47
0
 def create_autofit_group(self):        
     auto_button = QPushButton(get_icon('apply.png'), _("Run"), self)
     auto_button.clicked.connect(self.autofit)
     autoprm_button = QPushButton(get_icon('settings.png'), _("Settings"),
                                  self)
     autoprm_button.clicked.connect(self.edit_parameters)
     xrange_button = QPushButton(get_icon('xrange.png'), _("Bounds"), self)
     xrange_button.setCheckable(True)
     xrange_button.toggled.connect(self.toggle_xrange)
     auto_layout = QVBoxLayout()
     auto_layout.addWidget(auto_button)
     auto_layout.addWidget(autoprm_button)
     auto_layout.addWidget(xrange_button)
     self.button_list += [auto_button, autoprm_button, xrange_button]
     return create_groupbox(self, _("Automatic fit"), layout=auto_layout)
Exemple #48
0
def about(html=True, copyright_only=False):
    """Return text about this package"""
    import sys, os, os.path as osp, platform, guidata, guiqwt, qwt
    from guiqwt.config import _
    from guidata.qt.QtCore import QT_VERSION_STR, PYQT_VERSION_STR
    name = __file__.split(osp.sep)[-2]
    tf1 = (name, __version__, __description__)
    tf2 = (platform.python_version(),
           '64 bits' if sys.maxsize > 2**32 else '32 bits',
           QT_VERSION_STR, PYQT_VERSION_STR,
           qwt.__version__, guidata.__version__, guiqwt.__version__,
           _("on"), platform.system())
    if html:
        short_desc = "This widget is powered by <b>%s</b> v%s"\
                     "<p>%s<p>Created by Pierre Raybaut" % tf1
        desc = "Copyright &copy; 2010-2016 CEA"\
               "<p>Python %s %s, Qt %s, PyQt %s, "\
               "PythonQwt %s, guidata %s, guiqwt %s %s %s" % tf2
        if not copyright_only:
            desc = short_desc + "<br>" + desc
    else:
        short_desc = """%s v%s : %s
Created by Pierre Raybaut""" % tf1
        desc = """Copyright (c) 2010-2016 CEA
Python %s %s, Qt %s, PyQt %s, PythonQwt %s, guidata %s, guiqwt %s %s %s""" % tf2
        if not copyright_only:
            desc = short_desc + os.linesep + desc
    return desc
Exemple #49
0
 def __init__(self, parent=None):
     super(CrossSectionPlot, self).__init__(parent=parent, title="",
                                            section="cross_section")
     self.perimage_mode = True
     self.autoscale_mode = True
     self.autorefresh_mode = True
     self.apply_lut = False
     self.single_source = False
     
     self.last_obj = None
     self.known_items = {}
     self._shapes = {}
     
     self.curveparam = CurveParam(_("Curve"), icon="curve.png")
     self.set_curve_style("cross_section", "curve")
     
     if self._height is not None:
         self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum)
     elif self._width is not None:
         self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding)
         
     self.label = make.label(self.LABEL_TEXT, "C", (0, 0), "C")
     self.label.set_readonly(True)
     self.add_item(self.label)
     
     self.setAxisMaxMajor(self.Z_AXIS, self.Z_MAX_MAJOR)
     self.setAxisMaxMinor(self.Z_AXIS, 0)
Exemple #50
0
    def histogram2D(self, X, Y, NX=None, NY=None, logscale=None,
                    title=None, transparent=None, Z=None,
                    computation=-1,interpolation=0):
        """
        Make a 2D Histogram `plot item` 
        (:py:class:`guiqwt.image.Histogram2DItem` object)

            * X: data (1D array)
            * Y: data (1D array)
            * NX: Number of bins along x-axis (int)
            * NY: Number of bins along y-axis (int)
            * logscale: Z-axis scale (bool)
            * title: item title (string)
            * transparent: enable transparency (bool)
        """
        basename = _("2D Histogram")
        param = Histogram2DParam(title=basename, icon='histogram2d.png')
        if NX is not None:
            param.nx_bins = NX
        if NY is not None:
            param.ny_bins = NY
        if logscale is not None:
            param.logscale = int(logscale)
        if title is not None:
            param.label = title
        else:
            global HISTOGRAM2D_COUNT
            HISTOGRAM2D_COUNT += 1
            param.label = make_title(basename, HISTOGRAM2D_COUNT)
        if transparent is not None:
            param.transparent = transparent
        param.computation = computation
        param.interpolation = interpolation
        return Histogram2DItem(X, Y, param, Z=Z)
Exemple #51
0
    def legend(self, anchor='TR', c=None, restrict_items=None):
        """
        Make a legend `plot item` 
        (:py:class:`guiqwt.label.LegendBoxItem` or 
        :py:class:`guiqwt.label.SelectedLegendBoxItem` object)

            * anchor: legend position in relative position (string)
            * c (optional): position in canvas coordinates (tuple)
            * restrict_items (optional):
                - None: all items are shown in legend box
                - []: no item shown
                - [item1, item2]: item1, item2 are shown in legend box
        """
        param = LegendParam(_("Legend"), icon='legend.png')
        param.read_config(CONF, "plot", "legend")
        param.abspos = True
        param.absg = anchor
        param.anchor = anchor
        if c is None:
            c = ANCHOR_OFFSETS[anchor]
        param.xc, param.yc = c
        if restrict_items is None:
            return LegendBoxItem(param)
        else:
            return SelectedLegendBoxItem(param, restrict_items)
Exemple #52
0
 def __init__(self, parent):
     QSplitter.__init__(self, parent)
     # self.lineList = QListWidget(self)
     # self.addWidget(self.lineList)
     self.properties = DataSetEditGroupBox(_("Properties"), DAQParam)
     self.properties.setEnabled(True)
     self.addWidget(self.properties)
Exemple #53
0
    def __init__(self, wintitle="guiqwt plot", icon="guiqwt.svg",
                 toolbar=False, options=None, panels=None, param_cols=1,
                 legend_anchor='TR', auto_fit=True):
        if wintitle is None:
            wintitle = _('Curve fitting')

        self.x = None
        self.y = None
        self.fitfunc = None
        self.fitargs = None
        self.fitkwargs = None
        self.fitparams = None
        self.autofit_prm = None
        
        self.data_curve = None
        self.fit_curve = None
        self.legend = None
        self.legend_anchor = legend_anchor
        self.xrange = None
        self.show_xrange = False
        
        self.param_cols = param_cols
        self.auto_fit_enabled = auto_fit      
        self.button_list = [] # list of buttons to be disabled at startup

        self.fit_layout = None
        self.params_layout = None
        
        CurveWidgetMixin.__init__(self, wintitle=wintitle, icon=icon, 
                                  toolbar=toolbar, options=options,
                                  panels=panels)
        
        self.refresh()
Exemple #54
0
    def open(self, filename=None, *args):
        if filename is None or isinstance(filename, (int, bool)):
                            # catch Qt signal-slot connection which may
                            # sends boolean from QAction signal
            filename = QFileDialog.getOpenFileNames(None,
                                                    _('Open file'), '.')
            if filename is None:
                return
            else:
                filename = [unicode(fname) for fname in filename]
                self.open(filename)
                return
        elif not isinstance(filename, (list,tuple)):
            filename = [filename,]

        if len(args) != 0:
            filename.extend(args)

        for fname in filename:
            if re.match('.*flat$', fname):
                self.ffp.open(fname)
                measurements = self.ffp.get_measurements()
            elif re.match('.*\.sxm$', fname):
                self.nfp.open(fname)
                measurements = self.nfp.get_measurements()
            else:
                measurements = []
                print "Unknown file type"
                
            for i in range(len(measurements)):
                self.register_measurement(measurements.pop())
Exemple #55
0
    def __init__(self, wintitle="guiqwt plot", icon="guiqwt.png",
                 toolbar=False, options=None, parent=None, panels=None):
        QDialog.__init__(self, parent)
        self.setWindowFlags(Qt.Window)

        # WidgetMixin copy
        PlotManager.__init__(self, main=self)
        
        self.main_layout = QVBoxLayout(self)
        self.color_layout = QHBoxLayout()
        self.plot_layout = QGridLayout()
        self.option_layout = QHBoxLayout()

        self.plot_widget = None

        if panels is not None:
            for panel in panels:
                self.add_panel(panel)

        self.toolbar = QToolBar(_("Tools"))
        if not toolbar:
            self.toolbar.hide()

        # Configuring widget layout
        self._setup_widget_properties(wintitle=wintitle, icon=icon)
        self._setup_widget_layout()
        
        # Options
        self.option_callbacks = {}
        self.legend = None
Exemple #56
0
    def xyimage(self, x, y, data, title=None, alpha_mask=None, alpha=None,
                background_color=None, colormap=None,
                interpolation='linear', eliminate_outliers=None,
                xformat='%.1f', yformat='%.1f', zformat='%.1f'):
        """
        Make an xyimage `plot item` (image with non-linear X/Y axes) from data
        (:py:class:`guiqwt.image.XYImageItem` object)

            * x: 1D NumPy array (or tuple, list: will be converted to array)
            * y: 1D NumPy array (or tuple, list: will be converted to array
            * data: 2D NumPy array (image pixel data)
            * title: image title (optional)
            * interpolation: 'nearest', 'linear' (default), 'antialiasing' (5x5)
        """
        param = XYImageParam(title=_("Image"), icon='image.png')
        self.__set_image_param(param, title, alpha_mask, alpha, interpolation,
                               background=background_color, colormap=colormap,
                               xformat=xformat, yformat=yformat,
                               zformat=zformat)
        if isinstance(x, (list, tuple)):
            x = array(x)
        if isinstance(y, (list, tuple)):
            y = array(y)
        image = XYImageItem(x, y, data, param)
        if eliminate_outliers is not None:
            image.set_lut_range(lut_range_threshold(image, 256,
                                                    eliminate_outliers))
        return image
Exemple #57
0
 def __init__(self, parent):
     QSplitter.__init__(self, parent)
     self.imagelist = QListWidget(self)
     self.addWidget(self.imagelist)
     self.properties = DataSetEditGroupBox(_("Properties"), ImageParam)
     self.properties.setEnabled(False)
     self.addWidget(self.properties)
Exemple #58
0
    def __init__(self, wintitle):
        super(Window, self).__init__()
        self.default_tool = None
        self.plots = []
        self.itemlist = PlotItemList(None)
        self.contrast = ContrastAdjustment(None)
        self.xcsw = XCrossSection(None)
        self.ycsw = YCrossSection(None)
        
        self.manager = PlotManager(self)
        self.toolbar = QToolBar(_("Tools"), self)
        self.manager.add_toolbar(self.toolbar, "default")
        self.toolbar.setMovable(True)
        self.toolbar.setFloatable(True)
        self.addToolBar(Qt.TopToolBarArea, self.toolbar)

        frame = QFrame(self)
        self.setCentralWidget(frame)
        self.layout = QGridLayout()
        layout = QVBoxLayout(frame)
        frame.setLayout(layout)
        layout.addLayout(self.layout)
        self.frame = frame

        self.setWindowTitle(wintitle)
        self.setWindowIcon(get_icon('guiqwt.svg'))
Exemple #59
0
    def __init__(self, wintitle="guiqwt plot", icon="guiqwt.svg",
                 toolbar=False, options=None, panels=None):
        PlotManager.__init__(self, main=self)

        self.plot_layout = QGridLayout()
        
        if options is None:
            options = {}
        self.plot_widget = None
        self.create_plot(options)
        
        if panels is not None:
            for panel in panels:
                self.add_panel(panel)
        
        self.toolbar = QToolBar(_("Tools"))
        if not toolbar:
            self.toolbar.hide()

        # Configuring widget layout
        self.setup_widget_properties(wintitle=wintitle, icon=icon)
        self.setup_widget_layout()
        
        # Configuring plot manager
        self.add_toolbar(self.toolbar, "default")
        self.register_tools()