4 ## Copyright (C) 2006-2008 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
26 # $ ./mk_rate . && ./mk_rate . > players.yaml
28 # The conditions that games and players are rated as following:
29 # * Rated games, which were played by both rated players.
30 # * Rated players, who logged in the server with a name followed by a trip:
32 # * (Rated) players, who played more than $GAMES_LIMIT [15] (rated) games.
38 # Sample Commands to isntall prerequires will work for Debian.
41 # $ sudo aptitude install rubygems
43 # * Ruby bindings for the GNU Scientific Library (GSL)
44 # $ sudo aptitude install libgsl-ruby1.8
45 # Or, download it from http://rb-gsl.rubyforge.org/ .
47 # * RGL: Ruby Graph Library
48 # $ sudo gem install rgl
49 # Or, download it from http://rubyforge.org/projects/rgl/ .
56 require 'rgl/adjacency'
57 require 'rgl/connected_components'
59 #################################################
63 # Count out players who play less games than $GAMES_LIMIT
64 $GAMES_LIMIT = $DEBUG ? 0 : 15
71 # Holds the last time when a player gamed
72 $players_time = Hash.new { Time.at(0) }
75 #################################################
76 # Keeps the value of the lowest key
84 if @lowest.empty? || key < @lowest[0]
85 @lowest = [key, value]
98 #################################################
99 # Calculates rates of every player from a Win Loss GSL::Matrix
104 # The model of the win possibility is 1/(1 + 10^(-d/400)).
105 # The equation in this class is 1/(1 + e^(-Kd)).
106 # So, K should be calculated like this.
107 K = Math.log(10.0) / 400.0
109 # Convergence limit to stop Newton method.
111 # Stop Newton method after this iterations.
114 # Average rate among the players
123 # Calcurates the average of the vector.
125 def Rating.average(vector, mean=0.0)
126 sum = Array(vector).inject(0.0) {|sum, n| sum + n}
127 vector -= GSL::Vector[*Array.new(vector.size, sum/vector.size - mean)]
134 def initialize(win_loss_matrix)
138 when GSL::Matrix, GSL::Matrix::Int
147 attr_reader :rate, :n
151 (0...@size).collect {|k| yield k}
156 (0...@size).each {|k| yield k}
160 # The possibility that the player k will beet the player i.
163 1.0/(1.0 + exp(@rate[i]-@rate[k]))
167 # Most possible equation
174 sum += @n[k,i] * win_rate(i,k) - @n[i,k] * win_rate(k,i)
181 # / f0/R0 f0/R1 f0/R2 ... \
182 # dfk/dRj = | f1/R0 f1/R1 f1/R2 ... |
183 # \ f2/R0 f2/R1 f2/R2 ... /
189 sum += win_rate(i,k) * win_rate(k,i) * (@n[k,i] + @n[i,k])
193 sum = 2.0 * win_rate(j,k) * win_rate(k,j) * (@n[k,j] + @n[j,k])
199 # Jacobi matrix of the func().
205 (0...@size).collect do |k|
206 (0...@size).collect do |j|
214 # The initial value of the rate, which is of very importance for Newton
215 # method. This is based on my huristics; the higher the win probablity of
216 # a player is, the greater points he takes.
221 v = GSL::Vector[0, 0]
224 v += GSL::Vector[@n[k,i], @n[i,k]]
226 v.nrm2 < 1 ? 0 : v[0] / (v[0] + v[1])
228 rank = possibility.sort_index
229 @rate = player_vector do |k|
230 K*500 * (rank[k]+1) / @size
236 # Resets @rate as the higher the current win probablity of a player is,
237 # the greater points he takes.
240 @rate = @record.get || @rate
241 rank = @rate.sort_index
242 @rate = player_vector do |k|
243 K*@count*1.5 * (rank[k]+1) / @size
248 # mu is the deaccelrating parameter in Deaccelerated Newton method
249 def deaccelrate(mu, old_rate, a, old_f_nrm2)
250 @rate = old_rate - a * mu
251 if func_vector.nrm2 < (1 - mu / 4.0 ) * old_f_nrm2 then
255 @record.set(func_vector.nrm2, @rate)
259 $stderr.puts "mu: %f " % [mu] if $DEBUG
260 deaccelrate(mu*0.5, old_rate, a, old_f_nrm2)
264 # Main process to calculate ratings.
267 # Counter to stop the process.
268 # Calulation in Newton method may fall in an infinite loop
273 # Solve the equation:
275 # @rate_(n+1) = @rate_(n) - a
277 # f.nrm2 should approach to zero.
281 # $stderr.puts "j: %s" % [j.inspect] if $DEBUG
282 $stderr.puts "f: %s -> %f" % [f.to_a.inspect, f.nrm2] if $DEBUG
284 # GSL::Linalg::LU.solve or GSL::Linalg::HH.solve would be available instead.
285 a = GSL::Linalg::SV.solve(j, f)
286 a = self.class.average(a)
287 # $stderr.puts "a: %s -> %f" % [a.to_a.inspect, a.nrm2] if $DEBUG
289 # Deaccelerated Newton method
290 # GSL::Vector object should be immutable.
293 old_f_nrm2 = old_f.nrm2
294 deaccelrate(1.0, old_rate, a, old_f_nrm2)
295 @record.set(func_vector.nrm2, @rate)
297 $stderr.printf "|error| : %5.2e\n", a.nrm2 if $DEBUG
300 if @count > COUNT_MAX
301 $stderr.puts "Values seem to oscillate. Stopped the process."
302 $stderr.puts "f: %s -> %f" % [func_vector.to_a.inspect, func_vector.nrm2]
306 end while (a.nrm2 > ERROR_LIMIT * @rate.nrm2)
309 $stderr.puts "resolved f: %s -> %f" %
310 [func_vector.to_a.inspect, func_vector.nrm2] if $DEBUG
318 # Make the values of @rate finite.
321 @rate = @rate.collect do |a|
323 a.infinite? * AVERAGE_RATE * 100
331 # Flatten the values of @rate.
333 def average!(mean=0.0)
334 @rate = self.class.average(@rate, mean)
338 # Make the values of @rate integer.
341 @rate = @rate.collect do |a|
347 a.infinite? * AVERAGE_RATE * 100
353 #################################################
354 # Encapsulate a pair of keys and win loss matrix.
355 # - keys is an array of player IDs; [gps+123, foo+234, ...]
356 # - matrix holds games # where player i (row index) beats player j (column index).
357 # The row and column indexes match with the keys.
359 # This object should be immutable. If an internal state is being modified, a
360 # new object is always returned.
368 def self.mk_matrix(players)
369 keys = players.keys.sort
373 ((0...size).collect do |k|
375 p1_hash = players[p1]
376 ((0...size).collect do |j|
381 v = p1_hash[p2] || Vector[0,0]
386 return WinLossMatrix.new(keys, matrix)
389 def self.mk_win_loss_matrix(players)
390 obj = mk_matrix(players)
398 # an array of player IDs; [gps+123, foo+234, ...]
401 # matrix holds games # where player i (row index) beats player j (column index).
402 # The row and column indexes match with the keys.
405 def initialize(keys, matrix)
411 # Returns the size of the keys/matrix
422 # Removes a delete_index'th player and returns a new object.
424 def delete_row(delete_index)
426 (0...size).each do |i|
427 next if i == delete_index
428 row = @matrix.row(i).clone
429 row.delete_at(delete_index)
432 if copied_cols.size == 0
433 new_matrix = GSL::Matrix.new
435 new_matrix = GSL::Matrix[*copied_cols]
437 new_keys = @keys.clone
438 new_keys.delete_at(delete_index)
439 return WinLossMatrix.new(new_keys, new_matrix)
443 # Removes players in a rows; [1,3,5]
445 def delete_rows(rows)
447 rows.sort.reverse.each do |index|
448 obj = obj.delete_row(index)
454 # Removes players who do not pass a criteria to be rated, and returns a
458 $stderr.puts @keys.inspect if $DEBUG
459 $stderr.puts @matrix.inspect if $DEBUG
461 (0...size).each do |i|
466 if win < 1 || loss < 1 || win + loss < $GAMES_LIMIT
471 # The recursion ends if there is nothing to delete
472 return self if delete.empty?
474 new_obj = delete_rows(delete)
479 # Cuts self into connecting groups such as each player in a group has at least
480 # one game with other players in the group. Returns them as an array.
482 def connected_subsets
483 g = RGL::AdjacencyGraph.new
484 (0...size).each do |k|
485 (0...size).each do |i|
494 g.each_connected_component do |c|
497 new_keys << keys[v.to_s.to_i]
502 subsets = subsets.sort {|a,b| b.size <=> a.size}
504 result = subsets.collect do |keys|
507 ((0...keys.size).collect do |k|
508 p1 = @keys.index(keys[k])
509 ((0...keys.size).collect do |j|
513 p2 = @keys.index(keys[j])
518 WinLossMatrix.new(keys, matrix)
525 "size : #{@keys.size}" + "\n" +
526 @keys.inspect + "\n" +
533 #################################################
538 # After NHAFE_LIFE days value will get half.
539 # 0.693 is constant, where exp(0.693) ~ 0.5
545 Math::exp(-0.693/NHALF_LIFE*(days-7))
549 def _add_win_loss(winner, loser, time)
550 how_long_days = (Time.now - time)/(3600*24)
551 $players[winner] ||= Hash.new { GSL::Vector[0,0] }
552 $players[loser] ||= Hash.new { GSL::Vector[0,0] }
553 $players[winner][loser] += GSL::Vector[1.0*half_life(how_long_days),0]
554 $players[loser][winner] += GSL::Vector[0,1.0*half_life(how_long_days)]
557 def _add_time(player, time)
558 $players_time[player] = time if $players_time[player] < time
561 def add(black_mark, black_name, white_name, white_mark, time)
562 if black_mark == WIN_MARK && white_mark == LOSS_MARK
563 _add_win_loss(black_name, white_name, time)
564 elsif black_mark == LOSS_MARK && white_mark == WIN_MARK
565 _add_win_loss(white_name, black_name, time)
566 elsif black_mark == DRAW_MARK && white_mark == DRAW_MARK
569 raise "Never reached!"
571 _add_time(black_name, time)
572 _add_time(white_name, time)
576 if /@NORATE\+/ =~ id # the player having @NORATE in the name should not be rated
579 id.gsub(/@.*?\+/,"+")
583 str = File.open(file).read
585 if /^N\+(.*)$/ =~ str then black_name = $1.strip end
586 if /^N\-(.*)$/ =~ str then white_name = $1.strip end
588 if /^'summary:(.*)$/ =~ str
589 state, p1, p2 = $1.split(":").map {|a| a.strip}
590 return if state == "abnormal"
591 p1_name, p1_mark = p1.split(" ")
592 p2_name, p2_mark = p2.split(" ")
593 if p1_name == black_name
594 black_name, black_mark = p1_name, p1_mark
595 white_name, white_mark = p2_name, p2_mark
596 elsif p2_name == black_name
597 black_name, black_mark = p2_name, p2_mark
598 white_name, white_mark = p1_name, p1_mark
600 raise "Never reach!: #{black} #{white} #{p3} #{p2}"
603 if /^'\$END_TIME:(.*)$/ =~ str
604 time = Time.parse($1.strip)
606 if /^'rating:(.*)$/ =~ str
607 black_id, white_id = $1.split(":").map {|a| a.strip}
608 black_id = identify_id(black_id)
609 white_id = identify_id(white_id)
610 if black_id && white_id && (black_id != white_id)
611 add(black_mark, black_id, white_id, white_mark, time)
618 USAGE: #{$0} dir [...]
624 yaml["players"].each do |group_key, group|
625 group.each do |player_key, player|
626 rate = player['rate']
628 if rate > 10000 || rate < -10000
638 while dir = ARGV.shift do
639 Dir.glob( File.join(dir, "**", "*.csa") ) {|f| grep(f)}
646 obj = WinLossMatrix::mk_win_loss_matrix($players)
647 obj.connected_subsets.each do |win_loss_matrix|
648 yaml["players"][rating_group] = {}
650 rating = Rating.new(win_loss_matrix.matrix)
652 rating.average!(Rating::AVERAGE_RATE)
655 win_loss_matrix.keys.each_with_index do |p, i| # player_id, index#
656 win = win_loss_matrix.matrix.row(i).sum
657 loss = win_loss_matrix.matrix.col(i).sum
659 yaml["players"][rating_group][p] =
660 { 'name' => p.split("+")[0],
661 'rating_group' => rating_group,
662 'rate' => rating.rate[i],
663 'last_modified' => $players_time[p].dup,
671 non_rated_group = 999 # large enough
672 yaml["players"][non_rated_group] = {}
673 $players.each_key do |id|
674 # skip players who have already been rated
676 (0..rating_group).each do |i|
677 found = true if yaml["players"][i][id]
682 v = GSL::Vector[0, 0]
683 $players[id].each_value {|value| v += value}
684 next if v[0] < 1 && v[1] < 1
686 yaml["players"][non_rated_group][id] =
687 { 'name' => id.split("+")[0],
688 'rating_group' => non_rated_group,
690 'last_modified' => $players_time[id].dup,
694 unless validate(yaml)
695 $stderr.puts "Aborted. It did not result in valid ratings."
705 # vim: ts=2 sw=2 sts=0