Exemple #1
0
def main():
    # synthetic data
    from silx.math.fit.functions import sum_gauss

    x = numpy.arange(5000)
    # (height1, center1, fwhm1, ...) 5 peaks
    params1 = (50, 500, 100,
               20, 2000, 200,
               50, 2250, 100,
               40, 3000, 75,
               23, 4000, 150)
    y0 = sum_gauss(x, *params1)

    # random values between [-1;1]
    noise = 2 * numpy.random.random(5000) - 1
    # make it +- 5%
    noise *= 0.05

    # 2 gaussians with very large fwhm, as background signal
    actual_bg = sum_gauss(x, 15, 3500, 3000, 5, 1000, 1500)

    # Add 5% random noise to gaussians and add background
    y = y0 + numpy.average(y0) * noise + actual_bg

    # Open widget
    a = qt.QApplication(sys.argv)
    a.lastWindowClosed.connect(a.quit)

    def mySlot(ddict):
        print(ddict)

    w = BackgroundDialog()
    w.parametersWidget.parametersWidget.sigBackgroundParamWidgetSignal.connect(mySlot)
    w.setData(x, y)
    w.exec()
Exemple #2
0
def test(withGUI=True, withTestData=True):
    myapp.make_pipeline(withGUI)

    if withTestData:
        myapp.load_test_data()

    if withGUI:
        node0 = list(csi.nodes.values())[0]
        node0.fileNameFilters = ['*.fio', '*.h5', '*.dat']

        from silx.gui import qt
        from parseq.gui.mainWindow import MainWindowParSeq
        app = qt.QApplication(sys.argv)
        mainWindow = MainWindowParSeq()
        mainWindow.dataChanged()
        mainWindow.show()

        node0.widget.tree.setFocus()  # important
        node0.widget.tree.setCurrentIndex(csi.model.index(0))

        from modeltest import ModelTest
        node0.widget.files.ModelTest = ModelTest

        app.exec_()
    else:
        import matplotlib.pyplot as plt
        for data in csi.dataRootItem.get_items():
            plt.plot(data.r, data.ft)
        plt.show()
Exemple #3
0
def test():
    myapp.make_pipeline(True)

    app = qt.QApplication(sys.argv)
    mainWindow = AboutDialog(None)
    mainWindow.show()
    app.exec_()
Exemple #4
0
def example_image(mode):
    """set up the roi stats example for images"""
    app = qt.QApplication([])
    rectangle_roi, polygon_roi, arc_roi = get_2D_rois()

    window = _RoiStatsDisplayExWindow()
    window.setRois(rois2D=(rectangle_roi, polygon_roi, arc_roi))
    # Create the thread that calls submitToQtMainThread
    updateThread = UpdateThread(window.plot)
    updateThread.start()  # Start updating the plot

    # define some image and curve
    window.plot.addImage(numpy.arange(10000).reshape(100, 100), legend='img1')
    window.plot.addImage(numpy.random.random(10000).reshape(100, 100),
                         legend='img2',
                         origin=(0, 100))
    window.setStats(STATS)

    # add some couple (plotItem, roi) to be displayed by default
    img1_item = window.plot.getImage('img1')
    img2_item = window.plot.getImage('img2')
    window.addItem(item=img2_item, roi=rectangle_roi)
    window.addItem(item=img1_item, roi=polygon_roi)
    window.addItem(item=img1_item, roi=arc_roi)

    window.setUpdateMode(mode)

    window.show()
    app.exec()
    updateThread.stop()  # Stop updating the plot
def main():

    app = qt.QApplication([])

    ## load data from data/lena.hdf5
    datapath = 'data/lena.hdf5'
    f = h5py.File(datapath)
    image = numpy.array(f['lena'], dtype='float32')

    showH5ls(datapath)

    plotimage = plotHistogram(image)

    # create a PlotAction which plot the histogram for the current image
    #
    # - using silx.gui.plot.PlotActions.PlotAction
    #
    # - doc@ http://www.silx.org/doc/silx/dev/modules/gui/plot/actions/examples.html
    #

    myaction = ComputeHistogramAction(image)
    ## Add this action into the toolBar of the window
    #  TODO ...
    toolBar = plotimage.toolBar()
    # TODO ...

    # show automatically the histogram when the image change
    #
    # - using plotImage.sigActiveImageChanged.connect(plotHisto)
    # TODO ...

    plotimage.show()
    app.exec_()
