def show(self):
     if self._view is None:
         pg.mkQApp()
         self._view_widget = pg.GraphicsLayoutWidget()
         self._view = self._view_widget.addViewBox(0, 0)
         v = self._view
         cell_ids = sorted(self.cells.keys())
         pos = np.array([self.cells[i].position[:2] for i in cell_ids])
         if len(self.connections) == 0:
             adj = np.empty((0,2), dtype='int')
         else:
             adj = np.array(self.connections) - 1
         colors = []
         for cid in cell_ids:
             cell = self.cells[cid]
             color = [0, 0, 0]
             for i,cre in enumerate(self.cre_types):
                 if cell.labels[cre] == '+':
                     color[i] = 255
             colors.append(color)
         brushes = [pg.mkBrush(c) for c in colors]
         print(pos)
         print(adj)
         print(colors)
         self._graph = pg.GraphItem(pos=pos, adj=adj, size=30, symbolBrush=brushes)
         v.addItem(self._graph)
     self._view_widget.show()
def figure(title = None, background='w'):
    if background == 'w':
        pg.setConfigOption('background', 'w')  # set background to white
        pg.setConfigOption('foreground', 'k')
    pg.mkQApp()
    win = pg.GraphicsWindow(title=title)
    return win
Example #3
0
def main(modelFile=None, weightsFile=None, solverFile=None, filePath=None):
    pg.mkQApp()

    win = MainView(modelFile=modelFile, weightsFile=weightsFile, solverFile=solverFile, directory=filePath)
    win.show()

    if (sys.flags.interactive != 1) or not hasattr(QtCore, "PYQT_VERSION"):
        QtGui.QApplication.instance().exec_()
Example #4
0
def affichage(name, shareddic):
    """ Ploting and Display """
    pg.mkQApp()
    pg.setConfigOptions(antialias=True)  ## this will be expensive for the local plot
    force = pg.SpinBox(value=0, int=True, minStep=1, step=10, bounds=(-128, 128))#QtGui.QLineEdit()
    phase = pg.SpinBox(value=1, minStep=0.1, step=0.1, bounds=(0, 2))#QtGui.QLineEdit()
    freq = pg.SpinBox(value=55, minStep=1, step=1, dec=True, bounds=(0, 900))#QtGui.QLineEdit()
    label = QtGui.QLabel()
    #self.data = data
    #self.fps = fps
    labelf = QtGui.QLabel()
    labelf.setText('Force')
    labelp = QtGui.QLabel()
    labelp.setText('Phase')
    labelfr = QtGui.QLabel()
    labelfr.setText('Frequence')
    lcheck = QtGui.QCheckBox('plot local')
    lcheck.setChecked(True)
    lplt = pg.PlotWidget()
    lplt.setYRange(-45, 45)
    lplt.setTitle('Position')
    fplt = pg.PlotWidget()
    fplt.setYRange(-150, 150)
    fplt.setTitle('Forces')
    fplt.getAxis('bottom').setScale(1.0/RESANG)
    layout = pg.LayoutWidget()
    layout.addWidget(labelf)
    layout.addWidget(labelp)
    layout.addWidget(labelfr)
    layout.addWidget(force, row=2, col=0)
    layout.addWidget(phase, row=2, col=1)
    layout.addWidget(freq, row=2, col=2)
    layout.addWidget(lcheck, row=3, col=0)
    layout.addWidget(label, row=3, col=1)
    layout.addWidget(lplt, row=4, col=0, colspan=3)
    layout.addWidget(fplt, row=5, col=0, colspan=3)
    layout.resize(800, 800)
    layout.setWindowTitle('Timon 12: Demo')
    layout.show()
    def update(shareddic):
        """ Every refresh of the display """
        localdata = [0]*1000
        taille = 0#shareddic['taille']
        localdata = shareddic['data']
        localvitesse = shareddic['vitesse']
        lplt.plot(localdata, clear=True)
        lplt.plot(localvitesse, pen=(0, 0, 255))
        fps = shareddic['fps']
        label.setText("Communication %0.2f Hz Taille buffer: %0.2f" % (fps, taille/3.0))
        force = shareddic['force']
        degre = shareddic['degre']
        forcenow = shareddic['forcenow']
        fplt.plot(range(-ANGLEMAX*RESANG, ANGLEMAX*RESANG), force, clear=True)
        fplt.plot([degre*RESANG], [forcenow], pen=(0, 0, 255), symbolBrush=(255, 0, 0), symbolPen='r')
    timer = QtCore.QTimer()
    timer.timeout.connect(lambda: update(shareddic))
    timer.start(50)
    QtGui.QApplication.instance().exec_()
Example #5
0
  def __init__(self, points, title = None):
    pg.mkQApp();
    self.w = gl.GLViewWidget()
    self.w.opts['distance'] = 20
    self.w.show()
    self.w.setWindowTitle(title)

    self.g = gl.GLGridItem()
    self.w.addItem(self.g)
    self.sp = gl.GLScatterPlotItem(pos=points, color=(1,1,1,1), pxMode= True)
    self.w.addItem(self.sp);
Example #6
0
 def __init__(self, ui, view, parent=None):
   logger.debug('  ImageDisplay::__init__(%s)' % view)
   pg.mkQApp()
   self.COMData = None
   self.CCOMData = None
   self.cData = None
   self.imgData = None
   self.isocurve = 0
   self.overlays = {}
   self.vblist = []
   self.itemList = {
     'COM':[None, True], 
     'Movement':[None, True], 
     'Spiral':[None, True], 
     'spots':[None, True], 
     'TRACK':[None, True], 
     'MASK':[None, True], 
     'CALIBA':[None, True], 
     'CALIBB':[None, True], 
     'ROTATE':[None, True], 
     'INSIDE':[None, True],
     'ISOCURVE':[None, True],
     'SPLOT':[None, False]
     }
   self.overlayDict = dict(COM=None, TRACK=None, MASK=None, CALIBA=None, CALIBB=None, ROTATE=None, SIZE=None)
   self.vb = pg.ViewBox(enableMenu=False)
   self.vb.setAspectLocked()
   self.img = pg.ImageItem()
   #self.img = pg.ImageView()
   self.rotImg = None
   self.rotROI = None
   #self.addDisplayItem('IMG', self.img)
   self.vb.addItem(self.img)
   self.sp = pg.ScatterPlotItem()
   self.addDisplayItem('SPLOT', self.sp)
   self.hist = None
   if view != "Dummy":
     getattr(ui, view).setCentralItem(self.vb)
     #getattr(ui, view).setCentralItem(self.img)
   self.isRendered = False
   self.enabledOverlays = {}
   self.validOverlays = {}
   self.showCOMOverlay = False
   self.mousePos = (0, 0)
   self.saveMouseFlag = False
   #self.maskROI = None
   #self.trackingROI = None
   #self.calibROIa = None
   #self.calibROIb = None
   #print (self.vb.allChildren())
   #pl = self.ui.graphicsView.addPlot()
   #proxy = pg.SignalProxy(pl.scene().sigMouseMoved, rateLimit=60, slot=self.mouseMoved)
   if view != "Dummy":
     self.vb.scene().sigMouseMoved.connect(self.mouseMoved)
