Exemplo n.º 1
0
def test():
    """Test"""
    # -- Create QApplication
    import plotpy
    _app = plotpy.qapplication()
    # --    
    imshow(*compute_image())
Exemplo n.º 2
0
def test():
    """Test"""
    # -- Create QApplication
    import plotpy
    _app = plotpy.qapplication()
    # --
    from numpy import linspace, sin
    x = linspace(-10, 10, 200)
    dy = x/100.
    y = sin(sin(sin(x)))    
    x2 = linspace(-10, 10, 20)
    y2 = sin(sin(sin(x2)))
    curve2 = make.curve(x2, y2, color="g", curvestyle="Sticks")
    curve2.setTitle("toto")
    plot(make.curve(x, y, color="b"),
         curve2,
         make.curve(x, sin(2*y), color="r"),
         make.merror(x, y/2, dy),
         make.label("Relative position <b>outside</b>",
                    (x[0], y[0]), (-10, -10), "BR"),
         make.label("Relative position <i>inside</i>",
                    (x[0], y[0]), (10, 10), "TL"),
         make.label("Absolute position", "R", (0, 0), "R"),
         make.legend("TR"),
         make.marker(position=(5., .8), label_cb=lambda x, y: "A = %.2f" % x,
                     markerstyle="|", movable=False)
         )
Exemplo n.º 3
0
def run():
    """Run benchmark"""
    # Print informations banner
    from plotpy import qt
    import plotpy
    qt_lib = {'pyqt': 'PyQt4', 'pyqt5': 'PyQt5', 'pyside': 'PySide'}[qt.API]
    title = "plotpy plot benchmark [%s v%s (Qt v%s), plotpy v%s]" %\
            (qt_lib, qt.__version__, qt.QtCore.__version__, plotpy.__version__)
    print(title)
    print('-' * len(title))
    print()

    import plotpy
    app = plotpy.qapplication()

    # Run benchmarks
    close = True
    for benchmark in (
            CurveBM('Simple curve', 5e6),
            CurveBM('Curve with markers', 2e5, marker="Ellipse",
                    markersize=10),
            CurveBM('Curve with sticks', 1e6, curvestyle="Sticks"),
            ErrorBarBM('Error bar curve (vertical bars only)', 1e4),
            ErrorBarBM('Error bar curve (horizontal and vertical bars)',
                       1e4,
                       dx=True),
            HistogramBM('Simple histogram', 1e6, bins=1e5),
            PColorBM('Polar pcolor', 1e3),
            ImageBM('Simple image', 7e3, interpolation='antialiasing'),
    ):
        benchmark.start(close=close)
    if not close:
        app.exec_()
Exemplo n.º 4
0
def test():
    """Test"""
    # -- Create QApplication
    import plotpy
    _app = plotpy.qapplication()
    # --
    from numpy import linspace, sin
    x = linspace(-10, 10, 200)
    dy = x / 100.
    y = sin(sin(sin(x)))
    x2 = linspace(-10, 10, 20)
    y2 = sin(sin(sin(x2)))
    plot([
        make.curve(x, y, color="b"),
        make.label("Relative position <b>outside</b>", (x[0], y[0]),
                   (-10, -10), "BR"),
    ], [
        make.curve(x2, y2, color="g"),
    ], [
        make.curve(x, sin(2 * y), color="r"),
        make.label("Relative position <i>inside</i>", (x[0], y[0]),
                   (10, 10), "TL"),
    ], [
        make.merror(x, y / 2, dy),
        make.label("Absolute position", "R", (0, 0), "R"),
        make.legend("TR"),
    ])
Exemplo n.º 5
0
def do_mainloop(mainloop):
    global _current_fig
    if not _current_fig:
        print("Warning: must create a figure before showing it", file=sys.stderr)
    elif mainloop:
        app = plotpy.qapplication()
        app.exec_()
