Ejemplo n.º 1
0
def run(gravity, pendulumLength, initialTheta, initialOmega, initialTime,
        timeStep, maxTime, dragCoefficient, drivingForce, drivingFrequency):
    import vpython
    import numpy as np
    scene.title = "Complex Pendulum"
    barLength = 0.5
    sphereRadius = 0.05
    pendulum = makePendulum(barLength, sphereRadius)

    currentTime = initialTime
    currentTheta = initialTheta
    currentOmega = initialOmega
    naturalFrequency = np.sqrt(gravity / pendulumLength)
    pendulum.rotate(origin=vector(0, 0, 0),
                    angle=currentTheta,
                    axis=vector(0, 0, 1))
    vpython.sleep(1)

    while currentTime <= maxTime:
        currentOmega = currentOmega + (
            -naturalFrequency**2 * np.sin(currentTheta) -
            dragCoefficient * currentOmega +
            drivingForce * np.sin(drivingFrequency * currentTime)) * timeStep
        lastTheta = currentTheta
        currentTheta = currentTheta + currentOmega * timeStep
        currentTime = currentTime + timeStep
        rate(60)
        pendulum.rotate(origin=vector(0, 0, 0),
                        angle=currentTheta - lastTheta,
                        axis=vector(0, 0, 1))
Ejemplo n.º 2
0
def main():
    global Key_Event
    player = Player('s', 'w', 'a', 'd', color.red, player_number='first')
    # blue_player = Player('k', 'i', 'j', 'l', color.blue, player_number='second')
    # players = [red_player, blue_player]
    scene.bind('keydown', capture_key)
    columns, rows = 8, 24
    board = draw_board(columns, rows)
    scene.center = vector(int(columns / 2), int(rows / 2) - 3, 0)
    scene.range = columns + 2
    scene.autoscale = False

    while True:
        for _ in range(5):
            sleep((
                0.16 -
                int(board['level']) * 0.01) if board['level'] <= 15 else 0.01)
            received_inputs = Key_Event
            player.receive_input(board, received_inputs)
            player.update_shadow(board)
            Key_Event = []
        loss_check = player.nat_drop(board)
        if loss_check == 'FAILURE':
            return
        player.update_shadow(board)
def apply_rotation(cycle_points, rot_info_list, anim_steps=45):
    """
    animate the rotation of all points in 'cycle_points' as specified in 'rot_info_list'.
        the animation contains 'anim_steps' frames

    inputs:
    -------
        cycle_points - (list) - list of vpython objects that shall be rotated
        rot_info_list - (list) - list with rotation information triples:
            ('angle', 'axis', 'origin') of rotation for each object
        anim_steps - (int) - number of frames for the animation

    returns:
    --------
        None

    outputs:
    --------
        changes the position of every object in cycle_points by rotation
            as specified in 'rot_info_list'
    """
    for _ in range(anim_steps):
        for obj, rot_info in zip(cycle_points, rot_info_list):
            angle, axis, com = rot_info
            obj.rotate(angle=angle / anim_steps, axis=axis, origin=com)
            obj.rotate(angle=angle / anim_steps, axis=-axis)
        vpy.sleep(0.01)
Ejemplo n.º 4
0
 def replayLoop():
     if len(MooView.viewList) == 0:
         return
     numFrames = MooView.viewList[0].numFrames()
     while MooView.viewList[0].replayButton.text == "Stop Replay":
         for idx in range(numFrames):
             for view in MooView.viewList:
                 view.replaySnapshot(idx)
             vp.sleep(MooView.viewList[0].sleep)
         vp.sleep(0.5)  # Pause 0.5 sec between replays
Ejemplo n.º 5
0
 def updateValues(self):
     simTime = moose.element('/clock').currentTime
     #self.timeStr.set_text( "Time= {:.3f}".format( time ) )
     for i in self.drawables_:
         i.updateValues(simTime)
     if self.doRotation and abs(self.rotation) < 2.0 * 3.14 / 3.0:
         self.scene.forward = vp.rotate(self.scene.forward,
                                        angle=self.rotation,
                                        axis=self.scene.up)
         self.updateAxis()
     if self.viewIdx == 0:
         self.timeLabel.text = "Time = {:7.3f} sec".format(simTime)
         vp.sleep(self.sleep)
