Example #1
0
    def ReadTrackTree(self, NEvents=-1):
        event = 0
        nentries = self.TrackTree.GetEntriesFast()
        events = []
        for i in xrange(nentries):
            self.entry = self.TrackTree.GetEntry(i)
            events.append(self.TrackTree.event)
        for i in range(max(events) + 1):
            self.AllTracks.append([])
        print "%i events in track file" % max(events)

        for i in xrange(nentries):
            self.entry = self.TrackTree.GetEntry(i)
            track = Track()
            for i in range(self.TrackTree.size):
                track.trackX.append(self.TrackTree.trackX[i])
                track.trackY.append(self.TrackTree.trackY[i])
                track.chi2.append(self.TrackTree.chi2[i])
                track.ndof.append(self.TrackTree.ndof[i])
                track.trackNum.append(self.TrackTree.trackNum[i])
                track.dxdz.append(self.TrackTree.dxdz[i])
                track.dydz.append(self.TrackTree.dydz[i])
                track.iden.append(self.TrackTree.iden[i])
            event = self.TrackTree.event
            track.cluster = self.TrackTree.cluster
            self.AllTracks[event].append(track)
    def ReadTrackTree(self,NEvents=-1):
        event = 0
        nentries = self.TrackTree.GetEntriesFast()
        events = []
        for i in xrange(nentries) :
            self.entry = self.TrackTree.GetEntry(i)
            events.append(self.TrackTree.event)
        for i in range(max(events)+1):
            self.AllTracks.append([])
        print "%i events in track file"%max(events)

        for i in xrange(nentries) :
            self.entry = self.TrackTree.GetEntry(i)
            track = Track()
            for i in range(self.TrackTree.size) :
                track.trackX.append(self.TrackTree.trackX[i])
                track.trackY.append(self.TrackTree.trackY[i])
                track.chi2.append(self.TrackTree.chi2[i])
                track.ndof.append(self.TrackTree.ndof[i])
                track.trackNum.append(self.TrackTree.trackNum[i])
                track.dxdz.append(self.TrackTree.dxdz[i])
                track.dydz.append(self.TrackTree.dydz[i])
                track.iden.append(self.TrackTree.iden[i])
            event = self.TrackTree.event
            track.cluster = self.TrackTree.cluster
            self.AllTracks[event].append(track)
Example #3
0
 def __init__(self, *args, **kwargs):
     super(MyWindow, self).__init__(*args, **kwargs)
     #this clear thing affect the background color
     #comment it out to get a black background
     glClearColor(1, 1.0, 1.0, 1)
     self.fps_display = FPSDisplay(self)
     self.car = CarSprite()
     self.key_handler = key.KeyStateHandler()
     self.testTrack = Track([40, 60, 1200, 600], [240, 260, 800, 200])
     self.testGrid = Grid(40, 60, 1200, 600, 50)
Example #4
0
 def AddPoint(self, x, y):
     print "adding point", x, Track.PositionToTime(x)
     # work out which track is clicked and then pass on the event
     # to that track
     i = y / self.track_height
     if (i < len(self.tracks) and x > self.name_length):
         self.LastClickedTrack = self.tracks[i]
         self.tracks[i].AddPoint(Track.PositionToTime(x - self.name_length))
         # if the track clicked on is the currently playing track
         # reload it so that any changes are taken account of
         if i == self.selectedTrack:
             self.PlayTrack(i)
         self.Refresh()
Example #5
0
def tracksDict(pl, gm_api):
    """
    Takes in a google music playlist dictionary and an authenticated
    MobileClient api. The playlist dictionary contains the field
    'tracks'; itself a list of "properly ordered playlist entry dicts".

    Params:
        pl: google music playlist dict
        gm_api: authenticated Mobileclient object

    Returns: 
        playlist: A list of Track objects, in the order they appear in the
                  given playlist. Returned list may be incomplete if not all
                  tracks are hosted on GMusic.
        notFound: A list of trackIDs foor which metadata could not be found.
    """
    playlist = []
    notFound = []
    # song metadata used as cross-check reference if a playlist entry doesn't
    # have desired metadata
    all_song_meta_data = gm_api.get_all_songs()
    for t in pl['tracks']:
        # Check source:
        # '2' indicates hosted on Google Music, '1' otherwise
        if t['source'] == '2':
            song = Track.Track(title=t['track']['title'],
                               artist=t['track']['artist'])
            playlist.append(song)
        elif t['source'] == '1':
            # Important: when source is '1', playlistEntry object's 'trackId'
            # will correspond w/ a track object's 'id' in all_song_meta_data
            badtrackID = t['trackId']
            song = next((t for t in all_song_meta_data \
                            if t['id'] == badtrackID), None)
            if song != None:
                # create track object, add to new "playlist"
                track_obj = Track.Track(title=song['title'],
                                        artist=song['artist'])
                playlist.append(track_obj)
            else:
                msg = "Error with track " + str(badtrackID) + ": 'source'" + \
                      " field is '1', but could not find matching metadata."
                print(msg, file=sys.stderr)
                notFound.append(badtrackID)
        else:
            msg = "Error with track " + str(t['trackId']) + ": 'source'" + \
                  " field not '1' or '2'."
            print(msg, file=sys.stderr)
            notFound.append(t['trackId'])

    return playlist, notFound