Example #7
0
 def testRun(self, title='testing...', initfile=None):
     if initfile is None:
         raise ValueError('generate_run:testRun needs initfile name')
     self._prepareRun(inj=0.0)
     self.run_initialized = cellInit.init_model(self.cell, filename=initfile, restore_from_file=True)
     self.hf.h.t = 0.
     self.hf.h.tstop = 10
     #self.hf.h.run()
     self._executeRun(testPlot=True)
     pg.mkQApp()
     pl = pg.plot(np.array(self.monitor['time']), np.array(self.monitor['postsynapticV']))
     pl.setTitle(title)
     QtGui.QApplication.instance().exec_()
Example #8
0
    def __init__(self, func):

        self.func = func
    
        app = pg.mkQApp()
        self.win = pg.GraphicsWindow(title="Bar learning")
        self.win.resize(800,800)
        self.win.addLabel("Input")
        self.win.addLabel("Feature")
        self.win.nextRow()
        
        box = self.win.addViewBox(lockAspect=True)
        self.input_vis = pg.ImageItem()
        box.addItem(self.input_vis)
        
        box = self.win.addViewBox(lockAspect=True)
        self.feature_vis = pg.ImageItem()
        box.addItem(self.feature_vis)
        self.win.nextRow()
        
        self.win.addLabel("Receptive fields", colspan=2)
        self.win.nextRow()
        box = self.win.addViewBox(lockAspect=True, colspan=2)
        self.rv_vis = pg.ImageItem()
        box.addItem(self.rv_vis)
        
        self.win.show()
Example #9
0
def test_stream_between_local_nodes():
    # create local nodes in QApplication
    app = pg.mkQApp()

    sender = FakeSender()
    stream_spec = dict(protocol = 'tcp', interface = '127.0.0.1', port = '*',
                        transfertmode = 'plaindata', streamtype = 'analogsignal',
                        dtype = 'float32', shape = (-1, 16), compression ='',
                        scale = None, offset = None, units = '' )
    sender.configure(sample_interval = 0.001)
    sender.outputs['signals'].configure(**stream_spec)
    #sender.output.configure(**stream_spec)
    sender.initialize()
    
    receiver = FakeReceiver()
    receiver.configure()
    receiver.inputs['signals'].connect(sender.outputs['signals'])
    #receiver.input.connect(sender.output)
    receiver.initialize()
    
    # start them for a while
    sender.start()
    receiver.start()
    
    def terminate():
        sender.stop()
        receiver.stop()
        app.quit()
        
    timer = QtCore.QTimer(singleShot = True, interval = 3000)
    timer.timeout.connect(terminate)
    timer.start()
    
    app.exec_()
Example #10
0
def test_ThreadPollInput():
    app = pg.mkQApp()
    
    outstream = OutputStream()
    outstream.configure(**stream_spec)
    instream = InputStream()
    instream.connect(outstream)
    
    sender = ThreadSender(output_stream=outstream)
    poller = ThreadPollInput(input_stream=instream, return_data=True)
    
    
    global last_pos
    last_pos= 0
    def on_new_data(pos, arr):
        assert arr.shape==(chunksize, nb_channel)
        global last_pos
        last_pos += chunksize
        assert last_pos==pos
    
    def terminate():
        sender.wait()
        poller.stop()
        poller.wait()
        app.quit()
    
    sender.finished.connect(terminate)
    poller.new_data.connect(on_new_data)
    
    poller.start()
    sender.start()
    
    app.exec_()
Example #11
0
 def __init__(self, hoc, camerapos=[200., 45., 45.],):
     if not isinstance(hoc, HocReader):
         hoc = HocReader(hoc)
     self.hr = hoc
     self.graphics = []
     self.video_file = None
     pg.mkQApp()  # make sure there is a QApplication before instantiating any QWidgets.
     super(HocViewer, self).__init__()
     self.resize(720,720)
     # self.setBackgroundColor(pg.glColor(pg.mkColor(255, 255, 255, 255)))
     # self.setBackgroundColor(pg.glColor(pg.mkColor(0, 0, 0, 0)))
     # color='w'
     # self.setBackgroundColor(color)
     self.show()
     self.setWindowTitle('hocViewer')
     self.setCameraPosition(distance=camerapos[0], elevation=camerapos[1], azimuth=camerapos[2])
Example #12
0
def check_trigger(debounce_time, debounce_mode, targeted_trigs, detected_triggers):
    app = pg.mkQApp()
    
    dev, trigger = setup_nodes()
    trigger.params['debounce_time'] = debounce_time
    trigger.params['debounce_mode'] = debounce_mode
    
    def on_new_trigger(pos, indexes):
        #~ print(pos, indexes)
        detected_triggers.extend(indexes)
    poller = ThreadPollOutput(trigger.output, return_data=True)
    poller.new_data.connect(on_new_trigger)
    
    poller.start()
    trigger.start()
    dev.start()
    
    
    def terminate():
        dev.stop()
        trigger.stop()
        poller.stop()
        poller.wait()
        assert np.array_equal(detected_triggers, targeted_trigs), '{} should be {}'.format(detected_triggers, targeted_trigs)    
        app.quit()
    
    # start for a while
    timer = QtCore.QTimer(singleShot=True, interval=5000)
    timer.timeout.connect(terminate)
    timer.start()
    
    app.exec_()
Example #13
0
def open_catalogue_window():
    dataio = DataIO(dirname='test_peeler')
    catalogueconstructor = CatalogueConstructor(dataio=dataio)
    app = pg.mkQApp()
    win = CatalogueWindow(catalogueconstructor)
    win.show()
    app.exec_()
Example #14
0
def test_eeg_emotiv_direct():
    # Look for emotiv usb device
    all_devices = get_available_devices()
    device_handle = all_devices[0]
    
    # in main App
    app = pg.mkQApp()
    dev = Emotiv(name='Emotiv0')
    dev.configure(device_handle=device_handle)
    dev.outputs['signals'].configure(
        protocol='tcp', interface='127.0.0.1', transfermode='plaindata',)
    dev.outputs['impedances'].configure(
        protocol='tcp', interface='127.0.0.1', transfermode='plaindata',)
    dev.outputs['gyro'].configure(
        protocol='tcp', interface='127.0.0.1', transfermode='plaindata',)
    dev.initialize()
    viewer = QOscilloscope()
    viewer.configure(with_user_dialog=True)
    viewer.input.connect(dev.outputs['signals'])
    viewer.initialize()
    viewer.show()

    dev.start()
    viewer.start()

    def terminate():
        dev.stop()
        app.quit()

    # start for a while
    timer = QtCore.QTimer(singleShot=True, interval=3000)
    timer.timeout.connect(terminate)
    #~ timer.start()

    app.exec_()
