示例#1
0
 def sCaidalibre(self):
     self.alturaCL=self.alturaCL.get()
     self.velocidadX=self.velocidadX.get()
     try:
         self.alturaCL=float(self.alturaCL)
         self.velocidadX=float(self.velocidadX)
     except:
         self.alerta()
     gdpos=vgraph.gdisplay(x=600,y=0,xtitle='Tiempo',ytitle='Posicion(y)')
     plotpos=vgraph.gcurve(gdisplay=gdpos,color=vs.color.red)
     gdvel=vgraph.gdisplay(x=600,y=600,xtitle='Velocidad',ytitle='Tiempo')
     plotvel=vgraph.gcurve(gdisplay=gdvel,color=vs.color.blue)
     gdacl=vgraph.gdisplay(x=0,y=900,xtitle='Aceleracion',ytitle='Tiempo')
     plotacl=vgraph.gcurve(gdisplay=gdacl,color=vs.color.blue)
     suelo=vs.box(pos=(0,-5,0),length=30,height=0.1,width=1,color=vs.color.blue)
     esferaC=vs.sphere(pos=(0,self.alturaCL,-2),radius=1,color=vs.color.red)
     T=np.sqrt(2*(self.alturaCL+5)/9.8)
     t=0
     while t<T:
         esferaC.pos=(self.velocidadX*t,self.alturaCL-9.8*t**2/2,-2)
         plotpos.plot(pos=(t,self.alturaCL-9.8*t**2/2))
         plotvel.plot(pos=(t,-9.8*t))
         plotacl.plot(pos=(t,-9.8))
         t+=0.001
         vs.rate(100)
def main(n):
	pedestrians = generate_pedestrians(n)
	aux = [False] * n * 4
	minimizers = []
	done = False
	i = 0

	draw(pedestrians)
	for i, p in enumerate(pedestrians):
		start, end, img = p
		control = map(lambda p: p[0], pedestrians[:i] + pedestrians[i + 1:])
		minimizers.append( (minimize(start, end, control), control) )

	while not done:
		for i, p in enumerate(pedestrians):
			try:
				rate(WIDTH / 5)
				pedestrians[i] = (minimizers[i][0].next(), p[1], p[2])
				draw(pedestrians)
				for j, m in enumerate(minimizers):
					minimizer, control = m

					if j > i:
						control[i] = pedestrians[i][0]

					elif j < i:
						control[-i] = pedestrians[i][0]


			except StopIteration:
				aux[i] = True
				done = reduce(lambda x, y: x and y, aux)
示例#3
0
def calculate(x, y, z, vx, vy, vz, dt, m, g, B2, S0, omega):
    """ Calculate the trajectory of a baseball including air resistance and spin by
repeatedly calling the do_time_step function.  Also draw the trajectory using visual python. """
    t = 0.0
    # Establish lists with initial position and velocity components and time.
    x_list = [x]
    y_list = [y]
    z_list = [z]
    vx_list = [vx]
    vy_list = [vy]
    vz_list = [vz]
    t_list = [t]

    # Set up visual elements.
    mound = visual.box(pos=(0,0,0), length=0.1, width=0.5, height=0.03, color=visual.color.white)
    plate = visual.box(pos=(18,0,0), length=0.5, width=0.5, height=0.03, color=visual.color.white)
    ball = visual.sphere(pos=(x,y,z), radius=0.05, color=visual.color.white)
    ball.trail = visual.curve(color=ball.color)

    while y >= 0.0:
        visual.rate(100) # Limit to no more than 100 iterations per second.
        t, x, y, z, vx, vy, vz = do_time_step(t, dt, x, y, z, vx, vy, vz, m, B2, g, S0, omega)
        x_list.append(x)
        y_list.append(y)
        z_list.append(z)
        vx_list.append(vx)
        vy_list.append(vy)
        vz_list.append(vz)
        t_list.append(t)
        ball.pos = (x,y,z)
        ball.trail.append(pos=ball.pos)

    return t_list, x_list, y_list, z_list, vx_list, vy_list, vz_list
示例#4
0
def PlotSphereEvolution3(f):
  data = json.loads(open(f, "r").read())

  center = (
    (data["SystemSize"][1][0]+data["SystemSize"][0][0])*0.5,
    (data["SystemSize"][1][1]+data["SystemSize"][0][1])*0.5,
    (data["SystemSize"][1][2]+data["SystemSize"][0][2])*0.5
  )

  scene = vs.display(title='3D representation',
    x=0, y=0, width=1920, height=1080,
    center=center,background=(0,0,0)
  )

  vs.box(pos=center,
  length=data["SystemSize"][1][0]-data["SystemSize"][0][0],
  height=data["SystemSize"][1][1]-data["SystemSize"][0][1],
  width= data["SystemSize"][1][2]-data["SystemSize"][0][2],
  opacity=0.2,
  color=vs.color.red)

  spheres = [vs.sphere(radius=data["SphereSize"],pos=(data["Data"][0][0][i], data["Data"][1][0][i], data["Data"][2][0][i])) for i in range(data["SpheresNumber"])]

  nt = 0
  while True:
    vs.rate(60)
    for i in range(data["SpheresNumber"]):
      spheres[i].pos = (data["Data"][0][nt][i], data["Data"][1][nt][i], data["Data"][2][nt][i])
    if nt + 1 >= data["SavedSteps"]:
      nt = 0
    else:
      nt += 1
示例#5
0
    def prompt(self, initial=''):
        """\
        Display a prompt and process the command entered by the user.

        @return: The command string to be processed by the parent object.
        @rtype: C{str}
        """
        self.userspin = False
        self.message(initial + ' ')
        cmd = ''
        process_cmd = False
        while True:
            visual.rate(VISUAL_SETTINGS['rate'] * 2)
            if self.kb.keys:
                k = self.kb.getkey()
                if k == '\n':
                    process_cmd = True
                    self.message()
                    break
                elif k == 'backspace':
                    if len(cmd) > 0:
                        cmd = cmd[:-1]
                    else:
                        self.message()
                        break
                elif k.isalnum() or k in " -_(),.[]+*%=|&:<>'~/\\":
                    cmd += k
            self.message(initial + ' ' + cmd)
        self.userspin = True
        return cmd if process_cmd else None