def getFace(video, detector, recognizer):
    while True:
        threshold = 70
        frame = video.get_frame()
        face = detector.detect(frame, False)
        if len(face):
            frame, faces_img = get_images(frame, face)
            for i, face_img in enumerate(faces_img):
                pred, Confidence = recognizer.predict(face_img)

                print 'Confidence: ' + str(round(Confidence))
                print 'Threshold: ' + str(threshold)
                if Confidence < threshold:

                    if tr.track(frame, face) == 1:
                        break
                else:
                    cv2.putText(frame, "Unknown", (face[i][0], face[i][1]),
                                cv2.FONT_HERSHEY_PLAIN, 1.7, (206, 0, 209), 2,
                                cv2.LINE_AA)

        cv2.putText(frame, "ESC to exit", (5, frame.shape[0] - 5),
                    cv2.FONT_HERSHEY_PLAIN, 1.2, (206, 0, 209), 2, cv2.LINE_AA)
        #cv2.imshow('Video', frame)
        if cv2.waitKey(100) & 0xFF == 27:
            sys.exit()
Example #7
0
    def PCA(self):
        if self.pcs == None:
            print "CANNOT DO PCA, scipy isn't loaded"
        print "doing pca"
        motion = self.tracks[self.selectedTrack].GetMotion()
        splits = self.tracks[self.selectedTrack].GetSplits()
        if len(splits) > 0:
            motions = [
                Piavca.SubMotion(motion, split.GetStart(), split.GetEnd())
                for split in splits
            ]
        else:
            motions = [motion]
        splits = [(0, split.GetStart(), split.GetEnd()) for split in splits]
        length = Track.PositionToTime(
            self.track_length) * Track.frames_per_second
        #self.pcs.do_pca([motion], splits, length, Track.frames_per_second)
        self.pcs.addMotions(motions)
        self.pcs.setFramesPerSecond(Track.frames_per_second)
        self.pcs.create()
        #self.pcs.setMotion(motion)

        # load the PCAs into the avatar to play them
        Piavca.Core.getCore().setCurrentTime(0)
        #self.avatar.playMotionDirect(Piavca.PyMotion(self.pcs))
        self.avatar.playMotionDirect(self.pcs)
        Piavca.Core.getCore().setCurrentTime(self.time)
 def build(self):
     
     for elem in sorted(self.path.rglob('*')): # NOTE: <sorted(self.path.glob("**/*"))> gives every file and folder in self.path
         print(type(elem), elem)
         if elem.is_file() and elem.suffix in self.patterns:
             
             self.tracks.append(Track.Track(elem))
Example #9
0
    def addTrackWidget(self):
        self.index = self.count
        self.count += 1
        self.trackArray[self.index] = Track(str(self.count),
                                            str(self.projectPath))

        self.scrollLayout.addRow(self.trackArray[self.index])
