Ejemplo n.º 1
0
 class Meta:
     queryset = filter_active(total_ratings(Rating.objects.all()))
     allowed_methods = ['get', 'post']
     resource_name = 'activerating'
     authentication = APIKeyAuthentication()
     filtering = {
         'id':         ALL,
         'period':     ALL_WITH_RELATIONS,
         'player':     ALL_WITH_RELATIONS,
         'prev':       ALL_WITH_RELATIONS,
         'decay':      ALL,
         'domination': ALL,
         'rating':     ALL, 'rating_vp':     ALL, 'rating_vt':     ALL, 'rating_vz':     ALL,
         'dev':        ALL, 'dev_vp':        ALL, 'dev_vt':        ALL, 'dev_vz':        ALL,
         'bf_rating':  ALL, 'bf_rating_vp':  ALL, 'bf_rating_vt':  ALL, 'bf_rating_vz':  ALL,
         'bf_dev':     ALL, 'bf_dev_vp':     ALL, 'bf_dev_vt':     ALL, 'bf_dev_vz':     ALL,
         'comp_rat':   ALL, 'comp_rat_vp':   ALL, 'comp_rat_vt':   ALL, 'comp_rat_vz':   ALL,
         'position':   ALL, 'position_vp':   ALL, 'position_vt':   ALL, 'position_vz':   ALL,
     }
     ordering = [
         'id',
         'period',
         'player',
         'prev',
         'decay',
         'domination',
         'rating',     'rating_vp',     'rating_vt',     'rating_vz',
         'dev',        'dev_vp',        'dev_vt',        'dev_vz',
         'bf_rating',  'bf_rating_vp',  'bf_rating_vt',  'bf_rating_vz',
         'bf_dev',     'bf_dev_vp',     'bf_dev_vt',     'bf_dev_vz',
         'comp_rat',   'comp_rat_vp',   'comp_rat_vt',   'comp_rat_vz',
         'position',   'position_vp',   'position_vt',   'position_vz',
     ]
Ejemplo n.º 2
0
def race(request):
    race = get_param(request, 'race', 'all')
    if race not in 'PTZ':
        race = 'all'
    sub = ['All','Protoss','Terran','Zerg'][['all','P','T','Z'].index(race)]

    base = base_ctx('Records', sub, request)

    def sift(lst, num=5):
        ret, pls = [], set()
        for r in lst:
            if not r.player_id in pls:
                pls.add(r.player_id)
                ret.append(r)
            if len(ret) == num:
                return ret
        return ret

    high = (
        filter_active(total_ratings(Rating.objects.all()))
            .filter(period__id__gt=16).select_related('player', 'period')
    )
    
    if race != 'all':
        high = high.filter(player__race=race)

    base.update({
        'hightot': sift(high.order_by('-rating')[:200]),
        'highp':   sift(high.order_by('-tot_vp')[:200]),
        'hight':   sift(high.order_by('-tot_vt')[:200]),
        'highz':   sift(high.order_by('-tot_vz')[:200]),
        'race':    race if race != 'all' else '',
    })

    return render_to_response('records.djhtml', base)
Ejemplo n.º 3
0
def race(request):
    race = get_param(request, 'race', 'all')
    if race not in 'PTZ':
        race = 'all'
    sub = ['All', 'Protoss', 'Terran', 'Zerg'][['all', 'P', 'T',
                                                'Z'].index(race)]

    base = base_ctx('Records', sub, request)

    def sift(lst, num=5):
        ret, pls = [], set()
        for r in lst:
            if not r.player_id in pls:
                pls.add(r.player_id)
                ret.append(r)
            if len(ret) == num:
                return ret
        return ret

    high = (filter_active(total_ratings(Rating.objects.all())).filter(
        period__id__gt=16).select_related('player', 'period'))

    if race != 'all':
        high = high.filter(player__race=race)

    base.update({
        'hightot': sift(high.order_by('-rating')[:200]),
        'highp': sift(high.order_by('-tot_vp')[:200]),
        'hight': sift(high.order_by('-tot_vt')[:200]),
        'highz': sift(high.order_by('-tot_vz')[:200]),
        'race': race if race != 'all' else '',
    })

    return render_to_response('records.djhtml', base)
Ejemplo n.º 4
0
def home(request):
    base = base_ctx(request=request)

    entries = filter_active(Rating.objects.filter(period=base['curp']))\
              .order_by('-rating')\
              .select_related('player')[0:10]

    populate_teams(entries)

    blogs = Post.objects.order_by('-date')[0:3]

    base.update({
        'entries': entries,
        'blogposts': blogs
    })

    return render_to_response('index.html', base)
Ejemplo n.º 5
0
def home(request):
    base = base_ctx(request=request)

    if request.LANGUAGE_CODE != "en":
        base["messages"].append(Message(_("The blog/news section is only in English, sorry."), type=Message.INFO))

    entries = (
        filter_active(Rating.objects.filter(period=base["curp"]))
        .order_by("-rating")
        .select_related("player", "prev")[0:10]
    )

    entries = populate_teams(entries)

    blogs = Post.objects.order_by("-date")[0:3]

    base.update({"entries": entries, "blogposts": blogs})

    return render_to_response("index.djhtml", base)
