Beispiel #1
0
def set_scene(r):   # r = position of test body
    vp.display(title='Restricted 3body', background=(1,1,1))
    body = vp.sphere(pos=r, color=(0,0,1), radius=0.03, make_trail=1)
    sun = vp.sphere(pos=(-a,0), color=(1,0,0), radius=0.1)
    jupiter = vp.sphere(pos=(b, 0), color=(0,1,0), radius=0.05)
    circle = vp.ring(pos=(0,0), color=(0,0,0), thickness=0.005,
                     axis=(0,0,1), radius=1)      # unit circle
    return body
Beispiel #2
0
def Ch3_Uses():
	print '-------------------- 3.1 Graphs ---------------------------\n'
	#simple plot
	plt.figure(facecolor="white")
	x = [0.5, 1.0, 2.0, 4.0, 7.0, 10.0]
	y = [1.0, 2.4, 1.7, 0.3, 0.6, 1.8]
	plt.plot (x,y,'ro-')
	plt.show()
	
	#two plots with legends and different colors
	plt.figure(facecolor="white")
	x = linspace(0,12.56,100) #linspace takes three arguments initial and final value and the number of divisions
	y = sin(x)
	z = cos(x)
	plt.plot(x,y,'g-',label = 'sin x')
	plt.plot(x,z,'ro',label = 'cos x')
	#colors allowed by python are r,g,b,c,m,y,k,w for red, green,blue,cyan,magenta,yellow,black,white
	#Styles are -,o,--,s,* for solid line, dots, dash line, squares, stars,
	plt.ylim(-1.1,1.1)
	plt.xlim(-0.5,13)
	plt.xlabel('from 0 to 4pi')
	plt.ylabel('Trigonometric functions')
	plt.title('la verdad')
	leg = plt.legend()
	plt.show()
	
	plt.figure(facecolor="white")
	data = loadtxt("alltxt/ch3-1.txt",float)
	x = data[:,0]
	y = data[:,1]
	plt.plot(x,y)
	plt.show()
	
	print '------------------- 3.2 Scatter --------------------------\n'
	print '------------------- 3.3 Density --------------------------\n'
	plt.figure(facecolor="white")
	data = loadtxt("cpresources/circular.txt",float)
	plt.imshow(data,origin='lower')
	#plt imshow()
	plt.colorbar()
	plt.show()
	
	print '------------------- 3.4 3D Graphics --------------------------\n'
	sphere()
	sphere(radius=0.5, pos=[1.0,-0.2,0.0])
	sphere(color = color.green)
	s = empty(10,sphere)
	for n in range(10):
		s[n]= sphere()
		d = display(background = color.blue)
		display(autoscale=False)#set the automatic zoom off
		
	print '------------------- 3.5 Animations --------------------------\n'
	s = sphere(pos=[0,0,0])
	s.pos = [1,4,3]
	
	return 'done'
Beispiel #3
0
def set_scene(R, r):        # create bodies, velocity arrows
    vp.display(title='Three-body motion', background=(1,1,1))
    body, vel = [], []      # bodies, vel arrows
    c = [(1,0,0), (0,1,0), (0,0,1), (0,0,0)]    # RGB colors
    for i in range(3):
        body.append(vp.sphere(pos=r[i],radius=R,color=c[i],make_trail=1))
        vel.append(vp.arrow(pos=body[i].pos,shaftwidth=R/2,color=c[i]))
    line, com = vp.curve(color=c[3]), vp.sphere(pos=(0,0), radius=R/4.)
    return body, vel, line
Beispiel #4
0
def set_scene(R, r):  # create bodies, velocity arrows
    vp.display(title='Three-body motion', background=(1, 1, 1))
    body, vel = [], []  # bodies, vel arrows
    c = [(1, 0, 0), (0, 1, 0), (0, 0, 1), (0, 0, 0)]  # RGB colors
    for i in range(3):
        body.append(vp.sphere(pos=r[i], radius=R, color=c[i], make_trail=1))
        vel.append(vp.arrow(pos=body[i].pos, shaftwidth=R / 2, color=c[i]))
    line, com = vp.curve(color=c[3]), vp.sphere(pos=(0, 0), radius=R / 4.)
    return body, vel, line
    def __init__(self, npts=100000, Rotate=False, title=''):
        ptsize = 3
        mapptsize = 1
        self.scene_angle = 0
        self.localscene = visual.display(title=title + ' Local Coordinate System')
        self.globalscene = visual.display(title=title + ' Global Coordinate System')
        #self.globalscene.background = (1, 1, 1)
        #self.globalscene.up = (0, 0, 1)
        #self.globalscene.forward = (0, 1, -0.4)
        self.currentrow = 0

        self.auto_colour = False

        # Set up the global coordinate frame visualiser
        self.globalscene.select()

        self.globalscene.up =(0, 0, 1.0)

        #self.visualrobot = visual.box(length=3, height=2, width=1.5)
        w = 1
        wid = 0.2
        self.robotpts = np.array(( (0, -wid, 0, w), (0, wid, 0, w), (3*wid, 0, 0, w), (0, -wid, 0, w) ))
        #self.visualrobot = visual.points(pos=self.robotpts[:, :3], size=4, shape='round', color=(0, 1, 1))
        self.visualrobot = visual.curve(pos=self.robotpts[:, :3], color=(0, 1, 1))

        X = np.array([(-1, -1), (-1, 1), (1, 1), (1, -1), (-1, -1)])
        square = visual.curve(pos=50*X)
        self.leftmappts = visual.points(size=ptsize, shape='square', color=(1, 0, 0))
        self.rightmappts = visual.points(size=ptsize, shape='square', color=(0, 1, 0))
        self.spinmappts = visual.points(size=ptsize, shape='square', color=(0, 0, 1))
        X = np.zeros((npts, 3))
        self.mappts = visual.points(pos=X, size=mapptsize, shape='square', color=(1, 1, 1))
        self.trajpts_ind = 0
        self.trajpts = visual.points(pos=np.zeros((10000, 3)), color=(0, 0, 1), size=2)
        visual.scene.show_rendertime = True

        if Rotate:
            # Enable continuous rotation
            RV = RotateVisual(self.globalscene)
            RV.start()
        else:
            # Enable mouse panning
            MT = dispxyz.EnableMouseThread(self.globalscene)
            MT.start()

        # Set up the local coordinate frame visualiser
        if showlocal:
            self.localscene.select()
            self.leftpts = visual.points(color=(1, 0, 0), size=ptsize, shape='square')
            self.rightpts = visual.points(color=(0, 1, 0), size=ptsize, shape='square')
            self.spinpts = visual.points(color=(0, 0, 1), size=ptsize, shape='square')
            visual.scene.show_rendertime = True
        
        self.colourmin = -4
        self.colourmax = 4