Ejemplo n.º 6
0
def main():
    global Key_Event
    scene.bind('keydown', capture_key)
    end_of_game = False

    columns, rows = 10, 24

    scene.height = 550
    board = draw_board(columns, rows)
    scene.center = vector(int(columns / 2), int(rows / 2) - 3, 0)
    scene.range = columns + 2
    scene.autoscale = False

    red_player = Player('q',
                        'e',
                        's',
                        'w',
                        'a',
                        'd',
                        color.red,
                        player_number='first')
    blue_player = Player('u',
                         'o',
                         'k',
                         'i',
                         'j',
                         'l',
                         color.blue,
                         player_number='second')
    players = [red_player, blue_player]

    while not end_of_game:
        for _ in range(5):
            sleep((
                0.16 -
                int(board['level']) * 0.01) if board['level'] <= 15 else 0.01)
            received_inputs = Key_Event
            for player in players:
                player.receive_input(board, received_inputs)
            for player in players:
                player.update_shadow(board)
            Key_Event = []
        for player in players:
            loss_check = player.nat_drop(board)
            if loss_check == 'FAILURE':
                end_of_game = game_over(board, players)
            player.update_shadow(board)
Ejemplo n.º 7
0
    func, initcond, t, args=(g, ), full_output=True
)  #solucion de la ecuacion diferencial (parametros acordes a los definidos en la funcion)

theta, omega, ll, rr = solu.T  # solucion para cada paso de theta y omega

# =====================

scene.range = 0.2  # tamaño de la ventana de fondo

xp = l * sin(thes)  #pasa de coordenadas polares a cartesinas
yp = -l * cos(thes)
zp = 0.

sleeptime = 0.0001  # tiempon con el que se utiliza la posicion de la particula

prtcl = sphere(pos=vector(xp, yp, zp), radius=R,
               color=color.cyan)  #define objeto con que se va a trabajar

time_i = 0  #es un contador que se mueve ene el espacio temporal en donde se resolvio la ecuacion deferencial
t_run = 0  #tiempo en el q se ejecuta la animacion

#for i in omega:
#    print(i)

while t_run < t_final:  #animacion
    sleep(sleeptime)
    prtcl.pos = vector(l * sin(theta[time_i]), -l * cos(theta[time_i]), zp)

    t_run += t_delta
    time_i += 1
condINI=array([thetaI,thetaIp,phiI,phiIp])
sol=odeint(solucion,condINI,t,args=(g,l,k,m))
xp=l*thetaI
yp=-l
zp=0
r=1



pendulo1=sphere(pos=vector(xp,yp,zp),radius=r,color=color.green)
pendulo2=sphere(pos=vector(xp+l,yp,zp),radius=r,color=color.green)
#cuerda1=curve(vector(0,0,0),pendulo1.pos)
#cuerda2=curve(vector(l,0,0),pendulo2.pos)

cuerdas1=cylinder(pos=pendulo2.pos,axis=vector(0,0,0),radius=0.1,color=color.white)
cuerdas2=cylinder(pos=pendulo2.pos,axis=vector(l,0,0),radius=0.1,color=color.white)
base=box(pos=vector(l/2,0,0),size=vector(l+2,0.1,0.1),color=color.orange)
spring=helix(pos=pendulo2.pos,axis=vector(0,0,0),radius=0.3,constant=k,thickness=0.1,coils=10,color=color.white)
ti=0
while ti<tf:
    sleep(0.01)
    pendulo1.pos=vector(l*sol[ti,0],yp,zp)
    pendulo2.pos=vector(l*sol[ti,2]+l,yp,zp)
    cuerdas2.pos=pendulo2.pos
    cuerdas2.axis=vector(l,0,0)-cuerdas2.pos
    cuerdas1.pos=pendulo1.pos
    cuerdas1.axis=vector(0,0,0)-cuerdas1.pos
    spring.pos=pendulo1.pos
    spring.axis=pendulo2.pos-spring.pos
    ti = ti + 1
tin = 0.  #tiempo inicial
tfin = 15.  #tiempo final
tdif = (tfin - tin) / pasos  #diferencial de tiempo
t = linspace(tin, tfin, pasos)  #arreglo de diferencial de tiempo

soluc, outodeint = odeint(
    funcion, initcond, t, args=(g, ), full_output=True
)  #solucion de la ecuacion diferencial (parametros acordes a los definidos en la funcion)

theta, omega, ll, rr = soluc.T  # solucion para cada paso de theta y omega

scene.range = 0.2  # tamaño de la ventana de fondo

