def create_grid(size, height):
    has_height = (height != None and len(height) != 0)
    row_step = (GRID_SIZE - (-GRID_SIZE)) / float(size - 1)
    col_step = (GRID_SIZE - (-GRID_SIZE)) / float(size - 1)

    # first calculate all points
    points = [(GRID_SIZE - col * col_step, has_height and height[row][col] or 0, GRID_SIZE - row * row_step) for
            row in xrange(size) for col in xrange(size)]

    horizontal_curves = []
    vertical_curves = []
    # horizontal lines
    for i in xrange(0, len(points), size):
        for j in xrange(size - 1):
            horizontal_curves.append(curve(frame=grid_frame, pos=[
                points[i + j],
                points[i + j + 1]
                ]))

    # vertical lines
    for i in xrange(0, size):
        #print "i=%d" % i
        for j in xrange(0, len(points) - size, size):
            #print "j=%d" % j
            #print "i+j=%d" % (i+j)
            #print "i+j+size=%d" % (i+j+size)
            if i + j < len(points) and i + j + size < len(points):
                vertical_curves.append(curve(frame=grid_frame, pos=[
                    points[i + j],
                    points[i + j + size]
                    ]))
    
    return (horizontal_curves, vertical_curves)
示例#2
0
 def drawEdge(self, index, coeff, frame):
     coords = [[], []]
     for i in range(2):
         for j in range(2):
             coords[i].append(self.ends[i].coords[j])
         coords[i].append(self.ends[i].coords[2] + index * coeff)
     curve(pos=coords, color=color.black, radius=coeff, frame=frame)
示例#3
0
 def showAxes( self, frame, color, length, pos ): # Use frame=None for world.
     directions = [ vs.vector(length, 0, 0), vs.vector(0, length, 0), vs.vector(0, 0, length) ]
     texts = ["x","y","z"]
     pos = vs.vector(pos)
     for i in range(3): # each direction
        vs.curve( frame=frame, color=color, pos=[pos, pos+directions[i]])
        vs.label( frame=frame, color=color, pos=pos+directions[i], text=texts[i], opacity=0, box=False )
示例#4
0
def main():
    if len(argv) < 3:
        raise Exception('>>> ERROR! Please supply values for black hole mass [>= 1.0] and spin [0.0 - 1.0] <<<')
    m = float(argv[1])
    a = float(argv[2])
    horizon = m * (1.0 + sqrt(1.0 - a * a))
    cauchy = m * (1.0 - sqrt(1.0 - a * a))
    #  set up the scene
    scene.center = (0.0, 0.0, 0.0)
    scene.width = scene.height = 1024
    scene.range = (20.0, 20.0, 20.0)
    inner = 2.0 * sqrt(cauchy**2 + a**2)
    ellipsoid(pos = scene.center, length = inner, height = inner, width = 2.0 * cauchy, color = color.blue, opacity = 0.4)  # Inner Horizon
    outer = 2.0 * sqrt(horizon**2 + a**2)
    ellipsoid(pos = scene.center, length = outer, height = outer, width = 2.0 * horizon, color = color.blue, opacity = 0.3)  # Outer Horizon
    ergo = 2.0 * sqrt(4.0 + a**2)
    ellipsoid(pos = scene.center, length = ergo, height = ergo, width = 2.0 * horizon, color = color.gray(0.7), opacity = 0.2)  # Ergosphere
    if fabs(a) > 0.0:
        ring(pos=scene.center, axis=(0, 0, 1), radius = a, color = color.white, thickness=0.01)  # Singularity
    else:
        sphere(pos=scene.center, radius = 0.05, color = color.white)  # Singularity
    ring(pos=scene.center, axis=(0, 0, 1), radius = sqrt(isco(a)**2 + a**2), color = color.magenta, thickness=0.01)  # ISCO
    curve(pos=[(0.0, 0.0, -15.0), (0.0, 0.0, 15.0)], color = color.gray(0.7))
    #cone(pos=(0,0,12), axis=(0,0,-12), radius=12.0 * tan(0.15 * pi), opacity=0.2)
    #cone(pos=(0,0,-12), axis=(0,0,12), radius=12.0 * tan(0.15 * pi), opacity=0.2)
    #sphere(pos=(0,0,0), radius=3.0, opacity=0.2)
    #sphere(pos=(0,0,0), radius=12.0, opacity=0.1)
    # animate!
    ball = sphere()  # Particle
    counter = 0
    dataLine = stdin.readline()
    while dataLine:  # build raw data arrays
        rate(60)
        if counter % 1000 == 0:
            ball.visible = False
            ball = sphere(radius = 0.2)  # Particle
            ball.trail = curve(size = 1)  #  trail
        data = loads(dataLine)
        e = float(data['v4e'])
        if e < -120.0:
            ball.color = color.green
        elif e < -90.0:
            ball.color = color.cyan
        elif e < -60.0:
            ball.color = color.yellow
        elif e < -30.0:
            ball.color = color.orange
        else:
            ball.color = color.red
        r = float(data['r'])
        th = float(data['th'])
        ph = float(data['ph'])
        ra = sqrt(r**2 + a**2)
        sth = sin(th)
        ball.pos = (ra * sth * cos(ph), ra * sth * sin(ph), r * cos(th))
        ball.trail.append(pos = ball.pos, color = ball.color)
        counter += 1
        dataLine = stdin.readline()