def main(argv=None):
    """Display an image from a file in an :class:`ImageView` widget.

    :param argv: list of command line arguments or None (the default)
                 to use sys.argv.
    :type argv: list of str
    :return: Exit status code
    :rtype: int
    :raises IOError: if no image can be loaded from the file
    """
    import argparse
    import os.path

    global app  # QApplication must be global to avoid seg fault on quit
    app = qt.QApplication([])
    sys.excepthook = qt.exceptionHandler

    mainWindow = ScatterView()
    mainWindow.setAttribute(qt.Qt.WA_DeleteOnClose)
    xx, yy, value = createData()
    mainWindow.setData(x=xx, y=yy, value=value)
    mainWindow.show()
    mainWindow.setFocus(qt.Qt.OtherFocusReason)

    return app.exec_()
Exemple #7
0
def example_curve(mode):
    """set up the roi stats example for curves"""
    app = qt.QApplication([])
    roi_1, roi_2 = get_1D_rois()
    window = _RoiStatsDisplayExWindow()
    window.setRois(rois1D=(roi_2, roi_1))

    # define some image and curve
    window.plot.addCurve(x=numpy.linspace(0, 10, 56),
                         y=numpy.arange(56),
                         legend='curve1',
                         color='blue')
    window.plot.addCurve(x=numpy.linspace(0, 10, 56),
                         y=numpy.random.random_sample(size=56),
                         legend='curve2',
                         color='red')

    window.setStats(STATS)

    # add some couple (plotItem, roi) to be displayed by default
    curve1_item = window.plot.getCurve('curve1')
    window.addItem(item=curve1_item, roi=roi_1)
    window.addItem(item=curve1_item, roi=roi_2)
    curve2_item = window.plot.getCurve('curve2')
    window.addItem(item=curve2_item, roi=roi_2)

    window.setUpdateMode(mode)

    window.show()
    app.exec()
Exemple #8
0
def plot_stack(mystack,what="intensity",title0="X",title1="Y",title2="Z"):

    from silx.gui.plot.StackView import StackViewMainWindow
    from silx.gui import qt


    app = qt.QApplication(sys.argv[1:])

    sv = StackViewMainWindow()
    sv.setColormap("jet", autoscale=True)
    if what == "intensity":
        sv.setStack(numpy.absolute(mystack))
    elif what == "real":
        sv.setStack(numpy.real(mystack))
    elif what == "imaginary":
        sv.setStack(numpy.imag(mystack))
    elif what == "phase":
        sv.setStack(numpy.angle(mystack))
    elif what == "phase_deg":
        sv.setStack(numpy.angle(mystack,deg=True))
    else:
        raise Exception("Undefined label "+what)

    sv.setLabels([title0,title1,title2])
    sv.show()

    app.exec_()
def test_Spectrum(withGUI):  # with convenience functions
    import parseq_XES_scan as myapp

    myapp.make_pipeline(withGUI)
    myapp.load_test_data()

    if withGUI:
        from silx.gui import qt
        from parseq.gui.dataTreeModelView import DataTreeView
        MyTreeView = DataTreeView

        app = qt.QApplication(sys.argv)
        node = list(csi.nodes.values())[-1]
        view1 = MyTreeView(node)

        if "qt5" in qt.BINDING.lower():
            from modeltest import ModelTest
            ModelTest(csi.model, view1)

        view1.setWindowTitle("Spectra Tree Model")
        # select the 1st item (it is a group)
        view1.setCurrentIndex(csi.model.index(0))

        view1.show()
        app.exec_()
Exemple #10
0
def main():
    app = qt.QApplication([])

    plot = Plot1D()

    x = numpy.arange(21)
    y = numpy.arange(21)
    plot.addCurve(x=x, y=y, legend='myCurve')
    plot.addCurve(x=x, y=(y + 5), legend='myCurve2')

    plot.setActiveCurve('myCurve')

    plot.addScatter(x=[0, 2, 5, 5, 12, 20],
                    y=[2, 3, 4, 20, 15, 6],
                    value=[5, 6, 7, 10, 90, 20],
                    legend='myScatter')

    stats = [
        ('sum', numpy.sum),
        Integral(),
        (COM(), '{0:.2f}'),
    ]

    plot.getStatsWidget().setStats(stats)
    plot.getStatsWidget().parent().setVisible(True)

    plot.show()
    app.exec_()