xp = l * sin(thes)  #pasa de coordenadas polares a cartesinas
yp = -l * cos(thes)
zp = 0.

actime = 0.0001  # tiempon con el que se utiliza la posicion de la particula

prtcl = sphere(pos=vector(xp, yp, zp), radius=R,
               color=color.red)  #define objeto con que se va a trabajar

contime = 0  #es un contador que se mueve ene el espacio temporal en donde se resolvio la ecuacion deferencial
runtime = 0  #tiempo en el q se ejecuta la animacion

while runtime < tfin:  #animacion
    sleep(actime)
    prtcl.pos = vector(l * sin(theta[contime]), -l * cos(theta[contime]), zp)
    runtime += tdif
    contime += 1
Ejemplo n.º 10
0
def choose_branch(nb_branches, Q, state, e):
    if (np.count_nonzero(Q[state]) == 0 or np.random.rand(1) < e):
        chosen_branch = np.random.choice(nb_branches)
    else:
        chosen_branch = Q[state].argmax()
    return chosen_branch


tree_actions_index = np.load("tree_actions_index.npy")

env = Carom(render=False)
actions = env.get_actions()

env.reset()
sleep(2)
nb_branches = len(tree_actions_index[0, 0])
# action_index = int(tree_actions_index[0,0][2])
# env.step(actions[action_index][0],actions[action_index][1],actions[action_index][2],actions[action_index][3],actions[action_index][4])
# action_index = int(tree_actions_index[1,2][2])
# env.step(actions[action_index][0],actions[action_index][1],actions[action_index][2],actions[action_index][3],actions[action_index][4])
# action_index = int(tree_actions_index[2,8][1])
# env.step(actions[action_index][0],actions[action_index][1],actions[action_index][2],actions[action_index][3],actions[action_index][4])
nb_states = 0
num_episodes = 700
lr = .8
y = .95
e = 0.2
episodes = []
episode_rewards = []
for i in range(tree_actions_index.shape[0]):
theta, omega = solu.T  #matriz de 2*2 ( columnas para los pasos) solucion para cada paso de theta y omega , se definen las variables y solu.t devuelve la matriz transpuesta en los valores de theta y omega

# =====================

scene.range = 0.2  #  tamaño de la pantalla a visualizar

xp = l * sin(thes)  #coordenadas cartesianas de la esfera con el angulo inicial
yp = -l * cos(thes)  #igual
zp = 0.  #igual

sleeptime = 0.0001  #tiempo con que la maquina actualiza la posicion de la particula

prtcl = sphere(pos=vector(xp, yp, zp), radius=R, color=color.cyan
               )  #Define la particula con coordenadas iniciales dadas xp,yp,zp

time_i = 0  #defino contador que se mueve en el espacio que se soluciona la Ecuf difencial
t_run = 0  #con el que se corre la animacion

#for i in omega:
#    print(i)

while t_run < t_final:  #condicion para la animacion
    sleep(sleeptime)  #duerme
    prtcl.pos = vector(
        l * sin(theta[time_i]), -l * cos(theta[time_i]),
        zp)  #actualiza posicion de la particula aumenta el contador

    t_run += t_delta  #contadores y acumuladores
    time_i += 1  #igual
Ejemplo n.º 12
0

def new_thread():
    _thread.start_new_thread(Path_Calc)


vp.button(bind=new_thread, text='Path Calc')

start = False


def Go():
    global start
    start = True


vp.button(bind=Go, text='go')

time = 0
while time < total_steps:
    if start == False:
        vp.sleep(1)
        continue
    vp.rate(500)

    for j in range(len(Electrons)):
        Electrons[j].pos = paths[j][time]

    time += 1
    #print('step')
Ejemplo n.º 13
0
                  thickness=.1)
angle = 0
da = .01

trail = vp.curve(color=vp.color.magenta, radius=.02)
trail.append(vp.vector(1, 0, 0))
trail.append(vp.vector(1, 0, 2))
trail.append(vp.vector(2, 0, 2))

while angle < 3 * vp.pi / 4:
    vp.rate(100)
    ptr.rotate(angle=da, axis=vp.vector(0, 0, 1), origin=ptr.pos)
    trail.append(ptr.pos + ptr.axis)
    angle += da

vp.sleep(1)  # sleep for 1 second
vp.scene.autoscale = False
vp.scene.append_to_caption("""Drag the mouse and you'll drag a sphere.
On a touch screen, press and hold, then drag.""")