示例#5
0
        def iterate(tree, gen, filled, spec_fill=0):
            """Itère sur l'arbre (on commence = gen=1 et filled=[0, 0])
            filled détermine la hauteur maximale 
                où on peut dessiner pour une génération donnée
            gen est la génération"""
            # On stockera dans height les différentes hauteurs des sous-arbres
            height = []
            width = gen * COLWIDTH
            altitude = 0
            current_path = None
            x = width - COLWIDTH / 2
            if len(filled) <= gen:
                filled.append(filled[-1])

            for k in xrange(len(tree[INDEX_SUBS])):
                if k == 0:
                    h, w, alt, new_path = iterate(
                        tree[INDEX_SUBS][k],
                        gen + 1,
                        filled,
                        max(filled[gen], spec_fill) - (len(tree[INDEX_SUBS]) - 1) / 2 * COLWIDTH,
                    )
                else:
                    h, w, alt, new_path = iterate(tree[INDEX_SUBS][k], gen + 1, filled)
                if w > width:
                    width = w
                if alt > altitude:
                    altitude = alt
                height.append(h)
                if new_path != None:
                    current_path = new_path
            if len(height) == 0:
                height.append(max(filled[gen], filled[gen - 1], spec_fill) + COLWIDTH / 2)
            center = (height[0] + height[-1]) / 2
            altitude = max(altitude, center + COLWIDTH / 2)

            # Les traits
            for k in xrange(len(tree[INDEX_SUBS])):
                visual.curve(pos=[(center, -x, 0), (height[k], -x - COLWIDTH, 0)], radius=LINEWIDTH)

            # Le nœud
            point = (center, -x, 0)
            if tree[INDEX_STATE] == 2:
                current_path = tree[INDEX_PATH]
                # Le nœud courant est vert
                visual.sphere(pos=point, radius=WIDTH, color=(0.0, 1.0, 0.0))
            elif tree[INDEX_STATE] == 1:
                # Si c'est lu, on met en rouge
                visual.sphere(pos=point, radius=WIDTH, color=(0.5, 0.0, 0.0))
            else:
                # Sinon, on met en rouge clair
                visual.sphere(pos=point, radius=WIDTH, color=(1.0, 0.3, 0.3))

            self.dots[tree[INDEX_PATH]] = point
            if filled[gen] < height[-1] + COLWIDTH / 2:
                filled[gen] = height[-1] + COLWIDTH / 2
            return center, width, altitude, current_path
示例#6
0
 def draw_grid(self, width, length):
     scene.center = (int(width / 2), int(length / 2))
     scene.forward = (0, 0, -1) # Default view direction
     for x in range(-5, width * 10 + 5, 10):
         curve(pos=[(x / 10 + 0.5, -0.5), (x / 10 + 0.5, length - 0.5)],
               color=color.green)
     for y in range(-5, length * 10 + 5, 10):
         curve(pos=[(-0.5, y / 10 + 0.5), (width - 0.5, y / 10 + 0.5)],
               color=color.green)
示例#7
0
def drawGrid( posn=(0,0,0), sq=1, H=12, W = 1, normal='z', colour= clr.white ) :
    ht = H*sq
    wd = W*sq
    for i in range( 0, ht+1, sq ):  # FOR EACH HORIZONTAL LINE
        if normal == 'x':
            vs.curve( pos=[(posn[1]+i, posn[0], posn[2]+wd),(posn[1]+i, posn[0], posn[2])], color=colour)
            #print (posn[0] + posn[1]+i + posn[2]+wd) #for testing purposes
        else: vs.curve( pos=[(posn[0],    posn[1], posn[2]+i),
                                           (posn[0]+wd, posn[1], posn[2]+i)], color=colour)
示例#8
0
def axes( frame, colour, sz, posn ): # Make axes visible (of world or frame).
                                     # Use None for world.   
    directions = [vs.vector(sz,0,0), vs.vector(0,sz,0), vs.vector(0,0,sz)]
    texts = ["X","Y","Z"]
    posn = vs.vector(posn)
    for i in range (3): # EACH DIRECTION
       vs.curve( frame = frame, color = colour, pos= [ posn, posn+directions[i]])
       vs.label( frame = frame,color = colour,  text = texts[i], pos = posn+ directions[i],
                                                                    opacity = 0, box = False )
示例#9
0
 def __init__(self, size=100, small_interval=5, big_interval=50):
     self.frame = visual.frame(pos=(0,0,0))
     for i in range(-size, size+small_interval, small_interval):
         if i % big_interval == 0:
             c = visual.color.gray(0.65)
         else:
             c = visual.color.gray(0.25)
         visual.curve(frame=self.frame, pos=[(i,0,size),(i,0,-size)], color=c)
         visual.curve(frame=self.frame, pos=[(size,0,i),(-size,0,i)], color=c)
示例#10
0
文件: connobj.py 项目: regit/nf3d
    def plate(self):
        if (self.container):
            for obj in self.container.objects:
                obj.visible = 0
        self.container = visual.frame()
        field_length =  self.length() + 2*self.config['display']['radius']
        field_width = 3*self.config['display']['radius']*self.count + 10
        if (self.ordered):
            init = self.conns[0].obj[self.orderby]
            pborder = 0
            t = -1
            i = 0
            for conn in self.conns:
                if (init != conn.obj[self.orderby]):
                    if ((i % 2) == 1):
                        bcolor = self.config['colors']['box_light']
                    else:
                        bcolor = self.config['colors']['box']

                    if type(init) == (type(1)):
                        labeltext = self.orderby + "\n%d" % (init)
                    elif type(init) == (type('str')):
                        labeltext = self.orderby + "\n'%s'" % (init)
                    visual.box(frame=self.container, pos=(field_length/2 - self.level, -(self.config['display']['radius']+1), 3*self.config['display']['radius']*t/2+self.config['display']['radius'] + pborder/2), \
                             width = (3*self.config['display']['radius']*t - pborder), length = field_length, height = 1, color = bcolor)
                    visual.label(frame=self.container, pos = (self.config['display']['radius'] -self.level, 0,  3*self.config['display']['radius']*t/2+self.config['display']['radius'] + pborder/2),\
                        yoffset = 4*self.config['display']['radius'], xoffset = -4* self.config['display']['radius'],text = labeltext)
                    pborder = 3*self.config['display']['radius']*t+self.config['display']['radius']
                    init = conn.obj[self.orderby]
                    i += 1
                t += 1

            if type(init) == (type(1)):
                labeltext = self.orderby + "\n%d" % (init)
            elif type(init) == (type('str')):
                labeltext = self.orderby + "\n'%s'" % (init)
            if ((i % 2) == 1):
                bcolor = self.config['colors']['box_light']
            else:
                bcolor = self.config['colors']['box']
            visual.box(frame=self.container, pos=(field_length/2 - self.level, -(self.config['display']['radius']+1), 3*self.config['display']['radius']*t/2+self.config['display']['radius'] + pborder/2), \
                     width = (3*self.config['display']['radius']*t - pborder), length = field_length, height = 1, color = bcolor)
            visual.label(frame=self.container, pos = (self.config['display']['radius'] - self.level, 0, 3*self.config['display']['radius']*t/2+self.config['display']['radius'] + pborder/2),\
                yoffset = 4*self.config['display']['radius'], xoffset = -4* self.config['display']['radius'], text = labeltext)
        else:
             visual.box(frame=self.container, pos = (field_length/2 - self.level, -(self.config['display']['radius']+1),field_width/2), width = field_width, length = field_length, height = 1, color = self.config['colors']['box'])

        desctext = 'From %s to %s\n' % (time.strftime("%F %H:%M:%S", time.localtime(self.starttime)), \
            time.strftime("%F %H:%M:%S", time.localtime(self.endtime)))
        desctext += self.build_str_filter(" and ", "Filtering on ")
        visual.label(frame=self.container, pos = (field_length/2 - self.level, self.config['display']['radius']+0.5,0), yoffset = 4*self.config['display']['radius'], text = desctext)
        for i in range(self.config['display']['graduation']):
            visual.curve(frame=self.container, pos=[(field_length/self.config['display']['graduation']*i - self.level, -(self.config['display']['radius']+1)+1,0), (field_length/self.config['display']['graduation']*i - self.level,-(self.config['display']['radius']+1)+1,field_width)])
        for i in range(self.config['display']['graduation']/self.config['display']['tick']+1):
            ctime = time.strftime("%H:%M:%S", time.localtime(self.mintime + field_length/self.config['display']['graduation']*self.config['display']['tick']*i))
            visual.label(frame=self.container, pos=(field_length/self.config['display']['graduation']*self.config['display']['tick']*i - self.level, -(self.config['display']['radius']+1)+1,0), text = '%s' % (ctime), border = 5, yoffset = 1.5*self.config['display']['radius'])
    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
