Пример #1
0
def draw_graph_lagrange():
    # przygotowanie wykresu
    gd = graph(title='Interpolacja Lagrange\'a')
    f1 = gcurve(graph=gd, color=color.cyan)
    dots = gdots(graph=gd, color=color.red)
    f2 = gcurve(graph=gd, color=color.green)

    # tablica do przechowywania wylosowanych punktów
    initial_points = []

    # zmienna pomocnicza używana przy losowaniu punktów wielomianu
    index = 0

    # wyliczanie wartości funkcji podstawowej w tym przypadku cos(2*x) * exp(-0.2 * x)
    field_end = 8.05
    for x in arange(0, field_end, 0.1):
        y = cos(2 * x) * exp(-0.2 * x)
        f1.plot(x, y)

        #losowanie punktów do wyliczania interpolacji - odbywa kiedy x znajduje się w przedziale 1..field_end-1
        if 1 < x <= field_end - 1 and index % 2 == 0 and bool(getrandbits(1)):
            initial_points.append({'x': x, 'y': y})
            dots.plot(x, y)
        index = index + 1

    # wyliczanie i rysowanie interpolacji
    for point in lagrange_interpolation(initial_points, field_end):
        f2.plot(point['x'], point['y'])
Пример #2
0
def count():
    # algroytm działa także dla innych wielkości kwadratu r=a/2
    r = 0.5
    gd = graph(ymin=0, ymax=2 * r + 0.5, xmin=0, xmax=2 * r + 0.5)
    f1 = gcurve(graph=gd, color=color.cyan)
    f2 = gcurve(graph=gd, color=color.cyan)
    dots = gdots(graph=gd, color=color.red, radius=2)

    for x in arange(0, 2 * r + 0.001, 0.01):
        f1.plot(x, circle_point_lower(x, r))
        f2.plot(x, circle_point_upper(x, r))

    points_count = randrange(200, 300)
    ok_points = 0
    while x <= points_count:
        x = x + 1
        point = draw_point(2 * r)
        dots.plot(point[0], point[1])
        if circle_point_upper(point[0], r) >= point[1] >= circle_point_lower(
                point[0], r):
            ok_points = ok_points + 1

    field = ok_points / points_count
    pi = field / (r**2)
    f1.label = 'pi = ' + str(pi)
    f2.label = 'field = ' + str(field)
    gd.height = 450
    gd.width = 450
Пример #3
0
def main():

    parameters = {
        "birth_rate": 0.00,
        "death_rate": 0.00,
        "rate_of_transmission": 0.00004,
        "rate_of_incubation": 1,
        "rate_of_recovery": 1 / 14,
        "rate_of_loss_of_immunity": 0.00003,
        "rate_of_vaccination": 0,
        "rate_of_treatment": 0
    }

    pop_susceptible = 50000000  # number susceptible: Not yet infected.
    pop_exposed = 500000  # number exposed
    pop_infectious = 200  # number infected: Ongoing disease.
    pop_recovered = 100  # number recovered: Gained immunity, isolated, or dead.
    vector_population = [
        pop_susceptible, pop_exposed, pop_infectious, pop_recovered
    ]

    # Create graphs.
    s_plot = vpython.gcurve(color=vpython.color.blue, label="% susceptible")
    i_plot = vpython.gcurve(color=vpython.color.red, label="% infected")
    r_plot = vpython.gcurve(color=vpython.color.green, label="% recovered")
    e_plot = vpython.gcurve(color=vpython.color.orange, label="% exposed")

    time = 0
    tmax = 1000
    dt = 0.1

    while time < tmax:
        # Use RK4 method to determine the new vector_population.
        k1 = derivs(time, vector_population, parameters)
        k2 = derivs(time + dt / 2, add(vector_population, mult(k1, 0.5)),
                    parameters)
        k3 = derivs(time + dt / 2, add(vector_population, mult(k2, 0.5)),
                    parameters)
        k4 = derivs(time + dt, add(vector_population, k3), parameters)
        vector_population = add(
            vector_population,
            mult(
                add(
                    mult(k1, 1 / 6),
                    add(mult(k2, 1 / 3), add(mult(k3, 1 / 3),
                                             mult(k4, 1 / 6)))), dt))
        print(vector_population)

        # plot using vpython
        vpython.rate(50)  # fps of graph up§te
        s_plot.plot(time, vector_population[0])
        e_plot.plot(time, vector_population[1])
        i_plot.plot(time, vector_population[2])
        r_plot.plot(time, vector_population[3])

        time += dt
