Esempio n. 1
0
def print_weekly_stats(league: League, team: Team, week: int):
    ''' Print the weekly stats for the team during a given week. '''

    lineup = get_lineup(league, team, week)
    stats_table = [
        ['Week Score: ', team.scores[week - 1]],
        ['Best Possible Lineup: ',
         get_best_lineup(league, lineup)],
        ['Opponent Score: ', team.schedule[week - 1].scores[week - 1]],
        ['Weekly Finish: ',
         get_weekly_finish(league, team, week)],
        ['Best Trio: ', get_best_trio(lineup)],
        ['Number of Injuries: ', get_num_out(lineup)],
        ['Starting QB pts: ',
         avg_slot_score(lineup, 'QB')],
        ['Avg. Starting RB pts: ',
         avg_slot_score(lineup, 'RB')],
        ['Avg. Starting WR pts: ',
         avg_slot_score(lineup, 'WR')],
        ['Starting TE pts: ',
         avg_slot_score(lineup, 'TE')],
        ['Starting Flex pts: ',
         avg_slot_score(lineup, 'RB/WR/TE')],
        ['Starting DST pts: ',
         avg_slot_score(lineup, r'D/ST')],
        ['Starting K pts: ', avg_slot_score(lineup, 'K')],
        ['Total Bench pts: ', sum_bench_points(lineup)]
    ]

    print(
        '\n',
        table(stats_table, headers=['Week ' + str(week), ''], numalign='left'))
Esempio n. 2
0
def printCurrentStandings(league):
    ''' Inputs: None
        Outputs: table (prints current standings)
        This function prints the current standings for a league.
        This function does NOT account for tiebreakers.
    '''
    results = []
    for teamId in range(1, league.numTeams + 1):
        wins = league.teams[teamId].wins
        losses = league.teams[teamId].losses
        ties = league.teams[teamId].ties
        pf = league.teams[teamId].pointsFor
        results += [[league.teams[teamId], wins, losses, ties, pf]]
    results.sort(key=lambda x: x[4],
                 reverse=True)  # Sort first based on points for
    results.sort(key=lambda x: x[1],
                 reverse=True)  # Sort second based on win total
    results.sort(key=lambda x: x[2],
                 reverse=False)  # Sort third based on loss total
    resultsTable = []
    for team in results:
        resultsTable += [[
            team[0].teamName, team[1], team[2], team[3], team[4], team[0].owner
        ]]
    print(
        '\nWeek', league.currentWeek, '\n',
        table(resultsTable,
              headers=[
                  'Team', 'Wins', 'Losses', 'Ties', 'Points Scored', 'Owner'
              ],
              floatfmt='.2f'),
        '\n\n*These standings do not account for tiesbreakers')
    return resultsTable
Esempio n. 3
0
 def printWeeklyStats(self, week):
     ''' Print the weekly stats for the team during a given week. '''
     statsTable = [
         ['Week Score: ', self.scores[week]],
         ['Best Possible Lineup: ',
          self.bestLineup(week)],
         ['Opponent Score: ', self.schedule[week].scores[week]],
         ['Weekly Finish: ', self.weeklyFinish(week)],
         ['Best Trio: ', self.bestTrio(week)],
         ['Number of Injuries: ', self.numOut(week)],
         ['Starting QB pts: ',
          self.avgStartingScore(week, 0)],
         ['Avg. Starting RB pts: ',
          self.avgStartingScore(week, 2)],
         ['Avg. Starting WR pts: ',
          self.avgStartingScore(week, 4)],
         ['Starting TE pts: ',
          self.avgStartingScore(week, 6)],
         ['Starting Flex pts: ',
          self.avgStartingScore(week, 23)],
         ['Starting DST pts: ',
          self.avgStartingScore(week, 16)],
         ['Starting K pts: ',
          self.avgStartingScore(week, 17)],
         ['Total Bench pts: ',
          self.totalBenchPoints(week)]
     ]
     print(
         '\n',
         table(statsTable,
               headers=['Week ' + str(week), ''],
               numalign='left'))
