Esempio n. 1
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
Esempio n. 2
0
 def select_file(self):
     """Open a file selection dialog box"""
     fname = self.item.from_string(to_text_string(self.edit.text()))
     if isinstance(fname, list):
         fname = osp.dirname(fname[0])
     parent = self.parent_layout.parent
     _temp = sys.stdout
     sys.stdout = None
     if len(fname) == 0:
         fname = self.basedir
     _formats = self.item.get_prop_value("data", "formats")
     formats = [to_text_string(format).lower() for format in _formats]
     filter_lines = [(_("%s files") + " (*.%s)") % (format.upper(), format)
                     for format in formats]
     all_filter = _("All supported files") + " (*.%s)" % " *.".join(formats)
     if len(formats) > 1:
         if self.all_files_first:
             filter_lines.insert(0, all_filter)
         else:
             filter_lines.append(all_filter)
     if fname is None:
         fname = ""
     child_title = _get_child_title_func(parent)
     fname, _filter = self.filedialog(parent, child_title(self.item), fname,
                                      "\n".join(filter_lines))
     sys.stdout = _temp
     if fname:
         if isinstance(fname, list):
             fname = to_text_string(fname)
         self.edit.setText(fname)
Esempio n. 3
0
def exec_images_open_dialog(parent,
                            basedir='',
                            app_name=None,
                            to_grayscale=True,
                            dtype=None):
    """
    Executes an image*s* open dialog box (QFileDialog.getOpenFileNames)
        * 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
    
    Yields (filename, data) tuples if dialog is accepted, None otherwise
    """
    saved_in, saved_out, saved_err = sys.stdin, sys.stdout, sys.stderr
    sys.stdout = None
    filenames, _filter = getopenfilenames(
        parent, _("Open"), basedir,
        io.iohandler.get_filters('load', dtype=dtype))
    sys.stdin, sys.stdout, sys.stderr = saved_in, saved_out, saved_err
    filenames = [to_text_string(fname) for fname in list(filenames)]
    for filename in filenames:
        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
        yield filename, data
Esempio n. 4
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')
Esempio n. 5
0
def exec_images_open_dialog(parent, basedir='', app_name=None,
                            to_grayscale=True, dtype=None):
    """
    Executes an image*s* open dialog box (QFileDialog.getOpenFileNames)
        * 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
    
    Yields (filename, data) tuples if dialog is accepted, None otherwise
    """
    saved_in, saved_out, saved_err = sys.stdin, sys.stdout, sys.stderr
    sys.stdout = None
    filenames, _filter = getopenfilenames(parent, _("Open"), basedir,
                                io.iohandler.get_filters('load', dtype=dtype))
    sys.stdin, sys.stdout, sys.stderr = saved_in, saved_out, saved_err
    filenames = [to_text_string(fname) for fname in list(filenames)]
    for filename in filenames:
        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
        yield filename, data
Esempio n. 6
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()) )
Esempio n. 7
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)
Esempio n. 8
0
 def select_file(self):
     """Open a file selection dialog box"""
     fname = self.item.from_string(to_text_string(self.edit.text()))
     if isinstance(fname, list):
         fname = osp.dirname(fname[0])
     parent = self.parent_layout.parent
     _temp = sys.stdout
     sys.stdout = None
     if len(fname) == 0:
         fname = self.basedir
     _formats = self.item.get_prop_value("data", "formats")
     formats = [to_text_string(format).lower() for format in _formats]
     filter_lines = [(_("%s files")+" (*.%s)") % (format.upper(), format)
                     for format in formats]
     all_filter = _("All supported files")+" (*.%s)" % " *.".join(formats)
     if len(formats) > 1:
         if self.all_files_first:
             filter_lines.insert(0, all_filter)
         else:
             filter_lines.append(all_filter)
     if fname is None:
         fname = ""
     child_title = _get_child_title_func(parent)
     fname, _filter = self.filedialog(parent, child_title(self.item), fname,
                                      "\n".join(filter_lines))
     sys.stdout = _temp
     if fname:
         if isinstance(fname, list):
             fname = to_text_string(fname)
         self.edit.setText(fname)