Example #15
0
 def pg_setup(self, title=None):
     self.app = pg.mkQApp()
     if title is None:
         wintitle = 'NEURON run plots'
     else:
         wintitle = title
     self.view = pg.GraphicsView()
     self.lo = pg.GraphicsLayout()  #(border=(100,100,100))
     self.view.setCentralItem(self.lo)
     self.view.resize(800, 600)
     self.view.show()
     #self.win = pg.GraphicsWindow(title=wintitle)
     #self.win.show()
     #self.win.resize(800,600)
     #self.win.nextRow()
     #self.GL = pg.GraphicsLayoutWidget(parent=self.win)
     self.lo.addLabel('Cell: {0:s}'.format(title), colspan=9, size='12pt')
     self.plots = {}
     for i in range(1, 6):
         self.plots['p%d' % i] = None
     nr1 = 6
     for i in range(1,nr1+1):
         self.lo.addLayout(row=i, col=10)
     for i in range(1,11):
         self.lo.addLayout(row=nr1+2, col = i)
     self.plots['p1'] = self.lo.addPlot(title="Vsoma", row=1, col=1, rowspan=nr1-2, colspan=9)
     self.plots['Dendrite'] = self.lo.addPlot(title="Vdend", row=nr1-1, col=1, rowspan=1, colspan=9)
     self.plots['Iinj'] = self.lo.addPlot(title="IInj", row=nr1, col=1, rowspan=1, colspan=9)
def pyplotbrain_display_one_ROI_coords(ROI_coords_MNI_coords_file):

    ROI_coords_MNI_coords = np.array(np.loadtxt(ROI_coords_MNI_coords_file),dtype = 'int')
    
    
    print ROI_coords_MNI_coords

    app = pg.mkQApp()


    view = ppb.addView(with_config = True, background_color = (1,0,0))

    view.params['cortical_mesh'] =  'BrainMesh_ICBM152'

    view.plot_mesh()
    
    view.params['cortical_alpha'] =  0.5

    view.change_alpha_mesh()
    
    #view.params['cortical_mesh'] =  'BrainMesh_ICBM152'

    view.add_node(ROI_coords_MNI_coords, color = (1,0,0,.8), size = 4)

    app.exec_()
Example #17
0
    def veiw_commit(self, X, Y):
        """
        .. py:attribute:: veiw_custom()


           :param X: 
           :type X: 
           :param Y: 
           :type Y: 
           :rtype: UNKNOWN

        .. note:: 

        .. todo:: 
        """
        if isinstance(X[0],tuple):
            X = sorted([time.mktime(datetime(*i).timetuple()) for i in X])
        else:
            X = sorted(map(float, X))
        coords = zip(X, Y)
        app = pg.mkQApp()
        pw = pg.PlotWidget(viewBox=self.vb, axisItems={'bottom': self.axis}, enableMenu=False,
            title="PROJECT_NAME git log changes",clickable=True)
        def mouseMoved(pos):
                display_text = pg.TextItem(text='salooom',color=(176,23,31),anchor=pos)
                pw.addItem(display_text)
        pw.plot(X, Y, symbol='o')
        pw.show()
        pw.setWindowTitle('PROJECT_NAME Git Log: customPlot')
        r = pg.PolyLineROI([(0,0), (10,10)])
        pw.addItem(r)
        pw.scene().sigMouseClicked.connect(mouseMoved)
        if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
            QtGui.QApplication.instance().exec_()
Example #18
0
    def plot_trace_list(self, trace_list):

        app = pg.mkQApp()
        app.processEvents()
        ## Putting this at the beginning or end does not have much effect


        win = pg.GraphicsWindow(title="Basic plottting examples")
        win.resize(1000, 600)

        # Enable antialiasing for prettier plots
        pg.setConfigOptions(antialias=True)

        p = win.addPlot(title="x0-x1")

        xy = []
        for trace in trace_list:
            x_array = trace.x_array
            #p.plot(x_array[:, 0:2])
            xy.append(x_array)

        xy_array = np.vstack(xy)
        path = pg.arrayToQPath(xy_array[:, 0], xy_array[:, 1], connect='all')

        item = QtGui.QGraphicsPathItem(path)
        item.setPen(pg.mkPen('w'))
        p.addItem(item)

        #p.show()
        QtGui.QApplication.instance().exec_()
Example #19
0
def test_local_app_in_out():
    # connect Node.output to Node.input
    # so copy inaudio buffer to out audio buffer
    
    app = pg.mkQApp()
    
    dev = PyAudio()
    dev.configure(nb_channel=2, sample_rate=44100.,
                    input_device_index=0, output_device_index=0,
                    format='int16', chunksize=1024)
    dev.output.configure(protocol='tcp', interface='127.0.0.1', transfertmode='plaindata')
    dev.input.connect(dev.output)
    dev.initialize()
    dev.start()
    
    def terminate():
        dev.stop()
        dev.close()
        app.quit()
    
    # start for a while
    timer = QtCore.QTimer(singleShot=True, interval=3000)
    timer.timeout.connect(terminate)
    timer.start()
    app.exec_()
Example #20
0
 def __init__(self):
 
     app = pg.mkQApp()
     self.win = pg.GraphicsWindow(title="Bar learning")
     self.win.resize(800,800)
     self.win.addLabel("Input")
     self.win.addLabel("Feature")
     self.win.nextRow()
     
     box = self.win.addViewBox(lockAspect=True)
     self.input_vis = pg.ImageItem()
     box.addItem(self.input_vis)
     
     box = self.win.addViewBox(lockAspect=True)
     self.feature_vis = pg.ImageItem()
     box.addItem(self.feature_vis)
     self.win.nextRow()
     
     self.win.addLabel("Receptive fields", colspan=2)
     self.win.nextRow()
     box = self.win.addViewBox(lockAspect=True, colspan=2)
     self.rv_vis = pg.ImageItem()
     box.addItem(self.rv_vis)
     
     self.count = 0
     self.update_period = 200 # every 200 input presentations update weight plot
     self.win.show()
Example #21
0
def test_AnalogTrigger_after_stable():
    app = pg.mkQApp()
    
    dev, trigger = setup_nodes()
    trigger.params['debounce_time'] = 0.1
    trigger.params['debounce_mode'] = 'after-stable'
    
    all_triggers = []
    def on_new_trigger(pos, indexes):
        #~ print(pos, indexes)
        all_triggers.extend(indexes)
    poller = ThreadPollOutput(trigger.output)
    poller.new_data.connect(on_new_trigger)
    
    dev.start()
    trigger.start()
    poller.start()
    
    def terminate():
        dev.stop()
        trigger.stop()
        poller.stop()
        poller.wait()
        app.quit()
    
    # start for a while
    timer = QtCore.QTimer(singleShot=True, interval=5000)
    timer.timeout.connect(terminate)
    timer.start()
    
    app.exec_()
    #~ print(all_triggers)
    assert np.array_equal(all_triggers, [1001, 2001,  3025, 4001])
    def __init__(self):

        # create application window
        self._win = pg.GraphicsWindow( title="ATH9K Spectral Scan")
        self._app = QtGui.QApplication.instance()

        if self._app is None:
            #pg.setConfigOption( 'background', 'w')
            #pg.setConfigOption( 'foreground', 'k')
            self._app = pg.mkQApp()

        if self._win is None:
            self._win = pg.GraphicsWindow( title="ATH9K Spectral Scan")
        self._win.clear()

        # create dummy data
        self.f = list(range(0,SPECTRAL_HT20_NUM_BINS,1))
        self.avg = -120*np.ones(SPECTRAL_HT20_NUM_BINS)
        #self.env = -120*np.ones(SPECTRAL_HT20_NUM_BINS)

        # create plot layout
        self._plt = self._win.addPlot(row=1, col=1)
        self._plt.showGrid(x = True, y = True, alpha = 0.3)
        self._plt.setTitle(title = "RX Spectrum")
        self._plt.setLabel('left', 'Receive Power [dBm]')
        self._plt.setLabel('bottom', 'Frequency [MHz]')
        self._plt.enableAutoRange(x = False, y = False)
        self._plt.setXRange(0- 0.25, 55 + 0.25)
        self._plt.setYRange(-120, -40)
        self._plt.clear()
        self._plt.plot(self.f, self.avg, pen=(0, 0, 255))
        #self._plt.plot(self.f, self.env, pen=(255, 0, 0))
        self._app.processEvents()