Esempio n. 4
0
def printExpectedStandings(league, week):
    ''' Inputs: week that just passed
        Outputs: table (prints expected standings)
        This function predicts the expected final standings for a league based
        on the power rankings through a given week.
        This function does NOT account for tiebreakers.
    '''
    results = []
    for teamId in range(1, league.numTeams + 1):
        wins, losses, ties = league.expectedFinish(teamId, week)
        results += [[league.teams[teamId], wins, losses, ties]]
    results.sort(key=lambda x: x[1],
                 reverse=True)  # Sort first based on win total
    results.sort(key=lambda x: x[2],
                 reverse=False)  # Sort second based on loss total
    resultsTable = []
    for team in results:
        resultsTable += [[
            team[0].teamName, team[1], team[2], team[3], team[0].owner
        ]]
    print(
        '\nWeek', week, '\n',
        table(resultsTable,
              headers=['Team', 'Wins', 'Losses', 'Ties', 'Owner'],
              floatfmt='.2f'),
        '\n\n*These standings do not account for tiesbreakers')
    return resultsTable
Esempio n. 5
0
def printStats(items, tableFormat=''):
    ''' Expects output from collectTotalsValues, i.e.
    a dict with key - metric, and value - list of values'''
    rows = ([
        [ h, fmtFloat(np.sum(vals)), fmtFloat(np.mean(vals)), fmtFloat(np.median(vals)), fmtFloat(stats.tstd(vals)) ] for h, vals in items
    ])
    print(table(rows,
                headers = [ 'sum', 'mean', 'median', 'std dev' ],
                tablefmt = getTableFormat(tableFormat)))
Esempio n. 6
0
def printWeeklyStats(league, week):
    ''' Prints weekly stat report for a league during a given week. '''
    last = league.numTeams
    statsTable = [
        ['Most Points Scored: ',
         sortWeeklyScore(league, week)[1].owner],
        ['Least Points Scored: ',
         sortWeeklyScore(league, week)[last].owner],
        ['Best Possible Lineup: ',
         sortBestLineup(league, week)[1].owner],
        ['Best Trio: ', sortBestTrio(league, week)[1].owner],
        ['Worst Trio: ',
         sortBestTrio(league, week)[last].owner],
        ['Best Lineup Setter',
         sortDifference(league, week)[1].owner],
        ['Worst Lineup Setter',
         sortDifference(league, week)[last].owner],
        ['---------------------', '----------------'],
        ['Best QBs: ',
         sortPositionScore(league, week, 0)[1].owner],
        ['Best RBs: ',
         sortPositionScore(league, week, 2)[1].owner],
        ['Best WRs: ',
         sortPositionScore(league, week, 4)[1].owner],
        ['Best TEs: ',
         sortPositionScore(league, week, 6)[1].owner],
        ['Best Flex: ',
         sortPositionScore(league, week, 23)[1].owner],
        ['Best DST: ',
         sortPositionScore(league, week, 16)[1].owner],
        ['Best K: ', sortPositionScore(league, week, 17)[1].owner],
        ['Best Bench: ',
         sortBenchPoints(league, week)[1].owner],
        ['---------------------', '----------------'],
        ['Worst QBs: ',
         sortPositionScore(league, week, 0)[last].owner],
        ['Worst RBs: ',
         sortPositionScore(league, week, 2)[last].owner],
        ['Worst WRs: ',
         sortPositionScore(league, week, 4)[last].owner],
        ['Worst TEs: ',
         sortPositionScore(league, week, 6)[last].owner],
        ['Worst Flex: ',
         sortPositionScore(league, week, 23)[last].owner],
        ['Worst DST: ',
         sortPositionScore(league, week, 16)[last].owner],
        ['Worst K: ',
         sortPositionScore(league, week, 17)[last].owner],
        ['Worst Bench: ',
         sortBenchPoints(league, week)[last].owner]
    ]
    print('\n', table(statsTable, headers=['Week ' + str(week), '']))

    # ['Most Injuries: ', league.sortNumOut(week)[last].owner.split(' ')[0]],
    # ['Least Injuries: ', league.sortNumOut(week)[0].owner.split(' ')[0]],
    return statsTable
Esempio n. 7
0
def printCorrelation(items, tableFormat=''):
    ''' Expects output from collectTotalsValues, i.e.
    a dict with key - metric, and value - list of values'''
    rows = ([[h] + [
        fmtFloat(stats.pearsonr(v, v2)[0]) for a, v2 in items
    ] for h, v in items])

    print(table(rows,
                headers = [ key for key, val in items],
                tablefmt = getTableFormat(tableFormat)))