Esempio n. 9
0
 def __init__(self, item, parent_layout):
     super(FloatArrayWidget, self).__init__(item, parent_layout)
     _label = item.get_prop_value("display", "label")
     self.groupbox = self.group = QGroupBox(_label)
     self.layout = QGridLayout()
     self.layout.setAlignment(Qt.AlignLeft)
     self.groupbox.setLayout(self.layout)
     
     self.first_line, self.dim_label = get_image_layout("shape.png",
                                _("Number of rows x Number of columns"))
     edit_button = QPushButton(get_icon("arredit.png"), "")
     edit_button.setToolTip(_("Edit array contents"))
     edit_button.setMaximumWidth(32)
     self.first_line.addWidget(edit_button)
     self.layout.addLayout(self.first_line, 0, 0)
     
     self.min_line, self.min_label = get_image_layout("min.png",
                                              _("Smallest element in array"))
     self.layout.addLayout(self.min_line, 1, 0)
     self.max_line, self.max_label = get_image_layout("max.png",
                                              _("Largest element in array"))
     self.layout.addLayout(self.max_line, 2, 0)
     
     edit_button.clicked.connect(self.edit_array)
     self.arr = None # le tableau si il a été modifié
     self.instance = None
Esempio n. 10
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(),
                         ])
Esempio n. 11
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')
Esempio n. 12
0
    def __init__(self, item, parent_layout):
        super(FloatArrayWidget, self).__init__(item, parent_layout)
        _label = item.get_prop_value("display", "label")
        self.groupbox = self.group = QGroupBox(_label)
        self.layout = QGridLayout()
        self.layout.setAlignment(Qt.AlignLeft)
        self.groupbox.setLayout(self.layout)

        self.first_line, self.dim_label = get_image_layout(
            "shape.png", _("Number of rows x Number of columns"))
        edit_button = QPushButton(get_icon("arredit.png"), "")
        edit_button.setToolTip(_("Edit array contents"))
        edit_button.setMaximumWidth(32)
        self.first_line.addWidget(edit_button)
        self.layout.addLayout(self.first_line, 0, 0)

        self.min_line, self.min_label = get_image_layout(
            "min.png", _("Smallest element in array"))
        self.layout.addLayout(self.min_line, 1, 0)
        self.max_line, self.max_label = get_image_layout(
            "max.png", _("Largest element in array"))
        self.layout.addLayout(self.max_line, 2, 0)

        edit_button.clicked.connect(self.edit_array)
        self.arr = None  # le tableau si il a été modifié
        self.instance = None
Esempio n. 13
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())
Esempio n. 14
0
 def get_auto_help(self, instance):
     """Override DataItem method"""
     auto_help = super(IntItem, self).get_auto_help(instance)
     even = self.get_prop_value("data", instance, "even")
     if even is not None:
         if even:
             auto_help += ", " + _("even")
         else:
             auto_help += ", " + _("odd")
     return auto_help
Esempio n. 15
0
 def test_changeconfig(self):
     obj = QPen(Qt.red, 2, Qt.SolidLine)
     ls = LineStyleParam(_("Line style"))
     ls.update_param(obj)
     ls.write_config(CONF, "ls", "")
     ls = LineStyleParam(_("Line style"))
     ls.read_config(CONF, "ls", "")
     self.assertEqual(ls.width, 2)
     self.assertEqual(ls.style, "SolidLine")
     self.assertEqual(ls.color, "#ff0000")
Esempio n. 16
0
 def test_changeconfig(self):
     obj = QPen( Qt.red, 2, Qt.SolidLine )
     ls = LineStyleParam(_("Line style"))
     ls.update_param( obj )
     ls.write_config(CONF, "ls", "" )
     ls = LineStyleParam(_("Line style"))
     ls.read_config(CONF, "ls", "" )
     self.assertEqual(ls.width, 2)
     self.assertEqual(ls.style, "SolidLine")
     self.assertEqual(ls.color, "#ff0000")
Esempio n. 17
0
 def get_auto_help(self, instance):
     """Override DataItem method"""
     auto_help = super(IntItem, self).get_auto_help(instance)
     even = self.get_prop_value("data", instance, "even")
     if even is not None:
         if even:
             auto_help += ", "+_("even")
         else:
             auto_help += ", "+_("odd")
     return auto_help
Esempio n. 18
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()
Esempio n. 19
0
 def check(self):
     is_ok = True
     for edl in self.edit_layout:
         if not edl.check_all_values():
             is_ok = False
     if not is_ok:
         QMessageBox.warning(self, self.instance.get_title(),
                     _("Some required entries are incorrect")+"\n"+\
                     _("Please check highlighted fields."))
         return False
     return True