示例#6
0
def PlotSpheres3(f):
  data = json.loads(open(f, "r").read())

  scene = vs.display(title='3D representation',
    x=0, y=0, width=1920, height=1080,
    autocenter=True,background=(0,0,0))

  vs.box(pos=(
    (data["SystemSize"][1][0]+data["SystemSize"][0][0])*0.5,
    (data["SystemSize"][1][1]+data["SystemSize"][0][1])*0.5,
    (data["SystemSize"][1][2]+data["SystemSize"][0][2])*0.5
  ),
  length=data["SystemSize"][1][0]-data["SystemSize"][0][0],
  height=data["SystemSize"][1][1]-data["SystemSize"][0][1],
  width= data["SystemSize"][1][2]-data["SystemSize"][0][2],
  opacity=0.2,
  color=vs.color.red)

  spheres = [vs.sphere(radius=data["SphereSize"],pos=(data["Data"][0][i], data["Data"][1][i], data["Data"][2][i])) for i in range(data["SpheresNumber"])]

  vs.arrow(pos=data["SystemSize"][0], axis=(1,0,0), shaftwidth=0.1, color=vs.color.red)
  vs.arrow(pos=data["SystemSize"][0], axis=(0,1,0), shaftwidth=0.1, color=vs.color.green)
  vs.arrow(pos=data["SystemSize"][0], axis=(0,0,1), shaftwidth=0.1, color=vs.color.blue)

  while True:
    vs.rate(60)
示例#7
0
def Ch3_Prob5(time):
	base = 57.9#base for distance from the sun. (x = 1 means 57.9 km )
	rad_base = 10*2440#base for the radius of the planets size of each
	#Per_base = 88# base for the period
	
	sun = sphere(pos = [0,0,0], radius = .5)
	mercu = sphere(pos = [(57.90/base), 0, 0], radius = (2440.0/rad_base))
	venus = sphere(pos = [(108.2/base), 0, 0], radius = (6052.0/rad_base))
	earth = sphere(pos = [(149.6/base), 0, 0], radius = (6371.0/rad_base))
	marss = sphere(pos = [(227.6/base), 0, 0], radius = (3386.0/rad_base))
	
	#frequencies
	Fmerc = 2*pi/88
	Fvenu = 2*pi/224.7
	Feart = 2*pi/365.3
	Fmars = 2*pi/687.0
	
	#colors
	sun.color = color.yellow
	mercu.color = color.gray(0.5)
	earth.color = color.blue
	marss.color = color.red
	
	for t in arange(0,time,0.01):
		#print t
		rate(100)
		mercu.pos = [(57.90/base)*cos(Fmerc*t), (57.90/base)*sin(Fmerc*t), 0]
		venus.pos = [(108.2/base)*cos(Fvenu*t), (108.2/base)*sin(Fvenu*t), 0]
		earth.pos = [(149.6/base)*cos(Feart*t), (149.6/base)*sin(Feart*t), 0]
		marss.pos = [(227.6/base)*cos(Fmars*t), (227.6/base)*sin(Fmars*t), 0]
	return 'done'
示例#8
0
    def run(self):
        pos = None
        scene.forward = (0., 0., -1.)
        scene.userspin = False
        scene.autoscale = False
        while not self.stop.isSet():
            rate(self.fps)

            if scene.mouse.events:
                mouse = scene.mouse.getevent()
                if mouse.drag:
                    pos = mouse.pos
                    scene.cursor.visible = False
                elif mouse.release:
                    scene.cursor.visible = True
                    pos = None
            if pos:
                new = scene.mouse.pos
                if new != pos:
                    center = scene.center + mouse.pos - new
                    center.x = bound(center.x, -SEMICIRCLE, SEMICIRCLE)
                    center.y = bound(center.y, -RIGHT_ANGLE, RIGHT_ANGLE)
                    scene.center = center
                    pos = new

        #reinitialize the thread so that it may be called again
        threading.Thread.__init__(self)
示例#9
0
    def prompt(self, initial=""):
        """\
        Display a prompt and process the command entered by the user.

        @return: The command string to be processed by the parent object.
        @rtype: C{str}
        """
        self.userspin = False
        self.message(initial + " ")
        cmd = ""
        process_cmd = False
        while True:
            visual.rate(VISUAL_SETTINGS["rate"] * 2)
            if self.kb.keys:
                k = self.kb.getkey()
                if k == "\n":
                    process_cmd = True
                    self.message()
                    break
                elif k == "backspace":
                    if len(cmd) > 0:
                        cmd = cmd[:-1]
                    else:
                        self.message()
                        break
                elif k.isalnum() or k in " -_(),.[]+*%=|&:<>'~/\\":
                    cmd += k
            self.message(initial + " " + cmd)
        self.userspin = True
        return cmd if process_cmd else None
示例#10
0
def go():
    r = np.array([1.017, 0.0])  # initial x,y position for earth
    v = np.array([0.0, 6.179])  # initial vx, vy

    # draw the scene, planet earth/path, sun/sunlight
    scene = vp.display(
        title='Planetary motion',  # scene start 
        background=(.2, .5, 1),
        forward=(0, 2, -1))
    planet = vp.sphere(pos=r,
                       radius=0.1,
                       make_trail=True,
                       material=vp.materials.earth,
                       up=(0, 0, 1))
    sun = vp.sphere(pos=(0, 0),
                    radius=0.2,
                    color=vp.color.yellow,
                    material=vp.materials.emissive)
    sunlight = vp.local_light(pos=(0, 0), color=vp.color.yellow)  #scn end

    t, h = 0.0, 0.001
    while True:
        vp.rate(200)  # limit animation speed
        r, v = ode.leapfrog(earth, r, v, t, h)  # integrate
        planet.pos = r  # move planet
        if (scene.kb.keys): scene.kb.getkey(), scene.kb.getkey()  #pause