Esempio n. 8
0
def printLuckIndex(league, week):
    ''' This function prints the index quantifying how 'lucky' a team was all season long (up to a certain week) '''
    lucks = []
    for teamId in range(1, league.numTeams + 1):
        luck = league.seasonLuckIndex(teamId, week)
        lucks.append([
            league.teams[teamId].teamName,
            round(luck, 2), league.teams[teamId].owner
        ])
    lucks.sort(key=lambda x: x[1], reverse=True)
    print('\nThrough Week %d\n' % (week),
          table(lucks, headers=["Team", "Luck Index", "Owner"]))
    return lucks
Esempio n. 9
0
def print_dfa(sigma, delta, q0, f):
    headers = [''] + sigma
    body = []

    for q, edges in delta.items():
        row = get_row(q, q0, f)

        for p in edges.values():
            row.append(p if p else '-')

        body.append(row)

    print(table(body, headers, 'pretty'))
Esempio n. 10
0
def printPowerRankings(league, week):
    ''' Print my power rankings in a nice table. '''
    powerRankings = []
    for teamId in range(1, league.numTeams + 1):
        powerRankings += [[
            league.teamTotalPRank(teamId, week), league.teams[teamId]
        ]]
    sortedRankings = sorted(powerRankings, key=lambda x: x[0], reverse=True)
    powerRankingsTable = []
    for team in sortedRankings:
        powerRankingsTable += [[team[1].teamName, team[0], team[1].owner]]
    print(
        '\n', 'Week ', week, '\n',
        table(powerRankingsTable,
              headers=['Team', 'Power Index', 'Owner'],
              floatfmt='.2f'))
    return powerRankingsTable
Esempio n. 11
0
def main(confFile,
         tableFmt = ('t', 'psql', '')):
    global tableFormat
    tableFormat = tableFmt

    with open(confFile) as f:
        h = []
        v = []
        for line in f.readlines():
            if line.startswith('trans-') or line.startswith('state-'):
                ind = line.index('=')
                feature = line[:ind]
                value = line[ind + 1:]

                h.append(feature)
                v.append(value)
    print(table([v], headers=h, tablefmt=tableFmt))
Esempio n. 12
0
def printTable(allValues):
    tableHeaders = [ 'E?', 'Metric' ] + TARGETS
    rows = []
    for e, m in itertools.product(EXPERIMENTS, METRICS):
        metricValues = [ val.value for val
                         in filter(lambda x: x.metric == m and x.experiment == e,
                                   allValues)
        ]
        if not metricValues:
            continue
        row = [ e, m ]
        for value in metricValues:
            row.append('%0.5f' % value)
        while len(row) < len(METRICS) + 2:
            row.append('0')
        rows.append(row)

    print(table(rows, headers=tableHeaders, tablefmt='latex'))
Esempio n. 13
0
def print_current_standings(league: League):
    ''' Inputs: None
        Outputs: table (prints current standings)
        This function prints the current standings for a league.
        This function does NOT account for tiebreakers.
    '''
    standings = league.standings()
    results_table = []
    for team in standings:
        results_table += [[
            team.team_name, team.wins, team.losses, team.ties, team.points_for,
            team.owner
        ]]
    print(
        '\nWeek {}\n'.format(league.currentMatchupPeriod),
        table(results_table,
              headers=[
                  'Team', 'Wins', 'Losses', 'Ties', 'Points Scored', 'Owner'
              ],
              floatfmt='.2f'))
import requests
from tabulate import tabulate as table
from bs4 import BeautifulSoup as bs
data = []
page = requests.get(
    "https://www.livemint.com/news/india/coronavirus-cases-in-india-cross-37-000-death-toll-at-1-218-state-wise-tally-11588388406126.html"
)
#print(page.status_code)
parsed_page = bs(page.content, "lxml")
rows = parsed_page.find_all('p')
for row in rows:
    if '-' in row.text:
        if row.text.split("-")[1].rstrip().lstrip().isnumeric():
            row = row.text.split("-")
            data.append((row[0].strip(), row[1].strip()))

