示例#1
0
class SubplotWidget(QSplitter):
    """Construct a Widget that helps managing several plots
    together handled by the same manager

    Since the plots must be added to the manager before the panels
    the add_itemlist method can be called after having declared
    all the subplots
    """
    def __init__(self, manager, parent=None, **kwargs):
        super(SubplotWidget, self).__init__(parent, **kwargs)
        self.setOrientation(Qt.Horizontal)
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.manager = manager
        self.plots = []
        self.itemlist = None
        main = QWidget()
        self.plotlayout = QGridLayout()
        main.setLayout(self.plotlayout)
        self.addWidget(main)

    def add_itemlist(self, show_itemlist=False):
        self.itemlist = PlotItemList(self)
        self.itemlist.setVisible(show_itemlist)
        self.addWidget(self.itemlist)
        configure_plot_splitter(self)
        self.manager.add_panel(self.itemlist)

    def add_subplot(self, plot, i=0, j=0, plot_id=None):
        """Add a plot to the grid of plots"""
        self.plotlayout.addWidget(plot, i, j)
        self.plots.append(plot)
        if plot_id is None:
            plot_id = id(plot)
        self.manager.add_plot(plot, plot_id)
示例#2
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'))
示例#3
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()
示例#4
0
 def __init__(self, item, parent_layout):
     super(TabGroupWidget, self).__init__(item, parent_layout)
     self.tabs = QTabWidget()
     items = item.item.group
     self.widgets = []
     for item in items:
         if item.get_prop_value("display", parent_layout.instance,
                                "hide", False):
             continue
         item.set_prop("display", embedded=True)
         widget = parent_layout.build_widget(item)
         frame = QFrame()
         label = widget.item.get_prop_value("display", "label")
         icon = widget.item.get_prop_value("display", "icon", None)
         if icon is not None:
             self.tabs.addTab(frame, get_icon(icon), label)
         else:
             self.tabs.addTab(frame, label)
         layout = QGridLayout()
         layout.setAlignment(Qt.AlignTop)
         frame.setLayout(layout)
         widget.place_on_grid(layout, 0, 0, 1)
         try:
             widget.get()
         except Exception:
             print("Error building item :", item.item._name)
             raise
         self.widgets.append(widget)
示例#5
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
示例#6
0
文件: thoth.py 项目: fbianco/thoth
    def create_slice_dock(self):
        widget = QWidget()
        dock = QDockWidget("Slice", self)
        dock.setAllowedAreas(Qt.TopDockWidgetArea | Qt.BottomDockWidgetArea |
                             Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea)
        self.addDockWidget(Qt.BottomDockWidgetArea, dock)
        layout = QGridLayout(widget)
        self.slice_index_spin_box = QSpinBox()
        index_max = self.map_.measurement.param.axis3.get_length()
        self.slice_index_spin_box.setRange(0, index_max-1 )

        slice_slider = QSlider(Qt.Horizontal)
        slice_slider.setRange(0, index_max-1)
        self.connect(self.slice_index_spin_box, SIGNAL("valueChanged(int)"),
                     self.set_slice_index)
        self.connect(slice_slider, SIGNAL("valueChanged(int)"),
                     self.slice_index_spin_box.setValue)
        self.connect(self.slice_index_spin_box, SIGNAL("valueChanged(int)"),
                     slice_slider.setValue)
        self.slice_value_spin_box = QDoubleSpinBox()
        scale = self.map_.measurement.param.axis3.get_scale()
        self.slice_value_spin_box.setRange(scale.min(),scale.max())
        self.slice_value_spin_box.setValue(scale[0])
        self.connect(self.slice_value_spin_box, SIGNAL("valueChanged(double)"),
                     self.set_slice_value)
        unit = self.map_.measurement.param.axis3.unit
        self.slice_value_spin_box.setSuffix(unit)
        layout.addWidget(slice_slider, 0, 0)
        layout.addWidget(self.slice_index_spin_box, 0, 1)
        layout.addWidget(self.slice_value_spin_box, 0, 2)
        dock.setWidget(widget)
   def __init__(self, name, instanceId, widgetList, dataFunc, inactivityTimeout = True):
      dspWidget.__init__(self, name, instanceId, widgetList, inactivityTimeout = inactivityTimeout)

      self.dataFunc = dataFunc
      self.Fs = 2000
      self.sample_rate = 5333
      self.pascal_constant=2*10**-5

      self.pcm =[]

      self.layout = QGridLayout()
      self.setLayout(self.layout) 
      
      self.pcmPlotW = dspCurveWidget(title="Monitor Mic Data", show_itemlist=False)
      self.layout.addWidget(self.pcmPlotW, 1, 0, 1, 1)

      self.resize(1000, 300)



      self.Button1 = QPushButton("Level")

      self.layout.addWidget(self.Button1, 1,1,1,1)

      self.connect(self.Button1, SIGNAL('clicked()'), self.Button1Pressed)
示例#8
0
文件: plot.py 项目: alimuldal/guiqwt
class SubplotWidget(QSplitter):
    """Construct a Widget that helps managing several plots
    together handled by the same manager

    Since the plots must be added to the manager before the panels
    the add_itemlist method can be called after having declared
    all the subplots
    """
    def __init__(self, manager, parent=None, **kwargs):
        super(SubplotWidget, self).__init__(parent, **kwargs)
        self.setOrientation(Qt.Horizontal)
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.manager = manager
        self.plots = []
        self.itemlist = None
        main = QWidget()
        self.plotlayout = QGridLayout()
        main.setLayout(self.plotlayout)
        self.addWidget(main)

    def add_itemlist(self, show_itemlist=False):
        self.itemlist = PlotItemList(self)
        self.itemlist.setVisible(show_itemlist)
        self.addWidget(self.itemlist)
        configure_plot_splitter(self)
        self.manager.add_panel(self.itemlist)

    def add_subplot(self, plot, i=0, j=0, plot_id=None):
        """Add a plot to the grid of plots"""
        self.plotlayout.addWidget(plot, i, j)
        self.plots.append(plot)
        if plot_id is None:
            plot_id = id(plot)
        self.manager.add_plot(plot, plot_id)
示例#9
0
 def __init__(self, manager, parent=None):
     QSplitter.__init__(self, Qt.Horizontal, parent)
     self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
     self.manager = manager
     self.plots = []
     self.itemlist = None
     main = QWidget()
     self.plotlayout = QGridLayout()
     main.setLayout(self.plotlayout)
     self.addWidget(main)
示例#10
0
 def __init__(self, manager, parent=None, **kwargs):
     super(SubplotWidget, self).__init__(parent, **kwargs)
     self.setOrientation(Qt.Horizontal)
     self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
     self.manager = manager
     self.plots = []
     self.itemlist = None
     main = QWidget()
     self.plotlayout = QGridLayout()
     main.setLayout(self.plotlayout)
     self.addWidget(main)
示例#11
0
 def __init__(self, parent=None):
     QFrame.__init__(self, parent)
     layout = QGridLayout()
     self.setLayout(layout)
     angle = 0
     for row in range(7):
         for column in range(7):
             layout.addWidget(RotatedLabel("Label %03d°" % angle,
                                           angle=angle, color=Qt.blue,
                                           bold=True),
                              row, column, Qt.AlignCenter)
             angle += 10