Exemple #11
0
def main(filenames):
    app = qt.QApplication([])
    viewer = Viewer()
    for filename in filenames:
        viewer.appendFile(filename)
    viewer.setVisible(True)
    app.exec_()
Exemple #12
0
def main():
    global app
    app = qt.QApplication([])

    # Create the ad hoc window containing a PlotWidget and associated tools
    window = PlotAreaMainWindow(app)
    window.setAttribute(qt.Qt.WA_DeleteOnClose)
    window.setWindowTitle("PlotArea Main Window")
    window.show()

    # Add two plot windows to the plot area.
    window.plotArea.addPlotWindow(plotType='1D')
    window.plotArea.addPlotWindow(plotType='2D')

    plot0 = window.plotArea.getPlotWindow(0)
    plot1 = window.plotArea.getPlotWindow(1)

    # Add an 1D data + 2D image to the plots
    x0 = np.linspace(-10, 10, 200)
    x1 = np.linspace(-10, 5, 150)
    x = np.outer(x0, x1)
    image = np.sin(x) / x
    plot0.addCurve(x0, np.sin(x0) / x0, legend='test curve 0')
    plot0.addCurve(x1, np.sin(x1) / x1 + 0.1, legend='test curve 1')
    plot1.addImage(image)

    app.exec_()
Exemple #13
0
def main(argv):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        '--backend',
        dest="backend",
        action="store",
        default=None,
        help='Set plot backend. Should be "matplotlib" (default) or "opengl"')

    options = parser.parse_args(argv[1:])
    assert options.backend in (None, 'matplotlib', 'opengl')
    qapp = qt.QApplication([])

    plot_std = get_plot_std(backend=options.backend)
    plot_std.show()

    plot_mean = get_plot_mean_baseline(backend=options.backend)
    plot_mean.show()

    plot_stacked_histo = get_plot_stacked_histogram(backend=options.backend)
    plot_stacked_histo.show()

    plot_log = get_plot_log(backend=options.backend)
    plot_log.show()

    qapp.exec()
Exemple #14
0
    def makescreenshot(script_or_module, filename):
        _logger.info('generate screenshot for %s from %s, binding is %s'
                     '' % (filename, script_or_module, qt.BINDING))

        # Probe Qt binding
        if qt.BINDING == 'PyQt4':

            def grabWindow(winID):
                return qt.QPixmap.grabWindow(winID)
        elif qt.BINDING in ('PyQt5', 'PySide2'):

            def grabWindow(winID):
                screen = qt.QApplication.primaryScreen()
                return screen.grabWindow(winID)

        global _count
        _count = 15
        global _TIMEOUT
        _TIMEOUT = 1000.  # in ms
        app = qt.QApplication.instance() or qt.QApplication([])
        _logger.debug('Using Qt bindings: %s', qt)

        def _grabActiveWindowAndClose():
            global _count
            activeWindow = qt.QApplication.activeWindow()
            if activeWindow is not None:
                if activeWindow.isVisible():
                    # hot fix since issue with pySide2 API
                    if qt.BINDING == 'PySide2':
                        pixmap = activeWindow.grab()
                    else:
                        pixmap = grabWindow(activeWindow.winId())
                    saveOK = pixmap.save(filename)
                    if not saveOK:
                        _logger.error('Cannot save snapshot to %s', filename)
                else:
                    _logger.error('activeWindow is not visible.')
                app.quit()
            else:
                _count -= 1
                if _count > 0:
                    # Only restart a timer if everything is OK
                    qt.QTimer.singleShot(_TIMEOUT, _grabActiveWindowAndClose)
                else:
                    app.quit()
                    raise TimeoutError(
                        'Aborted: It took too long to have an active window.')

        script_or_module = os.path.abspath(script_or_module)

        sys.argv = [script_or_module]
        sys.path.append(os.path.abspath(os.path.dirname(script_or_module)))
        qt.QTimer.singleShot(_TIMEOUT, _grabActiveWindowAndClose)
        if sys.version_info < (3, ):
            execfile(script_or_module)
        else:
            with open(script_or_module) as f:
                code = compile(f.read(), script_or_module, 'exec')
                exec(code, globals(), locals())
