Esempio n. 1
0
def draw(lattice):
    lattice.logger.info("Hook6: Display water molecules with VPython.")
    lattice.logger.info("  Total number of atoms: {0}".format(len(lattice.atoms)))
    cellmat = lattice.repcell.mat
    offset = (cellmat[0] + cellmat[1] + cellmat[2]) / 2
    # prepare the reverse dict
    waters = defaultdict(dict)
    for atom in lattice.atoms:
        resno, resname, atomname, position, order = atom
        if "O" in atomname:
            waters[order]["O"] = position - offset
        elif "H" in atomname:
            if "H0" not in waters[order]:
                waters[order]["H0"] = position - offset
            else:
                waters[order]["H1"] = position - offset
    for order, water in waters.items():
        O = water["O"]        
        H0 = water["H0"]        
        H1 = water["H1"]        
        lattice.vpobjects['w'].add(vp.simple_sphere(radius=0.03, pos=vp.vector(*O), color=vp.vector(1,0,0)))
        lattice.vpobjects['w'].add(vp.simple_sphere(radius=0.02, pos=vp.vector(*H0), color=vp.vector(0,1,1)))
        lattice.vpobjects['w'].add(vp.simple_sphere(radius=0.02, pos=vp.vector(*H1), color=vp.vector(0,1,1)))
        lattice.vpobjects['w'].add(vp.cylinder(radius=0.015, pos=vp.vector(*O), axis=vp.vector(*(H0-O))))
        lattice.vpobjects['w'].add(vp.cylinder(radius=0.015, pos=vp.vector(*O), axis=vp.vector(*(H1-O))))
        lattice.vpobjects['l'].add(vp.label(pos=vp.vector(*O), xoffset=30, text="{0}".format(order), visible=False))
    for i,j in lattice.spacegraph.edges(data=False):
        if i in waters and j in waters:  # edge may connect to the dopant
            O = waters[j]["O"]
            H0 = waters[i]["H0"]
            H1 = waters[i]["H1"]
            d0 = H0 - O
            d1 = H1 - O
            rr0 = np.dot(d0,d0)
            rr1 = np.dot(d1,d1)
            if rr0 < rr1 and rr0 < 0.27**2:
                lattice.vpobjects['a'].add(vp.arrow(shaftwidth=0.015, pos=vp.vector(*H0), axis=vp.vector(*(O-H0)), color=vp.vector(1,1,0)))
            if rr1 < rr0 and rr1 < 0.245**2:
                lattice.vpobjects['a'].add(vp.arrow(shaftwidth=0.015, pos=vp.vector(*H1), axis=vp.vector(*(O-H1)), color=vp.vector(1,1,0)))
    lattice.logger.info("  Tips: use keys to draw/hide layers. [3 4 5 6 7 8 a w l]")
    lattice.logger.info("  Tips: Type ctrl-C twice at the terminal to stop.")
    lattice.logger.info("Hook6: end.")
Esempio n. 2
0
def vector_from(arr=np.array([0, 0, 0])):
    """
    Creates a vpython vector from a numpy array

    Parameters
    ----------
    arr: numpy array
        Array that is converted into a vpythonv ector
    """
    import vpython
    return vpython.vector(arr[0], arr[1], arr[2])
Esempio n. 3
0
def face(center, rpos):
    n = rpos.shape[0]
    
    # normalize relative vectors
    normalized = np.zeros_like(rpos)
    for i in range(n):
        normalized[i] = rpos[i] / np.linalg.norm(rpos[i])
    #normal for each triangle
    normals = np.zeros_like(rpos)
    for i in range(n):
        normals[i] = np.cross(normalized[i-1], normalized[i])
    # central normal
    c_normal = np.sum(normals, axis=0)
    c_normal /= np.linalg.norm(c_normal)
    if np.dot(c_normal, sun) < 0.0:
        c_normal = - c_normal
        normals  = - normals
    
    hue, sat = hue_sat[n]
    bri = 1
    r,g,b = colorsys.hsv_to_rgb(hue/360., sat, bri)
    pos = rpos + center
    v_center = vp.vertex( pos=vp.vector(*center), normal=vp.vector(*c_normal), color=vp.vector(r,g,b))
    vertices = [vp.vertex( pos=vp.vector(*p), normal=vp.vector(*(normals[i])), color=vp.vector(r,g,b) ) for i,p in enumerate(pos)]
    faces = set()
    for i in range(n):
        faces.add(vp.triangle(v0=vertices[i-1], v1=vertices[i], v2=v_center,  ))
#    group.add(sw.shapes.Polygon(pos, fill=rgb, stroke_linejoin="round", fill_opacity="1.0", stroke="#444", stroke_width=3))
    return faces
Esempio n. 4
0
import vpython as vp
import numpy as np
import time

