def run(self, rom_path): # Firstly load the ROM self.cpu.memory.read_rom(rom_path) # Setup a canvas canvas = GameBoy.GBCanvas() app.run() while self.running: # Increment the PC if self.debug: print("Exec PC: " + str(hex(self.cpu.r["pc"]))) # Firstly execute an instruction self.cpu.executeOpcode(self.cpu.memory.read(self.cpu.r["pc"])) # Sync the GPU with the CPU self.gpu.sync(self.cpu.last_clock_inc) # Get a frame if it is ready frame = self.gpu.get_frame() if frame is not None: # Place the frame into the current canvas.set_frame(frame) self.cpu.incPC()
def show(self): if self._points is None: raise ValueError("Points is empty, please call imgToPoints() first.") # centralize self.centralize() # colors colors = np.array(np.abs(self._points[:,:3]),dtype=np.float32) mx = np.max(colors[:,0]) my = np.max(colors[:,1]) mz = np.max(colors[:,2]) brighter = 0.05 colors[:,0]/=mx+brighter colors[:,1]/=my+brighter colors[:,2]/=mz+brighter alpha = np.empty((len(colors[:,0]),1)) alpha.fill(0.8) colors = np.hstack([colors,alpha]) # sizes sizes = self.histogramEqualize() # visualize c = Canvas(self._points[:,:3],colors,sizes) app.run()
def vispy_plot(): from vispy import app, scene, io # Prepare canvas canvas = scene.SceneCanvas(keys='interactive', size=(800, 600), show=True) canvas.measure_fps() # Set up a viewbox to display the image with interactive pan/zoom view = canvas.central_widget.add_view() # from escheresque.group.octahedral import Pyritohedral # group = Pyritohedral() for i in range(12): mesh = escheresque.stl.load_stl(filename.format(i)) meshvis = scene.visuals.Mesh( mesh.vertices * 100, mesh.faces[:, ::-1], shading='flat', parent=view.scene) # Create three cameras (Fly, Turntable and Arcball) fov = 60. cam1 = scene.cameras.FlyCamera(parent=view.scene, fov=fov, name='Fly') view.camera = cam1 app.run()
def traces(args): from vispy.app import run from phy.plot.traces import TraceView from phy.io.h5 import open_h5 from phy.io.traces import read_kwd, read_dat path = args.file if path.endswith('.kwd'): f = open_h5(args.file) traces = read_kwd(f) elif path.endswith(('.dat', '.bin')): if not args.n_channels: raise ValueError("Please specify `--n-channels`.") if not args.dtype: raise ValueError("Please specify `--dtype`.") if not args.sample_rate: raise ValueError("Please specify `--sample-rate`.") n_channels = int(args.n_channels) dtype = np.dtype(args.dtype) traces = read_dat(path, dtype=dtype, n_channels=n_channels) start, end = map(int, args.interval.split(',')) sample_rate = float(args.sample_rate) start = int(sample_rate * start) end = int(sample_rate * end) c = TraceView(keys='interactive') c.visual.traces = .01 * traces[start:end, ...] c.show() run() return None, None
def visualise_path(path): canvas = scene.SceneCanvas(show=True, keys='interactive') grid = canvas.central_widget.add_grid() vb = grid.add_view(name='vb') vb.parent = canvas.scene vb.clip_method='viewport' vb.camera = scene.TurntableCamera(elevation=30, azimuth=30, up='+z') a = [] col = True for i in range(len(path)): if i == 0: a += [(0.0, 0.0, 1.0, 1.0)] elif col: a += [(1.0, 0.0, 0.0, 1.0)] else: a += [(0.0, 1.0, 0.0, 1.0)] col = not col line1 = scene.visuals.Line(pos = path.copy(), method = 'gl', antialias=True, name='line1', color=a, parent=vb.scene, connect='strip') ax = scene.visuals.XYZAxis(name='test', parent=vb) app.run()
def tetplot(points, simplices, vertex_color=None, edge_color=None, alpha=1.0, axis=True): """ main function for tetplot """ TetPlot = scene.visuals.create_visual_node(TetPlotVisual) # convert data types for OpenGL pts_float32 = points.astype(np.float32) sim_uint32 = simplices.astype(np.uint32) # The real-things : plot using scene # build canvas canvas = scene.SceneCanvas(keys='interactive', show=True) # Add a ViewBox to let the user zoom/rotate view = canvas.central_widget.add_view() view.camera = 'turntable' view.camera.fov = 50 view.camera.distance = 5 # toggle drawing mode TetPlot(pts_float32, sim_uint32, vertex_color, color=None, alpha=alpha, mode='triangles', parent=view.scene) if edge_color is not None: TetPlot(pts_float32, sim_uint32, vertex_color, color=edge_color, alpha=alpha, mode='lines', parent=view.scene) # show axis if axis: scene.visuals.XYZAxis(parent=view.scene) # run if sys.flags.interactive != 1: app.run()
def main(argv): argParser = argparse.ArgumentParser() argParser.add_argument('-s', '--start_frame', action='store', type=int, default=0, help='starting frame for viewing the sequence') argParser.add_argument("path", action="store", type=str, help="path to either .sima folder or imaging sequence") args = argParser.parse_args(argv) canvas = Canvas(args.path, start=args.start_frame) canvas.show() app.run()
def __init__(self, h): self.h = h app.Canvas.__init__(self, keys='interactive', size=(800, 550)) hcyl = mplcyl.TruncatedCone() print('1') #plot_tc(p0=np.array([1, 3, 2]), p1=np.array([8, 5, 9]), R=[5.0, 2.0]) verts, edges = h.get_geometry() self.meshes = [] self.rotation = MatrixTransform() sec_ids = [] s = 1.0 x, y = 0., 0. for edge in edges: ends = verts['pos'][edge] # xyz coordinate of one end [x,y,z] dia = verts['dia'][edge] # diameter at that end sec_id = verts['sec_index'][edge[0]] # save the section index dif = ends[1]-ends[0] # distance between the ends length = (dif**2).sum() ** 0.5 # print length # print dia #C, T, B = hcyl.make_truncated_cone(p0=ends[0], p1=ends[1], R=[dia[0]/2., dia[1]/2.]) mesh_verts = create_cylinder(8, 8, radius=[dia[0]/2., dia[1]/2.], length=length, offset=False) #mesh_verts = create_grid_mesh(C[0], C[1], C[2]) # sec_id_array = np.empty(mesh_verts.shape[0]*3, dtype=int) # # sec_id_array[:] = sec_id # meshes.append(mesh_verts) # sec_ids.append(sec_id_array) self.meshes.append(visuals.MeshVisual(meshdata=mesh_verts, color='r')) # transform = ChainTransform([STTransform(translate=(x, y), # scale=(s, s, s)), # self.rotation]) # # for i, mesh in enumerate(self.meshes): # # x = 800. * (i % grid[0]) / grid[0] + 40 # mesh.transform = transform # mesh.transforms.scene_transform = STTransform(scale=(1, 1, 0.01)) gloo.set_viewport(0, 0, *self.physical_size) gloo.clear(color='white', depth=True) for mesh in self.meshes: mesh.draw() print('running') self.show() if sys.flags.interactive != 1: app.run()
def drawShadows(inputFile='/Users/rachel/Downloads/cloud_frac_padded_623_812_70_4096_4096.png', outputFile='/Users/rachel/Downloads/newshadow.png', lightPosition=(20, 0, 0), dataShape=(623, 812, 70), textureShape=(4096, 4096), tileLayout=(6,5), steps=81, alphaScale=2): ''' Given a tiled data PNG file and a light position, computes the shadows on the data and writes them to a second PNG. @param inputFile: path to the input PNG @type inputFile: string @param outputFile: path to write out the results @type outputFile: string @param lightPosition: position of the point light @type lightPosition: 3-tuple @param dataShape: 3D shape of the data field @type dataShape: 3-tuple @param textureShape: shape of the input image @type textureShape: 2-tuple @param tileLayout: (cols, rows) arrangement of tiles in the input PNG @type tileLayout: 2-tuple @param steps: how many steps to take through the data in calculations @type steps: int @param alphaScale: factor to scale the light absorption @type alphaScale: number ''' width = textureShape[0] height = textureShape[1] c = app.Canvas(show=False, size=(width, height)) cloudTex = getCloudTexture(inputFile, width, height) vertexPath = os.path.join(homeDir, 'shadow_vertex.glsl') fragmentPath = os.path.join(homeDir, 'shadow_frag.glsl') vertex = getShader(vertexPath) fragment = getShader(fragmentPath) program = mkProgram(vertex, fragment, cloudTex, dataShape=dataShape, textureShape=textureShape, tileLayout=tileLayout) setLightPosition(program, lightPosition) setResolution(program, steps, alphaScale) @c.connect def on_draw(event): gloo.clear((1,1,1,1)) program.draw(gl.GL_TRIANGLE_STRIP) im = gloo.util._screenshot((0, 0, c.size[0], c.size[1])) imsave(outputFile, im) c.close() app.run()
def __init__(self, bubble_list, boundaries = np.asarray([[0, 10], [0, 10], [0, 10]])): self.auto = False self.time_step = 0.05 self.bubbles = bubble_list self.bound = boundaries for bble in self.bubbles: bble.set_bound(self.bound) canvas = vscene.SceneCanvas(show=True, title=sys.argv[0]) # canvas.measure_fps() view = canvas.central_widget.add_view() if self.bound is not None: bound_pt = np.array([[self.bound[0, 0], self.bound[1, 0], self.bound[2, 0]], [self.bound[0, 1], self.bound[1, 0], self.bound[2, 0]], [self.bound[0, 1], self.bound[1, 1], self.bound[2, 0]], [self.bound[0, 0], self.bound[1, 1], self.bound[2, 0]], [self.bound[0, 0], self.bound[1, 0], self.bound[2, 0]], [self.bound[0, 0], self.bound[1, 0], self.bound[2, 1]], [self.bound[0, 1], self.bound[1, 0], self.bound[2, 1]], [self.bound[0, 1], self.bound[1, 1], self.bound[2, 1]], [self.bound[0, 0], self.bound[1, 1], self.bound[2, 1]], [self.bound[0, 0], self.bound[1, 0], self.bound[2, 1]]], dtype=np.float32) bound_vi = vscene.visuals.Line(pos=bound_pt, color=(1.00, 1.00, 1.00, 0.25)) view.add(bound_vi) view.camera = 'turntable' for bble in self.bubbles: bble.init_visual(view) def update(ev): for bble in self.bubbles: bble.step(self.time_step) timer = vapp.Timer() timer.connect(update) @canvas.events.key_press.connect def on_key_press(event): if event.key == 'Right': for bble in self.bubbles: bble.step(self.time_step) if event.key == 'Space': if self.auto: timer.stop() self.auto = False else: timer.start(self.time_step) self.auto = True if event.key == 's': for bble in self.bubbles: bble.shake() vapp.run()
def tetplot(points, simplices): """ main function for tetplot """ colors = np.random.rand(points.shape[0], 4) colors[:, -1] = 1.0 colors = colors.astype(np.float32) # extract triangles and edges triangles = sim2tri(simplices) edges = sim2edge(simplices) # plot Canvas(points, colors, triangles, edges) app.run()
def tetplot(points, simplices, vertex_color=None, edge_color=None, alpha=1.0, axis=True): """ main function for tetplot """ TetPlot = scene.visuals.create_visual_node(TetPlotVisual) # convert data types for OpenGL pts_float32 = points.astype(np.float32) sim_uint32 = simplices.astype(np.uint32) # The real-things : plot using scene # build canvas canvas = scene.SceneCanvas(keys='interactive', show=True) # Add a ViewBox to let the user zoom/rotate view = canvas.central_widget.add_view() view.camera = 'turntable' view.camera.fov = 50 view.camera.distance = 3 if vertex_color is not None and vertex_color.ndim == 1: vertex_color = blue_red_colormap(vertex_color) # drawing only triangles # 1. turn off mask_color, default = [1.0, 1.0, 1.0, alpha] # 2. mode = 'triangles' TetPlot(pts_float32, sim_uint32, vertex_color, mask_color=None, alpha=alpha, mode='triangles', parent=view.scene) # drawing only lines # 1. turn off vertex_color, default = [[1.0, 1.0, 1.0, 1.0]*N] # 2. mode = 'lines' # 3. alpha channel is specified instead of mask_color if edge_color is not None: TetPlot(pts_float32, sim_uint32, vertex_color=None, mask_color=edge_color, alpha=alpha, mode='lines', parent=view.scene) # show axis if axis: scene.visuals.XYZAxis(parent=view.scene) # run app.run()
def plot(self): from vispy import app, scene, io # Prepare canvas canvas = scene.SceneCanvas(keys='interactive', size=(800, 600), show=True) canvas.measure_fps() # Set up a viewbox to display the image with interactive pan/zoom view = canvas.central_widget.add_view() for a in self.actors: a.init_visual(scene, view.scene) fov = 60. cam1 = scene.cameras.FlyCamera(parent=view.scene, fov=fov, name='Fly') view.camera = cam1 # def on_resize(self, event): # 176 # setup the new viewport # gloo.set_viewport(0, 0, *event.physical_size) # w, h = event.size # self.projection = perspective(45.0, w / float(h), 1.0, 1000.0) # self.program['u_projection'] = self.projection dt = 0.002 def update(event): # update the simulation for i in range(1): self.integrate(dt) # upload new state to gpu for i in range(len(self.actors)): actor = self.actors[i] if isinstance(actor, MeshActor): if not isinstance(actor, StaticActor): actor.visual.set_data(vertices=actor.position[actor.mesh.faces]) if isinstance(actor, ParticleActor): actor.visual.set_data(actor.position) timer = app.Timer(interval=dt, connect=update) timer.start() app.run()
def plot(mesh, show_k=False, show_v=False, show_f=False): points = mesh.points springs = mesh.springs canvas = scene.SceneCanvas(keys='interactive', show=True) view = canvas.central_widget.add_view() view.camera = 'panzoom' view.camera.aspect = 1 edges = springs[['p0', 'p1']].view(('i8', 2)) lines = scene.Line( pos=points, connect=edges, antialias=False, method='gl', color='green', parent=view.scene) markers = scene.Markers( pos=points, face_color='blue', symbol='o', parent=view.scene, size=0.5, scaling=True ) view.camera.set_range() app.run()
def run( mesh, show_k=False, show_v=False, show_f=False, run=None, verbose=False): points = mesh.points springs = mesh.springs canvas = scene.SceneCanvas(keys='interactive', show=True) view = canvas.central_widget.add_view() view.camera = 'panzoom' view.camera.aspect = 1 edges = springs[['p0', 'p1']].view(('i8', 2)) lines = scene.Line( pos=points, connect=edges, antialias=False, method='gl', color='green', parent=view.scene) markers = scene.Markers( pos=points, face_color='blue', symbol='o', parent=view.scene, size=0.5, scaling=True ) view.camera.set_range() def update(ev): t0 = time.time() run(mesh) t1 = time.time() if verbose: print("run: %s" % (t1 - t0, )) if mesh.points.min() == numpy.nan or mesh.points.max() == numpy.nan: return False t0 = time.time() markers.set_data(pos=mesh.points, size=0.5, scaling=True) lines.set_data(pos=mesh.points) t1 = time.time() if verbose: print("set_data: %s" % (t1 - t0, )) if run is not None: timer = app.Timer(interval=0, connect=update, start=True) app.run()
def procShadows(dataArray, dataShape=(623, 812, 70), lightPosition=(20, 0, 0), steps=81, alphaScale=2, ambience=0.3): ''' Given a tiled data PNG file and a light position, computes the shadows on the data and writes them to a second PNG. Args: * dataArray (array): data for which to calculate shadows * dataShape (3-tuple): 3D shape of the data field * lightPosition (3-tuple): position of the point light * steps (int): how many steps to take through the data in calculations * alphaScale (int): factor to scale the light absorption ''' dataTexture = makeTexture(dataArray) textureShape = dataArray.shape[:2] tileLayout = (int(textureShape[0]/dataShape[0]), int(textureShape[1]/dataShape[1])) vertex = getShader(os.path.join(homeDir, 'shadow_vertex.glsl')) fragment = getShader(os.path.join(homeDir, 'shadow_frag.glsl')) program = makeProgram(vertex, fragment, dataTexture, dataShape=dataShape, textureShape=textureShape, tileLayout=tileLayout) setLightPosition(program, lightPosition) setResolution(program, steps, alphaScale) setAmbientLight(program, ambience) c = Canvas(size=textureShape, program=program) app.run() render = c.shadowsArray[:, :, :3] return render
def main(): graph, osm = read_osm(sys.argv[1]) print(osm.bounds) if len(sys.argv) > 2: if sys.argv[2] == 'renderer': path, _ = shortest_path.dijkstra(graph, '1081079917', '65501510') points = get_points_from_node_ids(osm, path) minX = float(osm.bounds['minlon']) maxX = float(osm.bounds['maxlon']) minY = float(osm.bounds['minlat']) maxY = float(osm.bounds['maxlat']) road_vbos, other_vbos = get_vbo(osm) c = Canvas(road_vbos, other_vbos, [minX, minY, maxX, maxY], scale=100) # c.measure_fps() # c = Canvas([([[0.0, 0.0, 0.0],[0.5, 0.5, 0.0],[2.0,0.0,0.0],[0.0,0.0,0.0]], (0.0, 0.0, 0.0))], [-1.0, -1.0, 1.0, 1.0], scale=1) app.run() else: # path, _ = shortest_path.bidirectional_dijkstra(graph, '1081079917', '65501510') matplotmap = MatplotLibMap(osm, graph)
def run(): """进入当前GUI事件循环。""" app.run()
def main(args=None): p = ParserCreator() if args is None: args = sys.argv[1:] elif isinstance(args, string_types): args = args.split(' ') args = p.parse(args) if args is None: return if args.profiler or args.line_profiler: from phy.utils.testing import _enable_profiler, _profile prof = _enable_profiler(args.line_profiler) else: prof = None import phy if args.debug: phy.debug() # Hide the traceback. if args.hide_traceback: def exception_handler(exception_type, exception, traceback): print("{}: {}".format(exception_type.__name__, exception)) sys.excepthook = exception_handler # Activate IPython debugger. if args.pdb: from IPython.core import ultratb sys.excepthook = ultratb.FormattedTB(mode='Verbose', color_scheme='Linux', call_pdb=1, ) func = args.func if func is None: p.parser.print_help() return out = func(args) if not out: return cmd, ns = out if not cmd: return requires_qt = ns.pop('requires_qt', False) requires_vispy = ns.pop('requires_vispy', False) # Default variables in namespace. ns.update(phy=phy, path=args.file) if 'session' in ns: ns['model'] = ns['session'].model # Interactive mode with IPython. if args.ipython: print("\nStarting IPython...") from IPython import start_ipython args_ipy = ["-i", "-c='{}'".format(cmd)] if requires_qt or requires_vispy: # Activate Qt event loop integration with Qt. args_ipy += ["--gui=qt"] start_ipython(args_ipy, user_ns=ns) else: if not prof: exec_(cmd, {}, ns) else: _profile(prof, cmd, {}, ns) if requires_qt: # Launch the Qt app. from phy.gui import run_qt_app run_qt_app() elif requires_vispy: # Launch the VisPy Qt app. from vispy.app import use_app, run use_app('pyqt4') run()
def main(objects, object_id, var_name=None): m = objects.where(objects == object_id, drop=True) data_source, objects_mask = object_file.split(".objects.") path, base_name = data_source.split("__") if var_name: fn = os.path.join(path, "3d_blocks", "full_domain", "{}.{}.nc".format(base_name, var_name)) if not os.path.exists(fn): fn = os.path.join(path, "masks", "{}.{}.nc".format(base_name, var_name)) da = xr.open_dataarray(fn, decode_times=False) da = da.squeeze().sel(xt=m.xt, yt=m.yt, zt=m.zt) da -= da.mean() da /= da.max() print(da.max()) else: da = m # vispy expects data as (z, y, x) da = da.transpose("zt", "yt", "xt") nz, ny, nx = da.shape fn_out = "temp_3d_block.nc" del da.xt.attrs["standard_name"] del da.yt.attrs["standard_name"] da.to_netcdf(fn_out) print("Wrote {}".format(fn_out)) # m = np.swapaxes(m, 0, 2) # x_min, x_max = m.xt.min(), m.xt.max() # y_min, y_max = m.yt.min(), m.yt.max() # xc, yc = m.xt.mean(), m.yt.mean() # Prepare canvas canvas = scene.SceneCanvas(keys="interactive", size=(1200, 800), show=True) canvas.measure_fps() # Set up a viewbox to display the image with interactive pan/zoom view = canvas.central_widget.add_view() # Set whether we are emulating a 3D texture emulate_texture = False # Create the volume visuals, only one is visible # data = np.swapaxes(m.values, 0, 1) data = da.fillna(0.0).values # np.flipud(np.rollaxis(m.values, 1)) data = (data - data.min()) / (data.max() - data.min()) volume1 = scene.visuals.Volume( data, parent=view.scene, threshold=0.5, emulate_texture=emulate_texture, method="translucent", cmap=translucent_cmap, ) # volume1.transform = scene.STTransform(translate=(0, 0, nz)) volume1.transform = scene.STTransform(translate=(-nx / 2, -ny / 2, 0)) # Create three cameras (Fly, Turntable and Arcball) fov = 60.0 cam = scene.cameras.ArcballCamera(parent=view.scene, fov=fov, name="Arcball", up="z") cam.distance = nz * 5 view.camera = cam _ = scene.Axis( pos=[[-0.5 * nx, -0.5 * ny], [0.5 * nx, -0.5 * ny]], tick_direction=(0, -1), font_size=16, axis_color="r", tick_color="r", text_color="r", parent=view.scene, ) _ = scene.Axis( pos=[[-0.5 * nx, -0.5 * ny], [0.5 * nx, -0.5 * ny]], tick_direction=(0, -1), font_size=16, axis_color="r", tick_color="r", text_color="r", parent=view.scene, ) # xax.transform = scene.STTransform(translate=(0, 0, -0.2)) yax = scene.Axis( pos=[[-0.5 * nx, -0.5 * ny], [-0.5 * nx, 0.5 * ny]], tick_direction=(-1, 0), font_size=16, axis_color="b", tick_color="b", text_color="b", parent=view.scene, ) yax.transform = scene.STTransform(translate=(0, 0, -0.2)) # Implement key presses @canvas.events.key_press.connect def on_key_press(event): global opaque_cmap, translucent_cmap if event.text == "1": pass elif event.text == "2": methods = ["translucent", "additive"] method = methods[(methods.index(volume1.method) + 1) % len(methods)] print("Volume render method: %s" % method) cmap = opaque_cmap if method in ["mip", "iso" ] else translucent_cmap volume1.method = method volume1.cmap = cmap elif event.text == "4": if volume1.method in ["mip", "iso"]: cmap = opaque_cmap = next(opaque_cmaps) else: cmap = translucent_cmap = next(translucent_cmaps) volume1.cmap = cmap elif event.text == "0": cam.set_range() elif event.text != "" and event.text in "[]": s = -0.025 if event.text == "[" else 0.025 volume1.threshold += s th = volume1.threshold print("Isosurface threshold: %0.3f" % th) # for testing performance # @canvas.connect # def on_draw(ev): # canvas.update() app.run()
def display_sources(sources, img_data, mrkr_size, wcs, cmap='grays', susscolor="blue", tmlcolor="green", tm2color="orange", titlestring="SPIRE PSC"): """ display sources overlaid on image Parameters: ----------- sources : dataframe including ra and dec values img_data : numpy array of the image mrkr_size : diameter of the markers in pixel units wcs : astropy.wcs wcs object for the image (to convert ra,dec to pixels) cmap : vispy color map, defaults to 'grays'. See vispy.colors.get_colormaps() Returns: -------- None """ nsrc = len(sources) pos = np.empty( shape=(0, 0) ) if (nsrc > 0): if (is_pacs == True): sworld = np.vstack([sources['susra'].values.astype(np.float64), sources['susdec'].values.astype(np.float64)]).T else: sworld = np.vstack([sources['ra'].values,sources['dec'].values]).T pos = wcs.wcs_world2pix(sworld,0) + 0.5 else: print("No sources found") sys.exit(-1); keydict = dict(escape='close', p=lambda x: max(0,i-1), n=lambda x: min(nsrc,i+1)) #canvas = scene.SceneCanvas(keys=keydict) canvas = scene.SceneCanvas(keys='interactive') canvas.size = img_data.shape canvas.title = titlestring canvas.show() # Set viewbox to display the image with interactive pan/zoom view = canvas.central_widget.add_view() # Create the image #image = scene.visuals.Image(bytescale(img_data, cmin=0.8*np.nanmin(img_data), # cmax=1.05*np.nanmax(img_data)), parent=view.scene) # note that vispy.color.get_colormaps() returns all the ColorMaps image = scene.visuals.Image(bytescale(img_data, cmin=0.9*np.nanmin(img_data), cmax=1.02*np.nanmax(img_data)), #clim=(0.8*np.nanmin(img_data), 1.05*np.nanmax(img_data)), cmap=cmap, parent=view.scene) # Set 2D camera (the camera will scale to the contents in the scene) view.camera = SourceInspectCamera(image,img_data,sources,pos,index=0,aspect=1) view.camera.set_range() # Add the markers if ((nsrc > 0) and (susscolor != None)): p1 = scene.visuals.Markers(parent=view.scene) p1.set_data(pos, face_color=None, edge_color=susscolor, scaling=True, edge_width=2.0, size=mrkr_size) if ((nsrc > 0) and (tmlcolor != None)): tmlworld = np.vstack([sources['ratml'].values,sources['dectml'].values]).T postml = wcs.wcs_world2pix(tmlworld,0) + 0.5 p2 = scene.visuals.Markers(parent=view.scene) p2.set_data(postml, face_color=None, edge_color=tmlcolor, scaling=True, edge_width=1.5, size=mrkr_size) if ((nsrc > 0) and (tm2color != None)): tm2world = np.vstack([sources['ratm2'].values,sources['dectm2'].values]).T postm2 = wcs.wcs_world2pix(tm2world,0) + 0.5 p3 = scene.visuals.Markers(parent=view.scene) p3.set_data(postm2, face_color=None, edge_color=tm2color, scaling=True, edge_width=1.5, size=mrkr_size) app.run() return
def run(sketch_setup=None, sketch_draw=None, frame_rate=60, mode="P2D"): """Run a sketch. if no `sketch_setup` and `sketch_draw` are specified, p5 automatically "finds" the user-defined setup and draw functions. :param sketch_setup: The setup function of the sketch (None by default.) :type sketch_setup: function :param sketch_draw: The draw function of the sketch (None by default.) :type sketch_draw: function :param frame_rate: The target frame rate for the sketch. :type frame_rate: int :math:`\geq 1` """ # get the user-defined setup(), draw(), and handler functions. if sketch_setup is not None: setup_method = sketch_setup elif hasattr(__main__, 'setup'): setup_method = __main__.setup else: setup_method = setup if sketch_draw is not None: draw_method = sketch_draw elif hasattr(__main__, 'draw'): draw_method = __main__.draw else: draw_method = draw handlers = dict() for handler in handler_names: if hasattr(__main__, handler): hfunc = getattr(__main__, handler) handlers[handler] = _fix_interface(hfunc) if mode == "P2D": p5.renderer = Renderer2D() p5.mode = 'P2D' elif mode == "P3D": p5.mode = 'P3D' p5.renderer = Renderer3D() else: raise ValueError("Invalid Mode %s" % mode) p5.sketch = Sketch(setup_method, draw_method, handlers, frame_rate) physical_width, physical_height = p5.sketch.physical_size width, height = p5.sketch.size builtins.pixel_x_density = physical_width // width builtins.pixel_y_density = physical_height // height p5.sketch.timer.start() app.run() exit()
def main(quantity, radius, speed, max_x, max_y, min_x=0, min_y=0): def update_atoms(): def collisions(): def collision(f_i, s_i): f_atom = atom_list[f_i] s_atom = atom_list[s_i] dist = ((f_atom.x - s_atom.x)**2 + (f_atom.y - s_atom.y)**2)**0.5 if dist < radius * 2 and f_i != s_i: co = abs((s_atom.x - f_atom.x) / dist) si = abs((s_atom.y - f_atom.y) / dist) f_atom.s = (f_atom.xs**2 + f_atom.ys**2)**0.5 s_atom.s = (s_atom.xs**2 + s_atom.ys**2)**0.5 if f_atom.x > s_atom.x: f_atom.x += (radius - dist / 2) * si s_atom.x -= (radius - dist / 2) * si f_atom.xs = si * s_atom.s s_atom.xs = -si * f_atom.s else: f_atom.x -= (radius - dist / 2) * si s_atom.x += (radius - dist / 2) * si f_atom.xs = -si * s_atom.s s_atom.xs = si * f_atom.s if f_atom.y > s_atom.y: f_atom.y += (radius - dist / 2) * co s_atom.y -= (radius - dist / 2) * co f_atom.ys = co * s_atom.s s_atom.ys = -co * f_atom.s else: f_atom.y -= (radius - dist / 2) * co s_atom.y += (radius - dist / 2) * co f_atom.ys = -co * s_atom.s s_atom.ys = co * f_atom.s grid = [] non_empty_cells = [] for x in range(int(width / diam) + 2): grid.append([]) for y in range(int(height / diam) + 2): grid[-1].append([]) for i in range(len(atom_list)): grid[int(atom_list[i].x / diam)][int(atom_list[i].y / diam)].append(i) non_empty_cells.append( (int(atom_list[i].x / diam), int(atom_list[i].y / diam))) for x, y in non_empty_cells: others = grid[x][y] + grid[x][y + 1] + grid[x][y - 1] + grid[ x + 1][y] + grid[x + 1][y - 1] + grid[x + 1][y + 1] + grid[ x - 1][y] + grid[x - 1][y - 1] + grid[x - 1][y + 1] for atom_i in grid[x][y]: for other_atom_i in others: collision(atom_i, other_atom_i) def apply_speed(): for atom in atom_list: if atom.x - radius < min_x: atom.x = min_x + radius atom.xs *= -1 elif atom.x + radius > max_x: atom.x = max_x - radius atom.xs *= -1 if atom.y - radius < min_y: atom.y = min_y + radius atom.ys *= -1 elif atom.y + radius > max_y: atom.y = max_y - radius atom.ys *= -1 atom.x += atom.xs atom.y += atom.ys collisions() apply_speed() diam = radius * 2 width = max_x - min_x height = max_y - min_y atom_list = [] for i in range(quantity): angle = uniform(0, 2 * pi) coeff = 1 #uniform(0.5,2) atom_list.append( atom(uniform(min_x + radius, max_x - radius), uniform(min_y + radius, max_y - radius), sin(angle) * speed * coeff, cos(angle) * speed * coeff)) vertex = """ attribute vec2 positions; uniform float radius; void main (void) { gl_Position = vec4(positions, 0.0, 1.0); gl_PointSize = 2.0*(radius); } """ fragment = """ in vec2 gl_PointCoord; void main() { float distance = length(vec2(0.5, 0.5) - gl_PointCoord); if (distance <= 0.5) gl_FragColor = vec4(0, 0, 0, 1); else discard; } """ c = app.Canvas(keys='interactive', size=(width, height), vsync=1) program = gloo.Program(vertex, fragment) program['radius'] = radius @c.connect def on_resize(event): gloo.set_viewport(0, 0, *event.size) #@c.connect #def on_draw(event): #update_atoms() #program['positions'] = [[(atom.x - width / 2) / width * 2, (atom.y - height / 2) / height * 2] for atom in atom_list] #gloo.clear((1,1,1,1)) #program.draw('points') #c.update() def frame(): update_atoms() program['positions'] = [[(atom.x - width / 2) / width * 2, (atom.y - height / 2) / height * 2] for atom in atom_list] gloo.clear((1, 1, 1, 1)) program.draw('points') c.update() timer = app.Timer(interval=1) timer.connect(frame) timer.start() c.show() app.run()
def run(): """Enter the native GUI event loop.""" app.run()
def main(quantity, radius, speed, max_x, max_y, min_x=0, min_y=0, loops = None): def collision(f_i, s_i): f_atom = atom_list[f_i]; s_atom = atom_list[s_i] dist = hypot((f_atom.x - s_atom.x), (f_atom.y - s_atom.y)) if dist < radius * 2 and f_i != s_i: co = abs((s_atom.x - f_atom.x) / dist) si = abs((s_atom.y - f_atom.y) / dist) sphere_dist = radius - dist / 2 f_atom.s = (f_atom.xs**2 + f_atom.ys**2)**0.5 s_atom.s = (s_atom.xs**2 + s_atom.ys**2)**0.5 if f_atom.x > s_atom.x: f_atom.xb += sphere_dist * si s_atom.xb -= sphere_dist * si f_atom.xs = si * s_atom.s s_atom.xs = -si * f_atom.s else: f_atom.xb -= sphere_dist * si s_atom.xb += sphere_dist * si f_atom.xs = -si * s_atom.s s_atom.xs = si * f_atom.s if f_atom.y > s_atom.y: f_atom.yb += sphere_dist * co s_atom.yb -= sphere_dist * co f_atom.ys = co * s_atom.s s_atom.ys = -co * f_atom.s else: f_atom.yb -= sphere_dist * co s_atom.yb += sphere_dist * co f_atom.ys = -co * s_atom.s s_atom.ys = co * f_atom.s def update_atoms(): # Find collisions fcol_t = time.perf_counter() for (x, y) in non_empty_cells: other_atoms_i = grid[x][y] + grid[x][y-1] + grid[x+1][y-1] + grid[x+1][y] + grid[x+1][y+1] #~ other_atoms_i = (x for cell in (grid[x][y], grid[x][y-1], grid[x+1][y-1], grid[x+1][y], grid[x+1][y+1]) for x in cell) for atom_i in grid[x][y]: for other_atom_i in other_atoms_i: collision(atom_i, other_atom_i) fcol_t = time.perf_counter() - fcol_t # Apply speed aplspd_t = time.perf_counter() for atom in atom_list: if atom.x - radius < min_x: atom.x = min_x + radius atom.xs *= -1 elif atom.x + radius > max_x: atom.x = max_x - radius atom.xs *= -1 if atom.y - radius < min_y: atom.y = min_y + radius atom.ys *= -1 elif atom.y + radius > max_y: atom.y = max_y - radius atom.ys *= -1 atom.x += atom.xs + atom.xb atom.y += atom.ys + atom.yb atom.xb = 0; atom.yb = 0 aplspd_t = time.perf_counter() - aplspd_t # Update grid updgrd_t = time.perf_counter() for (x, y) in non_empty_cells.copy(): for atom_i in grid[x][y].copy(): nx, ny = int(atom_list[atom_i].x / diam), int(atom_list[atom_i].y / diam) if (nx, ny) != (x, y): grid[x][y].remove(atom_i) grid[nx][ny].append(atom_i) if (nx, ny) not in non_empty_cells: non_empty_cells.append((nx, ny)) if len(grid[x][y]) == 0: non_empty_cells.remove((x, y)) updgrd_t = time.perf_counter() - updgrd_t # Return time spent return fcol_t, aplspd_t, updgrd_t diam = radius * 2 width = max_x - min_x height = max_y - min_y atom_list = [] for i in range(quantity): angle = uniform(0, 2*pi) coeff = 1 #uniform(0.5,2) atom_list.append(atom( uniform(min_x + radius, max_x - radius), uniform(min_y + radius, max_y - radius), sin(angle) * speed * coeff, cos(angle) * speed * coeff)) grid = [] for x in range(int(width / diam) + 2): grid.append([]) for y in range(int(height / diam) + 2): grid[-1].append([]) non_empty_cells = [] for i in range(len(atom_list)): x, y = int(atom_list[i].x / diam), int(atom_list[i].y / diam) grid[x][y].append(i) if (x, y) not in non_empty_cells: non_empty_cells.append((x, y)) vertex = """ attribute vec3 positions; attribute vec2 a_texcoord; uniform float radius; varying vec2 v_texcoord; void main(void) { gl_Position = vec4(0.0, 0.0, 0.0, 1.0); gl_PointSize = 2.0*(radius); v_texcoord = a_texcoord; } """ fragment = """ uniform sampler2D texture; varying vec2 v_texcoord; void main(void) { float distance = length(vec2(0.5, 0.5) - gl_PointCoord); if (distance <= 0.5) //gl_FragColor = vec4(1, 1, 1, 1); gl_FragColor = texture2D(texture, v_texcoord); else discard; } """ #~ im = np.full((1,1), 0.5, 'float32') im = io.load_crate() positions_1 = np.array([ [-1, -1, 0.0], [+1, -1, 0.0], [-1, +1, 0.0], [+1, +1, 0.0,] ], np.float32) texcoords_1 = np.array([ [1.0, 1.0], [0.0, 1.0], [1.0, 0.0], [0.0, 0.0]], np.float32) texcoords = np.array([[1.0, 1.0], [0.0, 1.0],[1.0, 0.0], [0.0, 0.0]], np.float32) program = Program(vertex, fragment) program['texture'] = Texture2D(im) program['radius'] = radius program['a_texcoord'] = texcoords program['positions_1'] = positions_1 program['texcoords_1']= texcoords_1 c = app.Canvas(keys='interactive', size=(width, height)) @c.connect def on_draw(event): #~ nonlocal loops runtime = update_atoms() #~ if loops != None: #~ update_times.append(runtime) #~ loops -= 1 #~ if loops == 0: #~ fcol_t, aplspd_t, updgrd_t = [sum(times) / len(times) for times in zip(*update_times)] #~ print(fcol_t, aplspd_t, updgrd_t) positions = [[(atom.x - width / 2) / width * 2, (atom.y - height / 2) / height * 2, 0] for atom in atom_list] program['positions'] = positions gloo.clear() program.draw('points') c.update() @c.connect def on_resize(event): gloo.set_viewport(0, 0, *event.size) c.show() app.run()
def start(self): app.run()
def start(self): gui.canvas.activate_zoom() gui.canvas.show() app.run() gui.field.load(wall_index=0)
def main(): """ Starts the application. Return ------ bool Definition success. """ arguments = command_line_arguments() if arguments.version: print('{0} - {1}'.format(__application_name__, __version__)) return True settings = json.load(open(SETTINGS_FILE)) if arguments.settings_file is not None: assert os.path.exists( arguments.settings_file), ('"{0}" file doesn\'t exists!'.format( arguments.settings_file)) settings.update(json.load(open(arguments.settings_file))) input_linearity = arguments.input_linearity.lower() if input_linearity == 'linear': input_linear = True elif input_linearity == 'oecf': input_linear = False else: input_extension = os.path.splitext(arguments.input_image)[1].lower() if input_extension in LINEAR_IMAGE_FORMATS: input_linear = True else: input_linear = False if arguments.input_image is not None: assert os.path.exists(arguments.input_image), ( '"{0}" input image doesn\'t exists!'.format(arguments.input_image)) image_path = arguments.input_image else: image_path = DEFAULT_IMAGE_PATH try: image = read_image(str(image_path)) if not input_linear: colourspace = RGB_COLOURSPACES[arguments.input_oecf] image = colourspace.cctf_decoding(image) # Keeping RGB channels only. image = image[..., 0:3] image = image[::int(arguments.input_resample), ::int(arguments. input_resample)] except ImportError: warning( '"OpenImageIO" is not available, image reading is not supported, ' 'falling back to some random noise!') image = None if not arguments.enable_warnings: warnings.filterwarnings("ignore") ColourAnalysis(image, arguments.input_image, arguments.input_colourspace, arguments.input_oecf, input_linear, arguments.reference_colourspace, arguments.correlate_colourspace, settings, arguments.layout) return run()
self._timer = app.Timer('auto', connect=self.on_timer, start=True) self.activate_zoom() self.show() def activate_zoom(self): """установка размера окна""" self.width, self.height = self.size print(self.width, self.height) gloo.set_viewport(0, 0, *self.physical_size) def on_draw(self, event): """перерисовка окна""" gloo.clear() self.program["a_height"] = self.surface.height( self.t) # пересчет высот для текущего времени self.program.draw('points') def on_timer(self, event): """приращение времени с обновлением изображения""" self.t += 0.01 self.update() def on_resize(self, event): """данные о новом размере окна в OpenGL""" self.activate_zoom() if __name__ == '__main__': c = Canvas() # обьект приложения app.run() # обработчик событий.
def preview_volume(vols, shifts=None): canvas = scene.SceneCanvas(keys="interactive") canvas.size = 1024, 1024 canvas.show() # create view box view = canvas.central_widget.add_view() # genereate colormap """ n_colors = 256 alphas = np.linspace(0.0, 1.0, n_colors) color = np.c_[ alphas, alphas, alphas, alphas ] cmap = Colormap(color) """ from utoolbox.data.io.amira import AmiraColormap color = AmiraColormap("volrenGlow.am") color = np.array(color) color[0, :] = 0 color[:, 3] /= 100 cmap = Colormap(color) for i, vol in enumerate(vols): volume = scene.visuals.Volume(vol, cmap=cmap, parent=view.scene, emulate_texture=False) volume.method = "translucent" volume.transform = scene.STTransform(scale=(2, 2, 5.5)) volume.set_gl_state("translucent", depth_test=False) if shifts: volume.transform = scene.STTransform(translate=shifts[i]) # assign camera camera = scene.cameras.TurntableCamera(parent=view.scene, fov=60.0, name="Arcball", elevation=30.0) view.camera = camera view.camera.flip = (False, True, True) view.camera.reset() # axis axis = scene.visuals.XYZAxis(parent=view) s = STTransform(translate=(50, 50), scale=(50, 50, 50, 1)) affine = s.as_matrix() axis.transform = affine # link with camera @canvas.events.mouse_move.connect def on_mouse_move(event): if event.button == 1 and event.is_dragging: axis.transform.reset() axis.transform.rotate(camera.roll, (0, 0, 1)) axis.transform.rotate(camera.elevation, (1, 0, 0)) axis.transform.rotate(camera.azimuth, (0, 1, 0)) axis.transform.scale((50, 50, 0.001)) axis.transform.translate((50.0, 50.0)) axis.update() # render rotation movie """ n_steps = 240 axis = [0, 0, 0] logger.debug(".. rendering") step_angle = 360.0 / n_steps writer = imageio.get_writer("t1-head_split_rotate.mp4", fps=24) for i in range(n_steps): im = canvas.render() writer.append_data(im) view.camera.transform.rotate(step_angle, axis) writer.close() """ app.run()
def plot_test(self): c = Canvas(self.paths) app.run()
canvas = scene.SceneCanvas(keys='interactive') canvas.size = 800, 600 canvas.show() # Set up a viewbox to display the image with interactive pan/zoom view = canvas.central_widget.add_view() # Create the image img_data = np.empty((100, 100, 3), dtype=np.ubyte) noise = np.random.normal(size=(100, 100), loc=50, scale=150) noise = gaussian_filter(noise, (4, 4, 0)) img_data[:] = noise[..., np.newaxis] image = scene.visuals.Image(img_data, parent=view.scene) # Create isocurve, make a child of the image to ensure the two are always # aligned. curve1 = scene.visuals.Isocurve(noise, level=60, color=(0, 0, 1, 1), parent=view.scene) curve2 = scene.visuals.Isocurve(noise, level=50, color=(0, 0, 0.5, 1), parent=view.scene) curve3 = scene.visuals.Isocurve(noise, level=40, color=(0, 0, 0.3, 1), parent=view.scene) # Set the view bounds to show the entire image with some padding view.camera.rect = (-10, -10, image.size[0]+20, image.size[1]+20) import sys if __name__ == '__main__' and sys.flags.interactive == 0: app.run()
def show(self): # Load the first frame self.canvas.set_frame_data(self.load_data_by_step_id(0)) self.canvas.show() app.run()
import sys from vispy import scene from vispy import app import numpy as np canvas = scene.SceneCanvas(keys='interactive') canvas.size = 800, 600 canvas.show() # Set up a viewbox to display the image with interactive pan/zoom view = canvas.central_widget.add_view() # Create the image img_data = np.random.random((800, 800, 3)) image = scene.visuals.Image(img_data, parent=view.scene) view.camera.set_range() # unsuccessfully tacked on the end to see if I can modify the figure. # Does nothing. img_data_new = np.zeros((800, 800, 3)) #image = scene.visuals.Image(img_data_new, parent=view.scene) image.set_data(img_data_new) view.camera.set_range() app.run() # run vispy event loop, does not return
def run(sketch_setup=None, sketch_draw=None, frame_rate=60, mode="P2D", renderer="vispy"): """Run a sketch. if no `sketch_setup` and `sketch_draw` are specified, p5 automatically "finds" the user-defined setup and draw functions. :param sketch_setup: The setup function of the sketch (None by default.) :type sketch_setup: function :param sketch_draw: The draw function of the sketch (None by default.) :type sketch_draw: function :param frame_rate: The target frame rate for the sketch. :type frame_rate: int :math:`\geq 1` """ # get the user-defined setup(), draw(), and handler functions. if sketch_setup is not None: setup_method = sketch_setup elif hasattr(__main__, 'setup'): setup_method = __main__.setup else: setup_method = setup if sketch_draw is not None: draw_method = sketch_draw elif hasattr(__main__, 'draw'): draw_method = __main__.draw else: draw_method = draw handlers = dict() for handler in handler_names: if hasattr(__main__, handler): hfunc = getattr(__main__, handler) handlers[handler] = _fix_interface(hfunc) if renderer == "vispy": import vispy vispy.use('glfw') from p5.sketch.Vispy2DRenderer.base import VispySketch from vispy import app builtins.current_renderer = "vispy" if mode == "P2D": p5.mode = 'P2D' from p5.sketch.Vispy2DRenderer.renderer2d import VispyRenderer2D p5.renderer = VispyRenderer2D() elif mode == "P3D": p5.mode = 'P3D' from p5.sketch.Vispy3DRenderer.renderer3d import Renderer3D p5.renderer = Renderer3D() else: ValueError("Invalid Mode %s" % mode) p5.sketch = VispySketch(setup_method, draw_method, handlers, frame_rate) physical_width, physical_height = p5.sketch.physical_size width, height = p5.sketch.size builtins.pixel_x_density = physical_width // width builtins.pixel_y_density = physical_height // height builtins.start_time = time.perf_counter() p5.sketch.timer.start() app.run() exit() else: raise NotImplementedError("Invalid Renderer %s" % renderer)
def main(): canvas = Canvas(show=True) canvas.title = 'Maps' app.run()
def run(): app.run()
def main(quantity, radius, speed, max_x, max_y, min_x=0, min_y=0): def update_atoms(): # Finding collisions for (x, y) in non_empty_cells.copy(): other_atoms_i = grid[x][y] | grid[x][y-1] | grid[x+1][y-1] | grid[x+1][y] | grid[x+1][y+1] for atom_i in grid[x][y].copy(): for other_atom_i in other_atoms_i: if atom_i != other_atom_i: collision(atom_list[atom_i], atom_list[other_atom_i], radius) nx, ny = int(atom_list[atom_i].x / diam), int(atom_list[atom_i].y / diam) if (nx, ny) != (x, y): grid[x][y].discard(atom_i) grid[nx][ny].add(atom_i) if (nx, ny) not in non_empty_cells: non_empty_cells.append((nx, ny)) if not grid[x][y]: non_empty_cells.remove((x, y)) # Applying speed for atom in atom_list: if atom.x - radius < min_x: atom.x = min_x + radius atom.xs *= -1 elif atom.x + radius > max_x: atom.x = max_x - radius atom.xs *= -1 if atom.y - radius < min_y: atom.y = min_y + radius atom.ys *= -1 elif atom.y + radius > max_y: atom.y = max_y - radius atom.ys *= -1 atom.x += atom.xs atom.y += atom.ys diam = radius * 2 width = max_x - min_x height = max_y - min_y atom_list = [] for i in range(quantity): angle = uniform(0, 2*pi) coeff = uniform(0.5,2) atom_list.append(atom( uniform(min_x + radius, max_x - radius), uniform(min_y + radius, max_y - radius), sin(angle) * speed * coeff, cos(angle) * speed * coeff)) grid = [] for x in range(int(width / diam) + 2): grid.append([]) for y in range(int(height / diam) + 2): grid[-1].append(set()) non_empty_cells = [] for i in range(len(atom_list)): grid[int(atom_list[i].x / diam)][int(atom_list[i].y / diam)].add(i) non_empty_cells.append((int(atom_list[i].x / diam), int(atom_list[i].y / diam))) vertex = """ attribute vec2 positions; uniform float radius; void main () { gl_Position = vec4(positions, 0.0, 1.0); gl_PointSize = 2.0*(radius); } """ fragment = """ in vec2 gl_PointCoord; void main() { float distance = length(vec2(0.5, 0.5) - gl_PointCoord); if (distance <= 0.5) gl_FragColor = vec4(1, 1, 1, 1); else discard; } """ program = gloo.Program(vertex, fragment) program['radius'] = radius c = app.Canvas(keys='interactive', size=(width, height)) @c.connect def on_draw(event): update_atoms() program['positions'] = [[(atom.x - width / 2) / width * 2, (atom.y - height / 2) / height * 2] for atom in atom_list] gloo.clear() program.draw('points') c.update() @c.connect def on_resize(event): gloo.set_viewport(0, 0, *event.size) c.show() app.run()
def plot_ellipsoid(self, hkle, dpi=100): r'''Plots the resolution ellipsoid in the $Q_x$, $Q_y$, $W$ zone Parameters ---------- hkle : tup A tuple of intergers or arrays of H, K, L, and W (energy transfer) values at which resolution ellipsoid are desired to be plotted ''' from vispy import app, scene, visuals import sys [H, K, L, W] = hkle try: if np.all(H == self.H) and np.all(K == self.K) and np.all(L == self.L) and np.all(W == self.W): NP = np.array(self.RMS) R0 = self.R0 else: self.calc_resolution(hkle) NP = np.array(self.RMS) R0 = self.R0 except AttributeError: self.calc_resolution(hkle) NP = np.array(self.RMS) R0 = self.R0 if NP.shape == (4, 4): NP = NP[np.newaxis].reshape((4, 4, 1)) R0 = [R0] # Create a canvas with a 3D viewport canvas = scene.SceneCanvas(keys='interactive', bgcolor='white') view = canvas.central_widget.add_view() surface = [] for ind in range(NP.shape[-1]): # for this plot to work, we need to remove row-column 3 of RMS A = np.copy(NP) RMS = np.delete(np.delete(A, 2, axis=0), 2, axis=1)[:, :, ind] # [xvec, yvec, zvec, sample, rsample] = self._StandardSystem() qx = [0] # _scalar([xvec[0], xvec[1], xvec[2]], [self.H[ind], self.K[ind], self.L[ind]], rsample) qy = [0] # _scalar([yvec[0], yvec[1], yvec[2]], [self.H[ind], self.K[ind], self.L[ind]], rsample) qw = [0] # [self.W[ind]] # Q vectors on figure axes # o1 = np.copy(self.orient1) # o2 = np.copy(self.orient2) # pr = _scalar([o2[0], o2[1], o2[2]], [yvec[0], yvec[1], yvec[2]], rsample) # o2[0] = yvec[0] * pr # o2[1] = yvec[1] * pr # o2[2] = yvec[2] * pr # # if np.abs(o2[0]) < 1e-5: # o2[0] = 0 # if np.abs(o2[1]) < 1e-5: # o2[1] = 0 # if np.abs(o2[2]) < 1e-5: # o2[2] = 0 # # if np.abs(o1[0]) < 1e-5: # o1[0] = 0 # if np.abs(o1[1]) < 1e-5: # o1[1] = 0 # if np.abs(o1[2]) < 1e-5: # o1[2] = 0 # frame = '[Q1,Q2,E]' # SMAGridPoints = 40 EllipsoidGridPoints = 100 def fn(r0, rms, q1, q2, q3, qx0, qy0, qw0): ee = rms[0, 0] * (q1 - qx0[0]) ** 2 + rms[1, 1] * (q2 - qy0[0]) ** 2 + rms[2, 2] * (q3 - qw0[ 0]) ** 2 + 2 * rms[0, 1] * (q1 - qx0[0]) * (q2 - qy0[0]) + 2 * rms[0, 2] * (q1 - qx0[0]) * ( q3 - qw0[0]) + 2 * rms[2, 1] * (q3 - qw0[0]) * (q2 - qy0[0]) return ee # plot ellipsoids wx = fproject(RMS.reshape((3, 3, 1)), 0) wy = fproject(RMS.reshape((3, 3, 1)), 1) ww = fproject(RMS.reshape((3, 3, 1)), 2) surface = [] x = np.linspace(-wx[0] * 1.5, wx[0] * 1.5, EllipsoidGridPoints) + qx[0] y = np.linspace(-wy[0] * 1.5, wy[0] * 1.5, EllipsoidGridPoints) + qy[0] z = np.linspace(-ww[0] * 1.5, ww[0] * 1.5, EllipsoidGridPoints) + qw[0] [xg, yg, zg] = np.meshgrid(x, y, z) data = fn(R0[ind], RMS, xg, yg, zg, qx, qy, qw) # Create isosurface visual surface.append(scene.visuals.Isosurface(data, level=2. * np.log(2.), color=(0.5, 0.6, 1, 1), shading='smooth', parent=view.scene)) # @UndefinedVariable for surf in surface: [nx, ny, nz] = data.shape center = scene.transforms.STTransform(translate=(-nx / 2., -ny / 2., -nz / 2.)) surf.transform = center frame = scene.visuals.Cube(size=(EllipsoidGridPoints * 5, EllipsoidGridPoints * 5, EllipsoidGridPoints * 5), color='white', edge_color=(0., 0., 0., 1.), parent=view.scene) # @UndefinedVariable grid = scene.visuals.GridLines(parent=view.scene) # @UndefinedVariable grid.set_gl_state('translucent') # Add a 3D axis to keep us oriented axis = scene.visuals.XYZAxis(parent=view.scene) # @UndefinedVariable # Use a 3D camera # Manual bounds; Mesh visual does not provide bounds yet # Note how you can set bounds before assigning the camera to the viewbox cam = scene.TurntableCamera() cam.azimuth = 135 cam.elevation = 30 cam.fov = 60 cam.distance = 1.2 * EllipsoidGridPoints cam.center = (0, 0, 0) view.camera = cam canvas.show() if sys.flags.interactive == 0: app.run()
gl_Position = vec4(a_position, 0.0, 1.0); } """ fragment = """ void main() { gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0); } """ program = gloo.Program(vertex, fragment) program['a_position'] = np.c_[ np.linspace(-1.0, +1.0, 1000).astype(np.float32), np.random.uniform(-0.5, +0.5, 1000).astype(np.float32)] @c.connect def on_resize(event): gloo.set_viewport(0, 0, *event.size) @c.connect def on_draw(event): gloo.clear((1,1,1,1)) program.draw('line_strip') c.show() app.run();
def main(): """ Starts the application. Return ------ bool Definition success. """ arguments = command_line_arguments() if arguments.version: print("{0} - {1}".format(__application_name__, __version__)) return True settings = json.load(open(SETTINGS_FILE)) if arguments.settings_file is not None: assert os.path.exists(arguments.settings_file), '"{0}" file doesn\'t exists!'.format(arguments.settings_file) settings.update(json.load(open(arguments.settings_file))) input_linearity = arguments.input_linearity.lower() if input_linearity == "linear": input_linear = True elif input_linearity == "oecf": input_linear = False else: input_extension = os.path.splitext(arguments.input_image)[1].lower() if input_extension in LINEAR_IMAGE_FORMATS: input_linear = True else: input_linear = False if arguments.input_image is not None: assert os.path.exists(arguments.input_image), '"{0}" input image doesn\'t exists!'.format(arguments.input_image) image_path = arguments.input_image else: image_path = DEFAULT_IMAGE_PATH if is_openimageio_installed: image = read_image(str(image_path)) if not input_linear: colourspace = RGB_COLOURSPACES[arguments.input_oecf] image = colourspace.inverse_transfer_function(image) # Keeping RGB channels only. image = image[..., 0:3] image = image[:: int(arguments.input_resample), :: int(arguments.input_resample)] else: warning('"OpenImageIO" is not available, image reading is not supported, ' "falling back to some random noise!") image = None if not arguments.enable_warnings: warnings.filterwarnings("ignore") ColourAnalysis( image, arguments.input_image, arguments.input_colourspace, arguments.input_oecf, input_linear, arguments.reference_colourspace, arguments.correlate_colourspace, settings, arguments.layout, ) return run()
def main(): c = Canvas(sys.argv[1]) c.show() app.run()
@c.connect def on_resize(event): (width, height) = event.size if width > height: x = (width - height) / 2 y = 0 w = h = height else: x = 0 y = (height - width) / 2 w = h = width gloo.set_viewport(x, y, w, h) # gloo.set_viewport(0, 0, *event.size) @c.connect def on_draw(event): gloo.clear((1, 1, 1, 1)) program.draw(gl.GL_TRIANGLES) clock = 0 # t = app.Timer(connect=tick, start=True, interval=(1/60), iterations=-1) c.show() app.run();
def run(self): count = 0 if 'camera' in self.model['input'] : #or 'opencv' in self.model['input'] : start = time.time() if self.camera.rpi : #'picamera' in self.model['input'] : stream = io.BytesIO() for foo in self.camera.cap.capture_continuous(stream, 'bgr', use_video_port=True): self.code(stream, connection) # If we've been capturing for more than 30 seconds, quit if message == b'RIP': finish = time.time() break # Reset the stream for the next capture stream.seek(0) stream.truncate() count += 1 # Write a length of zero to the stream to signal we're done connection.write(struct.pack('<L', 0)) else: #if 'opencv' in self.model['input'] : while True: # Wait for next request from client message = self.socket.recv() if self.verb: print("Received request %s" % message) if message == b'RIP': finish = time.time() break # grab a frame returned, cam_data = self.camera.cap.read() data = self.code(cam_data.reshape((self.h, self.w, 3))) # stream it self.send_array(self.socket, data) count += 1 elif 'noise' in self.model['input'] : while True: # Wait for next request from client message = self.socket.recv() if self.verb: print("Received request %s" % message) if message == b'RIP': finish = time.time() break data = np.random.randint(0, high=255, size=(self.w, self.h, 3)) # Reset the stream for the next capture self.send_array(self.socket, data) count += 1 elif 'stream' in self.model['input'] : context = zmq.Context() if self.verb: print("Connecting to retina with port %s" % self.model['port']) self.socket = context.socket(zmq.REQ) self.socket.connect ("tcp://%s:%s" % (self.model['ip'], self.model['port'])) t0 = time.time() start = time.time() try: if 'display' in self.model['output'] : from openRetina import Canvas from vispy import app c = Canvas(self) app.run() else: print('headless mode') while time.time()-start < self.model['T_SIM'] + self.sleep_time*2: data = self.request_frame() if self.verb: print('Image is ', data.shape, 'FPS=', 1./(time.time()-t0)) t0 = time.time() finally: if 'capture' in self.model['output'] : import imageio print(self.decode(self.request_frame()).mean()) imageio.imwrite('capture.png', np.fliplr(255*self.decode(self.request_frame()))) self.socket.send (b"RIP") self.socket.close() # print('Sent %d images in %d seconds at %.2ffps' % ( # count, finish-start, count / (finish-start))) self.socket.close()
def plot(self, start_x=0, start_y=0, span=-1, compression_factor=1, type="3D", elev_scale=0.1): start_time = time.time() int_data = [] if start_y + span >= self.real_nrows: print "ERROR: Number of rows specified greater than total in data set." return if start_x + span >= self.real_ncols: print "ERROR: Number of columns specified greater than total in data set." return if span == -1: span_x = self.real_ncols - start_x span_y = self.real_nrows - start_y x_ctr = 0 for i in xrange(start_y, start_y + span_y): x_ctr += 1 if (x_ctr % compression_factor) == 0: cur_row = self.data[i] new_row = [] y_ctr = 0 for j in xrange(start_x, start_x + span_x): y_ctr += 1 if (y_ctr % compression_factor) == 0: new_row.append(int(self.data[i][j])) int_data.append(new_row) Z = np.array(int_data) canvas = scene.SceneCanvas(keys='interactive', title="Terrain Map") view = canvas.central_widget.add_view() if type == "3D": #view.camera = scene.PerspectiveCamera(mode='ortho',fov=60.0) view.camera = scene.TurntableCamera( up='z', center=(span_y * 0.5 / compression_factor, span_x * 0.5 / compression_factor, 0)) if type == "2D": view.camera = scene.PanZoomCamera(up='z') # Black background, no paning, blue graph p1 = scene.visuals.SurfacePlot(z=Z, color=(0.5, 0.5, 1, 1), shading='smooth') p1.transform = scene.transforms.AffineTransform() #p1.transform.scale([1/49., 1/49., 0.02]) #p1.transform.translate([-0.5, -0.5, 0]) p1.transform.scale([1, 1, elev_scale]) p1.transform.translate([0, 0, 0]) view.add(p1) canvas.show() total_time = time.time() - start_time time_per_data = total_time / (span_x * span_y) print "Surface plot rendered in " + str( total_time) + " seconds (" + str( time_per_data) + " seconds/point)." app.run()
def scattertime(pos, mfc=[1, 1, 1, 0.8], mec=[0, 0, 0, 0.8], mfs=5, mes=1, bgc=[1, 1, 1], scaling=False, symbol='disc', title='Vispy Canvas'): """ Display a scatter plot in 2D or 3D. Parameters ---------- pos : array The array of locations to display each symbol. mfc : Color | ColorArray The color used to draw each symbol interior. mec : Color | ColorArray The color used to draw each symbol outline. mfs : float or array The symbol size in px. mes : float | None The width of the symbol outline in pixels. bgc : Color The color used for the background. scaling : bool If set to True, marker scales when rezooming. symbol : str The style of symbol to draw ('disc', 'arrow', 'ring', 'clobber', 'square', 'diamond', 'vbar', 'hbar', 'cross', 'tailed_arrow', 'x', 'triangle_up', 'triangle_down', 'star'). """ # Create the Canvas, the Scene and the View canvas = scene.SceneCanvas(keys='interactive', show=True, bgcolor=bgc, title=title) canvas2 = scene.SceneCanvas(keys='interactive', size=(80, 80), show=True, bgcolor=bgc) view = canvas.central_widget.add_view() # Create the scatter plot scatter = visuals.Markers() scatter.set_data(pos, face_color=mfc[0, :, :], edge_color=mec, scaling=scaling, size=mfs, edge_width=mes, symbol=symbol) view.add(scatter) t1 = Text('frame (ms) : 0', parent=view.scene, color='black') # 2D Shape if pos.shape[1] == 2: # Set the camera properties view.camera = 'panzoom' # 3D Shape elif pos.shape[1] == 3: view.camera = 'turntable' global time time = 0 def update(ev): global time time += 1 t1.text = 'frame (ms) : ' + str(time) time = time % mfc.shape[0] scatter.set_data(pos=pos, face_color=mfc[time, :, :], edge_color=mec, scaling=scaling, size=mfs) if 10 < time < 25: # if 15 < time < 46 : canvas2.bgcolor = (0, 0, 0) else: canvas2.bgcolor = (1, 1, 1) timer = app.Timer(.2, connect=update, start=True) app.run()
# print(session.model.spike_recordings) # print(session.model._recording_offsets) # plt.plot(session.model.spike_samples) # plt.show() # exit() # print(default_timer() - t0) # Cluster counts. # session.cluster_store.disk_store.clear() x = session.clustering.cluster_counts print(session.model.recordings) cl = (sorted(x.items(), key=operator.itemgetter(1))[::-1][:50]) clu = [_[0] for _ in cl][1:5] # print(clu) session.select(clu) # print(session.model.n_spikes) # print(session.model.n_recordings) # print(session.clustering.n_clusters) # session.select([3, 4, 5, 6]) session.show_correlograms() # session.show_features() # session.show_waveforms() run() session.close()
def startRender(self): self.show() app.run()
## Autor: David Ochoa import vispy.scene as vscene import vispy.app as vapp import numpy as np import sys std_ln_dic = dict(color=(1.00, 1.00, 1.00, 1.00), connect='segments') canvas = vscene.SceneCanvas(show=True, title=sys.argv[0]) view = canvas.central_widget.add_view() cube_pt = np.array([[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 1.0, 0.0], [1.0, 1.0, 0.0], [1.0, 1.0, 0.0], [1.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 1.0], [0.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 0.0, 1.0], [1.0, 0.0, 1.0], [0.0, 0.0, 1.0], [0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [1.0, 0.0, 1.0], [0.0, 1.0, 0.0], [0.0, 1.0, 1.0], [1.0, 1.0, 0.0], [1.0, 1.0, 1.0]], dtype=np.float32) cube_vi = vscene.visuals.Line(pos=cube_pt, **std_ln_dic) view.add(cube_vi) cube_vi = vscene.visuals.Line(pos=(cube_pt * 0.5 + 0.25), **std_ln_dic) view.add(cube_vi) view.camera = 'turntable' vapp.run()
def render(model, im_size, K, R, t, clip_near=100, clip_far=2000, surf_color=None, bg_color=(0.0, 0.0, 0.0, 0.0), ambient_weight=0.1, mode='rgb+depth+normal'): # Process input data #--------------------------------------------------------------------------- # Make sure vertices and faces are provided in the model assert ({'pts', 'faces'}.issubset(set(model.keys()))) # Set color of vertices if not surf_color: if 'colors' in model.keys(): assert (model['pts'].shape[0] == model['colors'].shape[0]) colors = model['colors'] if colors.max() > 1.0: colors /= 255.0 # Color values are expected to be in range [0, 1] else: colors = np.ones((model['pts'].shape[0], 4), np.float32) * 0.5 else: colors = np.tile(list(surf_color) + [1.0], [model['pts'].shape[0], 1]) vertices_type = [('a_position', np.float32, 3), ('a_normal', np.float32, 3), ('a_color', np.float32, colors.shape[1])] vertices = np.array(list(zip(model['pts'], model['normals'], colors)), vertices_type) # Rendering #--------------------------------------------------------------------------- render_rgb = mode in ['rgb', 'rgb+depth', 'rgb+normal', 'rgb+depth+normal'] render_depth = mode in [ 'depth', 'rgb+depth', 'depth+normal', 'rgb+depth+normal' ] render_normal = mode in [ 'normal', 'rgb+normal', 'depth+normal', 'rgb+depth+normal' ] c = _Canvas(vertices, model['faces'], im_size, K, R, t, clip_near, clip_far, bg_color, ambient_weight, render_rgb, render_depth, render_normal) app.run() #--------------------------------------------------------------------------- if mode == 'rgb': out = c.rgb elif mode == 'depth': out = c.depth elif mode == 'normal': out = c.normal elif mode == 'rgb+depth': out = c.rgb, c.depth elif mode == 'rgb+normal': out = c.rgb, c.normal elif mode == 'depth+normal': out = c.depth, c.normal elif mode == 'rgb+depth+normal': out = c.rgb, c.depth, c.normal else: out = None print('Error: Unknown rendering mode.') exit(-1) c.close() return out
def show(self): """Display the graphical user interface.""" # This function has to be placed here (and not in the user.py script) self.showMaximized() visapp.run()
def main(args=None): p = ParserCreator() if args is None: args = sys.argv[1:] elif isinstance(args, string_types): args = args.split(' ') args = p.parse(args) if args is None: return if args.profiler or args.line_profiler: from phy.utils.testing import _enable_profiler, _profile prof = _enable_profiler(args.line_profiler) else: prof = None import phy if args.debug: phy.debug() # Hide the traceback. if args.hide_traceback: def exception_handler(exception_type, exception, traceback): print("{}: {}".format(exception_type.__name__, exception)) sys.excepthook = exception_handler # Activate IPython debugger. if args.pdb: from IPython.core import ultratb sys.excepthook = ultratb.FormattedTB( mode='Verbose', color_scheme='Linux', call_pdb=1, ) func = getattr(args, 'func', None) if func is None: p.parser.print_help() return out = func(args) if not out: return cmd, ns = out if not cmd: return requires_qt = ns.pop('requires_qt', False) requires_vispy = ns.pop('requires_vispy', False) # Default variables in namespace. ns.update(phy=phy, path=args.file) if 'session' in ns: ns['model'] = ns['session'].model # Interactive mode with IPython. if args.ipython: print("\nStarting IPython...") from IPython import start_ipython args_ipy = ["-i", "-c='{}'".format(cmd)] if requires_qt or requires_vispy: # Activate Qt event loop integration with Qt. args_ipy += ["--gui=qt"] start_ipython(args_ipy, user_ns=ns) else: if not prof: exec_(cmd, {}, ns) else: _profile(prof, cmd, {}, ns) if requires_qt: # Launch the Qt app. from phy.gui import run_qt_app run_qt_app() elif requires_vispy: # Launch the VisPy Qt app. from vispy.app import use_app, run use_app('pyqt4') run()
def main(fname): mvc = MolecularViewerCanvas(fname) mvc.show() app.run()
def run(self): self.show() with warnings.catch_warnings(): app.run()
def show(self): app.run()
def run(self): import sys if sys.flags.interactive != 1: app.run()
self.program.draw('line_strip') def on_mouse_move(self, event): def _normalize((x, y)): w, h = float(self.width), float(self.height) return x/(w/2.)-1., y/(h/2.)-1. if event.is_dragging: x0, y0 = _normalize(event.press_event.pos) x1, y1 = _normalize(event.last_event.pos) x, y = _normalize(event.pos) dx, dy = x - x1, -(y - y1) button = event.press_event.button pan_x, pan_y = self.program['u_pan'] scale_x, scale_y = self.program['u_scale'] if button == 1: self.program['u_pan'] = (pan_x+dx/scale_x, pan_y+dy/scale_y) elif button == 2: scale_x_new, scale_y_new = scale_x * math.exp(2.5*dx), scale_y * math.exp(2.5*dy) self.program['u_scale'] = (scale_x_new, scale_y_new) self.program['u_pan'] = (pan_x - x0 * (1./scale_x - 1./scale_x_new), pan_y + y0 * (1./scale_y - 1./scale_y_new)) self.update() c = Canvas() c.show() app.run()