def __init__(self): self.traces = dict() self.app = QtGui.QApplication(sys.argv) self.w = gl.GLViewWidget() self.w.opts['distance'] = 40 self.w.setWindowTitle('pyqtgraph example: GLLinePlotItem') self.w.setGeometry(0, 110, 1920, 1080) self.w.show() # create the background grids gx = gl.GLGridItem() gx.rotate(90, 0, 1, 0) gx.translate(-10, 0, 0) self.w.addItem(gx) gy = gl.GLGridItem() gy.rotate(90, 1, 0, 0) gy.translate(0, -10, 0) self.w.addItem(gy) gz = gl.GLGridItem() gz.translate(0, 0, -10) self.w.addItem(gz) self.n = 50 self.m = 1000 self.y = np.linspace(-10, 10, self.n) self.x = np.linspace(-10, 10, self.m) self.phase = 0 for i in range(self.n): yi = np.array([self.y[i]] * self.m) d = np.sqrt(self.x ** 2 + yi ** 2) z = 10 * np.cos(d + self.phase) / (d + 1) pts = np.vstack([self.x, yi, z]).transpose() self.traces[i] = gl.GLLinePlotItem(pos=pts, color=pg.glColor( (i, self.n * 1.3)), width=(i + 1) / 10, antialias=True) self.w.addItem(self.traces[i])
def __init__(self): self.scale = 4000 # initialize Qt gui application and window self.app = pg.QtGui.QApplication([]) # initialize QT self.window = gl.GLViewWidget() # initialize the view object self.window.setWindowTitle('Path Viewer') self.window.setGeometry(0, 0, 1500, 1500) # args: upper_left_x, upper_right_y, width, height grid = gl.GLGridItem() # make a grid to represent the ground grid.scale(self.scale/20, self.scale/20, self.scale/20) # set the size of the grid (distance between each line) self.window.addItem(grid) # add grid to viewer self.window.setCameraPosition(distance=self.scale, elevation=90, azimuth=-90) view_location = Vector(2000, 2000, 3000) # defined in ENU coordinates # self.window.setCameraPosition(distance=self.scale, elevation=50, azimuth=-90) # view_location = Vector(2000, 2000, 0) # defined in ENU coordinates self.window.opts['center'] = view_location self.window.setBackgroundColor('k') # set background color to black self.window.show() # display configured window self.window.raise_() # bring window to the front self.plot_initialized = False # has the mav been plotted yet? # get points that define the non-rotated, non-translated mav and the mesh colors self.mav_points, self.mav_meshColors = self.get_mav_points() # dubins path parameters self.dubins_path = dubins_parameters() self.mav_body = []
def plot_map(self, world_map, tree, waypoints, smoothed_waypoints, radius): scale = 4000 # initialize Qt gui application and window self.plot_app = pg.QtGui.QApplication([]) # initialize QT self.plot_window = gl.GLViewWidget() # initialize the view object self.plot_window.setWindowTitle('World Viewer') self.plot_window.setGeometry(0, 0, 1500, 1500) # args: upper_left_x, upper_right_y, width, height grid = gl.GLGridItem() # make a grid to represent the ground grid.scale(scale/20, scale/20, scale/20) # set the size of the grid (distance between each line) self.plot_window.addItem(grid) # add grid to viewer self.plot_window.setCameraPosition(distance=scale, elevation=50, azimuth=-90) self.plot_window.setBackgroundColor('k') # set background color to black self.plot_window.show() # display configured window self.plot_window.raise_() # bring window to the front blue = np.array([[30, 144, 255, 255]])/255. red = np.array([[204, 0, 0]])/255. green = np.array([[0, 153, 51]])/255. DrawMap(world_map, self.plot_window) DrawWaypoints(waypoints, radius, blue, self.plot_window) DrawWaypoints(smoothed_waypoints, radius, red, self.plot_window) self.draw_tree(radius, green) # draw things to the screen self.plot_app.processEvents()
def __init__(self, data, parent = None): super(plotTexture, self).__init__(parent) self.data = data self.w = gl.GLViewWidget() self.w.opts['distance'] = 200 self.w.setWindowTitle('3D slice - texture plot') self.shape = self.data.shape #set intensity self.levels = (0, 1000) ## slice out three center planes, convert to RGBA for OpenGL texture self.slice1 = int(self.shape[0]/2) self.slice2 = int(self.shape[1]/2) self.slice3 = int(self.shape[2]/2) ## Create three image items from textures, add to view self.updateYZ() self.updateXZ() self.updateXY() self.addBorder(self.shape[0],self.shape[1],self.shape[2])
def viz(topo_dictionary_list): """ This function visualises the topologies. Parameters ---------- topo_dictionary_list : a list of dictionary A list of dictionary specifying the visualisation parameters. topo_list: the topos to visualise colour: keywords (RED,ORANGE,YELLOW,GREEN,BLUE,BLACK,WHITE) or rgb tuple to specify the colours draw_edges: bool whether to draw the edges of mesh, default is True att: name of the att to visualise with the topologies """ import PyQt5 def colour2rgb(colour): if colour == 'red': rgb = (1,0,0,1) elif colour == 'orange': rgb = (1,0.65,0,1) elif colour == 'yellow': rgb = (1,1,0,1) elif colour == 'green': rgb = (0,1,0,1) elif colour == 'blue': rgb = (1,0,0,1) elif colour == 'black': rgb = (0,0,0,1) elif colour == 'white': rgb = (1,1,1,1) return rgb os.environ['PYQTGRAPH_QT_LIB'] = "PyQt5" ## Create a GL View widget to display data app = QtGui.QApplication([]) w = gl.GLViewWidget() w.show() w.setWindowTitle('Geomie3D viz') bbox_list = [] for d in topo_dictionary_list: colour = d['colour'] rgb = colour2rgb(colour) draw_edges = True if 'draw_edges' in d.keys(): draw_edges = d['draw_edges'] topo_list = d['topo_list'] cmp = create.composite(topo_list) sorted_d = get.unpack_composite(cmp) #================================================================================= #get all the topology that can be viz as mesh #================================================================================= all_faces = [] faces = sorted_d['face'] if len(faces) > 0: all_faces = faces shells = sorted_d['shell'] if len(shells) > 0: shells2faces = np.array([get.faces_frm_shell(shell) for shell in shells]) shells2faces = shells2faces.flatten() all_faces = np.append(all_faces, shells2faces) solids = sorted_d['solid'] if len(solids) > 0: solids2faces = np.array([get.faces_frm_solid(solid) for solid in solids]) solids2faces = solids2faces.flatten() all_faces = np.append(all_faces, solids2faces) #if there are faces to be viz if len(all_faces) > 0: mesh_dict = modify.faces2mesh(all_faces) #flip the indices verts = mesh_dict['vertices'] idx = mesh_dict['indices'] #flip the vertices to be clockwise idx = np.flip(idx, axis=1) viz_mesh = make_mesh(verts, idx, draw_edges = draw_edges) viz_mesh.setColor(np.array(rgb)) w.addItem(viz_mesh) #================================================================================= #get all the topology that can viz as lines #================================================================================= all_edges = [] edges = sorted_d['edge'] if len(edges) > 0: all_edges = edges wires = sorted_d['wire'] if len(wires) > 0: wires2edges = np.array([get.edges_frm_wire(wire) for wire in wires]) all_edges = np.append(all_edges, wires2edges ) if len(all_edges) > 0: line_vertices = modify.edges2lines(all_edges) viz_lines = make_line(line_vertices, line_colour = rgb) w.addItem(viz_lines) #================================================================================= #get all the topology that can viz as points #================================================================================= vertices = sorted_d['vertex'] if len(vertices) > 0: points_vertices = np.array([v.point.xyz for v in vertices]) make_points(points_vertices, rgb, 10, pxMode = True) #================================================================================= #find the bbox #================================================================================= bbox = calculate.bbox_frm_topo(cmp) bbox_list.append(bbox) overall_bbox = calculate.bbox_frm_bboxes(bbox_list) midpt = calculate.bbox_centre(overall_bbox) w.opts['center'] = PyQt5.QtGui.QVector3D(midpt[0], midpt[1], midpt[2]) lwr_left = [overall_bbox[0], overall_bbox[1], overall_bbox[2]] upr_right = [overall_bbox[3], overall_bbox[4], overall_bbox[5]] dist = calculate.dist_btw_xyzs(lwr_left, upr_right) w.opts['distance'] = dist # w.setCameraPosition(distance=60) QtGui.QApplication.instance().exec_()
# bodies[:, -1] = 0.1 bodies = np.zeros((96, 10), dtype=np.float32) # Initialize body array theta = np.repeat(np.arange(19)*2*np.pi/19, 5) r = np.tile(np.arange(40, 80, 8), 19) bodies[1:, 0] = r*np.cos(theta) bodies[1:, 1] = r*np.sin(theta) bodies[1:, 3] = np.sqrt(G*1000000/r)*np.sin(theta)*1.2 bodies[1:, 4] = -np.sqrt(G*1000000/r)*np.cos(theta)*1.2 bodies[1:, 9] = G bodies[0, 9] = 1000000*G Oct = Octree(bodies) # Initialize app = QtGui.QApplication([]) # Initialize figure w = gl.GLViewWidget() # Initialize opengl widget w.opts['distance'] = 200 # Set viewing distance to the figure w.show() # Show the figure w.setWindowTitle('N-body simulation') # Set title of the window w.showFullScreen() # Show fullscreen (alt+f4 to quit) color = np.zeros((N, 4), dtype=np.float32) # Initialize color array for the plot color[:, 3] = 0.9 color[-1, 0] = 1 color[1:-1, 1] = 1 color[0, 2] = 1 # Set color of the plot based on the Milky Way & Andromeda data # color = np.zeros((N, 4), dtype=np.float32) # Initialize color array for the plot # color[:, 3] = 0.3 # Set transparency to 30% # color[:int(16384/mod), 2] = 1 # Set Milky Way core to blue
def create_main_frame(self): self.main_frame = QWidget() #self.main_frame.setFixedSize(self.width(), self.width()) self.dpi = 128 self.ShapeGroups = 200 self.view = gl.GLViewWidget() #self.view = pg.PlotWidget() #self.view.setFixedSize(self.width(),self.height()) self.view.setFixedSize(self.width(), self.width()) self.view.setParent(self.main_frame) # Other GUI controls self.save_button = QPushButton('&Save') self.save_button.clicked.connect(self.saveImgFile) self.draw_button = QPushButton('&Reset') self.draw_button.clicked.connect(self.Reset) self.load_button = QPushButton('&Load') #self.load_button.clicked.connect(self.Load) self.fit_cb = QCheckBox('&PolyFit') self.fit_cb.setChecked(False) self.fit_cb.stateChanged.connect(self.Magic) # int self.fit_label = QLabel('Exp') self.fit_seter = QLineEdit(self) self.fit_seter.textChanged[str].connect(self.FitChanged) self.shape_cb = QCheckBox('&Shape') self.shape_cb.setChecked(False) self.shape_cb.stateChanged.connect(self.Magic) # int self.Normalize_cb = QCheckBox('&Normalize') self.Normalize_cb.setChecked(False) self.Normalize_cb.stateChanged.connect(self.Magic) # int self.norm_slider_label = QLabel('Standard:' + self.NameChosen) self.norm_slider = QSlider(Qt.Horizontal) self.norm_slider.setRange(0, 4) self.norm_slider.setValue(0) self.norm_slider.setTracking(True) self.norm_slider.setTickPosition(QSlider.TicksBothSides) self.norm_slider.valueChanged.connect(self.Magic) # int self.x_element = QSlider(Qt.Horizontal) self.x_element.setRange(0, len(self.items) - 1) self.x_element.setValue(0) self.x_element.setTracking(True) self.x_element.setTickPosition(QSlider.TicksBothSides) self.x_element.valueChanged.connect(self.Magic) # int self.x_element_label = QLabel('X') self.logx_cb = QCheckBox('&Log') self.logx_cb.setChecked(False) self.logx_cb.stateChanged.connect(self.Magic) # int self.y_element = QSlider(Qt.Horizontal) self.y_element.setRange(0, len(self.items) - 1) self.y_element.setValue(1) self.y_element.setTracking(True) self.y_element.setTickPosition(QSlider.TicksBothSides) self.y_element.valueChanged.connect(self.Magic) # int self.y_element_label = QLabel('Y') self.logy_cb = QCheckBox('&Log') self.logy_cb.setChecked(False) self.logy_cb.stateChanged.connect(self.Magic) # int self.z_element = QSlider(Qt.Horizontal) self.z_element.setRange(0, len(self.items) - 1) self.z_element.setValue(2) self.z_element.setTracking(True) self.z_element.setTickPosition(QSlider.TicksBothSides) self.z_element.valueChanged.connect(self.Magic) # int self.z_element_label = QLabel('Z') self.logz_cb = QCheckBox('&Log') self.logz_cb.setChecked(False) self.logz_cb.stateChanged.connect(self.Magic) # int self.xlim_seter_left_label = QLabel('Xleft') self.xlim_seter_left = QLineEdit(self) self.xlim_seter_left.textChanged[str].connect(self.XleftChanged) self.xlim_seter_right_label = QLabel('Xright') self.xlim_seter_right = QLineEdit(self) self.xlim_seter_right.textChanged[str].connect(self.XrightChanged) self.ylim_seter_down_label = QLabel('Ydown') self.ylim_seter_down = QLineEdit(self) self.ylim_seter_down.textChanged[str].connect(self.YdownChanged) self.ylim_seter_up_label = QLabel('Yup') self.ylim_seter_up = QLineEdit(self) self.ylim_seter_up.textChanged[str].connect(self.YupChanged) self.hbox0 = QHBoxLayout() self.hbox1 = QHBoxLayout() self.hbox2 = QHBoxLayout() self.hbox3 = QHBoxLayout() self.hbox4 = QHBoxLayout() self.hbox5 = QHBoxLayout() self.hbox6 = QHBoxLayout() self.hbox7 = QHBoxLayout() ''' for w in [self.fit_cb,self.fit_label, self.fit_seter,self.xlim_seter_left_label,self.xlim_seter_left,self.xlim_seter_right_label,self.xlim_seter_right,self.ylim_seter_down_label,self.ylim_seter_down,self.ylim_seter_up_label,self.ylim_seter_up,self.shape_cb]: self.hbox0.addWidget(w) self.hbox0.setAlignment(w, Qt.AlignVCenter) ''' for w in [self.view]: self.hbox0.addWidget(w) self.hbox0.setAlignment(w, Qt.AlignVCenter) for w in [self.Normalize_cb, self.norm_slider_label, self.norm_slider]: self.hbox1.addWidget(w) self.hbox1.setAlignment(w, Qt.AlignVCenter) for w in [self.logx_cb, self.x_element_label, self.x_element]: self.hbox2.addWidget(w) self.hbox2.setAlignment(w, Qt.AlignVCenter) for w in [self.logy_cb, self.y_element_label, self.y_element]: self.hbox3.addWidget(w) self.hbox3.setAlignment(w, Qt.AlignVCenter) for w in [self.logz_cb, self.z_element_label, self.z_element]: self.hbox4.addWidget(w) self.hbox4.setAlignment(w, Qt.AlignVCenter) self.vbox = QVBoxLayout() #self.vbox.addWidget(self.view) self.vbox.addLayout(self.hbox0) self.vbox.addLayout(self.hbox1) self.vbox.addLayout(self.hbox2) self.vbox.addLayout(self.hbox3) self.vbox.addLayout(self.hbox4) self.main_frame.setLayout(self.vbox) self.setCentralWidget(self.main_frame)
def pg_plot_graph(G, show_edges=None, plot_name=''): r""" Plot a graph or an array of graphs. See plot_graph for full documentation. """ # TODO handling when G is a list of graphs global window_list if 'window_list' not in globals(): window_list = {} if not G.coords.shape: raise AttributeError( 'G has no coordinate set. Please run G.set_coords() first.') if show_edges is None: show_edges = G.Ne < 10000 ki, kj = np.nonzero(G.A) if G.directed: raise NotImplementedError('TODO') if G.coords.shape[1] == 2: raise NotImplementedError('TODO') else: raise NotImplementedError('TODO') else: if G.coords.shape[1] == 2: adj = np.concatenate( (np.expand_dims(ki, axis=1), np.expand_dims(kj, axis=1)), axis=1) w = pg.GraphicsWindow() w.setWindowTitle(G.plotting['plot_name'] if 'plot_name' in G.plotting else plot_name or G.gtype) v = w.addViewBox() v.setAspectLocked() extra_args = {} if isinstance(G.plotting['vertex_color'], list): extra_args['symbolPen'] = [ pg.mkPen(v_col) for v_col in G.plotting['vertex_color'] ] extra_args['brush'] = [ pg.mkBrush(v_col) for v_col in G.plotting['vertex_color'] ] elif isinstance(G.plotting['vertex_color'], int): extra_args['symbolPen'] = G.plotting['vertex_color'] extra_args['brush'] = G.plotting['vertex_color'] # Define syntaxic sugar mapping keywords for the display options for plot_args, pg_args in [('vertex_size', 'size'), ('vertex_mask', 'mask'), ('edge_color', 'pen')]: if plot_args in G.plotting: G.plotting[pg_args] = G.plotting.pop(plot_args) for pg_args in ['size', 'mask', 'pen', 'symbolPen']: if pg_args in G.plotting: extra_args[pg_args] = G.plotting[pg_args] if not show_edges: extra_args['pen'] = None g = pg.GraphItem(pos=G.coords, adj=adj, **extra_args) v.addItem(g) window_list[str(uuid.uuid4())] = w elif G.coords.shape[1] == 3: app = QtGui.QApplication([]) w = gl.GLViewWidget() w.opts['distance'] = 10 w.show() w.setWindowTitle(G.plotting['plot_name'] if 'plot_name' in G.plotting else plot_name or G.gtype) # Very dirty way to display a 3d graph x = np.concatenate( (np.expand_dims(G.coords[ki, 0], axis=0), np.expand_dims(G.coords[kj, 0], axis=0))) y = np.concatenate( (np.expand_dims(G.coords[ki, 1], axis=0), np.expand_dims(G.coords[kj, 1], axis=0))) z = np.concatenate( (np.expand_dims(G.coords[ki, 2], axis=0), np.expand_dims(G.coords[kj, 2], axis=0))) ii = range(0, x.shape[1]) x2 = np.ndarray((0, 1)) y2 = np.ndarray((0, 1)) z2 = np.ndarray((0, 1)) for i in ii: x2 = np.append(x2, x[:, i]) for i in ii: y2 = np.append(y2, y[:, i]) for i in ii: z2 = np.append(z2, z[:, i]) pts = np.concatenate( (np.expand_dims(x2, axis=1), np.expand_dims( y2, axis=1), np.expand_dims(z2, axis=1)), axis=1) extra_args = {'color': (0, 0, 1, 1)} if 'vertex_color' in G.plotting: if isinstance(G.plotting['vertex_color'], list): extra_args['color'] = np.array([ pg.glColor(pg.mkPen(v_col).color()) for v_col in G.plotting['vertex_color'] ]) elif isinstance(G.plotting['vertex_color'], int): extra_args['color'] = pg.glColor( pg.mkPen(G.plotting['vertex_color']).color()) else: extra_args['color'] = G.plotting['vertex_color'] # Define syntaxic sugar mapping keywords for the display options for plot_args, pg_args in [('vertex_size', 'size')]: if plot_args in G.plotting: G.plotting[pg_args] = G.plotting.pop(plot_args) for pg_args in ['size']: if pg_args in G.plotting: extra_args[pg_args] = G.plotting[pg_args] if show_edges: g = gl.GLLinePlotItem(pos=pts, mode='lines', color=G.plotting['edge_color']) w.addItem(g) gp = gl.GLScatterPlotItem(pos=G.coords, **extra_args) w.addItem(gp) window_list[str(uuid.uuid4())] = app
def __initWindow(self): w = gl.GLViewWidget() w.opts['distance'] = 4 w.setWindowTitle('pyqtgraph example: GLLinePlotItem') w.show() return w
# R,I,prob = step(R,I,V,spin,dx,dt,axes) ######################################################### ######################################################### # Plotting and stuffs import sys # Plotting Variables plotevery = 1 level = 2 Z = 0.5 EXPORT = True # Qt Setup app = QtGui.QApplication([]) w = gl.GLViewWidget() w.show() w.setWindowTitle('pyqtgraph example: GLIsosurface') w.setCameraPosition(azimuth=0, distance=30) g = gl.GLGridItem() g.scale(0.5, 0.5, 1) w.addItem(g) # Plot a the wavefunction isosurface verts, faces = pg.isosurface(prob, prob.max() / level) md = gl.MeshData(vertexes=verts, faces=faces) colors = np.ones((md.faceCount(), 4), dtype=float) colors[:, 3] = 0.2 colors[:, 2] = np.linspace(1, 1, 1)
def initialize(self): QtGui.QWidget.__init__(self) self.setMinimumSize(700, 500) self.setMaximumSize(700, 500) self.setWindowTitle('SMART Glove') # Widget name label ##### Create the widgets here ##### # Start button widget self.start = QtGui.QPushButton('Start', self) self.start.clicked.connect(self.handleStart) # Update Plot widget self.updatePlot = QtGui.QPushButton('Update Plot', self) self.updatePlot.clicked.connect(self.handleUpdate) # Instructions button widget self.instructions = QtGui.QPushButton('Instructions') self.instructions.clicked.connect(self.handleInstructions) #Instructions second window that opens self.instrucWindow = Instruc( self) #Calls the instructions window class # Debug Log Button Widget self.debug = QtGui.QPushButton('Debug Log', self) self.debug.clicked.connect(self.handleDebug) # Version button widget self.version = QtGui.QPushButton('Version', self) self.version.clicked.connect(self.handleVersion) # Versions second window that opens self.versionWindow = Vers(self) #Calls the Version window class #Calibration button widget self.calibration = QtGui.QPushButton('Glove Calibration', self) self.calibration.clicked.connect(self.handleCalibration) # Text widget: Will dispray number of taps self.tapData = QtGui.QLineEdit('Tap Data:') #self.tapData.setMinimumSize(1,1) self.tapData.setDisabled(True) # 3D Graph Plot Widget self.plot = gl.GLViewWidget() self.plot.show() # Plot actions/test #Code Reads from CSV, and creates data points #Code to collect max values from csv #create Axis sca = 60 n = sca / 20 self.axis = gl.GLAxisItem() self.axis.setSize(x=sca, y=sca, z=sca) self.plot.addItem(self.axis) #X grid self.xgrid = gl.GLGridItem() self.xgrid.rotate(90, 0, 1, 0) self.xgrid.translate(0 * n, 10 * n, 10 * n) # ( X translates X, Y trans Y, Z trans Z self.xgrid.scale(n, n, n) #xGrid scaling self.plot.addItem(self.xgrid) # Y Grid self.ygrid = gl.GLGridItem() self.ygrid.rotate(90, 0, 0, 1) self.ygrid.translate(10 * n, 10 * n, 0 * n) # ( Y trans X, X trans Y, Z trans Z) self.ygrid.scale(n, n, n) #yGrid scaling self.plot.addItem(self.ygrid) # Z Grid self.zgrid = gl.GLGridItem() self.zgrid.rotate(90, 1, 0, 0) self.zgrid.translate(10 * n, 0 * n, 10 * n) # (Z trans X, X trans Y, Y trans Z) self.zgrid.scale(n, n, n) # zGrid scaling self.plot.addItem(self.zgrid) self.pts = np.vstack([0, 0, 0]).transpose() self.plt = gl.GLLinePlotItem(pos=self.pts, color=pg.glColor((1, n * 1.3)), width=10., antialias=True) self.plot.addItem(self.plt) #Plots CSV data onto 3D plot ##### Layout manager of the widgets ##### layout = QtGui.QGridLayout() self.setLayout(layout) layout.addWidget(self.start, 0, 0, 1, 2) ## Start button layout.addWidget(self.updatePlot, 1, 0, 1, 2) layout.addWidget(self.instructions, 2, 0, 1, 2) ## Instructions button layout.addWidget(self.debug, 3, 0, 1, 2) ## Debug button layout.addWidget(self.version, 4, 0, 1, 2) ## Version button layout.addWidget(self.calibration, 5, 0, 1, 2) layout.addWidget(self.tapData, 6, 0, 1, 2) ## tapData text display layout.addWidget(self.plot, 0, 6, 6, 6) ##3D Plotting
layout.addWidget(stop_btn, 3, 1) layout.addWidget(reset_btn, 4, 1) slider = QtGui.QSlider(Qt.Horizontal) slider.setTickPosition(QtGui.QSlider.TicksBelow) slider.setSingleStep(1) slider.setRange(0, 9) slider.setValue(0) slider.valueChanged.connect(change_particle_size) slidervalue = QtGui.QLabel( 'Particle size = {:.1f}'.format(slider.value() / 10.0 + 0.1)) layout.addWidget(slider, 2, 0) layout.addWidget(slidervalue, 1, 0) grid = gl.GLViewWidget() grid.setCameraPosition(elevation=90, azimuth=0) ##, distance=0) verts = np.loadtxt("vertices.txt") faces = np.loadtxt("faces.txt", dtype=int) colors = np.genfromtxt("colours.txt", max_rows=len(faces), usecols=(0, 1, 2, 3)) ## Mesh item will automatically compute face normals. m1 = gl.GLMeshItem(vertexes=verts, faces=faces, faceColors=colors, smooth=False, drawEdges=True, edgeColor=(1, 1, 1, 1)) m1.translate(-0.75, -0.25, 0.0)
def init_figure(self): """Init figures""" self.canvas2d_cartesian = pg.GraphicsLayoutWidget() self.canvas2d_polar = pg.GraphicsLayoutWidget() self.canvas3d = gl.GLViewWidget() self.canvas3d_array = pg.GraphicsLayoutWidget() self.ui.layout_canvas.addWidget(self.canvas3d) self.ui.layout_canvas.addWidget(self.canvas3d_array) self.ui.layout_canvas.addWidget(self.canvas2d_cartesian) self.ui.layout_canvas.addWidget(self.canvas2d_polar) self.plot_type_changed(self.ui.cb_plottype.currentIndex()) """Surface view""" self.cmap = cm.get_cmap('jet') self.minZ = -100 self.maxZ = 0 self.surface_plot = gl.GLSurfacePlotItem(computeNormals=False) self.surface_plot.translate(0, 0, 100) self.axis = gl.GLAxisItem() self.canvas3d.addItem(self.axis) self.axis.setSize(x=150, y=150, z=150) self.xzgrid = gl.GLGridItem() self.yzgrid = gl.GLGridItem() self.xygrid = gl.GLGridItem() self.canvas3d.addItem(self.xzgrid) self.canvas3d.addItem(self.yzgrid) self.canvas3d.addItem(self.xygrid) self.xzgrid.setSize(x=180, y=100, z=0) self.xzgrid.setSpacing(x=10, y=10, z=10) self.yzgrid.setSize(x=100, y=180, z=0) self.yzgrid.setSpacing(x=10, y=10, z=10) self.xygrid.setSize(x=180, y=180, z=0) self.xygrid.setSpacing(x=10, y=10, z=10) # rotate x and y grids to face the correct direction self.xzgrid.rotate(90, 1, 0, 0) self.xzgrid.translate(0, -90, 50) self.yzgrid.rotate(90, 0, 1, 0) self.yzgrid.translate(-90, 0, 50) self.canvas3d.addItem(self.surface_plot) self.canvas3d.setCameraPosition(distance=300) """Array view""" self.array_view = pg.PlotItem() self.array_plot = pg.ScatterPlotItem() self.canvas3d_array.addItem(self.array_view) self.array_view.addItem(self.array_plot) self.array_view.setAspectLocked() self.array_view.setLabel(axis='bottom', text='Horizontal x', units='λ') self.array_view.setLabel( axis='left', text='Vertical y', units='λ') self.array_view.showGrid(x=True, y=True) self.array_plot.setPen(pg.mkPen(color=(244, 143, 177, 120), width=1)) self.array_plot.setBrush(pg.mkBrush(244, 143, 177, 200)) """Cartesian view""" self.cartesianView = pg.PlotItem() self.cartesianPlot = pg.PlotDataItem() self.cartesianPlotHold = pg.PlotDataItem() self.canvas2d_cartesian.addItem(self.cartesianView) self.penActive = pg.mkPen(color=(244, 143, 177), width=1) self.penHold = pg.mkPen(color=(158, 158, 158), width=1) self.cartesianPlot.setPen(self.penActive) self.cartesianPlotHold.setPen(self.penHold) self.cartesianView.addItem(self.cartesianPlot) self.cartesianView.setXRange(-90, 90) self.cartesianView.setYRange(-80, 0) self.cartesianView.setLabel(axis='bottom', text='Angle', units='°') self.cartesianView.setLabel( axis='left', text='Normalized amplitude', units='dB') self.cartesianView.showGrid(x=True, y=True, alpha=0.5) self.cartesianView.setLimits( xMin=-90, xMax=90, yMin=-110, yMax=1, minXRange=0.1, minYRange=0.1) """Polar view""" self.polarView = pg.PlotItem() self.polarPlot = pg.PlotDataItem() self.polarPlotHold = pg.PlotDataItem() self.canvas2d_polar.addItem(self.polarView) self.circleList = [] self.circleLabel = [] self.polarAmpOffset = 60 self.polarPlot.setPen(self.penActive) self.polarPlotHold.setPen(self.penHold) self.polarView.addItem(self.polarPlot) self.polarView.setAspectLocked() self.polarView.hideAxis('left') self.polarView.hideAxis('bottom') self.circleLabel.append(pg.TextItem('0 dB')) self.polarView.addItem(self.circleLabel[0]) self.circleLabel[0].setPos(self.polarAmpOffset, 0) for circle_idx in range(0, 6): self.circleList.append( QtGui.QGraphicsEllipseItem( -self.polarAmpOffset + self.polarAmpOffset / 6 * circle_idx, -self.polarAmpOffset + self.polarAmpOffset / 6 * circle_idx, (self.polarAmpOffset - self.polarAmpOffset / 6 * circle_idx) * 2, (self.polarAmpOffset - self.polarAmpOffset / 6 * circle_idx) * 2)) self.circleList[circle_idx].setStartAngle(2880) self.circleList[circle_idx].setSpanAngle(2880) self.circleList[circle_idx].setPen(pg.mkPen(0.2)) self.polarView.addItem(self.circleList[circle_idx]) self.circleLabel.append( pg.TextItem(str(-self.polarAmpOffset / 6 * (circle_idx + 1)))) self.circleLabel[circle_idx + 1].setPos( self.polarAmpOffset - self.polarAmpOffset / 6 * ( circle_idx + 1), 0) self.polarView.addItem(self.circleLabel[circle_idx + 1]) self.polarView.addLine(x=0, pen=0.6) self.polarView.addLine(y=0, pen=0.6) self.polarView.addLine(y=0, pen=0.3).setAngle(45) self.polarView.addLine(y=0, pen=0.3).setAngle(-45) self.polarView.setMouseEnabled(x=False, y=False)
(.9, .9 * .5, .0, 1), (.9, .9 * .5, .0, 1)]) def vertMarker(x, y, z): it = pgl.GLMeshItem(vertexes=vertV, faces=vertF, faceColors=colorF, smooth=False, computeNormals=False) it.translate(x, y, z) return it i = 0 app = pg.mkQApp() view = pgl.GLViewWidget() view.showMaximized() # view.show() posS = set(posV) for pos in posV: x, y, z = pos if (x - 1, y, z) in posS and (x + 1, y, z) in posS and ( x, y - 1, z) in posS and (x, y + 1, z) in posS and ( x, y, z - 1) in posS and (x, y, z + 1) in posS: continue i += 1 view.addItem(vertMarker(*pos)) view.setBackgroundColor((.1, .1, .1)) view.pan((x0 + x1) / 2, (y0 + y1) / 2, (z0 + z1) / 2)
def Initialize(): app = QtGui.QApplication([]) w = gl.GLViewWidget() w.opts['distance'] = 800 w.show() w.setWindowTitle('Tracked Position') w.move(20, 600) g = gl.GLGridItem() g.scale(25, 25, 1) w.addItem(g) ### finger points pos = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) size = np.array([10, 10, 10]) color = np.array([[1.0, 0.0, 0.0, 0.8], [0.0, 0.0, 1.0, 0.8], [0.0, 1.0, 0.0, 0.8]]) SP = gl.GLScatterPlotItem(pos=pos, size=size, color=color, pxMode=False) w.addItem(SP) ### heading vector pos = np.array([[0, 0, 0], [1, 1, 1]]) width = 2 color = np.array([[0.25, 0.25, 0.75, 1], [0.25, 0.25, 0.75, 1]]) LPh = gl.GLLinePlotItem(pos=pos, color=color, width=width, antialias=True) w.addItem(LPh) ### roll vector pos = np.array([[0, 0, 0], [1, 1, 1]]) width = 2 color = np.array([[0.25, 0.75, 0.25, 1], [0.25, 0.75, 0.25, 1]]) LPr = gl.GLLinePlotItem(pos=pos, color=color, width=width, antialias=True) w.addItem(LPr) ### joint positions pos = np.zeros((7, 3)) width = 3 size = 5 colorline = np.array([[0.5, 0.5, 0.5, 1]]) colorline = np.tile(colorline, (8, 1, 1)) color = np.array([[0.25, 0.25, 0.75, 1], [0.75, 0.25, 0.25, 1], [0.25, 0.75, 0.25, 1], [0.25, 0.25, 0.75, 1], [0.75, 0.25, 0.25, 1], [0.25, 0.75, 0.25, 1], [0.25, 0.25, 0.75, 1], [0.75, 0.25, 0.25, 1]]) armLines = gl.GLLinePlotItem(pos=pos, color=colorline, width=width, antialias=True) jointPos = gl.GLScatterPlotItem(pos=pos, size=size, color=color, pxMode=False) w.addItem(armLines) w.addItem(jointPos) ### joint coordinate systems p_0 = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]) width = 3 color = np.array([[0.75, 0.25, 0.25, 1], [0.25, 0.75, 0.25, 1], [0.25, 0.25, 0.75, 1]]) jointCoords = [] for i in range(7): jointXYZ = [] for j in range(3): pos = np.array([p_0[:3, j] + p_0[:3, 3], p_0[:3, 3]]) print pos jXYZ = gl.GLLinePlotItem(pos=pos, color=np.tile(color[j, :], (2, 1)), width=width, antialias=True) w.addItem(jXYZ) jointXYZ.append(jXYZ) jointCoords.append(jointXYZ) return app, w, SP, LPh, LPr, armLines, jointPos, jointCoords
def _make_glview(self): self.glview = gl.GLViewWidget() self.glview.opts['distance'] = 40 #self.glview.pan(dx=0, dy=0, dz=100) self._make_grid() self._make_quad()
def init_view(self): v = gl.GLViewWidget() self.dock.addWidget(v) v.setWindowTitle('') v.setCameraPosition(distance=1500, azimuth=-30, elevation=50) return v
def __init__(self): # Prepare Qt app = QtWidgets.QApplication([]) # Prepare window and OpenGL environment self.__widget = gl.GLViewWidget() self.__widget.setWindowTitle("Quantum by AgenttiX") self.__widget.show() # Create grid # grid = gl.GLGridItem() # grid.scale(10, 10, 1) # self.__widget.addItem(grid) # Default quantum numbers self.__n = 3 self.__l = 1 self.__m = 1 self.__Z = 1 self.__rdist = 50 self.__data = np.zeros((self.__rdist, self.__rdist, self.__rdist), dtype=complex) # Computation parameters self.__zoom = 1 widget2 = QtWidgets.QWidget() widget2.setWindowTitle("Quantum by AgenttiX") layout = QtWidgets.QGridLayout() widget2.setLayout(layout) self.radial = None self.__abs = None self.__volume = None labels = ["n", "l", "m", "Z"] for i, text in enumerate(labels): label = QtWidgets.QLabel() label.setText(text) layout.addWidget(label, i, 0) # Value inputs self.__input_n = pg.SpinBox(value=self.__n, int=True, dec=True, minStep=1, step=1) layout.addWidget(self.__input_n, 0, 1) self.__input_l = pg.SpinBox(value=self.__l, int=True, dec=True, minStep=1, step=1) layout.addWidget(self.__input_l, 1, 1) self.__input_m = pg.SpinBox(value=self.__m, int=True, dec=True, minStep=1, step=1) layout.addWidget(self.__input_m, 2, 1) self.__input_Z = pg.SpinBox(value=self.__Z, int=True, dec=True, minStep=1, step=1) layout.addWidget(self.__input_Z, 3, 1) self.__updateButton = QtWidgets.QPushButton("Update") layout.addWidget(self.__updateButton, 4, 1) self.__updateButton.clicked.connect(self.update) self.__infoLabel = QtWidgets.QLabel() layout.addWidget(self.__infoLabel, 5, 1) widget2.show() # Compute for the first time self.__first = True self.update() # Main loop app.exec()
xold = xnew yold = ynew i = i + 1 lst.append([xnew, ynew, 0]) print("------------------------------------------------------------\n") print(" ", i, "\t", xnew, "\t", ynew, "\t", err) return i, lst x = float(input('請輸入x: ')) y = float(input('請輸入y: ')) time, lis = newton(x, y) pos = np.array(lis, 'float32') app = QtGui.QApplication([]) glWidget = gl.GLViewWidget() glWidget.show() gridx = gl.GLGridItem() gridx.rotate(90, 0, 1, 0) #90度 #gridx.rotate(45, 0, 0, 1) gridx.translate(0, 0, 0) #-10,0,0 glWidget.addItem(gridx) gridy = gl.GLGridItem() gridy.rotate(90, 1, 0, 0) #gridy.rotate(45, 0, 0, 1) gridy.translate(0, 0, 0) #0,-10,0 glWidget.addItem(gridy) gz = gl.GLGridItem() gz.translate(0, 0, 0) glWidget.addItem(gz) #glWidget.opts['distance'] = 24
def add3DPlot(self, layout): if not self.GL_ENABLED: print('OpenGL not available') return False ''' try: w = gl.GLViewWidget() except: self.GL_ENABLED = False return w.opts['distance'] = 40 layout.addWidget(w) w.setWindowTitle('3D line Spectra') gz = gl.GLGridItem() gz.translate(0, 0, -self.width/2) w.addItem(gz) self.plot = w ''' try: w2 = gl.GLViewWidget() except: self.GL_ENABLED = False return w2.opts['distance'] = 80 layout.addWidget(w2) w2.setWindowTitle('3D surface Spectra') gz = gl.GLGridItem() gz.translate(0, 0, -self.width / 2) w2.addItem(gz) self.plot2 = gl.GLSurfacePlotItem(color=(.2, .1, 0, 0.5), computeNormals=False, smooth=False) #plt.shader()['colorMap'] = np.array([0.2, 2, 0.5, 0.2, 1, 1, 0.2, 0, 2]) #plt.translate(10, 10, 0) w2.addItem(self.plot2) self.plot2.translate(-self.width / 2, -self.width / 2, -self.width / 2) self.start_time = time.time() verts = np.array([[ [0, 0, 0], [0, self.width, -self.width / 5], [0, self.width, self.width / 5], ]]) self.m2colors = [[[0.11650455, 0.11115034, 0.64362394, 0.82398102], [0.63367245, 0.8738815, 0.95143971, 0.18921984], [0.3180938, 0.81616747, 0.6948056, 0.19030863]]] self.m2edgeColor = (1, 1, 0, 1) self.m2 = gl.GLMeshItem(vertexes=verts, vertexColors=self.m2colors, smooth=False, shader='balloon', drawEdges=True, edgeColor=self.m2edgeColor) self.m2.translate(-self.width / 2, -self.width / 2, -self.width / 2) self.m2.setGLOptions('additive') w2.addItem(self.m2) verts = np.array([[ [self.width, 0, 0], [self.width, self.width, -self.width / 5], [self.width, self.width, self.width / 5], ]]) self.m3 = gl.GLMeshItem(vertexes=verts, vertexColors=self.m2colors, smooth=False, shader='balloon', drawEdges=True, edgeColor=self.m2edgeColor) self.m3.translate(-self.width / 2, -self.width / 2, -self.width / 2) self.m3.setGLOptions('additive') w2.addItem(self.m3)
def __init__(self, points=None): '''Initialize this class. Input: points <np.array> [particle index [xyz coordinate [point <float>]]] Output: None''' # Initialize the parent QtGui.QWidget.__init__(self) # All of the points for all of the particles (these are precalculated) self.points = points # Create a counter frame and set the frame's attributes self.counterFrame = QtGui.QFrame() self.counterFrame.setFrameShadow(QtGui.QFrame.Sunken) self.counterFrame.setFrameShape(QtGui.QFrame.Box) # Create a controls frame and set the frame's attributes self.controlsFrame = QtGui.QFrame() self.controlsFrame.setFrameShadow(QtGui.QFrame.Raised) self.controlsFrame.setFrameShape(QtGui.QFrame.Panel) # Create the layouts self.mainLayout = QtGui.QVBoxLayout(self) self.counterLayout = QtGui.QHBoxLayout(self.counterFrame) self.controlsLayout = QtGui.QHBoxLayout(self.controlsFrame) self.viewLayout = QtGui.QHBoxLayout() # The starting time index (i.e. of the X number of points given, start at this one) self.initialPointIndex = 1 # The initial step size self.initialStepSize = 50 # The initial delay when "playing" the graph self.initialDelay = 40 # When fast-forwarding or rewinding, increase/decrease the timer's interval by this amount self.timerStepSize = 20 # Create a bold font self.boldFont = QtGui.QFont() self.boldFont.setBold(True) # Create a counter label self.counterLabel = QtGui.QLabel("Counter") self.counterLabel.setFont(self.boldFont) # Create a counter line edit self.counterLineEdit = QtGui.QLineEdit() self.counterLineEdit.setReadOnly(True) self.counterLineEdit.setAlignment(QtCore.Qt.AlignRight) self.counterLineEdit.setFixedWidth( QtGui.QFontMetrics(self.counterLineEdit.font()).width("0000000") + 20) # Create a step size label self.stepSizeLabel = QtGui.QLabel("Step") self.stepSizeLabel.setFont(self.boldFont) # Create a step size spin box self.stepSizeSpinBox = QtGui.QSpinBox() self.stepSizeSpinBox.setValue(self.initialStepSize) # Create a timer label self.timerLabel = QtGui.QLabel("Time Interval (ms)") self.timerLabel.setFont(self.boldFont) # Create a timer spin box self.timerSpinBox = QtGui.QSpinBox() self.timerSpinBox.setRange(0, 10000) self.timerSpinBox.setValue(self.initialDelay) # Create a time slider self.timeSlider = QtGui.QSlider() self.timeSlider.setSingleStep(1) self.timeSlider.setOrientation(QtCore.Qt.Horizontal) self.timeSlider.setEnabled(False) # Create the graph view self.view = gl.GLViewWidget() # Create the x, y, and z grids self.xGrid = gl.GLGridItem() self.yGrid = gl.GLGridItem() self.zGrid = gl.GLGridItem() # Rotate the x and y grid self.xGrid.rotate(90, 0, 1, 0) self.yGrid.rotate(90, 1, 0, 0) # Create x, y, and z axis (drawn as line plots) self.xAxis = gl.GLLinePlotItem(pos=np.array([[-10.0, 0.0, 0.0], [10.0, 0.0, 0.0]]), color=np.array([[1.0, 0.0, 0.0, 0.4], [1.0, 0.0, 0.0, 0.4]]), width=3.0) self.yAxis = gl.GLLinePlotItem(pos=np.array([[0.0, -10.0, 0.0], [0.0, 10.0, 0.0]]), color=np.array([[0.0, 1.0, 0.0, 0.4], [0.0, 1.0, 0.0, 0.4]]), width=3.0) self.zAxis = gl.GLLinePlotItem(pos=np.array([[0.0, 0.0, -10.0], [0.0, 0.0, 10.0]]), color=np.array([[0.0, 0.0, 1.0, 0.4], [0.0, 0.0, 1.0, 0.4]]), width=3.0) # Add the x, y, and z line plots to the view self.view.addItem(self.xAxis) self.view.addItem(self.yAxis) self.view.addItem(self.zAxis) # A list of scatter plots self.scatterList = [] # A list of line plots self.lineList = [] # Add graph items to the view self.view.addItem(self.xGrid) self.view.addItem(self.yGrid) self.view.addItem(self.zGrid) # Set the view's resize policy self.view.setSizePolicy(QtGui.QSizePolicy.MinimumExpanding, QtGui.QSizePolicy.MinimumExpanding) # Set the initial color values self.colors = [] # Create play and pause icons self.playIcon = QtGui.QIcon(sys.path[0] + "/icons/play.png") self.pauseIcon = QtGui.QIcon(sys.path[0] + "/icons/pause.png") # Create control buttons and disable them by default self.playPauseButton = self.createIconButton(self.playIcon, tooltip="Play") self.playPauseButton.setEnabled(False) self.ffButton = self.createIconButton( QtGui.QIcon(sys.path[0] + "/icons/fastforward.png"), tooltip="Faster") self.ffButton.setEnabled(False) self.rewindButton = self.createIconButton( QtGui.QIcon(sys.path[0] + "/icons/rewind.png"), tooltip="Slower") self.rewindButton.setEnabled(False) self.stepForwardButton = self.createIconButton( QtGui.QIcon(sys.path[0] + "/icons/stepforward.png"), tooltip="Step Forward") self.stepForwardButton.setEnabled(False) self.stepBackwardButton = self.createIconButton( QtGui.QIcon(sys.path[0] + "/icons/stepbackward.png"), tooltip="Step Backward") self.stepBackwardButton.setEnabled(False) # Create the reverse button self.reverseButton = QtGui.QCheckBox("Reverse") self.reverseButton.setFont(self.boldFont) # Create the reverse button self.loopButton = QtGui.QCheckBox("Loop") self.loopButton.setFont(self.boldFont) # Create an exit button self.exitButton = QtGui.QPushButton("Exit") self.exitButton.setToolTip("Exit this application") self.exitButton.setFont(self.boldFont) # Create a load button self.loadButton = QtGui.QPushButton("Load Points") self.loadButton.setToolTip("Load points to be shown on the graph") self.loadButton.setFont(self.boldFont) # Turn on the main context menu self.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu) # Create a plot list widget self.plotListWidget = QtGui.QListWidget() self.plotListWidget.setSizePolicy(QtGui.QSizePolicy.Maximum, QtGui.QSizePolicy.Preferred) self.plotListWidget.setVisible(False) # Create context menu actions self.showPlotListAction = QtGui.QAction("Show Plot List", self) self.showPlotListAction.setCheckable(True) self.xAction = QtGui.QAction("Show X Grid", self) self.xAction.setCheckable(True) self.xAction.setChecked(True) self.yAction = QtGui.QAction("Show Y Grid", self) self.yAction.setCheckable(True) self.yAction.setChecked(True) self.zAction = QtGui.QAction("Show Z Grid", self) self.zAction.setCheckable(True) self.zAction.setChecked(True) self.separator = QtGui.QAction(self) self.separator.setSeparator(True) # Add the actions to the context menu self.addActions([ self.showPlotListAction, self.separator, self.xAction, self.yAction, self.zAction ]) # Add widgets to the counter layout self.counterLayout.addWidget(self.counterLabel) self.counterLayout.addWidget(self.counterLineEdit) self.counterLayout.addSpacing(20) self.counterLayout.addWidget(self.stepSizeLabel) self.counterLayout.addWidget(self.stepSizeSpinBox) self.counterLayout.addStretch(0) self.counterLayout.addWidget(self.timerLabel) self.counterLayout.addWidget(self.timerSpinBox) # Add widgets to the controls layout self.controlsLayout.addWidget(self.reverseButton) self.controlsLayout.addWidget(self.loopButton) self.controlsLayout.addStretch(0) self.controlsLayout.addWidget(self.stepBackwardButton) self.controlsLayout.addWidget(self.rewindButton) self.controlsLayout.addWidget(self.playPauseButton) self.controlsLayout.addWidget(self.ffButton) self.controlsLayout.addWidget(self.stepForwardButton) self.controlsLayout.addStretch(0) self.controlsLayout.addWidget(self.loadButton) self.controlsLayout.addWidget(self.exitButton) # Add widgets to the view layout self.viewLayout.addWidget(self.view) self.viewLayout.addWidget(self.plotListWidget) # Make sure the counter and controls don't take up too much vertical space self.counterFrame.setSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed) self.controlsFrame.setSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed) # Add widgets and layouts to the main layout self.mainLayout.addWidget(self.counterFrame) self.mainLayout.addLayout(self.viewLayout) self.mainLayout.addWidget(self.timeSlider) self.mainLayout.addWidget(self.controlsFrame) # Initialize the counter self.counterLineEdit.setText(str(self.timeSlider.value())) # Create a timer (when this times out, the graph updates) self.timer = QtCore.QTimer() # Set the timer's interval (in ms) self.timer.setInterval(self.timerSpinBox.value()) # Initilize the graph self.initializeGraph() # Connect all the signals self.timer.timeout.connect(self.timeout) self.playPauseButton.clicked.connect(self.playPause) self.ffButton.clicked.connect(self.fastForward) self.rewindButton.clicked.connect(self.rewind) self.stepForwardButton.clicked.connect(self.stepForward) self.stepBackwardButton.clicked.connect(self.stepBackward) self.timerSpinBox.valueChanged[int].connect(self.timer.setInterval) self.loadButton.clicked.connect(self.loadPointsButtonClicked) self.exitButton.clicked.connect(exit) self.xAction.toggled.connect(self.showHideXGrid) self.yAction.toggled.connect(self.showHideYGrid) self.zAction.toggled.connect(self.showHideZGrid) self.showPlotListAction.toggled.connect(self.plotListWidget.setVisible) self.timeSlider.valueChanged.connect(self.timeSliderChanged) self.plotListWidget.itemChanged.connect(self.plotItemChanged)
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 method suitable for non-Jupyter use (i.e. via the Python \ console). By default, if the point cloud exceeds 5e5 points, then it is downsampled using a uniform random \ distribution of 5e5 points. 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 aritgmetic 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()
def pg_plot_signal(G, signal, show_edges=None, cp=[-6, -3, 160], vertex_size=None, vertex_highlight=False, climits=None, colorbar=True, bar=False, bar_width=1, plot_name=None): r""" Plot a graph signal in 2D or 3D, with pyqtgraph. See plot_signal for full documentation. """ if np.sum(np.abs(signal.imag)) > 1e-10: raise ValueError("Can't display complex signal.") if show_edges is None: show_edges = G.Ne < 10000 if vertex_size is None: vertex_size = 15 if climits is None: cmin = 1.01 * np.min(signal) cmax = 1.01 * np.max(signal) climits = [cmin, cmax] # pygtgraph window initialization in 2D and 3D global window_list if 'window_list' not in globals(): window_list = {} if G.coords.shape[1] == 2: w = pg.GraphicsWindow(plot_name or G.gtype) v = w.addViewBox() elif G.coords.shape[1] == 3: app = QtGui.QApplication([]) w = gl.GLViewWidget() w.opts['distance'] = 10 w.show() w.setWindowTitle(plot_name or G.gtype) # Plot edges if show_edges: ki, kj = np.nonzero(G.A) if G.directed: raise NotImplementedError('TODO') if G.coords.shape[1] == 2: raise NotImplementedError('TODO') else: raise NotImplementedError('TODO') else: if G.coords.shape[1] == 2: adj = np.concatenate( (np.expand_dims(ki, axis=1), np.expand_dims(kj, axis=1)), axis=1) g = pg.GraphItem(pos=G.coords, adj=adj, symbolBrush=None, symbolPen=None) v.addItem(g) if G.coords.shape[1] == 3: # Very dirty way to display a 3d graph x = np.concatenate((np.expand_dims(G.coords[ki, 0], axis=0), np.expand_dims(G.coords[kj, 0], axis=0))) y = np.concatenate((np.expand_dims(G.coords[ki, 1], axis=0), np.expand_dims(G.coords[kj, 1], axis=0))) z = np.concatenate((np.expand_dims(G.coords[ki, 2], axis=0), np.expand_dims(G.coords[kj, 2], axis=0))) ii = range(0, x.shape[1]) x2 = np.ndarray((0, 1)) y2 = np.ndarray((0, 1)) z2 = np.ndarray((0, 1)) for i in ii: x2 = np.append(x2, x[:, i]) for i in ii: y2 = np.append(y2, y[:, i]) for i in ii: z2 = np.append(z2, z[:, i]) pts = np.concatenate( (np.expand_dims(x2, axis=1), np.expand_dims( y2, axis=1), np.expand_dims(z2, axis=1)), axis=1) g = gl.GLLinePlotItem(pos=pts, mode='lines') gp = gl.GLScatterPlotItem(pos=G.coords, color=(1., 0., 0., 1)) w.addItem(g) w.addItem(gp) # Plot signal on top 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 = pg.ColorMap(pos, color) mininum = min(signal) maximum = max(signal) normalized_signal = [ 1 + 63 * (float(x) - mininum) / (maximum - mininum) for x in signal ] if G.coords.shape[1] == 2: gp = pg.ScatterPlotItem(G.coords[:, 0], G.coords[:, 1], size=vertex_size, brush=cmap.map(normalized_signal, 'qcolor')) v.addItem(gp) if G.coords.shape[1] == 3: gp = gl.GLScatterPlotItem(G.coords[:, 0], G.coords[:, 1], G.coords[:, 2], size=vertex_size, c=signal) w.addItem(gp) # Multiple windows handling if G.coords.shape[1] == 2: window_list[str(uuid.uuid4())] = w elif G.coords.shape[1] == 3: window_list[str(uuid.uuid4())] = app
def __init__(self): self.app = QtGui.QApplication(sys.argv) self.w = gl.GLViewWidget() self.w.setGeometry(0, 100, 1920, 1080) self.w.show() self.w.setWindowTitle('Terrain') self.w.setCameraPosition(distance=30, elevation=8) # grid = gl.GLGridItem() # grid.scale(2, 2, 2) # self.w.addItem(grid) self.NSTEPS = 1 self.ypoints = range(-20, 22, self.NSTEPS) self.xpoints = range(-20, 22, self.NSTEPS) self.nfaces = len(self.ypoints) self.offset = 0 # Colours to match the ENSWBL asthetic self.startR = 0.2 self.startG = 0.2 self.startB = 0.2 self.endR = 96.4 / 255 self.endG = 0 / 255 self.endB = 100 / 255 self.rStep = (self.endR - self.startR) / 20 self.gStep = (self.endG - self.startG) / 20 self.bStep = (self.endB - self.startB) / 20 self.open_simplex = OpenSimplex() verts = np.array( [[x, y, 2.5 * self.open_simplex.noise2d(x=n / 5, y=m / 5)] for n, x in enumerate(self.xpoints) for m, y in enumerate(self.ypoints)], dtype=np.float32) faces = [] colours = [] 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]) colours.append([0, 0, 0, 0]) colours.append([0, 0, 0, 0]) faces = np.array(faces) colours = np.array(colours) self.mesh1 = gl.GLMeshItem(vertexes=verts, faces=faces, faceColors=colours, smooth=True, drawEdges=False) self.mesh1.setGLOptions('additive') self.w.addItem(self.mesh1)
for i in range(1, const): weight_Di_1 = i / const weight_Di = 1 - weight_Di_1 mask_diastole.append( weight_Di_1 * mask3_before + weight_Di * mask3 ) mask3_before = mask3 mask_diastole.append( mask3 ) mask_diastole = np.dstack(mask_diastole) print(mask_diastole.shape) # Create an PyQT4 application object. app = QtGui.QApplication(sys.argv) # Create a window object. window = gl.GLViewWidget() window.resize(500, 500) window.setCameraPosition(distance=100) window.setWindowTitle('pyqtgraph : GLIsosurface') window.show() # uniform_filter() is equivalent to smooth3() in matlab. mask_diastole = scipy.ndimage.uniform_filter(mask_diastole, [5, 5, 20], mode='nearest') # Using marching cubes algorithm to get a polygonal mesh of an isosurface verts, faces = measure.marching_cubes(mask_diastole, 0.1) meshdata = gl.MeshData(vertexes=verts, faces=faces) mesh = gl.GLMeshItem(meshdata=meshdata, smooth=True, color=(1.0, 0.0, 0.0, 0.2), shader='balloon', glOptions='additive') # Translation [avgX, avgY, avgZ] = map(np.mean, zip(*verts))
def __init__(self,parent): self.traces = dict() self.app = QtGui.QApplication(sys.argv) #Main Widget containing everything self.mainWidget= QWidget(parent= parent) self.mainWidget.setGeometry(0, 0, 1400,1000) # general layout self.layout_general = QVBoxLayout(self.mainWidget) #Top Layout self.layout_top = QHBoxLayout( ) self.layout_general.addLayout(self.layout_top,70) #Top Layout self.layout_bottom = QHBoxLayout() self.layout_general.addLayout(self.layout_bottom,30) # Live Data text area self.data_info_text = QLabel('Live Data info') self.layout_top.addWidget(self.data_info_text,15) # 20% of the width #Anim 3D self.D3_holder = QWidget(parent=self.mainWidget ) self.w = gl.GLViewWidget(parent= self.D3_holder) self.layout_top.addWidget( self.w ,85) # 80% of the width # Plot self.plots = pg.GraphicsWindow(title="Basic plotting examples") pg.setConfigOptions(antialias=True) self.layout_bottom.addWidget( self.plots ,20) # 80% of the width #self.mainWidget.setLayout(self.layout) #self.w = gl.GLViewWidget() self.w.opts["distance"] = 160 self.w.setWindowTitle("3D view track") #self.w.setGeometry(0, 110, 720, 480) self.df = None self.track = None self.track_is_ploted = False self.index = 0 self.step_interval =None # Created the geometrie models_path = os.path.dirname(os.path.abspath(__file__)) obj = "simple_body.obj" obj_path = os.path.join(models_path, "3D_model", obj) self.geom = Create_geom.obj(obj_path) # create the background grids gx = gl.GLGridItem() gx.rotate(90, 0, 1, 0) gx.translate(-9, 0, 0) self.w.addItem(gx) gy = gl.GLGridItem() gy.rotate(90, 1, 0, 0) gy.translate(0, -10, 0) self.w.addItem(gy) gz = gl.GLGridItem() gz.translate(0, 0, -10) self.w.addItem(gz) xsize = QtGui.QVector3D(7, 7, 7) ax = gl.GLAxisItem(size=xsize, antialias=True, glOptions="translucent") self.w.addItem(ax) self.w.addItem(self.geom)
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.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 plot3DQTGraph(self): sphereDebug = 0 self.pcplot = gl.GLViewWidget() dummy = np.zeros((1, 3)) #use if need to debug the ellipsoid drawing if (sphereDebug == 1): colorArray = ('r', 'g', 'b', 'w', 'y') colors = np.zeros((42, 4)) for c in range(0, 7): colors[c * 6:c * 6 + 6, :] = pg.glColor(colorArray[c % 5]) sphereTrigs = getSphereMesh() self.sphere = gl.GLMeshItem(vertexes=sphereTrigs, smooth=False, drawEdges=True, edgeColor=pg.glColor('w'), drawFaces=False) self.pcplot.addItem(self.sphere) # create the background grids self.gz = gl.GLGridItem() self.gz.translate(0, 0, -2) self.boundaryBoxViz = [gl.GLLinePlotItem(), gl.GLLinePlotItem()] self.bottomSquare = [gl.GLLinePlotItem(), gl.GLLinePlotItem()] for box in self.boundaryBoxViz: box.setVisible(False) self.scatter = gl.GLScatterPlotItem(size=5) self.scatter.setData(pos=dummy) self.pcplot.addItem(self.gz) self.pcplot.addItem(self.boundaryBoxViz[0]) self.pcplot.addItem(self.boundaryBoxViz[1]) self.pcplot.addItem(self.bottomSquare[0]) self.pcplot.addItem(self.bottomSquare[1]) self.pcplot.addItem(self.scatter) #create box to represent device verX = 0.0625 verY = 0.05 verZ = 0.125 verts = np.empty((2, 3, 3)) verts[0, 0, :] = [-verX, 0, verZ] verts[0, 1, :] = [-verX, 0, -verZ] verts[0, 2, :] = [verX, 0, -verZ] verts[1, 0, :] = [-verX, 0, verZ] verts[1, 1, :] = [verX, 0, verZ] verts[1, 2, :] = [verX, 0, -verZ] self.evmBox = gl.GLMeshItem(vertexes=verts, smooth=False, drawEdges=True, edgeColor=pg.glColor('r'), drawFaces=False) self.pcplot.addItem(self.evmBox) #add mesh objects for ellipsoids self.ellipsoids = [] #self.dataImages = [] edgeColor = pg.glColor('k') for m in range(0, 20): #zeroEllipsoid = getSphereMesh(xc=100*m,yc=100*m,zc=100*m,xRadius=0.1,yRadius=0.1,zRadius=0.1) #mesh = gl.GLMeshItem() #mesh.setMeshData(vertexes=zeroEllipsoid,smooth=False,drawEdges=True,edgeColor=edgeColor,drawFaces=False) mesh = gl.GLLinePlotItem() mesh.setVisible(False) self.pcplot.addItem(mesh) self.ellipsoids.append(mesh)
# -*- coding: utf-8 -*- """ Demonstration of some of the shader programs included with pyqtgraph that can be used to affect the appearance of a surface. """ ## Add path to library (just for examples; you do not need this) from pyqtgraph.Qt import QtCore, QtGui import pyqtgraph as pg import pyqtgraph.opengl as gl app = QtGui.QApplication([]) w = gl.GLViewWidget() w.show() w.setWindowTitle('pyqtgraph example: GL Shaders') w.setCameraPosition(distance=15, azimuth=-90) g = gl.GLGridItem() g.scale(2, 2, 1) w.addItem(g) import numpy as np md = gl.MeshData.sphere(rows=2, cols=3) x = np.linspace(-8, 8, 6) m1 = gl.GLMeshItem(meshdata=md, smooth=True, color=(1, 0, 0, 0.2), shader='balloon',
def __init__(self): QtCore.QThread.__init__(self) self.app = QtGui.QApplication([]) self.w = gl.GLViewWidget() self.w.opts['distance'] = 200 self.w.show() self.w.setWindowTitle('Quadcopter Simulation') ## create three grids, add each to the view xgrid = gl.GLGridItem() ygrid = gl.GLGridItem() zgrid = gl.GLGridItem() self.w.addItem(xgrid) self.w.addItem(ygrid) self.w.addItem(zgrid) ## rotate x and y grids to face the correct direction xgrid.rotate(90, 0, 1, 0) ygrid.rotate(90, 1, 0, 0) xgrid.scale(1.0, 1.0, 1.0) ygrid.scale(1.0, 1.0, 1.0) zgrid.scale(1.0, 1.0, 1.0) rad = 0.5 arm_length = 1.0 + rad arm_width = 0.25/2. arm_height = 0.25/2. arm = np.array([ [-arm_width, -0, -arm_height], [-arm_width, -0, arm_height], [-arm_width, arm_length, -arm_height], [-arm_width, arm_length, arm_height], [arm_width, arm_length, -arm_height], [arm_width, arm_length, arm_height], [arm_width, -0, -arm_height], [arm_width, -0, arm_height], ]) rot_z1 = np.array([[cos(np.pi/4), -sin(np.pi/4), 0], [sin(np.pi/4), cos(np.pi/4), 0], [0., 0., 1.]]) rot_z2 = np.array([[cos(3*np.pi/4), -sin(3*np.pi/4), 0], [sin(3*np.pi/4), cos(3*np.pi/4), 0], [0., 0., 1.]]) rot_z3 = np.array([[cos(-np.pi/4), -sin(-np.pi/4), 0], [sin(-np.pi/4), cos(-np.pi/4), 0], [0., 0., 1.]]) rot_z4 = np.array([[cos(-3*np.pi/4), -sin(-3*np.pi/4), 0], [sin(-3*np.pi/4), cos(-3*np.pi/4), 0], [0., 0., 1.]]) verts1 = np.matmul(arm, rot_z1) verts2 = np.matmul(arm, rot_z2) verts3 = np.matmul(arm, rot_z3) verts4 = np.matmul(arm, rot_z4) faces = np.array([ [0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 0], [7, 0, 1], [1, 3, 5], [1, 7, 5], [0, 2, 4], [0, 6, 4] ]) colors_back = np.array([ [1, 0, 0, 0.3], [1, 0, 0, 0.3], [1, 0, 0, 0.3], [1, 0, 0, 0.3], [1, 0, 0, 0.3], [1, 0, 0, 0.3], [1, 0, 0, 0.3], [1, 0, 0, 0.3], [1, 0, 0, 0.3], [1, 0, 0, 0.3] ]) colors_front = np.array([ [1, 1, 1, 0.3], [1, 1, 1, 0.3], [1, 1, 1, 0.3], [1, 1, 1, 0.3], [1, 1, 1, 0.3], [1, 1, 1, 0.3], [1, 1, 1, 0.3], [1, 1, 1, 0.3], [1, 1, 1, 0.3], [1, 1, 1, 0.3] ]) # ## Mesh item will automatically compute face normals. self.arm1 = gl.GLMeshItem(vertexes=verts1, faces=faces, faceColors=colors_back, smooth=False) self.arm2 = gl.GLMeshItem(vertexes=verts2, faces=faces, faceColors=colors_back, smooth=False) self.arm3 = gl.GLMeshItem(vertexes=verts3, faces=faces, faceColors=colors_front, smooth=False) self.arm4 = gl.GLMeshItem(vertexes=verts4, faces=faces, faceColors=colors_front, smooth=False) self.w.addItem(self.arm1) self.w.addItem(self.arm2) self.w.addItem(self.arm3) self.w.addItem(self.arm4) md = gl.MeshData.sphere(rows=10, cols=10, radius=rad) self.body = gl.GLMeshItem(meshdata=md, smooth=False, drawFaces=True, drawEdges=True, edgeColor=(1,0,0,1), color=(1,0,0,1) ) self.w.addItem(self.body) # Keep track of my own state self.x = np.zeros((12,))