def visualize(flow_grid, input_grid):
    """
    Visualize the flow in flow_grid on input_grid with VPython, using gray 
    squares for blocked spaces (input_grid[i][j] = 1) and blue squares for
    spaces with flow (flow_grid[i][j] = '*').

    All objects in the scene will be removed prior to drawing.  The active 
    scene will be used.

    >>> visualize([['*','*',1],['*',1,1],['*',1,1]], [[0,0,1],[0,1,1],[0,0,1]])
    """
    from visual import box, display

    blue = (0, 0, 1)
    gray = (.5, .5, .5)
    black = (0.3, 0.3, 0.3)

    size = len(input_grid)
    total_size = size * size
    disp = display.get_selected()  # gets the active display
    if disp is None:  # no display, so create one
        display(title="Percolation", autocenter=True)
    else:  # display exists, empty it
        disp.autocenter = True  # autocenter for convenience
        # We only need to delete these boxes if there is a mismatch in the
        # number of boxes versus the number of grid cells. We assume that no
        # other objects are on the scene.
        if total_size != len(disp.objects):
            for object in disp.objects:
                object.visible = False  # make all objects in display invisible

    # redraw all of the grid, because of the size mismatch
    if total_size != len(disp.objects):
        for row in range(size):
            for col in range(size):
                # for blocked spaces, draw a gray box
                if input_grid[row][col] == 1:
                    box(pos=(col, -row, 0), color=gray)
                # for spaces with flow, draw a blue box
                elif flow_grid[row][col] != -1:
                    box(pos=(col, -row, 0), color=blue)
                else:
                    box(pos=(col, -row, 0), color=black)
    # or just change the colors, based on the grids given
    else:
        for object in disp.objects:
            x, y, _ = object.pos
            x, y = int(x), int(y)
            if flow_grid[-y][x] != -1:
                object.color = blue
            elif input_grid[-y][x] == 1:
                object.color = gray
            else:
                object.color = black
Beispiel #7
0
def set_scene(r):  # r = position of test body
    vp.display(title='Restricted 3body', background=(1, 1, 1))
    body = vp.sphere(pos=r, color=(0, 0, 1), radius=0.03, make_trail=1)
    sun = vp.sphere(pos=(-a, 0), color=(1, 0, 0), radius=0.1)
    jupiter = vp.sphere(pos=(b, 0), color=(0, 1, 0), radius=0.05)
    circle = vp.ring(pos=(0, 0),
                     color=(0, 0, 0),
                     thickness=0.005,
                     axis=(0, 0, 1),
                     radius=1)  # unit circle
    return body
def visualize(flow_grid, input_grid):
    """
    Visualize the flow in flow_grid on input_grid with VPython, using gray 
    squares for blocked spaces (input_grid[i][j] = 1) and blue squares for
    spaces with flow (flow_grid[i][j] = '*').

    All objects in the scene will be removed prior to drawing.  The active 
    scene will be used.

    >>> visualize([['*','*',1],['*',1,1],['*',1,1]], [[0,0,1],[0,1,1],[0,0,1]])
    """
    from visual import box, display

    blue = (0, 0, 1)
    gray = (.5, .5, .5)
    black = (0.3, 0.3, 0.3)

    size = len(input_grid)
    total_size = size * size
    disp = display.get_selected()       # gets the active display
    if disp is None:                    # no display, so create one
        display(title="Percolation", autocenter=True)
    else:                               # display exists, empty it
        disp.autocenter = True          # autocenter for convenience
        # We only need to delete these boxes if there is a mismatch in the
        # number of boxes versus the number of grid cells. We assume that no
        # other objects are on the scene.
        if total_size != len(disp.objects):
            for object in disp.objects:
                object.visible = False  # make all objects in display invisible

    # redraw all of the grid, because of the size mismatch
    if total_size != len(disp.objects):
        for row in range(size):
            for col in range(size):
                # for blocked spaces, draw a gray box
                if input_grid[row][col]==1:
                    box(pos=(col, -row, 0), color=gray)
                # for spaces with flow, draw a blue box
                elif flow_grid[row][col]!=-1:
                    box(pos=(col, -row, 0), color=blue)
                else:
                    box(pos=(col, -row, 0), color=black)
    # or just change the colors, based on the grids given
    else:
        for object in disp.objects:
            x, y, _ = object.pos
            x, y = int(x), int(y)
            if flow_grid[-y][x] != -1:
                object.color = blue
            elif input_grid[-y][x] == 1:
                object.color = gray
            else:
                object.color = black
Beispiel #9
0
def PrintPath(x,p):
	q = st[x]
	q = q + (end,)
	mat = [col*['.'] for r in range(row)]
	r,c = cell(q[len(q)-1])
	mat[r][c] = 'E'
	r,c = cell(q[0])
	mat[r][c] = 'S'
	for i in range(1,len(q)-1):
		r,c = cell(q[i])
		mat[r][c] = '#'
	visual.display(row,col,mat)
Beispiel #10
0
def setup_scene(fullscreen):
  '''
  Sets up the scene for the display output.
  '''
  # Set title and background color (white)
  scene = visual.display(title="Robot Simulation",background=(1,1,1))
  # Automatically center
  scene.autocenter = True
  # Removing autoscale
  scene.autoscale = 0
  # Set whether the windows will take up entire screen or not
  scene.fullscreen = fullscreen
  # Size of the windows seen is the size of one beam (to begin)
  scene.range = (BEAM['length'],BEAM['length'],BEAM['length'])
  # The center of the windows exists at the construction location
  scene.center = helpers.scale(.5,helpers.sum_vectors(
    CONSTRUCTION['corner'],scene.range))
  # Vector from which the camera start
  scene.forward = (1,0,0)
  # Define up (used for lighting)
  scene.up = (0,0,1)
  # Defines whether or not we exit the program when we exit the screen
  # visualization
  scene.exit = False

  return scene