Пример #4
0
def init_graphs():
    vpython.graph(
        title="Energy of Earth's Orbit",
        xtitle="Time (days)",
        ytitle="Energy (J)",
        fast=False,
    )
    return {
        "potential": vpython.gcurve(color=vpython.color.blue, width=2),
        "kinetic": vpython.gcurve(color=vpython.color.red, width=2),
        "total": vpython.gcurve(color=vpython.color.magenta, width=2),
    }
Пример #5
0
def draw_graph(start, end, n=10):
    f1 = gcurve(graph=graph(title='Metoda trapezów'), color=color.cyan)

    for i in arange(start, end + 0.001, 0.01):
        x = round(i, 3)
        f1.plot(x, integral_function(x))

    f1.label = 'field = ' + str(2 * integral(start, end, n))
Пример #6
0
def init_graph():
    vpython.graph(
        title="Ball on a Spring",
        xtitle="Time (s)",
        ytitle="Displacement (m)",
        fast=False,
    )
    return vpython.gcurve(color=vpython.color.red, width=2)
    def plot_supplimentary_information(self):
        self.plots = True
        atom_position_graph = vp.graph(title='Absolute Displacement of Red Atom', 
                                       xtitle=r't [s]', ytitle=r'|r(t)-vector| [m]', fast=True,
                                       legend=True)
        atom_velocity_graph = vp.graph(title='Absolute Speed of Red Atom', xtitle=r't [s]', ytitle=r'|r(t)-dot-vector| [m/s]', fast=True, 
                                       legend=True)
        atom_phasespace     = vp.graph(title='Phase space of Red Atom', ytitle=r'|r(t)-vector| [m]', fast=True, 
                                       legend=True, xtitle=r'|r(t)-dot-vector| [m/s]')
        label_constant = "Spring Constant: {} N/m"
        self.atom_position_points = vp.gcurve(graph=atom_position_graph, color=vp.color.red, size=0.1, 
        label=label_constant.format(self.atom_list[0].force_constant))
        
        self.atom_velocity_points = vp.gcurve(graph=atom_velocity_graph, color=vp.color.blue, size=0.1, 
            label=label_constant.format(self.atom_list[0].force_constant))

        self.atom_phasespace_points = vp.gcurve(graph=atom_phasespace, color=vp.color.green, size=0.1, 
            label=label_constant.format(self.atom_list[0].force_constant))
Пример #8
0
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, 3),
                      foreground=vp.color.white,
                      background=vp.color.black)

    vp.arrow(pos=vp.vector(0, 0, 0), axis=vp.vector(10, 0, 0), shaftwidth=0.3)
    vp.arrow(pos=vp.vector(0, 0, 0), axis=vp.vector(0, 10, 0), shaftwidth=0.3)

    plt_x = vp.gcurve(color=vp.color.red, size=2)
    plt_y = vp.gcurve(color=vp.color.red, size=2)

    return scene, plt_x, plt_y
