Exemplo n.º 1
0
    def __processSeasonData(self, seasonStart, seasonEnd):
        from Season import Season
        
        seasonData = self.__showData[seasonStart : seasonEnd]
        season = Season(self.__showName, seasonData)

        self.__seasons[season.getSeasonNumber()] = season
Exemplo n.º 2
0
    def test_construct_global_features(self):

        season = Season(2013)

        construct_global_features(season)

        self.assertEqual(1, 1)
Exemplo n.º 3
0
    def test_all_player_features(self):

        season = Season(2013)

        all_players = players.find({}).sort('id', pymongo.ASCENDING)
        offensive_features = []
        defensive_features = []

        for player_data in all_players:
            player = Player(player_data['id'])
            print 'Extracting offensive features for {} from the {}'.format(player, season)
            o_features = player_ocluster_features(player, season)
            print 'Extracting defensive features for {} from the {}'.format(player, season)
            d_features = player_dcluster_features(player, season)
            offensive_features.append(o_features)
            defensive_features.append(d_features)

        offensive_features = np.array(offensive_features)
        defensive_features = np.array(defensive_features)

        o_features_file = os.path.join('season_data', '2013', 'player_offense_features.csv')
        d_features_file = os.path.join('season_data', '2013', 'player_defense_features.csv')

        o_header = 'id,ast_pct,ts_pct,orb_pct,usg,ortg,mp_pct'
        d_header = 'id,blk_pct,stl_pct,drb_pct,drtg,pf_pct,mp_pct'

        np.savetxt(o_features_file, offensive_features, delimiter=',', header=o_header)
        np.savetxt(d_features_file, defensive_features, delimiter=',', header=d_header)

        self.assertTrue(os.path.exists(o_features_file))
        self.assertTrue(os.path.exists(d_features_file))
Exemplo n.º 4
0
    def test_player_dcluster_features(self):

        season = Season(2013)
        player = Player(399725)

        features = player_dcluster_features(player, season)
        print features
        self.assertEqual(1, 1)
Exemplo n.º 5
0
    def test_player_multi_game_plot(self):

        player1 = Player(399725)
        season = Season(2013)

        player1.multi_game_shot_chart(season.games)

        self.assertEqual(1, 1)
Exemplo n.º 6
0
    def test_team_dcluster_features(self):

        season = Season(2013)
        team = Team(12)

        features = team_dcluster_features(team, season)
        print features
        self.assertEqual(1, 1)
Exemplo n.º 7
0
class XBS:
    def __init__(self):
        self.Config = Config()
        self.Roster = Roster()
        self.Season = Season()

    def GetTeams(self):
        self.League.GetAllTeams(self.URL_team)

    def GetSeason(self):
        self.Season.GetAllGames(self.URL_game)
Exemplo n.º 8
0
class SeasonTest(TestCase):

    def setUp(self):
        self.season = Season(2013)

    def test_season_init(self):

        self.assertEqual(self.season.season, '2013-2014 NBA Season')
        self.assertEqual(self.season.start_date, dt.datetime(2013, 10, 29, 19, 30))
        self.assertEqual(self.season.end_date, dt.datetime(2014, 4, 15, 20, 0))

    def test_ortg_drtg(self):

        team = Team(6)

        drtg = self.season.drtg(team)
        ortg = self.season.ortg(team)

        print ortg, drtg

        self.assertAlmostEqual(ortg, 111.8, delta=0.5)
        self.assertAlmostEqual(drtg, 109.2, delta=0.5)
Exemplo n.º 9
0
def test_all_player_features(self):

    season = Season(2013)

    all_players = players.find({}).sort('id', pymongo.ASCENDING)
    offensive_features = []

    for player_data in all_players:
        player = Player(player_data['id'])
        print 'Extracting offensive features for {} from the {}'.format(player, season)
        features = player_ocluster_features(player, season)
        offensive_features.append(features)

    offensive_features = np.array(offensive_features)
Exemplo n.º 10
0
    def test_player_ocluster_features(self):

        season = Season(2013)
        player = Player(399725)

        features = player_ocluster_features(player, season)

        self.assertEqual(len(features), 7)
        self.assertEqual(int(features[0]), 399725)
        self.assertAlmostEqual(round(features[1], 2), 19.2, delta=0.05)
        self.assertAlmostEqual(round(features[2], 3), 0.583, delta=0.05)
        self.assertAlmostEqual(round(features[3], 2), 7.7, delta=0.05)
        self.assertAlmostEqual(round(features[4], 2), 29.0, delta=0.5)
        self.assertAlmostEqual(round(features[5], 2), 114, delta=0.5)
