Пример #1
0
    def setup(self):
        nmatches = len(self._schema_out) * (len(self._schema_out) - 1) // 2
        self._matches = []

        for r in range(0, nmatches):
            m = Match(self._num)
            self._matches.append(m)

            m.add_parent(self)
Пример #2
0
    def setup(self):
        nmatches = len(self._schema_out) * (len(self._schema_out) - 1) // 2
        self._matches = []

        for r in range(0, nmatches):
            m = Match(self._num)
            self._matches.append(m)

            m.add_parent(self)
Пример #3
0
    def set_players(self, players):
        self._pla = players[:len(players)/2]
        self._plb = players[len(players)/2:]
        self._nplayers = len(self._pla)

        self._matches = []
        for i in range(0,self._nplayers):
            m = Match(self._num)
            m.set_players([self._pla[i], self._plb[i]])
            self._matches.append(m)
Пример #4
0
    def __init__(self, dbpl=None, bos=None, s1=None, s2=None):
        if dbpl is None:
            return

        sipl = [make_player(p) for p in dbpl]
        num = bos[0]
        obj = MatchSim(num)
        obj.set_players(sipl)
        obj.modify(self.range(int(s1), 0, num), self.range(int(s2), 0, num))
        obj.compute()

        self.dbpl = dbpl
        self.bos = bos
        self.sipl = sipl
        self.num = num
        self.obj = obj
        self.pla, self.plb = dbpl[0], dbpl[1]
        self.rta = sipl[0].elo_vs_opponent(sipl[1])
        self.rtb = sipl[1].elo_vs_opponent(sipl[0])
        self.proba = obj.get_tally()[sipl[0]][1]
        self.probb = obj.get_tally()[sipl[1]][1]
        self.sca = s1
        self.scb = s2

        self.outcomes = [
            {'sca': outcome[1], 'scb': outcome[2], 'prob': outcome[0]}
            for outcome in obj.instances_detail()
        ]
Пример #5
0
    def __init__(self, dbpl=None, bos=None, s1=None, s2=None):
        if dbpl is None:
            return

        sipl = [make_player(p) for p in dbpl]
        num = bos[0]
        obj = MatchSim(num)
        obj.set_players(sipl)
        obj.modify(self.range(int(s1), 0, num), self.range(int(s2), 0, num))
        obj.compute()

        self.dbpl = dbpl
        self.bos = bos
        self.sipl = sipl
        self.num = num
        self.obj = obj
        self.pla, self.plb = dbpl[0], dbpl[1]
        self.rta = sipl[0].elo_vs_opponent(sipl[1])
        self.rtb = sipl[1].elo_vs_opponent(sipl[0])
        self.proba = obj.get_tally()[sipl[0]][1]
        self.probb = obj.get_tally()[sipl[1]][1]
        self.sca = s1
        self.scb = s2

        self.outcomes = [{
            'sca': outcome[1],
            'scb': outcome[2],
            'prob': outcome[0]
        } for outcome in obj.instances_detail()]