Пример #9
0
def newton_czybyszew(nodes_amount):
    gd = graph(title='Interpolacja Newtona\'a')
    f1 = gcurve(graph=gd, color=color.cyan)
    dots = gdots(graph=gd, color=color.red)
    f2 = gcurve(graph=gd, color=color.green)

    # wyliczanie wartości funkcji podstawowej w tym przypadku cos(2*x) * exp(-0.2 * x)
    field_end = 8.05
    for x in arange(0, field_end, 0.1):
        y = origin_newton_function(x)
        f1.plot(x, y)

    # tablica do przechowywania wylosowanych punktów
    initial_points = []
    for x in czybyszew_points(nodes_amount, 0, field_end):
        y = origin_newton_function(x)
        dots.plot(x, y)
        initial_points.append({'x': x, 'y': y})

    # wyliczanie i rysowanie interpolacji
    for point in newton_interpolation(initial_points, field_end):
        f2.plot(point['x'], point['y'])
def draw_function_average(start, end, tries=200):
    g = graph(title='Metoda próbkowania średniej')
    f1 = gcurve(graph=g, color=color.cyan)
    dots = gdots(graph=g, color=color.red)

    points = count_points(start, end)
    for point in points['points']:
        f1.plot(point)

    sampling = average_sampling(start, end, tries)
    for point in sampling['points']:
        dots.plot(point)

    f1.label = '2 * wartość całki= ' + str(2 * sampling['value'])
Пример #11
0
def init_beads(nbeads):
    beads = []
    for i in range(nbeads):
        theta_start = 180 * DEG * (i + 0.5) / nbeads
        bead = vpython.sphere(
            pos=vpython.vector(wire_x(theta_start), wire_y(theta_start), 0),
            radius=0.1 * WHEEL_RADIUS,
            color=COLORS[i],
        )
        # Use the bead object to keep track of all the dead's data, not just
        # the visual stuff.
        bead.v = vpython.vector(0, 0, 0)
        bead.graph = vpython.gcurve(color=COLORS[i], width=2)
        beads.append(bead)
    return beads
Пример #12
0
def _make_plot(theta, display_width, display_height):
    """ Makes the VPython graph.

    :return: The graph object.
    """

    graph(width=display_width / 2 - 10,
          height=display_height,
          background=color.white,
          align='right',
          xtitle='Time (s)',
          ytitle='Angle (\u00b0)')
    f = gcurve(color=color.red, dot=True, interval=100)
    f.plot(0, math.degrees(theta))
    return f
def draw_function_simple(start, end, tries=200):
    g = graph(title='Metoda prostego próbkowania')
    f1 = gcurve(graph=g, color=color.cyan)
    dots = gdots(graph=g, color=color.red)

    points = count_points(start, end)
    for point in points['points']:
        f1.plot(point)

    correct_points = 0

    for _ in range(0, tries):
        point = draw_point(start, end - start)
        dots.plot(point)
        if point[1] <= integral_function(point[0]):
            correct_points = correct_points + 1

    # max_val jest największą wartością funkcji,
    # odpowiada zmiennej H która musi być większa od f(x) dlatego koryguję o 0.1
    p_gross = count_gross_field(end - start, points['max_val'] + 0.0001)
    p = correct_points / tries * p_gross

    f1.label = '2 * wartość całki= ' + str(2 * p)
    dots.label = 'pole całkowite= ' + str(p_gross)
Пример #14
0
def plotCurveXY(x, y):
    stage = vp.canvas()
    f1 = vp.gcurve(color=vp.color.blue)
    for n in range(y.shape[0]):
        f1.plot(pos=(x[n], y[n]))
Пример #15
0
import vpython as vp
from robot_imu import RobotImu, ImuFusion
from delta_timer import DeltaTimer
import imu_settings

imu = RobotImu(gyro_offsets=imu_settings.gyro_offsets,
               mag_offsets=imu_settings.mag_offsets)
fusion = ImuFusion(imu)

vp.graph(xmin=0, xmax=60, scroll=True)
graph_pitch = vp.gcurve(color=vp.color.red)
graph_roll = vp.gcurve(color=vp.color.green)
graph_yaw = vp.gcurve(color=vp.color.blue)