示例#11
0
    def run(self):
        scene.userspin = True
        scene.autoscale = True
        scene.center = 0, 0, 0

        dragging = False

        lastTime = time.clock()
        elapsedTime = 0.

        while not self.stop.isSet():
            rate(self.fps)

            newTime = time.clock()
            elapsedTime = newTime - lastTime
            lastTime = newTime

            if scene.mouse.events:
                mouse = scene.mouse.getevent()
                if mouse.press:
                    dragging = True
                elif mouse.release:
                    dragging = False

            if not dragging and self.rpm:
                increment = CIRCLE * self.rpm / SEC_IN_MIN * elapsedTime
                scene.forward = rotate(scene.forward,
                                       increment,
                                       axis=(0., -1., 0.))

        #reinitialize the thread so that it may be called again
        threading.Thread.__init__(self)
示例#12
0
def restricted_3body(y):            # y = [r, v] expected
    testbody = set_scene(y[0])
    t, h = 0.0, 0.001
    while True:
        vp.rate(2000)
        y = ode.RK4(r3body, y, t, h)
        testbody.pos = y[0]
示例#13
0
def golf_ball_calc(x,y,z,vx,vy,vz,dt,m,g,B2,S0,w,w_vector):
    t = 0.0
    x_list = [x]
    y_list = [y]
    z_list = [z]
    vx_list = [vx]
    vy_list = [vy]
    vz_list = [vz]
    t_list = [t]
    v_vector = visual.vector(vx,vy,vz)

    tee = visual.box(pos=(0,0,0), length=0.05, width=0.05, height=0.5,color=visual.color.white)
    ball = visual.sphere(pos=(x,y,z), radius = 0.25, color = visual.color.white)
    ball.trail = visual.curve(color = visual.color.red)

    while y > 0.0:
        visual.rate(100)
        t,x,y,z,vx,vy,vz = golfball_step(t,x,y,z,vx,vy,vz,m,g,B2,S0,w,dt,w_vector,v_vector)
        x_list.append(x)
        y_list.append(y)
        z_list.append(z)
        vx_list.append(vx)
        vy_list.append(vy)
        vz_list.append(vz)
        t_list.append(t)
        v_vector = visual.vector(vx,vy,vz)
        ball.pos = (x,y,z)
        ball.trail.append(pos=ball.pos)

    return t_list,x_list,y_list,z_list,vx_list,vy_list,vz_list
示例#14
0
 def sResorte(self):
     self.kR=self.kR.get()
     self.masaR=self.masaR.get()
     try:
         self.kR=float(self.kR)
         self.masaR=float(self.masaR)
     except:
         self.alerta()
     gdpos=vgraph.gdisplay(x=600,y=0,xtitle='Tiempo',ytitle='Posicion')
     plotpos=vgraph.gcurve(gdisplay=gdpos,color=vs.color.red)
     gdvel=vgraph.gdisplay(x=600,y=600,xtitle='Velocidad',ytitle='Tiempo')
     plotvel=vgraph.gcurve(gdisplay=gdvel,color=vs.color.blue)
     gdacl=vgraph.gdisplay(x=0,y=900,xtitle='Aceleracion',ytitle='Tiempo')
     plotacl=vgraph.gcurve(gdisplay=gdacl,color=vs.color.green)
     resorte=vs.helix(pos=(0,5,0),axis=(0,0,-1),radius=0.5,color=vs.color.red)
     resfera=vs.sphere(pos=(0,0,0),radius=0.7,color=vs.color.blue)
     t=0
     while t<=100:
         resorte.axis=(0,-5+3*np.cos(np.sqrt(self.kR/self.masaR)*t),-1)
         resfera.pos=(0,3*np.cos(np.sqrt(self.kR/self.masaR)*t),0)
         plotpos.plot(pos=(t,3*np.cos(np.sqrt(self.kR/self.masaR)*t)))
         plotvel.plot(pos=(t,-3*np.sqrt(self.kR/self.masaR)*np.sin(np.sqrt(self.kR/self.masaR)*t)))
         plotacl.plot(pos=(t,-3*(self.kR/self.masaR)*np.cos(np.sqrt(self.kR/self.masaR)*t)))
         t+=0.01
         vs.rate(100)
示例#15
0
 def run(self):
     '''
     Run the simulation with racers that had been previously added to the world
     by add_racer method.
     '''
     # create the scene with the plane at the top
     visual.scene.center = visual.vector(0,-25,0)
     visual.box(pos=(0,0,0), size=(12,0.2,12), color=visual.color.green)
     # create the visual objects that represent the racers (balls)
     balls = [ visual.sphere(pos=(index,0,0), radius=0.5) for index in xrange(len(self.racers))]
     for ball, racer in zip(balls, self.racers):
         color = visual.color.blue
         try:
             # try to set the color given by a string
             color = getattr(visual.color, racer.color)
         except AttributeError:
             pass
         ball.trail  = visual.curve(color=color)
     while not reduce(lambda x, y: x and y, [racer.result for racer in self.racers]):
         # slow down the looping - allow only self.time_calibration
         # number of loop entries for a second
         visual.rate(self.time_calibration)
         # move the racers
         for racer in self.racers:
             self.__move_racer(racer) 
             
         for ball, racer in zip(balls, self.racers):
             ball.pos.y = -racer.positions[-1][1]
             ball.pos.x = racer.positions[-1][0]
             ball.trail.append(pos=ball.pos)
             
         self.current_time += self.interval
         self.timeline.append(self.current_time)
示例#16
0
def restricted_3body(y):  # y = [r, v] expected
    testbody = set_scene(y[0])
    t, h = 0.0, 0.001
    while True:
        vp.rate(2000)
        y = ode.RK4(r3body, y, t, h)
        testbody.pos = y[0]
示例#17
0
def Ch3_Exa3():
	s = sphere(pos=[1,0,0],radius=0.1)
	for theta in arange(0,10*pi,0.1):
		rate(1)
		x= cos(theta)
		y = sin (theta)
		s.pos = [x,y,0]
示例#18
0
 def solve_one(from_rod,to_rod):
     moves = calc_hanoi_sequence(num_of_disks,from_rod,to_rod)
     visual.rate(1.0)
     for move in moves:
         winsound.Beep(880,50)
         g.animate_disk_move(disk=move.disk_to_move,to_rod=move.to_rod,to_z_order=state.num_of_disks_per_rod[move.to_rod])
         state.move_disk_to_rod(disk=move.disk_to_move,to_rod=move.to_rod)