示例#12
0
 def __init__(self, parent=None):
     QFrame.__init__(self, parent)
     layout = QGridLayout()
     self.setLayout(layout)
     angle = 0
     for row in range(7):
         for column in range(7):
             layout.addWidget(
                 RotatedLabel("Label %03d°" % angle,
                              angle=angle,
                              color=Qt.blue,
                              bold=True), row, column, Qt.AlignCenter)
             angle += 10
    def __init__(self,
                 name,
                 instanceId,
                 widgetList,
                 dataFunc,
                 inactivityTimeout=True):
        dspWidget.__init__(self,
                           name,
                           instanceId,
                           widgetList,
                           inactivityTimeout=inactivityTimeout)

        self.dataFunc = dataFunc

        self.Fs = 2000

        layout = QGridLayout()
        self.setLayout(layout)

        self.resize(1024, 800)

        self.refPlotW = dspCurveWidget(mode="PCM",
                                       title="Reference PCM",
                                       show_itemlist=False)
        layout.addWidget(self.refPlotW, 1, 0, 1, 1)

        self.errPlotW = dspCurveWidget(mode="PCM",
                                       title="Error Mic PCM",
                                       show_itemlist=False)
        layout.addWidget(self.errPlotW, 2, 0, 1, 1)

        self.mscohPlotW = dspCurveWidget(mode="MSCoh",
                                         title="Magnitude Squared Coherence",
                                         show_itemlist=False)
        layout.addWidget(self.mscohPlotW, 3, 0, 1, 2)
示例#14
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'))
示例#15
0
文件: plot.py 项目: alimuldal/guiqwt
    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()
示例#16
0
文件: fit.py 项目: gyenney/Tools
    def setup_widget_layout(self):
        self.fit_layout = QHBoxLayout()
        self.params_layout = QGridLayout()
        params_group = create_groupbox(self,
                                       _("Fit parameters"),
                                       layout=self.params_layout)
        if self.auto_fit_enabled:
            auto_group = self.create_autofit_group()
            self.fit_layout.addWidget(auto_group)
        self.fit_layout.addWidget(params_group)
        self.plot_layout.addLayout(self.fit_layout, 1, 0)

        vlayout = QVBoxLayout(self)
        vlayout.addWidget(self.toolbar)
        vlayout.addLayout(self.plot_layout)
        self.setLayout(vlayout)
示例#17
0
文件: plot.py 项目: alimuldal/guiqwt
 def __init__(self, manager, parent=None, **kwargs):
     super(SubplotWidget, self).__init__(parent, **kwargs)
     self.setOrientation(Qt.Horizontal)
     self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
     self.manager = manager
     self.plots = []
     self.itemlist = None
     main = QWidget()
     self.plotlayout = QGridLayout()
     main.setLayout(self.plotlayout)
     self.addWidget(main)
示例#18
0
 def __init__(self, parent):
     QWidget.__init__(self, parent)
 
     layout = QGridLayout()
     self.setLayout(layout)
     
     self.plot1 = ImagePlot(self)
     layout.addWidget(self.plot1, 0, 0, 1, 1)
     self.plot2 = ImagePlot(self)
     layout.addWidget(self.plot2, 1, 0, 1, 1)
     
     self.contrast = ContrastAdjustment(self)
     layout.addWidget(self.contrast, 2, 0, 1, 2)
     self.itemlist = PlotItemList(self)
     layout.addWidget(self.itemlist, 0, 1, 2, 1)
     
     self.manager = PlotManager(self)
     for plot in (self.plot1, self.plot2):
         self.manager.add_plot(plot)
     for panel in (self.itemlist, self.contrast):
         self.manager.add_panel(panel)
示例#19
0
 def __init__(self, item, parent_layout):
     super(GroupWidget, self).__init__(item, parent_layout)
     embedded = item.get_prop_value("display", "embedded", False)
     if not embedded:
         self.group = QGroupBox(item.get_prop_value("display", "label"))
     else:
         self.group = QFrame()
     self.layout = QGridLayout()
     EditLayoutClass = parent_layout.__class__
     self.edit =  EditLayoutClass(self.group, item.instance,
                                  self.layout, item.item.group) 
     self.group.setLayout(self.layout)
示例#20
0
    def create_slice_dock(self):
        widget = QWidget()
        dock = QDockWidget("Slice", self)
        dock.setAllowedAreas(Qt.TopDockWidgetArea | Qt.BottomDockWidgetArea
                             | Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea)
        self.addDockWidget(Qt.BottomDockWidgetArea, dock)
        layout = QGridLayout(widget)
        self.slice_index_spin_box = QSpinBox()
        index_max = self.map_.measurement.param.axis3.get_length()
        self.slice_index_spin_box.setRange(0, index_max - 1)

        slice_slider = QSlider(Qt.Horizontal)
        slice_slider.setRange(0, index_max - 1)
        self.connect(self.slice_index_spin_box, SIGNAL("valueChanged(int)"),
                     self.set_slice_index)
        self.connect(slice_slider, SIGNAL("valueChanged(int)"),
                     self.slice_index_spin_box.setValue)
        self.connect(self.slice_index_spin_box, SIGNAL("valueChanged(int)"),
                     slice_slider.setValue)
        self.slice_value_spin_box = QDoubleSpinBox()
        scale = self.map_.measurement.param.axis3.get_scale()
        self.slice_value_spin_box.setRange(scale.min(), scale.max())
        self.slice_value_spin_box.setValue(scale[0])
        self.connect(self.slice_value_spin_box, SIGNAL("valueChanged(double)"),
                     self.set_slice_value)
        unit = self.map_.measurement.param.axis3.unit
        self.slice_value_spin_box.setSuffix(unit)
        layout.addWidget(slice_slider, 0, 0)
        layout.addWidget(self.slice_index_spin_box, 0, 1)
        layout.addWidget(self.slice_value_spin_box, 0, 2)
        dock.setWidget(widget)
示例#21
0
 def __init__(self, item, parent_layout):
     super(DataSetWidget, self).__init__(item, parent_layout)
     self.dataset = self.klass()
     # Création du layout contenant les champs d'édition du signal
     embedded = item.get_prop_value("display", "embedded", False)
     if not embedded:
         self.group = QGroupBox(item.get_prop_value("display", "label"))
     else:
         self.group = QFrame()
     self.layout = QGridLayout()
     self.group.setLayout(self.layout)
     EditLayoutClass = parent_layout.__class__
     self.edit = EditLayoutClass(self.parent_layout.parent, self.dataset, self.layout)
示例#22
0
 def __init__(self, label, klass, wordwrap=False, **kwargs):
     QGroupBox.__init__(self, label)
     self.klass = klass
     self.dataset = klass(**kwargs)
     self.layout = QVBoxLayout()
     if self.dataset.get_comment():
         label = QLabel(self.dataset.get_comment())
         label.setWordWrap(wordwrap)
         self.layout.addWidget(label)
     self.grid_layout = QGridLayout()
     self.layout.addLayout(self.grid_layout)
     self.setLayout(self.layout)
     self.edit = self.get_edit_layout()
示例#23
0
 def __init__(self, item, parent_layout):
     super(MultipleChoiceWidget, self).__init__(item, parent_layout)
     self.groupbox = self.group = QGroupBox(item.get_prop_value("display", "label"))
     layout = QGridLayout()
     self.boxes = []
     nx, ny = item.get_prop_value("display", "shape")
     cx, cy = 0, 0
     _choices = item.get_prop_value("data", "choices")
     for _, choice, _img in _choices:
         checkbox = QCheckBox(choice)
         layout.addWidget(checkbox, cx, cy)
         if nx < 0:
             cy += 1
             if cy >= ny:
                 cy = 0
                 cx += 1
         else:
             cx += 1
             if cx >= nx:
                 cx = 0
                 cy += 1
         self.boxes.append(checkbox)
     self.groupbox.setLayout(layout)