timer = DeltaTimer()
while True:
    vp.rate(100)
    dt, elapsed = timer.update()
    fusion.update(dt)
    graph_pitch.plot(elapsed, fusion.pitch)
    graph_roll.plot(elapsed, fusion.roll)
    graph_yaw.plot(elapsed, fusion.yaw)
Пример #16
0
import vpython as vp
import logging
import time
from robot_imu import RobotImu

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


pr = vp.graph(xmin=0, xmax=60, scroll=True)
graph_pitch = vp.gcurve(color=vp.color.red, graph=pr)
graph_roll = vp.gcurve(color=vp.color.green, graph=pr)

xyz = vp.graph(xmin=0, xmax=60, scroll=True)
graph_x = vp.gcurve(color=vp.color.orange, graph=xyz)
graph_y = vp.gcurve(color=vp.color.cyan, graph=xyz)
graph_z = vp.gcurve(color=vp.color.purple, graph=xyz)

start = time.time()
while True:
    vp.rate(100)
    elapsed = time.time() - start
    pitch, roll = imu.read_accelerometer_pitch_and_roll()
    raw_accel = imu.read_accelerometer()
    graph_pitch.plot(elapsed, pitch)
    graph_roll.plot(elapsed, roll)
    print(f"Pitch: {pitch:.2f}, Roll: {roll:.2f}")
    graph_x.plot(elapsed, raw_accel.x)
    graph_y.plot(elapsed, raw_accel.y)
    graph_z.plot(elapsed, raw_accel.z)
Пример #17
0
Xmax = 40.
Xmin = 0.25
step = 0.1
order = 10
start = 50

graph1 = vp.display(width=500,
                    height=500,
                    title="Spherical Bessel \
    L=1 (red) 10",
                    xtitle="x",
                    xmin=Xmin,
                    xmax=Xmax,
                    ymin=0.2,
                    ymax=0.5)
funct1 = vp.gcurve(color=color.red)
funct2 = vp.gcurve(color=color.green)


def down(x, n, m):  # Recursion woo!
    """
    Moving downward in the pyramidal method 
    we apply the Bessel equation to find the  
    range of the Bessel function
    """
    j = np.zeros((start + 2), float)  # initialize zeros
    j[m + 1] = j[m] = 1  # iterate the next element of j as 1
    for k in range(m, 0, 01):
        j[k - 1] = (
            (2 * k + 1) / x) * j[k] - j[k + 1]  # apply the iterative procedure
    scale = (np.sin(x) / x) / j[0]  # scale the j array appropriately