示例#19
0
def _close_final(): # There is a window, or an activated display
    global _do_loop
    if _do_loop:
        _do_loop = False # make sure we don't trigger this twice
        while True: # at end of user program, wait for user to close the program
            rate(1000)
            _Interact()
    _wx.Exit()
示例#20
0
 def animate_motion_to_pos(self,shape,new_pos):
     pos0 = shape.pos
     pos1 = new_pos
     num_steps = 10
     for i in xrange(num_steps):
         visual.rate(40)
         x = (i-1)*1.0/(num_steps-1)
         shape.pos = tuple([pos0[i]*(1-x) + pos1[i]*x for i in range(3)])
示例#21
0
文件: multibody.py 项目: xerebus/ph22
    def vs_run(self, dt, tx):
        '''Continuously evolve and update the visual simulation
        with timestep dt and visual speed tx relative to real-time.'''

        while True:
            self.evolve(dt)
            vs.rate(tx / dt)
            self.vs_update()
示例#22
0
 def UpdateVisuals():
     sim.window.center = sim.pos
     if FPV:
         sim.window.forward = copy(sim.CS.matrix[:, 0])
         sim.window.up = -copy(sim.CS.matrix[:,
                                             2])  #copy(sim.CS.matrix[:,1])
     from visual import rate
     rate(MaxFPS)
示例#23
0
文件: main.py 项目: nkhuyu/htc2015
 def get_next_mouseclick_coords(self):
   visual.scene.mouse.events = 0
   while True:
     visual.rate(30)
     if visual.scene.mouse.clicked:
       pick =  visual.scene.mouse.getclick().pick
       if pick.__class__ == visual.box:
         return pick.board_pos
示例#24
0
def main():
    if len(argv) < 3:
        raise Exception('>>> ERROR! Please supply values for black hole mass [>= 1.0] and spin [0.0 - 1.0] <<<')
    m = float(argv[1])
    a = float(argv[2])
    horizon = m * (1.0 + sqrt(1.0 - a * a))
    cauchy = m * (1.0 - sqrt(1.0 - a * a))
    #  set up the scene
    scene.center = (0.0, 0.0, 0.0)
    scene.width = scene.height = 1024
    scene.range = (20.0, 20.0, 20.0)
    inner = 2.0 * sqrt(cauchy**2 + a**2)
    ellipsoid(pos = scene.center, length = inner, height = inner, width = 2.0 * cauchy, color = color.blue, opacity = 0.4)  # Inner Horizon
    outer = 2.0 * sqrt(horizon**2 + a**2)
    ellipsoid(pos = scene.center, length = outer, height = outer, width = 2.0 * horizon, color = color.blue, opacity = 0.3)  # Outer Horizon
    ergo = 2.0 * sqrt(4.0 + a**2)
    ellipsoid(pos = scene.center, length = ergo, height = ergo, width = 2.0 * horizon, color = color.gray(0.7), opacity = 0.2)  # Ergosphere
    if fabs(a) > 0.0:
        ring(pos=scene.center, axis=(0, 0, 1), radius = a, color = color.white, thickness=0.01)  # Singularity
    else:
        sphere(pos=scene.center, radius = 0.05, color = color.white)  # Singularity
    ring(pos=scene.center, axis=(0, 0, 1), radius = sqrt(isco(a)**2 + a**2), color = color.magenta, thickness=0.01)  # ISCO
    curve(pos=[(0.0, 0.0, -15.0), (0.0, 0.0, 15.0)], color = color.gray(0.7))
    #cone(pos=(0,0,12), axis=(0,0,-12), radius=12.0 * tan(0.15 * pi), opacity=0.2)
    #cone(pos=(0,0,-12), axis=(0,0,12), radius=12.0 * tan(0.15 * pi), opacity=0.2)
    #sphere(pos=(0,0,0), radius=3.0, opacity=0.2)
    #sphere(pos=(0,0,0), radius=12.0, opacity=0.1)
    # animate!
    ball = sphere()  # Particle
    counter = 0
    dataLine = stdin.readline()
    while dataLine:  # build raw data arrays
        rate(60)
        if counter % 1000 == 0:
            ball.visible = False
            ball = sphere(radius = 0.2)  # Particle
            ball.trail = curve(size = 1)  #  trail
        data = loads(dataLine)
        e = float(data['v4e'])
        if e < -120.0:
            ball.color = color.green
        elif e < -90.0:
            ball.color = color.cyan
        elif e < -60.0:
            ball.color = color.yellow
        elif e < -30.0:
            ball.color = color.orange
        else:
            ball.color = color.red
        r = float(data['r'])
        th = float(data['th'])
        ph = float(data['ph'])
        ra = sqrt(r**2 + a**2)
        sth = sin(th)
        ball.pos = (ra * sth * cos(ph), ra * sth * sin(ph), r * cos(th))
        ball.trail.append(pos = ball.pos, color = ball.color)
        counter += 1
        dataLine = stdin.readline()
示例#25
0
文件: rmf.py 项目: bzamecnik/gpg
 def interactiveLoop(self):
     while True:
         visual.rate(50)
         if visual.scene.kb.keys:  # event waiting to be processed?
             key = visual.scene.kb.getkey()  # get keyboard info
             if len(key) == 1:
                 if key == " ":
                     demo.refresh()
                 elif key == "a":
                     demo.adjustFrames = not demo.adjustFrames
                     demo.refresh()
                 elif key == "c":
                     demo.sampleCount = max(3, int(demo.sampleCount * self.sampleCountIncreaseFactor))
                     print "Curve sample count: " + str(demo.sampleCount)
                     demo.refresh()
                 elif key == "C":
                     demo.sampleCount = int(demo.sampleCount * (1 / self.sampleCountIncreaseFactor))
                     print "Curve sample count: " + str(demo.sampleCount)
                     demo.refresh()
                 elif key == "f":
                     demo.showFrames = not demo.showFrames
                     demo.refresh()
                 elif key == "n":
                     break
                 elif key == "p":
                     demo.printInfo()
                 elif key == "h" or key == "?":
                     demo.printHelp()
                 elif key == "r":
                     # select next curve from the list of example curves
                     # wrapping around the list
                     selectedCurveIndex = 0
                     try:
                         selectedCurveIndex = demo.exampleCurves.index(demo.curve)
                     except ValueError:
                         print "Warning: Cannot find current curve, using the first one instead."
                     selectedCurveIndex += 1
                     selectedCurveIndex %= len(demo.exampleCurves)
                     demo.curve = demo.exampleCurves[selectedCurveIndex]
                     demo.refresh()
                 elif key == "s":
                     demo.showSweepSurface = not demo.showSweepSurface
                     demo.refresh()
                 elif key == "t":
                     demo.twistCount += 1
                     print "Twist count: " + str(demo.twistCount)
                     demo.refresh()
                 elif key == "T":
                     demo.twistCount -= 1
                     print "Twist count: " + str(demo.twistCount)
                     demo.refresh()
                 elif key == "w":
                     demo.showWorldFrame = not demo.showWorldFrame
                     demo.refresh()
             else:
                 if key == "f11":
                     self.toggleFullscreen()