示例#24
0
 def __init__(self, item, parent_layout):
     super(MultipleChoiceWidget, self).__init__(item, parent_layout)
     self.groupbox = self.group = QGroupBox(item.get_prop_value("display",
                                                                "label"))
     layout = QGridLayout()
     self.boxes = []
     nx, ny = item.get_prop_value("display", "shape")
     cx, cy = 0, 0
     _choices = item.get_prop_value("data", "choices")
     for _, choice, _img in _choices:
         checkbox = QCheckBox(choice)
         layout.addWidget(checkbox, cx, cy)
         if nx < 0:
             cy += 1
             if cy >= ny:
                 cy = 0
                 cx += 1
         else:
             cx += 1
             if cx >= nx:
                 cx = 0
                 cy += 1
         self.boxes.append(checkbox)
     self.groupbox.setLayout(layout)
示例#25
0
文件: fit.py 项目: CaptainAL/Spyder
 def setup_widget_layout(self):
     self.fit_layout = QHBoxLayout()
     self.params_layout = QGridLayout()
     params_group = create_groupbox(self, _("Fit parameters"),
                                    layout=self.params_layout)
     if self.auto_fit_enabled:
         auto_group = self.create_autofit_group()
         self.fit_layout.addWidget(auto_group)
     self.fit_layout.addWidget(params_group)
     self.plot_layout.addLayout(self.fit_layout, 1, 0)
     
     vlayout = QVBoxLayout(self)
     vlayout.addWidget(self.toolbar)
     vlayout.addLayout(self.plot_layout)
     self.setLayout(vlayout)
示例#26
0
文件: manager.py 项目: gyenney/Tools
    def __init__(self, parent):
        QWidget.__init__(self, parent)

        layout = QGridLayout()
        self.setLayout(layout)

        self.plot1 = ImagePlot(self)
        layout.addWidget(self.plot1, 0, 0, 1, 1)
        self.plot2 = ImagePlot(self)
        layout.addWidget(self.plot2, 1, 0, 1, 1)

        self.contrast = ContrastAdjustment(self)
        layout.addWidget(self.contrast, 2, 0, 1, 2)
        self.itemlist = PlotItemList(self)
        layout.addWidget(self.itemlist, 0, 1, 2, 1)

        self.manager = PlotManager(self)
        for plot in (self.plot1, self.plot2):
            self.manager.add_plot(plot)
        for panel in (self.itemlist, self.contrast):
            self.manager.add_panel(panel)
示例#27
0
    def __init__(self, parent=None, x=[], y=[], data=[]):
        QWidget.__init__(self, parent)

        if len(x) < 2:
            x = np.linspace(0, 1392, 1392)
            y = np.linspace(0, 1040, 1040)
            data = np.zeros((1040, 1392))

        self.x = x
        self.y = y
        self.data = data

        layout = QGridLayout(self)
        '''
        self.screen = ImageScreen(self,x,y,data,int(self.sizex*5.0/6.0),int(self.sizey*5.0/6.0))       
        self.cutX = CutScreen(self,sizex=int(self.sizex*5.0/6.0),sizey=int(self.sizey*1.0/6.0))       
        self.cutY = CutScreen(self,sizex=int(self.sizex*1.0/6.0),sizey=int(self.sizey*5.0/6.0))
        '''

        sx = 500
        sy = int(sx / 1.338)
        a = 0.2

        self.screen = ImageScreen(self, x, y, data, sizex=sx, sizey=sy)
        self.cutX = CutScreen(self, sizex=sx, sizey=int(a * sy))
        self.cutY = CutScreen(self, sizex=int(a * sx), sizey=sy)

        layout.addWidget(self.screen, 1, 0)
        layout.addWidget(self.cutX, 0, 0)
        layout.addWidget(self.cutY, 1, 1)

        self.setLayout(layout)

        self.updateGeometry()

        self.manager = PlotManager(self)
        self.manager.add_plot(self.screen.plot)
        self.manager.add_plot(self.cutX.plot)
        self.manager.add_plot(self.cutY.plot)

        roi = RegionSelectTool
        self.tools = [
            tools.SelectTool, tools.RectZoomTool, roi, tools.ColormapTool
        ]
        self.manager.register_all_curve_tools()
示例#28
0
    def setup_instance(self, instance):
        """Override DataSetEditDialog method"""
        from guidata.dataset.datatypes import DataSetGroup
        assert isinstance(instance, DataSetGroup)
        tabs = QTabWidget()
#        tabs.setUsesScrollButtons(False)
        self.layout.addWidget(tabs)
        for dataset in instance.datasets:
            layout = QVBoxLayout()
            layout.setAlignment(Qt.AlignTop)
            if dataset.get_comment():
                label = QLabel(dataset.get_comment())
                label.setWordWrap(self.wordwrap)
                layout.addWidget(label)
            grid = QGridLayout()
            self.edit_layout.append( self.layout_factory(dataset, grid) )
            layout.addLayout(grid)
            page = QWidget()
            page.setLayout(layout)
            if dataset.get_icon():
                tabs.addTab( page, get_icon(dataset.get_icon()),
                             dataset.get_title() )
            else:
                tabs.addTab( page, dataset.get_title() )
示例#29
0
   def __init__(self, name, instanceId, widgetList, dataFunc, inactivityTimeout = True):
      dspWidget.__init__(self, name, instanceId, widgetList, inactivityTimeout = inactivityTimeout)

      self.dataFunc = dataFunc

      self.Fs = 2000

      layout = QGridLayout()
      self.setLayout(layout)

      self.resize(1024, 800)

      self.refPlotW = dspCurveWidget(mode="Freq",title="Reference PCM", show_itemlist=False)
      layout.addWidget(self.refPlotW, 1, 1, 1, 1)
      self.refExitButton = QPushButton("Hide")
      layout.addWidget(self.refExitButton, 1,0,1,1)
      self.connect(self.refExitButton, SIGNAL('clicked()'), self.refExitButtonPressed)

      self.errPlotW = dspCurveWidget(mode="Freq",title="Error Mic PCM", show_itemlist=False)
      layout.addWidget(self.errPlotW, 2, 1, 1, 1)
      self.errExitButton = QPushButton("Hide")
      layout.addWidget(self.errExitButton, 2,0,1,1)
      self.connect(self.errExitButton, SIGNAL('clicked()'), self.errExitButtonPressed)

      self.outPlotW = dspCurveWidget(mode="Freq",title="ANC Output", show_itemlist=False)
      layout.addWidget(self.outPlotW, 3, 1, 1, 1)
      self.outExitButton = QPushButton("Hide")
      layout.addWidget(self.outExitButton, 3,0,1,1)
      self.connect(self.outExitButton, SIGNAL('clicked()'), self.outExitButtonPressed)

      self.coefPlotW = dspCurveWidget(title="ANC Filter", mode="Freq", show_buttons=False, show_itemlist=True)
      self.coefPlotW.customCurve = self.updateFilterCurve
      self.coefPlotW.plotPoints = 1024
      layout.addWidget(self.coefPlotW, 4, 1, 1, 1)
      self.coefExitButton = QPushButton("Hide")
      layout.addWidget(self.coefExitButton, 4,0,1,1)
      self.connect(self.coefExitButton, SIGNAL('clicked()'), self.coefExitButtonPressed)