axis_list = [vp.vector(-1, 0, 0), vp.vector(1, 0, 0),
             vp.vector(0, -1, 0), vp.vector(0, 1, 0)]

num = 0

arrow = vp.arrow(
    pos=vp.vector(0, 0, 0),
    axis=vp.vector(0.0, 0.0, 1),
    shaftwidth=0.1,
    color=vp.color.red)

arrow.rotate(
    angle=np.pi/2, axis=axis_list[num],
    origin=vp.vector(0, 0, 0.1))

for i in [0.2, 0.1, 0.0, 0.1]:
    time.sleep(2)
    arrow.shaftwidth = i + 0.001
    print(arrow.shaftwidth)

print('Done')
Esempio n. 5
0
def representer(xs, ys, name, clock, orienter):
    escena = vpython.canvas(width=1200, height=600)
    escena.title = name
    escena.background = vpython.color.cyan

    pos = vpython.vector(xs[0], 2, -ys[0])
    escena.range = 100
    escena.center = vpython.vector(0, 0, 0)
    escena.forward = vpython.vector(1, -2, 1)
    #suelo = vpython.box(pos = vpython.vector(0,-1,0),size=vpython.vector(10,0.01,200),color=vpython.color.white)
    suelo = vpython.box(pos=vpython.vector(250, -1, 0),
                        size=vpython.vector(500, 0.01, 200),
                        color=vpython.color.white,
                        texture=vpython.textures.wood)
    vehicle = vpython.box(pos=pos,
                          color=vpython.color.red,
                          size=vpython.vector(8, 4, 6))
    trayectoria = vpython.curve(color=vpython.color.yellow)
    road = vpython.curve(color=vpython.color.black)
    muro = vpython.box(pos=vpython.vector(0, 20, 10),
                       color=vpython.color.blue,
                       size=vpython.vector(20, 40.99, 2),
                       texture=vpython.textures.stucco)
    piedra1 = vpython.sphere(pos=vpython.vector(150, -1, -ys[150]),
                             color=vpython.color.black,
                             radius=1)
    piedra2 = vpython.sphere(pos=vpython.vector(xs[400], -1, -ys[400]),
                             color=vpython.color.black,
                             radius=1)
    time.sleep(clock)
    #escena.range = 45
    escena.range = 20
    for i in range(len(xs)):
        if i > 0:
            vehicle.rotate(axis=vpython.vector(0, 1, 0),
                           angle=-orienter[i - 1])
        pos = vpython.vector(xs[i], 2, -ys[i])
        #suelo.pos=vpython.vector(i/2.0,-1,0)
        #suelo.size = vpython.vector(i,0.01,200)

        muro.pos = vpython.vector(i / 2, 20, 10)
        muro.size = vpython.vector(i, 40.99, 2)

        vehicle.pos = pos
        escena.center = vpython.vector(xs[i], 5, -ys[i])
        trayectoria.append(pos)
        vehicle.rotate(axis=vpython.vector(0, -1, 0), angle=-orienter[i])
        road.append(vpython.vector(i, 2, 0))
        vpython.rate(40)
Esempio n. 6
0
import vpython as v
# 3.4 (a)
L = 1
R = 0.2
count = 1
for i in range(-2 * L, 2 * L + 1):
    for j in range(-2 * L, 2 * L + 1):
        for k in range(-2 * L, 2 * L + 1):
            v.sphere(pos=v.vector(i, j, k), radius=R, color=v.color.green)
            if i % 2 == 0 and j % 2 == 0 and k % 2 == 0:
                v.sphere(pos=v.vector(i, j, k), radius=R, color=v.color.blue)
Esempio n. 7
0
# coding: utf-8

from vpython import arrow, box, bumpmaps, color, distant_light, radians, rate, scene, sphere, textures, vector
import time
from toolbox_draw_body import draw_part
from toolbox_draw_body import p0, p1, p1_, p2, p2_
from toolbox_draw_body import p0_la, p1_la, p1__la, p2_la, p2__la
from toolbox_draw_body import pp_right_leg, p0_right_leg, p1_right_leg, p2_right_leg
from toolbox_draw_body import pp_left_leg, p0_left_leg, p1_left_leg, p2_left_leg


up = vector(0, 1, 0)
right = vector(-1, 0, 0)
front = vector(0, 0, 1)

p2 -= up*0.2
p2_la -= up*0.2
# p2 -= right*0.3
# p2_ -= right*0.3
# p2 -= up*0.2
# p2_ -= up*0.2

visible = False