示例#26
0
def main(n):
	origin = (0, 0)
	goal = (WIDTH, LENGTH)
	obstacles = generate_obstacles(n)

	# heatmap(obstacles)
	for intermediate in minimize(origin, goal, obstacles):
		rate(LENGTH / 10)
		origin = animate(origin, intermediate)
示例#27
0
def draw_efield(V, scale):      # draw electric field
    Ex, Ey = np.gradient(-V)
    Emag = np.sqrt(Ex*Ex + Ey*Ey)
    for i in range(2, M-1, 2):
        for j in range(2, N-1, 2):
            vp.arrow(pos=(i,j), axis=(Ex[i,j], Ey[i,j]), 
                     length=Emag[i,j]*scale)
        vp.rate(100)
    return Ex, Ey
示例#28
0
文件: ratbot.py 项目: dc25/puzzler
 def advance(self):
     self.x = self.x + self.direction[0]
     self.y = self.y + self.direction[1]
     dx = 1.0 * self.direction[0] / self.frames_per_move
     dy = 1.0 * self.direction[1] / self.frames_per_move
     for i in range(self.frames_per_move):
         visual.rate(self.framerate)
         self.rat.x = self.rat.x + dx
         self.rat.y = self.rat.y + dy
示例#29
0
 def simulate(self):
     # Do the simulation...
     self.total_time = 0.0
     self.dt = 0.04
     self.stop = False
     while not self.stop:
         rate(self.dt*1000)
         self.step()
         self.total_time += self.dt
示例#30
0
def draw_efield(V, scale):  # draw electric field
    Ex, Ey = np.gradient(-V)
    Emag = np.sqrt(Ex * Ex + Ey * Ey)
    for i in range(2, M - 1, 2):
        for j in range(2, N - 1, 2):
            vp.arrow(pos=(i, j),
                     axis=(Ex[i, j], Ey[i, j]),
                     length=Emag[i, j] * scale)
        vp.rate(100)
    return Ex, Ey
示例#31
0
文件: ratbot.py 项目: dc25/puzzler
 def turn(self, lr):
     if lr == 'left':
         sign = +1
     else:
         sign = -1
     self.d_index = (self.d_index + sign) % len(self.directions)
     self.direction = self.directions[self.d_index]
     da = sign * visual.pi / 2 / self.frames_per_move
     for i in range(self.frames_per_move):
         visual.rate(self.framerate)
         self.rat.rotate(angle=da, axis=self.zaxis, origin=self.rat.pos)
示例#32
0
文件: card3d.py 项目: jlettvin/card3d
def main(config, cards, f, s):
    while True:
        (change, msg) = getmessage(config, cards, s)
        if change:
            with open(config.card3dname, 'w') as target:
                config.write(target)
                #print "wrote: "+config.card3dname

        rate (100)
        for name, card in cards.iteritems():
            card()
示例#33
0
def animate_motion(x, k):
    # Animate using Visual-Python
    CO = zeros((n, 3))
    B2 = zeros((n, 3))
    C1 = zeros((n, 3))
    C3 = zeros((n, 3))
    CN = zeros((n, 3))

    for i, state in enumerate(x[:,:5]):
        CO[i], B2[i], C1[i], C3[i] = rd.anim(state, r)
        # Make the out of plane axis shorter since this is what control the height
        # of the cone
        B2[i] *= 0.001
        C1[i] *= r
        C3[i] *= r
        CN[i, 0] = state[3]
        CN[i, 1] = state[4]

    from visual import display, rate, arrow, curve, cone, box
    black = (0,0,0)
    red = (1, 0, 0)
    green = (0, 1, 0)
    blue = (0, 0, 1)
    white = (1, 1, 1)
    NO = (0,0,0)
    scene = display(title='Rolling disc @ %0.2f realtime'%k, width=800,
            height=800, up=(0,0,-1), uniform=1, background=white, forward=(1,0,0))
    # Inertial reference frame arrows
    N = [arrow(pos=NO,axis=(.001,0,0),color=red),
         arrow(pos=NO,axis=(0,.001,0),color=green),
         arrow(pos=NO,axis=(0,0,.001),color=blue)]
    # Two cones are used to look like a thin disc
    body1 = cone(pos=CO[0], axis=B2[0], radius=r, color=blue)
    body2 = cone(pos=CO[0], axis=-B2[0], radius=r, color=blue)
    # Body fixed coordinates in plane of disc, can't really be seen through cones
    c1 = arrow(pos=CO[0],axis=C1[0],length=r,color=red)
    c3 = arrow(pos=CO[0],axis=C3[0],length=r,color=green)
    trail = curve()
    trail.append(pos=CN[0], color=black)
    i = 1
    while i<n:
        rate(k/ts)
        body1.pos = CO[i]
        body1.axis = B2[i]
        body2.pos = CO[i]
        body2.axis = -B2[i]
        c1.pos = body1.pos
        c3.pos = body1.pos
        c1.axis = C1[i]
        c3.axis = C3[i]
        c1.up = C3[i]
        c3.up = C1[i]
        trail.append(pos=CN[i])
        i += 1
示例#34
0
文件: card3d.py 项目: jlettvin/card3d
def main(config, cards, f, s):
    while True:
        (change, msg) = getmessage(config, cards, s)
        if change:
            with open(config.card3dname, 'w') as target:
                config.write(target)
                #print "wrote: "+config.card3dname

        rate(100)
        for name, card in cards.iteritems():
            card()
