def init_vpython(self):
        scene = canvas(title="Fans", width=self.win, height=self.win, x=0, y=0,
               center=vec(0, 0, 0), forward=vec(1,0,-1),
               up=self.up)
        scene.autoscale = False
        scene.range = 25

        h = 0.1
        mybox = box(pos=vec(0, 0, -h/2), length=self.L, height=h, width=L, up=self.up,
                    color=color.white)

        # create dust particles
        for pos in self.positions:
            p = sphere(pos=vec(*pos), radius=self.radius, color=color.red)
            p.update = True  # to determine if needs position update
            self.particles.append(p)
示例#2
0
    def create_vis(self, canvas=None):
        """
        Creates a visualisation. By default, uses a vpython canvas, so imports vpython.
        Subclass class and change this to change the way visualisations are made.
        Parameters
        ----------
        canvas: vpython canvas
            display into which the visualization is drawn
        """
        import vpython
        #self.scene stores the display into which the system draws
        if not canvas:
            if not self.scene:
                self.scene = vpython.canvas()
        if canvas:
            self.scene = canvas

        # Draw particles if they aren't drawn yet
        for particle in self.particles:
            if not particle._visualized:
                self.spheres.append(vpython.sphere(pos=vector_from(particle.pos),
                    radius=particle.radius,
                    color=vector_from(particle.color),
                    opacity=particle.alpha,
                    display=self.scene))
                particle._visualized = True
        # Draw springs if they aren't drawn yet
        for spring in self.springs:
            if not spring._visualized:
                self.helices.append(vpython.helix(pos=vector_from(spring.particle_1.pos),
                    axis=vector_from(spring.axis),
                    radius=spring.radius,
                    opacity=spring.alpha,
                    color=vector_from(spring.color),
                    display=self.scene))
                spring._visualized = True
        # Draw pointers if they aren't drawn yet
        for pointer in self.pointers:
            if not pointer._visualized:
                self.arrows.append(vpython.arrow(pos=vector_from(pointer.pos),
                    axis=vector_from(pointer.axis),
                    shaftwidth=pointer.shaftwidth,
                    opacity=pointer.alpha,
                    color=vector_from(pointer.color),
                    display=self.scene))
                pointer._visualized = True
h = 0.1
mybox = box(pos=vec(0, 0, -h/2), length=L, height=h, width=L, up=up, color=gray)

m = 1  # kg
radius = 0.5  # arbitrary for now
dt = 1e-3
start = vec(0, 0, radius)
v0 = vec(0, 0, 10)
g = vec(0, 0, -9.81)
Fg = m*g
particles =[]

for position, c in zip([start, start+vec(0, 3*radius, 0)],
                           [color.red, color.blue]):
    p = sphere(pos=position, radius=radius, color=c)
    p.v = v0
    p.update = True  # to determine if needs position update
    particles.append(p)


# In[ ]:

k = 1

while True:
    rate(500)
    
    # update position first
    for p in particles:
        if p.update:
示例#4
0
import math
import time

win = 700
scene = vpython.canvas(title="Moon's Orbit", width=win, height=win)
scene.lights = []
scene.ambient = vpython.color.gray(0.1)
sunlight = [
    vpython.distant_light(direction=v(-1, 0, 0), color=v(1.0, 1.0, 1.0)),
    vpython.distant_light(direction=v(-1, 0, 0), color=v(1.0, 1.0, 1.0)),
    vpython.distant_light(direction=v(-1, 0, 0), color=v(1.0, 1.0, 1.0))
]

starteaxis = v(1, 0, 0)
earth = vpython.sphere(texture=vpython.textures.earth,
                       up=v(0, 0, 1),
                       axis=starteaxis)
earth.pos = v(0, 0, 0)
earth.radius = 1.5
earth.rotperiod = 1.0

moon = vpython.sphere()
moon.radius = 0.5
moon.color = vpython.color.gray(0.3)
moon.a = 5  # Semi-major axis
moon.e = 0.0  # eccentricity of orbit (0=circle)
moon.pos = v(moon.a * (1 - moon.e), 0, 0)
startpos = v(moon.a * (1 - moon.e), 0, 0)