示例#12
0
def getxmas():
    """Creates a complete Christmas Tree dipole assembly (minus base) at (0,0,0)

     Returned value is a tuple of (xmas, olist), where xmas is the frame containing the
     complete Christmas Tree dipoles, and olist is a list of all of the component objects."""
    xmas = visual.frame()
    olist = []
    for direction in ['E', 'W', 'N', 'S']:  # Create the four dipole arms
        ef, elist = getelement(frame=xmas, which=direction)
        olist.append(ef)
        olist.append(elist)

    # These objects (s1-s3) are the white plastic space assembly
    s1 = visual.curve(pos=[
        V(-0.233, -0.233, 0.59),
        V(0.233, -0.233, 0.59),
        V(0.233, 0.233, 0.59),
        V(-0.233, 0.233, 0.59),
        V(-0.233, -0.233, 0.59)
    ],
                      frame=xmas,
                      radius=0.02,
                      material=SPACERMAT,
                      color=color.white)
    s2 = visual.curve(pos=[V(-0.233, 0, 0.59),
                           V(0.233, 0, 0.59)],
                      frame=xmas,
                      radius=0.02,
                      material=SPACERMAT,
                      color=color.white)
    s3 = visual.curve(pos=[V(0, -0.233, 0.59),
                           V(0, 0.233, 0.59)],
                      frame=xmas,
                      radius=0.02,
                      material=SPACERMAT,
                      color=color.white)

    # This is an approximation to the LNA and feedhorn at the top of the tree
    lna = visual.box(pos=V(0, 0, 1.63),
                     frame=xmas,
                     height=0.03,
                     length=0.03,
                     width=0.08,
                     material=SPACERMAT,
                     color=color.white)

    # This is the cable duct going vertically down the centre of the tree from the LNA
    pole = visual.curve(pos=[V(0, 0, 0.38), V(0, 0, 1.73)],
                        frame=xmas,
                        radius=POLER,
                        material=POLEMAT,
                        color=color.white)

    olist.append([s1, s2, s3, lna, pole])
    return xmas, olist
示例#13
0
def axes(frame, colour, size, posn):
    """Make axes visible (of world or frame)."""
    # Use None for world.
    directions = [
        vs.vector(size, 0, 0), vs.vector(0, size, 0), vs.vector(0, 0, size)]
    texts = ["X", "Y", "Z"]
    posn = vs.vector(posn)
    for i in range(3): # EACH DIRECTION
        vs.curve(frame=frame, color=colour, pos=[posn, posn+directions[i]])
        vs.label(frame=frame, color=colour, text=texts[i],
                 pos=posn + directions[i], opacity=0, box=False)
示例#14
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
示例#15
0
    def display(self,data):
        #dominant = reduce(lambda y,x: x if x[1] > y[1] else y, zip(range(len(data)), data), [0,0])
        #if (dominant[1] > 10 and dominant[0] != 0.0):
        #    freq = freqs[dominant[0]]
        #    print freq,
        #    note = ftomidi(freq)
        #    print note
        #    PlayNote(note)
        #    dominant = dominant[0]
        #else:
        #    dominant = False

        if (len(self.curves) > self.maxlen):
            todel = self.curves.pop()
            todel.visible = False
            del todel

        for oldcurve in self.curves:
            for point in range(len(oldcurve.pos)):
                oldcurve.pos[point][2] -= self.step

        y = []
        for point in data:
            y.append(point)
            y.append(point)

        curve = visual.curve(color=visual.color.white, display=self.g, radius=0)

        for point in zip(range(len(data)),data):
            r = g = b = 1
            curve.append(pos=(point[0],point[1] * 10,0), color=(r,g,b))
        self.curves.insert(0,curve)
示例#16
0
    def display(self, data):
        #dominant = reduce(lambda y,x: x if x[1] > y[1] else y, zip(range(len(data)), data), [0,0])
        #if (dominant[1] > 10 and dominant[0] != 0.0):
        #    freq = freqs[dominant[0]]
        #    print freq,
        #    note = ftomidi(freq)
        #    print note
        #    PlayNote(note)
        #    dominant = dominant[0]
        #else:
        #    dominant = False

        if (len(self.curves) > self.maxlen):
            todel = self.curves.pop()
            todel.visible = False
            del todel

        for oldcurve in self.curves:
            for point in range(len(oldcurve.pos)):
                oldcurve.pos[point][2] -= self.step

        y = []
        for point in data:
            y.append(point)
            y.append(point)

        curve = visual.curve(color=visual.color.white,
                             display=self.g,
                             radius=0)

        for point in zip(range(len(data)), data):
            r = g = b = 1
            curve.append(pos=(point[0], point[1] * 10, 0), color=(r, g, b))
        self.curves.insert(0, curve)