Beispiel #11
0
def PlotSphereEvolution3(f):
  data = json.loads(open(f, "r").read())

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

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

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

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

  nt = 0
  while True:
    vs.rate(60)
    for i in range(data["SpheresNumber"]):
      spheres[i].pos = (data["Data"][0][nt][i], data["Data"][1][nt][i], data["Data"][2][nt][i])
    if nt + 1 >= data["SavedSteps"]:
      nt = 0
    else:
      nt += 1
Beispiel #12
0
def PlotSpheres3(f):
  data = json.loads(open(f, "r").read())

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

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

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

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

  while True:
    vs.rate(60)
Beispiel #13
0
def show_protective(nparticles):
    # create scene
    scene = visual.display(title='Protective zones', width=600, height=400, center=(0,0,0))
    scene.select()

    # read in positions, state and protective zones
    positions = (numpy.genfromtxt('position.dat'))[:nparticles]
    state = (numpy.genfromtxt('state.dat'))[:nparticles]
    zones = (numpy.genfromtxt('fpt.dat'))[:nparticles]

    # go through particles and display them
    for i in range(nparticles):
        # color the spheres according to state
        cball = visual.color.green

        if (state[i,0]==1):
            cball = visual.color.red
        else:
            cball = visual.color.blue

        if (state[i,3]==1):
            cball = visual.color.yellow
            
        if (state[i,3]==2):
            cball = visual.color.orange

        visual.sphere(pos=(positions[i,0], positions[i,1], positions[i,2]), radius=zones[i], color=cball)
        visual.label(pos=(positions[i,0], positions[i,1], positions[i,2]), text='{0:d}'.format(i))
Beispiel #14
0
    def __init__(self, background=None, ambient=None, show_axis=True):
        super(Visualiser, self).__init__()
        if not VISUAL_INSTALLED:
            return

        if background is None:
            background = (0.957, 0.957, 1)
        if ambient is None:
            ambient = 0.5
        self.display = visual.display(title='PVTrace', x=0, y=0, width=800, height=600, background=background,
                                      ambient=ambient)
        self.display.bind('keydown', self.keyInput)
        self.display.exit = False

        self.display.center = (0.025, 0.015, 0)
        self.display.forward = (0, 0.83205, -0.5547)
        
        show_axis = False
        if show_axis:
            visual.curve(pos=[(0, 0, 0), (.08, 0, 0)], radius=0.0005, color=visual.color.red)
            visual.curve(pos=[(0, 0, 0), (0, .07, 0)], radius=0.0005, color=visual.color.green)
            visual.curve(pos=[(0, 0, 0), (0, 0, .08)], radius=0.0005, color=visual.color.blue)
            visual.label(pos=(.09, 0, 0), text='X', background=visual.color.red, linecolor=visual.color.red)
            visual.label(pos=(0, .08, 0), text='Y', background=visual.color.green, linecolor=visual.color.green)
            visual.label(pos=(0, 0, .07), text='Z', background=visual.color.blue, linecolor=visual.color.blue)
Beispiel #15
0
	def __init__(self, room_=1, beam_axis_=0, target_pos_=(0,0,0)):
		self.labScene = visual.display(title="7Be(d,n)8B Experiment", width=800, height=600, background=GetRGBcode(153,204,255))
		axisx = visual.box(pos=(0,0,0), axis=(10.0,0,0), width=0.05, height=0.05, color=visual.color.red)
		axisy = visual.box(pos=(0,0,0), axis=(0,10.0,0), width=0.05, height=0.05, color=visual.color.blue)
		axisz = visual.box(pos=(0,0,0), axis=(0,0,10.0), width=0.05, height=0.05, color=visual.color.green)
		labelx = visual.label(pos=(5.0,0,0), text="Z-Axis")
		labely = visual.label(pos=(0,5.0,0), text="Y-Axis")
		labelz = visual.label(pos=(0,0,5.0), text="X-Axis")
		self.labScene.center = target_pos_
		self.labScene.autoscale = False
		
		self.room = room_
		self.beam_axis = beam_axis_
		self.target_pos = target_pos_
		
		self.Floors = []
		self.Walls = []
		self.Columns = []
		self.Others = []		

		self.BuildRoom()

		if(self.room == 1 or self.room == 2):
			chamber_radius = 0.25
			self.Beamline1 = visual.cylinder(pos=Translate(self.target_pos,GetCartesianCoords(chamber_radius, math.pi/2.0, DegToRad(180+self.beam_axis))), axis=ConvIM3(71.75,0,-71.75*math.tan(DegToRad(180-self.beam_axis))), radius=ConvIM(1.75), color=visual.color.blue) # East beamline
			self.Beamline2 = visual.cylinder(pos=Translate(self.target_pos,GetCartesianCoords(chamber_radius, math.pi/2.0, DegToRad(self.beam_axis))), axis=ConvIM3(-217.5,0,217.5*math.tan(DegToRad(180-self.beam_axis))), radius=ConvIM(1.75), color=visual.color.blue) # West beamline
			self.OneMeterChamber = visual.cylinder(pos=self.target_pos, axis=(0,chamber_radius*2,0), radius=chamber_radius, color=visual.color.blue)
			self.OneMeterChamber.pos[1] = -0.5
Beispiel #16
0
    def __init__(self):
        ode.World.__init__(self)
        self._myScene = visual.display()

        # A joint group for the contact joints that are generated whenever
        # two bodies collide
        self._contactGroup = ode.JointGroup()
Beispiel #17
0
def go():
    r = np.array([1.017, 0.0])  # initial x,y position for earth
    v = np.array([0.0, 6.179])  # initial vx, vy

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

    t, h = 0.0, 0.001
    while True:
        vp.rate(200)  # limit animation speed
        r, v = ode.leapfrog(earth, r, v, t, h)  # integrate
        planet.pos = r  # move planet
        if (scene.kb.keys): scene.kb.getkey(), scene.kb.getkey()  #pause
Beispiel #18
0
    def __init__(self):
        ode.World.__init__(self)
        self._myScene = visual.display()

        # A joint group for the contact joints that are generated whenever
        # two bodies collide
        self._contactGroup = ode.JointGroup()