moon.sidperiod = 27.321661  # Sidereal Period (moon's 'year', in Earth days)
moon.rotperiod = 27.321661  # Length of the planets sidereal day, in Earth days
示例#5
0
def c_angles(pt):
    # Find theta 1
    t1 = arctan2(pt[1], pt[0])

    a = rpv_r / cos(pi/2-t1)
    b = rpv_r
    u = rpv_offset + rpv_r

    # Rotation matrix for the scan points
    r_z = array([[cos(-t1), -sin(-t1), 0],
                 [sin(-t1), cos(-t1), 0],
                 [0, 0, 1]])

    new_pt = zeros(3)

    new_pt[0] = dot(r_z, array([[pt[0]], [pt[1]], [pt[2]]]))[0]
    new_pt[1] = dot(r_z, array([[pt[0]], [pt[1]], [pt[2]]]))[1]
    new_pt[2] = dot(r_z, array([[pt[0]], [pt[1]], [pt[2]]]))[2]

    try:
        slope = - a * (new_pt[2] - u) / (b * sqrt(-new_pt[2] ** 2 + 2 * u * new_pt[2] - u ** 2 + b ** 2))
    except:
        print("Error with Slope")

    te = arctan(1 / slope)

    if (pi / 2 - arctan2(a5, a4)) <= te <= 0:
        print("Theta_extra :", round(rad2deg(te), 2))
        input("ERROR: Theta_extra is outside of range. Press Enter to continue...")

    # Find parameters to calculate j4 location
    h4 = cos(pi / 2 - te) * a4
    tp1 = te
    tp2 = pi / 2 - tp1

    h5 = sin(tp2) * a5

    r1 = sin(pi / 2 - te) * a4
    r2 = cos(tp2) * a5

    xj4 = pt[0] - cos(t1) * (r1 - r2)
    yj4 = pt[1] - sin(t1) * (r1 - r2)
    zj4 = pt[2] - (h4 + h5)

    j4_loc = array([xj4, yj4, zj4])

    vp.sphere(pos=vp.vector(j4_loc[0], j4_loc[1], j4_loc[2]), color=vp.color.red, radius=0.1)

    # Find joint 2 location
    j2_loc = array([cos(t1) * a1, sin(t1) * a1, 0])
    r = j4_loc - j2_loc  # Technically j4 -j2
    r_norm = linalg.norm(r)
    gamma_1 = arcsin(j4_loc[2] / r_norm)
    phi_2 = arccos((a2 ** 2 + r_norm ** 2 - a3 ** 2) / (2 * a2 * r_norm))
    t2 = phi_2 - gamma_1

    # Find theta 3
    t3 = arccos((a3 ** 2 + a2 ** 2 - r_norm ** 2) / (2 * a3 * a2)) - pi

    # Find theta 4
    r0_4 = array([[cos(t1), 0, -sin(t1)], [sin(t1), 0, cos(t1)], [0, -1, 0]])

    r0_3 = array([[-sin(t2) * sin(t3) * cos(t1) + cos(t1) * cos(t2) * cos(t3),
                   -sin(t2) * cos(t1) * cos(t3) - sin(t3) * cos(t1) * cos(t2), -sin(t1)],
                  [-sin(t1) * sin(t2) * sin(t3) + sin(t1) * cos(t2) * cos(t3),
                   -sin(t1) * sin(t2) * cos(t3) - sin(t1) * sin(t3) * cos(t2), cos(t1)],
                  [-sin(t2) * cos(t3) - sin(t3) * cos(t2), sin(t2) * sin(t3) - cos(t2) * cos(t3), 0]])

    inv_r0_3 = linalg.inv(r0_3)

    r3_4 = dot(inv_r0_3, r0_4)
    t4 = arccos(r3_4[0][0]) - te

    return t1, t2, t3, t4