示例#17
0
 def frame(self, sign):
     self.glass = curve(
         pos=[
             (sign * self.time, -self.time * 1.1, 0),
             (sign * self.time * 0.05, -self.time * 0.1, 0),
             (sign * self.time * 0.05, self.time * 0.1, 0),
             (sign * self.time, self.time * 1.1, 0),
             (sign * self.time, self.time * 1.15, 0),
         ],
         radius=self.time * 0.025,
     )
     self.base = cylinder(
         pos=(0, sign * self.time * 1.15, 0),
         axis=(0, 1, 0),
         length=self.time * 0.1,
         radius=self.time * 1.2,
         color=(0.66, 0.46, 0.13),
     )
     self.pole = cylinder(
         pos=(sign * self.time, -self.time * 1.1, 0),
         axis=(0, 1, 0),
         length=self.time * 2.3,
         radius=self.time * 0.06,
         color=(0.66, 0.46, 0.13),
     )
示例#18
0
def golf_ball_calc(x,y,z,vx,vy,vz,dt,m,g,B2,S0,w,w_vector):
    t = 0.0
    x_list = [x]
    y_list = [y]
    z_list = [z]
    vx_list = [vx]
    vy_list = [vy]
    vz_list = [vz]
    t_list = [t]
    v_vector = visual.vector(vx,vy,vz)

    tee = visual.box(pos=(0,0,0), length=0.05, width=0.05, height=0.5,color=visual.color.white)
    ball = visual.sphere(pos=(x,y,z), radius = 0.25, color = visual.color.white)
    ball.trail = visual.curve(color = visual.color.red)

    while y > 0.0:
        visual.rate(100)
        t,x,y,z,vx,vy,vz = golfball_step(t,x,y,z,vx,vy,vz,m,g,B2,S0,w,dt,w_vector,v_vector)
        x_list.append(x)
        y_list.append(y)
        z_list.append(z)
        vx_list.append(vx)
        vy_list.append(vy)
        vz_list.append(vz)
        t_list.append(t)
        v_vector = visual.vector(vx,vy,vz)
        ball.pos = (x,y,z)
        ball.trail.append(pos=ball.pos)

    return t_list,x_list,y_list,z_list,vx_list,vy_list,vz_list
示例#19
0
 def run(self):
     '''
     Run the simulation with racers that had been previously added to the world
     by add_racer method.
     '''
     # create the scene with the plane at the top
     visual.scene.center = visual.vector(0,-25,0)
     visual.box(pos=(0,0,0), size=(12,0.2,12), color=visual.color.green)
     # create the visual objects that represent the racers (balls)
     balls = [ visual.sphere(pos=(index,0,0), radius=0.5) for index in xrange(len(self.racers))]
     for ball, racer in zip(balls, self.racers):
         color = visual.color.blue
         try:
             # try to set the color given by a string
             color = getattr(visual.color, racer.color)
         except AttributeError:
             pass
         ball.trail  = visual.curve(color=color)
     while not reduce(lambda x, y: x and y, [racer.result for racer in self.racers]):
         # slow down the looping - allow only self.time_calibration
         # number of loop entries for a second
         visual.rate(self.time_calibration)
         # move the racers
         for racer in self.racers:
             self.__move_racer(racer) 
             
         for ball, racer in zip(balls, self.racers):
             ball.pos.y = -racer.positions[-1][1]
             ball.pos.x = racer.positions[-1][0]
             ball.trail.append(pos=ball.pos)
             
         self.current_time += self.interval
         self.timeline.append(self.current_time)
示例#20
0
def calculate(x, y, z, vx, vy, vz, dt, m, g, B2, S0, omega):
    """ Calculate the trajectory of a baseball including air resistance and spin by
repeatedly calling the do_time_step function.  Also draw the trajectory using visual python. """
    t = 0.0
    # Establish lists with initial position and velocity components and time.
    x_list = [x]
    y_list = [y]
    z_list = [z]
    vx_list = [vx]
    vy_list = [vy]
    vz_list = [vz]
    t_list = [t]

    # Set up visual elements.
    mound = visual.box(pos=(0,0,0), length=0.1, width=0.5, height=0.03, color=visual.color.white)
    plate = visual.box(pos=(18,0,0), length=0.5, width=0.5, height=0.03, color=visual.color.white)
    ball = visual.sphere(pos=(x,y,z), radius=0.05, color=visual.color.white)
    ball.trail = visual.curve(color=ball.color)

    while y >= 0.0:
        visual.rate(100) # Limit to no more than 100 iterations per second.
        t, x, y, z, vx, vy, vz = do_time_step(t, dt, x, y, z, vx, vy, vz, m, B2, g, S0, omega)
        x_list.append(x)
        y_list.append(y)
        z_list.append(z)
        vx_list.append(vx)
        vy_list.append(vy)
        vz_list.append(vz)
        t_list.append(t)
        ball.pos = (x,y,z)
        ball.trail.append(pos=ball.pos)

    return t_list, x_list, y_list, z_list, vx_list, vy_list, vz_list
def extractXCurve(point):
    """after forwardMap has been called, call this 
    on the x parameter to get a visual curve of the elastica"""
    vcurve = vis.curve()
    for part in point.x:
        vcurve.append([part[0], part[1]])
    return vcurve