示例#30
0
class FloatArrayWidget(AbstractDataSetWidget):
    """
    FloatArrayItem widget
    """
    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

    def edit_array(self):
        """Open an array editor dialog"""
        parent = self.parent_layout.parent
        label = self.item.get_prop_value("display", "label")
        try:
            # Spyder 3
            from spyderlib.widgets.variableexplorer import arrayeditor
        except ImportError:
            # Spyder 2
            from spyderlib.widgets import arrayeditor
        editor = arrayeditor.ArrayEditor(parent)
        if editor.setup_and_check(self.arr, title=label):
            if editor.exec_():
                self.update(self.arr)
        
    def get(self):
        """Override AbstractDataSetWidget method"""
        self.arr = numpy.array(self.item.get(), copy=False)
        if self.item.get_prop_value("display", "transpose"):
            self.arr = self.arr.T
        self.update(self.arr)

    def update(self, arr):
        """Override AbstractDataSetWidget method"""
        shape = arr.shape
        if len(shape) == 1:
            shape = (1,) + shape
        dim = " x ".join( [ str(d) for d in shape ])
        self.dim_label.setText(dim)
        
        format = self.item.get_prop_value("display", "format")
        minmax = self.item.get_prop_value("display", "minmax")
        try:
            if minmax == "all":
                mint = format % arr.min()
                maxt = format % arr.max()
            elif minmax == "columns":
                mint = ", ".join([format % arr[r,:].min()
                                  for r in range(arr.shape[0])])
                maxt = ", ".join([format % arr[r,:].max()
                                  for r in range(arr.shape[0])])
            else:
                mint = ", ".join([format % arr[:, r].min()
                                  for r in range(arr.shape[1])])
                maxt = ", ".join([format % arr[:, r].max()
                                  for r in range(arr.shape[1])])
        except (TypeError, IndexError):
            mint, maxt = "-", "-"
        self.min_label.setText(mint)
        self.max_label.setText(maxt)

    def set(self):
        """Override AbstractDataSetWidget method"""
        if self.item.get_prop_value("display", "transpose"):
            value = self.value().T
        else:
            value = self.value()
        self.item.set(value)

    def value(self):
        return self.arr

    def place_on_grid(self, layout, row, label_column, widget_column,
                      row_span=1, column_span=1):
        """Override AbstractDataSetWidget method"""
        layout.addWidget(self.group, row, label_column, row_span, column_span+1)
示例#31
0
 def setup_instance(self, instance):
     """Construct main layout"""
     grid = QGridLayout()
     grid.setAlignment(Qt.AlignTop)
     self.layout.addLayout(grid)
     self.edit_layout.append( self.layout_factory( instance, grid) )
示例#32
0
class Window(QMainWindow):
    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'))

    def closeEvent(self, event):
        global _figures, _current_fig, _current_axes
        figure_title = to_text_string(self.windowTitle())
        if _figures.pop(figure_title) == _current_fig:
            _current_fig = None
            _current_axes = None
        self.itemlist.close()
        self.contrast.close()
        self.xcsw.close()
        self.ycsw.close()
        event.accept()
        
    def add_plot(self, i, j, plot):
        self.layout.addWidget(plot, i, j)
        self.manager.add_plot(plot)
        self.plots.append(plot)

    def replot(self):
        for plot in self.plots:
            plot.replot()
            item = plot.get_default_item()
            if item is not None:
                plot.set_active_item(item)
                item.unselect()
            
    def add_panels(self, images=False):
        self.manager.add_panel(self.itemlist)
        if images:
            for panel in (self.ycsw, self.xcsw, self.contrast):
                panel.hide()
                self.manager.add_panel(panel)
            
    def register_tools(self, images=False):
        if images:
            self.manager.register_all_image_tools()
        else:
            self.manager.register_all_curve_tools()
    
    def display(self):
        self.show()
        self.replot()
        self.manager.get_default_tool().activate()
        self.manager.update_tools_status()
示例#33
0
class Window(QMainWindow):
    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'))

    def closeEvent(self, event):
        global _figures, _current_fig, _current_axes
        figure_title = to_text_string(self.windowTitle())
        if _figures.pop(figure_title) == _current_fig:
            _current_fig = None
            _current_axes = None
        self.itemlist.close()
        self.contrast.close()
        self.xcsw.close()
        self.ycsw.close()
        event.accept()

    def add_plot(self, i, j, plot):
        self.layout.addWidget(plot, i, j)
        self.manager.add_plot(plot)
        self.plots.append(plot)

    def replot(self):
        for plot in self.plots:
            plot.replot()
            item = plot.get_default_item()
            if item is not None:
                plot.set_active_item(item)
                item.unselect()

    def add_panels(self, images=False):
        self.manager.add_panel(self.itemlist)
        if images:
            for panel in (self.ycsw, self.xcsw, self.contrast):
                panel.hide()
                self.manager.add_panel(panel)

    def register_tools(self, images=False):
        if images:
            self.manager.register_all_image_tools()
        else:
            self.manager.register_all_curve_tools()

    def display(self):
        self.show()
        self.replot()
        self.manager.get_default_tool().activate()
        self.manager.update_tools_status()
示例#34
0
    def __init__(self, parent):
        #super(ObjectFT, self).__init__(Qt.Vertical, parent)
        super().__init__(parent)

        self.stage = None
        self.offset = 0.  # offset from 0 where t0 is (mm)
        self.newOff = 0.
        self.stageRange = (0, 0)

        layoutWidget = QWidget()
        layout = QGridLayout()
        layoutWidget.setLayout(layout)

        # put layout together
        self.openStageBtn = QPushButton("Open stage")
        self.initStageBtn = QPushButton("Init stage")

        #absolute move
        #current position
        self.currentPos = QLabel('')
        #self.currentPos.setValidator(QDoubleValidator())
        #relative move (mm)
        self.deltaMove_mm = QLineEdit()
        self.deltaMove_mm.setText('0')
        self.deltaMove_mm.setValidator(QDoubleValidator())
        self.deltaMovePlus_mm = QPushButton('+')
        self.deltaMoveMinus_mm = QPushButton('-')
        #relative move (fs)
        self.deltaMove_fs = QLineEdit()
        self.deltaMovePlus_fs = QPushButton('+')
        self.deltaMoveMinus_fs = QPushButton('-')
        #velocity
        self.velocityLabel = QLabel('Velocity:')
        self.velocity = QSlider(Qt.Horizontal)
        self.velocity.setMinimum(0)
        self.velocity.setMaximum(
            2000)  # unit in µm; TODO: try to get max vel. from controller

        # scan from (fs)
        self.scanFrom = QLineEdit()
        self.scanFrom.setText('-100')
        self.scanFrom.setValidator(QIntValidator())
        # scan to (fs)
        self.scanTo = QLineEdit()
        self.scanTo.setText('100')
        self.scanTo.setValidator(QIntValidator())
        # scan stepsize (fs)
        self.scanStep = QLineEdit()
        self.scanStep.setText('10')
        self.scanStep.setValidator(QDoubleValidator())
        # center here button
        self.centerBtn = QPushButton('Center here')
        self.centerBtn.setToolTip('Center scan at current stage position')
        self.startScanBtn = QPushButton("Start scan")
        self.stopScanBtn = QPushButton("Stop scan")
        self.niceBtn = QPushButton('Make it nice')
        # spacer line
        hLine = QFrame()
        hLine.setFrameStyle(QFrame.HLine)
        hLine.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding)

        # put layout together
        layout.addWidget(self.openStageBtn, 0, 0)
        layout.addWidget(self.initStageBtn, 0, 1)
        layout.addWidget(QLabel("Current pos (mm):"), 1, 0)
        layout.addWidget(self.currentPos, 1, 1)
        layout.addWidget(self.velocityLabel, 2, 0)
        layout.addWidget(self.velocity, 3, 0, 1, 2)
        layout.addWidget(QLabel('Move relative (mm)'), 4, 0)
        layout.addWidget(self.deltaMove_mm, 5, 0, 1, 2)
        layout.addWidget(self.deltaMoveMinus_mm, 6, 0)
        layout.addWidget(self.deltaMovePlus_mm, 6, 1)
        layout.addWidget(QLabel('Move relative (fs)'), 7, 0)
        layout.addWidget(self.deltaMove_fs, 8, 0, 1, 2)
        layout.addWidget(self.deltaMoveMinus_fs, 9, 0)
        layout.addWidget(self.deltaMovePlus_fs, 9, 1)

        layout.addWidget(hLine, 10, 0, 1, 2)
        layout.addWidget(QLabel('Scan from (fs)'), 11, 0)
        layout.addWidget(self.scanFrom, 11, 1)
        layout.addWidget(QLabel('Scan to (fs)'), 12, 0)
        layout.addWidget(self.scanTo, 12, 1)
        layout.addWidget(QLabel('Stepsize (fs)'), 13, 0)
        layout.addWidget(self.scanStep, 13, 1)
        layout.addWidget(self.startScanBtn, 14, 0)
        layout.addWidget(self.stopScanBtn, 14, 1)
        layout.addWidget(self.centerBtn, 15, 1)
        layout.addWidget(self.niceBtn, 16, 1)
        layout.setRowStretch(17, 10)
        layout.setColumnStretch(2, 10)

        self.addWidget(layoutWidget)

        # make button and stuff functional
        self.openStageBtn.released.connect(self.connectStage)
        self.initStageBtn.released.connect(self.initStage)
        self.scanFrom.returnPressed.connect(self._xAxeChanged)
        self.scanTo.returnPressed.connect(self._xAxeChanged)
        self.centerBtn.released.connect(self._centerHere)
        self.deltaMovePlus_mm.released.connect(
            lambda x=1: self.moveRel_mm(float(self.deltaMove_mm.text())))
        self.deltaMoveMinus_mm.released.connect(
            lambda x=-1: self.moveRel_mm(float(self.deltaMove_mm.text()), x))

        ################
        # thread for updating position
        #self.currPosThr = GenericThread(self.__getCurrPos)
        self.updateCurrPos.connect(self.__updateCurrPos)
        self.currPos_thread = QThread()  # create the QThread
        self.currPos_thread.start()

        # This causes my_worker.run() to eventually execute in my_thread:
        self.currPos_worker = GenericWorker(self.__getCurrPos)
        self.currPos_worker.moveToThread(self.currPos_thread)