Example #10
0
def calculator(xCoords, yCoords, RPMGearVelArr, initialVel):
    '''
    This function takes the array of x coordinates, array of y coordinates and an array with five columns of:
    Power, RPM, Velocity, Torque, Gear Ratio. The initial normal force is calculated using the maximum velocity of the
    engine performance. The for loop iterates over the trackcoordinates, calculating the acceleration from the previous
    point, with a limit on the speed due to the maximum corner velocity. Assuming the acceleration is constant over the
    distance between the points the velocity can be calculated. The output is the time of the lap and a velocity
    distance graph.
    '''

    effectiveRadiusArr = Track.effectiveCurve(
        xCoords, yCoords)  # obtain track coordinates from Track script
    u = initialVel
    vArr = np.array([u])  # create velocity array with first value
    torqueInterpArr = np.array(
        [0])  # create Torque array with 0 as the first value
    entranceVelArr = np.array([])  # create empty array for entrance velocity
    distArr = np.array([0])
    count = 0  # set count equal to 0
    for i in range(0, len(xCoords) - 1):

        count = count + 1  # increase count
        hyp = ((xCoords[i + 1] - xCoords[i])**2 + (yCoords[i + 1] - yCoords[i])
               **2)**0.5  # calculate hypotenuse of points
        dist = distArr[-1] + hyp  # cumulative addition of hyp to the distance
        distArr = np.append(distArr, dist)

        u = vArr[[-1]]  # u is equal to the final value in vArr
        torqueInterp = np.interp(
            u, RPMGearVelArr[:, 2],
            RPMGearVelArr[:, 3])  # interpolate the torque for the
        # given velocity
        torqueInterpArr = np.append(torqueInterpArr, torqueInterp)
        gearRatioInterp = np.interp(
            u, RPMGearVelArr[:, 2],
            RPMGearVelArr[:, 4])  # approximation of interpolating the
        # gear values
        # using function acceleration to calculate the acceleration
        a = acceleration(torqueInterp, gearRatioInterp, finalDriveRatio,
                         efficiency, wheelDiameter, airDensity,
                         dragCoefficient, frontalArea, u, mass, g,
                         rollingResistanceCoefficient)
        v = (
            u**2 + 2 * hyp * a
        )**0.5  # assuming constant acceleration over the distance between the points
        if effectiveRadiusArr[
                i] != 'straight':  # if the effective radius is not 'straight', then the max corner
            # velocity may limit the velocity of the vehicle. If the velocity is larger than the maximum value it is
            # assumed the vehicle will travel at the maximum possible velocity
            float(effectiveRadiusArr[i])
            corner = maxCornerVel(
                tyreFrictionCoefficient,
                normalForce(mass, g, airDensity, liftCoefficient, liftArea,
                            u), mass, effectiveRadiusArr[i], airDensity,
                frontalArea, dragCoefficient, rollingResistanceCoefficient, g)
            if v > corner:
                v = corner
        vArr = np.append(vArr, v)
        entranceVelArr = np.append(entranceVelArr, v)
    return distArr, vArr
Example #11
0
    def loadProject(self):
        print "project loaded"

        fname = QtGui.QFileDialog.getOpenFileName(self, 'Open file')
        json_data = open(fname)
        data = json.load(json_data)
        pprint(data)

        fname = str(fname)

        base = os.path.basename(fname)
        path = os.path.splitext(base)[0]

        print "path " + path

        tracks = len(data["tracks"])
        print "tracks " + str(tracks)

        count = 0
        while count < tracks:
            print data["tracks"][count]["name"]

            self.index = self.count
            self.count += 1
            self.trackArray[self.index] = Track(str(self.count),
                                                str(self.projectPath))
            self.trackArray[self.index].setTrackName(
                data["tracks"][count]["name"])

            self.scrollLayout.addRow(self.trackArray[self.index])

            count += 1

        self.setProjectPath(path)
Example #12
0
    def draw_points(self):
        """
		draw_points: define points on the coordinate of canvas
		"""
        self.chess_points = [[None for i in range(15)] for j in range(15)]

        for i in range(15):
            for j in range(15):
                self.chess_points[i][j] = Track.Point(i, j)
Example #13
0
def main():

    # Google Music MobileClient api
    gm_api = gmusic.login_to_gmusic_with_oauth()
    print('Logged in to Google music using ',  getenv('GMUSIC_OAUTH_CREDS_PATH'))
    all_songs = gm_api.get_all_user_playlist_contents()

    # Spotify api
    sp_api = spotify.login2spotify()
    user = sp_api.me()
    print('Logged in to spotify as ', user['display_name'])
    sp_user_id = user['id']

    found = False
    while not found:
        try:
            pl_name = input("Playlist name: ")
            pl = next((p for p in all_songs if p['name'] == pl_name), None)
            if pl == None:
                print('Could not find playlist with name ', pl_name,
                        ', please try again.')
            else:
                found = True
        except EOFError:
            print('Ok yes goodbye')
            sys.exit(1)

    # Found desired playlist, so get data about its tracks
    all_song_meta_data = gm_api.get_all_songs()

    badtrackID = ''
    tracks = []
    count = 0
    for t in pl['tracks']:
        # Check for bad source.
        # '2' indicates hosted on Google Music, '1' otherwise
        if t['source'] == '1':
            badtrackID = t['trackId']
            song = next((t for t in all_song_meta_data if t['id'] == badtrackID), None)

        else: # t['source'] == '2'
            song = t['track']

        if song is not None:
            count += 1

        title = song['title']
        artist = song['artist']
        album = song['album']

        track = Track(title=title, artist=artist, album=album)
        tracks.append(track)

    new_playlist = Playlist(tracks=tracks, plTitle=pl_name)
    print('ok, added ', count, ' songs to Playlist object with length ', new_playlist.length)
    spotify.new_playlist(sp_api, new_playlist, interactive=True)
