def run_for(self, time, dt=0.01): """ Run simulation for a certain amount of time(as measured in the system's time). Recommended to use this instead of simulate(dt) for most situations. Parameters ---------- time: float Time for which the simulation will go on for in the system's time dt: float Time steps taken. """ # Make pointer objects if not already created if self.display_forces: self._assign_forces() # Create visualization if necessary if self.visualize: self.create_vis() # Import vpython if necessary if self.visualize and self.visualizer_type == "vpython": import vpython # Simulate for given time while self.time < time: if self.visualize and self.visualizer_type == "vpython": vpython.rate(150) self.simulate(dt) if self.stop_on_cycle: if self._cycle_completed(): break self.time += dt
def loop(self): while self.something_in_the_air: self.update() if self.particles: rate(200) for p,pos in zip(sim.particles, sim.positions): if p.update: p.pos = vec(*pos) if p.pos.z < start.z: p.update = False
particles =[] for position, c in zip([start, start+vec(0, 3*radius, 0)], [color.red, color.blue]): p = sphere(pos=position, radius=radius, color=c) p.v = v0 p.update = True # to determine if needs position update particles.append(p) # In[ ]: k = 1 while True: rate(500) # update position first for p in particles: if p.update: p.pos += p.v*dt if p.pos.z < start.z: p.update = False # calculate friction force Fd = -k * particles[1].v Fnet = Fg + Fd a = Fnet / m particles[0].v += g*dt particles[1].v += a*dt
for i in range(len(self.vwhitestars)): self.vwhitestars[i].pos = vpython.vector(*self.exitsXYZ[i]) if self.Q_Spheres: for sphere in self.Q_Spheres: sphere.draw() def intersections(self): pass def mobius_transform(self, kind, delta): pass def rotate_spindle(self, q, pole, delta): pass vpython.scene.width = 900 vpython.scene.height = 900 vpython.scene.range = 1.3 vpython.scene.forward = vpython.vector(-1, 0, 0) vpython.scene.up = vpython.vector(0, 1, 0) n = 4 sphere = Sphere(qutip.rand_ket(n)) energy = qutip.rand_herm(n) while True: new_v = qutip.Qobj(evolvev(sphere.v.full().T[0], energy.full(), 0.007)) new_v.dims = sphere.v.dims sphere.update(new_v) vpython.rate(1) sphere.draw()
#border=extrusion(pos=vector(0,0,0), shape=shapes.rectangle(width=50, height=50,thickness=0.05),color=vector(0.1,0.1,0.2)) #Bricks box = {} for x in chain(range(-20,-19), range(-16,-15), range(-12, -11), range(-8,-7), range(-4, -3), range(0,1), range(4,5), range(8,9), range(12,13), range(16,17), range(20, 21)): for y in chain(range(8,9), range(12,13), range(16,17), range(20,21)): z = 0 box[(x, y)]= vs.box(pos=vs.vector(x, y, z), length=4, height=4, width=0.1, color=vs.color.blue, texture=vs.textures.rock) #Initial Velocities paddle.v=vs.vector(3,0,0) ball.v=vs.vector(0.7,5,0) #Game while(flag==0): vs.rate(5./dt) t=t+dt #Paddle Physics paddle.pos=paddle.pos+paddle.v*dt #Ball Physics ball.v=ball.v+g*dt ball.pos=ball.pos+ball.v*dt #Paddle Boundaries if (paddle.pos.x>19): #Right boundary paddle.v.x=0 if (paddle.pos.x<-19): #Left Boundary paddle.v.x=0 #Ball Boundaries
ksi_ = idst(b_) arr = [] # setup vectors with solely x values for i in range(len(x)): arr.append([x[i] - L / 2, 0, 0]) ksi_c = curve(pos=arr) n = len(arr) def update_points(ksi_, y, z): for i in range(n): ksi_.modify(i, y=y[i], z=z[i]) t = 0 while True: rate(30) b_ = b0 * exp(1j * pi**2 * hbar * arange(1, N + 2)**2 / 2 / M / L**2 * t) ksi_ = idst(b_) y = real(ksi_) * 1e-9 z = imag(ksi_) * 1e-9 update_points(ksi_c, y, z) t += h * 5
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(planet_filename, moon_filename) ''' Animation ''' print('Begin animation') dt = 100 i = 0 # Counter for moving the belts while True: vp.rate(500000) # update all objects position; call velocity verlet algorithm for body in object_list: # obtain objects other than the one being called in this iteration other_objects = object_list.copy() other_objects.remove(body) # pass other_objects into motion method as object body.motion(dt, other_objects, 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
#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) cont = cont + 1 if (cont == 100): sphere(radius=1.0,pos=vector(posicaox2[k],posicaoy2[k],0),color=color.red) sphere(radius=1.0,pos=vector(posicaox3[k],posicaoy3[k],0),color=color.blue) cont = 0 rate(N/100)
def render(self, mode, render_step=10): assert isinstance(self._dyn, BallBalancerDynamics ), "Missing dynamics properties for simulation!" # Cheap printing to console if self._step_count % render_step == 0: print( "time step: {:3} | in bounds: {:1} | state: {} | action: {}" .format(self._step_count, self.state_space.contains(self._state), self._state, self._curr_action)) if not self.state_space.contains(self._state): # State is out of bounds np.set_printoptions(precision=3) print("min state : ", self.state_space.low) print("last state: ", self._state) print("max state : ", self.state_space.high) # Render using VPython import vpython as vp vp.rate(30) d_plate = 0.01 # only for animation # Init render objects on first call if self._anim_canvas is None: self._anim_canvas = vp.canvas(width=800, height=600, title="Quanser Ball Balancer") self._anim_ball = vp.sphere( pos=vp.vector(self._state[2], self._state[3], self._dyn.r_ball + d_plate / 2.), radius=self._dyn.r_ball, mass=self._dyn.m_ball, color=vp.color.red, canvas=self._anim_canvas, ) self._anim_plate = vp.box( pos=vp.vector(0, 0, 0), size=vp.vector(self._dyn.l_plate, self._dyn.l_plate, d_plate), color=vp.color.green, canvas=self._anim_canvas, ) # Compute plate orientation a = -self._plate_angs[0] # plate's angle around the y axis (alpha) b = self._plate_angs[1] # plate's angle around the x axis (beta) # Axis runs along the x direction self._anim_plate.axis = vp.vec( vp.cos(a), 0, vp.sin(a), ) * self._dyn.l_plate # Up runs along the y direction (vpython coordinate system is weird) self._anim_plate.up = vp.vec( 0, vp.cos(b), vp.sin(b), ) # Compute ball position x = self._state[2] # ball position along the x axis y = self._state[3] # ball position along the y axis self._anim_ball.pos = vp.vec( x * vp.cos(a), y * vp.cos(b), self._dyn.r_ball + x * vp.sin(a) + y * vp.sin(b) + vp.cos(a) * d_plate / 2., ) # Set caption text self._anim_canvas.caption = f"""
make_trail=True) ball_2 = vp.sphere(pos=initial_position_2, radius=0.5, color=vp.color.green, make_trail=True) wall_center = vp.vector(0., 0., 0.) wall_dimensions = vp.vector(0.25, 10., 10.) wall = vp.box(pos=wall_center, size=wall_dimensions, color=vp.color.red) animation_time_step = 0.01 # seconds rate_of_animation = 1 / animation_time_step time_step = 0.005 stop_time = 1. time = 0. ball_velocity = initial_velocity ball_2_velocity = initial_velocity_2 while time < stop_time: vp.rate(rate_of_animation) if ball.pos.x > wall.pos.x: ball_velocity.x = -ball_velocity.x # reverse ball velocity ball.pos.x += ball_velocity.x * time_step ball.pos.y += ball_velocity.y * time_step ball.pos.z += ball_velocity.z * time_step if ball_2.pos.x > wall.pos.x: ball_2_velocity.x = -ball_2_velocity.x # reverse ball_2 velocity ball_2.pos.x += ball_2_velocity.x * time_step ball_2.pos.y += ball_2_velocity.y * time_step ball_2.pos.z += ball_2_velocity.z * time_step time += time_step
def __init__(self, height=500, width=1000, title='', caption='', grid=True): # Private lists self.__line_styles = [ '', # None '-', # Solid (default) '--', # Dashes ':', # Dotted '-.', # Dash-dot ] self.__marker_styles = [ '+', # Plus 'o', # Circle '*', # Star '.', # Dot 'x', # Cross 's', # Square 'd', # Diamond '^', # Up triangle 'v', # Down triangle '<', # Left triangle '>', # Right triangle 'p', # Pentagon 'h', # Hexagon ] self.__colour_styles = [ 'r', # Red 'g', # Green 'b', # Blue 'y', # Yellow 'c', # Cyan 'm', # Magenta 'k', # Black (default) 'w', # White ] self.__colour_dictionary = { 'r': color.red.value, 'g': color.green.value, 'b': color.blue.value, 'c': color.cyan.value, 'y': color.yellow.value, 'm': color.magenta.value, 'k': color.black.value, 'w': color.white.value } # 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 = True # Keep 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()
scene.width = 1200 # Ajustando a largura da cena scene.height = 1000 # Ajustando a altura da cena scene.camera.pos = vector(2, -1, 2) scene.camera.axis = vector(-2, 1, -2) suporte = box(pos=vector(.0, .05, .0), up=vector(.0, 1., .0), length=2, height=.1, width=2, texture=textures.wood) # Suporte mola = helix(pos=vector(0, 0, 0), axis=vector(*r_vrl), color=color.yellow, radius=.03) # Mola do pendulo bola = sphere(axis=vector(*r_vrl), radius=.1, make_trail=True) # Bola # Constantes C = 1. while t <= b: rate(C / h) mola.axis = vector(*r_vrl) bola.pos = vector(*r_vrl) r_vrl, v_vrl, vpm = passo_vrl(f, r_vrl, v_vrl, vpm, t, h) t += h
), ] bodies = planets + [ star, ] # %% t = 0 dt = 0.001 while True: vp.rate(500) for b in bodies: b.force = vp.vector(0, 0, 0) for b1, b2 in itertools.product(bodies, bodies): if b1 != b2: b1.force += eval_gravitational_force(b1, b2) for b in bodies: b.momentum += b.force * dt b.pos += b.momentum / b.mass * dt t += dt time.sleep(0.1)
def run(self): pos = array(self.pos_list) p = array(self.p_list) m = array(self.m_list) m.shape = (self.ctx.stars, 1 ) # Numeric Python: (1 by Nstars) vs. (Nstars by 1) radius = array(self.r_list) vcm = sum(p) / sum(m) # velocity of center of mass p = p - m * vcm # make total initial momentum equal zero dt = 50.0 pos = pos + (p / m) * (dt / 2.0) # initial half-step num_hits = 0 L = self.ctx.L while True: rate(50) L *= 1.0 + self.ctx.h0 * dt # strength of force to allow for external mass con = 1.0 * self.ctx.G * self.ctx.stars * self.ctx.Msun / L**3 # Compute all forces on all stars r = pos - pos[:, newaxis] # all pairs of star-to-star vectors for i in range(self.ctx.stars): r[i, i] = 1e6 # otherwise the self-forces are infinite rmag = sqrt(add.reduce(r**2, -1)) # star-to-star scalar distances hit = less_equal(rmag, radius + radius[:, newaxis]) - identity( self.ctx.stars) # 1,2 encoded as 1 * stars + 2 hit_list = sort(nonzero(hit.flat)[0]).tolist() F = self.ctx.G * m * m[:, newaxis] * r / rmag[:, :, newaxis]**3 # all force pairs for i in range(self.ctx.stars): F[i, i] = 0 # no self-forces p = p + sum(F, 1) * dt + pos * con * dt * m # Having updated all momenta, now update all positions pos += (p / m) * dt # Expand universe pos *= 1.0 + self.ctx.h0 * dt # Update positions of display objects; add trail for i in range(self.ctx.stars): v = pos[i] self.stars[i].pos = vec(v[0], v[1], v[2]) # If any collisions took place, merge those stars for hit in hit_list: i, j = divmod(hit, self.ctx.stars) # decode star pair if not (self.stars[i].visible or self.stars[j].visible): continue # m[i] is a one-element list, e.g. [6e30] # m[i,0] is an ordinary number, e.g. 6e30 new_pos = (pos[i] * m[i, 0] + pos[j] * m[j, 0]) / (m[i, 0] + m[j, 0]) new_mass = m[i, 0] + m[j, 0] new_p = p[i] + p[j] new_radius = self.ctx.Rsun * ( (new_mass / self.ctx.Msun)**(1.0 / 3.0)) i_set, j_set = i, j if radius[j] > radius[i]: i_set, j_set = j, i self.stars[i_set].radius = new_radius m[i_set, 0] = new_mass pos[i_set] = new_pos p[i_set] = new_p self.stars[j_set].visible = 0 p[j_set] = vec(0, 0, 0) m[j_set, 0] = self.ctx.Msun * 1e-30 # give it a tiny mass num_hits += 1 pos[j_set] = (10.0 * L * num_hits, 0, 0) # put it far away
#initialize the position array: r = np.array([th0, om0], float) # RK4 algorithm for t in tp: thp.append(r[0]) omp.append(r[1]) 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 mp.title('Phasee Portrait of a Pendulum') mp.plot(thp, omp) mp.xlabel(r'Angle $(Rads)$') mp.ylabel(r'Angular Velocity $(\frac{Rads}{s})$') mp.show() # make animation rod = cylinder(pos=vector(0, 0, 0), axis=vector(l * np.cos(th0 - pi / 2), l * np.sin(th0 - pi / 2), 0), radius=l / 40) bob = sphere(pos=vector(l * np.cos(th0 - pi / 2), l * np.sin(th0 - pi / 2), 0), radius=l / 10) for theta in thp: rate(N // 10) rod.axis = vector(l * np.cos(theta - pi / 2), l * np.sin(theta - pi / 2), 0) bob.pos = vector(l * np.cos(theta - pi / 2), l * np.sin(theta - pi / 2), 0)
def main(theta=45.0, omega=0.0, dt=0.001, rod_length=5.0, dampening_coeff=0.3, acceleration_from_gravity=9.8, trail=False, animation_rate=2000, time_limit=None, repeat=True, limits=(0.01, 0.001), labels=True, display_width=1900, display_height=950, plot=False): """ Pendulum demo built for use with VPython. :param theta: (float) Starting angle of pendulum from rest in degrees (default is 45.0). :param omega: (float) Starting angular velocity of the pendulum in degrees/second (default is 0). :param dt: (float) Change in time in seconds; must be very small (default is 0.001). :param rod_length: (float) Length of rod in meters; end of rod to center of bob (default is 5.0). :param dampening_coeff: (float) The damping coefficient; a number between 0 and 1 (default is 0.3). :param acceleration_from_gravity: (float) The acceleration due to gravity on the pendulum in meters/second**2 (default is 9.8). :param trail: (bool) Shows the path of the moving bob (default is False). :param animation_rate: (int) The maximum amount of loop executions per second (default is 2000). :param time_limit: (float) A number that represents an ending time for the pendulum animation (t goes from 0 to time_limit with dt step sizes); if left as None the demo will run until it reaches its limit values (unless repeat is True) (default is None). :param repeat: (bool) If repeat is True and time_limit is None, repeats the demo after the pendulum has reached its limit values (default is True). :param limits: (list) A tuple that when time_limit is None, will use +- the given theta (degrees) and omega (degrees/time) values to determine when to either reset the pendulum or stop (default is (0.01, 0.001)). :param labels: (bool) True if you want to display a box of the input values (default is True). :param display_width: (int) The VPython canvas pixel width. :param display_height: (int) The VPython canvas pixel height. :param plot: (bool) If True, will display a graph of the bob's angle vs. time; can cause performance issues (default is False). """ _make_scene(plot, display_width, display_height) pen = Pendulum(theta=theta, omega=omega, dt=dt, rod_length=rod_length, dampening_coeff=dampening_coeff, acceleration_from_gravity=acceleration_from_gravity, trail=trail) pen.shelf() rod = pen.rod(pen.position) bob = pen.bob(pen.position) if labels: _make_labels(theta, omega, dampening_coeff, acceleration_from_gravity, rod_length) t = 0 if plot: f = _make_plot(pen.theta, display_width, display_height) if time_limit is None: while True: rate(animation_rate) angle = pen.angular_position() vel = pen.angular_velocity() if -limits[0] < angle < limits[0] and -limits[1] < vel < limits[1]: if repeat: pen.theta = math.radians(theta) pen.omega = math.radians(omega) bob.clear_trail() if plot: f.delete() t = 0 else: break rod.axis = pen.position bob.pos = pen.position if plot: f.plot(t, math.degrees(pen.theta)) t += dt else: while t <= time_limit: while t < time_limit: rate(animation_rate) pen.angular_position() pen.angular_velocity() rod.axis = pen.position bob.pos = pen.position if plot: f.plot(t, math.degrees(pen.theta)) t += dt if repeat and t >= time_limit: pen.theta = math.radians(theta) pen.omega = math.radians(omega) bob.clear_trail() if plot: f.delete() t = 0
# plot(tpoints, energy_points) # xlabel('t (s)') # ylabel('energy (J)') # show() # Make animation rod1 = cylinder(pos=vector(0, 0, 0), axis=vector(l * cos(theta1_0 - pi / 2), l * sin(theta1_0 - pi / 2), 0), radius=l / 40) bob1 = sphere(pos=vector(l * cos(theta1_0 - pi / 2), l * sin(theta1_0 - pi / 2), 0), radius=l / 10) rod2 = cylinder(pos=vector(l * cos(theta1_0 - pi / 2), l * sin(theta1_0 - pi / 2), 0), \ axis=vector(l * cos(theta2_0 - pi / 2), l * sin(theta2_0 - pi / 2), 0), radius=l/40) bob2 = sphere(pos=vector(l * cos(theta2_0 - pi / 2), l * sin(theta2_0 - pi / 2), 0), radius=l / 10) for i in range(N): rate(N // 100) vector1 = vector(l * cos(theta1_points[i] - pi / 2), l * sin(theta1_points[i] - pi / 2), 0) vector2 = vector(l * cos(theta2_points[i] - pi / 2), l * sin(theta2_points[i] - pi / 2), 0) rod1.axis = vector1 bob1.pos = vector1 rod2.pos = vector1 rod2.axis = vector2 bob2.pos = vector1 + vector2
color=vp.color.green, make_trail=True, retain=100) r_hat_trail = vp.sphere(pos=vp.vector(Rx[0], Ry[0], Rz[0]), radius=.005, color=vp.color.blue, make_trail=True, retain=100) # Run the Animations with Vpython using a loop # if statement allows the pause button to work vp.sleep(1) i = 0 while i < iterations: if running is True: vp.rate(60) r1 = vp.vector(Px[i], Py[i], Pz[i]) r2 = vp.vector(Qx[i], Qy[i], Qz[i]) r3 = vp.vector(Rx[i], Ry[i], Rz[i]) r1_neg = vp.vector(-Px[i], -Py[i], -Pz[i]) # Updates the vectors p_hat_pos.axis = r1 p_hat_neg.axis = r1_neg q_hat_DE.axis = r2 p_hat.axis = r1 q_hat.axis = r2 r_hat.axis = r3 # Updates the trails p_hat_pos_trail.pos = r1
# Mass m = Msun # Color col = vector(uniform(0.7,1.0),uniform(0.7,1.0), uniform(0.7,1.0)) # Create the star stars = np.append(stars, vpy.sphere(pos=pos, radius=r, color=col)) positions = np.append(positions, pos) masses = np.append(masses, m) velocities = np.append(velocities, vector(0,0,0)) # Main loop while True: vpy.rate(10) # Star to star scalar distances rscalar = positions-positions[:,np.newaxis] for row in range(np.shape(rscalar)[0]): for col in range(np.shape(rscalar)[1]): rscalar[row, col] = math.sqrt(rscalar[row, col].dot(rscalar[row, col])) if (rscalar[row, col] == 0): rscalar[row, col] = 1 # Star to star vectorial distances r = positions-positions[:,np.newaxis] # Star to star forces F = G*masses*masses[:,np.newaxis]/(rscalar**2) # Module for row in range(np.shape(F)[0]):
def main(): box_size = 10 box_thickness = 1 ball_radius = 0.5 # Set the axis of each side to be a perpendicular unit vector pointing into # the box. That'll allow us to handle all the walls in a loop, rather than # spelling them out axes = [ vpython.vector(1, 0, 0), vpython.vector(-1, 0, 0), vpython.vector(0, 1, 0), ] box_sides = [] for axis in axes: side = vpython.box( pos=-0.5 * box_size * axis, axis=axis, height=box_size, width=box_size, ) box_sides.append(side) vpython.arrow( pos=-0.5 * box_size * axis, axis=axis, color=vpython.color.blue, ) # Initial position chosen randomly inside the box x0 = vpython.vector( random.random() * box_size - 0.5 * box_size, random.random() * box_size - 0.5 * box_size, 0, ) # Initial velocity small enough that we should not escape v_max = math.sqrt(-2 * GRAVITY * (0.5 * box_size - x0.y)) v0 = vpython.vector( random.random() * v_max, random.random() * v_max, 0, ) # Initialize the ball. Python also lets us attach an extra attribute, in # this case velocity, to the ball object. ball = vpython.sphere( pos=x0, color=vpython.color.red, radius=ball_radius, ) ball.v = v0 ball.m = 1 # Set up the graph pane and each curve we want in it vpython.graph( title="Ball in a Box", xtitle="Time (s)", ytitle="Energy (J)", fast=False, ) graph_pot = vpython.gcurve(color=vpython.color.blue, width=2, label="Potential Energy") graph_kin = vpython.gcurve(color=vpython.color.red, width=2, label="Kinetic Energy") graph_tot = vpython.gcurve(color=vpython.color.magenta, width=2, label="Total Energy") # Time loop! Handle gravity and collisions t, dt, tmax = 0, 0.001, 10 while t < tmax: t += dt vpython.rate(1 / dt) dvdt = -GRAVITY * vpython.vector(0, -1, 0) ball.v += dvdt * dt ball.pos += ball.v * dt # Check for collisions for side in box_sides: # Vector from the center of the ball to the center of the wall center_to_center = ball.pos - side.pos # Project onto the wall's perpendicular unit vector to get distance distance = center_to_center.dot(side.axis) # If it's a collision, flip the component of the ball's velocity # that's perpendicular to the wall if distance < (ball.radius + 0.5 * box_thickness): dv = -2 * side.axis.dot(ball.v) ball.v += side.axis * dv energy_pot = -ball.m * GRAVITY * ball.pos.y energy_kin = 0.5 * ball.m * ball.v.dot(ball.v) graph_pot.plot(t, energy_pot) graph_kin.plot(t, energy_kin) graph_tot.plot(t, energy_pot + energy_kin) return
omegapoints.append(r[1]) 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 # Plot theta vs t def opt_plot(): plt.grid(True, linestyle=":", color='0.50') plt.minorticks_on() plt.tick_params(axis='both', which='minor', direction='in', top=True, right=True, length=5, width=1, labelsize=15) plt.tick_params(axis='both', which='major', direction='in', top=True, right=True, length=8, width=1, labelsize=15) # plt.plot(tpoints, (np.array(thetapoints, float)*180/np.pi), color='blue') # plt.title(r'$\theta$ vs $t$', family='serif', fontsize=15) # plt.xlabel('t (s)', family='serif', fontsize=15) # plt.ylabel(r'$\theta$ (degrees)', family='serif', fontsize=15) # opt_plot() # plt.show() # Making the animation rod = vp.cylinder(pos=vp.vector(0, 0, 0), axis=vp.vector(l*np.cos(theta_0-np.pi/2), l*np.sin(theta_0-np.pi/2), 0), radius=l/40) bob = vp.sphere(pos=vp.vector(l*np.cos(theta_0-np.pi/2), l*np.sin(theta_0-np.pi/2), 0), radius=l/10) for theta in thetapoints: vp.rate(N // 10) rod.axis = vp.vector(l*np.cos(theta-np.pi/2), l*np.sin(theta-np.pi/2), 0) bob.pos = vp.vector(l*np.cos(theta-np.pi/2), l*np.sin(theta-np.pi/2), 0)
g = 9.8 s = sphere() s.pos = vector(-7, 1, 0) s.velocity = vector(5, 19.2, 0) s.accel = vector(0, -g, 0) s.mass = 2.0 t = 0 while t < 10.0: # compute and graph energy kinetic_energy = 0.5 * s.mass * dot(s.velocity, s.velocity) potential_energy = s.mass * 9.8 * dot(s.pos + vector(0, ymax / 2, 0), vector(0, 1, 0)) kinetic.plot(pos=(t, kinetic_energy)) potential.plot(pos=(t, potential_energy)) energy.plot(pos=(t, kinetic_energy + potential_energy)) # update time and position t += dt s.pos += s.velocity * dt + 0.5 * s.accel * dt**2 s.velocity += s.accel * dt rate(1 / dt) print(s.pos) # collisions if not -xmax / 2 < s.pos.x < xmax / 2: s.velocity.x = -s.velocity.x if not -ymax / 2 < s.pos.y < ymax / 2: s.velocity.y = -s.velocity.y
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 if part in ['a']: figure(1) clf() title("theta(t)") plot(tpoints, thetapoints) xlabel("t") ylabel("theta") if part in ['b']: scene = canvas(width=500, height=500, center=vector(0, 0, 0), background=color.black) # sphere with radius of 5 cm bob = sphere(pos=vector(l, 0, 0), radius=0.01, color=color.red) it = 0 for t in arange(0, 1e6, 0.1): angle = thetapoints[it] - pi / 2 rate(60) # steps per second bob.pos = vector(l * cos(angle), l * sin(angle), 0) it = it + 1
def rate(framerate: int) -> None: """Alias for vpython.rate(framerate). Basically sleeps 1/framerate""" vpython.rate(framerate)
from vpython import sphere,rate, vector from math import cos,sin,pi from numpy import arange s = sphere(pos=vector(1, 0, 0), radius=0.1) for theta in arange(0, 10*pi, .1): rate(100) x = cos(theta) y = sin(theta) s.pos = vector(x, y, 0)
import vpython as vp from robot_imu import RobotImu, ImuFusion from delta_timer import DeltaTimer import imu_settings imu = RobotImu(gyro_offsets=imu_settings.gyro_offsets) fusion = ImuFusion(imu) vp.graph(xmin=0, xmax=60, scroll=True) graph_pitch = vp.gcurve(color=vp.color.red) graph_roll = vp.gcurve(color=vp.color.green) timer = DeltaTimer() while True: vp.rate(100) dt, elapsed = timer.update() fusion.update(dt) graph_pitch.plot(elapsed, fusion.pitch) graph_roll.plot(elapsed, fusion.roll)
# Make a binary system STARS = celest.create_binary_system(bounds=bounds) # Data for running the simulation and plotting years = 0 times = list() num_asteroids = list() avg_distance_from_star_A = list() avg_distance_from_star_B = list() average_asteroid_mass = list() # Animate the simulation while years <= 20 and len(PLANETESIMALS) > 0: mov.update_positions(PLANETESIMALS, STARS) mov.bounding_box(PLANETESIMALS, bounds) mov.bounding_box(STARS, bounds) vp.rate(30) # Update the logged information times.append(years) avg_distance_from_star_A.append( ut.average_distance_to_object(PLANETESIMALS, STARS[0])) avg_distance_from_star_B.append( ut.average_distance_to_object(PLANETESIMALS, STARS[1])) num_asteroids.append(len(PLANETESIMALS)) average_asteroid_mass.append(ut.average_asteroid_mass(PLANETESIMALS)) # Update time counter years += dt / YEAR # Now plot the information collected plt.plot(times, num_asteroids) plt.xlabel("Time (years)") plt.ylabel("Number of planetesimals")
T = RK4(T, S, t) #Calculando a posição e velocidade de Jupiter no próximo passo. Gm = Gm1 S = array([Tx[n], Tvx[n], Ty[n], Tvy[n]]) J = RK4(J, S, t) n += 1 t += h #Evoluindo o tempo t atual #plot(xT,yT) #Plotando a orbita da Terra #plot(xJ,yJ) #Plotando a orbita de Jupiter #show() scene = canvas(width=900, height=500, center=vector(0, 0, 0), background=color.black) #T1 = sphere(pos=vector(0,0,0),radius=e*6.3781*10**6,color = color.blue) #Terra #J1 = sphere(pos=vector(0,0,0),radius=e*7.1492*10**7,color = color.orange) #Jupiter #S1 = sphere(pos=vector(0,0,0),radius=e*6.96340*10**8,color = color.white) #Sol T1 = sphere(pos=vector(0, 0, 0), radius=10**10, color=color.blue) #Terra J1 = sphere(pos=vector(0, 0, 0), radius=10**10, color=color.orange) #Jupiter S1 = sphere(pos=vector(0, 0, 0), radius=10**10, color=color.white) #Sol for i in range(n): rate(700) T1.pos = vector(Tx[i], Ty[i], 0) J1.pos = vector(Jx[i], Jy[i], 0)
import vpython as vp import numpy as np from math import pi, cos, sin # L = 5 # for i in range(-L,L+1): # for j in range(-L,L+1): # for k in range(-L,L+1): # if ((i+j+k) % 2 == 0 ): # vp.sphere(pos=vp.vector(i,j,k), radius = 0.5, color = vp.vector(1,0,0)) # else: # vp.sphere(pos=vp.vector(i,j,k), radius = 0.2, color = vp.vector(0,0,1)) def sphere_position(t): x = 10 * (cos(10 + t)) y = 10 * (sin(10 + t)) return vp.vector(x, y, 0) t = 0 esfera = vp.sphere(pos=sphere_position(t), radius=1, color=vp.vector(1, 0, 0)) fio = vp.cylinder(pos=sphere_position(t), axis=vp.vector(0, 0, 0), radius=1) while t <= 20 * pi: vp.rate(10) esfera.pos = sphere_position(t) fio.pos = sphere_position(t) t = t + 0.1 * pi
vp.label(pos=vp.vector(a1 * 4, 0, rpv_offset), text='0') vp.label(pos=vp.vector(0, a1 * 4, rpv_offset), text='90') vp.label(pos=vp.vector(-a1 * 4, 0, rpv_offset), text='180') vp.label(pos=vp.vector(0, -a1 * 4, rpv_offset), text='270') vp.local_light(pos=vp.vector(0, 0, -10), color=vp.color.gray(0.2)) scan_pts = calc_scan_pts(scan_length, scan_index_angle) num_pts = int(size(scan_pts) / len(scan_pts)) # vp.scene.camera.pos = vp.vector(scan_pts[0][num_pts - 1], scan_pts[1][num_pts - 1], scan_pts[2][num_pts - 1]) # Loop through scan points, assume configuration 1 first config = 1 for j in range(num_pts): # Set the loop rate to be equivalent to the desired scan velocity. if sim_true_scan_speed: vp.rate(scan_vel / scan_res) j2, j3, j4, pvt, ee = c_jpos(scan_pts[:, j], config) t1, t2, t3, t4 = c_angles(scan_pts[:, j], config) # Check if end effector is in the scan location if calc_pos_err_check(ee, scan_pts[:, j]): config = ~config j2, j3, j4, pvt, ee = c_jpos(scan_pts[:, j], 1) t1, t2, t3, t4 = c_angles(scan_pts[:, j], 1) if calc_pos_err_check(ee, scan_pts[:, j]): # If problems, print the joint set and leave a red curve of the manipulator print_joint_set(t1, t2, t3, t4) vp.curve( pos=[(0, 0, 0), (j2[0], j2[1], j2[2]), (j3[0], j3[1], j3[2]), (j4[0], j4[1], j4[2]),
def initRender(self): self.canvas = canvas(width=1200, height=900, title='Car-3D') # self.canvas = canvas(width=1660, height=1010, title='Car-3D') ground_y = 0.17 thk = 0.1 ground_width = 10.0 wallB = box(canvas=self.canvas, pos=vector(0, -ground_y, 0), size=vector(ground_width, thk, ground_width), color=color.blue) # vector:(front/rear,z,l/r) car_w, car_l, car_h = 0.132, 0.26 / 0.6, 0.2 wheel_r, wheel_h = 0.095, 0.035 chassis = box(canvas=self.canvas, pos=vector(0, wheel_r + 0.05, 0), size=vector(car_l, car_h, car_w), color=color.green) wheel_r / 2 + thk wheel1 = cylinder(pos=vector(0.6 * car_l / 2.0, wheel_r, car_w / 2.0), axis=vector(0, 0, wheel_h), radius=wheel_r, color=color.blue) wheel2 = cylinder(pos=vector(0.6 * car_l / 2.0, wheel_r, -car_w / 2.0 - wheel_h), axis=vector(0, 0, wheel_h), radius=wheel_r, color=color.blue) wheel3 = cylinder(pos=vector(-0.6 * car_l / 2.0, wheel_r, car_w / 2.0), axis=vector(0, 0, wheel_h), radius=wheel_r, color=color.blue) wheel4 = cylinder(pos=vector(-0.6 * car_l / 2.0, wheel_r, -car_w / 2.0 - wheel_h), axis=vector(0, 0, wheel_h), radius=wheel_r, color=color.blue) self.car = compound([chassis, wheel3, wheel4], pos=vector(self.x_pos, self.y_pos, self.z_pos), make_trail=True, retain=300) self.frontwheel = compound([wheel1, wheel2], pos=vector(self.x_pos, self.y_pos, self.z_pos)) self.car.axis = vector(1, 0, 0) self.car.up = vector(0, 1, 0) self.car.mass = self.car_mass self.pointer = arrow(pos=self.car.pos, axis=self.car.axis, shaftwidth=0.01) origin = sphere(pos=vector(0, 0, 0), radius=0.02) self.x_axis = arrow(pos=vector(0, 0, 0), axis=vector(0, 0, 3), shaftwidth=0.3, color=color.red) self.y_axis = arrow(pos=vector(0, 0, 0), axis=vector(3, 0, 0), shaftwidth=0.3, color=color.blue) self.z_axis = arrow(pos=vector(0, 0, 0), axis=vector(0, 3, 0), shaftwidth=0.3, color=color.green) rate(FPS)
pos=vp.vector(-60, -8, 0), text="Velocity" + str(setpoint_plot[i] * rad2deg), xoffset=0, zoffset=0, yoffset=0, space=30, height=30, border=0, font='sans', box=False, line=False, align="left") i = 0 for i in range(len(theta_3D) - 2): vp.rate(1000 / slow_mo) #60 FPS # How much to move each time-step , X and Z are the rocket's axes, not the world's delta_pos_X = (Position_3D[i + 1][0] - Position_3D[i][0]) delta_pos_Z = (Position_3D[i + 1][1] - Position_3D[i][1]) # Moving the rocket rocket.pos.y += delta_pos_X rocket.pos.x += delta_pos_Z # Creates a cg and cp vector with reference to the origin of the 3D rocket (not the math model rocket) xcg_radius = loc2glob((L - xcg), 0, theta_3D[i]) xa_radius = loc2glob( xa_3D[i + 1] - xa_3D[i], 0, theta_3D[i] ) #Delta xa_radius, this is then integrated when you move the Aerodynamic Force arrow
np.random.uniform(bounds[1][0], bounds[1][1]), np.random.uniform(bounds[2][0], bounds[2][1])), color=v.color.red, radius=0.03) for x in range(tot_sphere)] # nb_case_possible = h_cube*l_cube*w_cube # dimension = 3 # surface_stator = stator_number * ((stator_r/10)**2 *np.pi) # surf_cube = a**2 # surf_stator_cube = surface_stator/surf_cube # nombre de cube correspondant a la surface total des stators # proba_in_stator = (1/(2*dimension))*(surf_stator_cube/nb_case_possible) # proba pour une bille de passer dans un stator N_dt = [] list_dt = [] while tot_time < 1500000: # v.rate(1000000) for sphere in list_sphere: choose_dir = random.choice(["x", "y", "z"]) if choose_dir == "x": x = random.choice([-a, a]) dr = v.vector(x, 0, 0) elif choose_dir == "y": y = random.choice([-a, a]) dr = v.vector(0, y, 0) else: z = random.choice([-a, a]) dr = v.vector(0, 0, z)
''' Created on 8 juil. 2012 @author: Laurent ''' from vpython import box, sphere, vector, color, rate floor = box(pos=vector(0, 0, 0), length=4, height=0.5, width=4, color=color.blue) ball = sphere(pos=vector(0, 4, 0), radius=1, color=color.red) ball.velocity = vector(0, -1, 0) dt = 0.01 while 1: rate(100) ball.pos = ball.pos + ball.velocity * dt if ball.pos.y < ball.radius: ball.velocity.y = abs(ball.velocity.y) else: ball.velocity.y = ball.velocity.y - 9.8 * dt
w = sqrt((q / m) * k) # omega f = w / (2 * pi) dt = 1 / f / kappa I = zeros(N_t) particle = sphere(pos=r, radius=0.5e-3, color=color.green, make_trail=True, retain=100) v -= dt * (q / m) * E(particle.pos) / 2 for i in range(N_t): v += dt * (q / m) * E(particle.pos) particle.pos += dt * v I[i] = v.z / v_phi rate(50) # spectral analysis I_spec = fft(I) m = zeros(N_t) for i in range(1, N_t // 2): w = 2 * pi * i / (N_t * dt) m[i] = k * q / w**2 # plot plt.figure("Test Ion: Carbon") plt.xlabel("m / u") plt.ylabel("normalized density") plt.xlim(0, 50)