示例#35
0
文件: FTIR.py 项目: BenMoon/LabSoft
    def __init__(self, parent):
        super(MakeNicerWidget, self).__init__(parent)

        self.data = np.array([]) # array which holds data
        
        # Time domain plot
        self.tdWidget = DockablePlotWidget(self, CurveWidget)
        self.tdWidget.calcFun.addFun('fs', lambda x: x,
                                           lambda x: x)
        self.tdWidget.calcFun.addFun('µm', lambda x: x*fsDelay*1e3,
                                           lambda x: x/fsDelay*1e-3)
        self.tdWidget.calcFun.addFun('mm', lambda x: x*fsDelay,
                                           lambda x: x/fsDelay)
        tdPlot = self.tdWidget.get_plot()
        self.tdSignal  = SignalFT(self, plot=tdPlot)
        self.tdFit     = SignalFT(self, plot=tdPlot, col='r')

        # Frequency domain plot
        self.fdWidget = DockablePlotWidget(self, CurveWidget)
        self.fdWidget.calcFun.addFun('PHz', lambda x: x,
                                            lambda x: x)
        self.fdWidget.calcFun.addFun('THz', lambda x: x*1e3,
                                            lambda x: x*1e-3)
        self.fdWidget.calcFun.addFun('µm', lambda x: c0/x*1e-9,
                                           lambda x: c0/x*1e-9)
        self.fdWidget.calcFun.addFun('eV', lambda x: x,
                                           lambda x: x)
        fdplot = self.fdWidget.get_plot()
        self.fdSignal  = SignalFT(self, plot=fdplot)
        self.fdFit     = SignalFT(self, plot=fdplot, col='r')

        self.smoothNum = QSpinBox() # gives number of smoothin points
        self.smoothNum.setMinimum(1)
        self.smoothNum.setSingleStep(2)

        # Put things together in layouts
        buttonLayout = QGridLayout()
        plotLayout   = QVBoxLayout()
        layout       = QHBoxLayout()
        plotLayout.addWidget(self.tdWidget)
        plotLayout.addWidget(self.fdWidget)

        buttonLayout.addWidget(QLabel('Fitting function'), 0, 0)
        buttonLayout.addWidget(
            QLineEdit("lambda x,A,f,phi: np.sin(2*np.pi*f*x+phi)"), 1, 0, 1, 2)
        buttonLayout.addWidget(QLabel('Smooth'), 2, 0)
        buttonLayout.addWidget(self.smoothNum, 2, 1)
        buttonLayout.setRowStretch(3, 20)

        layout.addLayout(buttonLayout)
        layout.addLayout(plotLayout)
        self.setLayout(layout)
        
        # connect signals
        self.updateTdPlot.connect(self.tdSignal.updatePlot)
        self.updateTdFitPlot.connect(self.tdFit.updatePlot)
        self.updateFdPlot.connect(lambda data:
            self.fdSignal.updatePlot(self.fdSignal.computeFFT(data)))
        self.updateFdFitPlot.connect(lambda data:
            self.fdFit.updatePlot(self.fdFit.computeFFT(data)))
        self.smoothNum.valueChanged.connect(self.smoothData)

        self.setData()
示例#36
0
    def __init__(self, parent):
        #super(ObjectFT, self).__init__(Qt.Vertical, parent)
        super().__init__(parent)

        self.scp = None  # variable to hold oscilloscope object
        self.mutex = QMutex()

        layoutWidget = QWidget()
        layout = QGridLayout()
        layoutWidget.setLayout(layout)

        self.openDevBtn = QPushButton('Open Osci')
        # channel stuff
        self.measCh = QComboBox()
        self.chSens = QComboBox()
        self.triggCh = QComboBox()
        self.frequency = QLineEdit()
        self.frequency.setValidator(QIntValidator())
        self.recordLen = QLineEdit()
        self.recordLen.setValidator(QIntValidator())
        self.delay = QLineEdit()
        self.delay.setValidator(QDoubleValidator())
        # trigger stuff
        self.triggLevel = QLineEdit()
        self.triggLevel.setToolTip(
            'http://api.tiepie.com/libtiepie/0.5/triggering_scpch.html#triggering_scpch_level'
        )
        self.triggLevel.setText(
            '0.5'
        )  # init value otherwise there's trouble with signal changing index of sensitivity
        self.triggLevel.setValidator(QDoubleValidator(0., 1., 3))
        self.hystereses = QLineEdit()
        self.hystereses.setText('0.05')
        self.hystereses.setToolTip(
            'http://api.tiepie.com/libtiepie/0.5/triggering_scpch.html#triggering_scpch_hysteresis'
        )
        self.hystereses.setValidator(QDoubleValidator(0., 1., 3))
        self.triggKind = QComboBox()
        # do averages
        self.averages = QSpinBox()
        self.averages.setValue(1)
        self.averages.setRange(1, 10000)

        # put layout together
        layout.addWidget(self.openDevBtn, 0, 0)
        layout.addWidget(QLabel('Measuring Ch'), 1, 0)
        layout.addWidget(self.measCh, 1, 1)
        layout.addWidget(QLabel('Ch sensitivity'), 2, 0)
        layout.addWidget(self.chSens, 2, 1)
        layout.addWidget(QLabel('Sample freq. (kHz)'), 3, 0)
        layout.addWidget(self.frequency, 3, 1)
        layout.addWidget(QLabel('Record length'), 4, 0)
        layout.addWidget(self.recordLen, 4, 1)
        layout.addWidget(QLabel('Delay'), 5, 0)
        layout.addWidget(self.delay, 5, 1)
        layout.addWidget(QLabel('Trigger Ch'), 6, 0)
        layout.addWidget(self.triggCh, 6, 1)
        layout.addWidget(QLabel('Trigger Level (%)'), 7, 0)
        layout.addWidget(self.triggLevel, 7, 1)
        layout.addWidget(QLabel('Hystereses'), 8, 0)
        layout.addWidget(self.hystereses, 8, 1)
        layout.addWidget(QLabel('Trigger kind'), 9, 0)
        layout.addWidget(self.triggKind, 9, 1)
        layout.addWidget(QLabel('Averages'), 10, 0)
        layout.addWidget(self.averages, 10, 1)
        layout.setRowStretch(11, 10)
        layout.setColumnStretch(2, 10)

        self.addWidget(layoutWidget)

        # connect UI to get things working
        self.openDevBtn.released.connect(self.openDev)
        self.chSens.currentIndexChanged.connect(self._changeSens)
        self.frequency.returnPressed.connect(self._changeFreq)
        self.recordLen.returnPressed.connect(self._changeRecordLength)
        self.triggCh.currentIndexChanged.connect(self._changeTrigCh)
        self.triggLevel.returnPressed.connect(self._triggLevelChanged)
        self.triggLevel.textChanged.connect(self._check_state)
        self.hystereses.returnPressed.connect(self._setHystereses)
        self.hystereses.textChanged.connect(self._check_state)