Exemplo n.º 11
0
Arquivo: nba.py Projeto: DimosGu/nba
def calc_all_player_times(year, recompute=False):

    class TimeComputationError(Exception):

        def __init__(self, msg):
            self.msg = msg
        def __str__(self):
            return self.msg

    all_players = players.find({}).sort('id', pymongo.ASCENDING)

    print('Loading the {}-{} NBA season'.format(year, year + 1))
    season = Season(year)
    print('Loaded season')
    print('Computing time on court for all players in all games...')

    for player_data in all_players:
        player = Player(player_data['id'])
        games_played = season.get_player_games_in_range(player)
        for game in games_played:
            print('Calculating time on court for {} ({}) in {} ({})'.format(player, player.id, game, game.id))
            boxscore_minutes = game.player_boxscore(player)['totalSecondsPlayed'] / 60.0
            if boxscore_minutes > 0:
                time_on_court = player.time_on_court(game, recompute=recompute)
                computed_minutes = compute_ts_length(time_on_court, unit='minutes')
            else:
                # there's never anything to calculate anyway
                computed_minutes = 0
            if not abs(computed_minutes - boxscore_minutes) <= 0.5:
                print('In computing playing time for {} ({}) in {} ({}):'.format(player, player.id, game, game.id),
                      file=sys.stderr)
                print('Discrepancy between computed time: {0:2.2f}, and boxscore time: {1:2.2f}'.format(computed_minutes, boxscore_minutes),
                      file=sys.stderr)
                #raise TimeComputationError('Discrepancy between computed time: {}, and boxscore time: {}'.format(computed_minutes, boxscore_minutes)

            else:
                print('{} played {} minutes in {}'.format(player, round(computed_minutes, 3), game))
Exemplo n.º 12
0
def test_features():

    season = Season(2013)
    player = Player(399725)

    features = player_ocluster_features(player, season)
Exemplo n.º 13
0
 def __init__(self):
     self.Config = Config()
     self.Roster = Roster()
     self.Season = Season()
Exemplo n.º 14
0
        spam_reader = csv.DictReader(user_file)
        for row in spam_reader:
            name = row.get('name')
            district = row.get('district')
            mother = row.get('mothers name')
            father = row.get('fathers name')
            registration = row.get('date registered')
            actor = Character(name, mother, father, district, registration)
            characters.append(actor)

    # Store a dictionary containing SeasonS objects with key season number
    seasons = {}
    with open('episode_per_season.csv') as appearance_file:
        spam_reader = csv.DictReader(appearance_file)
        for row in spam_reader:
            season = Season(int(row.get('season')))
            seasons[int(row.get('season'))] = season

    # Store characters information per season
    with open('episode_per_season.csv') as appearance_file:
        spam_reader = csv.DictReader(appearance_file)
        for row in spam_reader:
            user = row.get('user')
            episodes = row.get('no of episodes')
            died = row.get('died in this season')
            character = SeasonCharacter(user, episodes, died)
            seasons[int(row.get('season'))].characters()[user] = character

    html = "<!DOCTYPE html><html><head lang=\"en\"><meta charset=\"UTF-8\"><title>GOT Character Profile</title><style>" \
           "table, th, td {border: 1px solid black;}</style></head><body><h1>GOT Character " \
           "Profiles</h1><table><tr><th>Name</th><th>District</th><" \