Example #23
0
def test_mainwindow():
    app = pg.mkQApp()
    spikesorter = get_spikesorter()
    
    win = SpikeSortingWindow(spikesorter)
    win.show()
    
    app.exec_()
Example #24
0
def test_ndviewer():
    app = pg.mkQApp()
    spikesorter = get_spikesorter()
    
    ndscatter = NDScatter(spikesorter)
    ndscatter.show()
    
    app.exec_()
def test_WaveformViewer():
    controller = get_controller()
    
    app = pg.mkQApp()
    waveformviewer = WaveformViewer(controller=controller)
    waveformviewer.show()
    
    app.exec_()
def test_CatalogueTraceViewer():
    controller = get_controller()
    app = pg.mkQApp()
    traceviewer = CatalogueTraceViewer(controller=controller, signal_type = 'processed')
    traceviewer.show()
    traceviewer.resize(800,600)
    
    app.exec_()
def test_cataloguewindow():
    app = pg.mkQApp()
    spikesorter = get_spikesorter()
    
    win = CatalogueWindow(spikesorter)
    win.show()
    
    app.exec_()
Example #28
0
def test_peelerwindow():
    app = pg.mkQApp()
    spikesorter = get_spikesorter()
    
    win = PeelerWindow(spikesorter)
    win.show()
    
    app.exec_()
Example #29
0
    def __init__(self, hoc):
        if not isinstance(hoc, HocReader):
            hoc = HocReader(hoc)
        self.hr = hoc
        pg.mkQApp()  # make sure there is a QApplication before instantiating any QWidgets.
        super(HocViewer, self).__init__()
        self.resize(720,720)
        self.show()
        self.setWindowTitle('hocRender')
        self.setCameraPosition(distance=200., elevation=45., azimuth=45.)

        self.g = gl.GLGridItem()
        self.g.scale(2,2,1)
        self.addItem(self.g)
        
        self.graphics = []
        self.video_file = None
def test_waveformviewer():
    app = pg.mkQApp()
    spikesorter = get_spikesorter()
    
    waveformviewer = WaveformViewer(spikesorter)
    waveformviewer.show()
    
    app.exec_()
"""
Demonstrates the usage of DateAxisItem to display properly-formatted 
timestamps on x-axis which automatically adapt to current zoom level.

"""
import initExample  ## Add path to library (just for examples; you do not need this)

import time
from datetime import datetime, timedelta

import numpy as np
import pyqtgraph as pg
from pyqtgraph.Qt import QtGui

app = pg.mkQApp("DateAxisItem Example")

# Create a plot with a date-time axis
w = pg.PlotWidget(axisItems={'bottom': pg.DateAxisItem()})
w.showGrid(x=True, y=True)

# Plot sin(1/x^2) with timestamps in the last 100 years
now = time.time()
x = np.linspace(2 * np.pi, 1000 * 2 * np.pi, 8301)
w.plot(now - (2 * np.pi / x)**2 * 100 * np.pi * 1e7, np.sin(x), symbol='o')

w.setWindowTitle('pyqtgraph example: DateAxisItem')
w.show()

if __name__ == '__main__':
    pg.exec()
Example #32
0
"""
Optical system design demo
"""

import numpy as np
from optics import *

import pyqtgraph as pg
from pyqtgraph import Point

app = pg.mkQApp("Optics Demo")

w = pg.GraphicsLayoutWidget(show=True, border=0.5)
w.resize(1000, 900)
w.show()

### Curved mirror demo

view = w.addViewBox()
view.setAspectLocked()
#grid = pg.GridItem()
#view.addItem(grid)
view.setRange(pg.QtCore.QRectF(-50, -30, 100, 100))

optics = []
rays = []
m1 = Mirror(r1=-100, pos=(5, 0), d=5, angle=-15)
optics.append(m1)
m2 = Mirror(r1=-70, pos=(-40, 30), d=6, angle=180 - 15)
optics.append(m2)
Example #33
0
"""
This example demonstrates some of the plotting items available in pyqtgraph.
"""

import numpy as np

import pyqtgraph as pg
from pyqtgraph.Qt import QtCore

app = pg.mkQApp("InfiniteLine Example")
win = pg.GraphicsLayoutWidget(show=True, title="Plotting items examples")
win.resize(1000, 600)

# Enable antialiasing for prettier plots
pg.setConfigOptions(antialias=True)

# Create a plot with some random data
p1 = win.addPlot(title="Plot Items example",
                 y=np.random.normal(size=100, scale=10),
                 pen=0.5)
p1.setYRange(-40, 40)