示例#37
0
    def __init__(self, parent=None, x=[], y=[], data=[]):
        QWidget.__init__(self, parent)

        if len(x) < 2:
            x = np.linspace(0, 1392, 1392)
            y = np.linspace(0, 1040, 1040)
            data = np.zeros((1040, 1392))

        self.x = x
        self.y = y
        self.data = data

        sx = 600
        sy = int(sx / 1.338)
        stretch_x = 3
        stretch_y = 3

        #self.setGeometry(QRect(0,0,sx,sy))
        layout = QGridLayout(self)
        layout.setMargin(0)

        self.screen = ImageScreen(self, x, y, data)
        self.cutX = CutScreen(self)
        self.cutY = CutScreen(self)

        layout.addWidget(self.screen, 1, 0)
        layout.addWidget(self.cutX, 0, 0)
        layout.addWidget(self.cutY, 1, 1)

        layout.setColumnStretch(0, stretch_x)
        layout.setColumnStretch(1, 1)
        layout.setRowStretch(0, 1)
        layout.setRowStretch(1, stretch_y)

        self.setLayout(layout)

        self.updateGeometry()

        self.manager = PlotManager(self)
        self.manager.add_plot(self.screen.plot)
        self.manager.add_plot(self.cutX.plot)
        self.manager.add_plot(self.cutY.plot)

        #roi = ROISelectTool
        #bkgnd = BKGNDSelectTool

        self.tools = [tools.SelectTool, tools.RectZoomTool, tools.ColormapTool]

        self.manager.register_all_curve_tools()
示例#38
0
文件: fit.py 项目: CaptainAL/Spyder
class FitWidgetMixin(CurveWidgetMixin):
    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()
        
    # QWidget API --------------------------------------------------------------
    def resizeEvent(self, event):
        QWidget.resizeEvent(self, event)
        self.get_plot().replot()
        
    # CurveWidgetMixin API -----------------------------------------------------
    def setup_widget_layout(self):
        self.fit_layout = QHBoxLayout()
        self.params_layout = QGridLayout()
        params_group = create_groupbox(self, _("Fit parameters"),
                                       layout=self.params_layout)
        if self.auto_fit_enabled:
            auto_group = self.create_autofit_group()
            self.fit_layout.addWidget(auto_group)
        self.fit_layout.addWidget(params_group)
        self.plot_layout.addLayout(self.fit_layout, 1, 0)
        
        vlayout = QVBoxLayout(self)
        vlayout.addWidget(self.toolbar)
        vlayout.addLayout(self.plot_layout)
        self.setLayout(vlayout)
        
    def create_plot(self, options):
        CurveWidgetMixin.create_plot(self, options)
        for plot in self.get_plots():
            plot.SIG_RANGE_CHANGED.connect(self.range_changed)
        
    # Public API ---------------------------------------------------------------  
    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()
        
    def set_fit_data(self, fitfunc, fitparams, fitargs=None, fitkwargs=None):
        if self.fitparams is not None:
            self.clear_params_layout()
        self.fitfunc = fitfunc
        self.fitparams = fitparams
        self.fitargs = fitargs
        self.fitkwargs = fitkwargs
        self.populate_params_layout()
        self.refresh()
        
    def clear_params_layout(self):
        for i, param in enumerate(self.fitparams):
            for widget in param.get_widgets():
                if widget is not None:
                    self.params_layout.removeWidget(widget)
                    widget.hide()
        
    def populate_params_layout(self):
        add_fitparam_widgets_to(self.params_layout, self.fitparams,
                                self.refresh, param_cols=self.param_cols)
    
    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)
        
    def get_fitfunc_arguments(self):
        """Return fitargs and fitkwargs"""
        fitargs = self.fitargs
        if self.fitargs is None:
            fitargs = []
        fitkwargs = self.fitkwargs
        if self.fitkwargs is None:
            fitkwargs = {}
        return fitargs, fitkwargs
        
    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()
        
    def range_changed(self, xrange_obj, xmin, xmax):
        self.autofit_prm.xmin, self.autofit_prm.xmax = xmin, xmax
        self.compute_imin_imax()
        
    def toggle_xrange(self, state):
        self.xrange.setVisible(state)
        plot = self.get_plot()
        plot.replot()
        if state:
            plot.set_active_item(self.xrange)
        self.show_xrange = state
        
    def edit_parameters(self):
        if self.autofit_prm.edit(parent=self):
            self.xrange.set_range(self.autofit_prm.xmin, self.autofit_prm.xmax)
            plot = self.get_plot()
            plot.replot()
            self.compute_imin_imax()
        
    def compute_imin_imax(self):
        self.i_min = self.x.searchsorted(self.autofit_prm.xmin)
        self.i_max = self.x.searchsorted(self.autofit_prm.xmax, side='right')
        
    def errorfunc(self, params):
        x = self.x[self.i_min:self.i_max]
        y = self.y[self.i_min:self.i_max]
        fitargs, fitkwargs = self.get_fitfunc_arguments()
        return y - self.fitfunc(x, params, *fitargs, **fitkwargs)

    def autofit(self):
        meth = self.autofit_prm.method
        x0 = np.array([p.value for p in self.fitparams])
        if meth == "lq":
            x = self.autofit_lq(x0)
        elif meth=="simplex":
            x = self.autofit_simplex(x0)
        elif meth=="powel":
            x = self.autofit_powel(x0)
        elif meth=="bfgs":
            x = self.autofit_bfgs(x0)
        elif meth=="l_bfgs_b":
            x = self.autofit_l_bfgs(x0)
        elif meth=="cg":
            x = self.autofit_cg(x0)
        else:
            return
        for v, p in zip(x, self.fitparams):
            p.value = v
        self.refresh()
        for prm in self.fitparams:
            prm.update()

    def get_norm_func(self):
        prm = self.autofit_prm
        err_norm = eval(prm.err_norm)
        def func(params):
            err = np.linalg.norm(self.errorfunc(params), err_norm)
            return err
        return func

    def autofit_simplex(self, x0):
        prm = self.autofit_prm
        from scipy.optimize import fmin
        x = fmin(self.get_norm_func(), x0, xtol=prm.xtol, ftol=prm.ftol)
        return x

    def autofit_powel(self, x0):
        prm = self.autofit_prm
        from scipy.optimize import fmin_powell
        x = fmin_powell(self.get_norm_func(), x0, xtol=prm.xtol, ftol=prm.ftol)
        return x

    def autofit_bfgs(self, x0):
        prm = self.autofit_prm
        from scipy.optimize import fmin_bfgs
        x = fmin_bfgs(self.get_norm_func(), x0, gtol=prm.gtol,
                      norm=eval(prm.norm))
        return x

    def autofit_l_bfgs(self, x0):
        prm = self.autofit_prm
        bounds = [(p.min, p.max) for p in self.fitparams]
        from scipy.optimize import fmin_l_bfgs_b
        x, _f, _d = fmin_l_bfgs_b(self.get_norm_func(), x0, pgtol=prm.gtol,
                          approx_grad=1, bounds=bounds)
        return x
        
    def autofit_cg(self, x0):
        prm = self.autofit_prm
        from scipy.optimize import fmin_cg
        x = fmin_cg(self.get_norm_func(), x0, gtol=prm.gtol,
                    norm=eval(prm.norm))
        return x

    def autofit_lq(self, x0):
        prm = self.autofit_prm
        def func(params):
            err = self.errorfunc(params)
            return err
        from scipy.optimize import leastsq
        x, _ier = leastsq(func, x0, xtol=prm.xtol, ftol=prm.ftol)
        return x

    def get_values(self):
        """Convenience method to get fit parameter values"""
        return [param.value for param in self.fitparams]