Beispiel #19
0
 def __init__( self, NCellsPerDimension, Length, E0 ):
     self.n   = NCellsPerDimension
     self.L   = Length
     self.V   = self.L**3
     self.N   = 4 * self.n**3
     self.a   = self.L / self.n
     self.E0  = E0
     self.E   = E0
     self.U   = 0
     self.dU  = 0
     self.ddU = 0
     self.particles = []
     self.index = 0
     self.dt    = 1e-2
     self.dt_2  = self.dt * 0.5
     self.dt2_2 = self.dt * self.dt_2
 
     self.scene = visual.display( title = 'System',
                                  x=800, y=0,
                                  width=800, height=800,
                                  center = visual.vector(0.5,0.5,0.5) * self.L,
                                  autoscale = False,
                                  range = 1.5 * self.L)
 
     self.box   = visual.box( pos     = visual.vector(0.5,0.5,0.5) * self.L,
                              length  = self.L,
                              height  = self.L,
                              width   = self.L,
                              color   = visual.color.green,
                              opacity = 0.2 )
Beispiel #20
0
def setup_scene(fullscreen):
    '''
  Sets up the scene for the display output.
  '''
    # Set title and background color (white)
    scene = visual.display(title="Robot Simulation", background=(1, 1, 1))
    # Automatically center
    scene.autocenter = True
    # Removing autoscale
    scene.autoscale = 0
    # Set whether the windows will take up entire screen or not
    scene.fullscreen = fullscreen
    # Size of the windows seen is the size of one beam (to begin)
    scene.range = (BEAM['length'], BEAM['length'], BEAM['length'])
    # The center of the windows exists at the construction location
    scene.center = helpers.scale(
        .5, helpers.sum_vectors(CONSTRUCTION['corner'], scene.range))
    # Vector from which the camera start
    scene.forward = (1, 0, 0)
    # Define up (used for lighting)
    scene.up = (0, 0, 1)
    # Defines whether or not we exit the program when we exit the screen
    # visualization
    scene.exit = False

    return scene
Beispiel #21
0
 def __init__(self):
     self.step = 1
     self.maxlen = (slen / 2) / self.step
     self.g = visual.display(width=600,
                             height=200,
                             center=(slen / 4, 30, 0))
     self.curves = []
Beispiel #22
0
def main():
    scene = visual.display(width=settings.SCENE_WIDTH, height=settings.SCENE_HEIGHT)
    ground = visual.box(axis=(0, 1, 0), pos=(0, 0, 0), length=0.1, height=500, width=500, color=visual.color.gray(0.75), opacity=0.5)

    def addGait(gaitClass, gaitName):
        gait = gaitClass(gaitName, settings.GAIT_LEGS_GROUPS[gaitName], settings.GAIT_PARAMS[gaitName])
        GaitManager().add(gait)

    addGait(GaitTripod, "tripod")
    addGait(GaitTetrapod, "tetrapod")
    addGait(GaitRiple, "riple")
    addGait(GaitWave, "metachronal")
    addGait(GaitWave, "wave")
    GaitManager().select("riple")

    robot = Hexapod3D()

    remote = Gamepad(robot)

    GaitSequencer().start()
    remote.start()

    robot.setBodyPosition(z=30)

    robot.mainLoop()

    remote.stop()
    remote.join()
    GaitSequencer().stop()
    GaitSequencer().join()
Beispiel #23
0
	def __init__( self ):
		QtCore.QThread.__init__( self )
		self.C = 0
		# it is requred to process input events from visual window
		self.display = visual.display ()
		self.s = visual.sphere( pos=visual.vector( 1, 0, 0 ) )
		self.keep_running=True
Beispiel #24
0
 def __init__(self):
   win = vs.window(width=1024, height=720, menus=False, title='SIMULATE VPYTHON GUI')# make a main window. Also sets w.panel to addr of wx window object.
   scene = vs.display( window=win, width=800, height=720, forward=-vs.vector(1,1,2))# make a 3D panel
   vss = scene
   p = win.panel
   sphere_button = wx.Button(p, label='Sphere', pos=(810,10), size=(190,100))
   #sphere_button.Bind(wx.EVT_BUTTON, self.options())
   cube_button = wx.Button(p, label='Cube', pos=(810,120), size=(190,100))
Beispiel #25
0
    def __init__(self, vals, scene=None):
        data_show.__init__(self, vals)
        # If no axes are defined, create some.

        if scene==None:
            self.scene = visual.display(title='Data Visualization')
        else:
            self.scene = scene
Beispiel #26
0
    def __init__(self, vals, scene=None):
        data_show.__init__(self, vals)
        # If no axes are defined, create some.

        if scene == None:
            self.scene = visual.display(title='Data Visualization')
        else:
            self.scene = scene
Beispiel #27
0
    def __init__(self, vals, scene=None):
        super(vpython_show, self).__init__(vals)
        # If no axes are defined, create some.

        if scene is None:
            self.scene = visual.display(title='Data Visualization')
        else:
            self.scene = scene
Beispiel #28
0
 def __init__(self):
     Node.__init__(self)
     self.step = 10
     self.maxlen = (slen / 2) / self.step
     self.g = visual.display(width=600, height=200,center=(slen/4,30,0))
     self.curves = []
     self.label = False
     self.lastdominant = 0
Beispiel #29
0
 def __init__(self):
     Node.__init__(self)
     self.step = 1
     self.maxlen = (slen / 2) / self.step
     self.g = visual.display(width=600, height=200,center=(slen/4,30,0))
     self.curves = []
     self.label = False
     self.lastdominant = 0
Beispiel #30
0
def PrintPath(x, p):
    q = st[x]
    q = q + (end, )
    mat = [col * ['.'] for r in range(row)]
    L, U = q[len(q) - 1]
    r1, c1 = cell(U)
    r2, c2 = cell(L)
    mat[r1][c1] = mat[r2][c2] = 'E'
    L, U = q[0]
    r1, c1 = cell(U)
    r2, c2 = cell(L)
    mat[r1][c1] = mat[r1][c2] = 'S'
    for i in range(1, len(q) - 1):
        L, U = q[i]
        r1, c1 = cell(U)
        r2, c2 = cell(L)
        mat[r1][c1] = mat[r2][c2] = '#'
    visual.display(row, col, mat)