Пример #18
0
def optimized_animate_TRod(y, dt, rb):
    """ Animates RigidBody's vpython object (optimized version).

    TODO: To finally optimize, make sure vp.rate is consistent with real time and make sure to only display
    results needed. Exclude non-displayed results that are left out because of frame-rate."""
    frame_rate = dt**-1

    rb.create_vpython_object()
    animation_graph = vp.graph(scroll=True,
                               fast=True,
                               xmin=-5,
                               xmax=5,
                               ymin=-2.5,
                               ymax=2.5)
    omega1_plot = vp.gcurve(color=vp.color.red)
    omega2_plot = vp.gcurve(color=vp.color.green)
    omega3_plot = vp.gcurve(color=vp.color.blue)
    plot_interval = 1
    t = 0
    tot_axes = len(rb.R)
    omegas1 = y[:, 0].copy()
    omegas2 = y[:, 1].copy()
    omegas3 = y[:, 2].copy()
    np_axes = y[:, 3:12].copy()
    np_axes = np_axes.reshape((len(np_axes), 3, 3))
    vp_axes = []

    for R in np_axes:
        vp_R = []
        for axis in R:
            vp_R.append(vp.vector(*axis))
        vp_axes.append(vp_R)

    for k in range(len(y)):
        vp.rate(frame_rate)  # set framerate

        omega1 = omegas1[k]
        omega2 = omegas2[k]
        omega3 = omegas3[k]
        R = vp_axes[k]

        # Plot curves.
        if not k % plot_interval:  # Ex: If plot_interval = 3, only plot every 3rd point.

            omega1_plot.plot(t, omega1)
            omega2_plot.plot(t, omega2)
            omega3_plot.plot(t, omega3)

        t += dt

        # Loop over axes and rotate object and arrows.
        # Rotate x_arrow
        old_length = rb.vp_object_axes[0].length
        rb.vp_object_axes[0].axis = R[0]
        rb.vp_object_axes[0].length = old_length

        # Rotate y_arrow
        old_length = rb.vp_object_axes[1].length
        rb.vp_object_axes[1].axis = R[1]
        rb.vp_object_axes[1].length = old_length

        # Rotate z_arrow
        old_length = rb.vp_object_axes[2].length
        rb.vp_object_axes[2].axis = R[2]
        rb.vp_object_axes[2].length = old_length

        # # Rotation version (don't use both axis-setting and rotation)
        # rb.vp_object.rotate(angle=omega1*dt, axis=R[0])
        # rb.vp_object.rotate(angle=omega2*dt, axis=R[1])
        # rb.vp_object.rotate(angle=omega3*dt, axis=R[2])

        # Axis-setting version (don't use both axis-setting and rotation)
        rb.vp_object.axis = R[0]
        rb.vp_object.up = R[1]

        # Update angular momentum arrows.
        L = rb.I_body @ np.array(
            (omega1, omega2,
             omega3))  # Do this calc. outside loop for better optimization.
        L /= np.linalg.norm(L) * 1 / 5
        L_x = np.zeros(3)
        L_x[0] = L[0]
        L_y = np.zeros(3)
        L_y[1] = L[1]
        L_z = np.zeros(3)
        L_z[2] = L[2]
        rb.L_arrow.axis = vp.vector(*L)
        rb.L_components[0].axis = vp.vector(*L_x)
        rb.L_components[1].axis = vp.vector(*L_y)
        rb.L_components[
            1].pos = rb.L_components[0].pos + rb.L_components[0].axis
        rb.L_components[2].axis = vp.vector(*L_z)
        rb.L_components[
            2].pos = rb.L_components[1].pos + rb.L_components[1].axis
Пример #19
0
import vpython as vp
import time
from robot_imu import RobotImu
import imu_settings

imu = RobotImu(gyro_offsets=imu_settings.gyro_offsets)

vp.graph(xmin=0, xmax=60, ymax=360, ymin=-360, scroll=True)
graph_x = vp.gcurve(color=vp.color.red)
graph_y = vp.gcurve(color=vp.color.green)
graph_z = vp.gcurve(color=vp.color.blue)

start = time.time()
while True:
    vp.rate(100)
    elapsed = time.time() - start
    gyro = imu.read_gyroscope()
    print(f"Gyro x: {gyro.x:.2f}, y: {gyro.y:.2f}, z: {gyro.z:.2f}")
    graph_x.plot(elapsed, gyro.x)
    graph_y.plot(elapsed, gyro.y)
    graph_z.plot(elapsed, gyro.z)
    vector(-d, d, -d),
    vector(-d, d, d),
    vector(d, d, d),
    vector(d, d, -d),
    vector(-d, d, -d)
])
vert1 = curve(color=gray, radius=r)
vert2 = curve(color=gray, radius=r)
vert3 = curve(color=gray, radius=r)
vert4 = curve(color=gray, radius=r)
vert1.append([vector(-d, -d, -d), vector(-d, d, -d)])
vert2.append([vector(-d, -d, d), vector(-d, d, d)])
vert3.append([vector(d, -d, d), vector(d, d, d)])
vert4.append([vector(d, -d, -d), vector(d, d, -d)])

grafico0 = gcurve(color=color.cyan)
grafico1 = gcurve(color=color.red)

#campionamento temporale
dt = 0.005

t = 0

while t < 2:

    rate(50)

    #controlla se ci sono collisioni con il polline
    for particella in particelle:
        distance = mag(particella.pos - polline.pos)
        if distance < particella.radius + polline.radius:
Пример #21
0
ball.velocity = initial_velocity
ball.mass = 0.1

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

dt = 0.005
t = 0
T = 20
# k = 10
k = lambda t: np.sin(t)
d = 4
g = -9.81 * 0
drag_coefficient = 0.001 * 0

# A plot
kinetic = vp.gcurve(color=vp.color.blue)

while t < T:
    vp.rate(100)
    relative_displacement = rod.length - d
    ball_force = -k(t) * relative_displacement * ball.pos.norm()
    ball_force.y += g
    ball_force -= drag_coefficient * ball.velocity.mag**2 * ball.velocity.norm(
    )
    acceleration = ball_force / ball.mass
    ball.velocity += acceleration * dt
    kinetic_energy = 0.5 * ball.mass * ball.velocity.mag**2
    kinetic.plot(t, kinetic_energy)
    ball.pos += ball.velocity * dt
    rod.pos = ball.pos
    rod.axis = -ball.pos
Пример #22
0
from vpython import box, sphere, color, vector, rate, dot, graph, gcurve
import copy

ground = box(color=color.red, size=vector(22, 1, 1), pos=vector(0, -1.5, 0))
top = box(color=color.red, size=vector(22, 1, 1), pos=vector(0, 19.5, 0))
left = box(color=color.red, size=vector(1, 22, 1), pos=vector(-11, 9, 0))
right = box(color=color.red, size=vector(1, 22, 1), pos=vector(11, 9, 0))

energy = gcurve()
potential = gcurve(color=color.blue)
kinetic = gcurve(color=color.red)

dt = 0.1

g = 9.8
s = sphere()
s.pos = vector(-7, 10, 0)
#s.velocity = vector(5, 19.2, 0)
s.velocity = vector(0, 0, 0)
s.prev_pos = s.pos - (s.velocity * dt)
s.accel = vector(0, -g, 0)
s.mass = 2.0

t = 0

while t < 10:

    kinetic_energy = 0.5 * s.mass * dot(s.velocity, s.velocity)
    potential_energy = s.mass * 9.8 * dot(s.pos, vector(0, 1, 0))
    kinetic.plot(pos=(t, kinetic_energy))
    potential.plot(pos=(t, potential_energy))
Пример #23
0
import vpython as vp
from robot_imu import RobotImu
from delta_timer import DeltaTimer
import imu_settings

imu = RobotImu(mag_offsets=imu_settings.mag_offsets)

vp.graph(xmin=0, xmax=60, scroll=True)
graph_yaw = vp.gcurve(color=vp.color.blue)
timer = DeltaTimer()

while True:
    vp.rate(100)
    dt, elapsed = timer.update()
    mag = imu.read_magnetometer()
    yaw = -vp.degrees(vp.atan2(mag.y, mag.x))
    graph_yaw.plot(elapsed, yaw)
Пример #24
0
"""When running,
use VPYTHON_PORT=9020 VPYTHON_NOBROWSER=true"""
import vpython as vp
import time
import logging
from robot_imu import RobotImu

logging.basicConfig(level=logging.INFO)
imu = RobotImu()
vp.graph(xmin=0, xmax=60, scroll=True)
temp_graph = vp.gcurve()
start = time.time()
while True:
    vp.rate(100)
    temperature = imu.read_temperature()
    logging.info("Temperature {}".format(temperature))
    elapsed = time.time() - start
    temp_graph.plot(elapsed, temperature)
