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
58 # Sample Command lines that isntall prerequires will work on Debian.
62 # $ sudo aptitude install ruby1.8
66 # $ sudo aptitude install rubygems
68 # * Ruby bindings for the GNU Scientific Library (GSL[http://rb-gsl.rubyforge.org/])
70 # $ sudo aptitude install libgsl-ruby1.8
72 # * RGL: {Ruby Graph Library}[http://rubyforge.org/projects/rgl/]
74 # $ sudo gem install rgl
78 # $ ./mk_rate . > players.yaml
80 # or, if you do not want the file to be update in case of errors,
82 # $ ./mk_rate . && ./mk_rate . > players.yaml
84 # == How players are rated
86 # The conditions that games and players are rated as following:
88 # * Rated games, which were played by both rated players.
89 # * Rated players, who logged in the server with a name followed by a trip: "name,trip".
90 # * (Rated) players, who played more than $GAMES_LIMIT [15] (rated) games.
98 require 'rgl/adjacency'
99 require 'rgl/connected_components'
101 #################################################
105 # Count out players who play less games than $GAMES_LIMIT
106 $GAMES_LIMIT = $DEBUG ? 0 : 15
113 # Holds the last time when a player gamed
114 $players_time = Hash.new { Time.at(0) }
117 #################################################
118 # Keeps the value of the lowest key
126 if @lowest.empty? || key < @lowest[0]
127 @lowest = [key, value]
140 #################################################
141 # Calculates rates of every player from a Win Loss GSL::Matrix
146 # The model of the win possibility is 1/(1 + 10^(-d/400)).
147 # The equation in this class is 1/(1 + e^(-Kd)).
148 # So, K should be calculated like this.
149 K = Math.log(10.0) / 400.0
151 # Convergence limit to stop Newton method.
153 # Stop Newton method after this iterations.
156 # Average rate among the players
165 # Calcurates the average of the vector.
167 def Rating.average(vector, mean=0.0)
168 sum = Array(vector).inject(0.0) {|sum, n| sum + n}
169 vector -= GSL::Vector[*Array.new(vector.size, sum/vector.size - mean)]
176 def initialize(win_loss_matrix)
180 when GSL::Matrix, GSL::Matrix::Int
189 attr_reader :rate, :n
193 (0...@size).collect {|k| yield k}
198 (0...@size).each {|k| yield k}
202 # The possibility that the player k will beet the player i.
205 1.0/(1.0 + exp(@rate[i]-@rate[k]))
209 # Most possible equation
216 sum += @n[k,i] * win_rate(i,k) - @n[i,k] * win_rate(k,i)
223 # / f0/R0 f0/R1 f0/R2 ... \
224 # dfk/dRj = | f1/R0 f1/R1 f1/R2 ... |
225 # \ f2/R0 f2/R1 f2/R2 ... /
231 sum += win_rate(i,k) * win_rate(k,i) * (@n[k,i] + @n[i,k])
235 sum = 2.0 * win_rate(j,k) * win_rate(k,j) * (@n[k,j] + @n[j,k])
241 # Jacobi matrix of the func().
247 (0...@size).collect do |k|
248 (0...@size).collect do |j|
256 # The initial value of the rate, which is of very importance for Newton
257 # method. This is based on my huristics; the higher the win probablity of
258 # a player is, the greater points he takes.
263 v = GSL::Vector[0, 0]
266 v += GSL::Vector[@n[k,i], @n[i,k]]
268 v.nrm2 < 1 ? 0 : v[0] / (v[0] + v[1])
270 rank = possibility.sort_index
271 @rate = player_vector do |k|
272 K*500 * (rank[k]+1) / @size
278 # Resets @rate as the higher the current win probablity of a player is,
279 # the greater points he takes.
282 @rate = @record.get || @rate
283 rank = @rate.sort_index
284 @rate = player_vector do |k|
285 K*@count*1.5 * (rank[k]+1) / @size
290 # mu is the deaccelrating parameter in Deaccelerated Newton method
291 def deaccelrate(mu, old_rate, a, old_f_nrm2)
292 @rate = old_rate - a * mu
293 if func_vector.nrm2 < (1 - mu / 4.0 ) * old_f_nrm2 then
297 @record.set(func_vector.nrm2, @rate)
301 $stderr.puts "mu: %f " % [mu] if $DEBUG
302 deaccelrate(mu*0.5, old_rate, a, old_f_nrm2)
306 # Main process to calculate ratings.
309 # Counter to stop the process.
310 # Calulation in Newton method may fall in an infinite loop
315 # Solve the equation:
317 # @rate_(n+1) = @rate_(n) - a
319 # f.nrm2 should approach to zero.
323 # $stderr.puts "j: %s" % [j.inspect] if $DEBUG
324 $stderr.puts "f: %s -> %f" % [f.to_a.inspect, f.nrm2] if $DEBUG
326 # GSL::Linalg::LU.solve or GSL::Linalg::HH.solve would be available instead.
327 #a = GSL::Linalg::HH.solve(j, f)
328 a, = GSL::MultiFit::linear(j, f)
329 a = self.class.average(a)
330 # $stderr.puts "a: %s -> %f" % [a.to_a.inspect, a.nrm2] if $DEBUG
332 # Deaccelerated Newton method
333 # GSL::Vector object should be immutable.
336 old_f_nrm2 = old_f.nrm2
337 deaccelrate(1.0, old_rate, a, old_f_nrm2)
338 @record.set(func_vector.nrm2, @rate)
340 $stderr.printf "|error| : %5.2e\n", a.nrm2 if $DEBUG
343 if @count > COUNT_MAX
344 $stderr.puts "Values seem to oscillate. Stopped the process."
345 $stderr.puts "f: %s -> %f" % [func_vector.to_a.inspect, func_vector.nrm2]
349 end while (a.nrm2 > ERROR_LIMIT * @rate.nrm2)
352 $stderr.puts "resolved f: %s -> %f" %
353 [func_vector.to_a.inspect, func_vector.nrm2] if $DEBUG
361 # Make the values of @rate finite.
364 @rate = @rate.collect do |a|
366 a.infinite? * AVERAGE_RATE * 100
374 # Flatten the values of @rate.
376 def average!(mean=0.0)
377 @rate = self.class.average(@rate, mean)
383 def translate!(value)
388 # Make the values of @rate integer.
391 @rate = @rate.collect do |a|
397 a.infinite? * AVERAGE_RATE * 100
403 #################################################
404 # Encapsulate a pair of keys and win loss matrix.
405 # - keys is an array of player IDs; [gps+123, foo+234, ...]
406 # - matrix holds games # where player i (row index) beats player j (column index).
407 # The row and column indexes match with the keys.
409 # This object should be immutable. If an internal state is being modified, a
410 # new object is always returned.
418 def self.mk_matrix(players)
419 keys = players.keys.sort
423 ((0...size).collect do |k|
425 p1_hash = players[p1]
426 ((0...size).collect do |j|
431 v = p1_hash[p2] || Vector[0,0]
436 return WinLossMatrix.new(keys, matrix)
439 def self.mk_win_loss_matrix(players)
440 obj = mk_matrix(players)
448 # an array of player IDs; [gps+123, foo+234, ...]
451 # matrix holds games # where player i (row index) beats player j (column index).
452 # The row and column indexes match with the keys.
455 def initialize(keys, matrix)
461 # Returns the size of the keys/matrix
472 # Removes players in a rows such as [1,3,5], and then returns a new
475 def delete_rows(rows)
476 rows = rows.sort.reverse
479 (0...size).each do |i|
480 next if rows.include?(i)
481 row = @matrix.row(i).clone
487 if copied_cols.size == 0
488 new_matrix = GSL::Matrix.new
490 new_matrix = GSL::Matrix[*copied_cols]
493 new_keys = @keys.clone
495 new_keys.delete_at(j)
498 return WinLossMatrix.new(new_keys, new_matrix)
502 # Removes players who do not pass a criteria to be rated, and returns a
506 $stderr.puts @keys.inspect if $DEBUG
507 $stderr.puts @matrix.inspect if $DEBUG
509 (0...size).each do |i|
514 if win < 1 || loss < 1 || win + loss < $GAMES_LIMIT
519 # The recursion ends if there is nothing to delete
520 return self if delete.empty?
522 new_obj = delete_rows(delete)
527 # Cuts self into connecting groups such as each player in a group has at least
528 # one game with other players in the group. Returns them as an array.
530 def connected_subsets
531 g = RGL::AdjacencyGraph.new
532 (0...size).each do |k|
533 (0...size).each do |i|
542 g.each_connected_component do |c|
545 new_keys << keys[v.to_s.to_i]
550 subsets = subsets.sort {|a,b| b.size <=> a.size}
552 result = subsets.collect do |keys|
555 ((0...keys.size).collect do |k|
556 p1 = @keys.index(keys[k])
557 ((0...keys.size).collect do |j|
561 p2 = @keys.index(keys[j])
566 WinLossMatrix.new(keys, matrix)
573 "size : #{@keys.size}" + "\n" +
574 @keys.inspect + "\n" +
581 #################################################
586 # After NHAFE_LIFE days value will get half.
587 # 0.693 is constant, where exp(0.693) ~ 0.5
589 if days < $options["half-life-ignore"]
592 Math::exp(-0.693/$options["half-life"]*(days-$options["half-life-ignore"]))
596 def _add_win_loss(winner, loser, time)
597 how_long_days = ($options["base-date"] - time)/(3600*24)
598 $players[winner] ||= Hash.new { GSL::Vector[0,0] }
599 $players[loser] ||= Hash.new { GSL::Vector[0,0] }
600 $players[winner][loser] += GSL::Vector[1.0*half_life(how_long_days),0]
601 $players[loser][winner] += GSL::Vector[0,1.0*half_life(how_long_days)]
604 def _add_time(player, time)
605 $players_time[player] = time if $players_time[player] < time
608 def add(black_mark, black_name, white_name, white_mark, time)
609 if black_mark == WIN_MARK && white_mark == LOSS_MARK
610 _add_win_loss(black_name, white_name, time)
611 elsif black_mark == LOSS_MARK && white_mark == WIN_MARK
612 _add_win_loss(white_name, black_name, time)
613 elsif black_mark == DRAW_MARK && white_mark == DRAW_MARK
616 raise "Never reached!"
618 _add_time(black_name, time)
619 _add_time(white_name, time)
623 if /@NORATE\+/ =~ id # the player having @NORATE in the name should not be rated
626 id.gsub(/@.*?\+/,"+")
629 # Parse a game result line
632 time, state, black_mark, black_id, white_id, white_mark, file = line.split("\t")
633 unless time && state && black_mark && black_id &&
634 white_id && white_mark && file
635 $stderr.puts "Failed to parse the line : #{line}"
639 return if state == "abnormal"
640 time = Time.parse(time)
641 return if $options["base-date"] < time
642 black_id = identify_id(black_id)
643 white_id = identify_id(white_id)
645 if black_id && white_id && (black_id != white_id) &&
646 black_mark && white_mark
647 add(black_mark, black_id, white_id, white_mark, time)
652 yaml["players"].each do |group_key, group|
653 group.each do |player_key, player|
654 rate = player['rate']
656 if rate > 10000 || rate < -10000
666 USAGE: #{$0} [options] DIR..
667 DIR where CSA files are looked up recursively
669 --base-date a base time point for this calicuration (default now). Ex. '2009-10-31'
670 --half-life n [days] (default 60)
671 --half-life-ignore m [days] (default 7)
672 after m days, half-life effect works
673 --fixed-rate-player player whose rate is fixed at the rate
675 --help show this message
681 parser = GetoptLong.new(
682 ["--base-date", GetoptLong::REQUIRED_ARGUMENT],
683 ["--half-life", GetoptLong::REQUIRED_ARGUMENT],
684 ["--half-life-ignore", GetoptLong::REQUIRED_ARGUMENT],
685 ["--help", "-h", GetoptLong::NO_ARGUMENT],
686 ["--fixed-rate-player", GetoptLong::REQUIRED_ARGUMENT],
687 ["--fixed-rate", GetoptLong::REQUIRED_ARGUMENT])
690 parser.each_option do |name, arg|
692 $options[name] = arg.dup
694 if ( $options["fixed-rate-player"] && !$options["fixed-rate"]) ||
695 (!$options["fixed-rate-player"] && $options["fixed-rate"]) ||
696 ( $options["fixed-rate-player"] && $options["fixed-rate"].to_i <= 0)
702 raise parser.error_message
708 if $options["base-date"]
709 $options["base-date"] = Time::parse $options["base-date"]
711 $options["base-date"] = Time.now
713 $options["half-life"] ||= 60
714 $options["half-life"] = $options["half-life"].to_i
715 $options["half-life-ignore"] ||= 7
716 $options["half-life-ignore"] = $options["half-life-ignore"].to_i
717 $options["fixed-rate"] = $options["fixed-rate"].to_i if $options["fixed-rate"]
720 while line = $stdin.gets do
724 while file = ARGV.shift do
725 File.open(file) do |f|
726 f.each_line do |line|
737 obj = WinLossMatrix::mk_win_loss_matrix($players)
738 obj.connected_subsets.each do |win_loss_matrix|
739 yaml["players"][rating_group] = {}
741 rating = Rating.new(win_loss_matrix.matrix)
743 rating.average!(Rating::AVERAGE_RATE)
746 if $options["fixed-rate-player"]
747 # first, try exact match
748 index = win_loss_matrix.keys.index($options["fixed-rate-player"])
749 # second, try regular match
751 win_loss_matrix.keys.each_with_index do |p, i|
752 if %r!#{$options["fixed-rate-player"]}! =~ p
758 the_rate = rating.rate[index]
759 rating.translate!($options["fixed-rate"] - the_rate)
763 win_loss_matrix.keys.each_with_index do |p, i| # player_id, index#
764 win = win_loss_matrix.matrix.row(i).sum
765 loss = win_loss_matrix.matrix.col(i).sum
767 yaml["players"][rating_group][p] =
768 { 'name' => p.split("+")[0],
769 'rating_group' => rating_group,
770 'rate' => rating.rate[i],
771 'last_modified' => $players_time[p].dup,
779 non_rated_group = 999 # large enough
780 yaml["players"][non_rated_group] = {}
781 $players.each_key do |id|
782 # skip players who have already been rated
784 (0..rating_group).each do |i|
785 found = true if yaml["players"][i][id]
790 v = GSL::Vector[0, 0]
791 $players[id].each_value {|value| v += value}
792 next if v[0] < 1 && v[1] < 1
794 yaml["players"][non_rated_group][id] =
795 { 'name' => id.split("+")[0],
796 'rating_group' => non_rated_group,
798 'last_modified' => $players_time[id].dup,
802 unless validate(yaml)
803 $stderr.puts "Aborted. It did not result in valid ratings."
804 $stderr.puts yaml.to_yaml if $DEBUG
814 # vim: ts=2 sw=2 sts=0