Пример #6
0
    def set_players(self, players):
        self._pla = players[:len(players) // 2]
        self._plb = players[len(players) // 2:]
        self._nplayers = len(self._pla)
        self._numw = self._nplayers // 2 + 1
        self._nums = (self._nplayers - 1) // 2

        self._matches = []
        for i in range(0, self._nplayers):
            m = Match(self._num)
            m.set_players([self._pla[i], self._plb[i]])
            self._matches.append(m)
Пример #7
0
    def compute(self):
        N = 1000
        self._tally = [Tally(2), Tally(2)]

        self._matches = []
        for i in range(0,7):
            m = Match(self._num)
            m.set_players([self._pla[i], self._plb[i]])
            m.compute()
            self._matches.append(m)

        for i in range(0,N):
            self.compute_inst(1.0/N)
Пример #8
0
    def setup(self):
        self._matches = dict()
        self._bracket = []

        prev_round = None
        this_round = []

        for r in range(0, len(self._num)):
            for i in range(0, 2**(len(self._num)-1-r)):
                m = Match(self._num[r])
                this_round.append(m)

                m.add_parent(self)
                if prev_round != None:
                    prev_round[2*i].add_winner_link(m, 0)
                    prev_round[2*i+1].add_winner_link(m, 1)

            self._matches['Round ' + str(r+1)] = this_round
            self._bracket.append(this_round)
            prev_round = this_round
            this_round = []
Пример #9
0
    def setup(self):
        self._matches = dict()
        self._bracket = []

        prev_round = None
        this_round = []

        for r in range(0, len(self._num)):
            for i in range(0, 2**(len(self._num) - 1 - r)):
                m = Match(self._num[r])
                this_round.append(m)

                m.add_parent(self)
                if prev_round != None:
                    prev_round[2 * i].add_winner_link(m, 0)
                    prev_round[2 * i + 1].add_winner_link(m, 1)

            self._matches['Round ' + str(r + 1)] = this_round
            self._bracket.append(this_round)
            prev_round = this_round
            this_round = []
Пример #10
0
    def setup(self):
        self._first = [Match(self._num), Match(self._num)]
        self._second = [Match(self._num), Match(self._num)]
        self._final = Match(self._num)

        self._matches = self._first + self._second + [self._final]

        self._first[0].add_winner_link(self._second[0], 0)
        self._first[0].add_loser_link(self._second[1], 0)
        self._first[0].add_parent(self)
        self._first[1].add_winner_link(self._second[0], 1)
        self._first[1].add_loser_link(self._second[1], 1)
        self._first[1].add_parent(self)
        self._second[0].add_loser_link(self._final, 0)
        self._second[0].add_parent(self)
        self._second[1].add_winner_link(self._final, 1)
        self._second[1].add_parent(self)
        self._final.add_parent(self)
Пример #11
0
    def compute_match(self, pla, plb, base):
        obj = Match(self._num)
        obj.set_players([pla[0], plb[0]])
        obj.compute()
        inst = obj.random_instance_detail(new=True)

        if inst[1] > inst[2]:
            plb = plb[1:]
        else:
            pla = pla[1:]

        if len(plb) != 0 and len(pla) != 0:
            self.compute_match(pla, plb, base)
        elif len(plb) == 0:
            self._tally[0][1] += base
            self._tally[1][0] += base
        else:
            self._tally[1][1] += base
            self._tally[0][0] += base
Пример #12
0
    def setup(self):
        self._first = [Match(self._num), Match(self._num)]
        self._second = [Match(self._num), Match(self._num)]
        self._final = Match(self._num)

        self._matches = self._first + self._second + [self._final]

        self._first[0].add_winner_link(self._second[0], 0)
        self._first[0].add_loser_link(self._second[1], 0)
        self._first[0].add_parent(self)
        self._first[1].add_winner_link(self._second[0], 1)
        self._first[1].add_loser_link(self._second[1], 1)
        self._first[1].add_parent(self)
        self._second[0].add_loser_link(self._final, 0)
        self._second[0].add_parent(self)
        self._second[1].add_winner_link(self._final, 1)
        self._second[1].add_parent(self)
        self._final.add_parent(self)
Пример #13
0
    def compute_match(self, pla, plb, base):
        obj = Match(self._num)
        obj.set_players([pla[0], plb[0]])
        obj.compute()
        inst = obj.random_instance_detail(new=True)

        if inst[1] > inst[2]:
            plb = plb[1:]
        else:
            pla = pla[1:]

        if len(plb) != 0 and len(pla) != 0:
            self.compute_match(pla, plb, base)
        elif len(plb) == 0:
            self._tally[0][1] += base
            self._tally[1][0] += base
        else:
            self._tally[1][1] += base
            self._tally[0][0] += base
Пример #14
0
class MSLGroup(Composite):
    
    def __init__(self, num):
        self._num = num
        Composite.__init__(self, [1]*4, [1]*4)

    def setup(self):
        self._first = [Match(self._num), Match(self._num)]
        self._second = [Match(self._num), Match(self._num)]
        self._final = Match(self._num)

        self._matches = self._first + self._second + [self._final]

        self._first[0].add_winner_link(self._second[0], 0)
        self._first[0].add_loser_link(self._second[1], 0)
        self._first[0].add_parent(self)
        self._first[1].add_winner_link(self._second[0], 1)
        self._first[1].add_loser_link(self._second[1], 1)
        self._first[1].add_parent(self)
        self._second[0].add_loser_link(self._final, 0)
        self._second[0].add_parent(self)
        self._second[1].add_winner_link(self._final, 1)
        self._second[1].add_parent(self)
        self._final.add_parent(self)

    def get_match(self, key):
        key = key.split(' ')[0]
        if key.lower() == 'first':
            return self._first[0]
        elif key.lower() == 'second':
            return self._first[1]
        elif key.lower() == 'winners':
            return self._second[0]
        elif key.lower() == 'losers':
            return self._second[1]
        elif key.lower() == 'final':
            return self._final
        else:
            raise Exception('No such match found \'' + key + '\'')

    def should_use_mc(self):
        return False

    def fill(self):
        self._first[0].set_players(self._players[:2])
        self._first[1].set_players(self._players[2:])

    def tally_maker(self):
        return Tally(len(self._schema_out), self._players)

    def compute_mc(self):
        self.compute_exact()

    def compute_exact(self):
        for m in self._first:
            m.compute_partial()

        for (if0, if1) in itertools.product(self._first[0].instances(),\
                                            self._first[1].instances()):
            base_f = if0[0] * if1[0]
            if0[2].broadcast_instance(if0)
            if1[2].broadcast_instance(if1)
            for m in self._second:
                m.compute_partial()

            for (is0, is1) in itertools.product(self._second[0].instances(),\
                                                self._second[1].instances()):
                base_s = base_f * is0[0] * is1[0]
                is0[2].broadcast_instance(is0)
                is1[2].broadcast_instance(is1)
                self._final.compute_partial()

                for ifin in self._final.instances():
                    prob = base_s * ifin[0]
                    self._tally[is1[1][0]][0] += prob
                    self._tally[ifin[1][0]][1] += prob
                    self._tally[ifin[1][1]][2] += prob
                    self._tally[is0[1][1]][3] += prob
                    self._tally[is0[1][1]].pairs[ifin[1][1]] += prob

    def detail(self, strings):
        tally = self._tally

        out = strings['detailheader']

        out += strings['ptabletitle'].format(title='Detailed placement probabilities')
        out += strings['ptableheader']
        for h in ['4th', '3rd', '2nd', '1st']:
            out += strings['ptableheading'].format(heading=h)

        for p in self._players:
            if p.name == 'BYE':
                continue
            out += '\n' + strings['ptablename'].format(player=p.name)
            for i in tally[p]:
                if i > 1e-10:
                    out += strings['ptableentry'].format(prob=100*i)
                else:
                    out += strings['ptableempty']

        out += strings['ptablebetween']

        out += strings['ptabletitle'].format(title='Probability of each pair advancing')
        out += strings['ptableheader']
        for p in self._players:
            if p.name != 'BYE':
                out += strings['ptableheading'].format(heading=p.name[:7])
        for p in self._players:
            if p.name == 'BYE':
                continue
            out += '\n' + strings['ptablename'].format(player=p.name)
            for q in self._players:
                if q.name == 'BYE':
                    continue
                if p != q and tally[p].pairs[q] >= 1e-10:
                    out += strings['ptableentry'].format(prob=100*tally[p].pairs[q])
                else:
                    out += strings['ptableempty']

        out += strings['detailfooter']

        return out

    def summary(self, strings, title=None):
        tally = self._tally

        if title == None:
            title = 'MSL-style four-player group'
        out = strings['header'].format(title=title)

        players = sorted(self._players, key=lambda a: sum(tally[a][2:]),\
                         reverse=True)

        for p in players:
            if sum(tally[p][2:]) > 1e-10 and p.name != 'BYE':
                out += strings['mslgplayer'].format(player=p.name,\
                                                    prob=100*sum(tally[p][2:]))

        out += strings['nomimage']
        out += strings['footer'].format(title=title)

        return out
Пример #15
0
class MSLGroup(Composite):
    def __init__(self, num):
        self._num = num
        Composite.__init__(self, [1] * 4, [1] * 4)

    def setup(self):
        self._first = [Match(self._num), Match(self._num)]
        self._second = [Match(self._num), Match(self._num)]
        self._final = Match(self._num)

        self._matches = self._first + self._second + [self._final]

        self._first[0].add_winner_link(self._second[0], 0)
        self._first[0].add_loser_link(self._second[1], 0)
        self._first[0].add_parent(self)
        self._first[1].add_winner_link(self._second[0], 1)
        self._first[1].add_loser_link(self._second[1], 1)
        self._first[1].add_parent(self)
        self._second[0].add_loser_link(self._final, 0)
        self._second[0].add_parent(self)
        self._second[1].add_winner_link(self._final, 1)
        self._second[1].add_parent(self)
        self._final.add_parent(self)

    def get_match(self, key):
        key = key.split(' ')[0]
        if key.lower() == '1':
            return self._first[0]
        elif key.lower() == '2':
            return self._first[1]
        elif key.lower() == 'w':
            return self._second[0]
        elif key.lower() == 'l':
            return self._second[1]
        elif key.lower() == 'f':
            return self._final
        else:
            raise Exception('No such match found \'' + key + '\'')

    def should_use_mc(self):
        return False

    def fill(self):
        self._first[0].set_players(self._players[:2])
        self._first[1].set_players(self._players[2:])

    def tally_maker(self):
        return Tally(len(self._schema_out), self._players)

    def compute_mc(self):
        self.compute_exact()

    def compute_exact(self):
        for m in self._first:
            m.compute_partial()

        for (if0, if1) in itertools.product(self._first[0].instances(),\
                                            self._first[1].instances()):
            base_f = if0[0] * if1[0]
            if0[2].broadcast_instance(if0)
            if1[2].broadcast_instance(if1)
            for m in self._second:
                m.compute_partial()

            for (is0, is1) in itertools.product(self._second[0].instances(),\
                                                self._second[1].instances()):
                base_s = base_f * is0[0] * is1[0]
                is0[2].broadcast_instance(is0)
                is1[2].broadcast_instance(is1)
                self._final.compute_partial()

                for ifin in self._final.instances():
                    prob = base_s * ifin[0]
                    self._tally[is1[1][0]][0] += prob
                    self._tally[ifin[1][0]][1] += prob
                    self._tally[ifin[1][1]][2] += prob
                    self._tally[is0[1][1]][3] += prob
                    self._tally[is0[1][1]].pairs[ifin[1][1]] += prob

    def detail(self, strings):
        tally = self._tally

        out = strings['detailheader']

        out += strings['ptabletitle'].format(
            title='Detailed placement probabilities')
        out += strings['ptableheader']
        for h in ['4th', '3rd', '2nd', '1st']:
            out += strings['ptableheading'].format(heading=h)

        for p in self._players:
            if p.name == 'BYE':
                continue
            out += '\n' + strings['ptablename'].format(player=p.name)
            for i in tally[p]:
                if i > 1e-10:
                    out += strings['ptableentry'].format(prob=100 * i)
                else:
                    out += strings['ptableempty']

        out += strings['ptablebetween']

        out += strings['ptabletitle'].format(
            title='Probability of each pair advancing')
        out += strings['ptableheader']
        for p in self._players:
            if p.name != 'BYE':
                out += strings['ptableheading'].format(heading=p.name[:7])
        for p in self._players:
            if p.name == 'BYE':
                continue
            out += '\n' + strings['ptablename'].format(player=p.name)
            for q in self._players:
                if q.name == 'BYE':
                    continue
                if p != q and tally[p].pairs[q] >= 1e-10:
                    out += strings['ptableentry'].format(prob=100 *
                                                         tally[p].pairs[q])
                else:
                    out += strings['ptableempty']

        out += strings['detailfooter']

        return out

    def summary(self, strings, title=None):
        tally = self._tally

        if title == None:
            title = 'MSL-style four-player group'
        out = strings['header'].format(title=title)

        players = sorted(self._players, key=lambda a: sum(tally[a][2:]),\
                         reverse=True)

        for p in players:
            if sum(tally[p][2:]) > 1e-10 and p.name != 'BYE':
                out += strings['mslgplayer'].format(player=p.name,\
                                                    prob=100*sum(tally[p][2:]))

        out += strings['nomimage']
        out += strings['footer'].format(title=title)

        return out
Пример #16
0
def match(request):
    base = base_ctx('Inference', 'Predict', request=request)

    # {{{ Get data, set up and simulate
    form = SetupForm(request.GET)
    if not form.is_valid():
        return redirect('/inference/')

    num = form.cleaned_data['bo'][0]
    dbpl = form.cleaned_data['ps']
    sipl = [make_player(p) for p in dbpl]

    match = MatchSim(num)
    match.set_players(sipl)
    match.modify(
        get_param_range(request, 's1', (0, num), 0),
        get_param_range(request, 's2', (0, num), 0),
    )
    match.compute()
    # }}}

    # {{{ Postprocessing
    base.update({
        'form': form,
        'dbpl': dbpl,
        'rta': sipl[0].elo_vs_opponent(sipl[1]),
        'rtb': sipl[1].elo_vs_opponent(sipl[0]),
        'proba': match.get_tally()[sipl[0]][1],
        'probb': match.get_tally()[sipl[1]][1],
        'match': match,
    })

    base.update({
        'max': max(base['proba'], base['probb']),
        'fav': dbpl[0] if base['proba'] > base['probb'] else dbpl[1],
    })

    resa, resb = [], []
    outcomes = [
        {'sca': outcome[1], 'scb': outcome[2], 'prob': outcome[0]} 
        for outcome in match.instances_detail()
    ]
    resa = [oc for oc in outcomes if oc['sca'] > oc['scb']]
    resb = [oc for oc in outcomes if oc['scb'] > oc['sca']]
    if len(resa) < len(resb):
        resa = [None] * (len(resb) - len(resa)) + resa
    else:
        resb = [None] * (len(resa) - len(resb)) + resb
    base['res'] = list(zip(resa, resb))
    # }}}

    # {{{ Scores and other data
    thr = date.today() - relativedelta(months=2)
    pla_matches = dbpl[0].get_matchset()
    plb_matches = dbpl[1].get_matchset()
    base['tot_w_a'], base['tot_l_a'] = count_winloss_player(pla_matches, dbpl[0])
    base['frm_w_a'], base['frm_l_a'] = count_winloss_player(pla_matches.filter(date__gte=thr), dbpl[0])
    base['tot_w_b'], base['tot_l_b'] = count_winloss_player(plb_matches, dbpl[1])
    base['frm_w_b'], base['frm_l_b'] = count_winloss_player(plb_matches.filter(date__gte=thr), dbpl[1])
    if dbpl[1].race in 'PTZ':
        base['mu_w_a'], base['mu_l_a'] = count_matchup_player(pla_matches, dbpl[0], dbpl[1].race)
        base['fmu_w_a'], base['fmu_l_a'] = count_matchup_player(
            pla_matches.filter(date__gte=thr), dbpl[0], dbpl[1].race
        )
    if dbpl[0].race in 'PTZ':
        base['mu_w_b'], base['mu_l_b'] = count_matchup_player(plb_matches, dbpl[1], dbpl[0].race)
        base['fmu_w_b'], base['fmu_l_b'] = count_matchup_player(
            plb_matches.filter(date__gte=thr), dbpl[1], dbpl[0].race
        )
    wa_a, wb_a = count_winloss_games(Match.objects.filter(pla=dbpl[0], plb=dbpl[1]))
    wb_b, wa_b = count_winloss_games(Match.objects.filter(pla=dbpl[1], plb=dbpl[0]))
    base['vs_a'] = wa_a + wa_b
    base['vs_b'] = wb_a + wb_b

    base['matches'] = display_matches(
        Match.objects.filter(Q(pla=dbpl[0], plb=dbpl[1]) | Q(plb=dbpl[0], pla=dbpl[1]))
            .select_related('period', 'pla', 'plb')
            .order_by('-date', 'id'),
        fix_left=dbpl[0],
    )
    # }}}

    postable_match(base, request)

    base.update({"title": "{} vs. {}".format(dbpl[0].tag, dbpl[1].tag)})

    return render_to_response('pred_match.html', base)