print(table(data, headers=("STATES", "TOTAL CASES"), tablefmt="grid"))
Esempio n. 15
0
def run_test():
    global t0, h, xp0, t

    t0 = 0
    tf = 1
    h = (tf - t0) / steps
    xp0 = x0 * gamma
    t = np.arange(t0, tf + h, h)

    x_m = mid_point()
    x_i = implicit_mid_point()
    x_n = ns_implicit_mid()
    x_ex = exact()

    error_mid = relative_error(x_ex, x_m, steps)
    error_imp = relative_error(x_ex, x_i[:, 0], steps)
    error_nsimp = relative_error(x_ex, x_n[:, 0], steps)
    error_exact = relative_error(x_ex, x_ex, steps)

    fig, axs = plt.subplots(2)
    fig.set_figheight(10)
    fig.set_figwidth(10)
    title1 = "Exact solution and methods: gamma=" + str(
        gamma) + ", omega=" + str(omega) + ", h=" + str(h)
    axs[0].plot(t, x_ex, "limegreen", label="Exact Solution", linewidth=5.5)
    axs[0].plot(t, x_m, "cornflowerblue", label="EMP")
    axs[0].plot(t, x_i[:, 0], "blueviolet", marker="o", label="IMP")
    axs[0].plot(t, x_n[:, 0], "darkorange", label="NSIMP")
    axs[0].set(xlabel="time", ylabel="x(t)")
    axs[0].set_title(title1)
    axs[0].legend(loc="upper right", fontsize="small")

    title2 = "Errors: gamma=" + str(gamma) + ", omega=" + str(
        omega) + ", h=" + str(h)
    axs[1].plot(t,
                error_exact,
                "limegreen",
                label="Exact Error",
                linewidth=5.5)
    axs[1].plot(t, error_mid, "cornflowerblue", label="EMP Error")
    axs[1].plot(t, error_imp, "blueviolet", marker="o", label="IMP Error")
    axs[1].plot(t, error_nsimp, "darkorange", label="NSIMP Error")
    axs[1].set(xlabel="time", ylabel="Relative Error")
    axs[1].set_title(title2)
    axs[1].legend(loc="upper right", fontsize="small")
    plt.show()

    print()
    print(
        f"Testing using: steps = {steps}, x0 = {x0}, gamma = {gamma}, omega = {omega}, and h = {h}.",
        end="\n\n\n\n")
    table_results = results(t, x_m, x_i[:, 0], x_n[:, 0], error_mid, error_imp,
                            error_nsimp, x_ex)
    print(
        table(table_results,
              headers=[
                  "n", "t", "EMP", "IMP", "NSIMP", "EMP Error", "IMP Error",
                  "NSIMP Error", "Exact Solution"
              ]))
    print()
    print()

    return
Esempio n. 16
0
from tabulate import tabulate as table
data = [["Vivek", 23, "NIT Agartala"], ["Vikas", 24, "AIIMS-Delhi"],
        ["Rahul", 22, "Patna Science College"]]
headers = ["Name", "Age", "College"]
print(table(data, headers=headers))

#The above code is most basic table form.
#Let's play with it.
#Take data as dictionary.
data = {
    "Name": ["Vivek", 23, "NIT Agartala"],
    "Age": ["Vikas", 24, "AIIMS-Delhi"],
    "College": ["Rahul", 22, "Patna Science College"]
}
#Each key will be working as a header for our table.
#Each data for each key will be a row in our table.
print(table(data))
#Add headers
print(table(data, headers="keys"))
print()
#Lets style our table differently.
# plain, simple, grid, html, github, pretty, fancy_grid
print(table(data, headers="keys", tablefmt="plain"))
print(table(data, headers="keys", tablefmt="simple"))
print(table(data, headers="keys", tablefmt="grid"))
print(table(data, headers="keys", tablefmt="fancy_grid"))
print(table(data, headers="keys", tablefmt="github"))
print(table(data, headers="keys", tablefmt="pretty"))
print(table(data, headers="keys", tablefmt="html"))
#We can also given numbering to each row-data
print(table(data, headers="keys", tablefmt="grid", showindex="always"))
 def table_format(self, data, headers):
     # formato para tablas
     format_table = ["github", "pretty", "simple"]
     result = table(data, headers, tablefmt=format_table[2])
     print(result)