示例#35
0
def SimpleWalk(w, dwc=None, gamma=0.009, t_initial=0., t_final=40.2, dt=0.02):
    """Set gamma for walker w. Walk forward in steps of dt, 
    and update display."""
    w.gamma = gamma
    if dwc is None:
        dwc = CenteredWalkerDisplay(w)
    for t in scipy.arange(t_initial, t_final, dt):
        V.rate(framesPerSecond)	# Pause to show all frames
        w.Walk(t, t+dt, dt*29./30.)
        dwc.update()
    dwc.stanceLeg.visible = 0
    dwc.swingLeg.visible = 0
示例#36
0
def PlotElevator(filename):
  try:
    f = open(filename,'r')
    data = json.loads(f.read())
    f.close()
  except Exception as e:
    return str(e)

  print(data["L0"])
  pos = []
  for i in range(data["SavedSteps"]):
    if not None in [elem for s1 in data["Position"][i] for elem in s1]:
      pos.append(data["Position"][i])
    else:
      break

  pos = array(pos)
  vel = array(data["Velocity"])
  scene = vs.display(title='3D representation', x=500, y=0, width=1920, height=1080, background=(0,0,0), center=pos[0][-1])
  string = vs.curve(pos=pos[0], radius=50)
  earth = vs.sphere(radius=R_earth_equator)
  asteroid = vs.sphere(pos=pos[0][-1],radius=1e3, color=vs.color.red)
  anchor = vs.sphere(pos=pos[0][0],radius=1e2, color=vs.color.green)

  label_avg_l0 = vs.label(pos=pos[0][-1], text="t: %3.1f" % (data["Time"][0],))

  body = 1
  nt = 0
  while True:
    vs.rate(60)
    if scene.kb.keys: # event waiting to be processed?
        s = scene.kb.getkey() # get keyboard info
        if s == "d":
          if body == -1:
            body = 0
          elif body == 0:
            body = 1
          else:
            body = -1

    if body == 1:
      scene.center = (0,0,0)
    else:
      scene.center = pos[nt][body]
    string.pos=pos[nt]
    asteroid.pos=pos[nt][-1]
    anchor.pos=pos[nt][0]
    label_avg_l0.pos = asteroid.pos
    label_avg_l0.text = "t: %3.1f" % (data["Time"][nt],)
    if nt + 1 >= pos.shape[0]:
      nt = 0
    else:
      nt += 1
示例#37
0
 def Draw(self):
     v.rate(100)
     for i in range(3):
         self.displays[i].m.length = (self.mRNAs[i] + eps) / RNA_FACTOR
         self.displays[i].p.length = (self.proteins[i] +
                                      eps) / PROTEIN_FACTOR
         self.displays[i].P0.length = (self.P0[i] + eps)/\
                                      PROMOTER_FACTOR
         self.displays[i].P1.length = (self.P1[i] + eps)/\
                                      PROMOTER_FACTOR
         self.displays[i].P2.length = (self.P2[i] + eps)/\
                                      PROMOTER_FACTOR
示例#38
0
 def loop(self):
     # needed for running outside VIDLE
     while True:
         framesPerSec = 15
         rate(framesPerSec)  # x frames per second at max
         if self.animating:
             if self.angle == 0:
                 self.animateStep()
             elif self.angle < pi:
                 self.animateRotation()
             else:  # the angle is over pi
                 self.endRotation()
示例#39
0
def DrawSSS(sequence):
    global boxlist

    # make all the boxes invisible
    for b in boxlist:
        boxlist[b].visible = False

    # make only the boxes succesfully placed visible
    for xyz in sequence:
        boxlist[xyz].visible = True

    visual.rate(10)
示例#40
0
def DrawSSS(sequence):
    global boxlist

    # make all the boxes invisible
    for b in boxlist:
        boxlist[b].visible = False

    # make only the boxes succesfully placed visible
    for xyz in sequence:
        boxlist[xyz].visible = True

    visual.rate(10)
def SimpleWalk(w, dwc=None, gamma=0.009, t_initial=0., t_final=20.2, dt=0.02):
    """Set gamma for walker w. Walk forward in steps of dt, 
    and update display."""
    w.gamma = gamma
    if dwc is None:
        dwc = CenteredWalkerDisplay(w)
    for t in scipy.arange(t_initial, t_final, dt):
        V.rate(framesPerSecond)  # Pause to show all frames
        w.Walk(t, t + dt, dt * 29. / 30.)
        dwc.update()
    dwc.stanceLeg.visible = 0
    dwc.swingLeg.visible = 0
示例#42
0
 def run(self):
     self.score_graph = gcurve(color=vs.color.white)
     x_score = 0
     while not self.stop_event.is_set():
         route_points_list = self.solver.gen_route_points_list()
         self.draw_route(route_points_list)
         self.score_graph.plot(display=self.score_window,
                               pos=(x_score, self.solver.cur_score))
         x_score += 1
         vs.rate(1.0 / self.draw_interval)
     #self.route_window.visible = False
     #del self.route_window
     exit(0)
示例#43
0
 def run(self):
     self.score_graph = gcurve(color=vs.color.white)
     x_score = 0
     while not self.stop_event.is_set():
         route_points_list = self.solver.gen_route_points_list()
         self.draw_route(route_points_list)
         self.score_graph.plot(display=self.score_window,
                               pos=(x_score, self.solver.cur_score))
         x_score += 1
         vs.rate(1.0/self.draw_interval)
     #self.route_window.visible = False
     #del self.route_window
     exit(0)
示例#44
0
文件: Map.py 项目: AndresCasado/TFG
 def drawMap(self, width, height, definition=50):
     from visual import rate, box
     for i in np.linspace(-width / 2, width / 2, num=definition):
         rate(60)
         for j in np.linspace(-height / 2, height / 2, num=definition):
             point = np.array([j, i])
             d = self.SDF(point)
             if d > 0:
                 color = (d / 10, d / 10, d / 10)
             else:
                 color = (1 - d, 1 - d * width, 0)
             theBox = box(pos=point, color=color)
             theBox.size = (0.4, 0.4, 0.4)
             theBox.z -= np.abs(d)