Ejemplo n.º 6
0
def home(request):
    base = base_ctx(request=request)

    if request.LANGUAGE_CODE != 'en':
        base['messages'].append(
            Message(
                _('The blog/news section is only in English, sorry.'),
                type=Message.INFO,
            ))

    entries = filter_active(Rating.objects.filter(period=base['curp']))\
              .order_by('-rating')\
              .select_related('player', 'prev')[0:10]

    entries = populate_teams(entries)

    blogs = Post.objects.order_by('-date')[0:3]

    base.update({'entries': entries, 'blogposts': blogs})

    return render_to_response('index.djhtml', base)
Ejemplo n.º 7
0
def home(request):
    base = base_ctx(request=request)

    if request.LANGUAGE_CODE != 'en':
        base['messages'].append(Message(
            _('The blog/news section is only in English, sorry.'),
            type=Message.INFO,
        ))

    entries = filter_active(Rating.objects.filter(period=base['curp']))\
              .order_by('-rating')\
              .select_related('player', 'prev')[0:10]

    entries = populate_teams(entries)

    blogs = Post.objects.order_by('-date')[0:3]

    base.update({
        'entries': entries,
        'blogposts': blogs
    })

    return render_to_response('index.html', base)
Ejemplo n.º 8
0
def rating_list(request, period=None):
    if period is not None:
        period = get_object_or_404(Period, id=period, computed=True)
    else:
        period = Period.objects.filter(computed=True).latest('start')

    ret = {
        'id': period.id,
        'start': str(period.start),
        'end': str(period.end),
        'retplayers': period.num_retplayers,
        'newplayers': period.num_newplayers,
        'games': period.num_games,
        'list': []
    }

    rats = filter_active(Rating.objects.filter(period=period))
    rats = rats.select_related('player').order_by('-rating')

    number = 1
    for r in rats:
        ret['list'].append({
            'number': number,
            'player': player_object(r.player, sparse=True),
            'rating': r.rating,
            'rating_vp': r.rating_vp,
            'rating_vt': r.rating_vt,
            'rating_vz': r.rating_vz,
            'dev': r.dev,
            'dev_vp': r.dev_vp,
            'dev_vt': r.dev_vt,
            'dev_vz': r.dev_vz,
            'decay': r.decay
        })
        number += 1

    return HttpResponse(simplejson.dumps(ret), mimetype='application/json')
Ejemplo n.º 9
0
)
from ratings.tools import filter_active

# This is the benchmark position on the rating list. Above, players will gain domination points.
LIMIT = 7

# Nothing counts before here.
FIRST_PERIOD = 25

# {{{ Evaluate the domination scores
#print('[%s] Erasing domination scores' % str(datetime.now()), flush=True)
#Rating.objects.update(domination=None)

print('[%s] Reevaluating domination scores' % str(datetime.now()), flush=True)
for period in Period.objects.filter(computed=True, id__gte=FIRST_PERIOD):
    benchmark = filter_active(period.rating_set.all()).order_by('-rating')[LIMIT-1].rating
    filter_active(period.rating_set.all()).update(domination=F('rating')-benchmark)
# }}}

# {{{ Hall of fame
print('[%s] Reevaluating hall of fame' % str(datetime.now()), flush=True)
for player in Player.objects.all():
    ratings = list(
        player.rating_set.filter(period__id__gte=FIRST_PERIOD)
            .order_by('period__id')
            .values('domination', 'period__id')
    )

    if len(ratings) == 0:
        continue
Ejemplo n.º 10
0
)
from ratings.tools import filter_active

# This is the benchmark position on the rating list. Above, players will gain domination points.
LIMIT = 7

# Nothing counts before here.
FIRST_PERIOD = 25

# {{{ Evaluate the domination scores
#print('[%s] Erasing domination scores' % str(datetime.now()), flush=True)
#Rating.objects.update(domination=None)

print('[%s] Reevaluating domination scores' % str(datetime.now()), flush=True)
for period in Period.objects.filter(computed=True, id__gte=FIRST_PERIOD):
    benchmark = filter_active(
        period.rating_set.all()).order_by('-rating')[LIMIT - 1].rating
    filter_active(period.rating_set.all()).update(domination=F('rating') -
                                                  benchmark)
# }}}

# {{{ Hall of fame
print('[%s] Reevaluating hall of fame' % str(datetime.now()), flush=True)
for player in Player.objects.all():
    ratings = list(
        player.rating_set.filter(
            period__id__gte=FIRST_PERIOD).order_by('period__id').values(
                'domination', 'period__id'))

    if len(ratings) == 0:
        continue
