4 ## Copyright (C) 2006 Daigo Moriwaki <daigo at debian dot org>
6 ## This program is free software; you can redistribute it and/or modify
7 ## it under the terms of the GNU General Public License as published by
8 ## the Free Software Foundation; either version 2 of the License, or
9 ## (at your option) any later version.
11 ## This program is distributed in the hope that it will be useful,
12 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 ## GNU General Public License for more details.
16 ## You should have received a copy of the GNU General Public License
17 ## along with this program; if not, write to the Free Software
18 ## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 # This calculates rating scores of every players from CSA files, and outputs a
22 # yaml file (players.yaml) that Shogi Server can read.
25 # $ ./mk_rate . > players.yaml
27 # The conditions that games and players are rated as following:
28 # * Rated games, which were played by both rated players.
29 # * Rated players, who logged in the server with a name followed by a trip:
31 # * (Rated) players, who played more than $GAMES_LIMIT [ten] (rated) games.
37 # Ruby bindings for the GNU Scientific Library (GSL) is required.
38 # You can download it from http://rb-gsl.rubyforge.org/
39 # Or, if you use Debian,
40 # $ sudo aptitude install libgsl-ruby1.8
47 #################################################
51 # Count out players who play less games than $GAMES_LIMIT
52 $GAMES_LIMIT = $DEBUG ? 0 : 10
58 # Holds the last time when a player gamed
59 $players_time = Hash.new { Time.at(0) }
62 #################################################
63 # Keeps the value of the lowest key
71 if @lowest.empty? || key < @lowest[0]
72 @lowest = [key, value]
85 #################################################
86 # Calculates rates of every player from a Win Loss GSL::Matrix
91 # The model of the win possibility is 1/(1 + 10^(-d/400)).
92 # The equation in this class is 1/(1 + e^(-Kd)).
93 # So, K should be calculated like this.
94 K = Math.log(10.0) / 400.0
96 # Convergence limit to stop Newton method.
98 # Stop Newton method after this iterations.
101 # Average rate among the players
110 # Calcurates the average of the vector.
112 def Rating.average(vector, mean=0.0)
113 sum = Array(vector).inject(0.0) {|sum, n| sum + n}
114 vector -= GSL::Vector[*Array.new(vector.size, sum/vector.size - mean)]
121 def initialize(win_loss_matrix)
134 attr_reader :rate, :n
138 (0...@size).collect {|k| yield k}
143 (0...@size).each {|k| yield k}
147 # The possibility that the player k will beet the player i.
150 1.0/(1.0 + exp(@rate[i]-@rate[k]))
154 # Most possible equation
161 sum += @n[k,i] * win_rate(i,k) - @n[i,k] * win_rate(k,i)
168 # / f0/R0 f0/R1 f0/R2 ... \
169 # dfk/dRj = | f1/R0 f1/R1 f1/R2 ... |
170 # \ f2/R0 f2/R1 f2/R2 ... /
176 sum += win_rate(i,k) * win_rate(k,i) * (@n[k,i] + @n[i,k])
180 sum = 2.0 * win_rate(j,k) * win_rate(k,j) * (@n[k,j] + @n[j,k])
186 # Jacobi matrix of the func().
192 (0...@size).collect do |k|
193 (0...@size).collect do |j|
201 # The initial value of the rate, which is of very importance for Newton method.
202 # This is based on my huristics; the higher the win probablity of a player is,
203 # the greater points he takes.
208 v = GSL::Vector[0, 0]
211 v += GSL::Vector[@n[k,i], @n[i,k]]
213 v.nrm2 < 1 ? 0 : v[0] / (v[0] + v[1])
215 rank = possibility.sort_index
216 @rate = player_vector do |k|
217 K*500 * (rank[k]+1) / @size
223 # Resets @rate as the higher the current win probablity of a player is,
224 # the greater points he takes.
227 @rate = @record.get || @rate
228 rank = @rate.sort_index
229 @rate = player_vector do |k|
230 K*@count*1.5 * (rank[k]+1) / @size
235 # mu is the deaccelrating parameter in Deaccelerated Newton method
236 def deaccelrate(mu, old_rate, a, old_f_nrm2)
237 @rate = old_rate - a * mu
238 if func_vector.nrm2 < (1 - mu / 4.0 ) * old_f_nrm2 then
242 @record.set(func_vector.nrm2, @rate)
246 $stderr.puts "mu: %f " % [mu] if $DEBUG
247 deaccelrate(mu*0.5, old_rate, a, old_f_nrm2)
251 # Main process to calculate ratings.
254 # Counter to stop the process.
255 # Calulation in Newton method may fall in an infinite loop
260 # Solve the equation:
262 # @rate_(n+1) = @rate_(n) - a
264 # f.nrm2 should approach to zero.
268 # $stderr.puts "j: %s" % [j.inspect] if $DEBUG
269 $stderr.puts "f: %s -> %f" % [f.to_a.inspect, f.nrm2] if $DEBUG
271 # GSL::Linalg::LU.solve or GSL::Linalg::HH.solve would be available instead.
272 a = GSL::Linalg::SV.solve(j, f)
273 a = self.class.average(a)
274 # $stderr.puts "a: %s -> %f" % [a.to_a.inspect, a.nrm2] if $DEBUG
276 # Deaccelerated Newton method
277 # GSL::Vector object should be immutable.
280 old_f_nrm2 = old_f.nrm2
281 deaccelrate(1.0, old_rate, a, old_f_nrm2)
282 @record.set(func_vector.nrm2, @rate)
284 $stderr.printf "|error| : %5.2e\n", a.nrm2 if $DEBUG
287 if @count > COUNT_MAX
288 $stderr.puts "Values seem to oscillate. Stopped the process."
289 $stderr.puts "f: %s -> %f" % [func_vector.to_a.inspect, func_vector.nrm2]
293 end while (a.nrm2 > ERROR_LIMIT * @rate.nrm2)
296 $stderr.puts "resolved f: %s -> %f" %
297 [func_vector.to_a.inspect, func_vector.nrm2] if $DEBUG
305 # Make the values of @rate finite.
308 @rate = @rate.collect do |a|
310 a.infinite? * AVERAGE_RATE * 100
318 # Flatten the values of @rate.
320 def average!(mean=0.0)
321 @rate = self.class.average(@rate, mean)
325 # Make the values of @rate integer.
328 @rate = @rate.collect do |a|
334 a.infinite? * AVERAGE_RATE * 100
342 #################################################
346 def mk_win_loss_matrix(players)
347 keys = players.keys.sort.reject do |k|
348 players[k].values.inject(0) {|sum, v| sum + v[0] + v[1]} < $GAMES_LIMIT
355 ((0...size).collect do |k|
356 ((0...size).collect do |j|
360 v = players[keys[k]][keys[j]]
369 def _add_win_loss(winner, loser)
370 $players[winner] ||= Hash.new { GSL::Vector[0,0] }
371 $players[loser] ||= Hash.new { GSL::Vector[0,0] }
372 $players[winner][loser] += GSL::Vector[1,0]
373 $players[loser][winner] += GSL::Vector[0,1]
376 def _add_time(player, time)
377 $players_time[player] = time if $players_time[player] < time
380 def add(black_mark, black_name, white_name, white_mark, time)
381 if black_mark == WIN_MARK && white_mark == LOSS_MARK
382 _add_win_loss(black_name, white_name)
383 elsif black_mark == LOSS_MARK && white_mark == WIN_MARK
384 _add_win_loss(white_name, black_name)
386 raise "Never reached!"
388 _add_time(black_name, time)
389 _add_time(white_name, time)
393 id.gsub(/@.*?\+/,"+")
397 str = File.open(file).read
399 if /^N\+(.*)$/ =~ str then black_name = $1.strip end
400 if /^N\-(.*)$/ =~ str then white_name = $1.strip end
402 if /^'summary:(.*)$/ =~ str
403 dummy, p1, p2 = $1.split(":").map {|a| a.strip}
404 p1_name, p1_mark = p1.split(" ")
405 p2_name, p2_mark = p2.split(" ")
406 if p1_name == black_name
407 black_name, black_mark = p1_name, p1_mark
408 white_name, white_mark = p2_name, p2_mark
409 elsif p2_name == black_name
410 black_name, black_mark = p2_name, p2_mark
411 white_name, white_mark = p1_name, p1_mark
413 raise "Never reach!: #{black} #{white} #{p1} #{p2}"
416 if /^'\$END_TIME:(.*)$/ =~ str
417 time = Time.parse($1.strip)
419 if /^'rating:(.*)$/ =~ str
420 black_id, white_id = $1.split(":").map {|a| a.strip}
421 add(black_mark, identify_id(black_id),
422 identify_id(white_id), white_mark, time)
428 USAGE: #{$0} dir [...]
435 while dir = ARGV.shift do
436 Dir.glob( File.join(dir, "**", "*.csa") ) {|f| grep(f)}
439 win_loss_matrix, keys = mk_win_loss_matrix($players)
440 $stderr.puts keys.inspect if $DEBUG
441 $stderr.puts win_loss_matrix.inspect if $DEBUG
442 rating = Rating.new(win_loss_matrix)
444 rating.average!(Rating::AVERAGE_RATE)
448 keys.each_with_index do |p, i| # player_id, index#
449 win_loss = $players[p].values.inject(GSL::Vector[0,0]) {|sum, v| sum + v}
450 win = win_loss_matrix
452 { 'name' => p.split("+")[0],
453 'rate' => rating.rate[i],
454 'last_modified' => $players_time[p].dup,
455 'win' => win_loss[0],
456 'loss' => win_loss[1]}
465 # vim: ts=2 sw=2 sts=0