示例#45
0
def run_3body(scale):
    t, h, ic, cycle, R = 0.0, 0.001, 0, 20, 0.1  # anim cycle, R=obj size
    r, v = init_cond(scale)
    body, vel, line = set_scene(R, r)  # create objects
    while True:
        vp.rate(1000)
        r, v = ode.leapfrog(threebody, r, v, t, h)
        ic = ic + 1
        if (ic % cycle == 0):  # animate once per 'cycle'
            for i in range(3):  # move bodies, draw vel, path, lines
                body[i].pos = r[i]  # bodies
                vel[i].pos, vel[i].axis = body[i].pos, v[i]
                vel[i].length = R * (1 + 2 * vp.mag(v[i]))  # scale vel vector
            line.pos = [body[i].pos for i in [0, 1, 2]]  # lines
示例#46
0
def run_3body(scale):
    t, h, ic, cycle, R = 0.0, 0.001, 0, 20, 0.1 # anim cycle, R=obj size
    r, v = init_cond(scale)
    body, vel, line = set_scene(R, r)     # create objects
    while True:
        vp.rate(1000)
        r, v = ode.leapfrog(threebody, r, v, t, h)
        ic = ic + 1
        if (ic % cycle == 0):       # animate once per 'cycle'
            for i in range(3):      # move bodies, draw vel, path, lines
                body[i].pos = r[i]  # bodies 
                vel[i].pos, vel[i].axis = body[i].pos, v[i]
                vel[i].length = R*(1+2*vp.mag(v[i]))    # scale vel vector
            line.pos = [body[i].pos for i in [0,1,2]]   # lines  
示例#47
0
文件: view.py 项目: hugs/detour
 def focus(self):
     zoom_out()
     origin = int(scene.center.x)
     destination = int(self.card.pos.x)
     if (destination - origin < 0):
         direction = -1    # Scrollin' left
     elif (destination - origin > 0):
         direction = 1     # Scrollin' right
     else:
         direction = 1     # Not goin' anywhere
     for i in range(origin,destination,direction):
         scene.center = (i,0,0)
         rate(100) 
     zoom_in()
 def startLoop(self):
     itemcount = 0
     count = random.uniform(1,50)
     random.seed()
     
     while(1):
         visual.rate(const.framerate) # Frame rate
         
         # check for events, drive actions; must be executed repeatedly in a loop
         self.cCtrl.ctrls.interact()
         
         # do multiple simulation steps per frame to prevent jittering due to
         # 'small' collisions
         n = 6
         
         if itemcount < count:
             itemcount += 1
             self.bodies.append(e.drop_object(self.cWorld.world, self.cRobot.center))
                 
         itemcount+=1
         
         if itemcount == 500:
             itemcount = 0
             for b in self.bodies:
                 for body in b.GetElementKeys():
                     b.RemoveElement(body)
             self.bodies = []
     
         for i in range(n):           
             # Simulation step
             self.cWorld.world.step(self.dt/n)
             
             # terrain for future implementation
             #self.Terrain.UpdateDisplay()
             
             if self.cRobot.bodyExists():
                 self.cRobot.refreshRobot(self.cCtrl.lBody)
             
                 if (self.cRobot.centerRobot):
                     self.cWorld.world._getScene().center = self.cRobot.center
                 
                 for leg in self.cRobot.tibia:
                     leg.UpdateDisplay()
                     
                 for leg in self.cRobot.femur:
                     leg.UpdateDisplay()
                     
                 for b in self.bodies:
                     b.UpdateDisplay()
示例#49
0
 def startLoop(self):
     itemcount = 0
     count = random.uniform(1,50)
     random.seed()
     
     while(1):
         visual.rate(const.framerate) # Frame rate
         
         # check for events, drive actions; must be executed repeatedly in a loop
         self.cCtrl.ctrls.interact()
         
         # do multiple simulation steps per frame to prevent jittering due to
         # 'small' collisions
         n = 6
         
         if itemcount < count:
             itemcount += 1
             self.bodies.append(e.drop_object(self.cWorld.world, self.cRobot.center))
                 
         itemcount+=1
         
         if itemcount == 500:
             itemcount = 0
             for b in self.bodies:
                 for body in b.GetElementKeys():
                     b.RemoveElement(body)
             self.bodies = []
     
         for i in range(n):           
             # Simulation step
             self.cWorld.world.step(self.dt/n)
             
             # terrain for future implementation
             #self.Terrain.UpdateDisplay()
             
             if self.cRobot.bodyExists():
                 self.cRobot.refreshRobot(self.cCtrl.lBody)
             
                 if (self.cRobot.centerRobot):
                     self.cWorld.world._getScene().center = self.cRobot.center
                 
                 for leg in self.cRobot.tibia:
                     leg.UpdateDisplay()
                     
                 for leg in self.cRobot.femur:
                     leg.UpdateDisplay()
                     
                 for b in self.bodies:
                     b.UpdateDisplay()
示例#50
0
 def update(self):
     changes = []
     for i in xrange(0, self.rows):
         changes.append([])
         for j in xrange(0, self.columns):
             changes[i].append(self.update_box(i, j))
     rate(1.0)
     for i in xrange(0, self.rows):
         for j in xrange(0, self.columns):
             if changes[i][j] == self.alive:
                 self.data[i][j].opacity = 1
             else:
                 self.data[i][j].opacity = 0
             self.data[i][j].color = changes[i][j]
     return True
示例#51
0
def main(script, n=20):
    global scene

    n = int(n)
    size = 5
    scene = visual.display(title='Boids', width=800, height=600,
                           range=(size, size, size))
    world = World(n)
    scene.center = world.carrot.pos
    scene.autoscale = False

    while 1:
        # update the screen once per time step
        visual.rate(1/dt)
        world.step()
示例#52
0
def main():
    dt = 0.0001  # the unit time to calculate
    Nsteps = 20  # steps to refresh the screen
    gyro = Gyroscope()
    show = Show()  # create the screen to show the movement of gyroscope
    control = Control(gyro)  # create a screen to control gyroscope
    while True:
        rate(100)  # refresh the screen 100 times one second
        for i in range(Nsteps):
            gyro.go(dt)  # let the gyroscope go
        x, y, z = gyro.GetPos()
        angle = gyro.GetRotationVel() * dt * Nsteps
        show.update(x, y, z,
                    angle)  # update the position and angle of the gyroscope
        control.ShowEnergy()  # show total energy of gyroscope