def draw_anchor(p, a0=up, a1=right, a2=front, full=False, visible=visible):
    # draw anchor and regular axis
    if full:
        arrow(pos=p, radius=0.5, axis=a0.norm()*4,
              color=color.red, visible=visible)
        arrow(pos=p, radius=0.5, axis=a1.norm()*4,
    cell.place_atom('Si', vp.vector(a / 2, a / 2., a / 2))
    cell.place_atom('Si', vp.vector(a / 2, -a / 2., a / 2))
    cell.place_atom('Si', vp.vector(-a / 2, a / 2, a / 2))
    cell.place_atom('Si', vp.vector(-a / 2, -a / 2, a / 2))

    # Outer corners (front)
    cell.place_atom('Si', vp.vector(a / 2, a / 2, -a / 2))
    cell.place_atom('Si', vp.vector(a / 2, -a / 2, -a / 2))
    cell.place_atom('Si', vp.vector(-a / 2, a / 2, -a / 2))
    cell.place_atom('Si', vp.vector(-a / 2, -a / 2, -a / 2))

    # Faces and center atom
    cell.place_atom('Si', vp.vector(a / 2, 0., 0.))
    cell.place_atom('Si', vp.vector(-a / 2, 0., 0.))
    cell.place_atom('Si', vp.vector(0., 0., -a / 2))
    cell.place_atom('Si', vp.vector(0., 0., 0.))
    cell.place_atom('Si', vp.vector(0., 0., a / 2))


# Run program
a = 3.57  #angstroms

# Useless for now.
cell = [[a / 2, 0, 0], [0, a / 2, 0], [0, 0, a / 2]]

cell_structure = CellStructure(np.array(cell))

generate_fcc(cell_structure, a)

spring_solve(cell_structure, vp.vector(0.5, 0, 0), a)
Esempio n. 9
0
dt = 0.01
j = 3/2
n = int(2*j+1)

CS = coherent_states(j, N=20)
rots = tangent_rotations(CS)

state = qt.rand_ket(n)
H = qt.rand_herm(n)
U = (-1j*H*dt).expm()

vsphere = vp.sphere(color=vp.color.blue,\
                    opacity=0.4)
vstars = [vp.sphere(radius=0.2, emissive=True,\
                    pos=vp.vector(*xyz)) for xyz in spin_XYZ(state)]

pts = husimi(state, CS)
#vpts = [vp.sphere(pos=vp.vector(*pt[1]), radius=0.5*pt[0]) for pt in pts]
vpts = []
for i, pt in enumerate(pts):
    amp, normal = pt
    amp_vec = np.array([amp.real, amp.imag, 0])
    amp_vec = np.dot(rots[i], amp_vec)
    vpts.append(vp.arrow(pos=vp.vector(*normal), axis=0.5*vp.vector(*amp_vec)))

while True:
    state = U*state
    for i, xyz in enumerate(spin_XYZ(state)):
        vstars[i].pos = vp.vector(*xyz)
    pts = husimi(state, CS)
Esempio n. 10
0
vp.scene.width = 1000
vp.scene.height = 800

dt = 0.001
n = 50
a = qt.destroy(n)
Q = qt.position(n)
QL, QV = Q.eigenstates()
N = qt.num(n)
NL, NV = N.eigenstates()
H = N + 1/2
U = (-1j*dt*H).expm()

state = qt.basis(n,0)
amps = [state.overlap(v) for v in QV]
vamps = [vp.arrow(pos=vp.vector(QL[i], 0, 0),\
	      axis=vp.vector(amps[i].real, amps[i].imag, 0)) for i in range(n)]
vprobs = [vp.sphere(radius=0.1, color=vp.color.red,\
				    pos=vp.vector(QL[i], 1+3*(amps[i]*np.conjugate(amps[i])).real, 0))\
						for i in range(n)]
vexp = vp.sphere(color=vp.color.yellow, radius=0.3,\
					pos=vp.vector(qt.expect(Q, state), 0, 0))

def coherent(s):
	global n, a
	return np.exp(-s*np.conjugate(s)/2)*(s*a.dag()).expm()*(-np.conjugate(s)*a).expm()*qt.basis(n,0)

def keyboard(e):
	global state, n, NV
	key = e.key
	if key == "i":
Esempio n. 11
0
from vpython import cone,color,vector
cone(axis=vector(5,3,0),radius=1)
Esempio n. 12
0
if "--no-graphics" in sys.argv:
    pass

else:
    import vpython as vp
    #Inserisce le auto nel grafico e ritorna un dizionario che associa
    #ogni pallina alla targa dell'auto corrispondente
    palle = {}

    #for vpython useful commands see here: vpython.org/contents/docs/display.html
    vp.scene.title = "Visual Test VANET"
    vp.scene.x = 0
    vp.scene.y = 0
    vp.scene.width = 1300
    vp.scene.height = 900
    vp.scene.center = vp.vector(7000, 4500, 0)

    def displayCars(cars):
        balls = {}
        for c in cars:
            balls[cars[c].plate] = vp.sphere(pos=vp.vector(
                cars[c].pos[0], cars[c].pos[1], 0),
                                             radius=10)
        global palle
        palle = balls
        return balls

    def firstInfection():
        flag = 0
        while True:
            m = vp.scene.waitfor('click')
Esempio n. 13
0
def turtle_interpretation_3D(scene,
                             instructions,
                             delta=22.5,
                             width=0.3,
                             widthScaling=0.7,
                             tropismVec=vector(0, 0, 0),
                             tropismStrength=0):
    """Interprets a set of instructions for a turtle to draw a tree in 3D. """
    ############ INITIALIZATION #############
    bob = Turtle3D(width=width)

    turtlePosStack = []
    turtleHeadStack = []

    turtleXmax = 0
    turtleXmin = 0
    turtleYmax = 0
    turtleYmin = 0
    turtleZmax = 0
    turtleZmin = 0

    ######### MAIN FUNCTION ##############
    for mod in instructions:
        if mod.symbol == "F":
            bob.applyTropism(tropismVec, tropismStrength)
            if mod.param == []:
                bob.forward()
            else:
                bob.forward(mod.param[0])
            #Note that we only need to update the max coordinates if the turtle has moved
            turtleXmax = max(turtleXmax, bob.xcor())
            turtleXmin = min(turtleXmin, bob.xcor())
            turtleYmax = max(turtleYmax, bob.ycor())
            turtleYmin = min(turtleYmin, bob.ycor())
            turtleZmax = max(turtleZmax, bob.zcor())
            turtleZmin = min(turtleZmin, bob.zcor())
        elif mod.symbol == "f":
            bob.penUp()
            if mod.param == []:
                bob.forward()
            else:
                bob.forward(mod.param[0])
            bob.penDown()
        elif mod.symbol == "+":
            if mod.param == []:
                bob.turnLeft(delta)
            else:
                bob.turnLeft(mod.param[0])
        elif mod.symbol == "-":
            if mod.param == []:
                bob.turnRight(delta)
            else:
                bob.turnRight(mod.param[0])
        elif mod.symbol == "&":
            if mod.param == []:
                bob.pitchDown(delta)
            else:
                bob.pitchDown(mod.param[0])
        elif mod.symbol == "^":
            if mod.param == []:
                bob.pitchUp(delta)
            else:
                bob.pitchUp(mod.param[0])
        elif mod.symbol == "\\":
            if mod.param == []:
                bob.rollLeft(delta)
            else:
                bob.rollLeft(mod.param[0])
        elif mod.symbol == "/":
            if mod.param == []:
                bob.rollRight(delta)
            else:
                bob.rollRight(mod.param[0])
        elif mod.symbol == "|":
            bob.turnLeft(180)
        elif mod.symbol == "[":
            turtlePosStack.insert(0, bob.getPosition())
            turtleHeadStack.insert(0, bob.getHeading())
            bob.pushCurve()
        elif mod.symbol == "]":
            bob.setPosition(turtlePosStack.pop(0))
            bob.setHeading(turtleHeadStack.pop(0))
            bob.popCurve()
        elif mod.symbol == "!":
            if mod.param == []:
                bob.decrementDiameter(widthScaling)
            else:
                bob.setWidth(mod.param[0])
        elif mod.symbol == "{":
            bob.startPolygon()
        elif mod.symbol == "}":
            bob.endPolygon()
        elif mod.symbol == "'":
            bob.setColor(mod.param)

    #point the camera to the center of our drawing
    xcenter = 0
    ycenter = (turtleYmax + turtleYmin) / 2
    zcenter = 0
    scene.center = vector(xcenter, ycenter, zcenter)
    # draw a ground plane
    bob.drawGround(max(turtleXmax, turtleZmax) * 2)
    # set lighting
    scene.lights = []  # reset default lighting
    scene.ambient = color.gray(0.3)
    distant_light(direction=vector(0.22, 0.44, 0.88), color=color.gray(0.7))
    distant_light(direction=vector(-0.88, -0.22, -0.44), color=color.gray(0.3))
    distant_light(direction=vector(-0.22, -0.44, -0.88), color=color.gray(0.7))
    distant_light(direction=vector(0.88, 0.22, 0.44), color=color.gray(0.3))
    return 0
Esempio n. 14
0
 def drawGround(self, size):
     box(pos=vector(0, 0, 0),
         length=size,
         height=-size / 100,
         width=size,
         color=vector(10 / 255, 85 / 255, 0))
Esempio n. 15
0
 def setColor(self, rgb):
     self.currentColor = vector(rgb[0] / 255, rgb[1] / 255, rgb[2] / 255)
Esempio n. 16
0
     choice = int(user_input)
     print("Running case: ", choice)
 except ValueError:
     print("That is not a valid choice, try again: ")
     continue  #start again at the top of the while loop
 if choice == 0:  #shrub with leaves
     axiom = "A"
     productions = [
         "A?'(151,75,0) [ & F L ! A ] / / / / / '(151,75,0) [ & F L ! A ] / / / / / / / '(151,75,0) [ & F L ! A ]",
         "F?S / / / / / F", "S?F L",
         "L?[ '(12,102,0) ^ ^ { - f + f + f - | - f + f + f } ]"
     ]
     nrOfIterations = 7
     width = 1
     definitions = []
     tropismVector = vector(0, 0, 0)
     tropismStrength = 0
 elif choice == 1:  #simple tree 1
     axiom = "A(10,1)"
     productions = [
         "A(l,w)?!(w) F(l) [ &(a0) B(l*r2,w*wr) ] /(137.5) A(l*r1,w*wr)",
         "B(l,w)?!(w) F(l) [ -(a2) $ C(l*r2,w*wr) ] C(l*r1,w*wr)",
         "C(l,w)?!(w) F(l) [ +(a2) $ B(l*r2,w*wr) ] B(l*r1,w*wr)"
     ]
     nrOfIterations = 10
     width = 1
     definitions = [['r1', 0.9], ['r2', 0.6], ['a0', 45], ['a2', 45],
                    ['d', 137.5], ['wr', 0.707]]
     tropismVector = vector(0, 0, 0)
     tropismStrength = 0
 elif choice == 2:  #simple tree 2
Esempio n. 17
0
thetaI = 5 * pi / 180
thetaIp = 0
phiI = 15 * pi / 180
phiIp = 0
tI = 0
tf = 1000
n = 1000
t = linspace(tI, tf, n)
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.red,
                  make_trail=True)  #,trail_type="points")