Beispiel #31
0
    def __init__(self):
        self.canvas = visual.display(title='Crystal Viewer',
                                     width=500,
                                     height=500,
                                     background=(0, 0, 0),
                                     fov=math.pi / 10,
                                     scale=(0.5, 0.5, 0.5),
                                     userspin=0,
                                     exit=0)

        self.lastRotation = (0, 0, 0)
Beispiel #32
0
def display(cylinders,Lx,Ly):
    scene = visual.display(center = [Ly/2.0,.14,Lx/2.0], forward = [0,-1,0],
            up = [1,0,0],background=(1,1,1))
    surr = visual.curve(pos=[(0,0,0),(0,0,Lx),(Ly,0,Lx),(Ly,0,0),(0,0,0)],
            radius=.005*Lx,color=(0,0,0))
    for cyl in cylinders:
        x = cyl.pos[0]
        y = cyl.pos[1]
        z = 0
        rod = visual.cylinder(pos=(y,z,x), axis=(0,.001,0), radius = cyl.radius,
                color=(200,0,0))
Beispiel #33
0
 def __init__(self):
     scene.Scene.__init__(self)
     w = 800
     self.scene = visual.display(x=0,
                                 y=0,
                                 width=w,
                                 height=w,
                                 autoscale=True,
                                 forward=(1, 1, -1),
                                 newzoom=1,
                                 up=(0, 0, 1))
Beispiel #34
0
    def __init__(self):
        self.canvas = visual.display(title='Crystal Viewer'
                                     , width=500
                                     , height=500
                                     , background=(0, 0, 0)
                                     , fov=math.pi / 10
                                     , scale=(0.5, 0.5, 0.5)
                                     , userspin=0
                                     , exit=0)

        self.lastRotation = (0, 0, 0)
Beispiel #35
0
def animate_motion(x, k):
    # Animate using Visual-Python
    CO = zeros((n, 3))
    B2 = zeros((n, 3))
    C1 = zeros((n, 3))
    C3 = zeros((n, 3))
    CN = zeros((n, 3))

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

    from visual import display, rate, arrow, curve, cone, box
    black = (0,0,0)
    red = (1, 0, 0)
    green = (0, 1, 0)
    blue = (0, 0, 1)
    white = (1, 1, 1)
    NO = (0,0,0)
    scene = display(title='Rolling disc @ %0.2f realtime'%k, width=800,
            height=800, up=(0,0,-1), uniform=1, background=white, forward=(1,0,0))
    # Inertial reference frame arrows
    N = [arrow(pos=NO,axis=(.001,0,0),color=red),
         arrow(pos=NO,axis=(0,.001,0),color=green),
         arrow(pos=NO,axis=(0,0,.001),color=blue)]
    # Two cones are used to look like a thin disc
    body1 = cone(pos=CO[0], axis=B2[0], radius=r, color=blue)
    body2 = cone(pos=CO[0], axis=-B2[0], radius=r, color=blue)
    # Body fixed coordinates in plane of disc, can't really be seen through cones
    c1 = arrow(pos=CO[0],axis=C1[0],length=r,color=red)
    c3 = arrow(pos=CO[0],axis=C3[0],length=r,color=green)
    trail = curve()
    trail.append(pos=CN[0], color=black)
    i = 1
    while i<n:
        rate(k/ts)
        body1.pos = CO[i]
        body1.axis = B2[i]
        body2.pos = CO[i]
        body2.axis = -B2[i]
        c1.pos = body1.pos
        c3.pos = body1.pos
        c1.axis = C1[i]
        c3.axis = C3[i]
        c1.up = C3[i]
        c3.up = C1[i]
        trail.append(pos=CN[i])
        i += 1
Beispiel #36
0
 def __init__(self, background=(0,0,0), ambient=1.):
     super(Visualiser, self).__init__()
     if not Visualiser.VISUALISER_ON:
         return
     self.display = visual.display(title='PVTrace', x=0, y=0, width=800, height=600, background=background, ambient=ambient)
     self.display.exit = False
     visual.curve(pos=[(0,0,0), (.2,0,0)], radius=0.001, color=visual.color.red)
     visual.curve(pos=[(0,0,0), (0,.2,0)], radius=0.001, color=visual.color.green)
     visual.curve(pos=[(0,0,0), (0,0,.2)], radius=0.001, color=visual.color.blue)
     visual.label(pos=(.22, 0, 0), text='X', linecolor=visual.color.red)
     visual.label(pos=(0, .22, 0), text='Y', linecolor=visual.color.green)
     visual.label(pos=(0, 0, .22), text='Z', linecolor=visual.color.blue)
 def view(self):
     "Open a VPython window for the scene."
     color = self.options["background"]
     if type(color) == type(''):
         color = ColorByName(color)
     self.window = visual.display(title=self.options["title"],
                                  width=self.options["width"],
                                  height=self.options["height"],
                                  background=color.rgb,
                                  exit=0)
     for o in self.objects:
         o.display(self.window)
Beispiel #38
0
def set_scene(r):     # r = init position of planet
    # draw scene, mercury, sun, info box, Runge-Lenz vector
    scene = vp.display(title='Precession of Mercury', 
                       center=(.1*0,0), background=(.2,.5,1))
    planet= vp.sphere(pos=r, color=(.9,.6,.4), make_trail=True,
                      radius=0.05, material=vp.materials.diffuse)
    sun   = vp.sphere(pos=(0,0), color=vp.color.yellow,
                      radius=0.02, material=vp.materials.emissive)
    sunlight = vp.local_light(pos=(0,0), color=vp.color.yellow)
    info = vp.label(pos=(.3,-.4), text='Angle') # angle info
    RLvec = vp.arrow(pos=(0,0), axis=(-1,0,0), length = 0.25)
    return planet, info, RLvec