Example #14
0
def main():
    setTrack(Track.Track().track)
    """Testing SensorNode"""

    sn = SensorNode(0, 0)
    setPos(coord(5, 5))
    for i in xrange(0, 7):
        sn.direction = i
        result = sn.getResult()
        assert result == 0

    setPos(coord(5, 1))

    sn.direction = 0
    res = sn.getResult()
    assert res == 1

    sn.direction = 2
    res = sn.getResult()
    assert res == 0
    """Testing MoveNode"""

    mn = MoveNode(0, 0)
    res = EvaluateTree(Track.Track().track, coord(5, 1), mn)
    assert res == -1

    mn.direction = 1
    res = EvaluateTree(Track.Track().track, coord(5, 1), mn)
    assert res == 1
    """Testing moveCounting"""

    t = Track.Track()
    mn = MoveNode(0, 0)
    res = EvaluateTree(t.track, coord(5, 5), mn)
    assert res == 0
    res = EvaluateTree(t.track, getPos(), mn)
    assert res == 0
    res = EvaluateTree(t.track, getPos(), mn)
    assert res == 0
    res = EvaluateTree(t.track, getPos(), mn)
    assert res == 1
    res = EvaluateTree(t.track, getPos(), mn)
    assert res == -1
 def convert_to_object(self, spotify_track):
     id = spotify_track['id']
     track_title = spotify_track['name']
     artists = ', '.join([artist['name'] for artist in spotify_track['artists']])
     isrc = ''
     try:
         isrc = spotify_track['external_ids']['isrc']
     except KeyError:
         pass
     return Track(id, track_title, artists, isrc)
Example #16
0
    def __init__(self):

        self.car = Car.Car(220, 420, 40, 20)
        self.track = Track.Track('test', (255, 255, 255))

        self.isRendering = False
        self.observation_space = ((0, 1e9)) * 7

        self.rewardIndex = 0
        self.isRendering = False
    def __init__(self, screen=(540, 840)):
        self.SCREEN = screen
        pygame.init()
        self.logo = pygame.image.load('images.jpg')
        pygame.display.set_icon(self.logo)
        pygame.display.set_caption('run')

        self.screen = pygame.display.set_mode(self.SCREEN)
        self.tracks = Track.Track(self.screen)
        self.tracks.generate_track(self.SCREEN)
        pygame.display.flip()

        self.me = Person.Person(1, self.screen, self.SCREEN)
        self.me.person_draw()

        self.track = Track.Obstacle(self.screen, self.SCREEN)

        self.run = Track.Running(self.tracks.generate_track(self.SCREEN), self.SCREEN, self.me)

        self.default = 0
Example #18
0
    def __init__(self, *args, **kwargs):
        super(MyWindow, self).__init__(*args, **kwargs)
        #this clear thing affect the background color
        #comment it out to get a black background
        glClearColor(1, 1.0, 1.0, 1)
        self.fps_display = FPSDisplay(self)
        self.car = CarSprite()
        self.key_handler = key.KeyStateHandler()
        self.testTrack = Track([40, 60, 1200, 600], [240, 260, 800, 200])
        self.testGrid = Grid(40, 60, 1200, 600, 50)
        self.ai = AI()
        self.train = 0
        self.play = 0
        self.manualSaveCounter = 0

        #printing variable
        self.episodeCounter = self.ai.episodeCounter
        self.stepCounter = self.ai.stepCounter
        self.completeC = 0
        self.minStep = self.ai.maxSteps
        self.toggleGrid = 0
Example #19
0
 def ReadTracks(self, tracksFile):
     self.tracks = []
     self.tracks.append(Track.Track(self.motion, "All", None))
     try:
         file = open(tracksFile, 'r')
         # each line contains a name for the track
         # followed by a list of joint names
         for line in file.readlines():
             joints = line.split()
             self.tracks.append(
                 Track.Track(self.motion, joints[0], joints[1:]))
         print "tracks from file"
         print "self.motion", self.motion
     except IOError:
         for trackname in default_tracks.keys():
             self.tracks.append(
                 Track.Track(self.motion, trackname,
                             default_tracks[trackname]))
         print "self.motion", self.motion
     print "tracks used", self.tracks
     self.SetItemCount(len(self.tracks))