Exemplo n.º 6
0
def guifit(x,
           y,
           fitfunc,
           fitparams,
           fitargs=None,
           fitkwargs=None,
           wintitle=None,
           title=None,
           xlabel=None,
           ylabel=None,
           param_cols=1,
           auto_fit=True,
           winsize=None,
           winpos=None):
    """GUI-based curve fitting tool"""
    _app = plotpy.qapplication()
    #    win = FitWidget(wintitle=wintitle, toolbar=True,
    #                    param_cols=param_cols, auto_fit=auto_fit,
    #                    options=dict(title=title, xlabel=xlabel, ylabel=ylabel))
    win = FitDialog(edit=True,
                    wintitle=wintitle,
                    toolbar=True,
                    param_cols=param_cols,
                    auto_fit=auto_fit,
                    options=dict(title=title, xlabel=xlabel, ylabel=ylabel))
    win.set_data(x, y, fitfunc, fitparams, fitargs, fitkwargs)
    if winsize is not None:
        win.resize(*winsize)
    if winpos is not None:
        win.move(*winpos)
    if win.exec_():
        return win.get_values()
Exemplo n.º 7
0
def test():
    """Test"""
    # -- Create QApplication
    import plotpy
    _app = plotpy.qapplication()
    # --
    imshow(IMGFILE)
Exemplo n.º 8
0
 def save(self, fname, format, draft):
     if is_text_string(fname):
         if format == "pdf":
             self.app = plotpy.qapplication()
             if draft:
                 mode = QPrinter.ScreenResolution
             else:
                 mode = QPrinter.HighResolution
             printer = QPrinter(mode)
             printer.setOutputFormat(QPrinter.PdfFormat)
             printer.setOrientation(QPrinter.Landscape)
             printer.setOutputFileName(fname)
             printer.setCreator('plotpy.pyplot')
             self.print_(printer)
         else:
             if self.win is None:
                 self.show()
             if PYQT5:
                 pixmap = self.win.centralWidget().grab()
             else:
                 pixmap = QPixmap.grabWidget(self.win.centralWidget())
             pixmap.save(fname, format.upper())
     else:
         # Buffer
         fd = fname
         assert hasattr(fd, 'write'), "object is not file-like as expected"
         if self.win is None:
             self.show()
         pixmap = QPixmap.grabWidget(self.win.centralWidget())
         buff = QBuffer()
         buff.open(QIODevice.ReadWrite)
         pixmap.save(buff, format.upper())
         fd.write(buff.data())
         buff.close()
         fd.seek(0)
Exemplo n.º 9
0
 def save(self, fname, format, draft):
     if is_text_string(fname):
         if format == "pdf":
             self.app = plotpy.qapplication()
             if draft:
                 mode = QPrinter.ScreenResolution
             else:
                 mode = QPrinter.HighResolution
             printer = QPrinter(mode)
             printer.setOutputFormat(QPrinter.PdfFormat)
             printer.setOrientation(QPrinter.Landscape)
             printer.setOutputFileName(fname)
             printer.setCreator('plotpy.pyplot')
             self.print_(printer)
         else:
             if self.win is None:
                 self.show()
             if PYQT5:
                 pixmap = self.win.centralWidget().grab()
             else:
                 pixmap = QPixmap.grabWidget(self.win.centralWidget())
             pixmap.save(fname, format.upper())
     else:
         # Buffer
         fd = fname
         assert hasattr(fd, 'write'), "object is not file-like as expected"
         if self.win is None:
             self.show()
         pixmap = QPixmap.grabWidget(self.win.centralWidget())
         buff = QBuffer()
         buff.open(QIODevice.ReadWrite)
         pixmap.save(buff, format.upper())
         fd.write(buff.data())
         buff.close()
         fd.seek(0)
Exemplo n.º 10
0
def test():
    """Test"""
    # -- Create QApplication
    import plotpy
    _app = plotpy.qapplication()
    # --
    imshow(*compute_image())
Exemplo n.º 11
0
def run():
    """Run benchmark"""
    # Print informations banner
    from plotpy import qt
    import plotpy
    qt_lib = {'pyqt': 'PyQt4', 'pyqt5': 'PyQt5', 'pyside': 'PySide'}[qt.API]
    title = "plotpy plot benchmark [%s v%s (Qt v%s), plotpy v%s]" %\
            (qt_lib, qt.__version__, qt.QtCore.__version__, plotpy.__version__)
    print(title)
    print('-'*len(title))
    print()

    import plotpy
    app = plotpy.qapplication()
    
    # Run benchmarks
    close = True
    for benchmark in (
          CurveBM('Simple curve', 5e6),
          CurveBM('Curve with markers', 2e5,
                  marker="Ellipse", markersize=10),
          CurveBM('Curve with sticks', 1e6,
                  curvestyle="Sticks"),
          ErrorBarBM('Error bar curve (vertical bars only)', 1e4),
          ErrorBarBM('Error bar curve (horizontal and vertical bars)', 1e4,
                     dx=True),
          HistogramBM('Simple histogram', 1e6, bins=1e5),
          PColorBM('Polar pcolor', 1e3),
          ImageBM('Simple image', 7e3, interpolation='antialiasing'),
                     ):
        benchmark.start(close=close)
    if not close:
        app.exec_()
