def makeScene(self, mergeDisplays, bg='default'): if self.viewIdx == 0: MooView.origScene = vp.canvas(width=self.swx * SCALE_SCENE, height=self.swy * SCALE_SCENE, background=bgLookup(bg), align='left', autoscale=True) self.scene = MooView.origScene self.scene.bind('keydown', self.moveView) self.scene.bind('keydown', self.updateAxis) self.scene.bind('mousedown', self.pickObj) #self.flatbox = vp.box( width = 10, height = 6 ) elif mergeDisplays: self.scene = MooView.origScene else: self.scene = vp.canvas(width=self.swx * SCALE_SCENE, height=self.swy * SCALE_SCENE, background=bgvector, align='left', autoscale=True) self.scene.bind('keydown', self.moveView) self.scene.bind('keydown', self.updateAxis) self.scene.bind('mousedown', self.pickObj) ''' self.xAx2 = vp.cylinder( canvas = self.scene, pos = vp.vector( 0, 0, 0), axis = vp.vector( 1e-5, 0, 0 ), radius = 0.2e-6, color = vp.color.red ) self.yAx2 = vp.cylinder( canvas = self.scene, pos = vp.vector( 0, 0, 0), axis = vp.vector( 0, 1e-5, 0 ), radius = 0.2e-6, color = vp.color.green ) self.zAx2 = vp.cylinder( canvas = self.scene, pos = vp.vector( 0, 0, 0), axis = vp.vector( 0, 0, 1e-5 ), radius = 0.2e-6, color = vp.color.blue ) ''' self.scene.bind('mousedown mousemove mouseup', self.updateAxis)
def main(argv): num_points = 10 num_steps = 500 draw_steps = 10 coords = get_initial_directions(num_points) vp.canvas(title='Coordinate system rotations', width=1800, height=1200) csys = draw_initial(coords) energy_hist = [] energy_hist.append(get_total_energy(coords)) print('{:4.0f}: {:f} ({:f})'.format(0, energy_hist[-1], param['kangle'])) for step in range(num_steps): coords = update_positions(coords) energy_hist.append(get_total_energy(coords)) print('{:4.0f}: {:f} ({:f})'.format(step, energy_hist[-1], param['kangle'])) param['kangle'] = param['kangle'] / param['kred'] if (step + 1) % draw_steps == 0: # time.sleep(1/(1+step/10)) time.sleep(0.001) update_drawing(csys, coords) plt.semilogy(energy_hist) print(np.min(energy_hist)) plt.show()
def initGraphics(self, width:int=1200, height:int=800, range:int=1.5, background=color.white, title:str='Vpython animation', updaterate:int=60): canvas(width=width, height=height, range=range, background=background, title=title) self.ground._recursiveInitGraphicsVPython() for sd in self.springDampers: sd.initGraphics() for bc in self.bilateralConstraints: bc.initGraphics() self.updaterate = updaterate
def _make_scene(plot, display_width, display_height): """ Makes the VPython canvas. """ if plot: canvas(width=display_width / 2 - 10, height=display_height, align='left') else: canvas(width=display_width, height=display_height)
def plot_boxes(u, v): vp.canvas() for uu, vv in zip(u, v): vp.box(pos=vp.vec(0, 0, 0), axis=vp.vec(uu[0], uu[1], uu[2]), length=1, width=1, height=1, up=vp.vec(vv[0], vv[1], vv[2]), color=vp.vec( np.random.rand(1)[0], np.random.rand(1)[0], np.random.rand(1)[0]))
def __init__(self): self.black = vpy.vector(0.2, 0.2, 0.2) self.light = vpy.vector(0.7, 0.7, 0.7) self.red = vpy.vector(1, 0.1, 0) self.orange = vpy.vector(1, 0.5, 0) self.green = vpy.vector(0.5, 1, 0.3) self.blue = vpy.vector(0.3, 0.5, 1) self.white = vpy.vector(1, 1, 1) self.yellow = vpy.vector(1, 1, 0) self.faceColors = [ self.green, self.blue, self.yellow, self.white, self.red, self.orange ] self.zero = vpy.vector(0, 0, 0) self.canvas = vpy.canvas(background=vpy.vector(0.8, 0.8, 0.8)) # self.canvas.lights = [] # vpy.distant_light(direction=vpy.vector( 1, 0, 0), color=self.light) # vpy.distant_light(direction=vpy.vector(-1, 0, 0), color=self.light) vpy.distant_light(direction=vpy.vector(0, 1, 0), color=self.light) # vpy.distant_light(direction=vpy.vector( 0,-1, 0), color=self.light) # vpy.distant_light(direction=vpy.vector( 0, 0, 1), color=self.light) # vpy.distant_light(direction=vpy.vector( 0, 0,-1), color=self.light) self.faceIndexDict = {"t": 3, "g": 2, "f": 1, "b": 0, "r": 5, "l": 4} self.genCube()
def create_viz(): global state, G scene = vp.canvas(background=vp.color.white) n = len(state.dims[0]) d = state.dims[0][0] coords = [ vp.vector(root.real, root.imag, 0) for root in [np.exp(1j * 2 * np.pi * i / d) for i in range(d)] ] colors = [vp.color.red, vp.color.green, vp.color.blue] if n == 3 else\ [vp.vector(*np.random.random(3)) for i in range(n)] vpts = {} for i in range(n): pov_state = take_pov(state, 0, i, G) vp.label(text="pov: %d" % i,\ pos=vp.vector(3*i-n,-1.5,0),\ color=colors[i]) vp.ring(color=colors[i],\ radius=1,\ axis=vp.vector(0,0,1),\ thickness=0.01,\ pos=vp.vector(3*i-n, 0, 0)) for k in range(n): partial = pov_state.ptrace(k).full() for j in range(d): vpts[(i, k, j)] = vp.sphere(opacity=0.5,\ pos=vp.vector(3*i-n,np.random.randn()/25,0)+coords[j],\ color=colors[k],\ radius=partial[j,j].real/4) return vpts
def create_viz(): global state, G, basis scene = vp.canvas(background=vp.color.white) n = len(state.dims[0]) colors = [vp.color.red, vp.color.green, vp.color.blue] if n == 3 else\ [vp.vector(*np.random.random(3)) for i in range(n)] vpts = {} for i in range(n): pov_state = take_pov(state, 0, i, G, basis=basis) vp.label(text="pov: %d" % i,\ pos=vp.vector(3*i-n,-1.5,0),\ color=colors[i]) vp.sphere(color=colors[i],\ opacity=0.1,\ pos=vp.vector(3*i-n, 0, 0)) for k in range(n): partial = pov_state.ptrace(k) xyz = np.array([qt.expect(qt.sigmax(), partial),\ qt.expect(qt.sigmay(), partial),\ qt.expect(qt.sigmaz(), partial)]) vpts[(i,k)] = vp.arrow(opacity=0.3,\ pos=vp.vector(3*i-n, 0, 0)+0.01*vp.vector(*np.random.randn(3)),\ color=colors[k],\ axis=vp.vector(*xyz),\ visible=not np.isclose(np.linalg.norm(xyz), 0)) return vpts
def _init_anim(self): import vpython as vp l_plate = self.domain_param['l_plate'] m_ball = self.domain_param['m_ball'] r_ball = self.domain_param['r_ball'] d_plate = 0.01 # only for animation # Init render objects on first call self._anim['canvas'] = vp.canvas(width=800, height=800, title="Quanser Ball-Balancer") self._anim['ball'] = vp.sphere(pos=vp.vec(self.state[2], self.state[3], r_ball + d_plate / 2.), radius=r_ball, mass=m_ball, color=vp.color.red, canvas=self._anim['canvas']) self._anim['plate'] = vp.box(pos=vp.vec(0, 0, 0), size=vp.vec(l_plate, l_plate, d_plate), color=vp.color.green, canvas=self._anim['canvas']) self._anim['null_plate'] = vp.box( pos=vp.vec(0, 0, 0), size=vp.vec(l_plate * 1.1, l_plate * 1.1, d_plate / 10), color=vp.color.cyan, opacity=0.5, # 0 is fully transparent canvas=self._anim['canvas'])
def _init_anim(self): import vpython as vp l_pole = float(self.domain_param['l_pole']) r_pole = 0.05 th, _ = self.state # Init render objects on first call self._anim['canvas'] = vp.canvas(width=1000, height=600, title="Pendulum") # Joint self._anim['joint'] = vp.sphere( pos=vp.vec(0, 0, r_pole), radius=r_pole, color=vp.color.white, ) # Pole self._anim['pole'] = vp.cylinder(pos=vp.vec(0, 0, r_pole), axis=vp.vec(2 * l_pole * vp.sin(th), -2 * l_pole * vp.cos(th), 0), radius=r_pole, length=2 * l_pole, color=vp.color.blue, canvas=self._anim['canvas'])
def _init_anim(self): import vpython as vp r_ball = self.domain_param['r_ball'] l_beam = self.domain_param['l_beam'] d_beam = self.domain_param['d_beam'] x = float(self.state[0]) # ball position along the beam axis [m] a = float(self.state[1]) # angle [rad] self._anim['canvas'] = vp.canvas(width=800, height=600, title="Ball on Beam") self._anim['ball'] = vp.sphere( pos=vp.vec(x, d_beam/2. + r_ball, 0), radius=r_ball, color=vp.color.red, canvas=self._anim['canvas'] ) self._anim['beam'] = vp.box( pos=vp.vec(0, 0, 0), axis=vp.vec(vp.cos(a), vp.sin(a), 0), length=l_beam, height=d_beam, width=2*d_beam, color=vp.color.green, canvas=self._anim['canvas'] )
def __init__(self, ): self.cav = vp.canvas() self.cav.camera.rotate(angle=vp.radians(180), axis=self.cav.up) self.cav.camera.rotate(angle=vp.radians(180), axis=self.cav.forward) joints_radius = 10 joints_color = vpvec([1, 1, 1]) joints_opacity = 0.8 line_color = vp.color.cyan line_radius = 5 self.joints = [ vp.sphere( canvas=self.cav, pos=vpvec([0, 0, 0]), radius=joints_radius * 0.9, color=joints_color, opacity=joints_opacity, ) for i in range(21) ] self.jointline = { c: vp.curve( canvas=self.cav, pos=[vpvec([0, 0, 0]), vpvec([0, 0, 0])], color=line_color, radius=line_radius, ) for c in connections }
def draw_electrical_field(num_charge): scene = canvas(title='electric field of a list of charges', width=800, height=600, background=color.magenta) # dx = L / num_charge Q = 1e-8 # total charges # dq = 1e-8 / 6 # define charge of electrons dq = Q / num_charge charges = [] space_between = 2 * view_space_length / ( num_charge + 1) # evenly divide space between each electrons for x in arange(-view_space_length + space_between, view_space_length, space_between): q = ElectricBall(pos=vector(x, 0, 0), radius=1, color=color.red, charge=dq) charges.append(q) # creat arrow around electric balls arrows = [] observe_points_dis = 0.5 * view_space_length for x in arange(-1.5 * view_space_length, 1.51 * view_space_length, observe_points_dis): for y in arange(-1.0 * view_space_length, 1.01 * view_space_length, observe_points_dis): for z in arange(-1.0 * view_space_length, 1.01 * view_space_length, observe_points_dis): pointer = arrow(pos=vector(x, y, z), color=color.blue, opacity=0.0) electrical_vector = vector(0, 0, 0) # infinity large arrows will be ignored infinity = False # each arrow is affected by all of the charges for q in charges: direction_vector = pointer.pos - q.pos if direction_vector.mag == 0: infinity = True break # calculate electric field affected by each electric ball E = (k * dq / direction_vector.mag**2) * direction_vector.norm() # sum electric field at the each point electrical_vector += E if infinity: continue # if arrow is not too large, display it if electrical_vector.mag < observe_points_dis: # "rate(30)" tells the program to not do the loop more than 30 times a second. rate(20 * num_charge) pointer.axis = electrical_vector pointer.shaftwidth = 0.1 pointer.opacity = 1.0 arrows.append(pointer)
def create_scene(): scene = canvas(range=5) wire = cylinder(pos=vector(-10, -0.5, 0), axis=vector(20, 0, 0), radius=0.02, color=color.white) return scene
def draw_voronoi_3d(points_3d, pointsize=1): """ points_3d - (iter) - any iterable of numpy.ndarrays """ canvas = vpy.canvas(width=1280, height=720, background=vpy.vec(0.7, 0.7, 0.7)) draw_points(points_3d, color=vpy.vec(.3, .3, .8), radius=pointsize) vor = Voronoi(points_3d, incremental=False) # print(vor.points) # print(vor.vertices) draw_points(vor.vertices, color=vpy.vec(.9, .5, 0), radius=pointsize / 2) vertices = [vpy.vec(*list(pos)) for pos in vor.vertices] for poly_faces in get_polyhedra(vor): # print(faces, len(faces)) poly = Polyhedron( vertices, poly_faces, color=vpy.vec(*np.random.rand(3)), # color=vpy.vec(.9,.5,0), opacity=1, sort_faces=True) time.sleep(2)
class Game: world_size = 5 background_color = v.vector(1, 1, 0) dt = 0.005 # =delta-time ... how fast the simulation should run grid_size = 1 # must be positive integer. TODO: allow numpy array for floats grid = [] busy = False # lock flag to avoid too much widghets events points = None water = None # for diamond-square min_y = 0.0 # lowest valley max_y = 5.0 # highest peak ## # below sea, all is blue. between snow and sea, all is green. above snow, all is white sea_level = 1 #0.4 # must be between 0 and 1 # snow_level = 4 #0.8 # must be between 0 and 1 # roughness = 0.65 # must be between 0 and 1 # near 0: very smooth. near 1: very rough terrain landscape = None # final object scene1 = v.canvas( title= f"landscape world {world_size} x {world_size}, roughness {roughness}", width=1800, height=700, center=v.vector(0, 0, 0), background=background_color, resizable=False) scene1.autoscale = False
def plotData(File): file = open(FILE, "r") line0 = file.readline() N, DT, TEND, SIZE, VELSIZE, THETA = floatvec(line0.split(",")[0:6]) MASSES = floatvec(line0.split(",")[0:6]) scene = vp.canvas(width=1800 / 1.2, height=1000 / 1.2, autoscale=False, range=2 * SIZE, background=vp.vector(0, 0, 0.15)) posline0 = file.readline() pos0 = floatvec(posline0.split(",")[1:]) bodylist = [] for i in range(int(N)): theta = np.arctan2(pos0[3 * i + 1], pos0[3 * i]) + np.pi color = vp.vector(0.75 - 0.25 * np.sin(theta), 0.75 - 0.25 * np.sin(theta + 2 * np.pi / 3), 0.75 - 0.25 * np.sin(theta - 2 * np.pi / 3)) bodylist += [ vp.sphere(pos=vp.vector(*pos0[3 * i:3 * i + 3]), radius=RADIUS, color=color) ] posline = posline0 input("PRESS ENTER:") while posline: #input() pos = floatvec(posline.split(",")[1:]) for i in range(int(N)): body = bodylist[i] body.pos = vp.vector(*pos[3 * i:3 * i + 3]) posline = file.readline() file.close()
def _create_obj(self, entity: Entity, origin: Entity, texture: Optional[str]) -> vpython.compound: """Creates the habitat, and also a new minimap scene and habitat.""" assert texture is not None habitat = self._create_hab(entity, texture) habitat.pos = entity.screen_pos(origin) main_scene = vpython.canvas.get_selected() self._minimap_canvas = vpython.canvas(width=200, height=150, userspin=False, userzoom=False, up=common.DEFAULT_UP, forward=common.DEFAULT_FORWARD) self._minimap_canvas.append_to_caption( # The element styling will be removed at runtime. This just hides # this helptext during startup. "<span class='helptext' style='display: none'>" "This small 'minimap' shows the Habitat's orientation. The red " "arrow represents the Hab's velocity relative to the reference, " "and the gray arrow points to position of the reference." "</span>") self._small_habitat = self._create_hab(entity, texture) self._ref_arrow = vpython.arrow(color=vpython.color.gray(0.5)) self._velocity_arrow = vpython.arrow(color=vpython.color.red) main_scene.select() self._broken: bool = False return habitat
def main(): ''' Set up Stationary scene ''' scene = vp.canvas(title='Solar system',width=1300,height=600,center=vp.vector(0,0,0)) scene.autoscale = False scene.range = star_radius*model_scale scene.camera.pos = vp.vector(0,100000,star_radius*model_scale) # nice view # scene.camera.pos = vp.vector(100000,0,0) # side view # scene.camera.pos = vp.vector(0,100000,0) # top down view scene.camera.axis = vp.vector(vp.vector(0,0,0) - scene.camera.pos) # Background stars if show_backgound_stars == True: init_stars(star_radius, star_size, num_star) ''' Set up Animated objects ''' # Intialize Asteroid belt if show_asteroid_belt == True: print('Generating asteroid belt') ast_list, ast_radius_list, ast_theta0_list = init_belt(ast_belt_radius, ast_size, num_ast) # Initialize Kuiper belt if show_kuiper_belt == True: print('Generating kuiper belt') kui_list, kui_radius_list, kui_theta0_list = init_belt(kui_belt_radius, kui_size, num_kui) # Initialize planet system object_list = init_system(filename) ''' Animation ''' print('Begin animation') dt = 100 i = 0 # Counter for moving the belts while True: vp.rate(500000) # update planet position for body in object_list: body.motion(dt, i) # rotate asteroid belt and kuiper belt if rotate_belt == True and show_asteroid_belt == True: # shift theta of all belt objects for ast, ast_radius, ast_theta0 in zip(ast_list, ast_radius_list, ast_theta0_list): ast_theta = ast_theta0 + i * 2*np.pi/ast_belt_period # change in theta per unit time = omega = 2pi/T ast.pos = model_scale*ast_radius*vp.vector(vp.cos(ast_theta),0,vp.sin(ast_theta)) if rotate_belt == True and show_kuiper_belt == True: for kui, kui_radius, kui_theta0 in zip(kui_list, kui_radius_list, kui_theta0_list): kui_theta = kui_theta0 + i * 2*np.pi/kui_belt_period kui.pos = model_scale*kui_radius*vp.vector(vp.cos(kui_theta),0,vp.sin(kui_theta)) if i%int(print_step) == 0: print('Celestial object positions update completed - Running next iteration') i += 1
def draw_a_layer(self, layer, polylist=None, title=None): from vpython import canvas, vector, curve, color, sphere scene = canvas(title=title, width=800, height=800, center=vector(self.shape[0] / 2, self.shape[1] / 2, self.shape[2] / 2), background=color.white) self.draw_box() nums = self.get_num_of_polymers() for i in range(nums): chain = self.get_polymer(i) c = curve(color=color.yellow, radius=0.1) if chain: point2 = chain.get_list()["chain"][0].copy()['position'] type = chain.get_list()["chain"][0].copy()["type"] if type == 1: this_color = color.yellow elif type == 2: # continue this_color = color.blue elif type == 3: continue this_color = color.red c = curve(color=this_color, radius=0.1) else: continue for pointinfo in chain.get_list()["chain"]: point = pointinfo['position'] type = pointinfo["type"] if type == 1: this_color = color.yellow elif type == 2: # continue this_color = color.blue elif type == 3: continue this_color = color.red if point[0] != layer: continue else: sphere(pos=vector(point[0], point[1], point[2]), color=this_color, radius=0.2) if (self.if_out_of_range(point2, point)): pass else: c = curve(color=this_color, radius=0.1) c.append(vector(point[0], point[1], point[2])) point2 = point.copy() return scene
def __init__(self): self._commands: List[network.Request] = [] self._last_state: PhysicsState canvas = vpython.canvas(width=1, height=1) common.include_vpython_footer_file( Path('orbitx', 'graphics', 'simple_css.css')) # Hide vpython wtexts, except for the table. canvas.append_to_caption("""<style> span { /* Hide any wtexts we generate. */ display: none; } span.nohide { /* Make sure wtexts we make are not hidden. */ display: initial; } div.flex-box { display: flex; justify-content: space-between; } input { flex: 1; margin: 5px; } </style>""") canvas.append_to_caption("<title>OrbitX Physics Server</title>") canvas.append_to_caption("<h1>OrbitX Physics Server</h1>") canvas.append_to_caption(f"<h3>Running on {socket.getfqdn()}</h3>") canvas.append_to_caption("<div class='flex-box'></div>") vpython_widgets.Input(bind=self._load_hook, placeholder='Load savefile') vpython_widgets.Input(bind=self._load_hook, placeholder='Save savefile') vpython_widgets.stuff_widgets_into_flex_box( [vpython_widgets.last_div_id - 1, vpython_widgets.last_div_id]) canvas.append_to_caption("<hr />") self._clients_table = vpython.wtext(text='') vpython_widgets.last_div_id += 1 # We hide all other vpython-made wtexts, except for this one. canvas.append_to_caption(f"""<script> document.querySelector( 'span[id="{vpython_widgets.last_div_id}"]').className = 'nohide'; </script>""") self._last_contact_wtexts: List[vpython.wtext] = [] self._previous_number_of_clients: int = 0 # This is needed to launch vpython. vpython.sphere() canvas.delete() common.remove_vpython_css()
def __init__(self, height=500, width=1000, title='', caption='', grid=True): # Create a new independent scene self.scene = canvas() # Apply the settings self.scene.background = color.white self.scene.width = width self.scene.height = height self.scene.autoscale = False # Disable default controls self.scene.userpan = False # Remove shift+mouse panning (not very good controls) self.scene.userzoom = True # Keep zoom controls (scrollwheel) self.scene.userspin = True # Keep ctrl+mouse enabled to rotate (keyboard rotation more tedious) # Apply HTML title/caption if title != '': self.scene.title = title self.__default_caption = caption if caption != '': self.scene.caption = caption # List of robots currently in the scene self.__robots = [] self.__selected_robot = 0 # Checkbox states self.__grid_visibility = grid self.__camera_lock = False self.__grid_relative = True # Create the UI self.__ui_controls = self.__setup_ui_controls([]) # Indices to easily identify entities self.__idx_btn_reset = 0 # Camera Reset Button self.__idx_menu_robots = 1 # Menu box self.__idx_chkbox_ref = 2 # Reference Visibility Checkbox self.__idx_chkbox_rob = 3 # Robot Visibility Checkbox self.__idx_chkbox_grid = 4 # Grid Visibility Checkbox self.__idx_chkbox_cam = 5 # Camera Lock Checkbox self.__idx_chkbox_rel = 6 # Grid Relative Checkbox self.__idx_sld_opc = 7 # Opacity Slider self.__idx_btn_del = 8 # Delete button self.__idx_btn_clr = 9 # Clear button # Rotate the camera convert_grid_to_z_up(self.scene) # Any time a key or mouse is held down, run the callback function rate(30) # 30Hz self.scene.bind('keydown', self.__handle_keyboard_inputs) # Create the grid, and display if wanted self.__graphics_grid = GraphicsGrid(self.scene) if not self.__grid_visibility: self.__graphics_grid.set_visibility(False)
def viewScene(self): """ Canvas Scene """ scene = vp.canvas( title="Oscillations", x=0, y=0, width=1600, height=900, )
def main(): tree = createTree(iter = 4, rotation = False, seed = 30) #DRAWING METHODS: scene = canvas(width=1500, height=900, center=vector(5,5,0)) sphere( pos = vector(0,0,0), color = vector(1,0,0)) draw_axis(max_coord = 10) drawListBranch(tree) drawSphereFreeEnds(tree)
def __init__(self): self._screen_width, self._screen_height = pyautogui.size() self._scene = canvas(width=self._screen_width-20) self._scene.lights[1].visible = False self._scene.lights.pop(1) self._controls = Controls(self._scene) self._gravity = self._controls.gravity self._time_stamp = None while True: self.__build_scenario() self.__simulate_scenario()
def plotAndAnimateData(File): file = open(FILE, "r") line0 = file.readline() N, DT, TEND, SIZE, VELSIZE, THETA = floatvec(line0.split(",")[0:6]) MASSES = floatvec(line0.split(",")[0:6]) scene = vp.canvas(width=1000 / 1.2, height=1000 / 1.2, autoscale=False, range=2 * SIZE, background=vp.vector(0, 0, 0.15)) posline0 = file.readline() pos0 = floatvec(posline0.split(",")[1:]) bodylist = [] for i in range(int(N)): theta = np.arctan2(pos0[3 * i + 1], pos0[3 * i]) + np.pi color = vp.vector(0.75 - 0.25 * np.sin(theta), 0.75 - 0.25 * np.sin(theta + 2 * np.pi / 3), 0.75 - 0.25 * np.sin(theta - 2 * np.pi / 3)) bodylist += [ vp.sphere(pos=vp.vector(*pos0[3 * i:3 * i + 3]), radius=RADIUS, color=color) ] posline = posline0 input("PRESS ENTER TO START THE COUNTDOWN:") for i in range(10, 0, -1): print(i) time.sleep(1) print("GO!!!") ic = 0 fnum = 0 while posline: #input() pos = floatvec(posline.split(",")[1:]) for i in range(int(N)): body = bodylist[i] body.pos = vp.vector(*pos[3 * i:3 * i + 3]) posline = file.readline() if (ic % 1 == 0): # grab every 20 iterations, may need adjustment im = ImageGrab.grab(Bounds(scene)) num = '00' + repr(fnum) # sequence num 000-00999, trunc. below im.save('img-' + num[-3:] + '.png') # save to png file, 000-999, 3 digits fnum += 1 ic += 1 file.close() #call("ffmpeg -r 20 -i img-%3d.png -vcodec libx264 -vf format=yuv420p,scale={}:{} -y movie.mp4".format(int(1.2*scene.width), int(1.2*scene.height))) call( "ffmpeg -r 20 -i img-%3d.png -vcodec libx264 -vf format=yuv420p -y movie.mp4" ) print("\n Movie made: movie.mp4")
def get_minimum_energy(num_points, filenum): num_optim = num_points - 1 r0 = get_initial_guess(num_optim) # Transform into variable array x0 = np.reshape(r0, (num_optim * 3)) res = opt.minimize(objective_function, x0, method='Powell', options={'xtol': 1e-5, 'disp': False, 'maxfev': 10000}) if write_result: write_result_file(num_points, res, filenum) if plot_result: rot_vectors = np.reshape(res.x, (3, num_optim)) coords = get_coords(rot_vectors) vp.canvas(title='Coordinate system rotations', width=1800, height=1200) draw_initial(coords) return res.fun
def main(grid, init, goal, steering_noise, distance_noise, measurement_noise,weight_data, weight_smooth, p_gain, d_gain): landmarkss = [] for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j]==1: landmarkss.append((i,j)) z = (len(grid)*10)+5 x = (len(grid[0])*10)+5 escena = vpython.canvas(width=1200,height=1000) escena.title = "Simulador de Autonomía Vehicular" escena.background = vpython.color.cyan escena.center = vpython.vector(x/2,-1,z/2) escena.forward= vpython.vector(0,-2,-1) #escena.range= 80 #ejex= vpython.curve(color=vpython.color.blue) #ejey=vpython.curve(color=vpython.color.red) #ejez=vpython.curve(color=vpython.color.green) #vpython.userzoom = True #for i in range(x): # pos_x = vpython.vector(i,0,0) # ejex.append(pos_x) # pos_y = vpython.vector(0,i,0) # ejey.append(pos_y) # pos_z=vpython.vector(0,0,i) # ejez.append(pos_z) suelo = vpython.box(pos=vpython.vector(x/2,-0.5,z/2),color=vpython.color.white,size=vpython.vector(x,1.0,z),texture={'file':vpython.textures.metal, 'place':'all'}) high_wall = 30 for i in range(len(landmarkss)): x_wall = (landmarkss[i][1]*10)+5 z_wall = (landmarkss[i][0]*10)+5 if i%2==0: wall = vpython.box(pos=vpython.vector(x_wall,15,z_wall),color=vpython.vector(1,0.7,0.2),size=vpython.vector(10,high_wall,10),texture={'file':vpython.textures.metal, 'place':'all'}) else: wall = vpython.box(pos=vpython.vector(x_wall,25,z_wall),color=vpython.vector(1,0.7,0.2),size=vpython.vector(10,high_wall+20,10),texture={'file':vpython.textures.metal, 'place':'all'}) #IMPLEMENTING PLANING: A* ALGORITHM path = plan(grid, init, goal) path.astar() path_way = path.path #IMPLEMENTING SMOOTHNESS PATH path.smooth(weight_data, weight_smooth) path_smoothed = path.spath inicio =vpython.text(text="Inicio",align='center',color=vpython.color.green,pos=vpython.vector((path_smoothed[0][1]*10)+5,22,(path_smoothed[0][0]*10)+5),height=5,width=12) meta = vpython.text(text="Meta",align='center',color=vpython.color.green,pos=vpython.vector((path_smoothed[-1][1]*10)+5,22,(path_smoothed[-1][0]*10)+5),height=5,width=12) #IMPLEMENTING PARTICLE FILTERS AND PID return run(grid, goal, path.spath, [p_gain, d_gain],escena)
def __init__(self, height=500, width=1000, title='', caption='', grid=True): # Create a new independent scene self.scene = canvas() # Apply the settings self.scene.background = color.white self.scene.width = width self.scene.height = height self.scene.autoscale = False # Disable default controls self.scene.userpan = False # Remove shift+mouse panning (key overwritten) self.scene.userzoom = True # Keep zoom controls (scrollwheel) self.scene.userspin = False # Remove ctrl+mouse enabled to rotate self.__grid_visibility = grid self.__camera_lock = False # Apply HTML title/caption if title != '': self.scene.title = title self.__default_caption = caption if caption != '': self.scene.caption = caption # Rotate the camera # convert_grid_to_z_up(self.scene) # Any time a key or mouse is held down, run the callback function rate(30) # 30Hz self.scene.bind('keydown', self.__handle_keyboard_inputs) # Create the grid, and display if wanted self.__graphics_grid = GraphicsGrid(self.scene) # Toggle grid to 2D self.__graphics_grid.toggle_2d_3d() # Lock the grid self.__graphics_grid.set_relative(False) # Turn off grid if applicable if not self.__grid_visibility: self.__graphics_grid.set_visibility(False) # Reset the camera to known spot self.__reset_camera() self.__graphics_grid.update_grid()
def setup_display(): scene = vp.canvas(x=0, y=0, width=400, height=400, userzoom=False, userspin=True, autoscale=False, center=vp.vector(0, 0, 0), foreground=vp.color.white, background=vp.color.black) return scene
def init_vpython(self): scene = canvas(title="Fans", width=self.win, height=self.win, x=0, y=0, center=vec(0, 0, 0), forward=vec(1,0,-1), up=self.up) scene.autoscale = False scene.range = 25 h = 0.1 mybox = box(pos=vec(0, 0, -h/2), length=self.L, height=h, width=L, up=self.up, color=color.white) # create dust particles for pos in self.positions: p = sphere(pos=vec(*pos), radius=self.radius, color=color.red) p.update = True # to determine if needs position update self.particles.append(p)
def create_vis(self, canvas=None): """ Creates a visualisation. By default, uses a vpython canvas, so imports vpython. Subclass class and change this to change the way visualisations are made. Parameters ---------- canvas: vpython canvas display into which the visualization is drawn """ import vpython #self.scene stores the display into which the system draws if not canvas: if not self.scene: self.scene = vpython.canvas() if canvas: self.scene = canvas # Draw particles if they aren't drawn yet for particle in self.particles: if not particle._visualized: self.spheres.append(vpython.sphere(pos=vector_from(particle.pos), radius=particle.radius, color=vector_from(particle.color), opacity=particle.alpha, display=self.scene)) particle._visualized = True # Draw springs if they aren't drawn yet for spring in self.springs: if not spring._visualized: self.helices.append(vpython.helix(pos=vector_from(spring.particle_1.pos), axis=vector_from(spring.axis), radius=spring.radius, opacity=spring.alpha, color=vector_from(spring.color), display=self.scene)) spring._visualized = True # Draw pointers if they aren't drawn yet for pointer in self.pointers: if not pointer._visualized: self.arrows.append(vpython.arrow(pos=vector_from(pointer.pos), axis=vector_from(pointer.axis), shaftwidth=pointer.shaftwidth, opacity=pointer.alpha, color=vector_from(pointer.color), display=self.scene)) pointer._visualized = True
k1 = h*f(r,t) k2 = h*f(r+0.5*k1, t+0.5*h) k3 = h*f(r+0.5*k2, t+0.5*h) k4 = h*f(r+k3, t+h) r += (k1+2*k2+2*k3+k4)/6 print(0.5*(t/len(pontstemp))*10000.0,"%") #Preparando modo gráfico #Realizando o modo gráfico from vpython import sphere,canvas,color,vector,cylinder,box,helix,rate #Configuração da janela scene2 = canvas(title = "Simulação de órbitas caóticas", width = 600, height = 600,background=color.white) esferabola1 = sphere(radius=7,pos=vector(x1,y1,0),color=color.yellow) esferabola2 = sphere(radius=2,pos=vector(x2,y2,0),color=color.red) esferabola3 = sphere(radius=2,pos=vector(x3,y3,0),color=color.blue) cont = 0 T = len(pontstemp) for k in range(T): esferabola1.pos = vector(posicaox1[k],posicaoy1[k],0.0) esferabola2.pos = vector(posicaox2[k],posicaoy2[k],0.0) esferabola3.pos = vector(posicaox3[k],posicaoy3[k],0.0)
# In[ ]: win=600 L = 10. # container is a cube L on a side gray = vec(0.7,0.7,0.7) # color of edges of container up = vec(0, 0, 1) # In[ ]: scene = canvas(title="Fans", width=win, height=win, x=0, y=0, center=vec(0, 0, 0), forward=vec(1,0,-0.5), up=up) scene.autoscale = False scene.range = 10 h = 0.1 mybox = box(pos=vec(0, 0, -h/2), length=L, height=h, width=L, up=up, color=gray) m = 1 # kg radius = 0.5 # arbitrary for now dt = 1e-3 start = vec(0, 0, radius) v0 = vec(0, 0, 10) g = vec(0, 0, -9.81) Fg = m*g particles =[]