def test():
    from silx.math.fit import fittheories
    from silx.math.fit import fitmanager
    from silx.math.fit import functions
    from silx.gui.plot.PlotWindow import PlotWindow
    import numpy

    a = qt.QApplication([])

    x = numpy.arange(1000)
    y1 = functions.sum_gauss(x, 100, 400, 100)

    fit = fitmanager.FitManager(x=x, y=y1)

    fitfuns = fittheories.FitTheories()
    fit.addtheory(name="Gaussian",
                  function=functions.sum_gauss,
                  parameters=("height", "peak center", "fwhm"),
                  estimate=fitfuns.estimate_height_position_fwhm)
    fit.settheory('Gaussian')
    fit.configure(
        PositiveFwhmFlag=True,
        PositiveHeightAreaFlag=True,
        AutoFwhm=True,
    )

    # Fit
    fit.estimate()
    fit.runfit()

    w = ParametersTab()
    w.show()
    w.fillFromFit(fit.fit_results, view='Gaussians')

    y2 = functions.sum_splitgauss(x, 100, 400, 100, 40, 10, 600, 50, 500, 80,
                                  850, 10, 50)
    fit.setdata(x=x, y=y2)

    # Define new theory
    fit.addtheory(name="Asymetric gaussian",
                  function=functions.sum_splitgauss,
                  parameters=("height", "peak center", "left fwhm",
                              "right fwhm"),
                  estimate=fitfuns.estimate_splitgauss)
    fit.settheory('Asymetric gaussian')

    # Fit
    fit.estimate()
    fit.runfit()

    w.fillFromFit(fit.fit_results, view='Asymetric gaussians')

    # Plot
    pw = PlotWindow(control=True)
    pw.addCurve(x, y1, "Gaussians")
    pw.addCurve(x, y2, "Asymetric gaussians")
    pw.show()

    a.exec_()
Exemple #16
0
def main():
    app = qt.QApplication([])

    # Create the ad hoc plot widget and change its default colormap
    example = ColormapDialogExample()
    example.show()

    app.exec_()
Exemple #17
0
    def setUpClass(cls):
        """Makes sure Qt is inited"""
        cls._oldExceptionHook = sys.excepthook
        sys.excepthook = cls.exceptionHandler

        # Makes sure a QApplication exists and do it once for all
        if not qt.QApplication.instance():
            cls._qapp = qt.QApplication([])
Exemple #18
0
def main():
    sys.excepthook = logUncaughtExceptions
    app = qt.QApplication([])
    pyFAI.resources.silx_integration()
    widget = CalibrationWindow()
    setup(widget.model())
    widget.setVisible(True)
    app.exec_()
Exemple #19
0
    def fitgui(
        self,
        ylog=False,
        legend="data",
        loadfromfit=False,
        concentrations=True,
        spectra=True,
        environ_elements=None,
    ):
        if self.app is None:
            self.app = qt.QApplication([])
        w = McaAdvancedFit.McaAdvancedFit()

        # Copy mcafit
        x = self.mcafit.xdata0
        y = self.mcafit.ydata0
        w.setData(x, y, legend=legend, xmin=0, xmax=len(y) - 1)
        w.mcafit.configure(self.mcafit.getConfiguration())

        # GUI for fitting
        if ylog:
            w.graphWindow.yLogButton.click()
        w.graphWindow.energyButton.click()
        # w.graphWindow.setGraphYLimits(min(y[y>0]),None)
        w.refreshWidgets()
        w.show()
        result = self.app.exec_()

        # Parse result
        result = {}
        try:
            digestedresult = w.mcafit.digestresult()
        except AttributeError:
            digestedresult = None

        if digestedresult:
            # Load parameters from fit (if you did "load from fit")
            self.miscfromfitresult(digestedresult, out=result)
            if concentrations:
                self.concentrationsfromfitresult(digestedresult, out=result)
            if spectra:
                self.spectrafromfitresult(digestedresult, out=result)
            if loadfromfit:
                config = w.mcafit.getConfiguration()
                if concentrations:
                    self.configadjustconcentrations(config,
                                                    result["lmassfractions"],
                                                    exclude=environ_elements)
                self.loadfrompymca(config=config)
        else:
            if concentrations or spectra:
                result = self.fit(
                    loadfromfit=loadfromfit,
                    concentrations=concentrations,
                    spectra=spectra,
                )

        return result