示例#22
0
def gettreecable(treepos=V(0, 0, 0)):
    """Returns a single arc of cable from vertical (exiting duct at centre of dipole) to
     horizontal (short distance from base, shading to the ground color).

     The cable is positioned for a Christmas Tree positioned at 'treepos', and the
     cable points towards the APIU at (0,0,0).

     Returned is a tuple (cable, olist) where cable is the frame containing the
     curve (we need a frame for a single curve object, because curve objects can't
     be rotated), and a list containing the single component object.
  """
    cframe = visual.frame()
    cstartpos = treepos + (0, 0, 0.4
                           )  # Where the cable leaves the xmas tree trunk
    theta = visual.atan2(treepos.y, treepos.x)  # Angle to the APIU at (0,0,0)

    carc = visual.paths.arc(radius=0.37,
                            angle1=-visual.pi / 2,
                            angle2=0,
                            up=(0, -1, 0))
    carc.pos = [p + treepos + V(0.37, 0, 0.4) for p in carc.pos[::-1]]

    c1 = visual.curve(frame=cframe,
                      pos=carc,
                      radius=0.0129 / 2,
                      color=color.blue)
    c1.append(pos=treepos + V(1.5, 0, -0.065), color=GCOLOR)
    cframe.rotate(angle=theta + visual.pi, axis=(0, 0, 1), origin=cstartpos)

    return cframe, [c1]
示例#23
0
    def __init__(self, num_objs, ids):
        threading.Thread.__init__(self)

        visual.scene.autoscale = False
        visual.scene.center = (2 * 5 - 1.5, -3, 0)
        vt.scene.title = "Motion Visualizer"

        f = visual.frame()

        self.text = []
        self.objs = []
        self.graphs = []
        self.data = []
        self.index = []
        self.stop = False
        for i in range(num_objs):

            self.text.append(None)
            self.objs.append(VisObj((i * 5, 1, 0), f))
            self.data.append([])
            self.index.append(0)
            self.graphs.append([])
            self.data[-1] = [[], [], []]

            for n in range(100):
                self.data[-1][0].append([(i * 5 - 1.5) + (3.0 / 100) * n, -5,
                                         0])
            for n in range(100):
                self.data[-1][1].append([(i * 5 - 1.5) + (3.0 / 100) * n, -4,
                                         0])
            for n in range(100):
                self.data[-1][2].append([(i * 5 - 1.5) + (3.0 / 100) * n, -3,
                                         0])

            self.graphs[-1].append(
                visual.curve(pos=self.data[-1][0],
                             radius=0.05,
                             color=visual.color.red))

            self.graphs[-1].append(
                visual.curve(pos=self.data[-1][1],
                             radius=0.05,
                             color=visual.color.blue))
            self.graphs[-1].append(
                visual.curve(pos=self.data[-1][2],
                             radius=0.05,
                             color=visual.color.yellow))
示例#24
0
文件: ray.py 项目: mrelich/RayTracer
 def drawRay(self):
     #print "Drawing Ray"
     #print self.points
     self.ray = curve(pos=self.points,
                      color=(0,0,0),
                      #radius=0.005
                      radius=0.002
                      )
示例#25
0
文件: board.py 项目: hlku/sgf_parser
 def __init__(self, **kwargs):
     super(Board, self).__init__(**kwargs)
     
     visual.box(pos = (9, 9, -1),
                size = (20, 20, 1),
                color = (1, 0.75, 0),
                material = visual.materials.wood,
                frame = self)
     # lines
     params = dict(color = (.5, .5, .5), frame = self)
     for i in range(19):
         visual.curve(pos = [(0, i, 0), (18, i, 0)], radius = .05, **params)
     for i in range(19):
         visual.curve(pos=[(i, 0, 0), (i, 18, 0)], radius = .05, **params)
     
     self.stones, self.star = [], []
     for x in itertools.product((4, 10, 16), (4, 10, 16)): self.star.append(x[:])
示例#26
0
 def draw_route(self, route_points_list, color=vs.color.white):
     if self.route is not None:
         self.route.visible = False
         del self.route
     self.route = vs.curve(display=self.route_window,
                           pos=route_points_list,
                           color=color)
     return
示例#27
0
文件: board.py 项目: hlku/sgf_parser
    def __init__(self, **kwargs):
        super(Board, self).__init__(**kwargs)

        visual.box(pos=(9, 9, -1),
                   size=(20, 20, 1),
                   color=(1, 0.75, 0),
                   material=visual.materials.wood,
                   frame=self)
        # lines
        params = dict(color=(.5, .5, .5), frame=self)
        for i in range(19):
            visual.curve(pos=[(0, i, 0), (18, i, 0)], radius=.05, **params)
        for i in range(19):
            visual.curve(pos=[(i, 0, 0), (i, 18, 0)], radius=.05, **params)

        self.stones, self.star = [], []
        for x in itertools.product((4, 10, 16), (4, 10, 16)):
            self.star.append(x[:])
示例#28
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
示例#29
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
示例#30
0
def getbundle(
        spos=None,
        bframe=None):  # spos is  position that cable centre exits the box
    """Returns a single bundle of 64 dipole cables as they exit the APIU. The parameter 'spos'
     is the point at which they exit the SPIU box.

     If the 'bframe' parameter is given, all objects are created inside this frame.

     Note that the cable bundle returned always faces East - it most be rotated around
     'spos' after it's created for bundles exiting the West side of the APIU.

     Returned is a tuple of (cframe, blist) where cframe is the frame containing the cable
     bundle, and blist is the list of component objects."""
    cframe = visual.frame(frame=bframe)
    startz = spos.z  # Height above ground that cable centre exits the APIU box

    # Arc from the entry point (horizontal) to halfway to the ground (vertical)
    carc1 = visual.paths.arc(radius=startz / 2,
                             angle1=visual.pi,
                             angle2=visual.pi / 2,
                             up=(0, -1, 0))
    carc1.pos = [p + spos + V(0, 0, -startz / 2) for p in carc1.pos]
    c1 = visual.curve(frame=cframe,
                      pos=carc1,
                      radius=0.08 / 2,
                      color=color.blue)

    # Arc from halfway to the ground (vertical) to the ground (horizontal)
    carc2 = visual.paths.arc(radius=startz / 2,
                             angle1=visual.pi,
                             angle2=visual.pi / 2,
                             up=(0, 1, 0))
    carc2.pos = [p + spos + V(startz, 0, -startz / 2) for p in carc2.pos]
    c2 = visual.curve(frame=cframe,
                      pos=carc2,
                      radius=0.08 / 2,
                      color=color.blue)

    # Append a point to the curve 1.5m out in the desert, fading from blue to the ground color
    c2.append(pos=spos + V(1.5, 0, -startz), color=GCOLOR)

    blist = [c1, c2]
    return cframe, blist