Exemplo n.º 15
0
    def RetrieveSeason(self, Year):
        try:
            url = self.__baseURL + '/years/' + str(Year) + '/games.htm'
            page = requests.get(url).text
            soup = BeautifulSoup(page, 'html.parser')
            fullTable = soup.find_all('tbody')

            homeWins = 0
            awayWins = 0
            gameWeeks = []
            for i in range(1, 17):
                gameWeeks.append(Week(str(i), []))
            gameWeeks.append(Week('WildCard', []))
            gameWeeks.append(Week('Division', []))
            gameWeeks.append(Week('ConfChamp', []))
            gameWeeks.append(Week('SuperBowl', []))

            for content in fullTable[0].contents:
                if type(content) == NavigableString:
                    continue
                else:
                    # Home Team Won
                    if content.contents[5].text == '':
                        if content.contents[2].text == "Playoffs" or content.contents[2].text == "Date":
                            continue
                        homeTeam = self.__findTeam(content.contents[4].text)
                        homeScore = content.contents[8].text
                        awayTeam = self.__findTeam(content.contents[6].text)
                        awayScore = content.contents[9].text
                        boxscoreURL = self.__baseURL + content.contents[7].contents[0].attrs['href']
                        dateOfGame = self.__findTimeOfGame(Year, content.contents[2].text, content.contents[3].text)
                        weekOfGame = content.contents[0].text
                        homeWins += 1
                    #Away Team won
                    elif content.contents[5].text == '@':
                        homeTeam = self.__findTeam(content.contents[6].text)
                        homeScore = content.contents[9].text
                        awayTeam = self.__findTeam(content.contents[4].text)
                        awayScore = content.contents[8].text
                        boxscoreURL = self.__baseURL + content.contents[7].contents[0].attrs['href']
                        dateOfGame = self.__findTimeOfGame(Year, content.contents[2].text, content.contents[3].text)
                        weekOfGame = content.contents[0].text
                        awayWins += 1
                    #Superbowl
                    elif content.contents[5].text == 'N':
                        homeTeam = self.__findTeam(content.contents[4].text)
                        homeScore = content.contents[8].text
                        awayTeam = self.__findTeam(content.contents[6].text)
                        awayScore = content.contents[9].text
                        boxscoreURL = self.__baseURL + content.contents[7].contents[0].attrs['href']
                        dateOfGame = self.__findTimeOfGame(Year, content.contents[2].text, content.contents[3].text)
                        weekOfGame = content.contents[0].text
                    else:
                        continue

                    for week in gameWeeks:
                        if week.Week == weekOfGame:
                            week.Matches.append(Match(homeTeam, homeScore, awayTeam, awayScore, boxscoreURL, dateOfGame))
                            break

            season = Season(Year, gameWeeks, homeWins, awayWins)

        except Exception as e:
            print(e)
            season = None
        finally:
            return season
Exemplo n.º 16
0
        spam_reader = csv.DictReader(user_file)
        for row in spam_reader:
            name = row.get('name')
            district = row.get('district')
            mother = row.get('mothers name')
            father = row.get('fathers name')
            registration = row.get('date registered')
            actor = Character(name, mother, father, district, registration)
            characters.append(actor)

    # Store a dictionary containing Season objects with key season number
    seasons = {}
    with open('episode_per_season.csv') as appearance_file:
        spam_reader = csv.DictReader(appearance_file)
        for row in spam_reader:
            season = Season(int(row.get('season')))
            seasons[int(row.get('season'))] = season

    # Store character information per season
    with open('episode_per_season.csv') as appearance_file:
        spam_reader = csv.DictReader(appearance_file)
        for row in spam_reader:
            user = row.get('user')
            episodes = row.get('no of episodes')
            died = row.get('died in this season')
            character = SeasonCharacter(user, episodes, died)
            seasons[int(row.get('season'))].characters()[user] = character

    html = "<!DOCTYPE html><html><head lang=\"en\"><meta charset=\"UTF-8\"><title>GOT Character Profile</title><style>" \
           "table, th, td {border: 1px solid black;}</style></head><body><h1>GOT Character " \
           "Profiles</h1><table><tr><th>Name</th><th>District</th><" \