t = 0
dt = .01
y0 = gslabel.pos.y
ball_yo = ball.pos.y
while t < 10:
    vp.rate(1 / dt)
    ball.pos.y = ball_yo + 0.5 * vp.sin(-4 * t)
    spring.length = ball.pos.y - spring.pos.y - ball.radius + 0.15
    gslabel.yoffset = 28 * vp.sin(-4 * t)
    t += dt
Ejemplo n.º 14
0
def show(
    sec=10
):  # Animate scene for N seconds - use when importing library manually
    vpython.sleep(sec)
Ejemplo n.º 15
0
def launch(sample_rate, position, orientation, COM, COP, thrust, gravity, lift, drag):
    for step in range(len(position)):
        position[step][2] = -position[step][2]

    force_scale = 0.01
    l = 2
    rad = 0.09
    steps = len(position)

    # Initialization of enviorment
    render = vp.canvas(height=600, width=1200, background=vp.vector(0.8, 0.8, 0.8), forward=vp.vector(1, 0, 0), up=vp.vector(0, 0, 1))
    render.select()
    render.caption = "Loading..."
    render.visible = False

    # Initialization of body and cone
    body = vp.cylinder(pos=vp.vector(-l, 0, 0), axis=vp.vector(l*0.8, 0, 0), radius=rad)
    cone = vp.cone(pos=vp.vector(-l*0.2, 0, 0), axis=vp.vector(l*0.2, 0, 0), radius=rad)

    # Initialization of fins
    a_fins = vp.box(pos=vp.vector(-l + (l*0.05), 0, 0), size=vp.vector(l*0.1, rad*4, rad*0.25))
    b_fins = vp.box(pos=vp.vector(-l + (l*0.05), 0, 0), size=vp.vector(l*0.1, rad*0.25, rad*4))

    inv_box = vp.box(pos=vp.vector(l/2, 0, 0), size=vp.vector(l, 10e-10, 10e-10), visible=False)

    # Initialization of rocket
    rocket = vp.compound([body, cone, a_fins, b_fins, inv_box], pos=vp.vector(0, 0, 1), axis=vp.vector(1, 0, 0), up=vp.vector(0, 0, 1), color=vp.vector(1,1,1), opacity=0.5)

    COM_sphere = vp.sphere(radius = 0.04, color=vp.vector(0, 0, 0))
    COP_sphere = vp.sphere(radius = 0.04, color=vp.vector(0, 0, 0))
    thrust_pointer = vp.arrow(shaftwidth = 0.1, color=vp.vector(1, 1, 0))
    gravity_pointer = vp.arrow(shaftwidth = 0.1, color=vp.vector(0, 1, 1))
    lift_pointer = vp.arrow(shaftwidth = 0.1, color=vp.vector(1, 0, 1))
    drag_pointer = vp.arrow(shaftwidth = 0.1, color=vp.vector(0, 0, 1))

    a = 4
    c = 0.3
    b = a - c
    sqr_out = [[-a, a],[a, a],[a, -a],[-a, -a], [-a, a]]
    sqr_in1 = [[-b, b - 3*c],[b, b - 3*c],[b, -b],[-b, -b], [-b, b - 3*c]]
    sqr_in2 = [[-b, b],[b, b], [b, b - 2*c],[-b, b - 2*c], [-b, b]]
    ref_box = vp.extrusion(path=[vp.vector(-c/2, 0, 0), vp.vector(c/2, 0, 0)], shape=[sqr_out, sqr_in1, sqr_in2], color=vp.vector(0.5, 0.5, 0.5))

    render.camera.follow(rocket)
    render.autoscale = False
    launch_pad = vp.box(pos=vp.vector(position[0][0], position[0][1], -1), size=vp.vector(16, 16, 2), color=vp.vector(0.2, 0.2, 0.2))
    launch_pad = vp.box(pos=vp.vector(position[-1][0], position[-1][1], -1), size=vp.vector(16, 16, 2), color=vp.vector(0.2, 0.2, 0.2))

    rocket.normal = vp.cross(rocket.up, rocket.axis)


    #vp.attach_arrow(rocket, 'up', color=vp.color.green)
    #vp.attach_arrow(rocket, 'axis', color=vp.color.blue)
    #vp.attach_arrow(rocket, 'normal', color=vp.color.red)

    roll = 0
    vp.attach_trail(rocket, radius=rad/3, color=vp.color.red)

    sqr_out = [[-a, a],[a, a],[a, -a],[-a, -a], [-a, a]]
    sqr_in1 = [[-b, b - 3*c],[b, b - 3*c],[b, -b],[-b, -b], [-b, b - 3*c]]
    sqr_in2 = [[-b, b],[b, b], [b, b - 2*c],[-b, b - 2*c], [-b, b]]

    for step in range(2, steps):
        if not step % 5:
            a = 4
            c = 0.3
            b = a - c
            ref = vp.extrusion(path=[vp.vector(0, 0, 0), vp.vector(c, 0, 0)], shape=[sqr_out, sqr_in1, sqr_in2], axis=vp.vector(1, 0, 0), up=vp.vector(0, 1, 0), pos=vp.vector(position[step][0], position[step][1], position[step][2]))
            ref.up = vp.vector(0, 0, 1)
            ref.rotate(angle=orientation[step][0], axis=vp.cross(ref.axis, ref.up))
            ref.rotate(angle=orientation[step][1], axis=ref.up)
            ref.rotate(angle=orientation[step][2], axis=ref.axis)

    render.caption = "Running"
    render.visible = True
    for step in range(steps):
        x = position[step][0]
        y = position[step][1]
        z = position[step][2]

        rocket.normal = vp.cross(rocket.axis, rocket.up)

        pitch, yaw, roll = orientation[step][0], orientation[step][1], orientation[step][2]

        COM_x = x + COM[step] * np.cos(yaw) * np.cos(pitch)
        COM_y = y + COM[step] * np.sin(yaw) * np.cos(pitch)
        COM_z = z + COM[step] * np.sin(pitch)

        COP_x = x + COP[step] * np.cos(yaw) * np.cos(pitch)
        COP_y = y + COP[step] * np.sin(yaw) * np.cos(pitch)
        COP_z = z + COP[step] * np.sin(pitch)

        thrust_x = x + (-l) * np.cos(yaw) * np.cos(pitch)
        thrust_y = y + (-l) * np.sin(yaw) * np.cos(pitch)
        thrust_z = z + (-l) * np.sin(pitch)

        thrust_mag = np.linalg.norm(thrust[step]) * force_scale
        thrust_ax_x = thrust_mag * np.cos(yaw) * np.cos(pitch)
        thrust_ax_y = thrust_mag * np.sin(yaw) * np.cos(pitch)
        thrust_ax_z = thrust_mag * np.sin(pitch)

        lift_mag = lift[step][0] * force_scale
        lift_ax_x = 0
        lift_ax_y = 0
        lift_ax_z = lift_mag

        drag_mag = np.linalg.norm(drag[step]) * force_scale
        print(lift_mag)
        drag_ax_x = drag_mag
        drag_ax_y = 0
        drag_ax_z = 0

        gravity_mag = np.linalg.norm(gravity[step]) * force_scale

        thrust_pointer.pos = vp.vector(thrust_x, thrust_y, thrust_z)
        thrust_pointer.axis = vp.vector(thrust_ax_x, thrust_ax_y, thrust_ax_z)

        gravity_pointer.pos = vp.vector(COM_x, COM_y, COM_z)
        gravity_pointer.axis = vp.vector(0, 0, -gravity_mag)

        lift_pointer.pos = vp.vector(COP_x, COP_y, COP_z)
        lift_pointer.axis = vp.vector(lift_ax_x, lift_ax_y, lift_ax_z)

        drag_pointer.pos = vp.vector(COP_x, COP_y, COP_z)
        drag_pointer.axis = vp.vector(drag_ax_x,drag_ax_y, drag_ax_z)

        rocket.rotate(angle=pitch, axis=rocket.normal)
        rocket.rotate(angle=yaw, axis=rocket.up)
        rocket.rotate(angle=roll, axis=rocket.axis)

        COM_sphere.pos = vp.vector(COM_x, COM_y, COM_z)
        COP_sphere.pos = vp.vector(COP_x, COP_y, COP_z)

        rocket.pos = vp.vector(x, y, z)
        vp.sleep(1/sample_rate)
        if step + 1 != steps:
            rocket.rotate(angle=-roll, axis=rocket.axis)
            rocket.rotate(angle=-yaw, axis=rocket.up)
            rocket.rotate(angle=-pitch, axis=rocket.normal)

    render.caption = "Done"