def update(self, particle_data): if type(particle_data) is not np.ndarray: particle_data = np.array(particle_data) row_num, col_num = particle_data.shape # convert particle data format to shader data # check shader program for detail. shader_data = np.empty((particle_data.shape[0], particle_data.shape[1], 7), dtype=int) for i in range(row_num): for j in range(col_num): p = particle_data[i,j] shader_data[i,j,0] = self.PARTICLE_TYPE_INDEX_MAP[p['type']] shader_data[i,j,1] = j shader_data[i,j,2] = (row_num - i) - 1 for k in range(2): try: pb = p['bonds'][k] shader_data[i,j,3+k*2] = pb[1] shader_data[i,j,4+k*2] = (row_num - pb[0]) - 1 except IndexError: shader_data[i,j,[3+k*2,4+k*2]] = -1 shader_data2 = shader_data.reshape((-1, 7)) self._render_program['a_particle_type'] = shader_data2[:,0].astype(np.float32) self._render_program['a_position'] = shader_data2[:,1:3].astype(np.float32) self._render_program['a_bondding_positions'] = shader_data2[:,3:7].astype(np.float32) self._render_program['u_window_size'] = self._canvas.physical_size self._render_program['u_particle_num'] = [col_num, row_num] self._canvas.update() app.process_events()
def update(self, action): # action take 0-1 value v = action[:,0] * (self.MAX_VELOCITY - self.MIN_VELOCITY) + self.MIN_VELOCITY av = (action[:,1] - 0.5) * 2 * self.MAX_ANGULAR_VELOCITY self._agents_pos += (v * [np.cos(self._agents_th), np.sin(self._agents_th)]).T self._agents_th += av self._agents_pos[:,0] = (self._agents_pos[:,0] + self._FIELD_WIDTH) % self._FIELD_WIDTH self._agents_pos[:,1] = (self._agents_pos[:,1] + self._FIELD_HEIGHT) % self._FIELD_HEIGHT self._agents_th = (self._agents_th + 2.0 * np.pi) % (2.0 * np.pi) for x, y in self._agents_pos.astype(int): for i in range(-1, 2): for j in range(-1, 2): xi = (x + i + self._FIELD_WIDTH) % self._FIELD_WIDTH yi = (y + j + self._FIELD_HEIGHT) % self._FIELD_HEIGHT self._agents_fitness += self._field[yi,xi] if self._SECRATION is None: #self._field[yi,xi] *= 0.5 # current running self._field[yi,xi] *= 0.9 # sampledata_last2 else: self._field[yi, xi] += self._SECRATION self._field.clip(0, 1) self._field *= self._FIELD_DECAY_RATE self._field_image.set_data(self._field) for polygon, (x, y), th in zip(self._agent_polygon, self._agents_pos, self._agents_th): polygon.transform.reset() polygon.transform.rotate(180 * th / np.pi, (0,0,1)) polygon.transform.translate((x, y)) self._canvas.update() app.process_events()
def update(self, matrix): matrix[matrix < self.value_range[0]] = self.value_range[0] matrix[matrix > self.value_range[1]] = self.value_range[1] img = ((matrix.astype(np.float64) - self.value_range[0]) / (self.value_range[1] - self.value_range[0]) * 255).astype( np.uint8) self._render_program['u_texture'] = img self._canvas.update() app.process_events()
def main(self): # Process app events # This is going call the canvas' on_draw method app.process_events() # Update routines IF visual is set and active if self.current_visual is not None and self.current_visual.is_active: self.update_routines(self.current_visual)
def show_mol_surf(mol_obj=None, surf_datas=None, l_par=None, reduced_mol=False, **kwargs): canvas = scene.SceneCanvas(keys='interactive', bgcolor=(1, 1, 1, 1)) view = canvas.central_widget.add_view() num = None if surf_datas is not None: if isinstance(surf_datas, tuple): colors = ColorIter(len(surf_datas)) for data in surf_datas: if num is not None and len(data) != num: raise TypeError("different dimensions of surfaces") num = len(data) build_surface(data=data, view=view, color=next(colors)) else: build_surface(data=surf_datas, view=view, color=next(ColorIter(1))) num = len(surf_datas) if mol_obj is not None: mol = mol_obj.copy() if surf_datas is not None: if l_par is not None: mol.pos /= l_par mol.pos *= num vis_mol_wrap(mol, view=view, reduced_mol=reduced_mol) if num is None: num = 50 sr = kwargs.get('setrange', num) cam = scene.TurntableCamera(elevation=30, azimuth=30) if kwargs.get('show_axis', True): axis = myXYZAxis(length=num + 10, parent=view.scene) cam.set_range((-sr, sr), (-sr, sr), (-sr, sr)) view.camera = cam cube_size = kwargs.get('cube_size', 0.) scene.visuals.Cube(size=cube_size * num / 2, color=(0.9, 0.9, 0.3, 0.4), edge_color="black", parent=view.scene) canvas.show() if kwargs.get('quit', False): app.process_events() else: app.run() if kwargs.get('screenshot', False): name = kwargs.get("screenname", 'screenshot.png') im = _screenshot((0, 0, canvas.size[0], canvas.size[1])) imsave(name, im)
def render( self, image, elevations ): """ Renders the elevation map and returns the produced image :param image: Background image :param elevations: Elevation map """ self.quad_bg['texture'] = gloo.Texture2D(image) elevations = elevations.reshape( (elevations.size,1) ) # Reshape elevations to column array self.grid["elevation"] = np.squeeze(elevations).astype(np.float32) self.update() app.process_events() return self._im_zimg, self._im_xyzimg
def vispar(): def _exeval(f, *x, **y): nonlocal _error assert _done == _todo == [] # _todo.insert(0,fog(print,'Hello wurlzy')) _todo.insert(0, fog(f, *x, **y)) while not _done and not _error: pass assert _todo == [] if _error: assert not _done temp = _error _error = None raise temp out = _done.pop() assert not _done return out def _exec(*x, **y): return _exeval(exec, *x, **y) def _eval(*x, **y): return _exeval(eval, *x, **y) _error = None _todo = [] _done = [] # Results of _todo import rp.r_iterm_comm as ric _level = ric.pseudo_terminal_level run_as_new_thread(pseudo_terminal, globals(), exec=_exec, eval=_eval) while ric.pseudo_terminal_level == _level: pass while 1: if ric.pseudo_terminal_level == _level: break try: from vispy import app app.process_events() except: print("harry potwar strikes again! keep chuggin...") pass if _todo: try: _done.append(_todo.pop()()) except BaseException as e: _error = e assert not _todo print('...aaaannndddd were DONE chuggin.') app.quit( ) # NOT nessecary but PERHAPS its nicer than having a crashy window...make this optional though!!!
def update(self, points, options=None, redraw=False): if isinstance(self.view.camera, CustomPanZoomCamera): self.view.camera.expand_bounds(points[:, 0].min(), points[:, 1].min()) self.view.camera.expand_bounds(points[:, 0].max(), points[:, 1].max()) options = {} if options is None else options options.setdefault("edge_color", None) options.setdefault("face_color", (1, 1, 1, 0.5)) options.setdefault("size", 5) self.scatter.set_data(points, **options) if redraw: app.process_events()
def make_frame(t): global fnum # paramter t is time in seconds. so for 20 fps every second # has 20 calls. this is not the frame number # so multiply by some factor to get a faster movie surface.set_data(z = Z(fnum)) # Update the mathematical surface fnum += .25 # optionally change color ... surface.color = (np.clip(1.-fnum/20,0,1),1,np.clip(fnum/20,0,1),1) canvas.bgcolor=(0,np.clip(.3-(fnum/20),0,1),.3,1) # optionally call event loop. this will make the video ## follow the user interactions .... app.process_events() # draw and capture canvas.on_draw(None) # Update the image on Vispy's canvas return _screenshot((0,0,canvas.size[0],canvas.size[1]))[:,:,:3]
def __init__(self, **kwargs): vxprocess.AbstractProcess.__init__(self, **kwargs) self.app = app.use_app() self.visual_is_displayed = False self.enable_idle_timeout = False self.times = [] # Create canvas _interval = 1. / config.CONF_DISPLAY_FPS self.canvas = Canvas(_interval) # Process vispy events once too avoid frozen screen at start app.process_events() # Run event loop self.enable_idle_timeout = False self.run(interval=_interval)
def render(self, R, t, random_light_pos=None): # Rendering #--------------------------------------------------------------------------- self.c.render(R,t,random_light_pos) #app.run() app.process_events() #--------------------------------------------------------------------------- if self.mode == 'rgb': out = self.c.rgb elif self.mode == 'depth': out = self.c.depth elif self.mode == 'rgb+depth': out = self.c.rgb, self.c.depth else: out = None print('Error: Unknown rendering mode.') exit(-1) return out
def add_point(self, y, line_num=0, options=None, redraw=False): self.view.camera.expand_bounds(y=y) line = self.lines[line_num] step = self.steps[line_num] shift = 1 if isinstance(y, (int, float)) else len(y) if step < self.window_size: self.steps[line_num] = step + shift else: # shift to left by length y line.pos[:-shift, 1] = line.pos[shift:, 1] step = self.window_size - shift line.pos[step : step + shift, 1] = y options = {} if options is None else options line.set_data(line.pos, **options) if redraw: app.process_events()
def _test_functonality(backend): """ Create app and canvas so we have a context. Then run tests. """ # use the backend gl.use(backend) # Note that we explicitly use pyglet because with Qt we seem # to get errors for this test with app_opengl_context('qt') as context: _clear_screen() # Prepare w, h = context.c.size gl.glViewport(0, 0, w, h) gl.glScissor(0, 0, w, h) # touch gl.glClearColor(0.0, 0.0, 0.0, 1.0) # Setup visualization, ensure to do it in a paint event objects = context.test(_prepare_vis) _clear_screen() # Draw 1 context.test(_draw1) if SHOW: context.c.swap_buffers() app.process_events() time.sleep(1.0) _clear_screen() # Draw 2 context.test(_draw2) if SHOW: context.c.swap_buffers() app.process_events() time.sleep(1.0) _clear_screen() # Draw 3 context.test(_draw3) if SHOW: context.c.swap_buffers() app.process_events() time.sleep(1.0) # Clean up for delete_func, handle in objects: delete_func(handle)
def update_image(self,data): self.lines.roll_data(self.scale*data) app.process_events()
text_color='k', parent=view.scene) xax.transform = scene.STTransform(translate=(0, 0, -0.2)) yax = scene.Axis(pos=[[-0.5, -0.5], [-0.5, 0.5]], tick_direction=(-1, 0), font_size=16, axis_color='k', tick_color='k', text_color='k', parent=view.scene) yax.transform = scene.STTransform(translate=(0, 0, -0.2)) # Add a 3D axis to keep us oriented axis = scene.visuals.XYZAxis(parent=view.scene) def updatePlot(plot): z = np.random.normal(size=(160, 120), scale=200) z[100, 100] += 50000 z = gaussian_filter(z, (10, 10)) plot.set_data(z=z) if __name__ == '__main__': canvas.show() if sys.flags.interactive == 0: while True: updatePlot(p1) app.process_events()
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) n = 50 cube_vi = vscene.visuals.Line(pos=cube_pt, **std_ln_dic) view.add(cube_vi) view.camera = 'turntable' vapp.process_events() for i in range(1,n): scale = 1.0 - (1 / n) * i cube_vi.set_data(pos = (cube_pt * scale + (1 - scale) / 2)) time.sleep(0.05) vapp.process_events() for i in range(n,1,-1): scale = 1.0 - (1 / n) * i cube_vi.set_data(pos = (cube_pt * scale + (1 - scale) / 2)) time.sleep(0.05) vapp.process_events()
def redraw(self): app.process_events()
def redraw(self): app.process_events() if self.axis_need_fixing > 0: self.view.camera.zoom(2) self.view.camera.zoom(0.5) self.axis_need_fixing -= 1
def update(self): app.process_events()