Exemplo n.º 12
0
def test():
    """Test"""
    # -- Create QApplication
    import plotpy
    _app = plotpy.qapplication()
    # --
    items = compute_quads()+compute_quads3()
    imshow(items)
Exemplo n.º 13
0
def do_mainloop(mainloop):
    global _current_fig
    if not _current_fig:
        print("Warning: must create a figure before showing it",
              file=sys.stderr)
    elif mainloop:
        app = plotpy.qapplication()
        app.exec_()
Exemplo n.º 14
0
def test():
    """Test"""
    # -- Create QApplication
    import plotpy
    app = plotpy.qapplication()
    # --    
    win = Window()
    win.show()
    app.exec_()
Exemplo n.º 15
0
def test():
    """Test"""
    # -- Create QApplication
    import plotpy
    _app = plotpy.qapplication()
    # --
    for func in (compute_image, compute_image_2, compute_image_3):
        img = func()
        print(img.dtype)
        imshow(img)
Exemplo n.º 16
0
 def build_window(self):
     self.app = plotpy.qapplication()
     self.win = Window(wintitle=self.title)
     images = False
     for (i, j), ax in list(self.axes.items()):
         ax.setup_window(i, j, self.win)
         if ax.images:
             images = True
     self.win.add_panels(images=images)
     self.win.register_tools(images=images)
Exemplo n.º 17
0
 def build_window(self):
     self.app = plotpy.qapplication()
     self.win = Window(wintitle=self.title)
     images = False
     for (i, j), ax in list(self.axes.items()):
         ax.setup_window(i, j, self.win)
         if ax.images:
             images = True
     self.win.add_panels(images=images)
     self.win.register_tools(images=images)
Exemplo n.º 18
0
def test():
    """Test"""
    # -- Create QApplication
    import plotpy
    _app = plotpy.qapplication()
    # --
    filename = osp.join(osp.dirname(__file__), "brain.png")
    image = make.image(filename=filename, colormap="bone")
    rect = get_segment(image)
    print("Coordinates:", rect)
    print("Distance:", np.sqrt((rect[2]-rect[0])**2 + (rect[3]-rect[1])**2))
Exemplo n.º 19
0
def test():
    """Test"""
    # -- Create QApplication
    import plotpy
    _app = plotpy.qapplication()
    # --
    filename = osp.join(osp.dirname(__file__), "brain.png")
    win = create_window()
    image = make.image(filename=filename, colormap="bone", alpha_mask=True)
    plot = win.get_plot()
    plot.add_item(image)
    win.exec_()
Exemplo n.º 20
0
def test():
    """Test"""
    # -- Create QApplication
    import plotpy
    _app = plotpy.qapplication()
    # --
    from numpy import linspace, sin
    x = linspace(-10, 10, 1000)
    y = sin(sin(sin(x)))    
    x2 = linspace(-10, 10, 20)
    y2 = sin(sin(sin(x2)))
    print(get_point( (x, y), (x2, y2), (x, sin(2*y)) ))
Exemplo n.º 21
0
def xyimagebug(offset):
    from plotpy.plot import ImageDialog
    from plotpy.builder import make
    import numpy
    import plotpy
    app = plotpy.qapplication()
    data = numpy.random.rand(100, 100)
    x = numpy.arange(100)+offset 
    y = numpy.arange(100)
    image = make.xyimage(x, y, data=data)
    win = ImageDialog()
    plot = win.get_plot()
    plot.add_item(image)
    plot.select_item(image) #this helps in seeing where the image should be
    win.exec_()