Exemplo n.º 17
0
def modify_doc(doc):
    TOOLS = "pan,wheel_zoom,box_zoom,reset,save"
    season = Season()
    seasons_1990_on = season.seasons_1990_on

    source = ColumnDataSource(
        data={
            "x_3p": seasons_1990_on["3PA"],
            "y_3p": seasons_1990_on["3P"],
            "Tm": seasons_1990_on["Tm"],
            "x_2p": seasons_1990_on["2PA"],
            "y_2p": seasons_1990_on["2P"],
            "Year": seasons_1990_on["Year"],
            "Player": seasons_1990_on["Player"],
        }
    )


    slider = Slider(title="Year", start=1990, end=2017, step=1, value=2006)
    menu_options_list = ["ALL"] + seasons_1990_on["Tm"].unique().tolist()
    menu = Select(options=menu_options_list, value="ALL", title="Team")

    palette = season.get_palette()
    color_mapper = CategoricalColorMapper(
        factors=seasons_1990_on["Tm"].unique().tolist(),
        palette=palette
    )

    TOOLS = "pan,wheel_zoom,box_zoom,reset,save"
    p1 = figure(
        x_axis_label="3 Points Attempted",
        y_axis_label="3 Points Made",
        tools=TOOLS
    )
    p2 = figure(
        x_axis_label="2 Points Attempted",
        y_axis_label="2 Points Made",
        tools=TOOLS
    )



    ###################
    p1.circle(
        "x_3p",
        "y_3p",
        source=source,
        alpha=0.8,
        nonselection_alpha=0.1,
        color=dict(field="Tm", transform=color_mapper),
        legend="Tm",
    )

    p1.legend.location = "bottom_right"
    ####################

    ####################
    p2.circle(
        "x_2p",
        "y_2p",
        source=source,
        alpha=0.8,
        nonselection_alpha=0.1,
        color=dict(field="Tm", transform=color_mapper),
        legend="Tm",
    )

    p2.legend.location = "bottom_right"
    #######################

    hover1 = HoverTool(tooltips=[("Player", "@Player"), ("3 Pointers Attempted", "@y_3p")])
    p1.add_tools(hover1)
    hover2 = HoverTool(tooltips=[("Player", "@Player")])
    p2.add_tools(hover2)

    column1 = column(widgetbox(menu), widgetbox(slider))
    layout = row(column1, p1, p2)

    doc.add_root(layout)

    def callback(attr, old, new):
        if menu.value == "ALL":

            new_x_3p = seasons_1990_on[(seasons_1990_on["Year"] == slider.value)]["3PA"]
            new_y_3p = seasons_1990_on[(seasons_1990_on["Year"] == slider.value)]["3P"]
            new_tm = seasons_1990_on[(seasons_1990_on["Year"] == slider.value)]["Tm"]
            new_x_2p = seasons_1990_on[(seasons_1990_on["Year"] == slider.value)]["2PA"]
            new_y_2p = seasons_1990_on[(seasons_1990_on["Year"] == slider.value)]["2P"]
            new_year = seasons_1990_on[(seasons_1990_on["Year"] == slider.value)][
                "Year"
            ]
            new_player = seasons_1990_on[(seasons_1990_on["Year"] == slider.value)][
                "Player"
            ]
        else:
            new_x_3p = seasons_1990_on[(seasons_1990_on["Year"] == slider.value)]["3PA"]
            new_y_3p = seasons_1990_on[
                (seasons_1990_on["Year"] == slider.value)
                & (seasons_1990_on["Tm"] == menu.value)
            ]["3P"]
            new_tm = seasons_1990_on[
                (seasons_1990_on["Year"] == slider.value)
                & (seasons_1990_on["Tm"] == menu.value)
            ]["Tm"]
            new_x_2p = seasons_1990_on[
                (seasons_1990_on["Year"] == slider.value)
                & (seasons_1990_on["Tm"] == menu.value)
            ]["2PA"]
            new_y_2p = seasons_1990_on[
                (seasons_1990_on["Year"] == slider.value)
                & (seasons_1990_on["Tm"] == menu.value)
            ]["2P"]
            new_year = seasons_1990_on[
                (seasons_1990_on["Year"] == slider.value)
                & (seasons_1990_on["Tm"] == menu.value)
            ]["Year"]
            new_player = seasons_1990_on[
                (seasons_1990_on["Year"] == slider.value)
                & (seasons_1990_on["Tm"] == menu.value)
            ]["Player"]

        source.data = {
            "x_3p": new_x_3p,
            "y_3p": new_y_3p,
            "Tm": new_tm,
            "x_2p": new_x_2p,
            "y_2p": new_y_2p,
            "Year": new_year,
            "Player": new_player,
        }

    slider.on_change("value", callback)
    menu.on_change("value", callback)
Exemplo n.º 18
0
 def getSeasons(self, byear, endyear):
     for x in range(byear, endyear):
         self.seasons.append(Season(x, self.id))
Exemplo n.º 19
0
 def setUp(self):
     self.season = Season(2013)
Exemplo n.º 20
0
    team_list.sort(key=lambda x: x.name)

    for player in player_list:
        player.predict_year()

    # get team info
    for team in team_list:
        team.get_team_info()

    # Read JLT match

    SeasonData2 = wb.sheet_by_name("JLT 19")
    # create object season to be filled with JLT matches
    season_dict = {}
    #season_ident = str(season_ident[0]),str(season_ident[1])
    season_dict[season_ident] = Season(season_ident)

    # Loop through rows of data
    i = 0
    for i in range(SeasonData2.nrows):
        if i == 0:
            for j in range(SeasonData2.ncols):

                for title in jlt_head:
                    if title == SeasonData2.cell_value(i, j):
                        #print(SeasonData2.cell_value(i,j),j)
                        read_in_dict2[title] = j
                continue
        else:

            tmp_player = SeasonData2.cell_value(i, read_in_dict2["Player"])
Exemplo n.º 21
0
from Season import Season



s=Season()
s.simulateSeason()