Esempio n. 18
0
def print_weekly_stats(league: League, week: int):
    ''' Prints weekly stat report for a league during a given week '''
    # Load box scores for specified week
    box_scores = league.box_scores(week)

    statsTable = [
        [
            'Most Points Scored: ',
            sorted(league.teams,
                   key=lambda x: x.scores[week - 1],
                   reverse=True)[0].owner
        ],
        [
            'Least Points Scored: ',
            sorted(league.teams, key=lambda x: x.scores[week - 1])[0].owner
        ],
        [
            'Best Possible Lineup: ',
            sort_lineups_by_func(league, week, get_best_lineup,
                                 box_scores)[-1].owner
        ],
        [
            'Best Trio: ',
            sort_lineups_by_func(league, week, get_best_trio,
                                 box_scores)[-1].owner
        ],
        [
            'Worst Trio: ',
            sort_lineups_by_func(league, week, get_best_trio,
                                 box_scores)[0].owner
        ],
        [
            'Best Lineup Setter',
            sort_lineups_by_func(league, week, get_lineup_efficiency,
                                 box_scores)[-1].owner
        ],
        [
            'Worst Lineup Setter',
            sort_lineups_by_func(league, week, get_lineup_efficiency,
                                 box_scores)[0].owner
        ],
        ['---------------------', '----------------'],
        [
            'Best QBs: ',
            sort_lineups_by_func(league,
                                 week,
                                 avg_slot_score,
                                 box_scores,
                                 slot='QB')[-1].owner
        ],
        [
            'Best RBs: ',
            sort_lineups_by_func(league,
                                 week,
                                 avg_slot_score,
                                 box_scores,
                                 slot='RB')[-1].owner
        ],
        [
            'Best WRs: ',
            sort_lineups_by_func(league,
                                 week,
                                 avg_slot_score,
                                 box_scores,
                                 slot='WR')[-1].owner
        ],
        [
            'Best TEs: ',
            sort_lineups_by_func(league,
                                 week,
                                 avg_slot_score,
                                 box_scores,
                                 slot='TE')[-1].owner
        ],
        [
            'Best Flex: ',
            sort_lineups_by_func(league,
                                 week,
                                 avg_slot_score,
                                 box_scores,
                                 slot=r'RB/WR/TE')[-1].owner
        ],
        [
            'Best DST: ',
            sort_lineups_by_func(league,
                                 week,
                                 avg_slot_score,
                                 box_scores,
                                 slot=r'D/ST')[-1].owner
        ],
        [
            'Best K: ',
            sort_lineups_by_func(league,
                                 week,
                                 avg_slot_score,
                                 box_scores,
                                 slot='K')[-1].owner
        ],
        [
            'Best Bench:',
            sort_lineups_by_func(league, week, sum_bench_points,
                                 box_scores)[-1].owner
        ],
        ['---------------------', '----------------'],
        [
            'Worst QBs: ',
            sort_lineups_by_func(league,
                                 week,
                                 avg_slot_score,
                                 box_scores,
                                 slot='QB')[0].owner
        ],
        [
            'Worst RBs: ',
            sort_lineups_by_func(league,
                                 week,
                                 avg_slot_score,
                                 box_scores,
                                 slot='RB')[0].owner
        ],
        [
            'Worst WRs: ',
            sort_lineups_by_func(league,
                                 week,
                                 avg_slot_score,
                                 box_scores,
                                 slot='WR')[0].owner
        ],
        [
            'Worst TEs: ',
            sort_lineups_by_func(league,
                                 week,
                                 avg_slot_score,
                                 box_scores,
                                 slot='TE')[0].owner
        ],
        [
            'Worst Flex: ',
            sort_lineups_by_func(league,
                                 week,
                                 avg_slot_score,
                                 box_scores,
                                 slot=r'RB/WR/TE')[0].owner
        ],
        [
            'Worst DST: ',
            sort_lineups_by_func(league,
                                 week,
                                 avg_slot_score,
                                 box_scores,
                                 slot=r'D/ST')[0].owner
        ],
        [
            'Worst K: ',
            sort_lineups_by_func(league,
                                 week,
                                 avg_slot_score,
                                 box_scores,
                                 slot='K')[0].owner
        ],
        [
            'Worst Bench:',
            sort_lineups_by_func(league, week, sum_bench_points,
                                 box_scores)[0].owner
        ],
    ]
    print('\n', table(statsTable, headers=['Week ' + str(week), '']))
    return statsTable
Esempio n. 19
0
                temp.append(omega)
                start = time.time()
                mid_point()
                temp.append(time.time() - start)
                start = time.time()
                implicit_mid_point()
                temp.append(time.time() - start)
                start = time.time()
                ns_implicit_mid()
                temp.append(time.time() - start)
                times.append(temp)

    print(
        table(times,
              headers=[
                  "steps", "gamma", "omega", "EMP Time", "IMP Time",
                  "NSIMP Time"
              ]))
    # ================================================================================

    # ======================== Implicit Methods when gamma = 0 =======================
    steps = 10
    x0 = 1
    gamma = 0
    omega = 1

    # Generates the plots used in the report
    gamma_0()

    # To generate the tables used in the presention use run_test(), we did not use the plots from run_test() for this section
    # run_test()