golist-0.4/0042755000175000017500000000000007706242715011444 5ustar vossvossgolist-0.4/export-pairs0100755000175000017500000000551707706242671014033 0ustar vossvoss#! /usr/bin/env python # $Id: export-pairs 5068 2003-07-19 12:43:00Z voss $ # # Copyright 2003 Jochen Voss # # This script exports a matrix of recent games between any # pair of players. # # WARNING: this is not fully functional at the moment. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA import MySQLdb from dbhelper import get_tokens from mx.DateTime import now import string db=MySQLdb.connect(host='localhost', db='golist') c=db.cursor() print r"""\documentclass{article} \usepackage[dvips,landscape,a4paper,textwidth=27cm,nohead]{geometry} \usepackage[latin1]{inputenc} \setlength\oddsidemargin{1cm} \addtolength\oddsidemargin{-1in} \setlength\evensidemargin{1cm} \addtolength\evensidemargin{-1in} \setlength\textwidth{189mm} \setlength\parindent{0pt} \setlength\tabcolsep{2pt} \def\e#1{\vtop{#1}} \pagestyle{empty} \begin{document}""" def pairkey(a,b): return a+":"+b count=0 pairdata={} blackkeys=[] whitekeys=[] games=[] c.execute('SELECT black,white,board,handicap,' + 'if(withjigo="n",komi+0.5,komi) as komi,result' + ' FROM game ORDER BY gamedate DESC') l=c.fetchall() for g in l: if g[0] not in blackkeys: blackkeys.append(g[0]) if g[1] not in whitekeys: whitekeys.append(g[1]) key=pairkey(g[0],g[1]) komi=float(g[4]) entry="%d/%s/%g %s"%(g[2],g[3],komi,g[5][0]) if key in pairdata.keys(): pairdata[key].append(entry) else: pairdata[key] = [entry] whitekeys=whitekeys[:20] blackkeys=blackkeys[:27] print r"\fontsize{6pt}{8pt}\selectfont" print r"\begin{tabular}{r" + "*{%d}{c}"%len(whitekeys) + "}" print r"&\normalsize "+string.join(whitekeys,r"&\normalsize ")+r"\\[1ex]" for a in blackkeys: print r"\normalsize "+a, for b in whitekeys: key=pairkey(a,b) print "&", if key in pairdata.keys(): data=pairdata[key] data=data[0:3] data.reverse() if len(data)==1: print data[0], else: print r"\e{", for d in data: print r"\hbox{"+d+"}", print "}", else: print ".", print r"\\[1ex]" print r"""\end{tabular} \end{document} """ golist-0.4/README0100644000175000017500000000371007706242671012321 0ustar vossvossgolist - a framework to estimate player strength values GoList is a suite of scripts which maintain a SQL database of Go players and game results. It contains some code to estimate the players' Go playing strenghts. The program is written by Jochen Voss GoList is not yet finished, so you may encounter bugs or missing features. New versions of the program may be found at my home page http://www.mathematik.uni-kl.de/~wwwstoch/voss/comp/software.html . GoList comes with NO WARRANTY, to the extent permitted by law. You may redistribute copies of GoList under the terms of the GNU General Public License. For more information about these matters, read the file COPYING of the source code distribution. Please mail any comments, suggestions, and bug reports to Jochen Voss . INSTALLATION: The golist package needs the python mysql bindings and the kjbuckets package. At the moment there is no support for installation in system directories. Just unpack the source somewhere and start the scripts within this directory. USAGE: * to import the data for the first time: As the database administrator: GRANT ALL ON golist.* TO your_mysql_name; CREATE DATABASE golist; With your user account: mysql golist g.dat # edit "g.dat" import-games g.dat rm g.dat * Update the class of players where we can determine the strength. After a new player has made enough games call: update-components * Once upon a time (after some player did ten games) call: update-histories * to get the results: update-strengths export-results >outr.tex latex outr export-players >outp.tex latex outp export-games >outg.tex latex outg golist-0.4/export-results0100755000175000017500000000544307706242671014414 0ustar vossvoss#! /usr/bin/env python # $Id: export-results 5068 2003-07-19 12:43:00Z voss $ # # Copyright 2003 Jochen Voss # # This script emits the TeX source for a new result sheet. # The sheet lists the most recent games for proof-reading # and provides space to note new results. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA import MySQLdb from mx.DateTime import now db = MySQLdb.connect(host='localhost', db='golist') c=db.cursor() c.execute("SELECT gamedate FROM game ORDER BY gamedate DESC LIMIT 10") recentdates=c.fetchall() limit=recentdates[-1][0] c.execute("SELECT gamedate,black,white,board,handicap,komi,withjigo,result," + "probability" + ' FROM game WHERE gamedate>="%s" ORDER BY gamedate' % limit.Format("%Y-%m-%d")) recentgames=map(lambda x:x,c.fetchall()) print r"""\documentclass[12pt]{article} \usepackage[latin1]{inputenc} \usepackage[T1]{fontenc} \usepackage[a4paper,nohead,top=15mm]{geometry} \setlength\parindent{0pt} \pagestyle{empty} \begin{document} \vbox to 0pt{\vskip-8mm%% \hbox to\textwidth{\hss\fontsize{17pt}{20.5pt}\fontseries{bx}\selectfont %s\hskip-12mm}\vss}%% \begin{center} \textbf{Ergebnisliste des geheimen Go-Spielabends} \end{center} \bigskip \begin{tabular*}{\textwidth}{c@{\extracolsep\fill}llrrrlll} date&black&white&board&hc&komi&prob.\\""" % now().Format("%Y-%m-%d") olddate="" for g in recentgames: date=g[0].Format("%Y-%m-%d") if olddate == "" or date != olddate: print r"\noalign{\vskip1ex}" olddate=date s1="" s2="" if g[8] and (g[8]<0.1 or (g[7] == "jigo" and g[8]<0.003)): warn="???" else: warn="" if g[6] == "y": komi=g[5] else: komi=g[5]+0.5 if g[7] == "black": s1=r"\textbf" s2="" elif g[7] == "white": s1="" s2=r"\textbf" if g[8]: prob="%g"%g[8] else: prob="---" print ("%s& %s{%s}& %s{%s}& %d& %d& %g& %s& %s \\\\" % (date, s1,g[1],s2,g[2], g[3],g[4],komi,prob,warn)) print r"\noalign{\vskip1cm}" print now().Format("%Y-%m-%d& & & & & & & \\\\") print r"""\end{tabular*} \end{document} """ golist-0.4/gameprob.py0100644000175000017500000000274007706242671013611 0ustar vossvoss# This file was created automatically by SWIG. # Don't modify this file, modify the SWIG interface instead. # This file is compatible with both classic and new-style classes. import _gameprob def _swig_setattr(self,class_type,name,value): if (name == "this"): if isinstance(value, class_type): self.__dict__[name] = value.this if hasattr(value,"thisown"): self.__dict__["thisown"] = value.thisown del value.thisown return method = class_type.__swig_setmethods__.get(name,None) if method: return method(self,value) self.__dict__[name] = value def _swig_getattr(self,class_type,name): method = class_type.__swig_getmethods__.get(name,None) if method: return method(self) raise AttributeError,name import types try: _object = types.ObjectType _newclass = 1 except AttributeError: class _object : pass _newclass = 0 register_parameter = _gameprob.register_parameter set_param = _gameprob.set_param get_param = _gameprob.get_param res_BLACK = _gameprob.res_BLACK res_WHITE = _gameprob.res_WHITE res_JIGO = _gameprob.res_JIGO register_game = _gameprob.register_game probability = _gameprob.probability game_prob = _gameprob.game_prob applies_to = _gameprob.applies_to param_name = _gameprob.param_name param_board = _gameprob.param_board param_min = _gameprob.param_min param_max = _gameprob.param_max param_default = _gameprob.param_default find_param_by_name = _gameprob.find_param_by_name golist-0.4/gameprob.h0100644000175000017500000000361507706242671013412 0ustar vossvoss/* gameprob.h - declarations for "gameprob.c" * $Id: gameprob.h 5068 2003-07-19 12:43:00Z voss $ * * Copyright (C) 2002, 2003 Jochen Voss * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef FILE_GAMEPROB_H_SEEN #define FILE_GAMEPROB_H_SEEN /* parameters */ struct param_info { int id; char *name; double *ptr; double default_value, min, max; int board; }; extern void init_parameters (void); extern void register_parameter (int id, const char *name); extern struct param_info *find_parameter (int id); extern struct param_info *find_param_by_name (const char *name); extern void set_param (int id, double val); extern double get_param (int id); /* games */ enum result { res_BLACK, res_WHITE, res_JIGO }; struct game_info { int id; int black, white; int board, hc, komi, with_jigo; enum result res; }; extern void register_game (int id, int black, int white, int board, int hc, int komi, int with_jigo, const char *res); extern double probability (int black, int white, int board, int hc, int komi, int with_jigo, enum result res); extern double game_prob (int game); extern int applies_to (int param, int game); #endif /* FILE_GAMEPROB_H_SEEN */ golist-0.4/spieleabend.sh0100755000175000017500000000200507706242671014247 0ustar vossvoss#! /bin/sh # spieleabend.sh - print the sheets for our go meeting # $Id: spieleabend.sh 5068 2003-07-19 12:43:00Z voss $ # # Copyright 2003 Jochen Voss # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ./update-strengths ./export-players >outp.tex latex outp dvips outp # lpr outp.ps ./export-results >outr.tex latex outr dvips outr # lpr outr.ps golist-0.4/gameprob.i0100644000175000017500000000613307706242671013411 0ustar vossvoss/* gameprob.i - SWIG control file for the gameprob module * * Copyright (C) 2003 Jochen Voss. * * $Id: gameprob.i 5068 2003-07-19 12:43:00Z voss $ */ %module gameprob %{ #include "gameprob.h" static PyObject *wrap_param_name (PyObject *self, PyObject *args) { struct param_info *ptr; int id; if (! PyArg_ParseTuple (args, "i", &id)) return NULL; ptr = find_parameter (id); if (! ptr) { PyErr_SetString(PyExc_KeyError, "invalid parameter id"); return NULL; } if (! ptr->name) { PyErr_SetString(PyExc_ValueError, "parameter has no name"); return NULL; } return PyString_FromString (ptr->name); } static PyObject *wrap_param_min (PyObject *self, PyObject *args) { struct param_info *ptr; int id; if (! PyArg_ParseTuple (args, "i", &id)) return NULL; ptr = find_parameter (id); if (! ptr) { PyErr_SetString(PyExc_KeyError, "invalid parameter id"); return NULL; } return PyFloat_FromDouble (ptr->min); } static PyObject *wrap_param_max (PyObject *self, PyObject *args) { struct param_info *ptr; int id; if (! PyArg_ParseTuple (args, "i", &id)) return NULL; ptr = find_parameter (id); if (! ptr) { PyErr_SetString(PyExc_KeyError, "invalid parameter id"); return NULL; } return PyFloat_FromDouble (ptr->max); } static PyObject *wrap_param_default (PyObject *self, PyObject *args) { struct param_info *ptr; int id; if (! PyArg_ParseTuple (args, "i", &id)) return NULL; ptr = find_parameter (id); if (! ptr) { PyErr_SetString(PyExc_KeyError, "invalid parameter id"); return NULL; } return PyFloat_FromDouble (ptr->default_value); } static PyObject *wrap_param_board (PyObject *self, PyObject *args) { struct param_info *ptr; int id; if (! PyArg_ParseTuple (args, "i", &id)) return NULL; ptr = find_parameter (id); if (! ptr) { PyErr_SetString(PyExc_KeyError, "invalid parameter id"); return NULL; } return PyInt_FromLong (ptr->board); } static PyObject *wrap_find_param_by_name (PyObject *self, PyObject *args) { struct param_info *ptr; const char *name; if (! PyArg_ParseTuple (args, "s", &name)) return NULL; ptr = find_param_by_name (name); if (! ptr) { PyErr_SetString(PyExc_KeyError, "invalid parameter name"); return NULL; } return PyInt_FromLong (ptr->id); } %} extern void register_parameter (int id, const char *name); extern void set_param (int id, double val); extern double get_param (int id); %native(param_name) wrap_param_name; %native(param_board) wrap_param_board; %native(param_min) wrap_param_min; %native(param_max) wrap_param_max; %native(param_default) wrap_param_default; %native(find_param_by_name) wrap_find_param_by_name; enum result { res_BLACK, res_WHITE, res_JIGO }; extern void register_game (int id, int black, int white, int board, int hc, int komi, int with_jigo, const char *res); extern double probability (int black, int white, int board, int hc, int komi, int with_jigo, enum result res); extern double game_prob (int game); extern int applies_to (int param, int game); %init %{ init_parameters (); %} golist-0.4/ChangeLog0100644000175000017500000000526207706242671013217 0ustar vossvoss------------------------------------------------------------------------ rev 5068: voss | 2003-07-19 14:43:00 +0200 (Sat, 19 Jul 2003) | 6 lines * Prepare for a release: - add copyright notices and licensing information to all files - make sure that all files have $Id$ tags - add more comments and extend the README file - Add a copy of the GPL ------------------------------------------------------------------------ rev 5045: voss | 2003-07-09 10:14:01 +0200 (Wed, 09 Jul 2003) | 6 lines * export-results: fix for case that the first game is a jigo * spieleabend.sh: automatically print the results * ChangeLog: regenerated * README: mention my name * expand $Id$ keywords ------------------------------------------------------------------------ rev 4962: voss | 2003-04-29 23:45:37 +0200 (Tue, 29 Apr 2003) | 2 lines export-games: remove the bogous 'tag:' comment line ------------------------------------------------------------------------ rev 4905: voss | 2003-04-22 16:45:04 +0200 (Tue, 22 Apr 2003) | 3 lines Add forgotten files to the archive. Ignore forgotten autogenerated file "go-history-private.h". ------------------------------------------------------------------------ rev 4904: voss | 2003-04-22 16:42:39 +0200 (Tue, 22 Apr 2003) | 4 lines Update to package version 0.3.1. Set svn:keywords to expand $Id$ tags. Handle and remove old .cvsignore files. ------------------------------------------------------------------------ rev 4903: voss | 2003-04-22 16:38:33 +0200 (Tue, 22 Apr 2003) | 1 line remove games.xml from the archive ------------------------------------------------------------------------ rev 4902: voss | 2003-04-22 16:36:56 +0200 (Tue, 22 Apr 2003) | 1 line expand $ tags ------------------------------------------------------------------------ rev 4883: voss | 2003-04-14 15:22:51 +0200 (Mon, 14 Apr 2003) | 1 line add jv:section tags for the new make-links.sh script ------------------------------------------------------------------------ rev 4866: voss | 2003-04-14 15:11:11 +0200 (Mon, 14 Apr 2003) | 1 line switch to a more tight layout ------------------------------------------------------------------------ rev 4852: voss | 2003-04-14 13:16:32 +0200 (Mon, 14 Apr 2003) | 1 line remove arch related cruft ------------------------------------------------------------------------ rev 4812: voss | 2003-04-13 12:48:01 +0200 (Sun, 13 Apr 2003) | 2 lines move old version of the golist project in place ------------------------------------------------------------------------ rev 4811: voss | 2003-04-13 12:47:12 +0200 (Sun, 13 Apr 2003) | 2 lines import new version of the golist project ------------------------------------------------------------------------ golist-0.4/gameprob_wrap.doc0100644000175000017500000000073407706242671014760 0ustar vossvossgameprob_wrap.c [ Python Module : gameprob ] param_name(i) [ returns char * ] param_min(i) [ returns double ] param_max(i) [ returns double ] param_board(i) [ returns int ] find_param(name) [ returns int ] allocate_parameters(c) [ returns void ] set_param(i,val) [ returns void ] get_param(i) [ returns double ] probability(black,white,board,hc,komi,with_jigo,res) [ returns double ] golist-0.4/update-histories0100755000175000017500000000726207706242671014666 0ustar vossvoss#! /usr/bin/env python # update-histories - add missing entries to the history table # $Id: update-histories 5068 2003-07-19 12:43:00Z voss $ # # Copyright 2003 Jochen Voss # # Add missing entries to the histories table. # This should be run once upon a time. It prints a list of new # history entries to stdout. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA import MySQLdb from kjbuckets import kjSet from dbhelper import sql_write_line, get_player_strength, rank_to_strength def update_anonymous_players(c): c.execute("SELECT black FROM game" + " WHERE black rlike '[1-9][0-9]*[dk]'" + " GROUP by black") tokenb=map(lambda t:t[0],c.fetchall()) c.execute("SELECT white FROM game" + " WHERE white rlike '[1-9][0-9]*[dk]'" + " GROUP by white") tokenw=map(lambda t:t[0],c.fetchall()) needed=kjSet(tokenb+tokenw) c.execute("SELECT token FROM history" + " WHERE token rlike '[1-9][0-9]*[dk]'" + " GROUP by token") existing=kjSet(map(lambda t:t[0],c.fetchall())) for token in (needed-existing).items(): dict={} dict["token"]=token dict["validfrom"]="2000-01-01" dict["strength"]=rank_to_strength(token) dict["fix"]=rank_to_strength(token) dict["settled"]="y" sql_write_line(c,"history",dict) print "added entry for anonymous %s"%token def insert_entry(c,token,rank,validfrom,type="continuation"): dict={} dict["validfrom"]=validfrom.Format("%Y-%m-%d") dict["token"]=token strength=get_player_strength(c,token) if strength: dict["strength"]=strength if rank: dict["fix"]=rank_to_strength(rank) sql_write_line(c,"history",dict) print "%s entry %s for %s" % (type,dict["validfrom"],dict["token"]) def update_player_history_points(c,token,rank): c.execute("SELECT gamedate FROM game" + " WHERE black = '%s' OR white = '%s'" % (token,token) + " ORDER BY gamedate") games=map(lambda g:g[0],c.fetchall()) if not games: return c.execute("SELECT MAX(validfrom) FROM history" + " WHERE token = '%s'" % token + " GROUP BY token") lastdate=c.fetchone() if lastdate: lastdate=lastdate[0] if not lastdate: g=games[0] insert_entry(c,token,rank,g,"initial") lastdate=g games=filter(lambda x: x>=lastdate,games) count = 0 candidate = None for g in games: count += 1 if count<=10 or g == lastdate: continue if candidate: insert_entry(c,token,rank,candidate) candidate = g lastdate = g count = 0 def main(): db = MySQLdb.connect(host='localhost', db='golist') c=db.cursor() c.execute("LOCK TABLES game READ, player READ, history WRITE") update_anonymous_players(c) c.execute("SELECT token,rank FROM player where component=0") for p in c.fetchall(): update_player_history_points(c,p[0],p[1]) c.execute("UNLOCK TABLES") if __name__ == "__main__": main () golist-0.4/sql/0042755000175000017500000000000007706242671012244 5ustar vossvossgolist-0.4/sql/create.sql0100644000175000017500000000252407706242671014226 0ustar vossvoss-- -- Create empty tables for the golist database. -- Be careful: this deletes any previously stored golist database. -- -- Usage: -- mysql golist # # Import a list of new games. # The input file should be a template from "tmpl-games" # with new games filled in. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA import MySQLdb import fileinput from string import split from dbhelper import sql_write_line from math import floor db=MySQLdb.connect(host='localhost', db='golist') c=db.cursor() c.execute("LOCK TABLES game WRITE") short={ "joh": "johannes", "alex": "alexander" } for line in fileinput.input(): if line[0] == "#": continue w=split(line) dict={} dict["gamedate"]=w[0] if w[1] in short: w[1]=short[w[1]] dict["black"]=w[1] if w[2] in short: w[2]=short[w[2]] dict["white"]=w[2] dict["board"]=w[3] dict["handicap"]=w[4] komi=float(w[5]) dict["komi"]=floor(komi) if floor(komi) # # This script exports a list of players from the database. # Output format is either TeX source or plain text, as # choosen by the -T option. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA import MySQLdb from dbhelper import strength_to_rank from mx.DateTime import now import sys, getopt ###################################################################### class tex_output: def open(self): print r"""\documentclass[a4paper,12pt]{article} \usepackage[latin1]{inputenc} \usepackage[T1]{fontenc} \setlength\oddsidemargin{2.5cm} \addtolength\oddsidemargin{-1in} \setlength\evensidemargin{2.5cm} \addtolength\evensidemargin{-1in} \setlength\textwidth{16cm} \setlength\parindent{0pt} \pagestyle{empty} \begin{document} \begin{center} \textbf{Spielerliste für den geheimen Go-Spielabend}\\ Stand: %s \end{center} \bigskip \begin{tabular}{llcrrrrr} name&token&last seen&won&jigo&lost&strength&rank\\ \noalign{\vskip2pt}""" % now().Format("%Y-%m-%d") def close(self): print r"""\end{tabular} \end{document}""" def emit_player(self,name,token,last_seen,won,jigo,lost,strength,rank): if rank[0]=="*": rank="\\textbf{%s}" % rank[1:] print ("%s&%s&%s&%d&%d&%d&%s&%s\\\\" % (name,token,last_seen,won,jigo,lost,strength,rank)) class plain_output: def open(self): print "Spielerliste für den geheimen Go-Spielabend" print "Stand: %s" % now().Format("%Y-%m-%d") print print " won jigo lost str. rank" def close(self): pass def emit_player(self,name,token,last_seen,won,jigo,lost,strength,rank): if len(rank)>0 and rank[0]!="*": rank = " "+rank; print ("%-30s %3d %3d %3d %6s %4s" % (name,won,jigo,lost,strength,rank)) ###################################################################### flags=[] backend="tex" try: opts, args = getopt.getopt(sys.argv[1:],"aT:",["all","backend"]) except getopt.GetoptError: print "usage: export-players [-a] [-T type]" print " -a, --all show all players" print " -T, --backend choose the output backend (tex or plain)" sys.exit(1) for o,a in opts: if o in ("-a","--all"): flags.append("all") if o in ("-T","--backend"): backend=a try: out=eval(backend+"_output()") except: raise "unknown backend "+backend db=MySQLdb.connect(host='localhost', db='golist') c=db.cursor() def prot(x): if x: return x; return "" lastgame={} wins={} jigos={} total={} c.execute("SELECT token,MAX(gamedate) as lastgame,COUNT(game.id) as total" + " FROM player,game WHERE token=black OR token=white" + " GROUP BY token") l=c.fetchall() for g in l: lastgame[g[0]]=g[1] wins[g[0]]=0 jigos[g[0]]=0 total[g[0]]=g[2] c.execute("SELECT token,COUNT(game.id) as wins" + " FROM player,game" + ' WHERE token=black AND result="black"' + ' OR token=white AND result="white"' + " GROUP BY token") l=c.fetchall() for g in l: wins[g[0]]=g[1] c.execute("SELECT token,COUNT(game.id) as wins" + " FROM player,game" + ' WHERE (token=black OR token=white) AND result="jigo"' + " GROUP BY token") l=c.fetchall() for g in l: jigos[g[0]]=g[1] out.open() if "all" in flags: vstr="" else: vstr=" WHERE visible='y'" c.execute("SELECT token,name,rank,strength FROM player" + vstr + " ORDER BY strength DESC") l=c.fetchall() for g in l: p=g[0] if g[2]: rank="*" + g[2] elif g[3]: rank="%s" % strength_to_rank(g[3]) else: rank="" if g[3]: str="%.2f"%g[3] else: str="" out.emit_player(prot(g[1]), p, lastgame[p], wins[p], jigos[p], total[p]-wins[p]-jigos[p], str, rank) out.close() golist-0.4/COPYING0100644000175000017500000004311007706242672012473 0ustar vossvoss GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. golist-0.4/TODO0100644000175000017500000000014307706242672012127 0ustar vossvoss· update-components is wrong: players of a given strength are no longer automatically connected. golist-0.4/update-strengths0100755000175000017500000002422307706242672014673 0ustar vossvoss#! /usr/bin/env python # update-strength - update the players' strengths values # $Id: update-strengths 5068 2003-07-19 12:43:00Z voss $ # # Copyright 2003 Jochen Voss # # Calculate new player strength values. # This script is the central part of the golist framework. # It updates the strength fields in the 'player' table # and in the 'history' table. # # The script uses an iterative method and takes some time to run. # Running it repeatedly may give better results. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA import MySQLdb from dbhelper import get_tokens, get_historic_player_strength from _gameprob import * from math import log,sqrt from random import gauss from mx.DateTime import now import sys, getopt games=[] # game id values to look at params=[] # parameter id values to optimize neighbours={} # neighbouring parameters fix={} # id values for fixed parameters cushion=0.00001 def hid_penalty(p,w=2): npen=0 x=get_param(p) for q in neighbours[p]: d=get_param(q)-x npen += w*d*d if p in fix: d=fix[p]-x fpen=d*d else: fpen=0 return 0.3*npen+fpen def total_penalty(): s=0 for p in params: s+=hid_penalty(p,1) return s def log_sum_dict(dict): return reduce(lambda x,y:x+log(dict[y]+cushion),dict,0) def get_all_params(): dict={} for p in params: dict[p]=get_param(p) return dict def set_all_params(dict): for p in params: set_param(p,dict[p]) def sum_hid_games(p): s=0 for g in games: if not applies_to(p,g): continue pr=game_prob(g) s += log(pr+cushion) return s def sum_cached_hid_games(p,cache): s=0 for g in games: if not applies_to(p,g): continue s += log(cache[g]+cushion) return s def sum_all_games(): s=0 for g in games: pr=game_prob(g) s += log(pr+cushion) return s def try_all_games(): res={} for g in games: res[g]=game_prob(g) return res def optimise_single_param(p): "Find the optimal value of P while the remaining parameters stay fixed." bestx = get_param(p) bestval = sum_hid_games(p)-hid_penalty(p) min=param_min(p) max=param_max(p) for i in range(0,21): x=min+i*(max-min)/20.0 set_param(p,x) val=sum_hid_games(p)-hid_penalty(p) if val>bestval: bestx=x bestval=val base=bestx for i in range(-9,10): z=base+i*(max-min)/200.0 if zmax: continue set_param(p,z) val=sum_hid_games(p)-hid_penalty(p) if val>bestval: bestx=z bestval=val set_param(p,bestx) def gradient_step(dx): oldpos=get_all_params() oldvalues=try_all_games() oldpenalty=total_penalty() # calculate the gradient grad={} for p in params: set_param(p,oldpos[p]+0.01*dx) newval=sum_hid_games(p)-hid_penalty(p) set_param(p,oldpos[p]) oldval=sum_cached_hid_games(p,oldvalues)-hid_penalty(p) grad[p]=(newval-oldval)/(0.01*dx) l=0 for p in grad: l += grad[p]*grad[p] l=sqrt(l) if l==0: for p in grad: set_param(p, gauss(oldpos[p],dx)) else: for p in grad: set_param(p, oldpos[p] + grad[p]*dx/l) newvalues=try_all_games() zold=log_sum_dict(oldvalues) - oldpenalty znew=log_sum_dict(newvalues) - total_penalty() if znew <= zold: set_all_params(oldpos) return 0 else: print "g %+g" % (znew-zold) return 1 def random_step(dx): oldpos=get_all_params() oldvalues=try_all_games() oldpenalty=total_penalty() for p in params: set_param(p, gauss(oldpos[p],dx)) newvalues=try_all_games() zold=log_sum_dict(oldvalues) - oldpenalty znew=log_sum_dict(newvalues) - total_penalty() if znew <= zold: set_all_params(oldpos) return 0 else: print "r %+g" % (znew-zold) return 1 #def plot_parameter(p): # g = Gnuplot.Gnuplot(debug=1) # g.title('log-likelihood function for parameter %s' % param_name(p)) # oldx=get_param(p) # values=[] # min=param_min(p) # max=param_max(p) # for i in range(0,101): # x=min+i*(max-min)/100.0 # set_param(p,x) # val=sum_hid_games(p) # values.append([x,val]) # set_param(p,oldx) # g('set data style lines') # g.plot(values) # raw_input('Please press return to continue...\n') #try: # import Gnuplot # have_gnuplot=1 #except ImportError: # have_gnuplot=0 # # plot_parameter(find_param("s19")) # plot_parameter(1) ###################################################################### def parse_options(): guess_builtin=[] max_steps=200 try: opts, args = getopt.getopt(sys.argv[1:],"b:n:", ["builtin=","steps="]) except getopt.GetoptError: print "usage: update-strengths [-b builtins] [-n maxsteps]" print " -b NAMES, --builtin try to guess values for the built-in parameters" print " -n VAL, --steps do at most VAL steps (default: %d)"%max_steps sys.exit(1) for o,a in opts: if o in ("-b","--guess-builtin"): guess_builtin=a.split(":") if o in ("-n", "--max-steps"): max_steps=int(a) return (guess_builtin,max_steps) def read_params(c,guess_builtin): global params, neighbours c.execute("SELECT id,strength,token,fix,settled FROM history") for h in c.fetchall(): register_parameter(h[0],"%s:%d"%(h[2],h[0])) set_param(h[0],h[1]) if h[4]=="y": continue params.append(h[0]) if h[3]: fix[h[0]]=h[3] builtin={} c.execute("SELECT name,value FROM parameters") for p in c.fetchall(): builtin[p[0]]=p[1] for name in guess_builtin: p=find_param_by_name(name) if name in builtin: set_param(p,builtin[name]) params.append(p) c.execute("SELECT id,token FROM history ORDER BY token,validfrom") l=c.fetchall() for p in params: neighbours[p]=[] for i in range(0,len(l)): p=l[i][0] if p not in params: continue token=l[i][1] if i>0 and l[i-1][1]==token: neighbours[p].append(l[i-1][0]) if i0: if not gradient_step(dx): if dx>1e-14: dx *= 0.5 print "gradient step: dx=%g"%dx else: break steps -= 1 dx=0.1 fail = 0 if steps>0: print "even better value: %f" % (sum_all_games()-total_penalty()) print "random step: variance %g"%dx while steps>0: if not random_step(dx): if fail>10 and dx>1e-10: fail = 0 dx *= 0.5 print "random step: variance %g"%dx else: fail += 1 if fail>100: break else: fail = 0 steps -= 0.1 # write back the result print "final value: %f" % (sum_all_games()-total_penalty()) write_params(c) write_games(c) write_players(c) if __name__ == "__main__": main () golist-0.4/update-components0100755000175000017500000000505207706242672015036 0ustar vossvoss#! /usr/bin/env python # update-components - update the "component" column of table "player" # $Id: update-components 5068 2003-07-19 12:43:00Z voss $ # # Copyright 2003 Jochen Voss # # Find the strongly connected components of the game graph. # This does a complete recalculation and overwrites any previous # values in the components table. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA import MySQLdb from kjbuckets import kjGraph from dbhelper import get_tokens def get_pairs(): "Get the game results from the database." rel=kjGraph() c.execute("SELECT black,white,result FROM game" + " GROUP BY black,white,result") while 1: g=c.fetchone() if not g: break if g[2] == "black": rel.add((g[0],g[1])) elif g[2] == "white": rel.add((g[1],g[0])) elif g[2] == "jigo": rel.add((g[0],g[1])) rel.add((g[1],g[0])) else: raise "unknown type of herring: %s" % g[2] return rel def get_components(): rel=get_pairs().tclosure() tokens=get_tokens(c) comp={} maxcomp=0 c.execute("SELECT token FROM player WHERE rank") while 1: p=c.fetchone() if not p: break comp[p[0]]=maxcomp tokens.remove(p[0]) while tokens: p=tokens.pop() for q in comp.keys(): if rel.member((p,q)) and rel.member((q,p)): comp[p]=comp[q] break else: maxcomp+=1 comp[p]=maxcomp return comp def update_components(): tokens=get_tokens(c) comp=get_components() for p in tokens: c.execute('UPDATE player SET component = %d WHERE token = "%s"' % (comp[p],p)) db = MySQLdb.connect(host='localhost', db='golist') c=db.cursor() c.execute("LOCK TABLES game READ, player WRITE") update_components() c.execute("UNLOCK TABLES") golist-0.4/export-games0100755000175000017500000001000407706242672013775 0ustar vossvoss#! /usr/bin/env python # $Id: export-games 5068 2003-07-19 12:43:00Z voss $ # # Copyright 2003 Jochen Voss # # This script exports a list of games from the database. # Output format is either TeX source or plain text, as # choosen by the -T option. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA import MySQLdb from mx.DateTime import now import sys, getopt ###################################################################### class tex_output: def open(self,flags): print r"""\documentclass[a4paper]{article} \usepackage[latin1]{inputenc} \usepackage{longtable} \setlength\oddsidemargin{2.5cm} \addtolength\oddsidemargin{-1in} \setlength\evensidemargin{2.5cm} \addtolength\evensidemargin{-1in} \setlength\textwidth{16cm} \setlength\parindent{0pt} \pagestyle{empty} \begin{document} \begin{center} \textbf{Spieleliste des geheimen Go-Spielabends}""" if not "all" in flags: print r"\\ eine Auswahl neuerer Spiele" print r"""\end{center} \bigskip \begin{longtable}{cllrrrll} date&black&white&board&hc&komi&winner&prob.\\ \endhead\noalign{\vskip2pt}""" def close(self): print r"""\end{longtable} \end{document} """ def emit_game(self,date,black,white,board,hc,komi,winner,prob): print "%s&%s&%s&%d&%d&%g&%s&%s\\\\"%(date,black,white,board,hc,komi,winner,prob) ###################################################################### class plain_output: def open(self,flags): print "Spieleliste des geheimen Go-Spielabends" if not "all" in flags: print "eine Auswahl neuerer Spiele" print print "date\tblack\twhite\tboard\thc\tkomi\twinner\tprob." def close(self): pass def emit_game(self,date,black,white,board,hc,komi,winner,prob): print "%s\t%s\t%s\t%d\t%d\t%g\t%s\t%s"%(date,black,white,board,hc,komi,winner,prob) ###################################################################### flags=[] backend="tex" try: opts, args = getopt.getopt(sys.argv[1:],"aT:",["all","backend"]) except getopt.GetoptError: print "usage: export-games [-a] [-T type]" print " -a, --all print all games" print " -T, --backend choose the output backend (tex or plain)" sys.exit(1) for o,a in opts: if o in ("-a","--all"): flags.append("all") if o in ("-T","--backend"): backend=a try: out=eval(backend+"_output()") except: raise "unknown backend "+backend db=MySQLdb.connect(host='localhost', db='golist') c=db.cursor() out.open(flags) c.execute('SELECT id,gamedate,black,white,board,handicap,' + 'if(withjigo="n",komi+0.5,komi) as komi,result,probability' + ' FROM game ORDER BY gamedate,id') l=c.fetchall() def pairkey(a,b): if a=45: break for g in l: if g[0] not in games: continue if g[8]: prob="%f"%g[8] else: prob="---" out.emit_game(g[1].Format("%Y-%m-%d"),g[2],g[3],g[4],g[5],g[6],g[7],prob) out.close() golist-0.4/tmpl-games0100755000175000017500000000362707706242672013445 0ustar vossvoss#! /usr/bin/env python # $Id: tmpl-games 5068 2003-07-19 12:43:00Z voss $ # # Copyright 2003 Jochen Voss # # Export a template file to enter new games. # Usage: # tmpl-games >g.dat # # edit g.dat with your favourite editor # import-games ="%s" ORDER BY gamedate' % limit.Format("%Y-%m-%d")) recentgames=map(lambda x:x,c.fetchall()) print "# recent games:" print "# date black white board hc komi result" for g in recentgames: if g[8] and (g[8]<0.1 or (g[7] == "jigo" and g[8]<0.003)): warn=" <- ???" else: warn="" if g[6] == "y": komi=g[5] else: komi=g[5]+0.5 print ("# %s %12s %12s %2d %3d %4g %s%s" % (g[0].Format("%Y-%m-%d"),g[1],g[2],g[3],g[4],komi,g[7],warn)) print "# add new games here:" print now().Format("%Y-%m-%d\t") golist-0.4/import-xml0100755000175000017500000000544207706242672013504 0ustar vossvoss#! /usr/bin/env python # $Id: import-xml 5068 2003-07-19 12:43:00Z voss $ # # Copyright 2003 Jochen Voss # # Import an old-style golist file. This inserts the # contents of "games.xml" into the database. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA import MySQLdb from mx.DateTime import * from math import floor from xml.dom import * from xml.dom.minidom import parse from dbhelper import * fname='games.xml' db=MySQLdb.connect(host='localhost', db='golist') c=db.cursor() c.execute("LOCK TABLES game WRITE, player WRITE") dom=parse(fname) golist=dom.childNodes[0] if golist.tagName !="golist": raise "cannot read %s (not a golist file)" % fname for node in golist.childNodes: if node.nodeType !=Node.ELEMENT_NODE: continue if node.tagName == "player": token=node.getAttribute("token").encode("latin-1") name=node.getAttribute("name").encode("latin-1") rank=node.getAttribute("rank").encode("latin-1") strength=node.getAttribute("strength").encode("latin-1") dict={"token":token, "name":name} if rank: dict["rank"]=rank if strength: dict["strength"]=strength sql_write_line(c,"player",dict) elif node.tagName == "game": date=node.getAttribute("date").encode("latin-1") black=node.getAttribute("black").encode("latin-1") white=node.getAttribute("white").encode("latin-1") res=node.getAttribute("res").encode("latin-1") board=node.getAttribute("board").encode("latin-1") handicap=node.getAttribute("handicap").encode("latin-1") komi=node.getAttribute("komi").encode("latin-1") dict={"black":black, "white":white, "board":board, "result":res} if date: dict["gamedate"]=strptime(date,"%d.%m.%Y").Format("%Y-%m-%d") if handicap: dict["handicap"]=handicap if komi: komi=float(komi) x=floor(komi) dict["komi"]=x if x # # This module contains helper functions for the golist scripts. # These help to access the SQL database and to convert between # textual and numerical strength values. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA def get_tokens(c): "Get the list of all player tokens." c.execute("SELECT token FROM player") return map(lambda p:p[0],c.fetchall()) def rank_to_strength (rank): num=rank[:-1] sig=rank[-1] if sig == "k": return -float(num) elif sig == "d": return float(num)-1 else: raise "invalid rank "+rank def strength_to_rank (strength): x=round(strength) if x<0: rank="%dk" % -x else: rank="%dd" % (x+1) return rank def get_player_strength(c, token): "Get the current strength of player TOKEN." c.execute ("SELECT rank,strength FROM player WHERE token = '%s'" % token) x=c.fetchone() if x[1]: return x[1] if x[0]: return rank_to_strength(x[0]) return None def get_historic_player_strength(c, token, date): "Get the strength of player TOKEN at time DATE." c.execute ("SELECT strength FROM history" +" WHERE token='%s'" % token +" AND validfrom <= '%s'" % date.Format("%Y-%m-%d") +" ORDER BY validfrom DESC LIMIT 1") x=c.fetchone() if x: return x[0] return None def sql_write_line(c,table,dict): fields=dict.keys() values=dict.values() c.execute("INSERT INTO %s ("%table+",".join(fields)+")" + " VALUES (" + ",".join(["%s"]*len(fields)) + ")", values) golist-0.4/Makefile0100644000175000017500000000111307706242672013075 0ustar vossvoss# Makefile # $Id: Makefile 5045 2003-07-09 08:14:01Z voss $ .PHONY: all all: _gameprob.so _gameprob.so: gameprob.o gameprob_wrap.o ld -shared $^ -o $@ gameprob.o: gameprob.c gameprob.h gameprob_wrap.o: gameprob_wrap.c gameprob.h $(CC) $(CFLAGS) -c $< -I/usr/include/python2.2 -I/usr/lib/python2.2/config gameprob_wrap.c: gameprob.i swig -python gameprob.i .PHONY: backup backup: mysqldump --opt golist > backup/$$(date -I).sql .PHONY: clean distclean clean: rm -f gameprob.o gameprob_wrap.o _gameprob.so rm -f *.log *.aux distclean: clean rm -f outp.* outg.* g.dat *~ *.pyc golist-0.4/gameprob.c0100644000175000017500000002066207706242672013407 0ustar vossvoss/* gameprob.c - stochastic model for the game results * * Copyright (C) 2002, 2003 Jochen Voss * * This module implements a stochastic model for the outcome * of a game of go. The functionality is in the function * 'probability' below. * * These functions are hooked into the Python scripts via a * SWIG-generated interface. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ static const char rcsid[] = "$Id: gameprob.c 5068 2003-07-19 12:43:00Z voss $"; #include #include #include #include #include #include #include "gameprob.h" /* Jigo probabilities for games with integral komi values. * These are only wild guesses, which are not based on facts. */ #define P_JIGO_19 0.008 #define P_JIGO_13 0.017 #define P_JIGO_9 0.035 /* variable internal parameters */ static double /*1,*/ h13, h9; /* h = grade difference / handicap stone */ static double k19, k13, k9; /* k = komi / handicap stone */ static double e19, e13, e9; /* komi appropriate for even game */ static double jo19, jo13, jo9; /* jigo offsets */ static double s19, s13, s9; /* variance of results */ static const struct param_info internal [] = { { -1, "e19", &e19, 6, 0, 12, 19 }, { -2, "e13", &e13, 6, 0, 12, 13 }, { -3, "e9", &e9, 4, 0, 12, 9 }, { -4, "jo19", &jo19, 0.01, 0, 0.1, 19 }, { -5, "jo13", &jo13, 0.02, 0, 0.1, 13 }, { -6, "jo9", &jo9, 0.04, 0, 0.1, 9 }, { -7, "h13", &h13, 2.5, 1, 10, 13 }, { -8, "h9", &h9, 5, 1, 10, 9 }, { -9, "k19", &k19, 10, 1, 20, 19 }, { -10, "k13", &k13, 10, 5, 30, 13 }, { -11, "k9", &k9, 13, 5, 20, 9 }, { -12, "s19", &s19, 5, 2, 15, 19 }, { -13, "s13", &s13, 5, 2, 15, 13 }, { -14, "s9", &s9, 5, 2, 15, 9 }, }; #define PARAM_COUNT (sizeof(internal)/sizeof(struct param_info)) /********************************************************************** * game model parameters. */ static void *parameters = NULL; static int param_comp (const void *a, const void *b) { const struct param_info *pa = a; const struct param_info *pb = b; return (pa->id > pb->id) - (pa->id < pb->id); } struct param_info * find_parameter (int id) { struct param_info pi, **ptr;; pi.id = id; ptr = tfind (&pi, ¶meters, param_comp); return ptr ? *ptr : NULL; } static double Phi (double x) /* The distribution function of the standard normal distribution. */ { return (1+erf (x/M_SQRT2))/2; } static double jigo_offset (double p_jigo) /* Return the value x with 'Phi(+x)-Phi(-x) == P_JIGO'. * P_JIGO is the jigo probability for even game. */ { double l, r, q; q = 0.5*(1+p_jigo); assert (0.5 <= q && q < Phi(1)); l = 0; r = 1; while (l+1e-6 < r) { double m; assert (Phi(l) <= q && q < Phi(r)); m = 0.5*(l+r); if (Phi(m) <= q) { l = m; } else { r = m; } } return l; } void init_parameters (void) { int i; jo9 = jigo_offset (P_JIGO_9); jo13 = jigo_offset (P_JIGO_13); jo19 = jigo_offset (P_JIGO_19); for (i=0; i= 0 && ! find_parameter (id)); ptr = malloc (sizeof(struct param_info)); ptr->id = id; ptr->name = name ? strdup(name) : NULL; ptr->ptr = malloc(sizeof(double)); ptr->default_value = -19; ptr->min = -45; ptr->max = 7; ptr->board = 0; *(ptr->ptr) = ptr->default_value; tsearch (ptr, ¶meters, param_comp); } static const char *needle; struct param_info *name_search_res; static jmp_buf trampoline; static void name_search_fn (const void *node, VISIT val, int level) { if (val == leaf || val == preorder) { const struct param_info *p = *( struct param_info *const*)node; if (strcmp (p->name, needle) == 0) { name_search_res = (struct param_info *)p; longjmp (trampoline, 1); } } } struct param_info * find_param_by_name (const char *name) /* Note: this function is not thread safe. */ { needle = name; if (setjmp (trampoline)) { return name_search_res; } else { twalk (parameters, name_search_fn); return NULL; } } void set_param (int id, double val) { struct param_info *p = find_parameter (id); if (val < p->min) { val = p->min; } else if (val > p->max) { val = p->max; } *(p->ptr) = val; } double get_param (int id) { struct param_info *p = find_parameter (id); return *(p->ptr); } /********************************************************************** * Games */ static void *games = NULL; static int game_comp (const void *a, const void *b) { const struct game_info *pa = a; const struct game_info *pb = b; return (pa->id > pb->id) - (pa->id < pb->id); } struct game_info * find_game (int id) { struct game_info pi, **ptr;; pi.id = id; ptr = tfind (&pi, &games, game_comp); return ptr ? *ptr : NULL; } void register_game (int id, int black, int white, int board, int hc, int komi, int with_jigo, const char *res) { struct game_info *ptr; assert (! find_game(id)); ptr = malloc (sizeof(struct game_info)); ptr->id = id; ptr->black = black; ptr->white = white; ptr->board = board; ptr->hc = hc; ptr->komi = komi; ptr->with_jigo = with_jigo; if (strcmp(res,"black")==0) { ptr->res = res_BLACK; } else if (strcmp(res,"white")==0) { ptr->res = res_WHITE; } else if (strcmp(res,"jigo")==0) { ptr->res = res_JIGO; } else { assert (0); } tsearch (ptr, &games, game_comp); } static double game_offset (int board, int handicap, int komi) /* Returns the strength offset, measured in player grades. * Positive values indicate, that the setting favours black. */ { double h, k, e; switch (board) { case 19: h = 1; k = k19; e = e19; break; case 13: h = h13; k = k13; e = e13; break; case 9: h = h9; k = k9; e = e9; break; default: abort (); } if (handicap>0) return h*(handicap-1 + (e-komi)/k); return h*(e-komi)/k; } double probability (int black, int white, int board, int hc, int komi, int with_jigo, enum result res) /* Return the probability of a game. * BLACK and WHITE are indices for the player strength values table. * The return value depends on the model parameters. */ { double mu, sigma, jo; double p; switch (board) { case 19: sigma = s19; jo = jo19; break; case 13: sigma = s13; jo = jo13; break; case 9: sigma = s9; jo = jo9; break; default: assert (0); } mu = (get_param(black)-get_param(white)) + game_offset (board, hc, komi); switch (res) { case res_BLACK: p = 1 - Phi ((-mu+jo)/sigma); break; case res_WHITE: if (with_jigo) { p = Phi ((-mu-jo)/sigma); } else { p = Phi ((-mu+jo)/sigma); } break; default: /* res_JIGO */ assert (with_jigo); p = Phi ((-mu+jo)/sigma) - Phi ((-mu-jo)/sigma); break; } return p; } double game_prob (int game) /* Return the probability for the outcome of GAME. * The game index refers to an 'id' argument value of the * 'register_game' function. The result depends on the * model parameters. */ { struct game_info *g = find_game (game); return probability (g->black, g->white, g->board, g->hc, g->komi, g->with_jigo, g->res); } int applies_to (int param, int game) /* Check whether a given model parameter affect the probability of GAME. * Positive parameter indices indicate external parameters (i.e. player * strengths), negative indices indicate internal model parameters from * the table 'internal'. */ { struct game_info *g = find_game (game); if (param >= 0) { return (g->black == param || g->white == param); } else { struct param_info *p = find_parameter (param); return (p->board == 0 || p->board == g->board); } }