Esempio n. 20
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)
Esempio n. 21
0
 def check(self):
     is_ok = True
     for edl in self.edit_layout:
         if not edl.check_all_values():
             is_ok = False
     if not is_ok:
         QMessageBox.warning(self, self.instance.get_title(),
                     _("Some required entries are incorrect")+"\n"+\
                     _("Please check highlighted fields."))
         return False
     return True
Esempio n. 22
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()
Esempio n. 23
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)
Esempio n. 24
0
class FitParamDataSet(DataSet):
    name = StringItem(_("Name"))
    value = FloatItem(_("Value"), default=0.0)
    min = FloatItem(_("Min"), default=-1.0)
    max = FloatItem(_("Max"), default=1.0).set_pos(col=1)
    steps = IntItem(_("Steps"), default=5000)
    format = StringItem(_("Format"), default="%.3f").set_pos(col=1)
    logscale = BoolItem(_("Logarithmic"), _("Scale"))
    unit = StringItem(_("Unit"), default="").set_pos(col=1)
Esempio n. 25
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])
Esempio n. 26
0
 def test_changeconfig(self):
     obj = QwtSymbol(QwtSymbol.Rect, QBrush(Qt.black), QPen(Qt.yellow),
                     QSize(3, 3))
     sym = SymbolParam(_("Symbol"))
     sym.update_param(obj)
     sym.write_config(CONF, "sym", "")
     sym = SymbolParam(_("Symbol"))
     sym.read_config(CONF, "sym", "")
     self.assertEqual(sym.marker, "Rect")
     self.assertEqual(sym.size, 3)
     self.assertEqual(sym.edgecolor, "#ffff00")
     self.assertEqual(sym.facecolor, "#000000")
     sym.build_symbol()
Esempio n. 27
0
 def test_changeconfig(self):
     obj = QwtSymbol( QwtSymbol.Rect, QBrush(Qt.black), QPen(Qt.yellow),
                      QSize(3, 3) )
     sym = SymbolParam(_("Symbol"))
     sym.update_param( obj )
     sym.write_config(CONF, "sym", "" )
     sym = SymbolParam(_("Symbol"))
     sym.read_config(CONF, "sym", "" )
     self.assertEqual(sym.marker, "Rect")
     self.assertEqual(sym.size, 3)
     self.assertEqual(sym.edgecolor, "#ffff00")
     self.assertEqual(sym.facecolor, "#000000")
     sym.build_symbol()
Esempio n. 28
0
class AutoFitParam(DataSet):
    xmin = FloatItem("xmin")
    xmax = FloatItem("xmax")
    method = ChoiceItem(_("Method"), [
        ("simplex", "Simplex"),
        ("powel", "Powel"),
        ("bfgs", "BFGS"),
        ("l_bfgs_b", "L-BFGS-B"),
        ("cg", _("Conjugate Gradient")),
        ("lq", _("Least squares")),
    ],
                        default="lq")
    err_norm = StringItem("enorm",
                          default=2.0,
                          help=_("for simplex, powel, cg and bfgs norm used "
                                 "by the error function"))
    xtol = FloatItem("xtol",
                     default=0.0001,
                     help=_("for simplex, powel, least squares"))
    ftol = FloatItem("ftol",
                     default=0.0001,
                     help=_("for simplex, powel, least squares"))
    gtol = FloatItem("gtol", default=0.0001, help=_("for cg, bfgs"))
    norm = StringItem("norm",
                      default="inf",
                      help=_("for cg, bfgs. inf is max, -inf is min"))
