2 # $Id: mk_rate 316 2008-12-28 15:10:10Z beatles $
4 # Author:: Daigo Moriwaki
5 # Homepage:: http://sourceforge.jp/projects/shogi-server/
8 # Copyright (C) 2006-2008 Daigo Moriwaki <daigo at debian dot org>
10 # This program is free software; you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 2 of the License, or
13 # (at your option) any later version.
15 # This program is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 # GNU General Public License for more details.
20 # You should have received a copy of the GNU General Public License
21 # along with this program; if not, write to the Free Software
22 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
27 # mk_rate reads CSA files, calculates rating scores of each player, and then
28 # outputs a yaml file (players.yaml) that Shogi-server can recognize.
32 # ./mk_rate [options] DIR..
35 # CSA files are recursively looked up the directories.
38 # n [days] (default 60)
40 # --half-life-ignore::
41 # m [days] (default 7)
42 # after m days, the half-life effect works
45 # m [days] (default 365*2)
46 # old files will be ignored
48 # --fixed-rate-player::
49 # player whose rate is fixed at the rate
59 # Sample Command lines that isntall prerequires will work on Debian.
63 # $ sudo aptitude install ruby1.8
67 # $ sudo aptitude install rubygems
69 # * Ruby bindings for the GNU Scientific Library (GSL[http://rb-gsl.rubyforge.org/])
71 # $ sudo aptitude install libgsl-ruby1.8
73 # * RGL: {Ruby Graph Library}[http://rubyforge.org/projects/rgl/]
75 # $ sudo gem install rgl
79 # $ ./mk_rate . > players.yaml
81 # or, if you do not want the file to be update in case of errors,
83 # $ ./mk_rate . && ./mk_rate . > players.yaml
85 # == How players are rated
87 # The conditions that games and players are rated as following:
89 # * Rated games, which were played by both rated players.
90 # * Rated players, who logged in the server with a name followed by a trip: "name,trip".
91 # * (Rated) players, who played more than $GAMES_LIMIT [15] (rated) games.
99 require 'rgl/adjacency'
100 require 'rgl/connected_components'
102 #################################################
106 # Count out players who play less games than $GAMES_LIMIT
107 $GAMES_LIMIT = $DEBUG ? 0 : 15
114 # Holds the last time when a player gamed
115 $players_time = Hash.new { Time.at(0) }
118 #################################################
119 # Keeps the value of the lowest key
127 if @lowest.empty? || key < @lowest[0]
128 @lowest = [key, value]
141 #################################################
142 # Calculates rates of every player from a Win Loss GSL::Matrix
147 # The model of the win possibility is 1/(1 + 10^(-d/400)).
148 # The equation in this class is 1/(1 + e^(-Kd)).
149 # So, K should be calculated like this.
150 K = Math.log(10.0) / 400.0
152 # Convergence limit to stop Newton method.
154 # Stop Newton method after this iterations.
157 # Average rate among the players
166 # Calcurates the average of the vector.
168 def Rating.average(vector, mean=0.0)
169 sum = Array(vector).inject(0.0) {|sum, n| sum + n}
170 vector -= GSL::Vector[*Array.new(vector.size, sum/vector.size - mean)]
177 def initialize(win_loss_matrix)
181 when GSL::Matrix, GSL::Matrix::Int
190 attr_reader :rate, :n
194 (0...@size).collect {|k| yield k}
199 (0...@size).each {|k| yield k}
203 # The possibility that the player k will beet the player i.
206 1.0/(1.0 + exp(@rate[i]-@rate[k]))
210 # Most possible equation
217 sum += @n[k,i] * win_rate(i,k) - @n[i,k] * win_rate(k,i)
224 # / f0/R0 f0/R1 f0/R2 ... \
225 # dfk/dRj = | f1/R0 f1/R1 f1/R2 ... |
226 # \ f2/R0 f2/R1 f2/R2 ... /
232 sum += win_rate(i,k) * win_rate(k,i) * (@n[k,i] + @n[i,k])
236 sum = 2.0 * win_rate(j,k) * win_rate(k,j) * (@n[k,j] + @n[j,k])
242 # Jacobi matrix of the func().
248 (0...@size).collect do |k|
249 (0...@size).collect do |j|
257 # The initial value of the rate, which is of very importance for Newton
258 # method. This is based on my huristics; the higher the win probablity of
259 # a player is, the greater points he takes.
264 v = GSL::Vector[0, 0]
267 v += GSL::Vector[@n[k,i], @n[i,k]]
269 v.nrm2 < 1 ? 0 : v[0] / (v[0] + v[1])
271 rank = possibility.sort_index
272 @rate = player_vector do |k|
273 K*500 * (rank[k]+1) / @size
279 # Resets @rate as the higher the current win probablity of a player is,
280 # the greater points he takes.
283 @rate = @record.get || @rate
284 rank = @rate.sort_index
285 @rate = player_vector do |k|
286 K*@count*1.5 * (rank[k]+1) / @size
291 # mu is the deaccelrating parameter in Deaccelerated Newton method
292 def deaccelrate(mu, old_rate, a, old_f_nrm2)
293 @rate = old_rate - a * mu
294 if func_vector.nrm2 < (1 - mu / 4.0 ) * old_f_nrm2 then
298 @record.set(func_vector.nrm2, @rate)
302 $stderr.puts "mu: %f " % [mu] if $DEBUG
303 deaccelrate(mu*0.5, old_rate, a, old_f_nrm2)
307 # Main process to calculate ratings.
310 # Counter to stop the process.
311 # Calulation in Newton method may fall in an infinite loop
316 # Solve the equation:
318 # @rate_(n+1) = @rate_(n) - a
320 # f.nrm2 should approach to zero.
324 # $stderr.puts "j: %s" % [j.inspect] if $DEBUG
325 $stderr.puts "f: %s -> %f" % [f.to_a.inspect, f.nrm2] if $DEBUG
327 # GSL::Linalg::LU.solve or GSL::Linalg::HH.solve would be available instead.
328 #a = GSL::Linalg::HH.solve(j, f)
329 a, = GSL::MultiFit::linear(j, f)
330 a = self.class.average(a)
331 # $stderr.puts "a: %s -> %f" % [a.to_a.inspect, a.nrm2] if $DEBUG
333 # Deaccelerated Newton method
334 # GSL::Vector object should be immutable.
337 old_f_nrm2 = old_f.nrm2
338 deaccelrate(1.0, old_rate, a, old_f_nrm2)
339 @record.set(func_vector.nrm2, @rate)
341 $stderr.printf "|error| : %5.2e\n", a.nrm2 if $DEBUG
344 if @count > COUNT_MAX
345 $stderr.puts "Values seem to oscillate. Stopped the process."
346 $stderr.puts "f: %s -> %f" % [func_vector.to_a.inspect, func_vector.nrm2]
350 end while (a.nrm2 > ERROR_LIMIT * @rate.nrm2)
353 $stderr.puts "resolved f: %s -> %f" %
354 [func_vector.to_a.inspect, func_vector.nrm2] if $DEBUG
362 # Make the values of @rate finite.
365 @rate = @rate.collect do |a|
367 a.infinite? * AVERAGE_RATE * 100
375 # Flatten the values of @rate.
377 def average!(mean=0.0)
378 @rate = self.class.average(@rate, mean)
384 def translate!(value)
389 # Make the values of @rate integer.
392 @rate = @rate.collect do |a|
398 a.infinite? * AVERAGE_RATE * 100
404 #################################################
405 # Encapsulate a pair of keys and win loss matrix.
406 # - keys is an array of player IDs; [gps+123, foo+234, ...]
407 # - matrix holds games # where player i (row index) beats player j (column index).
408 # The row and column indexes match with the keys.
410 # This object should be immutable. If an internal state is being modified, a
411 # new object is always returned.
419 def self.mk_matrix(players)
420 keys = players.keys.sort
424 ((0...size).collect do |k|
426 p1_hash = players[p1]
427 ((0...size).collect do |j|
432 v = p1_hash[p2] || Vector[0,0]
437 return WinLossMatrix.new(keys, matrix)
440 def self.mk_win_loss_matrix(players)
441 obj = mk_matrix(players)
449 # an array of player IDs; [gps+123, foo+234, ...]
452 # matrix holds games # where player i (row index) beats player j (column index).
453 # The row and column indexes match with the keys.
456 def initialize(keys, matrix)
462 # Returns the size of the keys/matrix
473 # Removes players in a rows such as [1,3,5], and then returns a new
476 def delete_rows(rows)
477 rows = rows.sort.reverse
480 (0...size).each do |i|
481 next if rows.include?(i)
482 row = @matrix.row(i).clone
488 if copied_cols.size == 0
489 new_matrix = GSL::Matrix.new
491 new_matrix = GSL::Matrix[*copied_cols]
494 new_keys = @keys.clone
496 new_keys.delete_at(j)
499 return WinLossMatrix.new(new_keys, new_matrix)
503 # Removes players who do not pass a criteria to be rated, and returns a
507 $stderr.puts @keys.inspect if $DEBUG
508 $stderr.puts @matrix.inspect if $DEBUG
510 (0...size).each do |i|
515 if win < 1 || loss < 1 || win + loss < $GAMES_LIMIT
520 # The recursion ends if there is nothing to delete
521 return self if delete.empty?
523 new_obj = delete_rows(delete)
528 # Cuts self into connecting groups such as each player in a group has at least
529 # one game with other players in the group. Returns them as an array.
531 def connected_subsets
532 g = RGL::AdjacencyGraph.new
533 (0...size).each do |k|
534 (0...size).each do |i|
543 g.each_connected_component do |c|
546 new_keys << keys[v.to_s.to_i]
551 subsets = subsets.sort {|a,b| b.size <=> a.size}
553 result = subsets.collect do |keys|
556 ((0...keys.size).collect do |k|
557 p1 = @keys.index(keys[k])
558 ((0...keys.size).collect do |j|
562 p2 = @keys.index(keys[j])
563 @matrix[p1,p2] + 0.001
567 WinLossMatrix.new(keys, matrix)
574 "size : #{@keys.size}" + "\n" +
575 @keys.inspect + "\n" +
582 #################################################
587 # After NHAFE_LIFE days value will get half.
588 # 0.693 is constant, where exp(0.693) ~ 0.5
590 if days < $options["half-life-ignore"]
593 Math::exp(-0.693/$options["half-life"]*(days-$options["half-life-ignore"]))
597 def _add_win_loss(winner, loser, time)
598 how_long_days = (Time.now - time)/(3600*24)
599 $players[winner] ||= Hash.new { GSL::Vector[0,0] }
600 $players[loser] ||= Hash.new { GSL::Vector[0,0] }
601 $players[winner][loser] += GSL::Vector[1.0*half_life(how_long_days),0]
602 $players[loser][winner] += GSL::Vector[0,1.0*half_life(how_long_days)]
605 def _add_time(player, time)
606 $players_time[player] = time if $players_time[player] < time
609 def add(black_mark, black_name, white_name, white_mark, time)
610 how_long_days = (Time.now - time)/(3600*24)
611 if (how_long_days > $options["ignore"])
614 if black_mark == WIN_MARK && white_mark == LOSS_MARK
615 _add_win_loss(black_name, white_name, time)
616 elsif black_mark == LOSS_MARK && white_mark == WIN_MARK
617 _add_win_loss(white_name, black_name, time)
618 elsif black_mark == DRAW_MARK && white_mark == DRAW_MARK
621 raise "Never reached!"
623 _add_time(black_name, time)
624 _add_time(white_name, time)
628 if /@NORATE\+/ =~ id # the player having @NORATE in the name should not be rated
631 id.gsub(/@.*?\+/,"+")
635 if /^([^ ]+) ([^ ]+) ([^ ]+) ([^ ]+) ([0-9]+)$/ =~ str.strip then
636 add($1,$2,$3,$4,Time.at($5.to_i))
642 USAGE: #{$0} dir [...]
648 yaml["players"].each do |group_key, group|
649 group.each do |player_key, player|
650 rate = player['rate']
652 if rate > 10000 || rate < -10000
662 USAGE: #{$0} [options] DIR..
663 DIR where CSA files are looked up recursively
665 --half-life n [days] (default 60)
666 --half-life-ignore m [days] (default 7)
667 after m days, half-life effect works
668 --fixed-rate-player player whose rate is fixed at the rate
670 --help show this message
676 parser = GetoptLong.new(
677 ["--half-life", GetoptLong::REQUIRED_ARGUMENT],
678 ["--half-life-ignore", GetoptLong::REQUIRED_ARGUMENT],
679 ["--ignore", GetoptLong::REQUIRED_ARGUMENT],
680 ["--help", "-h", GetoptLong::NO_ARGUMENT],
681 ["--fixed-rate-player", GetoptLong::REQUIRED_ARGUMENT],
682 ["--fixed-rate", GetoptLong::REQUIRED_ARGUMENT])
685 parser.each_option do |name, arg|
687 $options[name] = arg.dup
689 if ( $options["fixed-rate-player"] && !$options["fixed-rate"]) ||
690 (!$options["fixed-rate-player"] && $options["fixed-rate"]) ||
691 ( $options["fixed-rate-player"] && $options["fixed-rate"].to_i <= 0)
697 raise parser.error_message
703 $options["half-life"] ||= 60
704 $options["half-life"] = $options["half-life"].to_i
705 $options["half-life-ignore"] ||= 7
706 $options["half-life-ignore"] = $options["half-life-ignore"].to_i
707 $options["ignore"] ||= 365*2
708 $options["ignore"] = $options["ignore"].to_i
709 $options["fixed-rate"] = $options["fixed-rate"].to_i if $options["fixed-rate"]
711 while line = $stdin.gets do
719 obj = WinLossMatrix::mk_win_loss_matrix($players)
720 obj.connected_subsets.each do |win_loss_matrix|
721 yaml["players"][rating_group] = {}
723 rating = Rating.new(win_loss_matrix.matrix)
725 rating.average!(Rating::AVERAGE_RATE)
728 if $options["fixed-rate-player"]
729 # first, try exact match
730 index = win_loss_matrix.keys.index($options["fixed-rate-player"])
731 # second, try regular match
733 win_loss_matrix.keys.each_with_index do |p, i|
734 if %r!#{$options["fixed-rate-player"]}! =~ p
740 the_rate = rating.rate[index]
741 rating.translate!($options["fixed-rate"] - the_rate)
745 win_loss_matrix.keys.each_with_index do |p, i| # player_id, index#
746 win = win_loss_matrix.matrix.row(i).sum
747 loss = win_loss_matrix.matrix.col(i).sum
749 yaml["players"][rating_group][p] =
750 { 'name' => p.split("+")[0],
751 'rating_group' => rating_group,
752 'rate' => rating.rate[i],
753 'last_modified' => $players_time[p].dup,
761 non_rated_group = 999 # large enough
762 yaml["players"][non_rated_group] = {}
763 $players.each_key do |id|
764 # skip players who have already been rated
766 (0..rating_group).each do |i|
767 found = true if yaml["players"][i][id]
772 v = GSL::Vector[0, 0]
773 $players[id].each_value {|value| v += value}
774 next if v[0] < 1 && v[1] < 1
776 yaml["players"][non_rated_group][id] =
777 { 'name' => id.split("+")[0],
778 'rating_group' => non_rated_group,
780 'last_modified' => $players_time[id].dup,
784 unless validate(yaml)
785 $stderr.puts "Aborted. It did not result in valid ratings."
786 $stderr.puts yaml.to_yaml if $DEBUG
796 # vim: ts=2 sw=2 sts=0