# Add three infinite lines with labels
inf1 = pg.InfiniteLine(movable=True,
                       angle=90,
                       label='x={value:0.2f}',
                       labelOpts={
                           'position': 0.1,
                           'color': (200, 200, 100),
                           'fill': (200, 200, 200, 50),
                           'movable': True
Example #34
0
zoom / pan to inspect any area of a 2D coordinate system. 

This unimaginative example demonstrates the constrution of a ViewBox-based
plot area with axes, very similar to the way PlotItem is built.
"""

## Add path to library (just for examples; you do not need this)
import initExample

## This example uses a ViewBox to create a PlotWidget-like interface

import numpy as np
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg

app = pg.mkQApp("ViewBox Example")
mw = QtGui.QMainWindow()
mw.setWindowTitle('pyqtgraph example: ViewBox')
mw.show()
mw.resize(800, 600)

gv = pg.GraphicsView()
mw.setCentralWidget(gv)
l = QtGui.QGraphicsGridLayout()
l.setHorizontalSpacing(0)
l.setVerticalSpacing(0)

vb = pg.ViewBox()

p1 = pg.PlotDataItem()
vb.addItem(p1)
Example #35
0
# -*- coding: utf-8 -*-
"""
Displays an interactive Koch fractal
"""
import initExample  ## Add path to library (just for examples; you do not need this)

from functools import reduce
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
import numpy as np

app = pg.mkQApp("Fractal Example")

# Set up UI widgets
win = pg.QtGui.QWidget()
win.setWindowTitle('pyqtgraph example: fractal demo')
layout = pg.QtGui.QGridLayout()
win.setLayout(layout)
layout.setContentsMargins(0, 0, 0, 0)
depthLabel = pg.QtGui.QLabel('fractal depth:')
layout.addWidget(depthLabel, 0, 0)
depthSpin = pg.SpinBox(value=5, step=1, bounds=[1, 10], delay=0, int=True)
depthSpin.resize(100, 20)
layout.addWidget(depthSpin, 0, 1)
w = pg.GraphicsLayoutWidget()
layout.addWidget(w, 1, 0, 1, 2)
win.show()

# Set up graphics
v = w.addViewBox()
v.setAspectLocked()
Example #36
0
    cp = None
    _has_cupy = False

parser = argparse.ArgumentParser(description="Benchmark for testing video performance")
parser.add_argument('--cuda', default=False, action='store_true', help="Use CUDA to process on the GPU", dest="cuda")
parser.add_argument('--dtype', default='uint8', choices=['uint8', 'uint16', 'float'], help="Image dtype (uint8, uint16, or float)")
parser.add_argument('--frames', default=3, type=int, help="Number of image frames to generate (default=3)")
parser.add_argument('--image-mode', default='mono', choices=['mono', 'rgb'], help="Image data mode (mono or rgb)", dest='image_mode')
parser.add_argument('--levels', default=None, type=lambda s: tuple([float(x) for x in s.split(',')]), help="min,max levels to scale monochromatic image dynamic range, or rmin,rmax,gmin,gmax,bmin,bmax to scale rgb")
parser.add_argument('--lut', default=False, action='store_true', help="Use color lookup table")
parser.add_argument('--lut-alpha', default=False, action='store_true', help="Use alpha color lookup table", dest='lut_alpha')
parser.add_argument('--size', default='512x512', type=lambda s: tuple([int(x) for x in s.split('x')]), help="WxH image dimensions default='512x512'")
args = parser.parse_args(sys.argv[1:])

#QtGui.QApplication.setGraphicsSystem('raster')
app = pg.mkQApp("Video Speed Test Example")

win = QtGui.QMainWindow()
win.setWindowTitle('pyqtgraph example: VideoSpeedTest')
ui = ui_template.Ui_MainWindow()
ui.setupUi(win)
win.show()

try:
    from pyqtgraph.widgets.RawImageWidget import RawImageGLWidget
except ImportError:
    RawImageGLWidget = None
    ui.rawGLRadio.setEnabled(False)
    ui.rawGLRadio.setText(ui.rawGLRadio.text() + " (OpenGL not available)")
else:
    ui.rawGLImg = RawImageGLWidget()
# -*- coding: utf-8 -*-
"""
Simple example demonstrating a button which displays a colored rectangle
and allows the user to select a new color by clicking on the button.
"""

import initExample ## Add path to library (just for examples; you do not need this)


import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
import numpy as np

app = pg.mkQApp("ColorButton Example")
win = QtGui.QMainWindow()
btn = pg.ColorButton()
win.setCentralWidget(btn)
win.show()
win.setWindowTitle('pyqtgraph example: ColorButton')

def change(btn):
    print("change", btn.color())
def done(btn):
    print("done", btn.color())

btn.sigColorChanging.connect(change)
btn.sigColorChanged.connect(done)

if __name__ == '__main__':
    pg.exec()
Example #38
0
import initExample

import numpy as np
from numpy import linspace
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
from pyqtgraph import MultiPlotWidget
try:
    from pyqtgraph.metaarray import *
except:
    print(
        "MultiPlot is only used with MetaArray for now (and you do not have the metaarray package)"
    )
    exit()

app = pg.mkQApp("MultiPlot Widget Example")
mw = QtGui.QMainWindow()
mw.resize(800, 800)
pw = MultiPlotWidget()
mw.setCentralWidget(pw)
mw.show()

data = np.random.normal(size=(3, 1000)) * np.array([[0.1], [1e-5], [1]])
ma = MetaArray(data,
               info=[{
                   'name':
                   'Signal',
                   'cols': [
                       {
                           'name': 'Col1',
                           'units': 'V'
def main():
    global plotItem, viewBox, pw

    (xMin, xMax, xDelta) = (-5, 5, 0.1)
    x = np.arange(xMin, xMax, xDelta)
    mu = 0.
    sigma = 1.
    y = 1 / (sigma * np.sqrt(2 * np.pi)) * np.exp(-(x - mu)**2 /
                                                  (2 * sigma**2))
    y *= 1000.  # to see the effect of SmartFormat

    mu = 1.0
    sigma = 0.7
    y2 = 1 / (sigma * np.sqrt(2 * np.pi)) * np.exp(-(x - mu)**2 /
                                                   (2 * sigma**2))
    y2 *= 1000.

    pg.setConfigOption('background', 'w')
    pg.setConfigOption('foreground', 'k')
    app = pg.mkQApp()

    win = pg.GraphicsWindow(title="Overlay, 2 log scales")
    win.clear()

    win.addLabel("A figure containing 2 plots", row=1, col=1, colspan=10)
    win.addLabel("A comment", row=2, col=1, colspan=10)

    plotItem = win.addPlot(axisItems={
        'left': SmartFormat(orientation='left'),
        'right': SmartFormat(orientation='right')
    },
                           row=3,
                           col=1)
    plotItem.setLabels(left='axis 1')

    ## create a new ViewBox, link the right axis to its coordinate system
    viewBox = pg.ViewBox()

    plotItem.showAxis('top')
    plotItem.showAxis('right')

    plotItem.scene().addItem(viewBox)
    #
    # Link this axis to a ViewBox, causing its displayed range to
    # match the visible range of the view.
    #
    plotItem.getAxis('right').linkToView(viewBox)
    #
    # link the views x-axis to another view
    #
    viewBox.setXLink(plotItem)
    plotItem.getAxis('right').setLabel('axis2', color='#00ffff')

    updateViews()
    plotItem.vb.sigResized.connect(updateViews)

    plotDataItem = plotItem.plot()
    plotDataItem.setData(x, y)

    dataItem = pg.PlotDataItem(x, y2, pen='#00ffff')
    dataItem.setLogMode(False, True)
    viewBox.addItem(dataItem)

    plotItem.setLogMode(x=False, y=True)

    viewBox.setXRange(-5, 5)
    viewBox.setYRange(-3, 3)

    app.processEvents()
    time.sleep(0.1)
    app.processEvents()

    print "Prtc ",
    sys.stdin.readline()
Example #40
0
# -*- coding: utf-8 -*-
"""
Test programmatically setting log transformation modes.
"""
import initExample  ## Add path to library (just for examples; you do not need this)

import numpy as np
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg

app = pg.mkQApp("Log Axis Example")

w = pg.GraphicsLayoutWidget(show=True)
w.setWindowTitle('pyqtgraph example: logAxis')
p1 = w.addPlot(0, 0, title="X Semilog")
p2 = w.addPlot(1, 0, title="Y Semilog")
p3 = w.addPlot(2, 0, title="XY Log")
p1.showGrid(True, True)
p2.showGrid(True, True)
p3.showGrid(True, True)
p1.setLogMode(True, False)
p2.setLogMode(False, True)
p3.setLogMode(True, True)
w.show()

y = np.random.normal(size=1000)
x = np.linspace(0, 1, 1000)
p1.plot(x, y)
p2.plot(x, y)
p3.plot(x, y)
Example #41
0
#!/usr/bin/python -i
# -*- coding: utf-8 -*-
## Add path to library (just for examples; you do not need this)
import initExample

from pyqtgraph.Qt import QtCore, QtGui
import numpy as np
import pyqtgraph as pg

pg.setConfigOptions(imageAxisOrder='row-major')

## create GUI
app = pg.mkQApp("ROI Types Examples")

w = pg.GraphicsLayoutWidget(show=True, size=(800, 800), border=True)
v = w.addViewBox(colspan=2)
v.invertY(True)  ## Images usually have their Y-axis pointing downward
v.setAspectLocked(True)

## Create image to display
arr = np.ones((100, 100), dtype=float)
arr[45:55, 45:55] = 0
arr[25, :] = 5
arr[:, 25] = 5
arr[75, :] = 5
arr[:, 75] = 5
arr[50, :] = 10
arr[:, 50] = 10

# add an arrow for asymmetry
arr[10, :50] = 10
#!/usr/bin/env python3
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
# pg.setConfigOptions(useOpenGL=True)
app = pg.mkQApp()  # A QtApp must be created before anyting else
from pyqtgraph import mkBrush, mkPen, mkColor
from qtGraph import Graph
import numpy as np
import matplotlib.cm as cm

pg.setConfigOption('background', 'w')  #to change background to white
import time
import fire
import logging
import random


class Play():
    def __init__(self, drawing_log):
        self.drawing_log = drawing_log
        self.Type = {}
        logging.basicConfig(
            format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        self.lg = logging.getLogger(__name__)
        self.lg.setLevel(logging.INFO)

    def get_team_size(self, n):
        return 2**(n - 1).bit_length()

    def get_buffer_size(self):
        team_size = self.get_team_size(
Example #43
0
"""
Simple example of loading UI template created with Qt Designer.

This example uses uic.loadUiType to parse and load the ui at runtime. It is also
possible to pre-compile the .ui file using pyuic (see VideoSpeedTest and 
ScatterPlotSpeedTest examples; these .ui files have been compiled with the
tools/rebuildUi.py script).
"""

import os

import numpy as np

import pyqtgraph as pg

pg.mkQApp()

## Define main window class from template
path = os.path.dirname(os.path.abspath(__file__))
uiFile = os.path.join(path, 'designerExample.ui')
WindowTemplate, TemplateBaseClass = pg.Qt.loadUiType(uiFile)

class MainWindow(TemplateBaseClass):  
    def __init__(self):
        TemplateBaseClass.__init__(self)
        self.setWindowTitle('pyqtgraph example: Qt Designer')
        
        # Create the main window
        self.ui = WindowTemplate()
        self.ui.setupUi(self)
        self.ui.plotBtn.clicked.connect(self.plot)
Example #44
0
                ch_hampeled = hampel(csi_todo[:, ch],
                                     window_size=winsize_hampel,
                                     n=3)[0]
                csi_hampeled.append(ch_hampeled)
            csi_hampeled = np.asarray(csi_hampeled).T
            csi_array = np.vstack(
                [csi_array, csi_hampeled[winsize_hampel:-winsize_hampel, :]])

            # print(f'filtered {todo_num} data!')
            hampeled_num += todo_num

        f_src.close()

        return lines_done

    app = pg.mkQApp("CSI Monitor")
    #mw = QtGui.QMainWindow()
    #mw.resize(800,800)

    win = pg.GraphicsLayoutWidget(show=True, title="CSI Monitor Window")
    win.resize(900, 600)
    win.setWindowTitle('Wifi-CSI')

    # Enable antialiasing for prettier plots
    pg.setConfigOptions(antialias=True)

    ROW, COLUMN = 5, 4
    plot_nums = ROW * COLUMN

    # plots = []
    curves = []
Example #45
0
"""
SVG export test
"""
import pyqtgraph as pg
import pyqtgraph.exporters
app = pg.mkQApp()


def test_plotscene():
    pg.setConfigOption('foreground', (0, 0, 0))
    w = pg.GraphicsWindow()
    w.show()
    p1 = w.addPlot()
    p2 = w.addPlot()
    p1.plot([1, 3, 2, 3, 1, 6, 9, 8, 4, 2, 3, 5, 3], pen={'color': 'k'})
    p1.setXRange(0, 5)
    p2.plot([1, 5, 2, 3, 4, 6, 1, 2, 4, 2, 3, 5, 3],
            pen={
                'color': 'k',
                'cosmetic': False,
                'width': 0.3
            })
    app.processEvents()
    app.processEvents()

    ex = pg.exporters.SVGExporter(w.scene())
    ex.export(fileName='test.svg')


def test_simple():
    scene = pg.QtGui.QGraphicsScene()
Example #46
0
"""
import initExample ## Add path to library (just for examples; you do not need this)

import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
import numpy as np

win = pg.GraphicsLayoutWidget(show=True)
win.resize(800,350)
win.setWindowTitle('pyqtgraph example: Histogram')
plt1 = win.addPlot()
plt2 = win.addPlot()

## make interesting distribution of values
vals = np.hstack([np.random.normal(size=500), np.random.normal(size=260, loc=4)])

## compute standard histogram
y,x = np.histogram(vals, bins=np.linspace(-3, 8, 40))

## Using stepMode="center" causes the plot to draw two lines for each sample.
## notice that len(x) == len(y)+1
plt1.plot(x, y, stepMode="center", fillLevel=0, fillOutline=True, brush=(0,0,255,150))

## Now draw all points as a nicely-spaced scatter plot
y = pg.pseudoScatter(vals, spacing=0.15)
#plt2.plot(vals, y, pen=None, symbol='o', symbolSize=5)
plt2.plot(vals, y, pen=None, symbol='o', symbolSize=5, symbolPen=(255,255,255,200), symbolBrush=(0,0,255,150))

if __name__ == '__main__':
    pg.mkQApp().exec_()
Example #47
0
"""
Demonstrate a simple data-slicing task: given 3D data (displayed at top), select 
a 2D plane and interpolate data along that plane to generate a slice image 
(displayed at bottom). 


"""

## Add path to library (just for examples; you do not need this)
import initExample

import numpy as np
from pyqtgraph.Qt import QtCore, QtGui
import pyqtgraph as pg

app = pg.mkQApp("Data Slicing Example")

## Create window with two ImageView widgets
win = QtGui.QMainWindow()
win.resize(800, 800)
win.setWindowTitle('pyqtgraph example: DataSlicing')
cw = QtGui.QWidget()
win.setCentralWidget(cw)
l = QtGui.QGridLayout()
cw.setLayout(l)
imv1 = pg.ImageView()
imv2 = pg.ImageView()
l.addWidget(imv1, 0, 0)
l.addWidget(imv2, 1, 0)
win.show()
Example #48
0
# -*- coding: utf-8 -*-
"""
Simple examples demonstrating the use of GLMeshItem.

"""

## Add path to library (just for examples; you do not need this)
import initExample

from pyqtgraph.Qt import QtCore, QtGui
import pyqtgraph as pg
import pyqtgraph.opengl as gl

app = pg.mkQApp("GLMeshItem Example")
w = gl.GLViewWidget()
w.show()
w.setWindowTitle('pyqtgraph example: GLMeshItem')
w.setCameraPosition(distance=40)

g = gl.GLGridItem()
g.scale(2,2,1)
w.addItem(g)

import numpy as np


## Example 1:
## Array of vertex positions and array of vertex indexes defining faces
## Colors are specified per-face

verts = np.array([
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Test the speed of rapidly updating multiple plot curves
"""

## Add path to library (just for examples; you do not need this)
import initExample

from pyqtgraph.Qt import QtGui, QtCore
import numpy as np
import pyqtgraph as pg
from pyqtgraph.ptime import time
app = pg.mkQApp("MultiPlot Speed Test")

plot = pg.plot()
plot.setWindowTitle('pyqtgraph example: MultiPlotSpeedTest')
plot.setLabel('bottom', 'Index', units='B')

nPlots = 100
nSamples = 500
curves = []
for idx in range(nPlots):
    curve = pg.PlotCurveItem(pen=(idx, nPlots * 1.3))
    plot.addItem(curve)
    curve.setPos(0, idx * 6)
    curves.append(curve)

plot.setYRange(0, nPlots * 6)
plot.setXRange(0, nSamples)
plot.resize(600, 900)
Example #50
0
"""
Demonstrate the use of layouts to control placement of multiple plots / views /
labels


"""

## Add path to library (just for examples; you do not need this)
import initExample

from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
import numpy as np

app = pg.mkQApp("Gradiant Layout Example")
view = pg.GraphicsView()
l = pg.GraphicsLayout(border=(100, 100, 100))
view.setCentralItem(l)
view.show()
view.setWindowTitle('pyqtgraph example: GraphicsLayout')
view.resize(800, 600)

## Title at top
text = """
This example demonstrates the use of GraphicsLayout to arrange items in a grid.<br>
The items added to the layout must be subclasses of QGraphicsWidget (this includes <br>
PlotItem, ViewBox, LabelItem, and GrphicsLayout itself).
"""
l.addLabel(text, col=1, colspan=4)
l.nextRow()
Example #51
0
# -*- coding: utf-8 -*-
"""
Simple demonstration of TreeWidget, which is an extension of QTreeWidget
that allows widgets to be added and dragged within the tree more easily.
"""
import initExample  ## Add path to library (just for examples; you do not need this)

import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
import numpy as np

app = pg.mkQApp("TreeWidget Example")

w = pg.TreeWidget()
w.setColumnCount(2)
w.show()
w.setWindowTitle('pyqtgraph example: TreeWidget')

i1 = QtGui.QTreeWidgetItem(["Item 1"])
i11 = QtGui.QTreeWidgetItem(["Item 1.1"])
i12 = QtGui.QTreeWidgetItem(["Item 1.2"])
i2 = QtGui.QTreeWidgetItem(["Item 2"])
i21 = QtGui.QTreeWidgetItem(["Item 2.1"])
i211 = pg.TreeWidgetItem(["Item 2.1.1"])
i212 = pg.TreeWidgetItem(["Item 2.1.2"])
i22 = pg.TreeWidgetItem(["Item 2.2"])
i3 = pg.TreeWidgetItem(["Item 3"])
i4 = pg.TreeWidgetItem(["Item 4"])
i5 = pg.TreeWidgetItem(["Item 5"])
b5 = QtGui.QPushButton('Button')
i5.setWidget(1, b5)
Example #52
0
# -*- coding: utf-8 -*-
"""
This example uses the isosurface function to convert a scalar field
(a hydrogen orbital) into a mesh for 3D display.
"""

## Add path to library (just for examples; you do not need this)
import initExample

from pyqtgraph.Qt import QtCore, QtGui
import pyqtgraph as pg
import pyqtgraph.opengl as gl

app = pg.mkQApp("GLIsosurface Example")
w = gl.GLViewWidget()
w.show()
w.setWindowTitle('pyqtgraph example: GLIsosurface')

w.setCameraPosition(distance=40)

g = gl.GLGridItem()
g.scale(2, 2, 1)
w.addItem(g)

import numpy as np


## Define a scalar field from which we will generate an isosurface
def psi(i, j, k, offset=(25, 25, 50)):
    x = i - offset[0]
    y = j - offset[1]
Example #53
0
# -*- coding: utf-8 -*-
## Add path to library (just for examples; you do not need this)
import initExample

from pyqtgraph.Qt import QtCore, QtGui
import pyqtgraph as pg
from pyqtgraph.GraphicsScene import GraphicsScene

app = pg.mkQApp("GraphicsScene Example")
win = pg.GraphicsView()
win.show()


class Obj(QtGui.QGraphicsObject):
    def __init__(self):
        QtGui.QGraphicsObject.__init__(self)
        GraphicsScene.registerObject(self)

    def paint(self, p, *args):
        p.setPen(pg.mkPen(200, 200, 200))
        p.drawRect(self.boundingRect())

    def boundingRect(self):
        return QtCore.QRectF(0, 0, 20, 20)

    def mouseClickEvent(self, ev):
        if ev.double():
            print("double click")
        else:
            print("click")
        ev.accept()
Example #54
0
  2. A combination histogram and gradient editor (HistogramLUTItem) for
     controlling the visual appearance of the image
  3. A timeline for selecting the currently displayed frame (for 3D data only).
  4. Tools for very basic analysis of image data (see ROI and Norm buttons)

"""

import numpy as np

import pyqtgraph as pg
from pyqtgraph.Qt import QtWidgets

# Interpret image data as row-major instead of col-major
pg.setConfigOptions(imageAxisOrder='row-major')

app = pg.mkQApp("ImageView Example")

## Create window with ImageView widget
win = QtWidgets.QMainWindow()
win.resize(800, 800)
imv = pg.ImageView()
win.setCentralWidget(imv)
win.show()
win.setWindowTitle('pyqtgraph example: ImageView')

## Create random 3D data set with time varying signals
dataRed = np.ones(
    (100, 200, 200)) * np.linspace(90, 150, 100)[:, np.newaxis, np.newaxis]
dataRed += pg.gaussianFilter(np.random.normal(size=(200, 200)), (5, 5)) * 100
dataGrn = np.ones(
    (100, 200, 200)) * np.linspace(90, 180, 100)[:, np.newaxis, np.newaxis]
Example #55
0
def wave(Nt, Nx, Ny, U0, boundary):
    # initialize variables
    U = np.zeros((time_chunks, Nx, Ny))
    U[0, :, :] = U0

    Ut = np.zeros((time_chunks, Nx, Ny))

    # step through time and compute frames to be displayed
    for time_chunk in tqdm(range(1, time_chunks)):
        U_curr = np.zeros((time_chunk_size, Nx, Ny))
        Uxx = np.zeros((time_chunk_size, Nx, Ny))
        Uyy = np.zeros((time_chunk_size, Nx, Ny))
        Ut_curr = np.zeros((time_chunk_size, Nx, Ny))

        U_curr[0, :, :] = U[time_chunk - 1, :, :]
        Ut_curr[0, :, :] = Ut[time_chunk - 1, :, :]

        for t in range(1, time_chunk_size):
            Ut_1 = Ut_curr[t - 1, :, :]

            midpoint = U_curr[t - 1, :, :] + Ut_1 * 0.5 * dt
            curr_time = (time_chunk * time_chunk_size + t) / (Nt / T)
            Utt_k2 = Utt(calc_Uxx(midpoint), calc_Uyy(midpoint), curr_time)

            Ut_curr[t, :, :] = dt * (Utt_k2) + Ut_1
            U_curr[t, :, :] = U_curr[t - 1, :, :] + dt * Ut_curr[t, :, :]

            if boundary:
                U_curr[t, 0, :] *= 0
                U_curr[t, Nx - 1, :] *= 0
                U_curr[t, :, 0] *= 0
                U_curr[t, :, Ny - 1] *= 0

        U[time_chunk, :, :] = U_curr[-1, :, :]
        Ut[time_chunk, :, :] = Ut_curr[-1, :, :]

    app = pg.mkQApp()

    view = gl.GLViewWidget()
    view.show()

    xgrid = gl.GLGridItem()
    ygrid = gl.GLGridItem()
    zgrid = gl.GLGridItem()

    xgrid.rotate(90, 0, 1, 0)
    ygrid.rotate(90, 1, 0, 0)

    colors = np.ones((Nx, Ny, 4)) * U[0, :, :, np.newaxis]
    min_u = np.min(U)
    max_u = np.max(U) - min_u
    colors = (colors - min_u) / max_u

    surface = gl.GLSurfacePlotItem(x=X_values,
                                   y=Y_values,
                                   z=U[0, :, :],
                                   colors=colors)
    view.addItem(surface)

    view.pan(50, 50, 60)

    t = 0

    def update():
        nonlocal t
        colors = np.ones((Nx, Ny, 4)) * U[t, :, :, np.newaxis]
        colors = (colors - min_u) / max_u
        surface.setData(x=X_values, y=Y_values, z=U[t, :, :], colors=colors)
        t += 1
        t %= U.shape[0]

    timer = QtCore.QTimer()
    timer.timeout.connect(update)
    timer.start(30)

    view.pan(-50, -50, -60)
    print(view.cameraPosition())

    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        app.exec_()  # Start QApplication event loop ***
Example #56
0
# -*- coding: utf-8 -*-
"""
Demonstrates use of GLScatterPlotItem with rapidly-updating plots.

"""

## Add path to library (just for examples; you do not need this)
import initExample

import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtGui
import pyqtgraph.opengl as gl
import numpy as np

app = pg.mkQApp("GLScatterPlotItem Example")
w = gl.GLViewWidget()
w.opts['distance'] = 20
w.show()
w.setWindowTitle('pyqtgraph example: GLScatterPlotItem')

g = gl.GLGridItem()
w.addItem(g)

##
##  First example is a set of points with pxMode=False
##  These demonstrate the ability to have points with real size down to a very small scale
##
pos = np.empty((53, 3))
size = np.empty((53))
color = np.empty((53, 4))
pos[0] = (1, 0, 0)
Example #57
0
    def plot3d(self,
               dim="z",
               point_size=1,
               cmap='Spectral_r',
               max_points=5e5,
               n_bin=8,
               plot_trees=False):
        """
        Plots the three dimensional point cloud using a `Qt` backend. By default, if the point cloud exceeds 5e5 \
         points, then it is downsampled using a uniform random distribution. This is for performance purposes.

        :param point_size: The size of the rendered points.
        :param dim: The dimension upon which to color (i.e. "z", "intensity", etc.)
        :param cmap: The matplotlib color map used to color the height distribution.
        :param max_points: The maximum number of points to render.
        """
        from pyqtgraph.Qt import QtCore, QtGui
        import pyqtgraph as pg
        import pyqtgraph.opengl as gl

        # Randomly sample down if too large
        if dim == 'user_data' and plot_trees:
            dim = 'random_id'
            self._set_discrete_color(n_bin, self.data.points['user_data'])
            cmap = self._discrete_cmap(n_bin, base_cmap=cmap)

        if self.data.count > max_points:
            sample_mask = np.random.randint(self.data.count,
                                            size=int(max_points))
            coordinates = np.stack(
                [self.data.points.x, self.data.points.y, self.data.points.z],
                axis=1)[sample_mask, :]

            color_dim = np.copy(self.data.points[dim].iloc[sample_mask].values)
            print("Too many points, down sampling for 3d plot performance.")
        else:
            coordinates = np.stack(
                [self.data.points.x, self.data.points.y, self.data.points.z],
                axis=1)
            color_dim = np.copy(self.data.points[dim].values)

        # If dim is user data (probably TREE ID or some such thing) then we want a discrete colormap
        if dim != 'random_id':
            color_dim = (color_dim - np.min(color_dim)) / (np.max(color_dim) -
                                                           np.min(color_dim))
            cmap = cm.get_cmap(cmap)
            colors = cmap(color_dim)

        else:
            colors = cmap(color_dim)

        # Start Qt app and widget
        pg.mkQApp()
        view = gl.GLViewWidget()

        # Create the points, change to opaque, set size to 1
        points = gl.GLScatterPlotItem(pos=coordinates, color=colors)
        points.setGLOptions('opaque')
        points.setData(size=np.repeat(point_size, len(coordinates)))

        # Add points to the viewer
        view.addItem(points)

        # Center on the arithmetic mean of the point cloud and display
        center = np.mean(coordinates, axis=0)
        view.opts['center'] = pg.Vector(center[0], center[1], center[2])
        # Very ad-hoc
        view.opts['distance'] = (self.data.max[0] - self.data.min[0]) * 1.2
        #return(view.opts)
        view.show()
Example #58
0
def test_streamconverter():
    app = pg.mkQApp()

    stream_spec = dict(protocol='tcp',
                       interface='127.0.0.1',
                       port='*',
                       transfermode='plaindata',
                       streamtype='analogsignal',
                       dtype='float32',
                       shape=(-1, nb_channel),
                       timeaxis=0,
                       compression='',
                       scale=None,
                       offset=None,
                       units='')

    outstream = OutputStream()
    outstream.configure(**stream_spec)
    sender = ThreadSender(output_stream=outstream)

    stream_spec2 = dict(
        protocol='tcp',
        interface='127.0.0.1',
        port='*',
        transfermode='sharedarray',
        streamtype='analogsignal',
        dtype='float32',
        shape=(nb_channel, -1),
        timeaxis=1,
        compression='',
        scale=None,
        offset=None,
        units='',
        sharedarray_shape=(nb_channel, chunksize * 20),
        ring_buffer_method='double',
    )

    conv = StreamConverter()
    conv.configure()
    conv.input.connect(outstream)
    conv.output.configure(**stream_spec2)
    conv.initialize()

    instream = InputStream()
    instream.connect(conv.output)

    global last_pos
    last_pos = 0

    def on_new_data(pos, arr):
        assert arr is None
        global last_pos
        last_pos += chunksize
        assert last_pos == pos

    def terminate():
        sender.wait()
        conv.stop()
        poller.stop()
        poller.wait()
        app.quit()

    poller = ThreadPollInput(input_stream=instream)
    sender.terminated.connect(terminate)
    poller.new_data.connect(on_new_data)

    poller.start()
    conv.start()
    sender.start()

    app.exec_()
Example #59
0
def main():
    app = pg.mkQApp()
    loader = ExampleLoader()
    app.exec_()
Example #60
0
"""
Example demonstrating a variety of scatter plot features.
"""



## Add path to library (just for examples; you do not need this)
import initExample

from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
import numpy as np
from collections import namedtuple
from itertools import chain

app = pg.mkQApp("Scatter Plot Item Example") 
mw = QtGui.QMainWindow()
mw.resize(800,800)
view = pg.GraphicsLayoutWidget()  ## GraphicsView with GraphicsLayout inserted by default
mw.setCentralWidget(view)
mw.show()
mw.setWindowTitle('pyqtgraph example: ScatterPlot')

## create four areas to add plots
w1 = view.addPlot()
w2 = view.addViewBox()
w2.setAspectLocked(True)
view.nextRow()
w3 = view.addPlot()
w4 = view.addPlot()
print("Generating data, this takes a few seconds...")