Esempio n. 29
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)        
Esempio n. 30
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])
Esempio n. 31
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)
Esempio n. 32
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)
Esempio n. 33
0
    def refresh(self, slider_value=None):
        """Refresh Fit Tool dialog box"""
        # Update button states
        enable = self.x is not None and self.y is not None \
                 and self.x.size > 0 and self.y.size > 0 \
                 and self.fitfunc is not None and self.fitparams is not None \
                 and len(self.fitparams) > 0
        for btn in self.button_list:
            btn.setEnabled(enable)

        if not enable:
            # Fit widget is not yet configured
            return

        fitargs, fitkwargs = self.get_fitfunc_arguments()
        yfit = self.fitfunc(self.x, [p.value for p in self.fitparams],
                            *fitargs, **fitkwargs)

        plot = self.get_plot()

        if self.legend is None:
            self.legend = make.legend(anchor=self.legend_anchor)
            plot.add_item(self.legend)

        if self.xrange is None:
            self.xrange = make.range(0., 1.)
            plot.add_item(self.xrange)
        self.xrange.set_range(self.autofit_prm.xmin, self.autofit_prm.xmax)
        self.xrange.setVisible(self.show_xrange)

        if self.data_curve is None:
            self.data_curve = make.curve([], [],
                                         _("Data"),
                                         color="b",
                                         linewidth=2)
            plot.add_item(self.data_curve)
        self.data_curve.set_data(self.x, self.y)

        if self.fit_curve is None:
            self.fit_curve = make.curve([], [],
                                        _("Fit"),
                                        color="r",
                                        linewidth=2)
            plot.add_item(self.fit_curve)
        self.fit_curve.set_data(self.x, yfit)

        plot.replot()
        plot.disable_autoscale()
Esempio n. 34
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('plotpy.svg'))
Esempio n. 35
0
    def __init__(self, package, parent=None):
        QSplitter.__init__(self, parent)
        self.setWindowTitle(_("Tests - %s module") % package.__name__)
        self.setWindowIcon(get_icon("%s.svg" % package.__name__, "plotpy.svg"))

        test_package_name = '%s.tests' % package.__name__
        _temp = __import__(test_package_name)
        test_package = sys.modules[test_package_name]

        tests = get_tests(test_package)
        listwidget = QListWidget(self)
        listwidget.addItems([osp.basename(test.filename) for test in tests])

        self.properties = TestPropertiesWidget(self)

        self.addWidget(listwidget)
        self.addWidget(self.properties)

        self.properties.run_button.clicked.connect(
            lambda: tests[listwidget.currentRow()].run())
        self.properties.quit_button.clicked.connect(self.close)
        listwidget.currentRowChanged.connect(
            lambda row: self.properties.set_item(tests[row]))
        listwidget.itemActivated.connect(
            lambda: tests[listwidget.currentRow()].run())
        listwidget.setCurrentRow(0)

        QShortcut(QKeySequence("Escape"), self, self.close)

        self.setSizes([200, 1])
        self.setStretchFactor(1, 1)
        self.resize(QSize(1000, 600))
        self.properties.set_item(tests[0])
Esempio n. 36
0
 def set_data(self,
              x,
              y,
              fitfunc=None,
              fitparams=None,
              fitargs=None,
              fitkwargs=None):
     if self.fitparams is not None and fitparams is not None:
         self.clear_params_layout()
     self.x = x
     self.y = y
     if fitfunc is not None:
         self.fitfunc = fitfunc
     if fitparams is not None:
         self.fitparams = fitparams
     if fitargs is not None:
         self.fitargs = fitargs
     if fitkwargs is not None:
         self.fitkwargs = fitkwargs
     self.autofit_prm = AutoFitParam(title=_("Automatic fitting options"))
     self.autofit_prm.xmin = x.min()
     self.autofit_prm.xmax = x.max()
     self.compute_imin_imax()
     if self.fitparams is not None and fitparams is not None:
         self.populate_params_layout()
     self.refresh()
Esempio n. 37
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)
Esempio n. 38
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('plotpy.svg'))
Esempio n. 39
0
 def __init__(self,
              name,
              value,
              min,
              max,
              logscale=False,
              steps=5000,
              format='%.3f',
              size_offset=0,
              unit=''):
     self.name = name
     self.value = value
     self.min = min
     self.max = max
     self.logscale = logscale
     self.steps = steps
     self.format = format
     self.unit = unit
     self.prefix_label = None
     self.lineedit = None
     self.unit_label = None
     self.slider = None
     self.button = None
     self._widgets = []
     self._size_offset = size_offset
     self._refresh_callback = None
     self.dataset = FitParamDataSet(title=_("Curve fitting parameter"))
Esempio n. 40
0
 def test_update(self):
     obj = QPen( Qt.red, 2, Qt.SolidLine )
     ls = LineStyleParam(_("Line style"))
     ls.update_param( obj )
     self.assertEqual(ls.width, 2)
     self.assertEqual(ls.style, "SolidLine")
     self.assertEqual(ls.color, "#ff0000")