示例#39
0
文件: plot.py 项目: alimuldal/guiqwt
class CurveWidgetMixin(PlotManager):
    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()
        
    def setup_widget_layout(self):
        raise NotImplementedError
        
    def setup_widget_properties(self, wintitle, icon):
        self.setWindowTitle(wintitle)
        if is_text_string(icon):
            icon = get_icon(icon)
        if icon is not None:
            self.setWindowIcon(icon)
        self.setMinimumSize(320, 240)
        self.resize(640, 480)

    def register_tools(self):
        """
        Register the plotting dialog box tools: the base implementation 
        provides standard, curve-related and other tools - i.e. calling 
        this method is exactly the same as calling 
        :py:meth:`guiqwt.plot.CurveDialog.register_all_curve_tools`
        
        This method may be overriden to provide a fully customized set of tools
        """
        self.register_all_curve_tools()

    def create_plot(self, options, row=0, column=0, rowspan=1, columnspan=1):
        """
        Create the plotting widget (which is an instance of class 
        :py:class:`guiqwt.plot.BaseCurveWidget`), add it to the dialog box 
        main layout (:py:attr:`guiqwt.plot.CurveDialog.plot_layout`) and 
        then add the `item list` panel

        May be overriden to customize the plot layout 
        (:py:attr:`guiqwt.plot.CurveDialog.plot_layout`)
        """
        self.plot_widget = BaseCurveWidget(self, **options)
        self.plot_layout.addWidget(self.plot_widget,
                                   row, column, rowspan, columnspan)
        
        # Configuring plot manager
        self.add_plot(self.plot_widget.plot)
        self.add_panel(self.plot_widget.itemlist)
示例#40
0
class CurveWidgetMixin(PlotManager):
    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()

    def setup_widget_layout(self):
        raise NotImplementedError

    def setup_widget_properties(self, wintitle, icon):
        self.setWindowTitle(wintitle)
        if is_text_string(icon):
            icon = get_icon(icon)
        if icon is not None:
            self.setWindowIcon(icon)
        self.setMinimumSize(320, 240)
        self.resize(640, 480)

    def register_tools(self):
        """
        Register the plotting dialog box tools: the base implementation 
        provides standard, curve-related and other tools - i.e. calling 
        this method is exactly the same as calling 
        :py:meth:`guiqwt.plot.CurveDialog.register_all_curve_tools`
        
        This method may be overriden to provide a fully customized set of tools
        """
        self.register_all_curve_tools()

    def create_plot(self, options):
        """
        Create the plotting widget (which is an instance of class 
        :py:class:`guiqwt.plot.BaseCurveWidget`), add it to the dialog box 
        main layout (:py:attr:`guiqwt.plot.CurveDialog.plot_layout`) and 
        then add the `item list` panel

        May be overriden to customize the plot layout 
        (:py:attr:`guiqwt.plot.CurveDialog.plot_layout`)
        """
        self.plot_widget = BaseCurveWidget(self, **options)
        self.plot_layout.addWidget(self.plot_widget, 0, 0)

        # Configuring plot manager
        self.add_plot(self.plot_widget.plot)
        self.add_panel(self.plot_widget.itemlist)
class dspPcmWidget(dspWidget):
   def __init__(self, name, instanceId, widgetList, dataFunc, inactivityTimeout = True):
      dspWidget.__init__(self, name, instanceId, widgetList, inactivityTimeout = inactivityTimeout)

      self.dataFunc = dataFunc
      self.Fs = 2000
      self.sample_rate = 5333
      self.pascal_constant=2*10**-5

      self.pcm =[]

      self.layout = QGridLayout()
      self.setLayout(self.layout) 
      
      self.pcmPlotW = dspCurveWidget(title="Monitor Mic Data", show_itemlist=False)
      self.layout.addWidget(self.pcmPlotW, 1, 0, 1, 1)

      self.resize(1000, 300)



      self.Button1 = QPushButton("Level")

      self.layout.addWidget(self.Button1, 1,1,1,1)

      self.connect(self.Button1, SIGNAL('clicked()'), self.Button1Pressed)



    

 
   def A_weighting(self, fs):

       f1 = 20.598997
       f2 = 107.65265
       f3 = 737.86223
       f4 = 12194.217
       A1000 = 1.9997

       NUMs = [(2*pi * f4)**2 * (10**(A1000/20)), 0, 0, 0, 0]
       DENs = polymul([1, 4*pi * f4, (2*pi * f4)**2],
                   [1, 4*pi * f1, (2*pi * f1)**2])
       DENs = polymul(polymul(DENs, [1, 2*pi * f3]),
                                 [1, 2*pi * f2])

       return bilinear(NUMs, DENs, fs)

   def C_weighting(self, fs):
      f1 = 20.598997 
      f4 = 12194.217
      C1000 = 0.0619

      NUMs = [(2*pi*f4)**2*(10**(C1000/20.0)),0,0]
      DENs = polymul([1,4*pi*f4,(2*pi*f4)**2.0],[1,4*pi*f1,(2*pi*f1)**2]) 

 
      return bilinear(NUMs,DENs,fs)
   
   def properties(self, signal, samplerate):
      signal_level = self.ac_rms(signal)
      weighted = self.A_weight(signal, samplerate)
      weighted1= self.C_weight(signal, samplerate)
      weighted_level = self.ac_rms(weighted)
      weighted_level1= self.ac_rms(weighted1)
    
      return [
    'RMS level: %.3f (%.3f dB SPL)' % (signal_level, self.dB(signal_level)+10),
    'A-weighted: %.3f (%.3f dB(A))' % (weighted_level, self.dB(weighted_level)+10),
    'C-weighted: %.3f (%.3f dB(C))' % (weighted_level1, self.dB(weighted_level1)+10)
    #'A-difference: %.3f dB' % self.dB(weighted_level/signal_level),
    #'-----------------',
]

   def ac_rms(self, signal):

       return self.rms_flat(signal - mean(signal))

   def rms_flat(self, a):

       return np.sqrt(np.mean(np.absolute(a)**2))

   def dB(self, level):

       return 20 * log10(self.rms_flat(level)/self.pascal_constant)

   def A_weight(self, signal, samplerate):
       B, A = self.A_weighting(samplerate)
       return lfilter(B, A, signal)

   def C_weight(self, signal, samplerate):
       B, A = self.C_weighting(samplerate)
       return lfilter(B, A, signal)

   def Button1Pressed(self):
       
       elements = np.asarray(self.pcm)
       rms_pcm = np.sqrt(np.mean(elements**2))
       dB = 20*scipy.log10(np.abs(rms_pcm/self.pascal_constant))
       #print (str(dB)+" "+'dB SPL')
       Sound_properties = self.properties(elements, self.sample_rate)
       print colored("Sound Properties:", 'yellow')
       print colored(Sound_properties[0], 'yellow')
       print colored(Sound_properties[1], 'yellow')
       print colored(Sound_properties[2], 'yellow')
       #print colored(Sound_properties[3], 'blue')
      

   def update(self):
      try:
         data = self.dataFunc(self.instanceId, self.preferredSamples)
      except RuntimeError:
         return
      
      channels = data.get('chn')
      blockSize = data.get('frm')
      self.pcm = data.get('pcm')
      #elements = np.asarray(pcm)


         
         #this will calculate the signal to noise ratio of monitor microphone placed in the point of interest(in between two micrphones)
         #snr = scipy.stats.signaltonoise(elements)


      #extracting list of pcm data into another list with two elements for taking first element and use for that finding rms value 
      #two_elements=[pcm[2*i:2*i+2] for i in range(int(0),int(math.ceil(len(pcm)/2.0)))]

      # Conditional to keep backwards compatibility with old SPI logs. 
      Fs = data.get('Fs') if (data.get('Fs') != 0) else self.Fs
      if Fs == 96:
          Fs = 96000
      self.sample_rate= Fs
      samples = len(self.pcm) / channels
      self.pcmPlotW.update(Fs, channels, blockSize, samples, self.pcm) 
      #self.updatesamples(str(samples))


   def rescale(self):
      self.pcmPlotW.rescale()