Example #20
0
    def __init__(self, avatar, motion, motion_name, tracksFile, parent, id):
        # the MotionTracks are based on the wxPython VListBox
        print "list constructor"
        wx.VListBox.__init__(self, parent, id)
        print "after parent constructor"

        self.distancemeasure = None

        # the Motion tracks will control time in Piavca, not
        # the piavca timer
        Piavca.Core.getCore().setAutoTimeOff()
        self.showfootplants = 0
        self.SetTime(0)
        self.playing = 0

        # the avatar the motion is played on
        self.avatar = avatar
        # the motion being analysed
        self.motion = motion
        self.motion_name = motion_name
        self.motiongraph = None
        # play the motion on the avatar
        self.avatar.playMotionDirect(motion)

        # set up the parameters of the tracks
        self.track_height = 20
        self.name_length = 60
        self.track_length = Track.TimeToPosition(motion.getMotionLength())
        print "track length", self.track_length, "motionlength", motion.getMotionLength(
        )
        self.selectedTrack = None
        # read in a specification of which tracks to use
        self.ReadTracks(tracksFile)

        # the last track that the user interacted with
        # (for undoing)
        self.LastClickedTrack = None

        # the size of the window
        windowlength = self.GetLength()
        windowheight = self.GetHeight()
        self.SetSize(wx.Size(windowlength, windowheight))
        print "end of list constructor"
        print "item count", self.GetItemCount()

        # start without any Principal Components
        #self.pcs = ComponentAnalysis.ComponentAnalysis()
        self.pcs = None
        try:
            self.pcs = Piavca.PCAMotion()
        except:
            pass
Example #21
0
    def OnDrawBackground(self, dc, rect, item):
        #print "drawing background", item
        if item == self.selectedTrack:
            dc.SetBrush(wx.Brush("orange"))
        else:
            dc.SetBrush(wx.Brush("white"))
        dc.DrawRectangle(rect.GetX(), rect.GetY(), rect.GetWidth(),
                         rect.GetHeight())

        dc.SetBrush(wx.Brush("blue"))
        dc.DrawRectangle(
            Track.TimeToPosition(self.time) + self.name_length, rect.GetTop(),
            5, rect.GetHeight())
Example #22
0
def main():

    # Organism

    # Dendraster

    # Largest Organism diameter in mm
    Dorg = 0.3

    dataFolder = '/Volumes/GRAVMACH1 2/HopkinsEmbroyologyCourse_GoodData/2018_06_11/Dendraster_starved_11Days_nofood'

    # Load the set of tracks we want to analyze
    TrackNames = {0: 'Dendraster1', 1: 'Dendraster2', 2: 'Dendraster3'}

    TrackFile = 'track.csv'

    SquaredDisp_XY = []
    SquaredDisp_Z = []

    trackLen_array = np.zeros(len(TrackNames.keys()))

    #    SquaredDisp_subtracks =
    for ii, currFolder in TrackNames.items():

        Track_curr = Track.GravMachineTrack(
            os.path.join(dataFolder, currFolder, TrackFile))

        trackLen_array[ii] = Track_curr.trackLen

        SquaredDisp_Z.append(
            squared_displacement(Track_curr.Z, 0, Track_curr.trackLen))

        SquaredDisp_XY.append(
            squared_displacement(Track_curr.X, 0, Track_curr.trackLen) +
            squared_displacement(Track_curr.Y, 0, Track_curr.trackLen))

    maxTrackLen = np.max(trackLen_array)

    stackedArray_Z = np.zeros((len(TrackNames.keys(), maxTrackLen)))
    stackedArray_XY = np.zeros((len(TrackNames.keys(), maxTrackLen)))

    for ii in TrackNames.keys():
        stackedArray_Z[ii, :trackLen_array[ii]] = SquaredDisp_Z[ii]
        stackedArray_XY[ii, :trackLen_array[ii]] = SquaredDisp_XY[ii]

    stackedArray_Z = np.ma.array(stackedArray_Z, mask=stackedArray_Z == 0)
    stackedArray_XY = np.ma.array(stackedArray_XY, mask=stackedArray_XY == 0)

    RMSD_Z = (stackedArray_Z.mean(axis=0))
    RMSD_XY = (stackedArray_XY.mean(axis=0))