Exemplo n.º 22
0
def test():
    """Test"""
    # -- Create QApplication
    import plotpy
    _app = plotpy.qapplication()
    # --
    filename = osp.join(osp.dirname(__file__), "brain.png")
    win = create_window()
    image = make.image(filename=filename, colormap="bone")
    data2 = np.array(image.data.T[200:], copy=True)
    image2 = make.image(data2, title="Modified", alpha_mask=True)
    plot = win.get_plot()
    plot.add_item(image)
    plot.add_item(image2, z=1)
    win.exec_()
Exemplo n.º 23
0
def test():
    """Test"""
    # -- Create QApplication
    import plotpy
    _app = plotpy.qapplication()
    # --
    from plotpy.tests.imagexy import compute_image
    x, y, data = compute_image()
    imshow(x, y, data, filter_area=(-3., -1., 0., 2.), yreverse=False)
    # --
    import os.path as osp, numpy as np
    from plotpy import io
    filename = osp.join(osp.dirname(__file__), "brain.png")
    data = io.imread(filename, to_grayscale=True)
    x = np.linspace(0, 30., data.shape[1])
    y = np.linspace(0, 30., data.shape[0])
    imshow(x, y, data, filter_area=(10, 20, 5, 15))
Exemplo n.º 24
0
def test():
    """Test"""
    # -- Create QApplication
    import plotpy
    _app = plotpy.qapplication()
    # --
    from numpy import linspace, sin
    x = linspace(-10, 10, 1000)+1
    y = sin(sin(sin(x)))+3

    curve = make.curve(x, y, "ab", "b")
    hcursor = make.hcursor(3.2, label='y = %.2f')
    vcursor = make.vcursor(7,  label='x = %.2f')
    vcursor2 = make.vcursor(-1,  label='NOT MOVABLE = %.2f', movable=False)
    xcursor = make.xcursor(-4, 2.5,  label='x = %.2f<br>y = %.2f')
    legend = make.legend("TR")
    plot(curve, hcursor, vcursor, vcursor2, xcursor, legend)
Exemplo n.º 25
0
def test():
    """Test"""
    # -- Create QApplication
    import plotpy
    _app = plotpy.qapplication()
    # --
    import numpy as np
    x = np.linspace(-10, 10, 200)
    y = x * np.exp(-x)
    item = make.curve(x, y, color="b")

    win = CurveDialog()
    plot = win.get_plot()
    plot.add_item(item)
    plot.set_axis_direction("left", True)
    plot.set_axis_direction("bottom", True)
    win.show()
    win.exec_()
Exemplo n.º 26
0
def guifit(x, y, fitfunc, fitparams, fitargs=None, fitkwargs=None,
           wintitle=None, title=None, xlabel=None, ylabel=None,
           param_cols=1, auto_fit=True, winsize=None, winpos=None):
    """GUI-based curve fitting tool"""
    _app = plotpy.qapplication()
#    win = FitWidget(wintitle=wintitle, toolbar=True,
#                    param_cols=param_cols, auto_fit=auto_fit,
#                    options=dict(title=title, xlabel=xlabel, ylabel=ylabel))
    win = FitDialog(edit=True, wintitle=wintitle, toolbar=True,
                    param_cols=param_cols, auto_fit=auto_fit,
                    options=dict(title=title, xlabel=xlabel, ylabel=ylabel))
    win.set_data(x, y, fitfunc, fitparams, fitargs, fitkwargs)
    if winsize is not None:
        win.resize(*winsize)
    if winpos is not None:
        win.move(*winpos)
    if win.exec_():
        return win.get_values()
Exemplo n.º 27
0
def test():
    """Test"""
    # -- Create QApplication
    import plotpy
    _app = plotpy.qapplication()
    # --
    import numpy as np
    x = np.linspace(-10, 10, 200)
    y = x*np.exp(-x)
    item = make.curve(x, y, color="b")
    
    win = CurveDialog()
    plot = win.get_plot()
    plot.add_item(item)
    plot.set_axis_direction("left", True)
    plot.set_axis_direction("bottom", True)
    win.show()
    win.exec_()