Esempio n. 41
0
def about(html=True, copyright_only=False):
    """Return text about this package"""
    import sys, os, os.path as osp, platform, plotpy
    from plotpy.config import _
    from plotpy.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, plotpy.__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, plotpy %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, plotpy %s %s %s""" % tf2
        if not copyright_only:
            desc = short_desc + os.linesep + desc
    return desc
Esempio n. 42
0
 def __init__(self, parent=None):
     super(CrossSectionPlot, self).__init__(parent=parent, title="",
                                            section="cross_section")
     self.perimage_mode = True
     self.autoscale_mode = False
     self.autorefresh_mode = True
     self.apply_lut = False
     self.single_source = False
     self.lockscales = True
     
     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)
Esempio n. 43
0
def about(html=True, copyright_only=False):
    """Return text about this package"""
    import sys, os, os.path as osp, platform, plotpy
    from plotpy.config import _
    from plotpy.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, plotpy.__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, plotpy %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, plotpy %s %s %s""" % tf2
        if not copyright_only:
            desc = short_desc + os.linesep + desc
    return desc
Esempio n. 44
0
    def __init__(self, wintitle="plotpy plot", icon="plotpy.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()
Esempio n. 45
0
 def __init__(self, package, parent=None):
     QSplitter.__init__(self, parent)
     self.setWindowTitle(_("Tests - %s module") % package.__name__)
     self.setWindowIcon(get_icon("%s.svg" % package.__name__, "plotpy.svg"))
     
     test_package_name = '%s.tests' % package.__name__
     _temp = __import__(test_package_name)
     test_package = sys.modules[test_package_name]
     
     tests = get_tests(test_package)
     listwidget = QListWidget(self)
     listwidget.addItems([osp.basename(test.filename) for test in tests])
     
     self.properties = TestPropertiesWidget(self)
     
     self.addWidget(listwidget)
     self.addWidget(self.properties)
     
     self.properties.run_button.clicked.connect(
                             lambda: tests[listwidget.currentRow()].run())
     self.properties.quit_button.clicked.connect(self.close)
     listwidget.currentRowChanged.connect(
                         lambda row: self.properties.set_item(tests[row]))
     listwidget.itemActivated.connect(
                         lambda: tests[listwidget.currentRow()].run())
     listwidget.setCurrentRow(0)
     
     QShortcut(QKeySequence("Escape"), self, self.close)
         
     self.setSizes([200, 1])
     self.setStretchFactor(1, 1)
     self.resize(QSize(1000, 600))
     self.properties.set_item(tests[0])
Esempio n. 46
0
    def __init__(self, wintitle="plotpy plot", icon="plotpy.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()
Esempio n. 47
0
    def __init__(self,
                 wintitle="plotpy plot",
                 icon="plotpy.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()
Esempio n. 48
0
 def test_update(self):
     obj = QPen(Qt.red, 2, Qt.SolidLine)
     ls = LineStyleParam(_("Line style"))
     ls.update_param(obj)
     self.assertEqual(ls.width, 2)
     self.assertEqual(ls.style, "SolidLine")
     self.assertEqual(ls.color, "#ff0000")
Esempio n. 49
0
 def __init__(self,
              label,
              klass,
              button_text=None,
              button_icon=None,
              show_button=True,
              wordwrap=False,
              **kwargs):
     DataSetShowGroupBox.__init__(self,
                                  label,
                                  klass,
                                  wordwrap=wordwrap,
                                  **kwargs)
     if show_button:
         if button_text is None:
             button_text = _("Apply")
         if button_icon is None:
             button_icon = get_icon("apply.png")
         elif is_text_string(button_icon):
             button_icon = get_icon(button_icon)
         apply_btn = QPushButton(button_icon, button_text, self)
         apply_btn.clicked.connect(self.set)
         layout = self.edit.layout
         layout.addWidget(apply_btn, layout.rowCount(), 0, 1, -1,
                          Qt.AlignRight)
Esempio n. 50
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 plotpy 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)
Esempio n. 51
0
 def deserialize(self, reader):
     """Deserialize object from HDF5 reader"""
     self.annotationparam = AnnotationParam(_("Annotation"),
                                            icon="annotation.png")
     reader.read('annotationparam', instance=self.annotationparam)
     self.annotationparam.update_annotation(self)
     self.shape.deserialize(reader)
     self.label.deserialize(reader)
Esempio n. 52
0
 def __init__(self, parent):
     QWidget.__init__(self, parent)
     font = QFont(get_family(MONOSPACE), 10, QFont.Normal)
     
     info_icon = QLabel()
     icon = get_std_icon('MessageBoxInformation').pixmap(24, 24)
     info_icon.setPixmap(icon)
     info_icon.setFixedWidth(32)
     info_icon.setAlignment(Qt.AlignTop)
     self.desc_label = QLabel()
     self.desc_label.setWordWrap(True)
     self.desc_label.setAlignment(Qt.AlignTop)
     self.desc_label.setFont(font)
     group_desc = QGroupBox(_("Description"), self)
     layout = QHBoxLayout()
     layout.addWidget(info_icon)
     layout.addWidget(self.desc_label)
     group_desc.setLayout(layout)
     
     if CodeEditor is None:
         self.editor = QTextEdit(self)
         self.editor.setFont(font)
     else:
         self.editor = CodeEditor(self)
         self.editor.setup_editor(linenumbers=True, font=font)
         self.editor.set_color_scheme("Spyder")
     self.editor.setReadOnly(True)
     group_code = QGroupBox(_("Source code"), self)
     layout = QVBoxLayout()
     layout.addWidget(self.editor)
     group_code.setLayout(layout)
     
     self.run_button = QPushButton(get_icon("apply.png"),
                                   _("Run this script"), self)
     self.quit_button = QPushButton(get_icon("exit.png"), _("Quit"), self)
     hlayout = QHBoxLayout()
     hlayout.addWidget(self.run_button)
     hlayout.addStretch()
     hlayout.addWidget(self.quit_button)
     
     vlayout = QVBoxLayout()
     vlayout.addWidget(group_desc)
     vlayout.addWidget(group_code)
     vlayout.addLayout(hlayout)
     self.setLayout(vlayout)
Esempio n. 53
0
 def add_buttons_to_layout(self, layout):
     """Add tool buttons to layout"""
     # Show crop rectangle checkbox
     show_crop = QCheckBox(_("Show cropping rectangle"), self)
     show_crop.setChecked(True)
     show_crop.toggled.connect(self.show_crop_rect)
     layout.addWidget(show_crop)
     layout.addSpacing(15)
     base.BaseTransformMixin.add_buttons_to_layout(self, layout)
Esempio n. 54
0
 def test_update(self):
     obj = QwtSymbol( QwtSymbol.Rect, QBrush(Qt.black), QPen(Qt.yellow),
                      QSize(3, 3) )
     sym = SymbolParam(_("Symbol"))
     sym.update_param( obj )
     self.assertEqual(sym.marker, "Rect")
     self.assertEqual(sym.size, 3)
     self.assertEqual(sym.edgecolor, "#ffff00")
     self.assertEqual(sym.facecolor, "#000000")
Esempio n. 55
0
 def __init__(self, curveparam=None, histparam=None):
     self.hist_count = None
     self.hist_bins = None
     self.bins = None
     self.old_bins = None
     self.source = None
     self.logscale = None
     self.old_logscale = None
     if curveparam is None:
         curveparam = CurveParam(_("Curve"), icon='curve.png')
         curveparam.curvestyle = "Steps"
     if histparam is None:
         self.histparam = HistogramParam(title=_("Histogram"),
                                         icon='histogram.png')
     else:
         self.histparam = histparam
     CurveItem.__init__(self, curveparam)
     self.setCurveAttribute(QwtPlotCurve.Inverted)
Esempio n. 56
0
 def __init__(self, item, parent_layout):
     super(TextEditWidget, self).__init__(item, parent_layout)
     self.edit = self.group = QTextEdit()
     self.edit.setToolTip(item.get_help())
     if hasattr(item, "min_equals_max") and item.min_equals_max():
         if item.check_item():
             self.edit.setEnabled(False)
         self.edit.setToolTip(_("Value is forced to %d") % item.get_max())
     self.edit.textChanged.connect(self.text_changed)
Esempio n. 57
0
 def get_description(self):
     doc = self.module.__doc__
     if doc is None or not doc.strip():
         return _("No description available")
     else:
         lines = doc.strip().splitlines()
         format = '<span style=\'color: #2222FF\'><b>%s</b></span>'
         lines[0] = format % lines[0]
         return '<br>'.join(lines)