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/ .
57 require 'rgl/adjacency'
58 require 'rgl/connected_components'
60 #################################################
64 # Count out players who play less games than $GAMES_LIMIT
65 $GAMES_LIMIT = $DEBUG ? 0 : 15
72 # Holds the last time when a player gamed
73 $players_time = Hash.new { Time.at(0) }
76 #################################################
77 # Keeps the value of the lowest key
85 if @lowest.empty? || key < @lowest[0]
86 @lowest = [key, value]
99 #################################################
100 # Calculates rates of every player from a Win Loss GSL::Matrix
105 # The model of the win possibility is 1/(1 + 10^(-d/400)).
106 # The equation in this class is 1/(1 + e^(-Kd)).
107 # So, K should be calculated like this.
108 K = Math.log(10.0) / 400.0
110 # Convergence limit to stop Newton method.
112 # Stop Newton method after this iterations.
115 # Average rate among the players
124 # Calcurates the average of the vector.
126 def Rating.average(vector, mean=0.0)
127 sum = Array(vector).inject(0.0) {|sum, n| sum + n}
128 vector -= GSL::Vector[*Array.new(vector.size, sum/vector.size - mean)]
135 def initialize(win_loss_matrix)
139 when GSL::Matrix, GSL::Matrix::Int
148 attr_reader :rate, :n
152 (0...@size).collect {|k| yield k}
157 (0...@size).each {|k| yield k}
161 # The possibility that the player k will beet the player i.
164 1.0/(1.0 + exp(@rate[i]-@rate[k]))
168 # Most possible equation
175 sum += @n[k,i] * win_rate(i,k) - @n[i,k] * win_rate(k,i)
182 # / f0/R0 f0/R1 f0/R2 ... \
183 # dfk/dRj = | f1/R0 f1/R1 f1/R2 ... |
184 # \ f2/R0 f2/R1 f2/R2 ... /
190 sum += win_rate(i,k) * win_rate(k,i) * (@n[k,i] + @n[i,k])
194 sum = 2.0 * win_rate(j,k) * win_rate(k,j) * (@n[k,j] + @n[j,k])
200 # Jacobi matrix of the func().
206 (0...@size).collect do |k|
207 (0...@size).collect do |j|
215 # The initial value of the rate, which is of very importance for Newton
216 # method. This is based on my huristics; the higher the win probablity of
217 # a player is, the greater points he takes.
222 v = GSL::Vector[0, 0]
225 v += GSL::Vector[@n[k,i], @n[i,k]]
227 v.nrm2 < 1 ? 0 : v[0] / (v[0] + v[1])
229 rank = possibility.sort_index
230 @rate = player_vector do |k|
231 K*500 * (rank[k]+1) / @size
237 # Resets @rate as the higher the current win probablity of a player is,
238 # the greater points he takes.
241 @rate = @record.get || @rate
242 rank = @rate.sort_index
243 @rate = player_vector do |k|
244 K*@count*1.5 * (rank[k]+1) / @size
249 # mu is the deaccelrating parameter in Deaccelerated Newton method
250 def deaccelrate(mu, old_rate, a, old_f_nrm2)
251 @rate = old_rate - a * mu
252 if func_vector.nrm2 < (1 - mu / 4.0 ) * old_f_nrm2 then
256 @record.set(func_vector.nrm2, @rate)
260 $stderr.puts "mu: %f " % [mu] if $DEBUG
261 deaccelrate(mu*0.5, old_rate, a, old_f_nrm2)
265 # Main process to calculate ratings.
268 # Counter to stop the process.
269 # Calulation in Newton method may fall in an infinite loop
274 # Solve the equation:
276 # @rate_(n+1) = @rate_(n) - a
278 # f.nrm2 should approach to zero.
282 # $stderr.puts "j: %s" % [j.inspect] if $DEBUG
283 $stderr.puts "f: %s -> %f" % [f.to_a.inspect, f.nrm2] if $DEBUG
285 # GSL::Linalg::LU.solve or GSL::Linalg::HH.solve would be available instead.
286 #a = GSL::Linalg::HH.solve(j, f)
287 a, = GSL::MultiFit::linear(j, f)
288 a = self.class.average(a)
289 # $stderr.puts "a: %s -> %f" % [a.to_a.inspect, a.nrm2] if $DEBUG
291 # Deaccelerated Newton method
292 # GSL::Vector object should be immutable.
295 old_f_nrm2 = old_f.nrm2
296 deaccelrate(1.0, old_rate, a, old_f_nrm2)
297 @record.set(func_vector.nrm2, @rate)
299 $stderr.printf "|error| : %5.2e\n", a.nrm2 if $DEBUG
302 if @count > COUNT_MAX
303 $stderr.puts "Values seem to oscillate. Stopped the process."
304 $stderr.puts "f: %s -> %f" % [func_vector.to_a.inspect, func_vector.nrm2]
308 end while (a.nrm2 > ERROR_LIMIT * @rate.nrm2)
311 $stderr.puts "resolved f: %s -> %f" %
312 [func_vector.to_a.inspect, func_vector.nrm2] if $DEBUG
320 # Make the values of @rate finite.
323 @rate = @rate.collect do |a|
325 a.infinite? * AVERAGE_RATE * 100
333 # Flatten the values of @rate.
335 def average!(mean=0.0)
336 @rate = self.class.average(@rate, mean)
342 def translate!(value)
347 # Make the values of @rate integer.
350 @rate = @rate.collect do |a|
356 a.infinite? * AVERAGE_RATE * 100
362 #################################################
363 # Encapsulate a pair of keys and win loss matrix.
364 # - keys is an array of player IDs; [gps+123, foo+234, ...]
365 # - matrix holds games # where player i (row index) beats player j (column index).
366 # The row and column indexes match with the keys.
368 # This object should be immutable. If an internal state is being modified, a
369 # new object is always returned.
377 def self.mk_matrix(players)
378 keys = players.keys.sort
382 ((0...size).collect do |k|
384 p1_hash = players[p1]
385 ((0...size).collect do |j|
390 v = p1_hash[p2] || Vector[0,0]
395 return WinLossMatrix.new(keys, matrix)
398 def self.mk_win_loss_matrix(players)
399 obj = mk_matrix(players)
407 # an array of player IDs; [gps+123, foo+234, ...]
410 # matrix holds games # where player i (row index) beats player j (column index).
411 # The row and column indexes match with the keys.
414 def initialize(keys, matrix)
420 # Returns the size of the keys/matrix
431 # Removes a delete_index'th player and returns a new object.
433 def delete_row(delete_index)
435 (0...size).each do |i|
436 next if i == delete_index
437 row = @matrix.row(i).clone
438 row.delete_at(delete_index)
441 if copied_cols.size == 0
442 new_matrix = GSL::Matrix.new
444 new_matrix = GSL::Matrix[*copied_cols]
446 new_keys = @keys.clone
447 new_keys.delete_at(delete_index)
448 return WinLossMatrix.new(new_keys, new_matrix)
452 # Removes players in a rows; [1,3,5]
454 def delete_rows(rows)
456 rows.sort.reverse.each do |index|
457 obj = obj.delete_row(index)
463 # Removes players who do not pass a criteria to be rated, and returns a
467 $stderr.puts @keys.inspect if $DEBUG
468 $stderr.puts @matrix.inspect if $DEBUG
470 (0...size).each do |i|
475 if win < 1 || loss < 1 || win + loss < $GAMES_LIMIT
480 # The recursion ends if there is nothing to delete
481 return self if delete.empty?
483 new_obj = delete_rows(delete)
488 # Cuts self into connecting groups such as each player in a group has at least
489 # one game with other players in the group. Returns them as an array.
491 def connected_subsets
492 g = RGL::AdjacencyGraph.new
493 (0...size).each do |k|
494 (0...size).each do |i|
503 g.each_connected_component do |c|
506 new_keys << keys[v.to_s.to_i]
511 subsets = subsets.sort {|a,b| b.size <=> a.size}
513 result = subsets.collect do |keys|
516 ((0...keys.size).collect do |k|
517 p1 = @keys.index(keys[k])
518 ((0...keys.size).collect do |j|
522 p2 = @keys.index(keys[j])
527 WinLossMatrix.new(keys, matrix)
534 "size : #{@keys.size}" + "\n" +
535 @keys.inspect + "\n" +
542 #################################################
547 # After NHAFE_LIFE days value will get half.
548 # 0.693 is constant, where exp(0.693) ~ 0.5
550 if days < $options["half-life-ignore"]
553 Math::exp(-0.693/$options["half-life"]*(days-$options["half-life-ignore"]))
557 def _add_win_loss(winner, loser, time)
558 how_long_days = (Time.now - time)/(3600*24)
559 $players[winner] ||= Hash.new { GSL::Vector[0,0] }
560 $players[loser] ||= Hash.new { GSL::Vector[0,0] }
561 $players[winner][loser] += GSL::Vector[1.0*half_life(how_long_days),0]
562 $players[loser][winner] += GSL::Vector[0,1.0*half_life(how_long_days)]
565 def _add_time(player, time)
566 $players_time[player] = time if $players_time[player] < time
569 def add(black_mark, black_name, white_name, white_mark, time)
570 if black_mark == WIN_MARK && white_mark == LOSS_MARK
571 _add_win_loss(black_name, white_name, time)
572 elsif black_mark == LOSS_MARK && white_mark == WIN_MARK
573 _add_win_loss(white_name, black_name, time)
574 elsif black_mark == DRAW_MARK && white_mark == DRAW_MARK
577 raise "Never reached!"
579 _add_time(black_name, time)
580 _add_time(white_name, time)
584 if /@NORATE\+/ =~ id # the player having @NORATE in the name should not be rated
587 id.gsub(/@.*?\+/,"+")
591 str = File.open(file).read
593 if /^N\+(.*)$/ =~ str then black_name = $1.strip end
594 if /^N\-(.*)$/ =~ str then white_name = $1.strip end
596 if /^'summary:(.*)$/ =~ str
597 state, p1, p2 = $1.split(":").map {|a| a.strip}
598 return if state == "abnormal"
599 p1_name, p1_mark = p1.split(" ")
600 p2_name, p2_mark = p2.split(" ")
601 if p1_name == black_name
602 black_name, black_mark = p1_name, p1_mark
603 white_name, white_mark = p2_name, p2_mark
604 elsif p2_name == black_name
605 black_name, black_mark = p2_name, p2_mark
606 white_name, white_mark = p1_name, p1_mark
608 raise "Never reach!: #{black} #{white} #{p3} #{p2}"
611 if /^'\$END_TIME:(.*)$/ =~ str
612 time = Time.parse($1.strip)
614 if /^'rating:(.*)$/ =~ str
615 black_id, white_id = $1.split(":").map {|a| a.strip}
616 black_id = identify_id(black_id)
617 white_id = identify_id(white_id)
618 if black_id && white_id && (black_id != white_id)
619 add(black_mark, black_id, white_id, white_mark, time)
626 USAGE: #{$0} dir [...]
632 yaml["players"].each do |group_key, group|
633 group.each do |player_key, player|
634 rate = player['rate']
636 if rate > 10000 || rate < -10000
646 USAGE: #{$0} [options] DIR..
647 DIR where CSA files are looked up recursively
649 --half-life n [days] (default 60)
650 --half-life-ignore m [days] (default 7)
651 after m days, half-life effect works
652 --fixed-rate-player player whose rate is fixed at the rate
654 --help show this message
660 parser = GetoptLong.new(
661 ["--half-life", GetoptLong::REQUIRED_ARGUMENT],
662 ["--half-life-ignore", GetoptLong::REQUIRED_ARGUMENT],
663 ["--help", "-h", GetoptLong::NO_ARGUMENT],
664 ["--fixed-rate-player", GetoptLong::REQUIRED_ARGUMENT],
665 ["--fixed-rate", GetoptLong::REQUIRED_ARGUMENT])
668 parser.each_option do |name, arg|
670 $options[name] = arg.dup
672 if ( $options["fixed-rate-player"] && !$options["fixed-rate"]) ||
673 (!$options["fixed-rate-player"] && $options["fixed-rate"]) ||
674 ( $options["fixed-rate-player"] && $options["fixed-rate"].to_i <= 0)
680 raise parser.error_message
686 $options["half-life"] ||= 60
687 $options["half-life"] = $options["half-life"].to_i
688 $options["half-life-ignore"] ||= 7
689 $options["half-life-ignore"] = $options["half-life-ignore"].to_i
690 $options["fixed-rate"] = $options["fixed-rate"].to_i if $options["fixed-rate"]
692 while dir = ARGV.shift do
693 Dir.glob( File.join(dir, "**", "*.csa") ) {|f| grep(f)}
700 obj = WinLossMatrix::mk_win_loss_matrix($players)
701 obj.connected_subsets.each do |win_loss_matrix|
702 yaml["players"][rating_group] = {}
704 rating = Rating.new(win_loss_matrix.matrix)
706 rating.average!(Rating::AVERAGE_RATE)
709 if $options["fixed-rate-player"]
710 # first, try exact match
711 index = win_loss_matrix.keys.index($options["fixed-rate-player"])
712 # second, try regular match
714 win_loss_matrix.keys.each_with_index do |p, i|
715 if %r!#{$options["fixed-rate-player"]}! =~ p
721 the_rate = rating.rate[index]
722 rating.translate!($options["fixed-rate"] - the_rate)
726 win_loss_matrix.keys.each_with_index do |p, i| # player_id, index#
727 win = win_loss_matrix.matrix.row(i).sum
728 loss = win_loss_matrix.matrix.col(i).sum
730 yaml["players"][rating_group][p] =
731 { 'name' => p.split("+")[0],
732 'rating_group' => rating_group,
733 'rate' => rating.rate[i],
734 'last_modified' => $players_time[p].dup,
742 non_rated_group = 999 # large enough
743 yaml["players"][non_rated_group] = {}
744 $players.each_key do |id|
745 # skip players who have already been rated
747 (0..rating_group).each do |i|
748 found = true if yaml["players"][i][id]
753 v = GSL::Vector[0, 0]
754 $players[id].each_value {|value| v += value}
755 next if v[0] < 1 && v[1] < 1
757 yaml["players"][non_rated_group][id] =
758 { 'name' => id.split("+")[0],
759 'rating_group' => non_rated_group,
761 'last_modified' => $players_time[id].dup,
765 unless validate(yaml)
766 $stderr.puts "Aborted. It did not result in valid ratings."
767 $stderr.puts yaml.to_yaml if $DEBUG
777 # vim: ts=2 sw=2 sts=0