def get_Resistance(folder, chip, devices, OptionalCurrent=0): ''' Sweep the current from 0 to 3mA and return the resistance. :param Folder: Target folder for data to be saved :param Chip: Target Chip :param Devices: Devices on Target Chip :return: return_measurements_Resistance-I,V,R arrays :return: funkygraphlist-List of abnormal graphs Called By: -Measurement Functions -check_connections -Measure_PCM_Chip_Warm Calls On: -plot_Resistance_Array_live -save_Resistance_data_device -save_data_live ''' # globals- necesarry to avoid automatic deletion of objects global app global windows, plots, curves, my_exporters # get variables inputs = inpfunc.format_input_resistance(devices) cards = inputs[0] channels = inputs[1] # create instance of the app app = QtGui.QApplication.instance() if app is None: app = QtGui.QApplication(sys.argv) else: pass # detect the number of plots need based on the cards, since there is a 1:1 ratio # between devices and cards (%use devices?) num_plots = len(devices) print("num plots: %d" % num_plots) # initialize by opening correct number of windows # each window contains a plot, each plot a curve and they are all stored in arrays curves = initialization(num_plots) # we need two indexes, one for pairs, one for normal index_pairs = 0 index = 0 my_exporters = [] # array to hold exporters # create exporters for i in range(0, num_plots): exporter = exporters.ImageExporter(plots[i].scene()) my_exporters.append(exporter) return_measurements = [] funkygraphlist = [] # take all the sweeps for i in range(0, num_plots): print("Begin Device %s sweep" % (i)) # get two channels and two current limits that are needed my_channels = [] my_channels.append(channels[index_pairs]) my_channels.append(channels[index_pairs + 1]) my_cards = [] my_cards.append(cards[index_pairs]) my_cards.append(cards[index_pairs + 1]) name = ic.create_name(chip, devices[i]) # create the name plots[i].setTitle(name) # set title to name # bring current window to focus windows[i].move( -900, 0) # move to other desktop, spyder had been blocking before windows[i].setWindowState(QtCore.Qt.WindowActive) windows[i].raise_() # this will activate the window (yellow flashing on icon) windows[i].activateWindow() extra_res = 0 if "2x20" in devices[i].name and devices[i].design_id[ 0].name == "PCMRS": extra_res = 138.19 if "10x40" in devices[i].name and devices[i].design_id[ 0].name == "PCMRS": extra_res = 138.37 # sweep the current device max_current = 2e-03 if OptionalCurrent != 0: max_current = OptionalCurrent I, V, R, funkygraphs = rc.plot_Resistance_Array_live( app, curves[i], my_cards[0], my_cards[1], my_channels[0], my_channels[1], max_current, continuity=True, extra_res=extra_res) try: m, b, r2, p, stdev = stats.linregress(I, V) except: m = 1e-09 if funkygraphs: funkygraphlist.append(devices[i].name) if I == 0 and V == 0 and R == 0: return 0, 0 slope = (V[-1] - V[0]) / (I[-1] - I[0]) # Plotting Critical Currents # # arrays that will be returned return_measurements.append(m) # setting labels label = pg.TextItem(text="", color=(0, 0, 0), fill=(255, 0, 0), anchor=(0, -1)) # label text label_text = ("Resistance: %s" % slope) label.setText(label_text) label.setPos(I[int(len(I) / 2)], V[int(len(V) / 2)]) graph = plots[i] graph.addItem(label) new_curve = plots[i].plot() new_curve.setData([I[0], I[-1]], [V[0], V[-1]], symbol='o', symbolBrush='r', pen='r', symbolSize=10) # Saving # filename = (folder + name + "_Resistance.png") print(filename) ic.create_dir(filename) # function to create dir if doesn't exist iv.save_data_live( I, V, R, (folder + name + "_Resistance_raw.dat")) # save the raw data save_Resistance_data_device(slope, (folder + name)) # save the important data try: my_exporters[i].export(filename) # export the graph except: print("Oh no wrapped object was deleted!!!!!") # repeat index = index + 1 index_pairs = index_pairs + 2 app.processEvents() print("End Device %s sweep\n" % (i)) return return_measurements, funkygraphlist
_str = 'Ch' + str(i) + ':' self.chanLabels.append(QtGui.QLabel(text=_str)) def createTempLabels(self): self.tempLabels = [] for i in range(self._numChan): self.tempLabels.append(QtGui.QLabel(text='0.00')) def createLayout(self): lay = QtGui.QGridLayout() for i in range(self._numChan): lay.addWidget(self.chanSelect[i],i,0) lay.addWidget(self.chanLabels[i],i,1) lay.addWidget(self.tempLabels[i],i,2) lay.addWidget(QtGui.QLabel(text=u'\u00b0C'),i,3) return lay def updateChanSelection(self): for i in range(self._numChan): if self.chanSelect[i].isChecked(): self.chanLabels[i].setStyleSheet("color: green") else: self.chanLabels[i].setStyleSheet("color: red") if __name__ == '__main__': app = QtGui.QApplication(sys.argv) test = MainWindow() test.show() app.exec_()
def __init__(self, song): self.app = QtGui.QApplication(sys.argv) self.window = gl.GLViewWidget() self.window.setGeometry(0, 200, 1280, 720) self.window.show() self.window.setWindowTitle('Terrain') self.window.setCameraPosition(distance=28, elevation=2, azimuth=0) self.nstep = 1 self.ypoints1 = [i for i in range(-25, 26, self.nstep)] self.xpoints1 = [i for i in range(-52, -1, self.nstep)] self.ypoints2 = [i for i in range(-25, 26, self.nstep)] self.xpoints2 = [i for i in range(2, 53, self.nstep)] self.nfaces = len(self.ypoints1) self.perlin = OpenSimplex() self.offset = 0 self.beat, self.posbeat = self.BeatMaker(song) self.beatindex = 0 self.color_choice = [{ "R": (117 / 255), "G": (221 / 255), "B": (221 / 255) }, { "R": (25 / 255), "G": (123 / 255), "B": (189 / 255) }, { "R": (11 / 255), "G": (19 / 255), "B": (43 / 255) }, { "R": (144 / 255), "G": (41 / 255), "B": (35 / 255) }, { "R": (144 / 255), "G": (41 / 255), "B": (35 / 255) }] def mesh_init(X, Y, Ampli): verts = np.array([[ x, y, Ampli * self.perlin.noise2d(x=x / 5, y=y / 5 + self.offset) ] for x in X for y in Y], dtype=np.float32) faces = [] colors = [] for m in range(self.nfaces - 1): yoff = m * self.nfaces for n in range(self.nfaces - 1): faces.append([ n + yoff, yoff + n + self.nfaces, yoff + n + self.nfaces + 1 ]) faces.append( [n + yoff, yoff + n + 1, yoff + n + self.nfaces + 1]) colors.append( [int(117 / 255), int(221 / 255), int(221 / 255), 0.78]) colors.append( [int(117 / 255), int(221 / 255), int(221 / 255), 0.8]) return np.array(verts), np.array(faces), np.array(colors) verts1, faces1, colors1 = mesh_init(self.ypoints1, self.xpoints1, 0.2) verts2, faces2, colors2 = mesh_init(self.ypoints2, self.xpoints2, 0.2) self.m1 = gl.GLMeshItem( vertexes=verts1, faces=faces1, faceColors=colors1, smooth=False, drawEdges=False, ) self.m1.setGLOptions('additive') self.window.addItem(self.m1) self.m2 = gl.GLMeshItem( vertexes=verts2, faces=faces2, faceColors=colors2, smooth=False, drawEdges=False, ) self.m2.setGLOptions('additive') self.window.addItem(self.m2)
def __init__(self, song): self.app = QtGui.QApplication(sys.argv) self.window = gl.GLViewWidget() self.window.setGeometry(0, 500, 1280, 720) self.window.show() self.window.setWindowTitle('Terrain') self.window.setCameraPosition(pos=QtGui.QVector3D(0, 0, 0), distance=105, elevation=0, azimuth=90) self.nstep = 1 self.ypoints1 = [i for i in range(-200, 201, self.nstep)] self.xpoints1 = [i for i in range(-10, 11, self.nstep)] self.ypoints2 = [i for i in range(-200, 201, self.nstep)] self.xpoints2 = [i for i in range(-10, 11, self.nstep)] self.nfaces1 = len(self.ypoints1) self.nfaces2 = len(self.xpoints1) self.perlin = OpenSimplex() self.offset = 0 self.beat, self.posbeat = self.BeatMaker(song) self.beatindex = 0 self.t = 0 self.color_choice = [{ "R": (115 / 255), "G": (115 / 255), "B": (115 / 255) }, { "R": (64 / 255), "G": (64 / 255), "B": (64 / 255) }, { "R": (38 / 255), "G": (38 / 255), "B": (38 / 255) }, { "R": (38 / 255), "G": (38 / 255), "B": (38 / 255) }, { "R": (11 / 255), "G": (19 / 255), "B": (43 / 255) }] def mesh_init(X, Y, z, Ampli): verts = np.array([[ x, y, z + Ampli * self.perlin.noise2d(x=x / 5, y=y / 5 + self.offset) ] for x in X for y in Y], dtype=np.float32) # for j in range(0, len(verts)): # if abs(verts[j, 1]) > 20: # verts[j, 2] = 100 faces = [] colors = [] for m in range(self.nfaces2 - 1): yoff = m * self.nfaces2 for n in range(self.nfaces1 - 1): faces.append([ n + yoff, yoff + n + self.nfaces1, yoff + n + self.nfaces1 + 1 ]) faces.append( [n + yoff, yoff + n + 1, yoff + n + self.nfaces1 + 1]) colors.append( [int(117 / 255), int(221 / 255), int(221 / 255), 1]) colors.append( [int(117 / 255), int(221 / 255), int(221 / 255), 1]) return np.array(verts), np.array(faces), np.array(colors) verts1, faces1, colors1 = mesh_init(self.ypoints1, self.xpoints1, 5, 0.2) verts2, faces2, colors2 = mesh_init(self.ypoints2, self.xpoints2, -5, 0.2) self.m1 = gl.GLMeshItem( vertexes=verts1, faces=faces1, faceColors=colors1, smooth=False, drawEdges=False, ) self.m1.setGLOptions('additive') self.window.addItem(self.m1) self.m2 = gl.GLMeshItem( vertexes=verts2, faces=faces2, faceColors=colors2, smooth=False, drawEdges=False, ) self.m2.setGLOptions('additive') self.window.addItem(self.m2)
"""Generation of graphics about Rollin function with pyqtgraph. Graphics will be shown on screen using Qt. """ import os import sys import statistics import numpy as np from pyqtgraph.Qt import QtGui, QtCore import pyqtgraph as pg from rollin import rollin __qtapp__ = QtGui.QApplication([]) pg.setConfigOptions(antialias=True) def init(title): win = pg.GraphicsWindow(title=title) # win.show = lambda: QtGui.QApplication.instance().exec_() plot = win.addPlot(title=title) plot.win = win plot.show = lambda: QtGui.QApplication.instance().exec_() return plot def init_base(title): win = pg.plot() win.setWindowTitle(title) win.show = lambda: QtGui.QApplication.instance().exec_() return win
def main(filepath): app = QtGui.QApplication([]) mw = DataViewerBase(filepath) mw.show() app.exec_()
#!/usr/bin/python # -*- coding: utf-8 -*- import sys from pyqtgraph.Qt import QtGui, QtCore import numpy as np import pyqtgraph as pg from pyqtgraph.ptime import time import serial app = QtGui.QApplication(["Clock Synchronization Offset"]) pg.setConfigOption('background', 'w') pg.setConfigOption('foreground', 'b') pg.setConfigOptions(antialias=True) win = pg.GraphicsWindow(title="Basic plotting examples") win.resize(1920, 1080) win.setWindowTitle('pyqtgraph example: Plotting') p = win.addPlot(title="Slave Clock Offset", pen='k') p.showGrid(x=True, y=True, alpha=0.3) curve = p.plot(pen='b', symbol='o', brush=pg.mkBrush(color='k')) curve1 = p.plot(pen='r') p1 = win.addPlot(title="Clock Offset Std.Deviation") curve2 = p1.plot(pen='g') data = [0] avgdata = [0] stddata = [0] try: serialPort = sys.argv[1]
def __init__(self, show_velocities = False, show_kalman = False, show_ultrasonic = True, show_encoders = True, show_camera = True, show_moving_avg = False, show_complementary = False): self.app = QtGui.QApplication([]) self.win_distance = pg.GraphicsWindow() self.start_time = time.time() # Initialize variables for velocity plotting, Kalman plotting, # the three sensors (ultrasonic, encoders, camera) # and two filters (moving average, complementary) self.show_velocities = show_velocities self.show_kalman = show_kalman self.show_ultrasonic = show_ultrasonic self.show_encoders = show_encoders self.show_camera = show_camera self.show_moving_avg = show_moving_avg self.show_complementary = show_complementary # Create a window for plotting distance and Kalman curves self.win_distance.setWindowTitle('Distance Plotter') if self.show_kalman: self.win_distance.resize(1024, 640) else: self.win_distance.resize(1024, 320) # Create a distance plot from Lab08 distance_plot = self.win_distance.addPlot() distance_plot.setLabel('top', "Distance (mm)") distance_plot.setXRange(-10, 2000) distance_plot.hideAxis('left') distance_plot.hideAxis('top') distance_plot.setAspectLocked() distance_plot.addLegend(offset=(800, 20), labelTextColor=[0, 0, 0, 0], verSpacing=-10, labelTextSize='6pt', colCount=2) # Initialize curves for each sensor on the distance plot if self.show_ultrasonic: self.curve_us = distance_plot.plot([], [], pen=pg.mkPen(width=3, color='r'), brush=pg.mkBrush(radius=10, color='r'), symbol='o', symbolBrush='r', symbolSize=10, name='Ultrasonic') if self.show_encoders: self.curve_enc = distance_plot.plot([], [], pen=pg.mkPen(width=3, color='g'), symbol='o', symbolBrush='g', symbolSize=10, name='Encoders') if self.show_camera: self.curve_cam = distance_plot.plot([], [], pen=pg.mkPen(width=3, color='b'), symbol='o', symbolBrush='b', symbolSize=10, name='Camera') if self.show_moving_avg: self.curve_ma_us = distance_plot.plot([], [], pen=pg.mkPen(width=3, color=1), symbol='o', symbolBrush=1, symbolSize=10, name='US Moving Average') if self.show_complementary: self.curve_compl = distance_plot.plot([], [], pen=pg.mkPen(width=3, color=2), symbol='o', symbolBrush=2, symbolSize=10, name='Complementary') if self.show_kalman: self.curve_kalman = distance_plot.plot([], [], pen=pg.mkPen(width=3, color='w'), symbol='o', symbolBrush='w', symbolSize=10, name='Kalman') # Load a background image of a track img_arr = np.asarray(cv2.cvtColor(cv2.imread('map.png'), cv2.COLOR_BGR2RGB)) img_item = pg.ImageItem(np.rot90(img_arr, -1)) img_item.scale(1.37, 1.37) img_item.setZValue(-100) distance_plot.addItem(img_item) # Create a plot for visualizing velocities according to different sensors if self.show_velocities: # Create the plot background self.win_velocity = pg.GraphicsWindow() self.win_velocity.setWindowTitle('Velocity Plotter') self.win_velocity.resize(640, 320) velocity_plot = self.win_velocity.addPlot() velocity_plot.setLabel('left', "Velocity (mm/s)") velocity_plot.setLabel('bottom', "Time (s)") velocity_plot.addLegend() velocity_plot.setYRange(-200, 200) self.velocity_plot = velocity_plot # Initialize velocity curves for each sensor VEL_INIT_X = list(reversed([ -x*0.1 for x in range(100) ])) VEL_INIT_Y = [0]*100 if self.show_ultrasonic: self.curve_us_vel = velocity_plot.plot(VEL_INIT_X[:], VEL_INIT_Y[:], pen=pg.mkPen(width=1, color='r'), name='Ultrasonic') if self.show_encoders: self.curve_enc_vel = velocity_plot.plot(VEL_INIT_X[:], VEL_INIT_Y[:], pen=pg.mkPen(width=1, color='g'), name='Encoders') if self.show_camera: self.curve_cam_vel = velocity_plot.plot(VEL_INIT_X[:], VEL_INIT_Y[:], pen=pg.mkPen(width=1, color='b'), name='Camera') if self.show_moving_avg: self.curve_ma_us_vel = velocity_plot.plot(VEL_INIT_X[:], VEL_INIT_Y[:], pen=pg.mkPen(width=1, color=1), name='US Moving Average') if self.show_complementary: self.curve_compl_vel = velocity_plot.plot(VEL_INIT_X[:], VEL_INIT_Y[:], pen=pg.mkPen(width=1, color=2), name='Complementary') if self.show_kalman: self.curve_kalman_vel = velocity_plot.plot(VEL_INIT_X[:], VEL_INIT_Y[:], pen=pg.mkPen(width=1, color='w'), name='Kalman') # Create a plot for visualizing Kalman filter behaviour if self.show_kalman: # Create the plot background self.win_distance.nextRow() kalman_plot = self.win_distance.addPlot() kalman_plot.setXRange(-10, 2000) kalman_plot.setYRange(0, 0.02) kalman_plot.hideAxis('left') kalman_plot.addLegend() # Initialize all Gaussian curves gaussian_names_and_colours = [("Camera", 'b'), ("Encoders", 'g'), ("Filtered result", 'w')] self.gaussian_curves = {} for name, color in gaussian_names_and_colours: self.gaussian_curves[name] = kalman_plot.plot([], [], pen=pg.mkPen(width=1, color=color), name=name)
def run(): app = QtGui.QApplication([]) loader = ExampleLoader() app.exec_()
def __init__(self): # pyqtgraph stuff pg.setConfigOptions(antialias=False) self.traces = dict() self.app = QtGui.QApplication(sys.argv) self.win = pg.GraphicsWindow(title='Spectrum Analyzer') self.win.setWindowTitle('Spectrum Analyzer') self.win.setGeometry(5, 115, 1024, 1070) wf_xlabels = [(0, '0'), (2048, '2048'), (4096, '4096')] wf_xaxis = pg.AxisItem(orientation='bottom') wf_xaxis.setTicks([wf_xlabels]) wf_ylabels = [(-16384, '-16384'), (0, '0'), (16384, '16384')] wf_yaxis = pg.AxisItem(orientation='left') wf_yaxis.setTicks([wf_ylabels]) sp_xlabels = [(np.log10(10), '10'), (np.log10(100), '100'), (np.log10(1000), '1000'), (np.log10(22050), '22050')] sp_xaxis = pg.AxisItem(orientation='bottom') sp_xaxis.setTicks([sp_xlabels]) self.waveform = self.win.addPlot( title='WAVEFORM', row=1, col=1, axisItems={ 'bottom': wf_xaxis, 'left': wf_yaxis }, ) self.spectrum = self.win.addPlot( title='SPECTRUM', row=2, col=1, axisItems={'bottom': sp_xaxis}, ) self.amplitude = self.win.addPlot( title='AMPLITUDE', row=3, col=1, ) # pyaudio stuff self.FORMAT = pyaudio.paInt16 self.CHANNELS = 1 self.RATE = 44100 self.CHUNK = 1024 * 2 self.p = pyaudio.PyAudio() self.stream = self.p.open( format=self.FORMAT, channels=self.CHANNELS, rate=self.RATE, input=True, frames_per_buffer=self.CHUNK, ) # waveform and spectrum x points self.x = np.arange(0, 2 * self.CHUNK, 2) self.f = np.linspace(0, self.RATE / 2, self.CHUNK / 2) self.data = [] self.sampleing = False self.thread0 = Thread(target=self.monitor, args=("audio_monitor-0", )) self.thread0.daemon = True self.thread0.start()
def __init__(self, broker_addr="", profile_addr="", graph_name="graph", loop=None): super().__init__() if loop is None: self.app = QtGui.QApplication([]) loop = QEventLoop(self.app) asyncio.set_event_loop(loop) self.ctx = zmq.asyncio.Context() if broker_addr: self.broker = self.ctx.socket(zmq.SUB) self.broker.setsockopt_string(zmq.SUBSCRIBE, 'profiler') self.broker.connect(broker_addr) else: self.broker = None self.graph_name = graph_name self.profile_addr = profile_addr self.profile = self.ctx.socket(zmq.SUB) self.profile.setsockopt_string(zmq.SUBSCRIBE, self.graph_name) self.task = None self.deserializer = Deserializer() self.current_version = 0 self.metadata = {} # {version : metadata} self.parents = set() self.heartbeat_data = {} self.widget = QtWidgets.QWidget() self.layout = QtGui.QGridLayout(self.widget) self.widget.setLayout(self.layout) self.enabled_nodes = {} self.trace_layout = QtGui.QFormLayout(self.widget) hbox = QtWidgets.QHBoxLayout(self.widget) selectAll = QtWidgets.QPushButton("Select All", self.widget) selectAll.clicked.connect(self.selectAll) unselectAll = QtWidgets.QPushButton("Unselect All", self.widget) unselectAll.clicked.connect(self.unselectAll) hbox.addWidget(selectAll) hbox.addWidget(unselectAll) self.trace_layout.addRow(hbox) self.trace_group = WidgetGroup() self.trace_group.sigChanged.connect(self.state_changed) self.layout.addLayout(self.trace_layout, 0, 0, -1, 1) self.graphicsLayoutWidget = pg.GraphicsLayoutWidget() self.layout.addWidget(self.graphicsLayoutWidget, 0, 1, -1, -1) self.time_per_heartbeat = self.graphicsLayoutWidget.addPlot(row=0, col=0) self.time_per_heartbeat.showGrid(True, True) self.time_per_heartbeat.setLabel('bottom', "Heartbeat") self.time_per_heartbeat.setLabel('left', "Time (Sec)") self.time_per_heartbeat_data = collections.defaultdict( lambda: np.array([np.nan] * 100)) self.time_per_heartbeat_traces = {} self.time_per_heartbeat_legend = self.time_per_heartbeat.addLegend() self.heartbeats_per_second = self.graphicsLayoutWidget.addPlot(row=0, col=1) self.heartbeats_per_second.showGrid(True, True) self.heartbeats_per_second.setLabel('bottom', "Heartbeat") self.heartbeats_per_second.setLabel('left', "Heartbeats/Second") self.heartbeats_per_second_data = np.array([np.nan] * 100) self.heartbeats_per_second_trace = None self.percent_per_heartbeat = self.graphicsLayoutWidget.addPlot( row=1, col=0, rowspan=1, colspan=2) self.percent_per_heartbeat.showGrid(True, True) self.percent_per_heartbeat_trace = None self.last_updated = pg.LabelItem( parent=self.time_per_heartbeat.getViewBox()) self.total_heartbeat_time = pg.LabelItem( parent=self.percent_per_heartbeat.getViewBox()) self.heartbeat_per_second = pg.LabelItem( parent=self.heartbeats_per_second.getViewBox()) self.win = ProfilerWindow(self) self.win.setWindowTitle('Profiler') self.win.setCentralWidget(self.widget) self.win.show() with loop: loop.run_until_complete( asyncio.gather(self.process_broker_message(), self.monitor()))
def __init__(self): # オーディオ設定 self.p = pyaudio.PyAudio() self.stream = self.p.open(format=self.FORMAT, channels=self.CHANNELS, rate=self.RATE, output=True, input=True, stream_callback=self.callback, frames_per_buffer=self.CHUNK) # pyqtgraph self.app = QtGui.QApplication([]) self.app.quitOnLastWindowClosed() self.win = QtGui.QMainWindow() self.win.setWindowTitle("SpectrumAnalyzer") self.win.resize(1600, 600) self.centralwid = QtGui.QWidget() self.win.setCentralWidget(self.centralwid) self.lay = QtGui.QVBoxLayout() self.centralwid.setLayout(self.lay) # グラフ1 self.plotwid1 = pg.PlotWidget(name="wave") self.plotitem1 = self.plotwid1.getPlotItem() self.plotitem1.setMouseEnabled(x=False, y=False) #self.plotitem1.setYRange(0, self.SPECTRUM_RANGE)#スペクトル用 #self.plotitem1.setXRange(0, self.RATE / 2, padding = 0) self.plotitem1.setYRange(self.WAVE_RANGE * -1, self.WAVE_RANGE * 1) #波形用 self.plotitem1.setXRange(self.START, self.START + self.N, padding=0) # グラフ2 self.plotwid2 = pg.PlotWidget(name="spectrum") self.plotitem2 = self.plotwid2.getPlotItem() self.plotitem2.setMouseEnabled(x=False, y=False) self.plotitem2.setYRange(0, self.SPECTRUM_RANGE) self.plotitem2.setXRange(0, self.RATE / 1.8, padding=0) # グラフ3 self.plotwid3 = pg.PlotWidget(name="Coloration spectrum") self.plotitem3 = self.plotwid3.getPlotItem() self.plotitem3.setMouseEnabled(x=False, y=False) self.plotitem3.setYRange(0, self.SPECTRUM_RANGE) self.plotitem3.setXRange(0, self.RATE / 1.8, padding=0) # Axis self.specAxis1 = self.plotitem1.getAxis("bottom") self.specAxis1.setLabel("Time [sample]") self.specAxis2 = self.plotitem2.getAxis("bottom") self.specAxis2.setLabel("Frequency [Hz]") self.specAxis3 = self.plotitem3.getAxis("bottom") self.specAxis3.setLabel("Frequency [Hz]") self.curve_wave = self.plotitem1.plot() self.curve_spectrum = self.plotitem2.plot() self.curve_coloration = self.plotitem3.plot() self.lay.addWidget(self.plotwid1) self.lay.addWidget(self.plotwid2) self.lay.addWidget(self.plotwid3) self.win.show() #アップデート self.timer = QtCore.QTimer() self.timer.timeout.connect(self.update) self.timer.start(self.UPDATE_SECOND)
def plot_Ic_Rn_from_type(Wafers, Designs): """ Plots Ic and RN of a certain design type in popup individual windows :param Wafers: Target Wafers :param Designs: Target Designs :Graphs: Ic for Devices and Rn for Devices Called By: - Measurement_GUI_V3 -showData Calls On: - Database V4 -Show_chips_from_wafer -show_devices_from_chip -show_measurements_from_device -Plot Generation -Initialization """ # function to plot all Ic's on same window global app, windows, plots, curves import database_v4 as d # create app instance app = QtGui.QApplication.instance() if app is None: app = QtGui.QApplication(sys.argv) else: pass # create plotting elements initialization(len(Wafers) * 2) for n in range(0, len(Wafers) * 2, 2): all_chips = d.show_chips_from_wafer(Wafers[n]) if not all_chips: print("\nNo chips found, did you enter design name right?") for window in windows: window.close() return -1 chips = [] for i in range(0, len(all_chips)): if all_chips[i].type.name == Designs[n]: chips.append(all_chips[i]) if chips == []: print("\nNo chips found, did you enter design name right?") for window in windows: window.close() return -1 # Ic plot plots[n].setLabel('left', 'Ic', 'A') plots[n].setLabel('bottom', 'Device', '') # Rn Plot plots[n + 1].setLabel('left', 'Rn', 'A') plots[n + 1].setLabel('bottom', 'Device', '') Ic_curves = [] Rn_curves = [] for i in range(0, len(chips)): Ic_curve = plots[n].plot() Ic_curves.append(Ic_curve) Rn_curve = plots[n + 1].plot() Rn_curves.append(Rn_curve) # plot Ic_legend = plots[n].addLegend() plots[n].showGrid(x=True, y=True, alpha=0.3) Rn_legend = plots[n + 1].addLegend() plots[n + 1].showGrid(x=True, y=True, alpha=0.3) num_devices = 20 for i in range(0, len(chips)): devices = d.show_devices_from_chip(chips[i].name) devices = devices[:num_devices] Ics = [] Rns = [] x_axis = [] x_label = [] for j in range(0, len(devices)): # Query database, returns [Ic, Rn] data = d.show_measurements_from_device(chips[i], devices[j]) Ics.append(data[0]) Rns.append(data[1]) x_axis.append(j) x_label.append(devices[j].name) Ic_curves[i].setData(x_axis, Ics, pen=i, symbol='o', symbolBrush=i) Rn_curves[i].setData(x_axis, Rns, pen=i, symbol='o', symbolBrush=i) Ic_legend.addItem(Ic_curves[i], chips[i].name) Rn_legend.addItem(Rn_curves[i], chips[i].name) app.processEvents() x_label = dict(enumerate(x_label)) plots[n].getAxis('bottom').setTicks([x_label.items()]) plots[n].setTitle("%s Ic" % Wafers[n]) plots[n + 1].getAxis('bottom').setTicks([x_label.items()]) plots[n + 1].setTitle("%s Rn" % Wafers[n]) return 0
def plot3D_QT(mgr, xspace, yspace, zspace, pred, opacity=255): """Somewhat buggy pyqtgraph plotting""" from pyqtgraph.Qt import QtCore, QtGui import pyqtgraph.opengl as gl app = QtGui.QApplication([]) w = gl.GLViewWidget() w.opts['distance'] = 200 w.show() # w.setWindowTitle('pyqtgraph example: GLVolumeItem') # print(w.width()) # print(w.height()) # w.setFixedWidth(640) # w.setFixedHeight(480) w.resizeGL(1600, 1200) xname, xgrid = xspace yname, ygrid = yspace zname, zgrid = zspace # Construct spaces support = pred.support xbits = len([bit for bit in support if bv_var_name(bit) == xname]) ybits = len([bit for bit in support if bv_var_name(bit) == yname]) zbits = len([bit for bit in support if bv_var_name(bit) == zname]) xbins = 2**xbits ybins = 2**ybits zbins = 2**zbits # Construct bitmask mask = np.full((xbins, ybins, zbins), False) config = mgr.configure() # pick_iter alters config so save config state for pt in mgr.pick_iter(pred): xvars = [k for k, v in pt.items() if bv_var_name(k) == xname] yvars = [k for k, v in pt.items() if bv_var_name(k) == yname] zvars = [k for k, v in pt.items() if bv_var_name(k) == zname] xvars.sort() # Sort by bit names yvars.sort() zvars.sort() xbv = [pt[bit] for bit in xvars] ybv = [pt[bit] for bit in yvars] zbv = [pt[bit] for bit in zvars] x_idx = bv2int(xbv) if not dynamicperiodic(xgrid) else graytobin(bv2int(xbv)) y_idx = bv2int(ybv) if not dynamicperiodic(ygrid) else graytobin(bv2int(ybv)) z_idx = bv2int(zbv) if not dynamicperiodic(zgrid) else graytobin(bv2int(zbv)) mask[x_idx, y_idx, z_idx] = True d2 = np.empty(mask.shape + (4,), dtype=np.ubyte) d2[..., 0] = mask.astype(np.float) * 255 d2[..., 1] = mask.astype(np.float) * 255 d2[..., 2] = mask.astype(np.float) * 255 d2[..., 3] = mask.astype(np.float) * opacity v = gl.GLVolumeItem(d2, smooth=False) v.translate(-xbins//2, -ybins//2, -zbins//2) w.addItem(v) g = gl.GLGridItem() g.scale(xbins//10, ybins//10, zbins//10) w.addItem(g) ax = gl.GLAxisItem() w.addItem(ax) QtGui.QApplication.instance().exec_() mgr.configure(reordering=config['reordering']) # Reinstate config state
color[int(65536 / mod):, 0] = 0.6 # Set Andromeda halo to even lighter red d_bodies = cuda.to_device(bodies) # Copy the array of body vectors to the gpu '''------------------------------------------------- Parameters -------------------------------------------------''' # Set block and grid dimensions for the GPU blockdim = 32 # Amount of threads per block griddim = int(np.ceil(N / blockdim)) # Amount of blocks # Initialize GPU functions with the given grid and block dimensions leapfrog = leapfrog.configure(griddim, blockdim) # Configure leapfrog function total_acceleration = total_acceleration.configure( griddim, blockdim) # Configure total_acceleration function '''------------------------------------------------ 3D Animation ------------------------------------------------''' app = QtGui.QApplication([]) # Initialize application # Initialize window for the scatter plots w = gl.GLViewWidget() # Initialize opengl widget w.opts['distance'] = 12500 # Set viewing distance to the figure w.show() # Show the figure w.setWindowTitle('N-body simulation') # Set title of the window w.setGeometry(960, 35, 960, 995) # Set window to envelop right side of the screen # Scatter plot of all the bodies sp = gl.GLScatterPlotItem(pos=bodies[:, :3], color=color, size=7) # Set initial frame sp.scale(20, 20, 20) # Scale the plot to match the grids sp.translate(-10, -10, -10) # Translate the plot to match the grids sp.rotate(80, 0, 0, 1)
def main(): global data_q, frameData, dataOk global general_thread_stop_flag # gui related globals global draw_x_y, draw_z_v # thread related globals global main_stop_event today = datetime.datetime.now() # root_dn = 'data/f_data-' + str(today).replace(':', '-').replace(' ', '_') warnings.simplefilter('ignore', np.RankWarning) # START QtAPPfor the plot app = QtGui.QApplication([]) # Set the plot pg.setConfigOption('background', 'w') win = pg.GraphicsWindow(title="2D scatter plot") fig_z_y = win.addPlot() fig_z_y.setXRange(-0.5, 0.5) fig_z_y.setYRange(0, 1.5) fig_z_y.setLabel('left', text='Y position (m)') fig_z_y.setLabel('bottom', text='X position (m)') draw_x_y = fig_z_y.plot([], [], pen=None, symbol='o') # set the processed plot fig_z_v = win.addPlot() fig_z_v.setXRange(-1, 1) fig_z_v.setYRange(-1, 1) fig_z_v.setLabel('left', text='Z position (m)') fig_z_v.setLabel('bottom', text='Doppler (m/s)') draw_z_v = fig_z_v.plot([], [], pen=None, symbol='o') print("Started, input anything in this console and hit enter to stop") # start the prediction thread thread1 = PredictionThread( 1, model=load_model( 'D:/thumouse/trained_models/thuMouse_noAug_349e-3.h5'), timestep=10) thread2 = InputThread(2) thread1.start() thread2.start() while True: dataOk, detObj = update() if dataOk: # Store the current frame into frameData frameData[time.time()] = detObj frameRow = np.asarray( [detObj['x'], detObj['y'], detObj['z'], detObj['doppler']]).transpose() data_q.append( np.expand_dims(preprocess_frame(frameRow, isClipping=False), axis=0)) time.sleep( 0.033) # This is framing frequency Sampling frequency of 30 Hz if pred_stop_flag.is_set(): # set the stop flag for threads pred_thread_stop_flag = True # release sem for threads so that they can stop # wait for other threads to finish thread1.join() thread2.join() # close the plot window win.close() break # Stop sequence print('Stopped')
def __init__(self, plotdirections, plotaccelerations, plotRefreshRate, dt, enablePlotting, scientificplot, boundaryMap): self.app = None self.w = None self.runBtn = None self.quitBtn = None self.togglePlottingBtn = None self.agentPlot = None self.dataPlot = None self.dataCurve = None self.layout = None self.plotdirections = None self.plotaccelerations = None self.plotRefreshRate = None self.enablePlotting = None self.data3 = None self.ptr = None self.running = True self.terminate = False self.plotTime = time.perf_counter() - time.perf_counter() self.data3 = np.empty(100) self.ptr3 = 0 ## Always start by initializing Qt (only once per application) self.app = QtGui.QApplication([]) ## Define a top-level widget to hold everything self.w = QtGui.QWidget() ## Create some widgets to be placed inside self.runBtn = QtGui.QPushButton('Pause') self.quitBtn = QtGui.QPushButton('Quit') self.togglePlottingBtn = QtGui.QPushButton( 'Disable plotting' if enablePlotting else 'Enable plotting') self.quitBtn.clicked.connect(self.onQuit) self.runBtn.clicked.connect(self.toggleRunning) self.togglePlottingBtn.clicked.connect(self.togglePlotting) # Create a PlotWidget which shows position of agents as circles via scatterplotting self.agentPlot = pg.PlotWidget() if scientificplot: self.agentPlot.showGrid(True, True, 0.3) else: self.agentPlot.hideAxis('left') self.agentPlot.hideAxis('bottom') boundaryMapMaxLen = np.max(np.shape(boundaryMap)) self.agentPlot.setXRange(0, boundaryMapMaxLen) self.agentPlot.setYRange(-boundaryMapMaxLen / 2, boundaryMapMaxLen / 2) self.agentPlot.setDownsampling(mode='peak') self.dataPlot = pg.PlotWidget() self.dataPlot.showGrid(True, True, 0.3) self.dataPlot.setDownsampling(mode='peak') self.dataPlot.setClipToView(True) self.dataCurve = self.dataPlot.plot() ## Create a grid layout to manage the widgets size and position self.layout = QtGui.QGridLayout() self.w.setLayout(self.layout) ## Add widgets to the layout in their proper positions self.layout.addWidget(self.runBtn, 0, 0) self.layout.addWidget(self.togglePlottingBtn, 1, 0) self.layout.addWidget(self.quitBtn, 2, 0) self.layout.addWidget(self.agentPlot, 0, 1, 1, 1) # plot goes on right side, spanning 3 rows #self.layout.addWidget(self.dataPlot, 0, 2, 1, 1) self.wallPen = pg.mkPen(color=(100, 100, 100), width=3) self.w.show() self.plotdirections = plotdirections self.plotaccelerations = plotaccelerations self.plotRefreshRate = plotRefreshRate self.enablePlotting = enablePlotting
def main(args): app = QtGui.QApplication([]) mainWindow = MainWindow(args=args) mainWindow.show() sys.exit(app.exec_())
def __init__(self): self.serData = serial_data('/dev/ttyACM0', 57600, 5) self.started = 0 self.freq = 1 self.N = 1000 self.winSize = 1 self.Fs = 250 self.T = 1 / self.Fs self.time = 0.0 self.x = np.arange(0, 3, self.T) self.t = np.zeros(len(self.x)) #Filter stuff self.filtord = 3 #Filtering AC mains fc = 50 f_l = (fc-2)*2/self.Fs f_h = (fc+2)*2/self.Fs self.b, self.a = scisig.butter(self.filtord, [f_l, f_h], btype='bandstop', output='ba') self.zi = scisig.lfilter_zi(self.b, self.a) #Full wave rectifier inteference fc1 = 100 f_l1 = (fc1-2)*2/self.Fs f_h1 = (fc1+2)*2/self.Fs self.b1, self.a1 = scisig.butter(self.filtord, [f_l1, f_h1], btype='bandstop', output='ba') self.zi1 = scisig.lfilter_zi(self.b1, self.a1) #High pass for baseline drift fc2 = 0.2*2/self.Fs self.b2, self.a2 = scisig.butter(self.filtord, fc2, btype='highpass', output='ba') self.zi2 = scisig.lfilter_zi(self.b2, self.a2) self.timer = QtCore.QTimer() self.timer.timeout.connect(self.update) self.traces = dict() self.traces = dict() self.app = QtGui.QApplication(sys.argv) super(Window, self).__init__() self.setGeometry(50, 50, 1000, 700) self.setWindowTitle("Test") self.setWindowIcon(QtGui.QIcon('logo.png')) self.home() extractAction = QtGui.QAction("&Quit", self) extractAction.setShortcut("Ctrl+Q") extractAction.setStatusTip('Exit..') extractAction.triggered.connect(self.close_application) action2 = QtGui.QAction("&Change Title", self) action2.setStatusTip("Change the title...") action2.triggered.connect(self.changeTest) self.statusBar() mainMenu = self.menuBar() mainMenu.setNativeMenuBar(False) fileMenu = mainMenu.addMenu("&File") fileMenu.addAction(extractAction) editMenu = mainMenu.addMenu("&Edit") editMenu.addAction(action2) self.Graphs = QtGui.QWidget() self.layout = QtGui.QVBoxLayout() self.RawSig = pg.PlotWidget(title="Raw Signal") self.FFT = pg.PlotWidget(title="FFT") self.layout.addWidget(self.RawSig) self.layout.addWidget(self.FFT) self.Graphs.setLayout(self.layout) self.setCentralWidget(self.Graphs) self.traces['sin'] = self.RawSig.plot(pen='y') self.traces['FFT'] = self.FFT.plot(pen='y')
def _start(): '''Start the module This uses the global variables from setup and adds a set of global variables ''' global parser, args, config, r, response, patch, monitor, debug, ft_host, ft_port, ft_input, name global channels, winx, winy, winwidth, winheight, window, clipsize, stepsize, lrate, ylim, timeout, hdr_input, start, filtorder, filter, notch, app, win, timeplot, curve, curvemax, plotnr, channr, timer, begsample, endsample # read variables from ini/redis channels = patch.getint('arguments', 'channels', multiple=True) winx = patch.getfloat('display', 'xpos') winy = patch.getfloat('display', 'ypos') winwidth = patch.getfloat('display', 'width') winheight = patch.getfloat('display', 'height') window = patch.getfloat('arguments', 'window', default=5.0) # in seconds clipsize = patch.getfloat('arguments', 'clipsize', default=0.0) # in seconds stepsize = patch.getfloat('arguments', 'stepsize', default=0.1) # in seconds lrate = patch.getfloat('arguments', 'learning_rate', default=0.2) ylim = patch.getfloat('arguments', 'ylim', multiple=True, default=None) # this is the timeout for the FieldTrip buffer timeout = patch.getfloat('fieldtrip', 'timeout', default=30) hdr_input = None start = time.time() while hdr_input is None: monitor.info('Waiting for data to arrive...') if (time.time() - start) > timeout: raise RuntimeError("timeout while waiting for data") time.sleep(0.1) hdr_input = ft_input.getHeader() monitor.info('Data arrived') monitor.debug(hdr_input) monitor.debug(hdr_input.labels) window = int(round(window * hdr_input.fSample)) # in samples clipsize = int(round(clipsize * hdr_input.fSample)) # in samples # lowpass, highpass and bandpass are optional, but mutually exclusive filtorder = 9 if patch.hasitem('arguments', 'bandpass'): filter = patch.getfloat('arguments', 'bandpass', multiple=True) elif patch.hasitem('arguments', 'lowpass'): filter = patch.getfloat('arguments', 'lowpass') filter = [np.nan, filter] elif patch.hasitem('arguments', 'highpass'): filter = patch.getfloat('arguments', 'highpass') filter = [filter, np.nan] else: filter = [np.nan, np.nan] # notch filtering is optional notch = patch.getfloat('arguments', 'notch', default=np.nan) # wait until there is enough data begsample = -1 while begsample < 0: time.sleep(0.1) hdr_input = ft_input.getHeader() if hdr_input != None: begsample = hdr_input.nSamples - window endsample = hdr_input.nSamples - 1 # initialize graphical window app = QtGui.QApplication(sys.argv) win = pg.GraphicsWindow(title="EEGsynth plotsignal") win.setWindowTitle('EEGsynth plotsignal') win.setGeometry(winx, winy, winwidth, winheight) # Enable antialiasing for prettier plots pg.setConfigOptions(antialias=True) # Initialize variables timeplot = [] curve = [] curvemax = [None] * len(channels) # Create panels for each channel for plotnr, channr in enumerate(channels): timeplot.append(win.addPlot(title="%s%s" % ('Channel ', channr))) timeplot[plotnr].setLabel('left', text='Amplitude') timeplot[plotnr].setLabel('bottom', text='Time (s)') curve.append(timeplot[plotnr].plot(pen='w')) win.nextRow() signal.signal(signal.SIGINT, _stop) # Set timer for update timer = QtCore.QTimer() timer.timeout.connect(_loop_once) timer.setInterval(10) # timeout in milliseconds timer.start(int(round(stepsize * 1000))) # stepsize in milliseconds
def __init__(self): self.pnoise = PerlinNoise() self.flying_const = 0.03 self.amplitude = 50.0 self.wlength = 0.1 self.flying = False self.noctaves = 5 self.persistence = 0.4 self.lacunarity = 3.6 self.scale = 40 self.app = QtGui.QApplication(sys.argv) self.w = QtWidgets.QWidget() self.w.resize(800, 600) self.w.setWindowTitle('Perlin Noise') self.layout = QtWidgets.QHBoxLayout() self.layout.setContentsMargins(0, 0, 6, 0) self.gbox_layout = QtWidgets.QFormLayout() self.gbox_layout.setContentsMargins(0, 10, 0, 0) self.options = QtWidgets.QGroupBox() self.options.setFixedWidth(250) self.options.setTitle('Cool things') self.options.setStyleSheet("""QGroupBox::title { subcontrol-origin: margin; top: 10px; left: 7px; padding: 0px 0px 0px 0px; }""") self.options.setLayout(self.gbox_layout) self.label_length = QtWidgets.QLabel() self.label_length.setText('Length(λ):') self.slider_length = QtWidgets.QSlider() self.slider_length.setRange(1, 100) self.slider_length.setOrientation(1) self.slider_length.valueChanged.connect( lambda x: self.set_wlength(x / 100)) self.slider_length.setValue(self.wlength * 100) self.label_amplitude = QtWidgets.QLabel() self.label_amplitude.setText('Amplitude(A):') self.slider_ampl = QtWidgets.QSlider() self.slider_ampl.setRange(0, 100) self.slider_ampl.setOrientation(1) self.slider_ampl.valueChanged.connect( lambda x: self.set_amplitude(x / 10)) self.slider_ampl.setValue(self.amplitude) self.label_flying = QtWidgets.QLabel() self.label_flying.setText('Flying Const(F):') self.slider_fly = QtWidgets.QSlider() self.slider_fly.setRange(0, 100) self.slider_fly.setOrientation(1) self.slider_fly.valueChanged.connect(lambda x: self.set_fly(x / 100)) self.slider_fly.setValue(self.flying_const * 100) self.cb_flying = QtWidgets.QCheckBox() self.cb_flying.setText('Fly Over') self.cb_flying.clicked.connect(self.set_flying) self.button_grad = QtWidgets.QPushButton() self.button_grad.setText('Randomize Gradient Vectors') self.button_grad.clicked.connect(self.pnoise.randomize_grad) self.cb_cosint = QtWidgets.QCheckBox() self.cb_cosint.setText('Cosine Interpolation') self.cb_cosint.clicked.connect(self.pnoise.use_cosinterpol) self.cb_octaves = QtWidgets.QCheckBox() self.cb_octaves.setText('Use Octaves') self.cb_octaves.clicked.connect(self.pnoise.use_octaves) self.label_octaves = QtWidgets.QLabel() self.label_octaves.setText('Octaves:') self.slider_oct = QtWidgets.QSlider() self.slider_oct.setRange(0, 10) self.slider_oct.setOrientation(1) self.slider_oct.valueChanged.connect(lambda x: self.set_octave(x)) self.slider_oct.setValue(self.noctaves) self.label_persistence = QtWidgets.QLabel() self.label_persistence.setText('Persistence:') self.slider_per = QtWidgets.QSlider() self.slider_per.setRange(0, 10) self.slider_per.setOrientation(1) self.slider_per.valueChanged.connect( lambda x: self.set_persistence(x / 10)) self.slider_per.setValue(self.persistence * 10) self.label_lacunarity = QtWidgets.QLabel() self.label_lacunarity.setText('Lacunarity:') self.slider_lac = QtWidgets.QSlider() self.slider_lac.setRange(0, 1000) self.slider_lac.setOrientation(1) self.slider_lac.valueChanged.connect( lambda x: self.set_lacunarity(x / 10)) self.slider_lac.setValue(self.lacunarity * 10) self.label_scale = QtWidgets.QLabel() self.label_scale.setText('Scale:') self.slider_sca = QtWidgets.QSlider() self.slider_sca.setRange(0, 50) self.slider_sca.setOrientation(1) self.slider_sca.valueChanged.connect(lambda x: self.set_scale(x)) self.slider_sca.setValue(self.scale) self.glw = gl.GLViewWidget() self.glw.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) self.glw.setCameraPosition(distance=100, elevation=25, azimuth=45) self.n = 1 self.x = range(0, 70, self.n) self.y = range(0, 70, self.n) self.p_faces = len(self.y) self.fly_inc = 0 v = np.array([[0, 0, 0]]) f = np.array([[0, 0, 0]]) self.mesh = gl.GLMeshItem( vertexes=v, faces=f, smooth=False, drawEdges=True, drawFaces=False, ) self.mesh.setGLOptions('additive') self.glw.addItem(self.mesh) self.layout.addWidget(self.glw) self.layout.addWidget(self.options) self.gbox_layout.addWidget(self.label_length) self.gbox_layout.addWidget(self.slider_length) self.gbox_layout.addWidget(self.label_amplitude) self.gbox_layout.addWidget(self.slider_ampl) self.gbox_layout.addWidget(self.label_flying) self.gbox_layout.addWidget(self.slider_fly) self.gbox_layout.addWidget(self.cb_flying) self.gbox_layout.addWidget(self.button_grad) self.gbox_layout.addWidget(self.cb_octaves) self.gbox_layout.addWidget(self.cb_cosint) self.gbox_layout.addWidget(self.label_octaves) self.gbox_layout.addWidget(self.slider_oct) self.gbox_layout.addWidget(self.label_persistence) self.gbox_layout.addWidget(self.slider_per) self.gbox_layout.addWidget(self.label_lacunarity) self.gbox_layout.addWidget(self.slider_lac) self.gbox_layout.addWidget(self.label_scale) self.gbox_layout.addWidget(self.slider_sca) self.w.setLayout(self.layout) self.w.show()
def main(): app = QtGui.QApplication(sys.argv) mainwin = MainWindow() mainwin.show() sys.exit(app.exec_())
def __init__(self, data_filename, bgimg, delta_video_filename, skip_frames=5): ''' skip_frames - when playing back movie, how many frames to skip between updates (to speed up viewing) ''' self.data_filename = data_filename self.load_data() self.backgroundimg_filename = bgimg self.backgroundimg = None self.binsx = None self.binsy = None trange = np.max(self.pd.time_epoch.values) - np.min( self.pd.time_epoch.values) self.troi = [ np.min(self.pd.time_epoch.values), np.min(self.pd.time_epoch.values) + trange * 0.1 ] self.skip_frames = skip_frames self.path = os.path.dirname(delta_video_filename) # load delta video bag if delta_video_filename != 'none': self.dvbag = rosbag.Bag(delta_video_filename) else: self.dvbag = None # trajectory colors self.trajec_to_color_dict = {} self.trajec_width_dict = {} self.plotted_traces_keys = [] self.plotted_traces = [] self.trajectory_ends_vlines = [] ## create GUI self.app = QtGui.QApplication([]) self.w = QtGui.QWidget() self.layout = QtGui.QGridLayout() self.w.setLayout(self.layout) self.w.show() # play movie button play_btn = QtGui.QPushButton('play video sequence') play_btn.pressed.connect(self.play_movie) self.layout.addWidget(play_btn, 0, 0) # stop movie button stop_btn = QtGui.QPushButton('stop video sequence') stop_btn.pressed.connect(self.stop_movie) self.layout.addWidget(stop_btn, 1, 0) # toggle delete trajectory button toggle_delete_object_id_btn = QtGui.QPushButton( 'delete objects\ncrosshair = red') toggle_delete_object_id_btn.pressed.connect( self.toggle_delete_object_id_numbers) self.layout.addWidget(toggle_delete_object_id_btn, 3, 0) self.delete_objects = False # toggle cut trajectory button toggle_cut_object_id_btn = QtGui.QPushButton( 'cut objects\ncrosshair = yellow') toggle_cut_object_id_btn.pressed.connect( self.toggle_cut_object_id_numbers) self.layout.addWidget(toggle_cut_object_id_btn, 4, 0) self.cut_objects = False # start collecting object ids button start_collecting_object_id_btn = QtGui.QPushButton( 'select objects to join\ncrosshair = green') start_collecting_object_id_btn.pressed.connect( self.start_collecting_object_id_numbers) self.layout.addWidget(start_collecting_object_id_btn, 5, 0) self.join_objects = False # save collected object ids button save_collected_object_id_btn = QtGui.QPushButton( 'join selected\nobject id numbers') save_collected_object_id_btn.pressed.connect( self.save_collected_object_id_numbers) self.layout.addWidget(save_collected_object_id_btn, 6, 0) # undo undo_btn = QtGui.QPushButton('undo last action') undo_btn.pressed.connect(self.undo) self.layout.addWidget(undo_btn, 7, 0) self.p1 = pg.PlotWidget(title="Basic array plotting") self.p1.enableAutoRange('xy', False) self.layout.addWidget(self.p1, 1, 1) if self.config is not None: print '**** Sensory stimulus: ', self.config.sensory_stimulus_on for r, row in enumerate(self.config.sensory_stimulus_on): v1 = pg.PlotDataItem([ self.config.sensory_stimulus_on[r][0], self.config.sensory_stimulus_on[r][0] ], [0, 10]) v2 = pg.PlotDataItem([ self.config.sensory_stimulus_on[r][-1], self.config.sensory_stimulus_on[r][-1] ], [0, 10]) f12 = pg.FillBetweenItem(curve1=v1, curve2=v2, brush=pg.mkBrush('r')) self.p1.addItem(f12) self.p2 = pg.PlotWidget() self.layout.addWidget(self.p2, 0, 1) lr = pg.LinearRegionItem(values=self.troi) f = 'update_time_region' lr.sigRegionChanged.connect(self.__getattribute__(f)) self.p1.addItem(lr) self.draw_timeseries_vlines_for_interesting_timepoints() self.current_time_vline = pg.InfiniteLine(angle=90, movable=False) self.p1.addItem(self.current_time_vline, ignoreBounds=True) self.current_time_vline.setPos(0) pen = pg.mkPen((255, 255, 255), width=2) self.current_time_vline.setPen(pen)
def main(): #set up plottig GUI app = QtGui.QApplication([]) pg.setConfigOption('background', 'w') win = pg.GraphicsWindow(title="Occupancy Detection GUI") plot1 = win.addPlot() plot1.setXRange(-6, 6) plot1.setYRange(0, 6) plot1.setLabel('left', text='Y position (m)') plot1.setLabel('bottom', text='X position (m)') s1 = plot1.plot([], [], pen=None, symbol='o') plot2 = win.addPlot() plot2.setXRange(-6, 6) plot2.setYRange(0, 6) plot2.setLabel('left', text='Y position (m)') plot2.setLabel('bottom', text='X position (m)') s2 = plot2.plot([], [], pen=None, symbol='o') parsingMatFile = '/home/pi/Desktop/OccupancyDetection/Data/Experiment Data 2/3PeopleWalking.mat' tlvData = (loadmat(parsingMatFile))['tlvStream'][0] #Initialise Kalman Parameters centroidX = np.zeros( (4, 1)) #Centroid X contains all tracked centroids/occupant centroidP = [ ] #Centroid P contains 4x4 error covariance matrix of each occupant/centroid P = np.identity(4) #initialise first occupant centroidP.extend([P]) Q = np.multiply(0.2, np.identity(4)) #system covariance matrix R = np.multiply(5, np.array([[1], [1]])) #measurement covariance matrix #tree based weightThresholdIntial = 0.2 #minimum distance between points minClusterSizeInitial = 10 weightThresholdFinal = 0.8 #minimum distance between points minClusterSizeFinal = 8 #zone snr snrFirstZone = 340 snrMiddleZone = 140 snrLastZone = 50 tlvHeaderLengthInBytes = 8 pointLengthInBytes = 16 targetLengthInBytes = 68 tiPosX = np.array([]) tiPosY = np.array([]) isFirst = 1 for tlvStream in tlvData: #parsing pointCloud, targetDict = tlvParsing(tlvStream, tlvHeaderLengthInBytes, pointLengthInBytes, targetLengthInBytes) if pointCloud.size > 0: posX, posY, SNR = parsePointCloud( pointCloud) #dictionary that contains the point cloud data #initial noise reduction clusters = TreeClustering(posX, posY, SNR, weightThresholdIntial, minClusterSizeInitial) if clusters.size > 0: # row 1 - x # row 2 - y # row 3 - SNR # row 4 - cluster number # snr zone snr test # 4.5 to the end -> last zone # 3-4.5m -> middle zone # 1-3m -> first zone snrMask_LastZone = np.logical_and( np.greater(clusters[1, :], 4.5), np.greater(clusters[2, :], snrLastZone)) #zone 4.5m and greater snrMask_MiddleZone = np.logical_and( np.logical_and(np.greater(clusters[1, :], 3), np.less_equal(clusters[1, :], 4.5)), np.greater(clusters[2, :], snrMiddleZone)) #zone 3-4.5m with SNR > 20 snrMask_FirstZone = np.logical_and( np.less_equal(clusters[1, :], 3), np.greater(clusters[2, :], snrFirstZone)) overallSnrMask = np.logical_or( np.logical_or(snrMask_FirstZone, snrMask_MiddleZone), snrMask_LastZone) snrFilteredClusters = clusters[:, overallSnrMask] if snrFilteredClusters.size > 0: # s2.setData(snrFilteredClusters[0,:], snrFilteredClusters[1,:]) dbClusters = TreeClustering(snrFilteredClusters[0, :], snrFilteredClusters[1, :], snrFilteredClusters[2, :], weightThresholdFinal, minClusterSizeFinal) if dbClusters.size > 0: #row 1 - x #row 2 - y #row 3 - cluster number k = int(max(dbClusters[3, :])) + 1 points = np.transpose( np.array([dbClusters[0, :], dbClusters[1, :]])) #kmeans centroidClusterer = KMeans(n_clusters=k).fit(points) centroidData = np.array([ centroidClusterer.cluster_centers_[:, 0], centroidClusterer.cluster_centers_[:, 1] ]) #tracking centroidX, centroidP, isFirst = LiveRKF( centroidData, centroidX, centroidP, Q, R, isFirst) #plot #calculate x and y positions xPositions = np.multiply(centroidX[0, :], np.cos(centroidX[2, :])) yPositions = np.multiply(centroidX[0, :], np.sin(centroidX[2, :])) s1.setData(xPositions, yPositions) if len(targetDict) != 0: #kinematic data object structure #row 0 - posX #row 1 - posY #row 2 - velX #row 3 - velY #row 4 - accX #row 5 - accY tiPosX = targetDict['kinematicData'][0, :] tiPosY = targetDict['kinematicData'][1, :] print(tiPosY) s2.setData(tiPosX, tiPosY) QtGui.QApplication.processEvents()
# Import libraries from numpy import * from pyqtgraph.Qt import QtGui, QtCore import pyqtgraph as pg import serial from random import randint # Create object serial port # portName = "COM12" # replace this port name by yours! # baudrate = 9600 # ser = serial.Serial(portName,baudrate) ### START QtApp ##### app = QtGui.QApplication([]) # you MUST do this once (initialize things) #################### win = pg.GraphicsWindow(title="Signal from serial port") # creates a window p = win.addPlot( title="Realtime plot") # creates empty space for the plot in the window curve = p.plot() # create an empty "plot" (a curve to plot) windowWidth = 500 # width of the window displaying the curve Xm = linspace( 0, 0, windowWidth) # create array that will contain the relevant time series ptr = -windowWidth # set first x position # Realtime data plot. Each time this function is called, the data display is updated def update(): global curve, ptr, Xm
def _qtg_plot_signal(G, signal, edges, vertex_size, limits, title): qtg, gl, QtGui = _import_qtg() if G.coords.shape[1] == 2: window = qtg.GraphicsWindow(title) view = window.addViewBox() elif G.coords.shape[1] == 3: if not QtGui.QApplication.instance(): QtGui.QApplication([]) # We want only one application. widget = gl.GLViewWidget() widget.opts['distance'] = 10 widget.show() widget.setWindowTitle(title) if edges: if G.is_directed(): raise NotImplementedError else: if G.coords.shape[1] == 2: adj = _get_coords(G, edge_list=True) pen = tuple(np.array(G.plotting['edge_color']) * 255) g = qtg.GraphItem(pos=G.coords, adj=adj, symbolBrush=None, symbolPen=None, pen=pen) view.addItem(g) elif G.coords.shape[1] == 3: x, y, z = _get_coords(G) pos = np.stack((x, y, z), axis=1) g = gl.GLLinePlotItem(pos=pos, mode='lines', color=G.plotting['edge_color']) widget.addItem(g) pos = [1, 8, 24, 40, 56, 64] color = np.array([[0, 0, 143, 255], [0, 0, 255, 255], [0, 255, 255, 255], [255, 255, 0, 255], [255, 0, 0, 255], [128, 0, 0, 255]]) cmap = qtg.ColorMap(pos, color) signal = 1 + 63 * (signal - limits[0]) / limits[1] - limits[0] if G.coords.shape[1] == 2: gp = qtg.ScatterPlotItem(G.coords[:, 0], G.coords[:, 1], size=vertex_size/10, brush=cmap.map(signal, 'qcolor')) view.addItem(gp) if G.coords.shape[1] == 3: gp = gl.GLScatterPlotItem(pos=G.coords, size=vertex_size/3, color=cmap.map(signal, 'float')) widget.addItem(gp) if G.coords.shape[1] == 2: global _qtg_windows _qtg_windows.append(window) elif G.coords.shape[1] == 3: global _qtg_widgets _qtg_widgets.append(widget)
def __init__(self): self.viewer = None self.dims = (300, 300) self.observation_space = spaces.Box(low=0, high=300, shape=(self.dims)) # Action space omits the Tackle/Catch actions, which are useful on defense self.action_space = spaces.Discrete(3) self.reward = 0 self.actions = self.action_space self.df = read_hdf('uptodate.h5') self.df = self.df.loc['2000-1-1':'2014-1-1'] self.grouped = self.df.groupby(lambda x: x.date).filter( lambda x: len(x) > 389 and len(x) < 391) self.grouped = self.grouped.groupby(lambda x: x.date) self.dates = self.grouped.groups.keys() shuffle(self.dates) self.epochs = len( self.dates ) # number of epochs = # of trading days we are training for. print(self.epochs) self.app = QtGui.QApplication([]) self.win = pg.GraphicsWindow() self.p1 = self.win.addPlot() self.p1.setXRange(0, 390) self.terminal = False self.text1 = pg.TextItem(text='LONG ', anchor=(0, 0), border='w', fill=(255, 255, 255, 255)) self.text2 = pg.TextItem(text='SHORT', anchor=(0, 1), border='w', fill=(255, 255, 255, 255)) self.text3 = pg.TextItem(text='BUY ', anchor=(1, 1), border='w', fill=(255, 255, 255, 255)) self.text4 = pg.TextItem(text='SELL ', anchor=(1, 0), border='w', fill=(255, 255, 255, 255)) self.lineitem = pg.InfiniteLine() self.lineitem.setValue(0) self.p1.addItem(self.text1) self.p1.addItem(self.text2) self.p1.addItem(self.text3) self.p1.addItem(self.text4) self.p1.addItem(self.lineitem) self.curve1 = self.p1.plot() self.app.processEvents() self.counter = 0 self.aaaa = pg.exporters.ImageExporter(self.p1) self.aaaa.export('temp.png') self.state = color.rgb2gray(io.imread('temp.png')) self.state = np.array(self.state) self.data = [] self.count = 0 self.cumrewards = 0.0 self.testrewards1 = [] self.testprofits1 = [] self.testrewards = 0.0 self.testprofits = 0.0 self.b = "16:00:00" self.dt = datetime.strptime(self.b, "%H:%M:%S") self.currenttime = datetime.strptime('9:29:00', "%H:%M:%S") self.currentdate = self.dates[0] self.dates.pop(0) self.times = self.grouped.get_group(self.currentdate).index.tolist() self.close = self.grouped.get_group(self.currentdate).values.tolist() self.position = 0 self.bprice = 0 print("done") self._seed() self.reset()
# Create object serial port from rms_function import rms_function portName = "COM6" baudRate = 115200 R = 30 Y_range = [-2500, 2500] # ser = serial.Serial(portName, baudRate) ser = serial.Serial(portName, int(baudRate), timeout=1, parity=serial.PARITY_NONE, stopbits=1) ### START QtApp ##### app = QtGui.QApplication([]) # initialize things #################### win = pg.GraphicsWindow(title="Signal from Bluetooth") # create a window win.setBackground('w') p = win.addPlot( title="Realtime plot") # create empty space for the plot in the window p.setYRange(min=int(Y_range[0]), max=int(Y_range[1])) # p2 = win.addPlot(title="RMS plot") # create empty space for the plot in the window # p2.setYRange(min=int(Y_range[0]), max=int(Y_range[1])) curve = p.plot(pen=pg.mkPen(color='k', width=0.2)) curve2 = p.plot(pen=pg.mkPen(color='b', width=0.5)) # create an empty "plot" (a curve to plot) # pg.setConfigOption('background', 'w')
import random import numpy as np from PIL import Image img = Image.open('heart_1.png').convert('RGBA') arr = np.array(img) img2 = Image.open('heart_2.png').convert('RGBA') arr2 = np.array(img2) SCALE_FACTOR = (4500000)/24/(2**23-1) #From the pyOpenBCI repo colors = 'rgbycmwr' app = QtGui.QApplication([]) win = pg.GraphicsWindow(title='Python OpenBCI GUI') # title_graph = win.addPlot(row=0, col=0, colspan=4,title='Python OpenBCI GUI') ts_plots = win.addPlot(row=0, col=0, colspan=4, title='Channel %d' % 1, labels={'left': 'uV'}) fft_plot = win.addPlot(row=2, col=0, rowspan=2, colspan=2, title='Filtered Plot', labels={'left': 'uV', 'bottom': 'Hz'}) fft_plot.setLimits(xMin=1,xMax=125, yMin=0, yMax=1e7) ss_plot = win.addPlot(row=4, col=0, rowspan=2, colspan=2, title='signal',labels={'left':'Is beat'}) heart_im = win.addViewBox(lockAspect=True) imv = pg.ImageItem() heart_im.addItem(imv) imv.setImage(arr) data= [0]
def setup_pyqtgraph(self): ## App pg.setConfigOptions(antialias=True) self.traces = dict() self.app = QtGui.QApplication(sys.argv) ## 2D View self.view_2d = pg.GraphicsWindow( title='VIO - Trajectory Error and Matches') ## 3D View self.view_3d = gl.GLViewWidget() size = 30000 self.view_3d.setGeometry(5, 115, size, size) self.view_3d.opts['distance'] = size / 5 self.view_3d.setWindowTitle('VIO - Trajectory') gx, gy, gz = gl.GLGridItem(), gl.GLGridItem(), gl.GLGridItem() gx.setSpacing(size / 100, size / 100) gy.setSpacing(size / 100, size / 100) gz.setSpacing(size / 100, size / 100) gx.setSize(size, size) gy.setSize(size, size) gz.setSize(size, size) gx.rotate(90, 0, 1, 0) gx.translate(-size // 2, 0, 0) gy.rotate(90, 1, 0, 0) gy.translate(0, -size // 2, 0) gz.translate(0, 0, -size // 2) self.view_3d.addItem(gx) self.view_3d.addItem(gy) self.view_3d.addItem(gz) self.view_3d.show() ## Matches View self.matches_win = pg.GraphicsLayoutWidget() self.matches_win.setWindowTitle('Inliers and outliers matches') ## A plot area (ViewBox + axes) for displaying the image self.match_plot = self.matches_win.addPlot( title="Inliers and outliers matches") ## Item for displaying image data self.matches_img = pg.ImageItem() self.match_plot.addItem(self.matches_img) self.matches_win.show() ## Plots self.plot_data = { 'error': { 'x': [], 'y': [], 'z': [] }, 'true_pose': [], 'vo_pose': [] } self.trajectory_error_plot = self.view_2d.addPlot( title='Trajectory Error', row=1, col=1, labels={ 'left': 'Error (m)', 'bottom': 'Frame ID' }) self.trajectory_error_plot.addLegend() self.plots = { 'error': { 'x': self.trajectory_error_plot.plot(pen=(255, 0, 0), width=3, name='Error x'), 'y': self.trajectory_error_plot.plot(pen=(0, 255, 0), width=3, name='Error y'), 'z': self.trajectory_error_plot.plot(pen=(0, 0, 255), width=3, name='Error z') }, 'true_pose': gl.GLScatterPlotItem(color=(0.0, 0.0, 1.0, 1), size=1, pxMode=False), # Blue 'vo_pose': gl.GLScatterPlotItem(color=(0.0, 1.0, 0.0, 1), size=1, pxMode=False) } # Green self.view_3d.addItem(self.plots['true_pose']) self.view_3d.addItem(self.plots['vo_pose']) self.sequence_id = 0