4 # Author:: Daigo Moriwaki
5 # Homepage:: http://sourceforge.jp/projects/shogi-server/
8 # Copyright (C) 2006-2009 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 # a base time point for this calicuration (default now). Ex. '2009-10-31'
41 # n [days] (default 60)
43 # --half-life-ignore::
44 # m [days] (default 7)
45 # after m days, the half-life effect works
47 # --fixed-rate-player::
48 # player whose rate is fixed at the rate
54 # skip draw games. [default: draw games are counted in as 0.5 win and 0.5
62 # Sample Command lines that isntall prerequires will work on Debian.
66 # $ sudo aptitude install ruby1.8
70 # $ sudo aptitude install rubygems
72 # * Ruby bindings for the GNU Scientific Library (GSL[http://rb-gsl.rubyforge.org/])
74 # $ sudo aptitude install libgsl-ruby1.8
76 # * RGL: {Ruby Graph Library}[http://rubyforge.org/projects/rgl/]
78 # $ sudo gem install rgl
82 # $ ./mk_rate . > players.yaml
84 # or, if you do not want the file to be update in case of errors,
86 # $ ./mk_rate . && ./mk_rate . > players.yaml
88 # == How players are rated
90 # The conditions that games and players are rated as following:
92 # * Rated games, which were played by both rated players.
93 # * Rated players, who logged in the server with a name followed by a trip: "name,trip".
94 # * (Rated) players, who played more than $GAMES_LIMIT [15] (rated) games.
102 require 'rgl/adjacency'
103 require 'rgl/connected_components'
105 #################################################
109 # Count out players who play less games than $GAMES_LIMIT
110 $GAMES_LIMIT = $DEBUG ? 0 : 15
117 # Holds the last time when a player gamed
118 $players_time = Hash.new { Time.at(0) }
121 #################################################
122 # Keeps the value of the lowest key
130 if @lowest.empty? || key < @lowest[0]
131 @lowest = [key, value]
144 #################################################
145 # Calculates rates of every player from a Win Loss GSL::Matrix
150 # The model of the win possibility is 1/(1 + 10^(-d/400)).
151 # The equation in this class is 1/(1 + e^(-Kd)).
152 # So, K should be calculated like this.
153 K = Math.log(10.0) / 400.0
155 # Convergence limit to stop Newton method.
157 # Stop Newton method after this iterations.
160 # Average rate among the players
169 # Calcurates the average of the vector.
171 def Rating.average(vector, mean=0.0)
172 sum = Array(vector).inject(0.0) {|sum, n| sum + n}
173 vector -= GSL::Vector[*Array.new(vector.size, sum/vector.size - mean)]
180 def initialize(win_loss_matrix)
184 when GSL::Matrix, GSL::Matrix::Int
193 attr_reader :rate, :n
197 (0...@size).collect {|k| yield k}
202 (0...@size).each {|k| yield k}
206 # The possibility that the player k will beet the player i.
209 1.0/(1.0 + exp(@rate[i]-@rate[k]))
213 # Most possible equation
220 sum += @n[k,i] * win_rate(i,k) - @n[i,k] * win_rate(k,i)
227 # / f0/R0 f0/R1 f0/R2 ... \
228 # dfk/dRj = | f1/R0 f1/R1 f1/R2 ... |
229 # \ f2/R0 f2/R1 f2/R2 ... /
235 sum += win_rate(i,k) * win_rate(k,i) * (@n[k,i] + @n[i,k])
239 sum = 2.0 * win_rate(j,k) * win_rate(k,j) * (@n[k,j] + @n[j,k])
245 # Jacobi matrix of the func().
251 (0...@size).collect do |k|
252 (0...@size).collect do |j|
260 # The initial value of the rate, which is of very importance for Newton
261 # method. This is based on my huristics; the higher the win probablity of
262 # a player is, the greater points he takes.
267 v = GSL::Vector[0, 0]
270 v += GSL::Vector[@n[k,i], @n[i,k]]
272 v.nrm2 < 1 ? 0 : v[0] / (v[0] + v[1])
274 rank = possibility.sort_index
275 @rate = player_vector do |k|
276 K*500 * (rank[k]+1) / @size
282 # Resets @rate as the higher the current win probablity of a player is,
283 # the greater points he takes.
286 @rate = @record.get || @rate
287 rank = @rate.sort_index
288 @rate = player_vector do |k|
289 K*@count*1.5 * (rank[k]+1) / @size
294 # mu is the deaccelrating parameter in Deaccelerated Newton method
295 def deaccelrate(mu, old_rate, a, old_f_nrm2)
296 @rate = old_rate - a * mu
297 if func_vector.nrm2 < (1 - mu / 4.0 ) * old_f_nrm2 then
301 @record.set(func_vector.nrm2, @rate)
305 $stderr.puts "mu: %f " % [mu] if $DEBUG
306 deaccelrate(mu*0.5, old_rate, a, old_f_nrm2)
310 # Main process to calculate ratings.
313 # Counter to stop the process.
314 # Calulation in Newton method may fall in an infinite loop
319 # Solve the equation:
321 # @rate_(n+1) = @rate_(n) - a
323 # f.nrm2 should approach to zero.
327 # $stderr.puts "j: %s" % [j.inspect] if $DEBUG
328 $stderr.puts "f: %s -> %f" % [f.to_a.inspect, f.nrm2] if $DEBUG
330 # GSL::Linalg::LU.solve or GSL::Linalg::HH.solve would be available instead.
331 #a = GSL::Linalg::HH.solve(j, f)
332 a, = GSL::MultiFit::linear(j, f)
333 a = self.class.average(a)
334 # $stderr.puts "a: %s -> %f" % [a.to_a.inspect, a.nrm2] if $DEBUG
336 # Deaccelerated Newton method
337 # GSL::Vector object should be immutable.
340 old_f_nrm2 = old_f.nrm2
341 deaccelrate(1.0, old_rate, a, old_f_nrm2)
342 @record.set(func_vector.nrm2, @rate)
344 $stderr.printf "|error| : %5.2e\n", a.nrm2 if $DEBUG
347 if @count > COUNT_MAX
348 $stderr.puts "Values seem to oscillate. Stopped the process."
349 $stderr.puts "f: %s -> %f" % [func_vector.to_a.inspect, func_vector.nrm2]
353 end while (a.nrm2 > ERROR_LIMIT * @rate.nrm2)
356 $stderr.puts "resolved f: %s -> %f" %
357 [func_vector.to_a.inspect, func_vector.nrm2] if $DEBUG
365 # Make the values of @rate finite.
368 @rate = @rate.collect do |a|
370 a.infinite? * AVERAGE_RATE * 100
378 # Flatten the values of @rate.
380 def average!(mean=0.0)
381 @rate = self.class.average(@rate, mean)
387 def translate!(value)
392 # Make the values of @rate integer.
395 @rate = @rate.collect do |a|
401 a.infinite? * AVERAGE_RATE * 100
407 #################################################
408 # Encapsulate a pair of keys and win loss matrix.
409 # - keys is 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.
413 # This object should be immutable. If an internal state is being modified, a
414 # new object is always returned.
422 def self.mk_matrix(players)
423 keys = players.keys.sort
427 ((0...size).collect do |k|
429 p1_hash = players[p1]
430 ((0...size).collect do |j|
435 v = p1_hash[p2] || Vector[0,0]
440 return WinLossMatrix.new(keys, matrix)
443 def self.mk_win_loss_matrix(players)
444 obj = mk_matrix(players)
452 # an array of player IDs; [gps+123, foo+234, ...]
455 # matrix holds games # where player i (row index) beats player j (column index).
456 # The row and column indexes match with the keys.
459 def initialize(keys, matrix)
465 # Returns the size of the keys/matrix
476 # Removes players in a rows such as [1,3,5], and then returns a new
479 def delete_rows(rows)
480 rows = rows.sort.reverse
483 (0...size).each do |i|
484 next if rows.include?(i)
485 row = @matrix.row(i).clone
491 if copied_cols.size == 0
492 new_matrix = GSL::Matrix.new
494 new_matrix = GSL::Matrix[*copied_cols]
497 new_keys = @keys.clone
499 new_keys.delete_at(j)
502 return WinLossMatrix.new(new_keys, new_matrix)
506 # Removes players who do not pass a criteria to be rated, and returns a
510 $stderr.puts @keys.inspect if $DEBUG
511 $stderr.puts @matrix.inspect if $DEBUG
513 (0...size).each do |i|
518 if win < 1 || loss < 1 || win + loss < $GAMES_LIMIT
523 # The recursion ends if there is nothing to delete
524 return self if delete.empty?
526 new_obj = delete_rows(delete)
531 # Cuts self into connecting groups such as each player in a group has at least
532 # one game with other players in the group. Returns them as an array.
534 def connected_subsets
535 g = RGL::AdjacencyGraph.new
536 (0...size).each do |k|
537 (0...size).each do |i|
546 g.each_connected_component do |c|
549 new_keys << keys[v.to_s.to_i]
554 subsets = subsets.sort {|a,b| b.size <=> a.size}
556 result = subsets.collect do |keys|
559 ((0...keys.size).collect do |k|
560 p1 = @keys.index(keys[k])
561 ((0...keys.size).collect do |j|
565 p2 = @keys.index(keys[j])
570 WinLossMatrix.new(keys, matrix)
577 "size : #{@keys.size}" + "\n" +
578 @keys.inspect + "\n" +
585 #################################################
590 # After NHAFE_LIFE days value will get half.
591 # 0.693 is constant, where exp(0.693) ~ 0.5
593 if days < $options["half-life-ignore"]
596 Math::exp(-0.693/$options["half-life"]*(days-$options["half-life-ignore"]))
600 def _add_win_loss(winner, loser, time)
601 how_long_days = ($options["base-date"] - time)/(3600*24)
602 $players[winner] ||= Hash.new { GSL::Vector[0,0] }
603 $players[loser] ||= Hash.new { GSL::Vector[0,0] }
604 $players[winner][loser] += GSL::Vector[1.0*half_life(how_long_days),0]
605 $players[loser][winner] += GSL::Vector[0,1.0*half_life(how_long_days)]
608 def _add_draw(player1, player2, time)
609 how_long_days = ($options["base-date"] - time)/(3600*24)
610 $players[player1] ||= Hash.new { GSL::Vector[0,0] }
611 $players[player2] ||= Hash.new { GSL::Vector[0,0] }
612 $players[player1][player2] += GSL::Vector[0.5*half_life(how_long_days),0.5*half_life(how_long_days)]
613 $players[player2][player1] += GSL::Vector[0.5*half_life(how_long_days),0.5*half_life(how_long_days)]
616 def _add_time(player, time)
617 $players_time[player] = time if $players_time[player] < time
620 def add(black_mark, black_name, white_name, white_mark, time)
621 if black_mark == WIN_MARK && white_mark == LOSS_MARK
622 _add_win_loss(black_name, white_name, time)
623 elsif black_mark == LOSS_MARK && white_mark == WIN_MARK
624 _add_win_loss(white_name, black_name, time)
625 elsif black_mark == DRAW_MARK && white_mark == DRAW_MARK
626 if $options["skip-draw-games"]
629 _add_draw(black_name, white_name, time)
632 raise "Never reached!"
634 _add_time(black_name, time)
635 _add_time(white_name, time)
639 if /@NORATE\+/ =~ id # the player having @NORATE in the name should not be rated
642 id.gsub(/@.*?\+/,"+")
645 # Parse a game result line
648 time, state, black_mark, black_id, white_id, white_mark, file = line.split("\t")
649 unless time && state && black_mark && black_id &&
650 white_id && white_mark && file
651 $stderr.puts "Failed to parse the line : #{line}"
655 return if state == "abnormal"
656 time = Time.parse(time)
657 return if $options["base-date"] < time
658 black_id = identify_id(black_id)
659 white_id = identify_id(white_id)
661 if black_id && white_id && (black_id != white_id) &&
662 black_mark && white_mark
663 add(black_mark, black_id, white_id, white_mark, time)
668 yaml["players"].each do |group_key, group|
669 group.each do |player_key, player|
670 rate = player['rate']
672 if rate > 10000 || rate < -10000
682 USAGE: #{$0} [options] DIR..
683 DIR where CSA files are looked up recursively
685 --base-date a base time point for this calicuration (default now). Ex. '2009-10-31'
686 --half-life n [days] (default 60)
687 --half-life-ignore m [days] (default 7)
688 after m days, half-life effect works
689 --fixed-rate-player player whose rate is fixed at the rate
691 --skip-draw-games skip draw games. [default: draw games are counted in
692 as 0.5 win and 0.5 lost]
693 --help show this message
699 parser = GetoptLong.new(
700 ["--base-date", GetoptLong::REQUIRED_ARGUMENT],
701 ["--half-life", GetoptLong::REQUIRED_ARGUMENT],
702 ["--half-life-ignore", GetoptLong::REQUIRED_ARGUMENT],
703 ["--help", "-h", GetoptLong::NO_ARGUMENT],
704 ["--fixed-rate-player", GetoptLong::REQUIRED_ARGUMENT],
705 ["--fixed-rate", GetoptLong::REQUIRED_ARGUMENT],
706 ["--skip-draw-games", GetoptLong::NO_ARGUMENT])
709 parser.each_option do |name, arg|
711 $options[name] = arg.dup
713 if ( $options["fixed-rate-player"] && !$options["fixed-rate"]) ||
714 (!$options["fixed-rate-player"] && $options["fixed-rate"]) ||
715 ( $options["fixed-rate-player"] && $options["fixed-rate"].to_i <= 0)
721 raise parser.error_message
727 if $options["base-date"]
728 $options["base-date"] = Time::parse $options["base-date"]
730 $options["base-date"] = Time.now
732 $options["half-life"] ||= 60
733 $options["half-life"] = $options["half-life"].to_i
734 $options["half-life-ignore"] ||= 7
735 $options["half-life-ignore"] = $options["half-life-ignore"].to_i
736 $options["fixed-rate"] = $options["fixed-rate"].to_i if $options["fixed-rate"]
739 while line = $stdin.gets do
743 while file = ARGV.shift do
744 File.open(file) do |f|
745 f.each_line do |line|
756 obj = WinLossMatrix::mk_win_loss_matrix($players)
757 obj.connected_subsets.each do |win_loss_matrix|
758 yaml["players"][rating_group] = {}
760 rating = Rating.new(win_loss_matrix.matrix)
762 rating.average!(Rating::AVERAGE_RATE)
765 if $options["fixed-rate-player"]
766 # first, try exact match
767 index = win_loss_matrix.keys.index($options["fixed-rate-player"])
768 # second, try regular match
770 win_loss_matrix.keys.each_with_index do |p, i|
771 if %r!#{$options["fixed-rate-player"]}! =~ p
777 the_rate = rating.rate[index]
778 rating.translate!($options["fixed-rate"] - the_rate)
782 win_loss_matrix.keys.each_with_index do |p, i| # player_id, index#
783 win = win_loss_matrix.matrix.row(i).sum
784 loss = win_loss_matrix.matrix.col(i).sum
786 yaml["players"][rating_group][p] =
787 { 'name' => p.split("+")[0],
788 'rating_group' => rating_group,
789 'rate' => rating.rate[i],
790 'last_modified' => $players_time[p].dup,
798 non_rated_group = 999 # large enough
799 yaml["players"][non_rated_group] = {}
800 $players.each_key do |id|
801 # skip players who have already been rated
803 (0..rating_group).each do |i|
804 found = true if yaml["players"][i][id]
809 v = GSL::Vector[0, 0]
810 $players[id].each_value {|value| v += value}
811 next if v[0] < 1 && v[1] < 1
813 yaml["players"][non_rated_group][id] =
814 { 'name' => id.split("+")[0],
815 'rating_group' => non_rated_group,
817 'last_modified' => $players_time[id].dup,
821 unless validate(yaml)
822 $stderr.puts "Aborted. It did not result in valid ratings."
823 $stderr.puts yaml.to_yaml if $DEBUG
833 # vim: ts=2 sw=2 sts=0