pendulo2 = sphere(pos=vector(xp + l, yp, zp),
                  radius=r,
                  color=color.red,
                  make_trail=True)  #,trail_type="points")
#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.yellow)
cuerdas2 = cylinder(pos=pendulo2.pos,
Esempio n. 18
0
# coding: utf-8

from vpython import compound, color, vector, box, radians, rate


box1 = box(pos=vector(1, 0, 0), length=1, width=2, height=3, color=color.red)
box2 = box(pos=vector(5, 0, 0), length=1, width=2, height=3, color=color.blue)

bb = compound([box1, box2])
print(bb)
print(box2)

while True:
    rate(30)
    bb.rotate(axis=vector(1, 0, 0), angle=radians(2))
    # invalid for box1 and box2
            the radius of the drawn sphere

    returns:
    --------
        None

    outputs:
    --------
        draws a vpython cone for the given point
    """
    if radius == None:
        radius = point_dict["size"]/50

    if not isinstance(point_dict["coords"], vpy.vector):
        dict_to_vpy(point_dict)
    return vpy.cone(pos=point_dict["coords"],
                    color=point_dict["vpy_color"],
                    radius=radius,
                    axis=PUZZLE_COM-point_dict["coords"])


if __name__ == "__main__":
    canvas = vpy.canvas(background = vpy.vector(0.8,0.8,0.8),
                        up = vpy.vector(0,0,1),
                        forward = vpy.vector(-1,0,0))
    canvas.lights = []
    vpy.distant_light(direction = vpy.vector( 1, 1, 1), color = vpy.vector(0.7,0.7,0.7))
    vpy.distant_light(direction = vpy.vector(-1,-1,-1), color = vpy.vector(0.7,0.7,0.7))

    # draw_points(get_point_dicts("mixup cube points.ggb"))
    draw_points(get_point_dicts("rubiks cube points.ggb"))
Esempio n. 20
0
# coding: utf-8

from vpython import arrow, box, color, compound, radians, rate, vector

O = vector(0, 0, 0)
up = vector(1, 0, 0)
right = vector(0, 1, 0)
front = vector(0, 0, 1)

arrow(pos=O, axis=up, color=color.red)
arrow(pos=O, axis=right, color=color.green)
arrow(pos=O, axis=front, color=color.blue)

box1 = box(pos=O + vector(0, 10, 0),
           width=1,
           height=2,
           length=3,
           color=color.cyan,
           opacity=0.5)
box2 = box(pos=O + vector(0, -10, 0),
           width=1,
           height=2,
           length=3,
           color=color.cyan,
           opacity=0.5)

cb = compound([box1, box2])

while True:
    rate(30)
    cb.rotate(axis=up, angle=radians(2))
Esempio n. 21
0
import vpython as vp
import logging
from robot_imu import RobotImu
from robot_pose import robot_view

logging.basicConfig(level=logging.INFO)
imu = RobotImu()
robot_view()

accel_arrow = vp.arrow(axis=vp.vector(0, 1, 0))
x_arrow = vp.arrow(axis=vp.vector(1, 0, 0), color=vp.color.red)
y_arrow = vp.arrow(axis=vp.vector(0, 1, 0), color=vp.color.green)
z_arrow = vp.arrow(axis=vp.vector(0, 0, 1), color=vp.color.blue)

while True:
    vp.rate(100)
    accel = imu.read_accelerometer()
    print(f"Accelerometer: {accel}")
    accel_arrow.axis = accel.norm()
Esempio n. 22
0
Created on Thu Feb 11 13:58:34 2021

@author: Andrea Bassi
"""
import vpython as vp

from simple_oscillator_with_class import Oscillator


class Dumped_Oscillator(Oscillator):
    def __init__(self, k, m, beta, radius, length):
        super().__init__(k, m, radius, length)
        self.beta = beta

    def dump(self):
        self.acceleration += -self.beta * self.body.velocity / self.m


osc = Dumped_Oscillator(k=1, m=1, beta=0.1, radius=0.15, length=1)

osc.set_initial_conditions(vp.vector(1.5, 0, 0), vp.vector(0, 0, 0))

dt = 0.01 * 2 * vp.pi * vp.sqrt(osc.m / osc.k)

while True:
    vp.rate(100)
    osc.calculate_acceleration()
    osc.dump()
    osc.set_velocity(dt)
    osc.set_position(dt)
Esempio n. 23
0
from vpython import sphere, vector, sin, cos, rate, pi, cross, curve, color

B = vector(0, 0, 5e-4)
q = -1.6e-19
m = 9e-31

s = sphere(radius=2.0e-7)
t = 0  # seconds
dt = 1e-12  # seconds
s.velocity = vector(100, 0, 0)
trail = curve(color=color.blue, pos=s.pos)

while t < 3e-6:
    s.acceleration = q * cross(s.velocity, B) / m
    s.velocity += s.acceleration * dt
    s.pos += s.velocity * dt
    trail.append(s.pos)
    t = t + dt
    rate(4e-7 / dt)
Esempio n. 24
0
def drawPoints(points_list, rad = 0.1, color = vector(1,0,0)):
    PointList = []
    for pt in points_list:
        PointList.append(sphere(pos= pt , radius= rad, color = color))
Esempio n. 25
0
from vpython import sphere, vector, rate


def get_velocity(m, target):
    direction = target.r - m.r
    velocity = direction.norm() * 5
    return velocity


missiles = [
    sphere(pos=vector(0, 0, 0)),
    sphere(pos=vector(0, 100, 0)),
    sphere(pos=vector(100, 100, 0)),
    sphere(pos=vector(100, 0, 0))
]

t = 0
dt = 0.001

while t < 100:
    for i, m in enumerate(missiles):
        velocity = get_velocity(m, missiles[(i + 1) % 4])
        m.pos += velocity * dt
    t += dt
    rate(1 / dt)
def setup_display():
    scene = vp.canvas(x=0, y=0, width=400, height=400,
        userzoom=False, userspin=True, autoscale=False,
        center=vp.vector(0, 0, 0), foreground=vp.color.white, background=vp.color.black)

    return scene
Esempio n. 27
0
from vpython import sphere, vector, sin, cos, rate, pi

s = sphere()
t = 0  # seconds
dt = 0.001  # seconds
R = 10  # meters
omega = 3.14  # radians/second

s.pos = vector(R * cos(t * omega), R * sin(t * omega * 2), 0)
s.velocity = omega * R * vector(-sin(t * omega), cos(t * 2 * omega) * 2, 0)

while t < 100 * 2 * pi / omega:
    s.velocity = omega * R * vector(-sin(t * omega), cos(t * 2 * omega) * 2, 0)
    s.pos += s.velocity * dt
    t += dt
    rate(1 / dt)
def generate_fcc(cell, a, num_of_atoms=100):
    # Outer corners (back)
    cell.place_atom('Si', vp.vector(a / 2, a / 2., a / 2))
    cell.place_atom('Si', vp.vector(a / 2, -a / 2., a / 2))
    cell.place_atom('Si', vp.vector(-a / 2, a / 2, a / 2))
    cell.place_atom('Si', vp.vector(-a / 2, -a / 2, a / 2))

    # Outer corners (front)
    cell.place_atom('Si', vp.vector(a / 2, a / 2, -a / 2))
    cell.place_atom('Si', vp.vector(a / 2, -a / 2, -a / 2))
    cell.place_atom('Si', vp.vector(-a / 2, a / 2, -a / 2))
    cell.place_atom('Si', vp.vector(-a / 2, -a / 2, -a / 2))

    # Faces and center atom
    cell.place_atom('Si', vp.vector(a / 2, 0., 0.))
    cell.place_atom('Si', vp.vector(-a / 2, 0., 0.))
    cell.place_atom('Si', vp.vector(0., 0., -a / 2))
    cell.place_atom('Si', vp.vector(0., 0., 0.))
    cell.place_atom('Si', vp.vector(0., 0., a / 2))
Esempio n. 29
0
def angle_to_vpy(angle: float) -> vpython.vector:
    return vpython.vector(np.cos(angle), np.sin(angle), 0)
Esempio n. 30
0
    def __create_grid_objects(self):
        """
        Draw a grid along each 3D plane, that is closest to the camera.
        """
        # Create grid from 0,0,0 to positive directions with step sizes of the scale
        min_x_coord = 0
        max_x_coord = min_x_coord + round(self.__num_squares * self.__scale, 2)
        min_y_coord = 0
        max_y_coord = min_y_coord + round(self.__num_squares * self.__scale, 2)
        min_z_coord = 0
        max_z_coord = min_z_coord + round(self.__num_squares * self.__scale, 2)

        # Get all coords
        x_coords = arange(min_x_coord, max_x_coord + self.__scale,
                          self.__scale)
        y_coords = arange(min_y_coord, max_y_coord + self.__scale,
                          self.__scale)
        z_coords = arange(min_z_coord, max_z_coord + self.__scale,
                          self.__scale)

        # If the grid has given too many objects
        if len(x_coords) > self.__num_squares + 1:
            x_coords = x_coords[0:self.__num_squares + 1]
        if len(y_coords) > self.__num_squares + 1:
            y_coords = y_coords[0:self.__num_squares + 1]
        if len(z_coords) > self.__num_squares + 1:
            z_coords = z_coords[0:self.__num_squares + 1]

        # As curve objects cannot be compounded, so must be a single entity

        line_thickness = min(max(self.__scale / 25, 0.01), 2)  # 0.01 -> 5

        # Update curve objects
        self.grid_object.get('xy_plane').radius = line_thickness
        self.grid_object.get('xy_plane').append(vector(0, 0, 0))

        self.grid_object.get('xz_plane').radius = line_thickness
        self.grid_object.get('xz_plane').append(vector(0, 0, 0))

        self.grid_object.get('yz_plane').radius = line_thickness
        self.grid_object.get('yz_plane').append(vector(0, 0, 0))

        # Zig-Zag through all of the points
        # XY plane
        for idx, x_point in enumerate(x_coords):
            if idx % 2 == 0:
                y_vals = y_coords
            else:
                y_vals = y_coords[::-1]
            for y_point in y_vals:
                self.grid_object.get('xy_plane'). \
                    append(vector(x_point, y_point, 0))

        for idx, y_point in enumerate(y_coords[::-1]):
            if idx % 2 == 0:
                x_vals = x_coords[::-1]
            else:
                x_vals = x_coords
            for x_point in x_vals:
                self.grid_object.get('xy_plane'). \
                    append(vector(x_point, y_point, 0))

        # XZ Plane
        for idx, x_point in enumerate(x_coords):
            if idx % 2 == 0:
                z_vals = z_coords
            else:
                z_vals = z_coords[::-1]
            for z_point in z_vals:
                self.grid_object.get('xz_plane'). \
                    append(vector(x_point, 0, z_point))

        for idx, z_point in enumerate(z_coords[::-1]):
            if idx % 2 == 0:
                x_vals = x_coords[::-1]
            else:
                x_vals = x_coords
            for x_point in x_vals:
                self.grid_object.get('xz_plane'). \
                    append(vector(x_point, 0, z_point))

        # YZ Plane
        for idx, y_point in enumerate(y_coords):
            if idx % 2 == 0:
                z_vals = z_coords
            else:
                z_vals = z_coords[::-1]
            for z_point in z_vals:
                self.grid_object.get('yz_plane'). \
                    append(vector(0, y_point, z_point))

        for idx, z_point in enumerate(z_coords[::-1]):
            if idx % 2 == 0:
                y_vals = y_coords[::-1]
            else:
                y_vals = y_coords
            for y_point in y_vals:
                self.grid_object.get('yz_plane'). \
                    append(vector(0, y_point, z_point))
Esempio n. 31
0
    def vinit(self):
        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)

        self.vsphere = vpython.sphere(pos=vpython.vector(0, 0, 0),
                                      radius=1,
                                      color=vpython.color.blue,
                                      opacity=0.5)
        self.vearth = vpython.sphere(pos=vpython.vector(0, 0, 0),
                                     radius=0.1,
                                     color=vpython.color.cyan,
                                     opacity=0.5,
                                     emissive=True)
        self.vobserver = vpython.sphere(pos=vpython.vector(0, 0, 0),
                                        radius=0.01,
                                        color=vpython.color.yellow,
                                        opacity=0.5,
                                        emissive=True,
                                        make_trail=True)

        self.vstamp = vpython.label(pos=vpython.vector(0, 0, 0),
                                    text="",
                                    height=10,
                                    opacity=0.6,
                                    visible=False)
        self.vfixed_stars = [
            vpython.sphere(radius=0.01,
                           emissive=True,
                           color=vpython.color.white,
                           make_trail=False) for i in range(len(STAR_NAMES))
        ]

        self.vplanets = [
            vpython.sphere(radius=0.1, emissive=True, make_trail=False)
            for i in range(7)
        ]
        self.vplanets[0].color = vpython.color.yellow
        self.vplanets[1].color = vpython.color.white
        self.vplanets[2].color = vpython.color.blue
        self.vplanets[3].color = vpython.color.green
        self.vplanets[4].color = vpython.color.red
        self.vplanets[5].color = vpython.color.orange
        self.vplanets[6].color = vpython.color.gray(0.5)

        self.vqubits = [
            vpython.sphere(radius=0.1, emissive=True, make_trail=False)
            for i in range(3)
        ]
        self.veigs = [
            vpython.sphere(color=vpython.color.black,
                           radius=0.05,
                           emissive=True,
                           make_trail=False) for i in range(6)
        ]
        self.vlines = [
            vpython.curve(
                pos=[vpython.vector(0, 0, 0),
                     vpython.vector(0, 0, 0)]) for i in range(3)
        ]
        self.vlines[0].color = vpython.color.red
        self.vlines[1].color = vpython.color.green
        self.vlines[2].color = vpython.color.blue