Beispiel #39
0
 def __init__(self, background=(0,0,0), ambient=1.):
     super(Visualiser, self).__init__()
     if not VISUAL_INSTALLED:
         return
     self.display = visual.display(title='PVTrace', x=0, y=0, width=800, height=600, background=(0.957, 0.957, 1), ambient=0.5)
     self.display.exit = False
     visual.curve(pos=[(0,0,0), (.2,0,0)], radius=0.001, color=visual.color.red)
     visual.curve(pos=[(0,0,0), (0,.2,0)], radius=0.001, color=visual.color.green)
     visual.curve(pos=[(0,0,0), (0,0,.2)], radius=0.001, color=visual.color.blue)
     visual.label(pos=(.22, 0, 0), text='X', linecolor=visual.color.red)
     visual.label(pos=(0, .22, 0), text='Y', linecolor=visual.color.green)
     visual.label(pos=(0, 0, .22), text='Z', linecolor=visual.color.blue)
Beispiel #40
0
def set_scene(R):        # draw scene, ball, trails, spin, info box
    scene = vp.display(background=(.2,.5,1), forward=(-1,-.1,-.1),
                       center=(.5*R,1,0), ambient=.4, fullscreen=1)
    floor = vp.box(pos=(R/2,0,0), length=1.1*R, height=.1, width=8, 
                   color=vp.color.orange, opacity=0.7)  # transparent 
    zone = vp.curve(pos=[(R,0,1),(R,1,1),(R,1,-1),(R,0,-1)], radius=.02)
    ball = vp.sphere(pos=(0,0,0), radius=.2, material=vp.materials.rough)
    trail = vp.curve(pos=(0,0,0), radius=0.04)
    ideal = vp.curve(pos=(0,0,0), radius=0.04, color=vp.color.green)
    spin = vp.arrow(axis=omega,pos=(0,0,0),length=1)   # omega dir
    info = vp.label(pos=(1.1*R,2,-2),text='Any key=repeat')
    return scene, ball, trail, ideal, spin
 def view(self):
     "Open a VPython window for the scene."
     color = self.options["background"]
     if type(color) == type(''):
         color = ColorByName(color)
     self.window = visual.display(title = self.options["title"],
                                  width = self.options["width"],
                                  height = self.options["height"],
                                  background = color.rgb,
                                  exit = 0)
     for o in self.objects:
         o.display(self.window)
Beispiel #42
0
def PlotElevator(filename):
  try:
    f = open(filename,'r')
    data = json.loads(f.read())
    f.close()
  except Exception as e:
    return str(e)

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

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

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

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

    if body == 1:
      scene.center = (0,0,0)
    else:
      scene.center = pos[nt][body]
    string.pos=pos[nt]
    asteroid.pos=pos[nt][-1]
    anchor.pos=pos[nt][0]
    label_avg_l0.pos = asteroid.pos
    label_avg_l0.text = "t: %3.1f" % (data["Time"][nt],)
    if nt + 1 >= pos.shape[0]:
      nt = 0
    else:
      nt += 1
Beispiel #43
0
    def __init__(self,*args,**kwargs):
        import visual
        self.V = visual

        Canvas.__init__(self,*args,**kwargs)
        self.scene = visual.display(height=self.height,width=self.width,
                                    background=(1,1,1))
        self.scene.center = (self.width/2.,self.height/2.,0)
        self.scene.up = (0,-1,0)
        self.scene.forward = (0,0,1)
        self.scene.autoscale = True
#        self.scene.scale = (2./self.width,2./self.height,1)
        self._rgb = (0,0,0)
Beispiel #44
0
 def __init__(self, draw_interval=1.0):
     super(TSPViewer, self).__init__()
     self.solvers = []
     self._nodes = None
     self.route_window = vs.display(title='TSP Route Viewer', autocenter=True)        
     self.score_window = gdisplay(title='TSP Score Viewer',
                                  xtitle='iteration', ytitle='score' )
     self.setDaemon(True)
     self.route = None
     self.scores = []
     self.stop_event = threading.Event()
     self.draw_interval = draw_interval
     return
    def __init__( self, title, **options ):
        default = { 'x' : 0, 'y' : 0,
                    'width' : 800, 'height' : 600,
                    'center' : (0,0,0),
                    'autoscale' : True,
                    'forward' : (0, 0, -1 ) }

        for opt in default:
            if not opt in options:
                options[opt] = default[opt]

        self.simu = visual.display( title = title, **options )
        self.objects = {}
Beispiel #46
0
    def __init__(self, *args, **kwargs):
        import visual
        self.V = visual

        Canvas.__init__(self, *args, **kwargs)
        self.scene = visual.display(height=self.height,
                                    width=self.width,
                                    background=(1, 1, 1))
        self.scene.center = (self.width / 2., self.height / 2., 0)
        self.scene.up = (0, -1, 0)
        self.scene.forward = (0, 0, 1)
        self.scene.autoscale = True
        #        self.scene.scale = (2./self.width,2./self.height,1)
        self._rgb = (0, 0, 0)
Beispiel #47
0
 def __init__(self, background=(0, 0, 0), ambient=1.0):
     super(Visualiser, self).__init__()
     if not Visualiser.VISUALISER_ON:
         return
     self.display = visual.display(
         title="PVTrace", x=0, y=0, width=800, height=600, background=(0.957, 0.957, 1), ambient=0.5
     )
     self.display.exit = False
     visual.curve(pos=[(0, 0, 0), (0.2, 0, 0)], radius=0.001, color=visual.color.red)
     visual.curve(pos=[(0, 0, 0), (0, 0.2, 0)], radius=0.001, color=visual.color.green)
     visual.curve(pos=[(0, 0, 0), (0, 0, 0.2)], radius=0.001, color=visual.color.blue)
     visual.label(pos=(0.22, 0, 0), text="X", linecolor=visual.color.red)
     visual.label(pos=(0, 0.22, 0), text="Y", linecolor=visual.color.green)
     visual.label(pos=(0, 0, 0.22), text="Z", linecolor=visual.color.blue)
Beispiel #48
0
def main(script, n=20):
    global scene

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

    while 1:
        # update the screen once per time step
        visual.rate(1/dt)
        world.step()
def main(script, n=20):
    global scene

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

    while 1:
        # update the screen once per time step
        visual.rate(1/dt)
        world.step()
Beispiel #50
0
 def __init__(self, draw_interval=1.0):
     super(TSPViewer, self).__init__()
     self.solvers = []
     self._nodes = None
     self.route_window = vs.display(title='TSP Route Viewer',
                                    autocenter=True)
     self.score_window = gdisplay(title='TSP Score Viewer',
                                  xtitle='iteration',
                                  ytitle='score')
     self.setDaemon(True)
     self.route = None
     self.scores = []
     self.stop_event = threading.Event()
     self.draw_interval = draw_interval
     return