示例#42
0
 def setup_instance(self, instance):
     """Construct main layout"""
     grid = QGridLayout()
     grid.setAlignment(Qt.AlignTop)
     self.layout.addLayout(grid)
     self.edit_layout.append( self.layout_factory( instance, grid) )
示例#43
0
文件: fit.py 项目: gyenney/Tools
class FitWidgetMixin(CurveWidgetMixin):
    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()

    # QWidget API --------------------------------------------------------------
    def resizeEvent(self, event):
        QWidget.resizeEvent(self, event)
        self.get_plot().replot()

    # CurveWidgetMixin API -----------------------------------------------------
    def setup_widget_layout(self):
        self.fit_layout = QHBoxLayout()
        self.params_layout = QGridLayout()
        params_group = create_groupbox(self,
                                       _("Fit parameters"),
                                       layout=self.params_layout)
        if self.auto_fit_enabled:
            auto_group = self.create_autofit_group()
            self.fit_layout.addWidget(auto_group)
        self.fit_layout.addWidget(params_group)
        self.plot_layout.addLayout(self.fit_layout, 1, 0)

        vlayout = QVBoxLayout(self)
        vlayout.addWidget(self.toolbar)
        vlayout.addLayout(self.plot_layout)
        self.setLayout(vlayout)

    def create_plot(self, options):
        CurveWidgetMixin.create_plot(self, options)
        for plot in self.get_plots():
            plot.SIG_RANGE_CHANGED.connect(self.range_changed)

    # Public API ---------------------------------------------------------------
    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()

    def set_fit_data(self, fitfunc, fitparams, fitargs=None, fitkwargs=None):
        if self.fitparams is not None:
            self.clear_params_layout()
        self.fitfunc = fitfunc
        self.fitparams = fitparams
        self.fitargs = fitargs
        self.fitkwargs = fitkwargs
        self.populate_params_layout()
        self.refresh()

    def clear_params_layout(self):
        for i, param in enumerate(self.fitparams):
            for widget in param.get_widgets():
                if widget is not None:
                    self.params_layout.removeWidget(widget)
                    widget.hide()

    def populate_params_layout(self):
        add_fitparam_widgets_to(self.params_layout,
                                self.fitparams,
                                self.refresh,
                                param_cols=self.param_cols)

    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)

    def get_fitfunc_arguments(self):
        """Return fitargs and fitkwargs"""
        fitargs = self.fitargs
        if self.fitargs is None:
            fitargs = []
        fitkwargs = self.fitkwargs
        if self.fitkwargs is None:
            fitkwargs = {}
        return fitargs, fitkwargs

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

    def range_changed(self, xrange_obj, xmin, xmax):
        self.autofit_prm.xmin, self.autofit_prm.xmax = xmin, xmax
        self.compute_imin_imax()

    def toggle_xrange(self, state):
        self.xrange.setVisible(state)
        plot = self.get_plot()
        plot.replot()
        if state:
            plot.set_active_item(self.xrange)
        self.show_xrange = state

    def edit_parameters(self):
        if self.autofit_prm.edit(parent=self):
            self.xrange.set_range(self.autofit_prm.xmin, self.autofit_prm.xmax)
            plot = self.get_plot()
            plot.replot()
            self.compute_imin_imax()

    def compute_imin_imax(self):
        self.i_min = self.x.searchsorted(self.autofit_prm.xmin)
        self.i_max = self.x.searchsorted(self.autofit_prm.xmax, side='right')

    def errorfunc(self, params):
        x = self.x[self.i_min:self.i_max]
        y = self.y[self.i_min:self.i_max]
        fitargs, fitkwargs = self.get_fitfunc_arguments()
        return y - self.fitfunc(x, params, *fitargs, **fitkwargs)

    def autofit(self):
        meth = self.autofit_prm.method
        x0 = np.array([p.value for p in self.fitparams])
        if meth == "lq":
            x = self.autofit_lq(x0)
        elif meth == "simplex":
            x = self.autofit_simplex(x0)
        elif meth == "powel":
            x = self.autofit_powel(x0)
        elif meth == "bfgs":
            x = self.autofit_bfgs(x0)
        elif meth == "l_bfgs_b":
            x = self.autofit_l_bfgs(x0)
        elif meth == "cg":
            x = self.autofit_cg(x0)
        else:
            return
        for v, p in zip(x, self.fitparams):
            p.value = v
        self.refresh()
        for prm in self.fitparams:
            prm.update()

    def get_norm_func(self):
        prm = self.autofit_prm
        err_norm = eval(prm.err_norm)

        def func(params):
            err = np.linalg.norm(self.errorfunc(params), err_norm)
            return err

        return func

    def autofit_simplex(self, x0):
        prm = self.autofit_prm
        from scipy.optimize import fmin
        x = fmin(self.get_norm_func(), x0, xtol=prm.xtol, ftol=prm.ftol)
        return x

    def autofit_powel(self, x0):
        prm = self.autofit_prm
        from scipy.optimize import fmin_powell
        x = fmin_powell(self.get_norm_func(), x0, xtol=prm.xtol, ftol=prm.ftol)
        return x

    def autofit_bfgs(self, x0):
        prm = self.autofit_prm
        from scipy.optimize import fmin_bfgs
        x = fmin_bfgs(self.get_norm_func(),
                      x0,
                      gtol=prm.gtol,
                      norm=eval(prm.norm))
        return x

    def autofit_l_bfgs(self, x0):
        prm = self.autofit_prm
        bounds = [(p.min, p.max) for p in self.fitparams]
        from scipy.optimize import fmin_l_bfgs_b
        x, _f, _d = fmin_l_bfgs_b(self.get_norm_func(),
                                  x0,
                                  pgtol=prm.gtol,
                                  approx_grad=1,
                                  bounds=bounds)
        return x

    def autofit_cg(self, x0):
        prm = self.autofit_prm
        from scipy.optimize import fmin_cg
        x = fmin_cg(self.get_norm_func(),
                    x0,
                    gtol=prm.gtol,
                    norm=eval(prm.norm))
        return x

    def autofit_lq(self, x0):
        prm = self.autofit_prm

        def func(params):
            err = self.errorfunc(params)
            return err

        from scipy.optimize import leastsq
        x, _ier = leastsq(func, x0, xtol=prm.xtol, ftol=prm.ftol)
        return x

    def get_values(self):
        """Convenience method to get fit parameter values"""
        return [param.value for param in self.fitparams]