Ejemplo n.º 11
0
        UPDATE match SET rtb_id =
            (SELECT id FROM rating 
              WHERE rating.player_id=match.plb_id
                AND rating.period_id=%i
            )
         WHERE period_id=%i AND plb_id IN (%s)'''
        % (period.id, period.id+1, ','.join(str_ids))
    )
# }}}

# {{{ Bookkeeping
Match.objects.filter(period=period).update(treated=True)

def mean(a):
    return sum([f.rating for f in a])/len(a)
rp = mean(filter_active(Rating.objects.filter(period=period, player__race=P)).order_by('-rating')[:5])
rt = mean(filter_active(Rating.objects.filter(period=period, player__race=T)).order_by('-rating')[:5])
rz = mean(filter_active(Rating.objects.filter(period=period, player__race=Z)).order_by('-rating')[:5])
period.dom_p = cdf(rp-rt) + cdf(rp-rz)
period.dom_t = cdf(rt-rp) + cdf(rt-rz)
period.dom_z = cdf(rz-rp) + cdf(rz-rt)

period.num_retplayers = sum([1 if p['rating'] and len(p['wins']) > 0 else 0 for p in players.values()])
period.num_newplayers = sum([1 if not p['rating'] and len(p['wins']) > 0 else 0 for p in players.values()])
period.num_games = ngames
period.computed = True
period.needs_recompute = False
period.save()

Rating.objects.filter(period=period).update(
    position=None, position_vp=None, position_vt=None, position_vz=None
Ejemplo n.º 12
0
def team(request, team_id):
    # {{{ Get team object and base context, generate messages and make changes if needed
    team = get_object_or_404(Group, id=team_id)
    base = base_ctx('Ranking', None, request)

    if request.method == 'POST' and base['adm']:
        form = TeamModForm(request)
        base['messages'] += form.update_team(team)
    else:
        form = TeamModForm(team=team)

    base.update({
        'team': team,
        'form': form,
    })
    base['messages'] += generate_messages(team)
    # }}}

    # {{{ Easy statistics
    players = team.groupmembership_set.filter(current=True, playing=True)
    player_ids = players.values('player')
    matches = Match.objects.filter(Q(pla__in=player_ids) | Q(plb__in=player_ids))

    base.update({
        'nplayers':  players.count(),
        'nprotoss':  players.filter(player__race=P).count(),
        'nterran':   players.filter(player__race=T).count(),
        'nzerg':     players.filter(player__race=Z).count(),
        'earnings':  (
            Earnings.objects.filter(player__in=player_ids).aggregate(Sum('earnings'))['earnings__sum']
        ),
        'nmatches':  matches.count(),
        'noffline':  matches.filter(offline=True).count(),
    })
    # }}}

    # {{{ Player lists
    all_members = total_ratings(
        Rating.objects.all().order_by('-rating').filter(
            player__groupmembership__group=team,
            player__groupmembership__current=True,
            player__groupmembership__playing=True,
            period=base['curp']
        )
    )

    base.update({
        'active':      filter_active(all_members),
        'inactive':    filter_inactive(all_members),
        'nonplaying':  (
            team.groupmembership_set.filter(current=True, playing=False)
                .select_related('player').order_by('player__tag')
        ),
        'past':        (
            team.groupmembership_set.filter(current=False)
                .annotate(null_end=Count('end'))
                .select_related('player').order_by('-null_end', '-end', 'player__tag')
        ),
    })
    # }}}

    base.update({"title": team.name})

    return render_to_response('team.html', base)
Ejemplo n.º 13
0
def period(request, period_id=None):
    base = base_ctx('Ranking', 'Current', request)

    # {{{ Get period object
    if not period_id:
        period = base['curp']
    else:
        period = get_object_or_404(Period, id=period_id, computed=True)

    if period.is_preview():
        base['messages'].append(
            Message(msg_preview % django_date_filter(period.end, 'F jS'),
                    type=Message.INFO))

    base['period'] = period
    if period.id != base['curp'].id:
        base['curpage'] = ''
    # }}}

    # {{{ Best and most specialised players
    qset = total_ratings(filter_active(
        Rating.objects.filter(period=period))).select_related('player')
    qsetp = qset.filter(player__race=P)
    qsett = qset.filter(player__race=T)
    qsetz = qset.filter(player__race=Z)
    base.update({
        'best':
        qset.latest('rating'),
        'bestvp':
        qset.latest('tot_vp'),
        'bestvt':
        qset.latest('tot_vt'),
        'bestvz':
        qset.latest('tot_vz'),
        'bestp':
        qsetp.latest('rating'),
        'bestpvp':
        qsetp.latest('tot_vp'),
        'bestpvt':
        qsetp.latest('tot_vt'),
        'bestpvz':
        qsetp.latest('tot_vz'),
        'bestt':
        qsett.latest('rating'),
        'besttvp':
        qsett.latest('tot_vp'),
        'besttvt':
        qsett.latest('tot_vt'),
        'besttvz':
        qsett.latest('tot_vz'),
        'bestz':
        qsetz.latest('rating'),
        'bestzvp':
        qsetz.latest('tot_vp'),
        'bestzvt':
        qsetz.latest('tot_vt'),
        'bestzvz':
        qsetz.latest('tot_vz'),
        'specvp':
        qset.extra(select={
            'd': 'rating_vp/dev_vp*(rating+1.5)'
        }).latest('d'),
        'specvt':
        qset.extra(select={
            'd': 'rating_vt/dev_vt*(rating+1.5)'
        }).latest('d'),
        'specvz':
        qset.extra(select={
            'd': 'rating_vz/dev_vz*(rating+1.5)'
        }).latest('d'),
        'specpvp':
        qsetp.extra(select={
            'd': 'rating_vp/dev_vp*(rating+1.5)'
        }).latest('d'),
        'specpvt':
        qsetp.extra(select={
            'd': 'rating_vt/dev_vt*(rating+1.5)'
        }).latest('d'),
        'specpvz':
        qsetp.extra(select={
            'd': 'rating_vz/dev_vz*(rating+1.5)'
        }).latest('d'),
        'spectvp':
        qsett.extra(select={
            'd': 'rating_vp/dev_vp*(rating+1.5)'
        }).latest('d'),
        'spectvt':
        qsett.extra(select={
            'd': 'rating_vt/dev_vt*(rating+1.5)'
        }).latest('d'),
        'spectvz':
        qsett.extra(select={
            'd': 'rating_vz/dev_vz*(rating+1.5)'
        }).latest('d'),
        'speczvp':
        qsetz.extra(select={
            'd': 'rating_vp/dev_vp*(rating+1.5)'
        }).latest('d'),
        'speczvt':
        qsetz.extra(select={
            'd': 'rating_vt/dev_vt*(rating+1.5)'
        }).latest('d'),
        'speczvz':
        qsetz.extra(select={
            'd': 'rating_vz/dev_vz*(rating+1.5)'
        }).latest('d'),
    })
    # }}}

    # {{{ Highest gainer and biggest losers

    # TODO: Fix these queries, highly dependent on the way django does things.
    gainers = filter_active(Rating.objects.filter(period=period))\
        .filter(prev__isnull=False)\
        .select_related('prev', 'player')\
        .extra(select={'diff': 'rating.rating - T3.rating'})\
        .order_by('-diff')
    losers = filter_active(Rating.objects.filter(period=period))\
        .filter(prev__isnull=False)\
        .select_related('prev', 'player')\
        .extra(select={'diff': 'rating.rating - T3.rating'})\
        .order_by('diff')

    base.update({'updown': zip(gainers[:5], losers[:5])})
    # }}}

    # {{{ Matchup statistics
    qset = period.match_set
    base['pvt_wins'], base['pvt_loss'] = count_matchup_games(qset, 'P', 'T')
    base['pvz_wins'], base['pvz_loss'] = count_matchup_games(qset, 'P', 'Z')
    base['tvz_wins'], base['tvz_loss'] = count_matchup_games(qset, 'T', 'Z')
    base.update({
        'pvp_games': count_mirror_games(qset, 'P'),
        'tvt_games': count_mirror_games(qset, 'T'),
        'zvz_games': count_mirror_games(qset, 'Z'),
    })

    base['tot_mirror'] = base['pvp_games'] + base['tvt_games'] + base[
        'zvz_games']
    # }}}

    # {{{ Build country list
    all_players = Player.objects.filter(rating__period_id=period.id,
                                        rating__decay__lt=INACTIVE_THRESHOLD)
    base['countries'] = country_list(all_players)
    # }}}

    # {{{ Initial filtering of ratings
    entries = filter_active(period.rating_set).select_related('player')

    # Race filter
    race = get_param(request, 'race', 'ptzrs')
    q = Q()
    for r in race:
        q |= Q(player__race=r.upper())
    entries = entries.filter(q)

    # Country filter
    nats = get_param(request, 'nats', 'all')
    if nats == 'foreigners':
        entries = entries.exclude(player__country='KR')
    elif nats != 'all':
        entries = entries.filter(player__country=nats)

    # Sorting
    sort = get_param(request, 'sort', '')
    if sort not in ['vp', 'vt', 'vz']:
        entries = entries.order_by('-rating', 'player__tag')
    else:
        entries = entries.extra(select={
            'd': 'rating+rating_' + sort
        }).order_by('-d', 'player__tag')

    entries = entries.prefetch_related('prev')

    base.update({
        'race': race,
        'nats': nats,
        'sort': sort,
    })
    # }}}

    # {{{ Pages etc.
    pagesize = SHOW_PER_LIST_PAGE
    page = int(get_param(request, 'page', 1))
    nitems = entries.count()
    npages = nitems // pagesize + (1 if nitems % pagesize > 0 else 0)
    page = min(max(page, 1), npages)
    entries = entries[(page - 1) * pagesize:page *
                      pagesize] if page > 0 else []

    pn_start, pn_end = page - 2, page + 2
    if pn_start < 1:
        pn_end += 1 - pn_start
        pn_start = 1
    if pn_end > npages:
        pn_start -= pn_end - npages
        pn_end = npages
    if pn_start < 1:
        pn_start = 1

    base.update({
        'page': page,
        'npages': npages,
        'startcount': (page - 1) * pagesize,
        'entries': populate_teams(entries),
        'nperiods': Period.objects.filter(computed=True).count(),
        'pn_range': range(pn_start, pn_end + 1),
    })
    # }}}

    base.update({
        'sortable': True,
        'localcount': True,
    })

    fmt_date = django_date_filter(period.end, "F jS, Y")

    return render_to_response('period.djhtml', base)
Ejemplo n.º 14
0
                AND rating.period_id=%i
            )
         WHERE period_id=%i AND plb_id IN (%s)''' %
                (period.id, period.id + 1, ','.join(str_ids)))