示例#31
0
def update_grid():
    delete_current_grid()

    if not showSpan:
        return 

    global span_frame

    span_frame = visual.frame() 

    vecs = map(lambda i: visual.vector(vectors[i].axis)*span_fact,selected)
    for v in vecs:
        rest = vecs[0:len(vecs)] # deep copy  
        rest.remove(v)
        all_sums = all_sums_comb(rest)
        for aSum in all_sums:
            visual.curve(frame = span_frame, pos = [aSum,aSum+v], color = span_color)
            if not is_span_positive:
                visual.curve(frame = span_frame, pos = [aSum,aSum-v], color = span_color)
示例#32
0
 def drawGrid(self,
              posn=(0, 0, 0),
              sq=1,
              H=12,
              W=1,
              normal='z',
              colour=clr.white):
     ht = H * sq
     wd = W * sq
     for i in range(0, ht + 1, sq):  # FOR EACH HORIZONTAL LINE
         if normal == 'x':
             vs.curve(pos=[(posn[1] + i, posn[0], posn[2] + wd),
                           (posn[1] + i, posn[0], posn[2])],
                      color=colour)
             #print (posn[0] + posn[1]+i + posn[2]+wd) #for testing purposes
         else:
             vs.curve(pos=[(posn[0], posn[1], posn[2] + i),
                           (posn[0] + wd, posn[1], posn[2] + i)],
                      color=colour)
示例#33
0
 def __init__(self, points, color, manifold):
     self.__points = points
     super(self.__class__, self).__init__(
         visual.curve(
             radius=0.01,
             pos=[manifold.getCurrentPosVec(pos) for pos in points],
             color=color,
             display=manifold.display,
         )
     )
     self.__manifold = manifold
示例#34
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
示例#35
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))
示例#36
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
示例#37
0
	def __init__(self, start=CGAL.Point_2(), end=CGAL.Point_2(), label=None, display=DEFAULT_SCENE):
		super(VSegment_2, self).__init__(start, end)
		self.__repr = None
		self.__line = visual.curve(pos=[(start.x(), start.y()), (end.x(), end.y())])
		#self.color = visual.color.white
		#if label is not None:
		#	self.label = label
		#else:
		#	self.__label = DEF_SEGMENT_LABEL
		
		display.insertVSegments_2(self)	
示例#38
0
    def input(self, data):
        fft = data['fft']

        if (len(self.curves) > self.maxlen):
            todel = self.curves.pop()
            todel.visible = False
            del todel

        for oldcurve in self.curves:
            for point in range(len(oldcurve.pos)):
                oldcurve.pos[point][2] -= self.step

        y = []
        for point in fft:
            y.append(point)
            y.append(point)

        curve = visual.curve(color=visual.color.white,
                             display=self.g,
                             radius=0)

        if data.has_key('dominantbucket'):
            dominant = data['dominantbucket']
        else:
            dominant = False

        if (self.lastdominant != dominant and self.label):
            self.label.visible = False
            del self.label
            self.label = False

        for point in zip(range(len(fft)), fft):
            if dominant and (point[0] + 2) > dominant and (point[0] -
                                                           2) < dominant:
                r = 1
                g = 0
                b = 0

                if (self.lastdominant != dominant and dominant == point[0]):
                    self.label = visual.label(pos=(point[0], 10, 0),
                                              text=str(data['note']),
                                              xoffset=20,
                                              yoffset=12,
                                              height=10,
                                              border=6,
                                              font='sans')
            else:
                r = g = b = point[1] / 3

            curve.append(pos=(point[0], point[1], 0), color=(r, g, b))
        self.lastdominant = dominant

        self.curves.insert(0, curve)
示例#39
0
 def draw(self):
     import visual
     frame = visual.frame()
     outline = visual.curve(frame=frame,
                            pos=[(0.0,0.0,0.0),(1.0,0.0,0.0),
                                 (1.0,1.0,0.0),(0.0,1.0,0.0),
                                 (0.0,0.0,0.0)],color=visual.color.red)
     for e in self.elements:
         outline = []
         for n in e.nodes:
             for d in n.dofs:
                 if d.name=="Displacement":
                     outline.append( (n.position.x + d.value[0],
                                      n.position.y + d.value[1],
                                      0.0) )
                     break
             else:
                 outline.append( (n.position.x, n.position.y,0.0) )
         outline.append(outline[0])
         visual.curve(frame=frame,pos=outline)
     return frame
示例#40
0
文件: plas2.py 项目: anilkunwar/OOF2
 def draw(self):
     import visual
     frame = visual.frame()
     outline = visual.curve(frame=frame,
                            pos=[(0.0,0.0,0.0),(1.0,0.0,0.0),
                                 (1.0,1.0,0.0),(0.0,1.0,0.0),
                                 (0.0,0.0,0.0)],color=visual.color.red)
     for e in self.elements:
         outline = []
         for n in e.nodes:
             for d in n.dofs:
                 if d.name=="Displacement":
                     outline.append( (n.position.x + d.value[0],
                                      n.position.y + d.value[1],
                                      0.0) )
                     break
             else:
                 outline.append( (n.position.x, n.position.y,0.0) )
         outline.append(outline[0])
         visual.curve(frame=frame,pos=outline)
     return frame
示例#41
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
示例#42
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)
示例#43
0
def update_grid():
    delete_current_grid()

    if not showSpan:
        return

    global span_frame

    span_frame = visual.frame()

    vecs = map(lambda i: visual.vector(vectors[i].axis) * span_fact, selected)
    for v in vecs:
        rest = vecs[0:len(vecs)]  # deep copy
        rest.remove(v)
        all_sums = all_sums_comb(rest)
        for aSum in all_sums:
            visual.curve(frame=span_frame,
                         pos=[aSum, aSum + v],
                         color=span_color)
            if not is_span_positive:
                visual.curve(frame=span_frame,
                             pos=[aSum, aSum - v],
                             color=span_color)