Exemplo n.º 28
0
def test():
    """Test"""
    # -- Create QApplication
    import plotpy
    _app = plotpy.qapplication()
    # --
    win = OCSImageDialog(toolbar=True,
                         wintitle="Oblique averaged cross section test")
    win.resize(600, 600)

    #    from plotpy.tests.image import compute_image
    #    data = np.array((compute_image(4000, grid=False)+1)*32e3, dtype=np.uint16)
    #    image = make.maskedimage(data, colormap="bone", show_mask=True)

    filename = osp.join(osp.dirname(__file__), "brain_cylinder.png")
    image = make.maskedimage(filename=filename, colormap="bone")

    plot = win.get_plot()
    plot.add_item(image)
    win.exec_()
Exemplo n.º 29
0
def test():
    """Test"""
    # -- Create QApplication
    import plotpy
    _app = plotpy.qapplication()
    # --    
    filename = osp.join(osp.dirname(__file__), "brain.png")

    win = create_window()
    image1 = make.image(filename=filename, title="Original",
                        alpha_mask=False, colormap='gray')
    data2 = np.array(image1.data.T[200:], copy=True)
    image2 = make.image(data2, title="Modified")#, alpha_mask=True)
    plot = win.get_plot()
    plot.add_item(image1, z=0)
    plot.add_item(image2, z=1)
    plot.set_items_readonly(False)
    image2.set_readonly(True)
    win.get_itemlist_panel().show()
    win.show()
    win.exec_()
Exemplo n.º 30
0
def test():
    """Test"""
    # -- Create QApplication
    import plotpy
    _app = plotpy.qapplication()
    # --
    import numpy as np
    x = np.linspace(1, 10, 200)
    y = np.exp(-x)
    y[0] = 0
    item = make.curve(x, y, color="b")
    item = make.error(x, y, None, y*.23)
    
    win = CurveDialog()
    plot = win.get_plot()
    plot.set_axis_scale("left", "log")
    plot.set_axis_scale("bottom", "log")
#    plot.set_axis_limits("left", 4.53999297625e-05, 22026.4657948)
    plot.add_item(item)
    win.show()
    win.exec_()
Exemplo n.º 31
0
def test():
    """Test"""
    # -- Create QApplication
    import plotpy
    _app = plotpy.qapplication()
    # --    
    filename = osp.join(osp.dirname(__file__), "brain.png")
    image = make.image(filename=filename, title="Original", colormap='gray')
    
    win = ImageDialog(edit=False, toolbar=True, wintitle="Contrast test",
                      options=dict(show_contrast=True))
    plot = win.get_plot()
    plot.add_item(image)
    win.resize(600, 600)
    win.show()
    try:
        plot.save_widget('contrast.png')
    except IOError:
        # Skipping this part of the test 
        # because user has no write permission on current directory
        pass
    win.exec_()
Exemplo n.º 32
0
def test():
    """Test"""
    # -- Create QApplication
    import plotpy
    _app = plotpy.qapplication()
    # --
    from numpy import linspace, sin, trapz
    x = linspace(-10, 10, 1000)
    y = sin(sin(sin(x)))

    curve = make.curve(x, y, "ab", "b")
    range = make.range(-2, 2)
    disp0 = make.range_info_label(range, 'BR', "x = %.1f ± %.1f cm",
                                  title="Range infos")

    disp1 = make.computation(range, "BL", "trapz=%g",
                             curve, lambda x, y: trapz(y, x))

    disp2 = make.computations(range, "TL",
                              [(curve, "min=%.5f", lambda x, y: y.min()),
                               (curve, "max=%.5f", lambda x, y: y.max()),
                               (curve, "avg=%.5f", lambda x, y: y.mean())])
    legend = make.legend("TR")
    plot( curve, range, disp0, disp1, disp2, legend)
Exemplo n.º 33
0
def test():
    """Test"""
    # -- Create QApplication
    import plotpy
    _app = plotpy.qapplication()
    # --
    from numpy import linspace, sin
    x = linspace(-10, 10, 200)
    dy = x/100.
    y = sin(sin(sin(x)))    
    x2 = linspace(-10, 10, 20)
    y2 = sin(sin(sin(x2)))
    plot([make.curve(x, y, color="b"),
          make.label("Relative position <b>outside</b>",
                     (x[0], y[0]), (-10, -10), "BR"),],
         [make.curve(x2, y2, color="g"),
          ],
         [make.curve(x, sin(2*y), color="r"),
          make.label("Relative position <i>inside</i>",
                     (x[0], y[0]), (10, 10), "TL"),],
         [make.merror(x, y/2, dy),
          make.label("Absolute position", "R", (0, 0), "R"),
          make.legend("TR"),]
         )