def configure_new_instance(evt):
    global scene
    global value
    new_balls = int(value.GetValue())
    print("Gotcha!")
    print(new_balls)

    scene.delete()

    scene = vs.display(window=win,
                       width=830,
                       height=690,
                       forward=-vs.vector(1, 1, 2))

    clear_balls()
    #new_win = vs.window(width=1024, height=720, menus=False, title='ELASTIC COLLISIONS BBY v2')
    create_ball(new_balls)
    change_walls(0)
def set_scene(r):  # r = init position of planet
    # draw scene, mercury, sun, info box, Runge-Lenz vector
    scene = vp.display(title='Precession of Mercury',
                       center=(.1 * 0, 0),
                       background=(.2, .5, 1))
    planet = vp.sphere(pos=r,
                       color=(.9, .6, .4),
                       make_trail=True,
                       radius=0.05,
                       material=vp.materials.diffuse)
    sun = vp.sphere(pos=(0, 0),
                    color=vp.color.yellow,
                    radius=0.02,
                    material=vp.materials.emissive)
    sunlight = vp.local_light(pos=(0, 0), color=vp.color.yellow)
    info = vp.label(pos=(.3, -.4), text='Angle')  # angle info
    RLvec = vp.arrow(pos=(0, 0), axis=(-1, 0, 0), length=0.25)
    return planet, info, RLvec
Beispiel #53
0
    def InitVisuals():

        from visual import display, points, box
        window = display(title="F16 Simulation",
                         width=Resolution[0],
                         height=Resolution[1])
        window.up = np.identity(3)[2]
        window.forward = -np.ones(3)
        window.center = pos

        if FPV:
            window.range = 15 * 3  #2

        if stereo is not None:
            window.stereo = stereo

        D = 2500  #5000#2500

        #--- CS ---
        for i in range(3):
            arrow(axis=np.identity(3)[i] * 1000,
                  color=np.identity(3)[i],
                  opacity=0.75)

        #--- Point Cloud ---
        if 1:
            Points = []
            d = 500  #100
            n = int(D / d)
            for i in range(-n, n + 1):
                for j in range(-n, n + 1):
                    for k in range(0, n + 1):
                        p = np.array([i, j, k]).astype(float) * d
                        Points.append(tuple(p))  #+=list(p)
            points(pos=Points)

        if 1:
            box(width=D * 2,
                height=D * 2,
                depth=10,
                axis=-np.identity(3)[2],
                color=[0.6, 0.3, 0.15])

        return window
def set_scene(R):  # draw scene, ball, trails, spin, info box
    scene = vp.display(background=(.2, .5, 1),
                       forward=(-1, -.1, -.1),
                       center=(.5 * R, 1, 0),
                       ambient=.4,
                       fullscreen=1)
    floor = vp.box(pos=(R / 2, 0, 0),
                   length=1.1 * R,
                   height=.1,
                   width=8,
                   color=vp.color.orange,
                   opacity=0.7)  # transparent
    zone = vp.curve(pos=[(R, 0, 1), (R, 1, 1), (R, 1, -1), (R, 0, -1)],
                    radius=.02)
    ball = vp.sphere(pos=(0, 0, 0), radius=.2, material=vp.materials.rough)
    trail = vp.curve(pos=(0, 0, 0), radius=0.04)
    ideal = vp.curve(pos=(0, 0, 0), radius=0.04, color=vp.color.green)
    spin = vp.arrow(axis=omega, pos=(0, 0, 0), length=1)  # omega dir
    info = vp.label(pos=(1.1 * R, 2, -2), text='Any key=repeat')
    return scene, ball, trail, ideal, spin
Beispiel #55
0
 def showEnvirModel(self):
     scene = visual.display(title='Channel Environment Visualization',
                            exit=False)
     scene.objects
     max_x = readFloat(self.ui.lineEdit_CS_X)
     max_y = readFloat(self.ui.lineEdit_CS_Y)
     max_z = readFloat(self.ui.lineEdit_CS_Z)
     offset = (-max_x / 2, -max_y / 2, -max_z / 2)
     th = 0.02
     wl = self.simul.wall_thick
     visualBrick(Brick(vector_3(wl - th, 0, 0), vector_3(wl, max_y, max_z)),
                 opacity=0.2,
                 offset=offset)
     visualBrick(Brick(vector_3(0, wl - th, 0), vector_3(max_x, wl, max_z)),
                 opacity=0.2,
                 offset=offset)
     visualBrick(Brick(vector_3(0, 0, wl - th), vector_3(max_x, max_y, wl)),
                 opacity=0.2,
                 offset=offset)
     visualBrick(Brick(vector_3(max_x - wl, 0, 0),
                       vector_3(max_x + th - wl, max_y, max_z)),
                 opacity=0.2,
                 offset=offset)
     visualBrick(Brick(vector_3(0, max_y - wl, 0),
                       vector_3(max_x, max_y + th - wl, max_z)),
                 opacity=0.2,
                 offset=offset)
     visualBrick(Brick(vector_3(0, 0, max_z - wl),
                       vector_3(max_x, max_y, max_z + th - wl)),
                 opacity=0.2,
                 offset=offset)
     #visualBrick(Brick(vector_3(0, 0, 0), vector_3(max_x, max_y, max_z)), opacity = 0.3, offset = offset)
     for scatt in self.simul.scatterers:
         visualBrick(scatt.shape,
                     offset=offset,
                     opacity=0.9,
                     color=(0.69, 0.09, 0.122),
                     material=visual.materials.plastic)
Beispiel #56
0
######## GUI Code #######

win = window(
    menus=True,
    title=_title,
    x=wx.SystemSettings.GetMetric(wx.SYS_SCREEN_X) / 2 - WIN_WIDTH / 2,
    y=wx.SystemSettings.GetMetric(wx.SYS_SCREEN_Y) / 2 - WIN_HEIGHT / 2,
    width=WIN_WIDTH,
    height=WIN_HEIGHT)