示例#6
0
    plt.figure()
    for i in range(len(r[c, :]) // 2):
        plt.plot(time, r[:, i])
    plt.xlim(0, 20)
    #plt.ylim(0,.4)
    plt.show()

    return r, time, oscN


rs, t, Nosc = Numerical_DE(5, 0, 20, 1000)

from vpython import box, sphere, cylinder, color, vector, rate

radi = .105

balls = np.empty(Nosc, sphere)

displ = rs[:, :Nosc]

print(len(displ[0, :]))
for k in range(5):

    balls[k] = sphere(pos=vector(.75 * k, 0, 0), radius=radi, color=color.red)
while True:
    for x in range(len(displ[:, 0])):
        rate(100)
        for i, b in enumerate(balls):
            b.pos = vector(.75 * i - displ[x, i], 0, 0)
示例#7
0
import vpython as vp

initial_position = vp.vector(-1., 0., 0.)
initial_velocity = vp.vector(1., 0., 0.)
initial_position_2 = vp.vector(1., 0., 0)
initial_velocity_2 = vp.vector(1, 0, 0)
ball = vp.sphere(pos=initial_position,
                 radius=0.1,
                 color=vp.color.red,
                 make_trail=True,
                 trail_type='points')
ball_2 = vp.sphere(pos=initial_position_2,
                   radius=0.1,
                   color=vp.color.yellow,
                   make_trail=True,
                   trail_type='points')
animation_time_step = 0.1  # seconds
rate_of_animation = 1 / animation_time_step
time_step = 0.05
stop_time = 10.

time = 0.
while time < stop_time:
    vp.rate(rate_of_animation)
    x = initial_position.x + initial_velocity.x * time
    y = initial_position.y + initial_velocity.y * time
    z = initial_position.z + initial_velocity.z * time
    ball.pos = vp.vector(x, y, z)
    x = initial_position_2.x + initial_velocity_2.x * time
    y = initial_position_2.y + initial_velocity_2.y * time
    z = initial_position_2.z + initial_velocity_2.z * time
linkz_color = np.zeros((lattice_size,lattice_size,lattice_size), dtype=vector)

# Color and size the sites and links
color_sites(site_color, lattice_size)
color_links(linkx_color, linky_color, linkz_color, lattice_size)
size_sites(site_radii, lattice_size)
size_links(link_radii_x, link_radii_y, link_radii_z, lattice_size)


# Generate lattice
for i in range(lattice_size+1):
    for j in range(lattice_size+1):
        for k in range(lattice_size+1):
            op_factor = 6/((i+1)**op + (j+1)**op + (k+1)**op)
            sphere(pos=vector(i,j,k),
                    radius=site_radii[i-1,j-1,k-1],
                    color=site_color[i-1,j-1,k-1],
                    opacity=op_factor)

for i in range(lattice_size):
    for j in range(lattice_size):
        for k in range(lattice_size):
            op_factor = 6/((i+1)**op + (j+1)**op + (k+1)**op)
            cylinder(pos=vector(i,j,k),
                    axis=vector(1,0,0),
                    radius=link_radii_x[i,j,k],
                    color=linkx_color[i,j,k],
                    opacity=op_factor)
            cylinder(pos=vector(i,j,k),
                    axis=vector(0,1,0),
                    radius=link_radii_y[i,j,k],
                    color=linky_color[i,j,k],
示例#9
0
    theta_output.text = s.value


def get_length(s):
    length_output.text = s.value


# SET THE SCENE AND 3D OBJECTS
scene = vp.canvas(width=500,
                  height=400,
                  userspin=False,
                  userzoom=False,
                  title="Ideal Pendulum Simulation by haiq70",
                  autoscale=False,
                  center=vp.vector(0, -3, 0))
bob = vp.sphere(pos=vp.vector(0, -length, 0), radius=0.5)
string = vp.cylinder(pos=vp.vector(0, 0, 0),
                     axis=vp.vector(0, -length, 0),
                     radius=0.02)

# BUTTONS
vp.button(bind=start_button_clicked, text='Start')
vp.button(bind=pause_button_clicked, text='Pause')
scene.append_to_caption('\n\n')

# SLIDER (SPATIAL DEVIATION)
scene.append_to_caption("Spatial deviation: ")
slider_sd = vp.slider(min=0.1, max=90, bind=get_theta, step=0.1, value=5)
theta_output = vp.wtext(text=slider_sd.value)
scene.append_to_caption(" \u00b0 \n")
示例#10
0
from vpython import sphere, vector, color

# Constants
L = 2
R = 0.3

if __name__ == "__main__":
    for i in range(-L, L + 1):
        for j in range(-L, L + 1):
            for k in range(-L, L + 1):
                if ((i + j + k) % 2) == 0:
                    sphere(pos=vector(i, j, k), radius=R, color=color.blue)
                else:
                    sphere(pos=vector(i, j, k), radius=R, color=color.white)
示例#11
0
import vpython as vp

initial_position_1 = vp.vector(-10, 12, 1)
initial_velocity_1 = vp.vector(10, -12, -2)
ball_1 = vp.sphere(pos=initial_position_1,
                   radius=0.5,
                   color=vp.color.cyan,
                   make_trail=True)

initial_position_2 = vp.vector(-10, -5, -1)
initial_velocity_2 = vp.vector(14, 5, 2)
ball_2 = vp.sphere(pos=initial_position_2,
                   radius=0.5,
                   color=vp.color.yellow,
                   make_trail=True)

wall_center = vp.vector(0., 0., 0.)
wall_dimensions = vp.vector(0.25, 10., 10.)
wall = vp.box(pos=wall_center, size=wall_dimensions, color=vp.color.magenta)

animation_time_step = 0.01  # seconds
rate_of_animation = 1 / animation_time_step
time_step = 0.005
stop_time = 2

time = 0.
ball_velocity_1 = initial_velocity_1
ball_velocity_2 = initial_velocity_2
while time < stop_time:
    vp.rate(rate_of_animation)
    if ball_1.pos.x > wall.pos.x - 0.30:
示例#12
0
# =====================

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

xp = l * sin(phi1)  #Pasa de coordenadas polares a cartesianas
yp = -l * cos(phi1)
zp = 0.

xs = l * (sin(phi1) + sin(phi2))
ys = -l * (cos(phi1) + cos(phi2))
zs = 0.

sleeptime = 0.0001  #Tiempo con que se actualiza la posición de la partícula

prtcl = sphere(pos=vector(xp, yp, zp), radius=R,
               color=color.green)  #Primera esfera
prtcls = sphere(pos=vector(xs, ys, zs), radius=R,
                color=color.blue)  #Segunda esfera

time_i = 0  #Contador que se mueve en el espacio temporal en el que se resolvió la ecuación diferencial
t_run = 0  #Tiempo en el que se ejecuta la animación

#for i in omega:
#    print(i)

while t_run < t_final:  #ANIMACIÓN
    prtcl.pos = vector(l * sin(phi_1[time_i]), -l * cos(phi_1[time_i]), zp)
    prtcls.pos = vector(l * (sin(phi_1[time_i]) + sin(phi_2[time_i])),
                        -l * (cos(phi_1[time_i]) + cos(phi_2[time_i])), zs)
    t_run += t_delta
    sleep(sleeptime)
示例#13
0
    def __init__(self, planetDataList, maxTrailLength, planetObjectList):
        name = planetDataList[0]
        planetOrbitRadius = planetDataList[1]
        planetPeriod = planetDataList[2]
        # eccentricity = planetDataList[3]
        mass = planetDataList[4]
        sphereRadius = planetDataList[5]

        self.name = name
        self.sphereRadius = sphereRadius
        self.mass = mass
        self.lastPeriodEndTime = 0
        self.halfPeriodCounter = 1
        self.timeList = []
        self.positionList = []
        self.velocityList = []
        self.periodLengthList = []
        if self.name != 'Sun':
            # eccentricityModifier = planetOrbitRadius - (planetOrbitRadius * eccentricity)  # to include eccentricity, replace planetOrbitRadius on next line with eccentricityModifier. I do not believe this produces an accurate eccentricity, but it does make the orbit elliptical.
            initialVelocity = (2 * pi * planetOrbitRadius) / planetPeriod
            self.velocity = vector(0, initialVelocity, 0)
            self.position = vector(planetOrbitRadius, 0, 0)

            if self.name == 'Earth':
                self.sphere = sphere(pos=self.position,
                                     radius=self.sphereRadius,
                                     color=color.blue,
                                     make_trail=True,
                                     trail_color=color.cyan,
                                     retain=maxTrailLength,
                                     interval=traceInterval)
            elif self.name == 'Mars':
                self.sphere = sphere(pos=self.position,
                                     radius=self.sphereRadius,
                                     color=color.red,
                                     make_trail=True,
                                     trail_color=color.orange,
                                     retain=maxTrailLength,
                                     interval=traceInterval)
            elif self.name == 'Jupiter':
                self.sphere = sphere(pos=self.position,
                                     radius=self.sphereRadius,
                                     color=color.orange,
                                     make_trail=True,
                                     trail_color=color.red,
                                     retain=maxTrailLength,
                                     interval=traceInterval)
            elif self.name == 'Uranus':
                self.sphere = sphere(pos=self.position,
                                     radius=self.sphereRadius,
                                     color=color.blue,
                                     make_trail=True,
                                     trail_color=color.cyan,
                                     retain=maxTrailLength,
                                     interVal=traceInterval)
            else:
                self.sphere = sphere(pos=self.position,
                                     radius=self.sphereRadius,
                                     color=color.white,
                                     make_trail=True,
                                     trail_color=color.white,
                                     retain=maxTrailLength,
                                     interval=traceInterval)
        else:
            totalPlanetMomentum = vector(0, 0, 0)
            positionOffsetThing = 0
            for index in range(len(planetObjectList)):
                localPlanet = planetObjectList[index]
                totalPlanetMomentum = totalPlanetMomentum + (
                    localPlanet.mass * localPlanet.velocity)
                positionOffsetThing = positionOffsetThing + (
                    localPlanet.mass * localPlanet.position.x)
            sunPositionOffset = -positionOffsetThing / self.mass
            self.velocity = -totalPlanetMomentum / self.mass
            self.position = vector(sunPositionOffset, 0, 0)
            self.sphere = sphere(pos=self.position,
                                 radius=self.sphereRadius,
                                 color=color.yellow,
                                 make_trail=True,
                                 trail_color=color.yellow,
                                 retain=maxTrailLength,
                                 interval=traceInterval)
        self.lastStepSign = self.velocity.y / abs(self.velocity.y)

        if maxTrailLength == -2:
            self.sphere.make_trail = False
示例#14
0
t = linspace(t_start, t_final, n_steps)

solu, outodeint = odeint(func, initcond, t, args=(g, l), full_output=True)

theta, omega = solu.T

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

scene.range = 0.2  # m

xp = l * sin(thes)
yp = -l * cos(thes)
zp = 0.

sleeptime = 0.0001

prtcl = sphere(pos=vector(xp, yp, zp), radius=R, color=color.cyan)

time_i = 0
t_run = 0

#for i in omega:
#    print(i)

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

    t_run += t_delta
    time_i += 1
示例#15
0
 def visual(self):
     ball=vpy.sphere()
     for i in range(len(self.theta)):
         vpy.rate(100)
         ball.pos.x+=self.t[i]
         ball.pos.y+=self.theta[i]
示例#16
0
colors = [
    vpython.color.red, vpython.color.green, vpython.color.blue,
    vpython.color.yellow, vpython.color.cyan, vpython.color.magenta
]
poslist = []
plist = []
mlist = []
rlist = []

for i in range(Nstars):
    x = L * random.gauss(0, 1)
    y = L * random.gauss(0, 1)
    z = L * random.gauss(0, 1)
    d = math.sqrt(x**2 + y**2 + z**2)
    r = Rsun
    star = vpython.sphere(pos=v(x, y, z), radius=r, color=colors[i % 6])
    star.trail = vpython.curve(pos=[star.pos],
                               color=colors[i % 6],
                               radius=Rtrail)
    Stars.append(star)
    mass = Msun
    px = mass * vsun * (-1 + 2 * random.random()) * (1 - d / (1.7 * L))
    py = mass * vsun * (-1 + 2 * random.random()) * (1 - d / (1.7 * L))
    pz = mass * vsun * (-1 + 2 * random.random()) * (1 - d / (1.7 * L))
    poslist.append([x, y, z])
    plist.append([px, py, pz])
    mlist.append(mass)
    rlist.append(r)

pos = numpy.array(poslist)
p = numpy.array(plist)
as the speed of the orbits for convenience.

Jorge Bustos
Feb 17, 2019
"""

from __future__ import division, print_function
import vpython as vp
import numpy as np

c1 = 0.0029  #multiplier for the radius of the planets
c1_s = 0.00005  #multiplier for the radius of the Sun
c2 = 1000  #multiplier for time of the orbit animation

Sun = vp.sphere(pos=vp.vector(0, 0, 0),
                radius=c1_s * 695500,
                color=vp.color.yellow)
Mercury = vp.sphere(pos=vp.vector(57.9, 0, 0),
                    radius=c1 * 2440,
                    color=vp.color.cyan)
Venus = vp.sphere(pos=vp.vector(108.2, 0, 0),
                  radius=c1 * 6052,
                  color=vp.color.magenta)
Earth = vp.sphere(pos=vp.vector(149.2, 0, 0),
                  radius=c1 * 6371,
                  color=vp.color.blue)
Mars = vp.sphere(pos=vp.vector(227.9, 0, 0),
                 radius=c1 * 3386,
                 color=vp.color.red)
Jupiter = vp.sphere(pos=vp.vector(778.5, 0, 0),
                    radius=c1 * 69173,
示例#18
0
from vpython import vector
from copy import copy

kinetic = gcurve(color=color.blue)
potential = gcurve(color=color.red)
energy = gcurve(color=color.black)
thermal = gcurve(color=color.green)

m = 2  # kg
k = 4  # N/m
d = 2

t = 0
dt = 0.01  # s

s = sphere()
spring = helix(radius=0.6, thickness=0.3)

s.velocity = vector(-10, 0, 0)
s.pos = vector(10, 0, 0) * dt  # m
s.prev_pos = s.pos - s.velocity * dt  # m

thermal_energy = 0

while t < 12.0 * pi:
    kinetic_energy = 0.5 * m * dot(s.velocity, s.velocity)
    potential_energy = 0.5 * k * dot(s.prev_pos, s.prev_pos)
    thermal_energy += d * dot(s.velocity, s.velocity) * dt

    s.force = -k * s.pos - d * s.velocity + 3.0 * sin(1.0 * t) * vector(
        1, 0, 0)
示例#19
0
import vpython as vp

animation_time_step = 0.1  # seconds
rate_of_animation = 1 / animation_time_step
time_step = 0.05
stop_time = 10.

initial_position1 = vp.vector(-5, 0., 0.)
initial_velocity1 = vp.vector(1., 0., 0.)
ball1 = vp.sphere(pos=initial_position1,
                  radius=0.1,
                  color=vp.color.red,
                  make_trail=True,
                  trail_type="points",
                  trail_radius=0.1)

initial_position2 = vp.vector(0., -5., 0.)
initial_velocity2 = vp.vector(0., 1., 0.)
ball2 = vp.sphere(pos=initial_position2,
                  radius=0.1,
                  color=vp.color.cyan,
                  make_trail=True,
                  trail_type="points",
                  trail_radius=0.1)

time = 0.
while time < stop_time:
    vp.rate(rate_of_animation)
    x = initial_position1.x + initial_velocity1.x * time
    y = initial_position1.y + initial_velocity1.y * time
    z = initial_position1.z + initial_velocity1.z * time
示例#20
0
                height=450,
                title="Single Simple Pendulum",
                xtitle="x",
                ytitle="y",
                foreground=vp.color.black,
                background=vp.color.white,
                stereo="redcyan")

#
initial_position = vp.vector(-4, 0, 0)
initial_velocity = vp.vector(0, 0, 0)

# Define Ball/Blob
ball = vp.sphere(pos=initial_position,
                 radius=0.5,
                 color=vp.color.cyan,
                 opacity=0.8,
                 make_trail=True,
                 emissive=False)

# Define Rod
rod = vp.cylinder(pos=initial_position, axis=-ball.pos, radius=0.1)

# scene.autoscale = 0

ball.velocity = initial_velocity
ball.mass = 0.1

#scene.camera.follow(ball)

dt = 0.005
t = 0
示例#21
0
文件: main.py 项目: rbunger/Orbitrap
# mesh for the orbitrap

mesh = Orbitrap_mesh()
mesh.plot(-U_r, "inner")
mesh.plot(0.0, "outer")

# Leap-Frog time integration

w = sqrt((q / m) * k)  # omega
f = w / (2 * pi)
dt = 1 / f / kappa
I = zeros(N_t)
particle = sphere(pos=r,
                  radius=0.5e-3,
                  color=color.green,
                  make_trail=True,
                  retain=100)
v -= dt * (q / m) * E(particle.pos) / 2
for i in range(N_t):
    v += dt * (q / m) * E(particle.pos)
    particle.pos += dt * v
    I[i] = v.z / v_phi
    rate(50)

# spectral analysis

I_spec = fft(I)
m = zeros(N_t)
for i in range(1, N_t // 2):
    w = 2 * pi * i / (N_t * dt)
示例#22
0
vp.scene.width = 800


def eval_gravitational_force(p1: vp.sphere, p2: vp.sphere):
    G = 1
    r = p1.pos - p2.pos
    distance = vp.mag(r)
    rhat = r / distance
    force = -rhat * G * p1.mass * p2.mass / distance ** 2
    return force


star = vp.sphere(
    pos=vp.vector(0, 0, 0),
    radius=0.2,
    color=vp.color.yellow,
    mass=2.0 * 1000,
    momentum=vp.vector(0, 0, 0),
    make_trail=True,
)

planets = [
    vp.sphere(
        pos=vp.vector(1, 0, 0),
        radius=0.05,
        color=vp.color.green,
        mass=1,
        momentum=vp.vector(0, 30, 0),
        make_trail=True,
    ),
    vp.sphere(
        pos=vp.vector(0, 3, 0),
示例#23
0
def plot_vpython(network,
                 Psize='pore.diameter',
                 Tsize='throat.diameter',
                 Pcolor=None,
                 Tcolor=None,
                 cmap='jet',
                 **kwargs):
    r"""
    Quickly visualize a network in 3D using VPython.

    Parameters
    ----------
    network : GenericNetwork
        The network to visualize.
    Psize : str (default = 'pore.diameter')
        The dictionary key pointing to the pore property by which sphere
        diameters should be scaled
    Tsize : str (default = 'throat.diameter')
        The dictionary key pointing to the throat property by which cylinder
        diameters should be scaled
    Pcolor : str
        The dictionary key pointing to the pore property which will control
        the sphere colors.  The default is None, which results in a bright
        red for all pores.
    Tcolor : str
        The dictionary key pointing to the throat property which will control
        the cylinder colors.  The default is None, which results in a unform
        pale blue for all throats.
    cmap : str or Matplotlib colormap object (default is 'jet')
        The color map to use when converting pore and throat properties to
        RGB colors.  Can either be a string indicating which color map to
        fetch from matplotlib.cmap, or an actual cmap object.
    kwargs : dict
        Any additional kwargs that are received are passed to the VPython
        ``canvas`` object.  Default options are:

        *'height' = 500* - Height of canvas

        *'width' = 800* - Width of canvas

        *'background' = [0, 0, 0]* - Sets the background color of canvas

        *'ambient' = [0.2, 0.2, 0.3]* - Sets the brightness of lighting

    Returns
    -------
    canvas : VPython Canvas object
        The canvas object containing the generated scene. The object has
        several useful methods.

    Notes
    -----
    **Important**

    a) This does not work in Spyder. It should only be called from a
    Jupyter Notebook.

    b) This is only meant for relatively small networks. For proper
    visualization use Paraview.

    """
    import matplotlib.pyplot as plt

    try:
        from vpython import canvas, vec, sphere, cylinder
    except ModuleNotFoundError:
        raise Exception('VPython must be installed to use this function')

    if isinstance(cmap, str):
        cmap = getattr(plt.cm, cmap)

    if Pcolor is None:
        Pcolor = [vec(230 / 255, 57 / 255, 0 / 255)] * network.Np
    else:
        a = cmap(network[Pcolor] / network[Pcolor].max())
        Pcolor = [vec(row[0], row[1], row[2]) for row in a]

    if Tcolor is None:
        Tcolor = [vec(51 / 255, 153 / 255, 255 / 255)] * network.Nt
    else:
        a = cmap(network[Tcolor] / network[Tcolor].max())
        Tcolor = [vec(row[0], row[1], row[2]) for row in a]

    # Set default values for canvas properties
    if 'background' not in kwargs.keys():
        kwargs['background'] = vec(1.0, 1.0, 1.0)
    if 'height' not in kwargs.keys():
        kwargs['height'] = 500
    if 'width' not in kwargs.keys():
        kwargs['width'] = 800
    # Parse any given values for canvas properties
    for item in kwargs.keys():
        try:
            kwargs[item] = vec(*kwargs[item])
        except TypeError:
            pass
    scene = canvas(title=network.name, **kwargs)

    for p in network.Ps:
        r = network[Psize][p] / 2
        xyz = network['pore.coords'][p]
        c = Pcolor[p]
        sphere(pos=vec(*xyz), radius=r, color=c, shininess=.5)

    for t in network.Ts:
        head = network['throat.endpoints.head'][t]
        tail = network['throat.endpoints.tail'][t]
        v = tail - head
        r = network[Tsize][t]
        L = np.sqrt(np.sum((head - tail)**2))
        c = Tcolor[t]
        cylinder(pos=vec(*head),
                 axis=vec(*v),
                 opacity=1,
                 size=vec(L, r, r),
                 color=c)

    return scene
示例#24
0
    return (m_f)


def fza_vect(mag_fza, pos_1, pos_2):
    vect = mag_fza * vp.hat(pos_2 - pos_1)
    return (vect)


cond_ini(n, rango_masas, longitud, r_ini, v_ini, m_ini)

r = [r_ini]
v = [v_ini]
m = [m_ini]

#objetos:
planetas = [vp.sphere(pos=i, radius=0.5) for i in r[0]]
orbitas = []

for i, j in zip(planetas, masas):
    i.masa = j  #<--- agregamos masa al objeto

#for i in planetas:                                 #
#trail_i = vp.curve(color = vp.vector(1,0,0))   # ->  esto habilitarlo si quiero todos
#orbitas.append(trail_i)                        #

trail_i = vp.curve(color=vp.vector(1, 0, 0))  #
orbitas.append(trail_i)  # -> pa solo 1.

#fin objetos

########################################################hacer esto para alterar una masa a placer:
示例#25
0
 def __setstate__(self, stuff):
     self.__dict__ = stuff
     self.vsphere = vp.sphere(color=self.color,\
                              radius=self.radius)
示例#26
0
for i in range(1, num_pts):
    scan_pts[0][i] = (inc * cos(scan_angle) + scan_pts[0][i - 1]) * 1
    scan_pts[1][i] = (inc * sin(scan_angle) + scan_pts[1][i - 1]) * 1
    scan_pts[2][i] = -(sqrt(rpv_r ** 2 - scan_pts[1][i] ** 2) - h)

vp.scene.camera.pos = vp.vector(scan_pts[0][num_pts - 1], scan_pts[1][num_pts - 1], scan_pts[2][num_pts - 1])

# Loop through scan points
for j in range(num_pts):
    j2, j3, j4, pvt, ee = c_jpos(scan_pts[:, j])
    t1, t2, t3, t4 = c_angles(scan_pts[:, j])

    # Check if end effector is in the scan location
    if round(float(scan_pts[0, j]), 4) != round(float(ee[0]), 4) or round(float(scan_pts[1, j]), 4) != round(
            float(ee[1]), 4) or round(float(scan_pts[2, j]), 4) != round(float(ee[2]), 4):
        print("ERROR POSITION %2.2f %2.2f %2.2f" % (ee[0], ee[1], ee[2]))

    # Print the calculated results
    print("%2.2f %2.2f %2.2f %2.2f %2.2f %2.2f %2.2f %2.2f %2.2f %2.2f " % (
        scan_pts[0, j], scan_pts[1, j], scan_pts[2, j], rad2deg(t1), rad2deg(t2),
        rad2deg(t3), rad2deg(t4), ee[0], ee[1], ee[2]))

    # Visual Python: Show scan points in green and the manipulator as a grey curve
    vp.sphere(pos=vp.vector(scan_pts[0, j], scan_pts[1, j], scan_pts[2, j]), color=vp.color.green, radius=0.1)

    vp.curve(
        pos=[(0, 0, 0), (j2[0], j2[1], j2[2]), (j3[0], j3[1], j3[2]), (j4[0], j4[1], j4[2]),
             (pvt[0], pvt[1], pvt[2]), (ee[0], ee[1], ee[2])], radius=0.05)
    time.sleep(.02)
示例#27
0
scene.width = 1200  # Ajustando a largura da cena
scene.height = 1000  # Ajustando a altura da cena
scene.camera.pos = vector(2, -1, 2)
scene.camera.axis = vector(-2, 1, -2)

suporte = box(pos=vector(.0, .05, .0),
              up=vector(.0, 1., .0),
              length=2,
              height=.1,
              width=2,
              texture=textures.wood)  # Suporte

mola = helix(pos=vector(0, 0, 0),
             axis=vector(*r_vrl),
             color=color.yellow,
             radius=.03)  # Mola do pendulo

bola = sphere(axis=vector(*r_vrl), radius=.1, make_trail=True)  # Bola

# Constantes

C = 1.

while t <= b:
    rate(C / h)
    mola.axis = vector(*r_vrl)
    bola.pos = vector(*r_vrl)
    r_vrl, v_vrl, vpm = passo_vrl(f, r_vrl, v_vrl, vpm, t, h)
    t += h
示例#28
0
    myLabel = myText[myLine].strip()
    myLabels.append(myLabel)
    myLine += 1
    myConceptLoopCounter += 1
print("myConceptCount is ", myConceptCount)
print("Labels are ", myLabels)
myNormalize()
a = vp.canvas(
    title='Simple Galileo Viewer by Rob Zimmelman c. 2018 All Rights Reserved',
    width=1400,
    height=700,
    background=vp.color.black)
myBox = vp.box(length=200, width=200, height=0.01, opacity=0.5)
for i in range(0, myConceptCount):
    print(i, x[i], y[i], z[i])
    a = vp.sphere(pos=vp.vector(xNorm[i], yNorm[i], zNorm[i]),
                  color=vp.color.red,
                  radius=1.0)
    b = vp.label(text=myLabels[i],
                 pos=vp.vector(xNorm[i], yNorm[i], zNorm[i]),
                 color=vp.color.yellow,
                 box=True,
                 line=True,
                 xoffset=75,
                 yoffset=15,
                 radius=12.0)
    c = vp.arrow(pos=vp.vector(xNorm[i], 0, zNorm[i]),
                 color=vp.color.blue,
                 shaftwidth=0.25,
                 axis=vp.vector(0, yNorm[i], 0))
示例#29
0
t = linspace(t_start, t_final, n_steps)#arreglo de diferencial de tiempo

solu, outodeint = odeint( 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 = 1 # 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) #Definimos la esfera

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( ll[time_i]*sin(theta[time_i]), -ll[time_i]*cos(theta[time_i]), zp )
    t_run += t_delta
    time_i += 1
	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)
示例#31
0
    r += (k1 + 2 * k2 + 2 * k3 + k4) / 6

# plot(tpoints, theta1_points,'b')
# plot(tpoints, theta2_points, 'g')
# plot(tpoints, energy_points)
# xlabel('t (s)')
# ylabel('energy (J)')
# show()

# Make animation
rod1 = cylinder(pos=vector(0, 0, 0),
                axis=vector(l * cos(theta1_0 - pi / 2),
                            l * sin(theta1_0 - pi / 2), 0),
                radius=l / 40)
bob1 = sphere(pos=vector(l * cos(theta1_0 - pi / 2),
                         l * sin(theta1_0 - pi / 2), 0),
              radius=l / 10)
rod2 = cylinder(pos=vector(l * cos(theta1_0 - pi / 2), l * sin(theta1_0 - pi / 2), 0), \
                axis=vector(l * cos(theta2_0 - pi / 2), l * sin(theta2_0 - pi / 2), 0), radius=l/40)
bob2 = sphere(pos=vector(l * cos(theta2_0 - pi / 2),
                         l * sin(theta2_0 - pi / 2), 0),
              radius=l / 10)

for i in range(N):
    rate(N // 100)
    vector1 = vector(l * cos(theta1_points[i] - pi / 2),
                     l * sin(theta1_points[i] - pi / 2), 0)
    vector2 = vector(l * cos(theta2_points[i] - pi / 2),
                     l * sin(theta2_points[i] - pi / 2), 0)
    rod1.axis = vector1
    bob1.pos = vector1
示例#32
0
    "masa_anillo": 1,
}

dt = 0.01
t_max = 10
t = 0
ka = 1

Particulas_libres = []
Particulas_anillo = []
#posiciones de discretizacion del anillo
for i in range(cond_ini["num_parts_anillo"]):
    p_0 = (cond_ini["radio_anillo"]) * vp.vector(
        np.cos((2 * np.pi * i) / (cond_ini["num_parts_anillo"])),
        np.sin((2 * np.pi * i) / (cond_ini["num_parts_anillo"])), 0)
    part_i = vp.sphere(pos=p_0, radius=0.3, color=vp.vector(1, 1, 1))
    part_i.carga = cond_ini["carga_anillo"]
    part_i.momento = vp.vector(0, 0, 0)
    Particulas_anillo.append(part_i)
#partículas dentro
for i in range(cond_ini["num_parts_dentro"]):
    r_part = np.linspace(0, cond_ini["radio_anillo"] * 0.75, 100)
    theta_part = np.linspace(0, 2 * np.pi, 100)
    r_i = rand.choice(r_part)
    theta_i = rand.choice(theta_part)
    p_0 = r_i * (vp.vector(np.cos(theta_i), np.sin(theta_i), 0))
    part_i = vp.sphere(pos=p_0, radius=0.3, color=vp.vector(1, 0, 1))
    #pa vels
    vel_part = np.linspace(cond_ini["v_min"], cond_ini["v_max"], 100)
    vel_i = vp.vector(rand.choice(vel_part), rand.choice(vel_part), 0)
    part_i.vel = vel_i
示例#33
0
#initialize the position array:
r = np.array([th0, om0], float)
# RK4 algorithm
for t in tp:
    thp.append(r[0])
    omp.append(r[1])
    k1 = h * f(r, t)
    k2 = h * f(r + 0.5 * k1, t + 0.5 * h)
    k3 = h * f(r + 0.5 * k2, t + 0.5 * h)
    k4 = h * f(r + k3, t + h)
    r += (k1 + 2 * k2 + 2 * k3 + k4) / 6

mp.title('Phasee Portrait of a Pendulum')
mp.plot(thp, omp)
mp.xlabel(r'Angle $(Rads)$')
mp.ylabel(r'Angular Velocity $(\frac{Rads}{s})$')
mp.show()

# make animation
rod = cylinder(pos=vector(0, 0, 0),
               axis=vector(l * np.cos(th0 - pi / 2), l * np.sin(th0 - pi / 2),
                           0),
               radius=l / 40)
bob = sphere(pos=vector(l * np.cos(th0 - pi / 2), l * np.sin(th0 - pi / 2), 0),
             radius=l / 10)
for theta in thp:
    rate(N // 10)
    rod.axis = vector(l * np.cos(theta - pi / 2), l * np.sin(theta - pi / 2),
                      0)
    bob.pos = vector(l * np.cos(theta - pi / 2), l * np.sin(theta - pi / 2), 0)
示例#34
0
文件: ball.py 项目: 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
示例#35
0
import vpython as vp
import serial
import time
from math import *
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=3)
print(ser.name)
scene = vp.canvas()
scene.background = vp.color.gray(.2)
head_main = vp.ellipsoid(pos=vp.vector(0, .85, 0),
                         length=1.3,
                         width=1.3,
                         height=1.7,
                         color=vp.vector(.9, .7, .5))
left_eye = vp.sphere(pos=vp.vector(-.25, 1, .5),
                     radius=.15,
                     color=vp.vector(0, 0, 0))
right_eye = vp.sphere(pos=vp.vector(.25, 1, .5),
                      radius=.15,
                      color=vp.vector(0, 0, 0))
head = vp.compound([head_main, left_eye, right_eye])
for i in range(5):
    print(ser.readline())

old_theta = 0
old_phi = 0

while 1:
    read = ser.readline().decode("utf-8").split()
    x = float(read[1])
    y = float(read[3])
    z = float(read[5])