示例#44
0
    def input(self,data):
        fft = data['fft']

        if (len(self.curves) > self.maxlen):
            todel = self.curves.pop()
            todel.visible = False
            del todel

        for oldcurve in self.curves:
            for point in range(len(oldcurve.pos)):
                oldcurve.pos[point][2] -= self.step

        y = []
        for point in fft:
            y.append(point)
            y.append(point)

        curve = visual.curve(color=visual.color.white, display=self.g, radius=0)

        if data.has_key('dominantbucket'):
            dominant = data['dominantbucket']
        else:
            dominant = False


        if (self.lastdominant != dominant and self.label):
            self.label.visible = False
            del self.label
            self.label = False

        for point in zip(range(len(fft)),fft):
            if dominant and (point[0] + 2) > dominant and (point[0] - 2) < dominant:
                r = 1
                g = 0
                b = 0

                if (self.lastdominant != dominant and dominant == point[0]):
                    self.label = visual.label(pos=(point[0],10,0),
                                       text=str(data['note']), xoffset=20,
                                       yoffset=12,
                                       height=10, border=6,
                                       font='sans')
            else:
                r = g = b = point[1] / 3

            curve.append(pos=(point[0],point[1],0), color=(r,g,b))
        self.lastdominant = dominant

        self.curves.insert(0,curve)
示例#45
0
def main():
	visual.rate(10)

	a, b, c = 0.2, 0.2, 5.7
	x, y, z = 0.0, 0.0, 0.0
	dt = 0.01
	system = Roessler(a, b, c, x, y, z, dt)

	num_curves = 100
	for i in range(num_curves):
		curve = visual.curve(color = visual.color.white)
		curve_max_points = 1000 # "skipping points" otherwise
		for j in range(curve_max_points):
			system.advance()
			x, y, z = system.get_xyz()
			curve.append(pos = (x, y, z))
示例#46
0
def main():
    visual.rate(10)

    a, b, c = 0.2, 0.2, 5.7
    x, y, z = 0.0, 0.0, 0.0
    dt = 0.01
    system = Roessler(a, b, c, x, y, z, dt)

    num_curves = 100
    for i in range(num_curves):
        curve = visual.curve(color=visual.color.white)
        curve_max_points = 1000  # "skipping points" otherwise
        for j in range(curve_max_points):
            system.advance()
            x, y, z = system.get_xyz()
            curve.append(pos=(x, y, z))
示例#47
0
def main():
    visual.rate(100)

    beta, rho, sigma = 8.0 / 3.0, 28.0, 10.0
    x, y, z = 5.0, 5.0, 5.0
    dt = 0.002
    system = Lorentz(beta, rho, sigma, x, y, z, dt)

    num_curves = 30
    for i in range(num_curves):
        curve = visual.curve(color=visual.color.white)
        curve_max_points = 1000  # "skipping points" otherwise
        for j in range(curve_max_points):
            system.advance()
            x, y, z = system.get_xyz()
            curve.append(pos=(x, y, z))
示例#48
0
def main():
	visual.rate(100)

	beta, rho, sigma = 8.0/3.0, 28.0, 10.0
	x, y, z = 5.0, 5.0, 5.0
	dt = 0.002
	system = Lorentz(beta, rho, sigma, x, y, z, dt)

	num_curves = 30
	for i in range(num_curves):
		curve = visual.curve(color = visual.color.white)
		curve_max_points = 1000 # "skipping points" otherwise
		for j in range(curve_max_points):
			system.advance()
			x, y, z = system.get_xyz()
			curve.append(pos = (x, y, z))
示例#49
0
 def frame(self, sign):
     self.glass = curve(pos=[(sign * self.time, -self.time * 1.1, 0),
                             (sign * self.time * 0.05, -self.time * 0.1, 0),
                             (sign * self.time * 0.05, self.time * 0.1, 0),
                             (sign * self.time, self.time * 1.1, 0),
                             (sign * self.time, self.time * 1.15, 0)],
                        radius=self.time * .025)
     self.base = cylinder(pos=(0, sign * self.time * 1.15, 0),
                          axis=(0, 1, 0),
                          length=self.time * 0.1,
                          radius=self.time * 1.2,
                          color=(.66, .46, .13))
     self.pole = cylinder(pos=(sign * self.time, -self.time * 1.1, 0),
                          axis=(0, 1, 0),
                          length=self.time * 2.3,
                          radius=self.time * 0.06,
                          color=(.66, .46, .13))
def f(alfa, v0):
    vel_fotogramas = 25
    g = 9.81
    v0x = v0 * np.cos(np.deg2rad(alfa))
    v0z = v0 * np.sin(np.deg2rad(alfa))
    t_total = 2 * v0z / g
    x_final = v0x * t_total
    suelo = vs.box(pos=(x_final / 2., -1, 0),
                   size=(x_final, 1, 10),
                   color=vs.color.green)
    canyon = vs.cylinder(pos=(0, 0, 0),
                         axis=(2 * np.cos(np.deg2rad(alfa)),
                               2 * np.sin(np.deg2rad(alfa)), 0))
    bola = vs.sphere(pos=(0, 0, 0))
    bola.trail = vs.curve(color=bola.color)
    flecha = vs.arrow(pos=(0, 0, 0), axis=(v0x, v0z, 0), color=vs.color.yellow)
    labelx = vs.label(pos=bola.pos,
                      text='posicion x = 0 m',
                      xoffset=1,
                      yoffset=80,
                      space=bola.radius,
                      font='sans',
                      box=False,
                      height=10)
    labely = vs.label(pos=bola.pos,
                      text='posicion y = 0 m',
                      xoffset=1,
                      yoffset=40,
                      space=bola.radius,
                      font='sans',
                      box=False,
                      height=10)
    t = 0
    while t <= t_total:
        bola.pos = (v0x * t, v0z * t - 0.5 * g * t**2, 0)
        flecha.pos = (v0x * t, v0z * t - 0.5 * g * t**2, 0)
        flecha.axis = (v0x, v0z - g * t, 0)
        bola.trail.append(pos=bola.pos)
        labelx.pos = bola.pos
        labelx.text = 'posicion x = %s m' % str(v0x * t)
        labely.pos = bola.pos
        labely.text = 'posicion y = %s m' % str(v0z * t - 0.5 * g * t**2)
        t = t + t_total / 100.
        vs.rate(vel_fotogramas)

    return x_final