win.win.SetMinSize(
    (WIN_WIDTH, WIN_HEIGHT
     ))  # The VPython window object doesn't inherit from the wx.Frame,
win.win.SetMaxSize(
    (WIN_WIDTH,
     WIN_HEIGHT))  # but rather *has* a frame, which happens to be called 'win'
disp = display(window=win, x=d, y=d, height=DISP_HEIGHT, width=DISP_WIDTH)

p = win.panel  # Panel to hold controls

# Rule
rule_txt = wx.StaticText(
    p,
    pos=(DISP_WIDTH + d * 2, d),
    label="Rule: ",
)
rule_txt.SetFont(font)
rule_txtctrl = wx.TextCtrl(
    p,
    pos=(rule_txt.Position.Get()[0] + rule_txt.Size.Get()[0],
         rule_txt.Position.Get()[1]),
    size=(200, 22),
Beispiel #57
0
def distance():
    s = 0.0
    for i in range(N):
        s += mag(r[i+1]-r[i])
    return s

# Choose N city locations and calculate the initial distance
r = empty([N+1,2],float)
for i in range(N):
    r[i,0] = random()
    r[i,1] = random()
r[N] = r[0]
D = distance()

# Set up the graphics
display(center=[0.5,0.5])
for i in range(N):
    sphere(pos=r[i],radius=R)
l = curve(pos=r,radius=R/2)

# Main loop
t = 0
T = Tmax
while T>Tmin:

    # Cooling
    t += 1
    T = Tmax*exp(-t/tau)

    # Update the visualization every 100 moves
    if t%100==0:
Beispiel #58
0
import visual as vp, numpy as np, ode


def hockey(Y, t):  # return eqn of motion
    accel = 0.
    for i in range(len(loc)):
        accel += Q[i] * (Y[0] - loc[i]) / (vp.mag(Y[0] - loc[i]))**3
    return [Y[1], q * accel]  # list for non-vectorized solver


a, b, w = 1., 0.5, 0.125  # rink size, goal width
q, qcor, qmid, qcen = -1.0, 1.0, -2., 2.  # Qs: puck, cor., mid, cen.
Q = [qcor, qmid, qcor, qcor, qmid, qcor, qcen]  # charges, locations
loc = [[-a, b], [0, b], [a, b], [a, -b], [0, -b], [-a, -b], [0, 0]]

scene = vp.display(title='Electric hockey', background=(.2, .5, 1))
puck = vp.sphere(pos=(-a, 0, 0), radius=0.05, make_trail=True)  # trail
rink = vp.curve(pos=loc[:-1] + [loc[0]], radius=0.01)  # closed curve
goalL = vp.curve(pos=[(-a, w, 0), (-a, -w, 0)], color=(0, 1, 0), radius=.02)
goalR = vp.curve(pos=[(a, w, 0), (a, -w, 0)], color=(0, 1, 0), radius=.02)
for i in range(len(loc)):  # charges, red if Q>0, blue if Q<0
    color = (1, 0, 0) if Q[i] > 0 else (0, 0, 1)
    vp.sphere(pos=loc[i], radius=0.05, color=color)

v, theta = input('enter speed, theta; eg, 2.2, 19:')  # try 2.2, 18.5
v, theta = min(4, v), max(1, theta) * np.pi / 180.  # check valid input
Y = np.array([[-a, 0], [v * np.cos(theta), v * np.sin(theta)]])
while True:
    vp.rate(200)
    Y = ode.RK45n(hockey, Y, t=0., h=0.002)
    x, y = Y[0][0], Y[0][1]
"""
Spyder Editor

This is a temporary script file.
"""
############################################################
#Moving Vpython objects around screen using SUVAT equations#
#Fahad Chohan 30/11/2015                                   #
############################################################

# Importing numpy and functions for annimating a sphere
from visual import sphere, curve, color, display, rate
import numpy as np

# set up the scene
scene = display(x=50, y=50, width=640, height=480, center=(20, 0, 0))
ground = curve(pos=[(-5, 0, 0), (50, 0, 0)], color=color.green)

# initial ball coordinates (metres)
x0 = 0.0
y0 = 0.0
y = y0
g = 9.8  # gravitational acceleration, m/s2
dt = 0.01  # time interval for loop, in seconds
x = 0.0

# input initial angle and velocity
dtheta = float(raw_input("Input the initial angle in degrees: "))
theta = np.radians(dtheta)
theta1 = theta
v0 = float(raw_input("Input the initial velocity in metres/second: "))
    f[1:, :] -= ftop  # below, left: use 3rd law
    f[:, 1:] -= fright
    a = (f - damp * v) / mass + gvec
    v[0, 0], v[0, -1], v[-1, 0], v[-1, -1] = 0, 0, 0, 0  # fixed coners
    return np.array([v, a])


L, M, N = 2.0, 15, 15  # size, (M,N) particle array
h, mass, damp = 0.01, 0.004, 0.01  # keep damp between [.01,.1]
x, y = np.linspace(0, L, M), np.linspace(0, L, N)  # particle grid
r, v = np.zeros((N, M, 3)), np.zeros((N, M, 3))
spring_k, spring_l = 50.0, x[1] - x[0]  # spring const., relaxed length
r[:, :, 0], r[:, :, 1] = np.meshgrid(x, y)  # initialize pos
Y, gvec = np.array([r, v]), np.array([0, 0, -9.8])  # [v,a], g vector

scene = vp.display(title='Tablecloth',
                   background=(.2, .5, 1),
                   up=(0, 0, 1),
                   center=(L / 2, L / 2, -L / 4),
                   forward=(1, 2, -1))
vp.points(pos=[(0, 0, 0), (0, L, 0), (L, L, 0), (L, 0, 0)], size=50)  # corners
x, y, z = r[:, :, 0], r[:, :, 1], r[:, :, 2]  # mesh points
net = vpm.net(x, y, z, vp.color.yellow, 0.005)  # mesh net
mesh = vpm.mesh(x, y, z, vp.color.red, vp.color.yellow)

while (1):
    vp.rate(100), vpm.wait(scene)  # pause if key pressed
    Y = ode.RK4(cloth, Y, 0, h)
    x, y, z = Y[0, :, :, 0], Y[0, :, :, 1], Y[0, :, :, 2]
    net.move(x, y, z), mesh.move(x, y, z)