Пример #25
0
def main():
    box_size = 10
    box_thickness = 1
    ball_radius = 0.5
    # Set the axis of each side to be a perpendicular unit vector pointing into
    # the box. That'll allow us to handle all the walls in a loop, rather than
    # spelling them out
    axes = [
        vpython.vector(1, 0, 0),
        vpython.vector(-1, 0, 0),
        vpython.vector(0, 1, 0),
    ]
    box_sides = []
    for axis in axes:
        side = vpython.box(
            pos=-0.5 * box_size * axis,
            axis=axis,
            height=box_size,
            width=box_size,
        )
        box_sides.append(side)

        vpython.arrow(
            pos=-0.5 * box_size * axis,
            axis=axis,
            color=vpython.color.blue,
        )

    # Initial position chosen randomly inside the box
    x0 = vpython.vector(
        random.random() * box_size - 0.5 * box_size,
        random.random() * box_size - 0.5 * box_size,
        0,
    )
    # Initial velocity small enough that we should not escape
    v_max = math.sqrt(-2 * GRAVITY * (0.5 * box_size - x0.y))
    v0 = vpython.vector(
        random.random() * v_max,
        random.random() * v_max,
        0,
    )
    # Initialize the ball. Python also lets us attach an extra attribute, in
    # this case velocity, to the ball object.
    ball = vpython.sphere(
        pos=x0,
        color=vpython.color.red,
        radius=ball_radius,
    )
    ball.v = v0
    ball.m = 1
    # Set up the graph pane and each curve we want in it
    vpython.graph(
        title="Ball in a Box",
        xtitle="Time (s)",
        ytitle="Energy (J)",
        fast=False,
    )
    graph_pot = vpython.gcurve(color=vpython.color.blue,
                               width=2,
                               label="Potential Energy")
    graph_kin = vpython.gcurve(color=vpython.color.red,
                               width=2,
                               label="Kinetic Energy")
    graph_tot = vpython.gcurve(color=vpython.color.magenta,
                               width=2,
                               label="Total Energy")
    # Time loop! Handle gravity and collisions
    t, dt, tmax = 0, 0.001, 10
    while t < tmax:
        t += dt
        vpython.rate(1 / dt)
        dvdt = -GRAVITY * vpython.vector(0, -1, 0)
        ball.v += dvdt * dt
        ball.pos += ball.v * dt
        # Check for collisions
        for side in box_sides:
            # Vector from the center of the ball to the center of the wall
            center_to_center = ball.pos - side.pos
            # Project onto the wall's perpendicular unit vector to get distance
            distance = center_to_center.dot(side.axis)
            # If it's a collision, flip the component of the ball's velocity
            # that's perpendicular to the wall
            if distance < (ball.radius + 0.5 * box_thickness):
                dv = -2 * side.axis.dot(ball.v)
                ball.v += side.axis * dv
        energy_pot = -ball.m * GRAVITY * ball.pos.y
        energy_kin = 0.5 * ball.m * ball.v.dot(ball.v)
        graph_pot.plot(t, energy_pot)
        graph_kin.plot(t, energy_kin)
        graph_tot.plot(t, energy_pot + energy_kin)
    return
            self._amp = delta


# create oscillator instance
osc = oscillator(RADIUS, initial_position, initial_velocity)

time = 0

vp.graph(scroll=True,
         fast=False,
         xmin=0,
         xmax=50,
         xtitle='times(s)',
         ytitle='delta (m)')

g0 = vp.gcurve()
#g1 = vp.gcurve(color = vp.color.red)

while True:

    vp.rate(100)

    # add elastic force
    delta = osc.mass.pos - rest_position
    elastic_force = -(K * delta) / M

    # add fluid resistance
    dumping_force = -B * osc.mass.velocity

    # add external force oscillating at angular frequency omega
    external_force = F0 * np.cos(omega * time) * vp.vector(1, 0, 0)
Пример #27
0
    return Rnew, Vnew

# compute net force
def force(R, V, mass):
    return mass*G - 0.0*mass*V

# visualization stuff
#scene = vp.canvas(title='3D scene', center = vp.vector(0.0, 0.0, 0.0))
scene = vp.canvas(title='Parabolic motion')
scene.autoscale = True
ball = vp.sphere(pos=vp.vector(R0[0], R0[1], R0[2]), radius=0.01, color=vp.color.cyan) 
ball.velocity = vp.vector(V0[0], V0[1], V0[2])
vscale = 0.02
varr = vp.arrow(pos=ball.pos, axis=vscale*ball.velocity, color=vp.color.yellow)
ball.trail = vp.curve(color=ball.color)
ypos = vp.gcurve(color=vp.color.cyan, dot=True)
yvel = vp.gcurve(color=vp.color.red, dot=True)