Example #23
0
def build(json_path):
    connections.create_connection(hosts=['localhost'])

    music = Index('music')

    # define custom settings
    music.settings(number_of_shards=1, number_of_replicas=0)

    # delete the index, ignore if it doesn't exist
    music.delete(ignore=404)

    # create the index in elasticsearch
    # music.create()
    Track.init()

    track_dict = import_dict(json_path)

    track_list = []
    for key in track_dict:
        latitude = convert(track_dict[key]["artist_latitude"])

        longitude = convert(track_dict[key]["artist_longitude"])

        song_hotttnesss = convert(track_dict[key]["song_hotttnesss"])

        danceability = convert(track_dict[key]["danceability"])

        duration = convert(track_dict[key]["duration"])

        track = Track(track_id=track_dict[key]["track_id"],
                      title=track_dict[key]["title"],
                      lyric=track_dict[key]["original_lyrics"],
                      artist_name=track_dict[key]["artist_name"],
                      artist_id=track_dict[key]["artist_id"],
                      artist_location=track_dict[key]["artist_location"],
                      genres=track_dict[key]["genre"],
                      album=track_dict[key]["release"],
                      year=track_dict[key]["year"],
                      similar_artists=track_dict[key]["similar_artists"],
                      artist_latitude=latitude,
                      artist_longitude=longitude,
                      song_hotttnesss=song_hotttnesss,
                      danceability=danceability,
                      duration=duration)
        track.meta.id = key
        track_list.append(track)

    print len(track_list)
    es = Elasticsearch()
    helpers.bulk(es, (d.to_dict(include_meta=True) for d in track_list))
Example #24
0
class MyWindow(pyglet.window.Window):
    def __init__(self, *args, **kwargs):
        super(MyWindow, self).__init__(*args, **kwargs)
        #this clear thing affect the background color
        #comment it out to get a black background
        glClearColor(1, 1.0, 1.0, 1)
        self.fps_display = FPSDisplay(self)
        self.car = CarSprite()
        self.key_handler = key.KeyStateHandler()
        self.testTrack = Track([40, 60, 1200, 600], [240, 260, 800, 200])
        self.testGrid = Grid(40, 60, 1200, 600, 50)

    def on_draw(self):
        glClear(GL_COLOR_BUFFER_BIT)
        self.fps_display.draw()
        self.testGrid.draw()
        self.testTrack.draw()
        self.car.draw()

    def on_key_press(self, symbol, modifiers):
        if symbol == key.UP:
            print('accelerate')
            self.car.goStraight()
        elif symbol == key.DOWN:
            print('reverse')
            self.car.goReverse()
        elif symbol == key.LEFT:
            print('turn left')
            self.car.turnLeft()
        elif symbol == key.RIGHT:
            print('turn right')
            self.car.turnRight()
        elif symbol == key.ESCAPE:
            pyglet.app.exit()

    def update(self, dt):
        pass
Example #25
0
 def OnLeftClick(self, x, y):
     print "OnLeftClick"
     self.restartPlaying = 0
     if x < self.name_length:
         i = y / self.track_height
         if (i < len(self.tracks)):
             self.SelectTrack(i)
     else:
         self.SetTime(Track.PositionToTime(x - self.name_length))
         # restart playing to get make sure it plays from the new time
         if self.playing:
             self.Stop()
             self.restartPlaying = 1
         else:
             self.restartPlaying = 0
Example #26
0
    def __init__(self, target=None, height=0, width=0):
        """
		Initializing the chessboard by drawing points and grids.

		Attributes:
		target: a drawing object. It uses to add the title of the frame. 
		height: an integer that stands for the height of canvas.
		width: an integer that stands for the width of canvas.
        Track_Record: track the chessbroad status.

        Then, draw points and grids on the canvas.
		"""
        tkinter.Canvas.__init__(self, target, height=height, width=width)
        self.Track_Record = Track.Track_Record()
        self.draw_points()  #draw points on canvas
        self.draw_canvas()  #draw grids on canvas
Example #27
0
    def __init__(self, pop_size, mut_rate):
        self.pop_size = pop_size
        self.mut_rate = mut_rate
        self.tracks = []

        # Seeds the initial population with random tracks
        for i in range(pop_size):
            track = Track()
            track.random(32)
            track.normalize()
            hq.heappush(self.tracks, track)