Exemplo n.º 34
0
from numpy import random, array, dot, concatenate

from plotpy.plot import ImageDialog
from plotpy.builder import make
from plotpy.config import _

def hist2d(X, Y):
    win = ImageDialog(edit=True, toolbar=True,
                      wintitle="2-D Histogram X0=(0,1), X1=(-1,-1)")
    hist2d = make.histogram2D(X, Y, 200, 200)
    curve = make.curve(X[::50], Y[::50],
                       linestyle='', marker='+', title=_("Markers"))
    plot = win.get_plot()
    plot.set_aspect_ratio(lock=False)
    plot.set_antialiasing(False)
    plot.add_item(hist2d)
    plot.add_item(curve)
    plot.set_item_visible(curve, False)
    win.show()
    win.exec_()

if __name__ == "__main__":
    import plotpy
    _app = plotpy.qapplication()
    N = 150000
    m = array([[ 1., .2], [-.2, 3.]])
    X1 = random.normal(0, .3, size=(N, 2))
    X2 = random.normal(0, .3, size=(N, 2))
    X = concatenate((X1+[0, 1.], dot(X2, m)+[-1, -1.])) 
    hist2d(X[:, 0], X[:, 1])
Exemplo n.º 35
0
from plotpy.widgets.fliprotate import FlipRotateDialog, FlipRotateWidget
from plotpy.tests.rotatecrop import imshow, create_test_data

def widget_test(fname, qapp):
    """Test the rotate/crop widget"""
    array0, item = create_test_data(fname)
    widget = FlipRotateWidget(None)
    widget.set_item(item)
    widget.set_parameters(-90, True, False)
    widget.show()
    qapp.exec_()

def dialog_test(fname, interactive=True):
    """Test the rotate/crop dialog"""
    array0, item = create_test_data(fname)
    dlg = FlipRotateDialog(None)
    dlg.set_item(item)
    if dlg.exec_():
        array1 = dlg.output_array
        imshow(array0, title="array0", hold=True)
        imshow(array1, title="array1")


if __name__ == '__main__':
    from plotpy import qapplication
    qapp = qapplication()  # analysis:ignore
    
    widget_test("brain.png", qapp)
    dialog_test(fname="brain.png", interactive=True)
    
Exemplo n.º 36
0
        self.data = io.imread(filename, to_grayscale=True)
        self.show_data(self.data)
        param = ImageParam()
        param.title = filename
        param.height, param.width = self.data.shape
        update_dataset(self.param_gbox.dataset, param)
        self.param_gbox.get()
        self.filter_gbox.setEnabled(True)
        
    def show_data(self, data):
        plot = self.get_plot()
        if self.item is not None:
            self.item.set_data(data)
        else:
            self.item = make.image(data, colormap="gray")
            plot.add_item(self.item, z=0)
        plot.set_active_item(self.item)
        plot.replot()
        
    def apply_filter(self):
        param = self.filter_gbox.dataset
        filterfunc = getattr(scipy.ndimage, param.name)
        data = filterfunc(self.data, param.size)
        self.show_data(data)

if __name__ == "__main__":
    from plotpy import qapplication
    _app = qapplication()
    dlg = ExampleDialog()
    dlg.exec_() # No need to call app.exec_: a dialog box has its own event loop
Exemplo n.º 37
0
    if interactive:
        ok = dlg.exec_()
    else:
        dlg.show()
        dlg.accept()
        ok = True
    if ok:
        array1 = dlg.output_array
        if array0.shape == array1.shape:
            if (array1 == array0).all() and not interactive:
                print("Test passed successfully.")
                return
            imshow(array1-array0, title="array1-array0")
        else:
            print(array0.shape, '-->', array1.shape)
        imshow(array0, title="array0", hold=True)
        imshow(array1, title="array1")


if __name__ == '__main__':
    from plotpy import qapplication
    qapp = qapplication()  # analysis:ignore
    
    multiple_widget_test("brain.png", qapp)

    widget_test("brain.png", qapp)

    dialog_test(fname="brain.png", interactive=False)
#    dialog_test(fname="contrast.png", interactive=False)
    dialog_test(fname="brain.png", interactive=True)