def test():
    myapp.make_pipeline(withGUI=True)
    myapp.load_test_data()

    app = qt.QApplication(sys.argv)
    mainWindow = CombineSpectraWidget()
    mainWindow.setWindowTitle("Combine")
    mainWindow.show()
    app.exec_()
Exemple #21
0
def test():
    myapp.make_pipeline(withGUI=True)
    app = qt.QApplication(sys.argv)

    dlg = SaveProjectDlg()
    dlg.ready.connect(showRes)
    dlg.open()

    app.exec_()
Exemple #22
0
def main():
    global app
    app = qt.QApplication([])

    # Create the ad hoc window containing a PlotWidget and associated tools
    window = MyPlotWindow()
    window.setAttribute(qt.Qt.WA_DeleteOnClose)
    window.show()
    window.showImage()
    app.exec_()
Exemple #23
0
def main():
    app = qt.QApplication([])
    sys.excepthook = qt.exceptionHandler
    window = FindContours()
    window.generateIsland()
    window.show()
    result = app.exec()
    # remove ending warnings relative to QTimer
    app.deleteLater()
    return result
Exemple #24
0
def main():
    app = qt.QApplication([])

    widget = DataViewerFrame()
    widget.addView(MyColorView(widget))
    widget.setData(Color.GREEN)
    widget.show()
    result = app.exec()
    # remove ending warnings relative to QTimer
    app.deleteLater()
    sys.exit(result)
 def setUpClass(cls):
     cls.app = None
     if sys.platform.startswith('linux') and not os.environ.get(
             'DISPLAY', ''):
         # On linux and no DISPLAY available (e.g., ssh without -X)
         logger.warning(
             'pyFAI.integrate_widget tests disabled (DISPLAY env. variable not set)'
         )
         cls.app = None
     elif qt is not None:
         cls.app = qt.QApplication([])
Exemple #26
0
def create_plot2d():
    from silx.gui.plot import Plot2D
    global app  # QApplication must be global to avoid seg fault on quit
    app = qt.QApplication([])
    plot = Plot2D()  # Create the plot widget
    plot.setAttribute(qt.Qt.WA_DeleteOnClose)
    plot.setKeepDataAspectRatio(
        False)  # To keep aspect ratio between X and Y axes
    plot.show()  # Make the plot widget visible
    plot.setFocus(qt.Qt.OtherFocusReason)
    return plot
Exemple #27
0
def main(filenames):
    app = qt.QApplication([])

    tree = hdf5.Hdf5TreeView()
    tree.setVisible(True)

    model = tree.findHdf5TreeModel()
    for filename in filenames:
        model.insertFile(filename)

    app.exec_()
Exemple #28
0
def main(filenames):
    """
    :param filenames: list of file paths
    """
    app = qt.QApplication([])
    sys.excepthook = qt.exceptionHandler
    window = Hdf5TreeViewExample(filenames)
    window.show()
    result = app.exec_()
    # remove ending warnings relative to QTimer
    app.deleteLater()
    sys.exit(result)
    def setUpClass(cls):
        cls.app = None
        if sys.platform.startswith('linux') and not os.environ.get('DISPLAY', ''):
            # On linux and no DISPLAY available (e.g., ssh without -X)
            logger.warning('pyFAI.integrate_widget tests disabled (DISPLAY env. variable not set)')
            cls.app = None
        elif qt is not None:
            cls.app = qt.QApplication([])

        config = {"poni": UtilsTest.getimage("Pilatus1M.poni")}
        integration_config.normalize(config, inplace=True)
        cls.base_config = config
Exemple #30
0
def qapp(use_gui, xvfb, request):
    _set_qt_binding(request.config.option.qt_binding)

    from silx.gui import qt
    app = qt.QApplication.instance()
    if app is None:
        app = qt.QApplication([])
    try:
        yield app
    finally:
        if app is not None:
            app.closeAllWindows()