Example #28
0
    def mousemoving_map(self, event):
        self.clean_markings()

        # TODO: there is maybe stil a bug in CROSSING = False in seldom cases?
        self.pos = event.pos
        spos = self.is_station_pos(self.pos)
        # TODO: there should be no station in the way
        #       (plus a little extrasize)
        #       or: minimum angle between tracks
        if self.draw_status and spos and not is_in_range(
                self.pos, self.startpos):
            # create a potential new track
            if (not DOUBLE_TRACKS and not self.is_track(self.startpos, spos)
                    and not self.is_track(spos, self.startpos)):
                if (len(self.get_station(spos).get_tracks()) < MAXSTATIONTRACKS
                        and len(self.get_station(
                            self.startpos).get_tracks()) < MAXSTATIONTRACKS):
                    if 'track' in DEBUG:
                        print("stop drawing at ", self.pos, " moving to ",
                              spos)
                    if self.score >= TRACKCOST:
                        self.status = "Build track for $" + str(TRACKCOST)
                        self.score -= TRACKCOST
                        if self.have_line:
                            if 'track' in DEBUG:
                                print("appending track to line with color",
                                      self.drawing_color)
                            # TODO: parameter in self should not be necessary
                            newtrack = Track.Track(self, self.startpos, spos,
                                                   self.drawing_color,
                                                   self.line, 0)
                        else:
                            if 'track' in DEBUG: print("creating new line...")
                            self.line = Line.Line(self, self.startpos, spos)
                            self.lines.append(self.line)
                            self.have_line = True
                        self.startpos = spos
                    else:
                        self.status = "Not enough money left to build track for $" + str(
                            TRACKCOST)
                else:
                    self.status = "to many tracks at station!"
            else:
                self.status = "no doubletracks allowed!"
Example #29
0
def init(data):
    data.width = width
    data.height = height
    data.size = (data.width, data.height)
    data.screen = pygame.display.set_mode(data.size)
    data.fps = 60
    Obstacle.Obstacle.init()
    data.obstacles = pygame.sprite.Group()
    data.leftObstacles = pygame.sprite.Group()
    data.midObstacles = pygame.sprite.Group()
    data.rightObstacles = pygame.sprite.Group()
    Explosion.init()
    data.explosions = pygame.sprite.Group()
    data.bg = Colors.black
    data.bg = pygame.image.load("Images/background4.png").convert()
    data.bg = pygame.transform.scale(data.bg, (data.width, data.height))
    data.track = Track.Track(data)
    Player.init(data)
    data.players = pygame.sprite.GroupSingle()
    data.leftPlayers = pygame.sprite.GroupSingle()
    data.midPlayers = pygame.sprite.GroupSingle()
    data.rightPlayers = pygame.sprite.GroupSingle()
    data.scrollY = 0
    data.score = 0
    data.mode = "splashScreen"
    data.gameModes = ["Groove Mode", "Rhythm Mode"]
    data.title = pygame.image.load("Images/title.png")
    data.instructions = pygame.image.load("Images/instructions.png")
    data.running = True
    data.songsPath = "Music"
    data.songNames = [i for i in os.listdir(data.songsPath) \
                    if not os.path.isdir(data.songsPath + '/' + i)]
    data.songs = [
        font.render(i[:-4], False, Colors.white) for i in data.songNames
    ]
    data.highlighted = 0
    data.lanes = 3
    data.delay = 3000  # in ms,  3 seconds
    data.songGameOffset = .75  # in seconds
    data.curIndex = -1
    data.lastLane = 0
    data.lastIndexObstacleAdded = 0
    data.indecesBetweenObstacles = 10
Example #30
0
def _load_playlist(manager, playlist_filename):
    print "Loading playlist '" + playlist_filename + "'"
    with open(playlist_filename, "r") as f:
        content = f.readlines()
        for l in content:
            soundpath = l.rstrip()
            if soundpath:
                try:
                    imagepath = soundpath + ".bmp"

                    sound, image = _get_sound_and_image(soundpath, imagepath)
                    if sound != None:
                        track = Track.Track(sound,
                                            soundpath.split("/")[-1], image)

                        manager.add(track)
                except RuntimeError:
                    print "Error when loading sound '" + l + "'"
        f.close()
Example #31
0
 def __init__(self, game, start, end):
     self.game = game
     self.color = game.LINES[-1]
     self.tracks = []
     self.stations = [start, end]
     newtrack = Track.Track(self.game, start, end, self.color, self)