# }}}

# {{{ Bookkeeping
Match.objects.filter(period=period).update(treated=True)


def mean(a):
    return sum([f.rating for f in a]) / len(a)


rp = mean(
    filter_active(Rating.objects.filter(
        period=period, player__race=P)).order_by('-rating')[:5])
rt = mean(
    filter_active(Rating.objects.filter(
        period=period, player__race=T)).order_by('-rating')[:5])
rz = mean(
    filter_active(Rating.objects.filter(
        period=period, player__race=Z)).order_by('-rating')[:5])
period.dom_p = cdf(rp - rt) + cdf(rp - rz)
period.dom_t = cdf(rt - rp) + cdf(rt - rz)
period.dom_z = cdf(rz - rp) + cdf(rz - rt)

period.num_retplayers = sum(
    [1 if p['rating'] and len(p['wins']) > 0 else 0 for p in players.values()])
period.num_newplayers = sum([
    1 if not p['rating'] and len(p['wins']) > 0 else 0
    for p in players.values()
Ejemplo n.º 15
0
from simul.playerlist import make_player

proleague = 'pl' in sys.argv

nplayers_max = 6 if proleague else 5
nplayers_min = 6 if proleague else 1
Simulator = TeamPL if proleague else TeamAK

# {{{ Get a list of teams that can compete
curp = get_latest_period()
allowed_teams = []
teams = Group.objects.filter(active=True, is_team=True)
for t in teams:
    nplayers_available = filter_active(Rating.objects.filter(
        period=curp,
        player__groupmembership__group=t,
        player__groupmembership__current=True,
        player__groupmembership__playing=True,
    )).count()

    if nplayers_available >= nplayers_min:
        allowed_teams.append(t)

disallowed = Group.objects.filter(is_team=True).exclude(id__in=[t.id for t in allowed_teams])
if proleague:
    disallowed.update(scorepl=0.0)
else:
    disallowed.update(scoreak=0.0)

nteams = len(allowed_teams)
# }}}
Ejemplo n.º 16
0
from aligulac.tools import get_latest_period

from ratings.models import (
    Group,
    Rating,
)
from ratings.tools import filter_active

from simul.formats.teamak import TeamAK
from simul.formats.teampl import TeamPL
from simul.playerlist import make_player

print('[%s] Updating team ratings' % str(datetime.now()), flush=True)

# {{{ Update ratings
curp = get_latest_period()
for team in Group.objects.filter(active=True, is_team=True):
    ratings = filter_active(Rating.objects.filter(
        period=curp,
        player__groupmembership__group=team,
        player__groupmembership__current=True,
        player__groupmembership__playing=True,
    )).order_by('-rating')

    if ratings.count() >= 5:
        team.meanrating = sum([r.rating for r in ratings[:5]]) / 5
    else:
        team.meanrating = -10
    team.save()
# }}}
Ejemplo n.º 17
0
def team(request, team_id):
    # {{{ Get team object and base context, generate messages and make changes if needed
    team = get_object_or_404(Group, id=team_id)
    base = base_ctx('Teams', None, request)

    if request.method == 'POST' and base['adm']:
        form = TeamModForm(request)
        base['messages'] += form.update_team(team)
    else:
        form = TeamModForm(team=team)

    base.update({
        'team': team,
        'form': form,
    })
    base['messages'] += generate_messages(team)
    # }}}

    # {{{ Easy statistics
    players = team.groupmembership_set.filter(current=True, playing=True)
    player_ids = players.values('player')
    matches = Match.objects.filter(
        Q(pla__in=player_ids) | Q(plb__in=player_ids))

    base.update({
        'nplayers':
        players.count(),
        'nprotoss':
        players.filter(player__race=P).count(),
        'nterran':
        players.filter(player__race=T).count(),
        'nzerg':
        players.filter(player__race=Z).count(),
        'earnings': (Earnings.objects.filter(player__in=player_ids).aggregate(
            Sum('earnings'))['earnings__sum']),
        'nmatches':
        matches.count(),
        'noffline':
        matches.filter(offline=True).count(),
    })
    # }}}

    # {{{ Player lists
    all_members = total_ratings(
        Rating.objects.all().order_by('-rating').filter(
            player__groupmembership__group=team,
            player__groupmembership__current=True,
            player__groupmembership__playing=True,
            period=base['curp']).select_related('player').prefetch_related(
                'prev'))

    base.update({
        'active':
        filter_active(all_members),
        'inactive':
        filter_inactive(all_members),
        'nonplaying': (team.groupmembership_set.filter(
            current=True,
            playing=False).select_related('player').order_by('player__tag')),
        'past': (team.groupmembership_set.filter(current=False).annotate(
            null_end=Count('end')).select_related('player').order_by(
                '-null_end', '-end', 'player__tag')),
    })
    # }}}

    return render_to_response('team.djhtml', base)
Ejemplo n.º 18
0
from ratings.models import (
    Group,
    Rating,
)
from ratings.tools import filter_active

from simul.formats.teamak import TeamAK
from simul.formats.teampl import TeamPL
from simul.playerlist import make_player

print('[%s] Updating team ratings' % str(datetime.now()), flush=True)

# {{{ Update ratings
curp = get_latest_period()
for team in Group.objects.filter(active=True, is_team=True):
    ratings = filter_active(
        Rating.objects.filter(
            period=curp,
            player__groupmembership__group=team,
            player__groupmembership__current=True,
            player__groupmembership__playing=True,
        )).order_by('-rating')

    if ratings.count() >= 5:
        team.meanrating = sum([r.rating for r in ratings[:5]]) / 5
    else:
        team.meanrating = -10
    team.save()
# }}}
Ejemplo n.º 19
0
from simul.playerlist import make_player

proleague = 'pl' in sys.argv

nplayers_max = 6 if proleague else 5
nplayers_min = 6 if proleague else 1
Simulator = TeamPL if proleague else TeamAK

# {{{ Get a list of teams that can compete
curp = get_latest_period()
allowed_teams = []
teams = Group.objects.filter(active=True, is_team=True)
for t in teams:
    nplayers_available = filter_active(Rating.objects.filter(
        period=curp,
        player__groupmembership__group=t,
        player__groupmembership__current=True,
        player__groupmembership__playing=True,
    )).count()

    if nplayers_available >= nplayers_min:
        allowed_teams.append(t)

disallowed = Group.objects.filter(is_team=True).exclude(id__in=[t.id for t in allowed_teams])
if proleague:
    disallowed.update(scorepl=0.0)
else:
    disallowed.update(scoreak=0.0)

nteams = len(allowed_teams)
# }}}
Ejemplo n.º 20
0
def period(request, period_id=None):
    base = base_ctx('Ranking', 'Current', request)

    # {{{ Get period object
    if not period_id:
        period = base['curp']
    else:
        period = get_object_or_404(Period, id=period_id, computed=True)

    if period.is_preview():
        base['messages'].append(Message(msg_preview % cdate(period.end, _('F jS')), type=Message.INFO))

    base['period'] = period
    if period.id != base['curp'].id:
        base['curpage'] = ''
    # }}}

    # {{{ Best and most specialised players
    qset = total_ratings(filter_active(Rating.objects.filter(period=period))).select_related('player')
    qsetp = qset.filter(player__race=P)
    qsett = qset.filter(player__race=T)
    qsetz = qset.filter(player__race=Z)
    base.update({
        'best':     qset.latest('rating'),
        'bestvp':   qset.latest('tot_vp'),
        'bestvt':   qset.latest('tot_vt'),
        'bestvz':   qset.latest('tot_vz'),
        'bestp':    qsetp.latest('rating'),
        'bestpvp':  qsetp.latest('tot_vp'),
        'bestpvt':  qsetp.latest('tot_vt'),
        'bestpvz':  qsetp.latest('tot_vz'),
        'bestt':    qsett.latest('rating'),
        'besttvp':  qsett.latest('tot_vp'),
        'besttvt':  qsett.latest('tot_vt'),
        'besttvz':  qsett.latest('tot_vz'),
        'bestz':    qsetz.latest('rating'),
        'bestzvp':  qsetz.latest('tot_vp'),
        'bestzvt':  qsetz.latest('tot_vt'),
        'bestzvz':  qsetz.latest('tot_vz'),
        'specvp':   qset.extra(select={'d':   'rating_vp/dev_vp*(rating+1.5)'}).latest('d'),
        'specvt':   qset.extra(select={'d':   'rating_vt/dev_vt*(rating+1.5)'}).latest('d'),
        'specvz':   qset.extra(select={'d':   'rating_vz/dev_vz*(rating+1.5)'}).latest('d'),
        'specpvp':  qsetp.extra(select={'d':  'rating_vp/dev_vp*(rating+1.5)'}).latest('d'),
        'specpvt':  qsetp.extra(select={'d':  'rating_vt/dev_vt*(rating+1.5)'}).latest('d'),
        'specpvz':  qsetp.extra(select={'d':  'rating_vz/dev_vz*(rating+1.5)'}).latest('d'),
        'spectvp':  qsett.extra(select={'d':  'rating_vp/dev_vp*(rating+1.5)'}).latest('d'),
        'spectvt':  qsett.extra(select={'d':  'rating_vt/dev_vt*(rating+1.5)'}).latest('d'),
        'spectvz':  qsett.extra(select={'d':  'rating_vz/dev_vz*(rating+1.5)'}).latest('d'),
        'speczvp':  qsetz.extra(select={'d':  'rating_vp/dev_vp*(rating+1.5)'}).latest('d'),
        'speczvt':  qsetz.extra(select={'d':  'rating_vt/dev_vt*(rating+1.5)'}).latest('d'),
        'speczvz':  qsetz.extra(select={'d':  'rating_vz/dev_vz*(rating+1.5)'}).latest('d'),
    })
    # }}}

    # {{{ Highest gainer and biggest losers

    # TODO: Fix these queries, highly dependent on the way django does things.
    gainers = filter_active(Rating.objects.filter(period=period))\
        .filter(prev__isnull=False)\
        .select_related('prev', 'player')\
        .extra(select={'diff': 'rating.rating - T3.rating'})\
        .order_by('-diff')
    losers = filter_active(Rating.objects.filter(period=period))\
        .filter(prev__isnull=False)\
        .select_related('prev', 'player')\
        .extra(select={'diff': 'rating.rating - T3.rating'})\
        .order_by('diff')

    base.update({
        'gainers': gainers[:5],
        'losers': losers[:5]
    })
    # }}}

    # {{{ Matchup statistics
    qset = period.match_set
    base['pvt_wins'], base['pvt_loss'] = count_matchup_games(qset, 'P', 'T')
    base['pvz_wins'], base['pvz_loss'] = count_matchup_games(qset, 'P', 'Z')
    base['tvz_wins'], base['tvz_loss'] = count_matchup_games(qset, 'T', 'Z')
    base.update({
        'pvp_games': count_mirror_games(qset, 'P'),
        'tvt_games': count_mirror_games(qset, 'T'),
        'zvz_games': count_mirror_games(qset, 'Z'),
    })

    base['tot_mirror'] = base['pvp_games'] + base['tvt_games'] + base['zvz_games']
    # }}}

    # {{{ Build country list
    all_players = Player.objects.filter(rating__period_id=period.id, rating__decay__lt=INACTIVE_THRESHOLD)
    base['countries'] = country_list(all_players)
    # }}}

    # {{{ Initial filtering of ratings
    entries = filter_active(period.rating_set).select_related('player')

    # Race filter
    race = get_param(request, 'race', 'ptzrs')
    q = Q()
    for r in race:
        q |= Q(player__race=r.upper())
    entries = entries.filter(q)

    # Country filter
    nats = get_param(request, 'nats', 'all')
    if nats == 'foreigners':
        entries = entries.exclude(player__country='KR')
    elif nats != 'all':
        entries = entries.filter(player__country=nats)

    # Sorting
    sort = get_param(request, 'sort', '')
    if sort not in ['vp', 'vt', 'vz']: 
        entries = entries.order_by('-rating', 'player__tag')
    else:
        entries = entries.extra(select={'d':'rating+rating_'+sort}).order_by('-d', 'player__tag')

    entries = entries.prefetch_related('prev')

    base.update({
        'race': race,
        'nats': nats,
        'sort': sort,
    })
    # }}}

    # {{{ Pages etc.
    pagesize = SHOW_PER_LIST_PAGE
    page = int(get_param(request, 'page', 1))
    nitems = entries.count()
    npages = nitems//pagesize + (1 if nitems % pagesize > 0 else 0)
    page = min(max(page, 1), npages)
    entries = entries[(page-1)*pagesize : page*pagesize] if page > 0 else []

    base.update({
        'page':       page,
        'npages':     npages,
        'startcount': (page-1)*pagesize,
        'entries':    populate_teams(entries),
        'nperiods':   Period.objects.filter(computed=True).count(),
    })
    # }}}

    base.update({
        'sortable':   True,
        'localcount': True,
    })
        
    fmt_date = django_date_filter(period.end, "F jS, Y")
    # Translators: List (number): (date)
    base.update({"title": _("List {num}: {date}").format(num=period.id, date=fmt_date)})

    return render_to_response('period.html', base)
Ejemplo n.º 21
0
def period(request, period_id):
    base = base_ctx('Ranking', 'Current', request)

    # {{{ Get period object
    period = get_object_or_404(Period, id=period_id, computed=True)
    if period.is_preview():
        base['messages'].append(Message(msg_preview % period.end.strftime('%B %d'), type=Message.INFO))

    base['period'] = period
    if period.id != base['curp'].id:
        base['curpage'] = ''
    # }}}

    # {{{ Best and most specialised players
    qset = total_ratings(filter_active(Rating.objects.filter(period=period))).select_related('player')
    qsetp = qset.filter(player__race=P)
    qsett = qset.filter(player__race=T)
    qsetz = qset.filter(player__race=Z)
    base.update({
        'best':     qset.latest('rating'),
        'bestvp':   qset.latest('tot_vp'),
        'bestvt':   qset.latest('tot_vt'),
        'bestvz':   qset.latest('tot_vz'),
        'bestp':    qsetp.latest('rating'),
        'bestpvp':  qsetp.latest('tot_vp'),
        'bestpvt':  qsetp.latest('tot_vt'),
        'bestpvz':  qsetp.latest('tot_vz'),
        'bestt':    qsett.latest('rating'),
        'besttvp':  qsett.latest('tot_vp'),
        'besttvt':  qsett.latest('tot_vt'),
        'besttvz':  qsett.latest('tot_vz'),
        'bestz':    qsetz.latest('rating'),
        'bestzvp':  qsetz.latest('tot_vp'),
        'bestzvt':  qsetz.latest('tot_vt'),
        'bestzvz':  qsetz.latest('tot_vz'),
        'specvp':   qset.extra(select={'d':   'rating_vp/dev_vp*rating'}).latest('d'),
        'specvt':   qset.extra(select={'d':   'rating_vt/dev_vt*rating'}).latest('d'),
        'specvz':   qset.extra(select={'d':   'rating_vz/dev_vz*rating'}).latest('d'),
        'specpvp':  qsetp.extra(select={'d':  'rating_vp/dev_vp*rating'}).latest('d'),
        'specpvt':  qsetp.extra(select={'d':  'rating_vt/dev_vt*rating'}).latest('d'),
        'specpvz':  qsetp.extra(select={'d':  'rating_vz/dev_vz*rating'}).latest('d'),
        'spectvp':  qsett.extra(select={'d':  'rating_vp/dev_vp*rating'}).latest('d'),
        'spectvt':  qsett.extra(select={'d':  'rating_vt/dev_vt*rating'}).latest('d'),
        'spectvz':  qsett.extra(select={'d':  'rating_vz/dev_vz*rating'}).latest('d'),
        'speczvp':  qsetz.extra(select={'d':  'rating_vp/dev_vp*rating'}).latest('d'),
        'speczvt':  qsetz.extra(select={'d':  'rating_vt/dev_vt*rating'}).latest('d'),
        'speczvz':  qsetz.extra(select={'d':  'rating_vz/dev_vz*rating'}).latest('d'),
    })
    # }}}

    # {{{ Matchup statistics
    qset = period.match_set
    base['pvt_wins'], base['pvt_loss'] = count_matchup_games(qset, 'P', 'T')
    base['pvz_wins'], base['pvz_loss'] = count_matchup_games(qset, 'P', 'Z')
    base['tvz_wins'], base['tvz_loss'] = count_matchup_games(qset, 'T', 'Z')
    base.update({
        'pvp_games': count_mirror_games(qset, 'P'),
        'tvt_games': count_mirror_games(qset, 'T'),
        'zvz_games': count_mirror_games(qset, 'Z'),
    })

    base['tot_mirror'] = base['pvp_games'] + base['tvt_games'] + base['zvz_games']
    # }}}

    # {{{ Build country list
    all_players = Player.objects.filter(rating__period_id=period.id, rating__decay__lt=INACTIVE_THRESHOLD)
    base['countries'] = country_list(all_players)
    # }}}

    # {{{ Initial filtering of ratings
    entries = filter_active(period.rating_set).select_related('player')

    # Race filter
    race = get_param(request, 'race', 'ptzrs')
    q = Q()
    for r in race:
        q |= Q(player__race=r.upper())
    entries = entries.filter(q)

    # Country filter
    nats = get_param(request, 'nats', 'all')
    if nats == 'foreigners':
        entries = entries.exclude(player__country='KR')
    elif nats != 'all':
        entries = entries.filter(player__country=nats)

    # Sorting
    sort = get_param(request, 'sort', '')
    if sort not in ['vp', 'vt', 'vz']: 
        entries = entries.order_by('-rating', 'player__tag')
    else:
        entries = entries.extra(select={'d':'rating+rating_'+sort}).order_by('-d', 'player__tag')

    base.update({
        'race': race,
        'nats': nats,
        'sort': sort,
    })
    # }}}

    # {{{ Pages etc.
    pagesize = 40
    page = int(get_param(request, 'page', 1))
    nitems = entries.count()
    npages = nitems//pagesize + (1 if nitems % pagesize > 0 else 0)
    page = min(max(page, 1), npages)
    entries = entries[(page-1)*pagesize : page*pagesize]

    base.update({
        'page':       page,
        'npages':     npages,
        'startcount': (page-1)*pagesize,
        'entries':    populate_teams(entries),
        'nperiods':   Period.objects.filter(computed=True).count(),
    })
    # }}}

    base.update({
        'sortable':   True,
        'localcount': True,
    })
        
    fmt_date = django_date_filter(period.end, "F jS, Y")
    base.update({"title": "List {}: {}".format(period.id, fmt_date)})

    return render_to_response('period.html', base)