Esempio n. 32
0
 def reorient(self):
     vpython.scene.forward = vpython.vector(-1, 0, 0)
     vpython.scene.up = vpython.vector(0, 1, 0)
     self.touched = True
QL, QV = Q.eigenstates()
N = qt.num(n)
NL, NV = N.eigenstates()
H = N + 1 / 2
U = (-1j * dt * H).expm()


def coherent(s):
    global n, a
    return np.exp(-s * np.conjugate(s) / 2) * (s * a.dag()).expm() * (
        -np.conjugate(s) * a).expm() * qt.basis(n, 0)


state = qt.basis(n, 0)
amps = [state.overlap(v) for v in QV]
vamps = [vp.arrow(pos=vp.vector(QL[i], 0, 0),\
       axis=vp.vector(amps[i].real, amps[i].imag, 0)) for i in range(n)]
vprobs = [vp.sphere(radius=0.1, color=vp.color.red,\
        pos=vp.vector(QL[i], 1+3*(amps[i]*np.conjugate(amps[i])).real, 0))\
      for i in range(n)]
vexp = vp.sphere(color=vp.color.yellow, radius=0.3,\
     pos=vp.vector(qt.expect(Q, state), 0, 0))

grid_pts = 20
grid = np.linspace(-10, 10, 20)
CS = [[coherent(x + 1j * y) for y in grid] for x in grid]
cs = [[state.overlap(CS[i][j]) for j in range(grid_pts)]
      for i in range(grid_pts)]