Example #32
0
# (Tau=torque,alpha=alpha,beta=beta,v0=14)
#speed, err= sp.integrate.quad( accelbalance ,0,1, args=(tiger19 , tire , Tau , v0 ))
#print speed

def brakebalance(u,t,car,tire,v0):
    u1, u2=u
        #u1=x u2=x'
    beta=( 2*car.massv ) / ( car.cd * const.rhoair * car.frontarea )
    gamma=( 2*car.massv ) / ( tire.mu * car.cl * const.rhoair * car.frontarea )
    uprime=[u2 , -tire.mu * sp.constants.g - ( 1/gamma + 1/beta ) * u2**2]
    return uprime
  
#print sp.integrate.odeint(brakebalance,[0,14],np.linspace(0,2,100),args=(tiger19,tire,v0))

#Track must start and end with corner (can be same corner if continous track)
track1=Track()
track1.add_feature(Corner(10,25))
track1.add_feature(Straight(70))
track1.add_feature(Corner(10,25))
track1.add_feature(EndFeature)

def LapTimeCalc(Track,Car,Tire,tau):
    vlast=0.01
    dt=.001
    laptime=float(0)

    for i in range(Track.num_features()):
        print i
        feature = Track._features[i]        
        if isinstance(Track._features[i],EndFeature):
            next_feature=Track.features[0]            
    def GetTrack(self,i) :

        self.getEvent(i)
        posX_tmp = []
        posY_tmp = []
        dxdz_tmp = []
        dydz_tmp = []
        iden_tmp = []
        chi2_tmp = []
        ndof_tmp = []
        trackNum_tmp = []
        nTrackParams_tmp = 0


        tracks = []

        #--------------------- self.t_nTrackParams = self.TrackTree.nTrackParams
        #------------------------------------- self.t_euEv= self.TrackTree.euEvt
        #------------------------------------- self.t_posX = self.TrackTree.xPos
        #-------------------------------------- self.t_posY= self.TrackTree.yPos
        #-------------------------------------- self.t_dxdz= self.TrackTree.dxdz
        #-------------------------------------- self.t_dydz= self.TrackTree.dydz
        #-------------------------------------- self.t_iden= self.TrackTree.iden
        #------------------------------ self.t_trackNum= self.TrackTree.trackNum
        #-------------------------------------- self.t_chi2= self.TrackTree.chi2
        #------------------------------------- self.t_ndof = self.TrackTree.ndof

        for data in self.t_posX :
            posX_tmp.append(data)
        for data in self.t_posY :
            posY_tmp.append(data)
        for data in self.t_iden :
            iden_tmp.append(data)
        for data in self.t_dxdz :
            dxdz_tmp.append(data)
        for data in self.t_dydz :
            dydz_tmp.append(data)
        for data in self.t_chi2 :
            chi2_tmp.append(data)
        for data in self.t_ndof :
            ndof_tmp.append(data)
        for data in self.t_trackNum :
            trackNum_tmp.append(data)

        nTrackParams_tmp=self.t_nTrackParams

        if len(trackNum_tmp)>0 :
            for j in range(max(trackNum_tmp)+1) :
                aTrack = Track()
                ndata = nTrackParams_tmp/(max(trackNum_tmp)+1)
                #print "nTrackParam : %i len(trackNum %i)"%(nTrackParams_tmp,max(trackNum_tmp)+1)
                aTrack.trackX = posX_tmp[j*ndata:j*ndata+ndata]
                aTrack.trackY = posY_tmp[j*ndata:j*ndata+ndata]
                for index,element in enumerate(aTrack.trackX) :
    #!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1
                    aTrack.trackX[index] = aTrack.trackX[index]-halfChip_X-pitchX/2.
                    aTrack.trackY[index] = aTrack.trackY[index]-halfChip_Y-pitchY/2.
                aTrack.iden = iden_tmp[j*ndata:j*ndata+ndata]
                aTrack.chi2 = chi2_tmp[j*ndata:j*ndata+ndata]
                aTrack.trackNum = trackNum_tmp[j*ndata:j*ndata+ndata]
                aTrack.ndof = ndof_tmp[j*ndata:j*ndata+ndata]
                aTrack.dxdz = dxdz_tmp[j*ndata:j*ndata+ndata]
                aTrack.dydz = dydz_tmp[j*ndata:j*ndata+ndata]

                if(aTrack.chi2[0]<self.Chi2_Cut):
                    tracks.append(aTrack)

                #print aTrack.chi2
        self.AllTracks.append(tracks)