示例#53
0
def go(x, y, vx, vy):  # motion with full drag and spin effects
    h, t, Y = 0.01, 0., np.array([[x, y, 0.], [vx, vy, 0.]])  # initialize
    while (Y[0, 0] < R and Y[0, 1] > 0.2):  # before homeplate&above ground
        vp.rate(40)
        t, Y = t + h, ode.RK4(baseball, Y, t, h)  # integrate
        ball.pos, spin.pos = Y[0], Y[0] - offset  # move ball, arrow
        spin.rotate(angle=phi), ball.rotate(angle=phi, axis=omega)  #spin
        trail.append(pos=ball.pos)
        ideal.append(pos=(x + vx * t, y + vy * t - 0.5 * g * t * t,
                          0.))  # ideal case
    while (not scene.kb.keys):  # check for key press
        vp.rate(40)
        spin.rotate(angle=phi), ball.rotate(angle=phi, axis=omega)
    scene.kb.getkey()  # clear key
    trail.append(pos=(0, 0, 0), retain=0)  # reset trails
    ideal.append(pos=(0, 0, 0), retain=0)
示例#54
0
def main():
    visual.rate(100)

    beta, rho, sigma = 8.0 / 3.0, 28.0, 10.0
    x, y, z = 5.0, 5.0, 5.0
    dt = 0.002
    system = Lorentz(beta, rho, sigma, x, y, z, dt)

    num_curves = 30
    for i in range(num_curves):
        curve = visual.curve(color=visual.color.white)
        curve_max_points = 1000  # "skipping points" otherwise
        for j in range(curve_max_points):
            system.advance()
            x, y, z = system.get_xyz()
            curve.append(pos=(x, y, z))
示例#55
0
def main():
    visual.rate(10)

    a, b, c = 0.2, 0.2, 5.7
    x, y, z = 0.0, 0.0, 0.0
    dt = 0.01
    system = Roessler(a, b, c, x, y, z, dt)

    num_curves = 100
    for i in range(num_curves):
        curve = visual.curve(color=visual.color.white)
        curve_max_points = 1000  # "skipping points" otherwise
        for j in range(curve_max_points):
            system.advance()
            x, y, z = system.get_xyz()
            curve.append(pos=(x, y, z))
示例#56
0
def relax(V, imax=200):  # find self-consistent soln
    for i in range(imax):
        V[1:-1, 1:-1] = (
            V[1:-1, :-2] + V[1:-1, 2:]  # left, right 
            + V[:-2, 1:-1] + V[2:, 1:-1]) / 4  # top, bottom
        V = set_boundary(V)  # enforce boundary condition
        draw_pot(V), vp.rate(1000)
    return V
def f(alfa, v0):
    vel_fotogramas = 25
    g = 9.81
    v0x = v0 * np.cos(np.deg2rad(alfa))
    v0z = v0 * np.sin(np.deg2rad(alfa))
    t_total = 2 * v0z / g
    x_final = v0x * t_total
    suelo = vs.box(pos=(x_final / 2., -1, 0),
                   size=(x_final, 1, 10),
                   color=vs.color.green)
    canyon = vs.cylinder(pos=(0, 0, 0),
                         axis=(2 * np.cos(np.deg2rad(alfa)),
                               2 * np.sin(np.deg2rad(alfa)), 0))
    bola = vs.sphere(pos=(0, 0, 0))
    bola.trail = vs.curve(color=bola.color)
    flecha = vs.arrow(pos=(0, 0, 0), axis=(v0x, v0z, 0), color=vs.color.yellow)
    labelx = vs.label(pos=bola.pos,
                      text='posicion x = 0 m',
                      xoffset=1,
                      yoffset=80,
                      space=bola.radius,
                      font='sans',
                      box=False,
                      height=10)
    labely = vs.label(pos=bola.pos,
                      text='posicion y = 0 m',
                      xoffset=1,
                      yoffset=40,
                      space=bola.radius,
                      font='sans',
                      box=False,
                      height=10)
    t = 0
    while t <= t_total:
        bola.pos = (v0x * t, v0z * t - 0.5 * g * t**2, 0)
        flecha.pos = (v0x * t, v0z * t - 0.5 * g * t**2, 0)
        flecha.axis = (v0x, v0z - g * t, 0)
        bola.trail.append(pos=bola.pos)
        labelx.pos = bola.pos
        labelx.text = 'posicion x = %s m' % str(v0x * t)
        labely.pos = bola.pos
        labely.text = 'posicion y = %s m' % str(v0z * t - 0.5 * g * t**2)
        t = t + t_total / 100.
        vs.rate(vel_fotogramas)

    return x_final
示例#58
0
def Ch10_Prob3():
	posx = posy = 0
	#mybox = box(pos = [0,0], axis = [0,0], lenght = 10, height = 10)
	Bromotion = sphere(pos = [posx, posy, 0], radius = 0.1)
	for t in range(0,100):
		rate(1)
		x = random()
		y = random()
		if x> 0.5:
			posx = posx + 1
		else:
			posx = posx - 1
		if y> 0.5:
			posy = posy + 1	
		else:
			posy = posy - 1
		
		Bromotion.pos = [posx, posy, 0]
	return 'done'
示例#59
0
 def moveTo(self, newPosition):
     """Simply puts the block on top of the stack numbered newPosition"""
     Block.moveTo(self, newPosition)
     # Now animate our movement
     height = 0
     for block in self.stack:
         if block is self: break
         else: height -= 1
     start = array(self.box.pos)
     end = array((newPosition - (self.stacks.blockCount / 2), height, 0))
     # Move in 30 steps
     step = array((end - start) / 30.)
     for i in range(1, 31):
         self.box.pos = start + (step * i)
         self.label.pos = start + (step * i) + array([0, 0, 1])
         rate(120)
     self.box.pos = end
     self.label.pos = end + array([0, 0, 1])
     print self.box.pos