vcs = [[vp.arrow(pos=vp.vector(x, y+12, 0), color=vp.color.green,\
     axis=vp.vector(cs[i][j].real, cs[i][j].imag,0))
   for j, y in enumerate(grid)] for i, x in enumerate(grid)]
Esempio n. 34
0
File: ball.py Progetto: lgarcin/Math
'''
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
	k3 = h*f(r+0.5*k2, t+0.5*h)
	k4 = h*f(r+k3, t+h)
	r += (k1+2*k2+2*k3+k4)/6

	print(0.5*(t/len(pontstemp))*10000.0,"%")


#Preparando modo gráfico
#Realizando o modo gráfico
from vpython import sphere,canvas,color,vector,cylinder,box,helix,rate

#Configuração da janela
scene2 = canvas(title = "Simulação de órbitas caóticas", width = 600, height = 600,background=color.white)


esferabola1 = sphere(radius=7,pos=vector(x1,y1,0),color=color.yellow)
esferabola2 = sphere(radius=2,pos=vector(x2,y2,0),color=color.red)
esferabola3 = sphere(radius=2,pos=vector(x3,y3,0),color=color.blue)


cont = 0
T = len(pontstemp)
for k in range(T):

	esferabola1.pos = vector(posicaox1[k],posicaoy1[k],0.0)
	esferabola2.pos = vector(posicaox2[k],posicaoy2[k],0.0)
	esferabola3.pos = vector(posicaox3[k],posicaoy3[k],0.0)

	cont = cont + 1
	if (cont == 100):
		sphere(radius=1.0,pos=vector(posicaox2[k],posicaoy2[k],0),color=color.red)