示例#51
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)
示例#52
0
                background=black,
                forward=(1, 0, 0))

# Inertial reference frame arrows
N = [
    arrow(pos=NO, axis=N1, color=red),
    arrow(pos=NO, axis=N2, color=green),
    arrow(pos=NO, axis=N3, color=blue)
]

torus = ring(pos=CO[0], axis=B2[0], radius=r1, thickness=r2, color=blue)
# Arrows for body fixed coordinates in plane of torus
c1 = arrow(pos=CO[0], axis=C1[0], up=C3[0], color=red)
c3 = arrow(pos=CO[0], axis=C3[0], up=C1[0], color=green)
# Ground contact path
trail = curve()
trail.append(pos=(x[0, 3], x[0, 4], 0.0), color=white)

i = 1
while i < n:
    torus.pos = CO[i]
    torus.axis = B2[i]
    c1.pos = CO[i]
    c3.pos = CO[i]
    c1.axis = C1[i]
    c3.axis = C3[i]
    c1.up = C3[i]
    c3.up = C1[i]
    trail.append(pos=(x[i, 3], x[i, 4], 0.0), color=white)
    i += 1
    rate(k / ts)
示例#53
0
        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:
        l.pos = r
        rate(25)
def vPythSim(a, e, O, I, w, M):
    visual.scene.autoscale = False
    #Asteroid
    a = a
    e = e
    O = radians(O)
    I = radians(I)
    w = radians(w)
    M = radians(M)
    positionEq = equatorial(eclipticPos(position(a, newton(M, e), e), O, I, w),
                            radians(23.437))
    rVector = visual.vector(0, 0, 0)
    rVector.x = positionEq[0]
    rVector.y = positionEq[1]
    rVector.z = positionEq[2]

    #Earth
    earthA = 1.000703137122473
    earthe = 1.599048849057274E-02
    earthO = radians(1.652211903265974E+02)
    earthI = radians(2.744957205807269E-03)
    earthW = radians(2.973932488195502E+02)
    earthM = radians(2.061751020668477E+02)

    earthPos = equatorial(
        eclipticPos(position(earthA, newton(earthM, earthe), earthe), earthO,
                    earthI, earthW), radians(23.437))
    erVector = visual.vector(0, 0, 0)
    erVector.x = earthPos[0]
    erVector.y = earthPos[1]
    erVector.z = earthPos[2]

    ##    def MVcalc(a,k,mu,T):
    ##        n=k*sqrt(mu/a**3)
    ##        return n*T
    ##
    ##    def Mcalc2(a,T,Mo,tOld):
    ##        n=0.01720209894*sqrt(1.000000/a**3)
    ##        return n*(T-tOld)+Mo

    t = 0
    #Where 0 corresponds to the JD of the central observation (where simulation starts)
    dt = 0.5
    asteroid = visual.sphere(pos=rVector * 150, radius=(5), color=color.white)
    asteroid.trail = visual.curve(color=color.white)
    Earth = visual.sphere(pos=erVector * 150,
                          radius=(15),
                          material=materials.earth)
    Earth.trail = visual.curve(color=color.white)
    sun = visual.sphere(pos=(0, 0, 0), radius=(50), color=color.yellow)
    while (1 == 1):
        visual.rate(100)
        t = t + 1
        M = MVcalc(a, 0.01720209894, 1, t)
        E = newton(M, e)
        positionEq = equatorial(eclipticPos(position(a, E, e), O, I, w),
                                radians(23.437))
        rVector.x = positionEq[0]
        rVector.y = positionEq[1]
        rVector.z = positionEq[2]
        asteroid.pos = rVector * 150
        asteroid.trail.append(pos=asteroid.pos)

        earthM = MVcalc(earthA, 0.01720209894, 1, t)
        earthE = newton(earthM, earthe)
        earthPos = equatorial(
            eclipticPos(position(earthA, earthE, earthe), earthO, earthI,
                        earthW), radians(23.437))
        erVector.x = earthPos[0]
        erVector.y = earthPos[1]
        erVector.z = earthPos[2]
        Earth.pos = erVector * 150
        Earth.trail.append(pos=Earth.pos)
    return True
示例#55
0
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]
    if (abs(x) > a or abs(y) > b):
        txt = 'Goal!' if (x > 0 and abs(y) < w) else 'Miss!'
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: "))
e = float(raw_input("Input the value for coefficient of restitution: "))
def draw_bonds(mol):
    for l in mol.bonds:
        b = curve(pos=(mol.atoms[l[0] - 1].xyz[0], mol.atoms[l[0] - 1].xyz[1],
                       mol.atoms[l[0] - 1].xyz[2]))
        b.append(mol.atoms[l[1] - 1].xyz)
v0x = v0 * np.cos(alfa)
v0z = v0 * np.sin(alfa)
t_total = Tv
x_final = 6.75
## Empezamos con visual python (vpython)
## Creamos el 'suelo'
suelo = vs.box(pos=(x_final / 2., -1, 0),
               size=(x_final, 1, 10),
               color=vs.color.green)
## Creamos el 'canon'
canyon = vs.cylinder(pos=(0, 0, 0),
                     axis=(2 * np.cos(alfa), 2 * np.sin(alfa), 0),
                     size=(0, 0, 0, 0))
## Creamos el proyectil y una linea que dejara la estela del proyectil
bola = vs.sphere(pos=(0, 0, 0), radius=0.5, color=vs.color.magenta)
bola.trail = vs.curve(color=vs.color.cyan)
## Creamos el vector que indica la direccion del movimiento (vector velocidad)
flecha = vs.arrow(pos=(0, 0, 0),
                  axis=(v0x, v0z, 0),
                  color=vs.color.yellow,
                  size=(0))
## texto (ponemos etiquetas para informar de la posicion del proyectil)
labelx = vs.label(pos=bola.pos,
                  text='posicion x = 0 m',
                  xoffset=1,
                  yoffset=80,
                  space=bola.radius,
                  font='sans',
                  box=False,
                  height=10)
labely = vs.label(pos=bola.pos,
示例#59
0
 def draw(self):
     self.f = visual.frame()
     self.vis = visual.curve(frame=self.f, x=[0, 1, 2])
     Primitive.draw(self)