# initial conditions
Y = np.zeros(NSTEPS); VY = np.zeros(NSTEPS) # To save only Y coordinates, as function of time
Y[0] = R0[1]; VY[0] = V0[1]
R = R0; V = V0 ; F = force(R, V, MASS) # Value which changes at each time step
V = start_integration(V, F, MASS, DT) # Move Velocity from 0 to -dt/2

# main evolution loop
it = 1
while it < NSTEPS:
    F = force(R, V, MASS)
    R, V = integration(R, V, F, MASS, DT)
    Y[it] = R[1]; VY[it] = V[1]
    if R[1] < 0:
Пример #28
0
import random
import vpython as vp

"""
Spontaneous decay simulation using "sys.stdout.write("\a")" so that we hear an alert each time there is a decay.
"""

# initialize the parameters
lambda1 = 0.001
max = 200
time_max = 500
seed = random.seed(18203)
number = nloop = max

graph1 = vp.gdisplay(width=1000, height=1000, title="Spontaneous Decay", xtitle="Time",
            ytitle="Number left", xmax=500, xmin=0, ymax=300, ymin=0)

decayfunction = vp.gcurve(color=color.green)

# decay that atom yo
for time in range(0, time_max+1):
    # time loop
    for atom in ranger(1, number+1)
        decay = random.random()
        if decay < lambda1:
            nloop = nloop - 1 # Decay occurs
            sys.stdout.write("\a")
    number = nloop
    decayfunction.plotpos=(time,number)
    rate(30)
import vpython

e_graph = vpython.gcurve(color=vpython.color.blue)


def gforce(p1, p2):
    # Calculate the gravitational force exerted on p1 by p2.
    G = 1  # Change to 6.67e-11 to use real-world values.
    # Calculate distance vector between p1 and p2.
    r_vec = p1.pos - p2.pos
    # Calculate magnitude of distance vector.
    r_mag = vpython.mag(r_vec)
    # Calcualte unit vector of distance vector.
    r_hat = r_vec / r_mag
    # Calculate force magnitude.
    force_mag = G * p1.mass * p2.mass / r_mag**2
    # Calculate force vector.
    force_vec = -force_mag * r_hat

    return force_vec


def main():

    star = vpython.sphere(pos=vpython.vector(0, 0, 0),
                          radius=0.2,
                          color=vpython.color.yellow,
                          mass=1.0 * 1000,
                          momentum=vpython.vector(0, 0, 0),
                          make_trail=True)
    planet_one = vpython.sphere(pos=vpython.vector(1, 0, 0),
Пример #30
0
v0x = v0 * np.cos(angle * np.pi / 180)
v0y = v0 * np.sin(angle * np.pi / 180)
T = 2 * v0y / g  # time
H = v0y * voy / (2 * g)  # height (vertical distance)
R = 2 * v0x * v0y / g  # horizontal distance

graph1 = vp.gdisplay(
    title="Projectile width (red)/without (yellow) Air Resistance",
    xtitle="x",
    ytitle="y",
    xmax=R,
    xmin=-R / 20,
    ymax=8,
    ymin=-6.0)

funct1 = vp.gcurve(color=color.red)
funct1 = vp.gcurve(color=color.yellow)

print("Frictionless T = " + str(T))
print("Frictionless H = " + str(H))
print("Frictionless R = " + str(R))


def plotNumeric(k):
    """
    Plot the numeric solution to the projectile using individual values 
    for each variable. 
    """
    vx = v0 * np.cos(angle * np.pi / 180)
    vy = v0 * np.sin(angle * np.pi / 180)
    x = 0