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 game results files generated by the mk_game_results command,
28 # calculates rating scores of each player, and then outputs a yaml file
29 # (players.yaml) that Shogi-server can recognize.
33 # ./mk_rate [options] GAME_RESULTS_FILE [...]
38 # a path to a file listing results of games, which is genrated by the
39 # mk_game_results command.
40 # In the second style above, the file content can be read from the stdin.
43 # a base time point for this calicuration (default now). Ex. '2009-10-31'
46 # n [days] (default 60)
48 # --half-life-ignore::
49 # m [days] (default 7)
50 # after m days, the half-life effect works
52 # --fixed-rate-player::
53 # player whose rate is fixed at the rate
59 # skip draw games. [default: draw games are counted in as 0.5 win and 0.5
67 # Sample Command lines that isntall prerequires will work on Debian.
71 # $ sudo aptitude install ruby1.8
75 # $ sudo aptitude install rubygems
77 # * Ruby bindings for the GNU Scientific Library (GSL[http://rb-gsl.rubyforge.org/])
79 # $ sudo aptitude install libgsl-ruby1.8
81 # * RGL: {Ruby Graph Library}[http://rubyforge.org/projects/rgl/]
83 # $ sudo gem install rgl
87 # $ ./mk_rate game_results.txt > players.yaml
89 # $ ./mk_game_results . | ./mk_rate > players.yaml
91 # If you do not want the file to be update in case of errors,
93 # $ ./mk_rate game_results.txt && ./mk_rate game_results.txt > players.yaml
95 # == How players are rated
97 # The conditions that games and players are rated as following:
99 # * Rated games, which were played by both rated players.
100 # * Rated players, who logged in the server with a name followed by a trip: "name,trip".
101 # * (Rated) players, who played more than $GAMES_LIMIT [15] (rated) games.
109 require 'rgl/adjacency'
110 require 'rgl/connected_components'
112 #################################################
116 # Count out players who play less games than $GAMES_LIMIT
117 $GAMES_LIMIT = $DEBUG ? 0 : 15
124 # Holds the last time when a player gamed
125 $players_time = Hash.new { Time.at(0) }
128 #################################################
129 # Keeps the value of the lowest key
137 if @lowest.empty? || key < @lowest[0]
138 @lowest = [key, value]
151 #################################################
152 # Calculates rates of every player from a Win Loss GSL::Matrix
157 # The model of the win possibility is 1/(1 + 10^(-d/400)).
158 # The equation in this class is 1/(1 + e^(-Kd)).
159 # So, K should be calculated like this.
160 K = Math.log(10.0) / 400.0
162 # Convergence limit to stop Newton method.
164 # Stop Newton method after this iterations.
167 # Average rate among the players
176 # Calcurates the average of the vector.
178 def Rating.average(vector, mean=0.0)
179 sum = Array(vector).inject(0.0) {|sum, n| sum + n}
180 vector -= GSL::Vector[*Array.new(vector.size, sum/vector.size - mean)]
187 def initialize(win_loss_matrix)
191 when GSL::Matrix, GSL::Matrix::Int
200 attr_reader :rate, :n
204 (0...@size).collect {|k| yield k}
209 (0...@size).each {|k| yield k}
213 # The possibility that the player k will beet the player i.
216 1.0/(1.0 + exp(@rate[i]-@rate[k]))
220 # Most possible equation
227 sum += @n[k,i] * win_rate(i,k) - @n[i,k] * win_rate(k,i)
234 # / f0/R0 f0/R1 f0/R2 ... \
235 # dfk/dRj = | f1/R0 f1/R1 f1/R2 ... |
236 # \ f2/R0 f2/R1 f2/R2 ... /
242 sum += win_rate(i,k) * win_rate(k,i) * (@n[k,i] + @n[i,k])
246 sum = 2.0 * win_rate(j,k) * win_rate(k,j) * (@n[k,j] + @n[j,k])
252 # Jacobi matrix of the func().
258 (0...@size).collect do |k|
259 (0...@size).collect do |j|
267 # The initial value of the rate, which is of very importance for Newton
268 # method. This is based on my huristics; the higher the win probablity of
269 # a player is, the greater points he takes.
274 v = GSL::Vector[0, 0]
277 v += GSL::Vector[@n[k,i], @n[i,k]]
279 v.nrm2 < 1 ? 0 : v[0] / (v[0] + v[1])
281 rank = possibility.sort_index
282 @rate = player_vector do |k|
283 K*500 * (rank[k]+1) / @size
289 # Resets @rate as the higher the current win probablity of a player is,
290 # the greater points he takes.
293 @rate = @record.get || @rate
294 rank = @rate.sort_index
295 @rate = player_vector do |k|
296 K*@count*1.5 * (rank[k]+1) / @size
301 # mu is the deaccelrating parameter in Deaccelerated Newton method
302 def deaccelrate(mu, old_rate, a, old_f_nrm2)
303 @rate = old_rate - a * mu
304 if func_vector.nrm2 < (1 - mu / 4.0 ) * old_f_nrm2 then
308 @record.set(func_vector.nrm2, @rate)
312 $stderr.puts "mu: %f " % [mu] if $DEBUG
313 deaccelrate(mu*0.5, old_rate, a, old_f_nrm2)
317 # Main process to calculate ratings.
320 # Counter to stop the process.
321 # Calulation in Newton method may fall in an infinite loop
326 # Solve the equation:
328 # @rate_(n+1) = @rate_(n) - a
330 # f.nrm2 should approach to zero.
334 # $stderr.puts "j: %s" % [j.inspect] if $DEBUG
335 $stderr.puts "f: %s -> %f" % [f.to_a.inspect, f.nrm2] if $DEBUG
337 # GSL::Linalg::LU.solve or GSL::Linalg::HH.solve would be available instead.
338 #a = GSL::Linalg::HH.solve(j, f)
339 a, = GSL::MultiFit::linear(j, f)
340 a = self.class.average(a)
341 # $stderr.puts "a: %s -> %f" % [a.to_a.inspect, a.nrm2] if $DEBUG
343 # Deaccelerated Newton method
344 # GSL::Vector object should be immutable.
347 old_f_nrm2 = old_f.nrm2
348 deaccelrate(1.0, old_rate, a, old_f_nrm2)
349 #@rate -= a # Instead, do not deaccelerate
350 @record.set(func_vector.nrm2, @rate)
352 $stderr.printf "|error| : %5.2e\n", a.nrm2 if $DEBUG
355 if @count > COUNT_MAX
356 $stderr.puts "Values seem to oscillate. Stopped the process."
357 $stderr.puts "f: %s -> %f" % [func_vector.to_a.inspect, func_vector.nrm2]
361 end while (a.nrm2 > ERROR_LIMIT * @rate.nrm2)
364 $stderr.puts "resolved f: %s -> %f" %
365 [func_vector.to_a.inspect, func_vector.nrm2] if $DEBUG
366 $stderr.puts "Count: %d" % [@count] if $DEBUG
374 # Make the values of @rate finite.
377 @rate = @rate.collect do |a|
379 a.infinite? * AVERAGE_RATE * 100
387 # Flatten the values of @rate.
389 def average!(mean=0.0)
390 @rate = self.class.average(@rate, mean)
396 def translate!(value)
401 # Make the values of @rate integer.
404 @rate = @rate.collect do |a|
410 a.infinite? * AVERAGE_RATE * 100
416 #################################################
417 # Encapsulate a pair of keys and win loss matrix.
418 # - keys is an array of player IDs; [gps+123, foo+234, ...]
419 # - matrix holds games # where player i (row index) beats player j (column index).
420 # The row and column indexes match with the keys.
422 # This object should be immutable. If an internal state is being modified, a
423 # new object is always returned.
431 def self.mk_matrix(players)
432 keys = players.keys.sort
436 ((0...size).collect do |k|
438 p1_hash = players[p1]
439 ((0...size).collect do |j|
444 v = p1_hash[p2] || GSL::Vector[0,0]
449 return WinLossMatrix.new(keys, matrix)
452 def self.mk_win_loss_matrix(players)
453 obj = mk_matrix(players)
461 # an array of player IDs; [gps+123, foo+234, ...]
464 # matrix holds games # where player i (row index) beats player j (column index).
465 # The row and column indexes match with the keys.
468 def initialize(keys, matrix)
474 # Returns the size of the keys/matrix
485 # Removes players in a rows such as [1,3,5], and then returns a new
488 def delete_rows(rows)
489 rows = rows.sort.reverse
492 (0...size).each do |i|
493 next if rows.include?(i)
494 row = @matrix.row(i).clone
500 if copied_cols.size == 0
501 new_matrix = GSL::Matrix.new
503 new_matrix = GSL::Matrix[*copied_cols]
506 new_keys = @keys.clone
508 new_keys.delete_at(j)
511 return WinLossMatrix.new(new_keys, new_matrix)
515 # Removes players who do not pass a criteria to be rated, and returns a
519 $stderr.puts @keys.inspect if $DEBUG
520 $stderr.puts @matrix.inspect if $DEBUG
522 (0...size).each do |i|
527 if win < 1 || loss < 1 || win + loss < $GAMES_LIMIT
532 # The recursion ends if there is nothing to delete
533 return self if delete.empty?
535 new_obj = delete_rows(delete)
540 # Cuts self into connecting groups such as each player in a group has at least
541 # one game with other players in the group. Returns them as an array.
543 def connected_subsets
544 g = RGL::AdjacencyGraph.new
545 (0...size).each do |k|
546 (0...size).each do |i|
555 g.each_connected_component do |c|
558 new_keys << keys[v.to_s.to_i]
563 subsets = subsets.sort {|a,b| b.size <=> a.size}
565 result = subsets.collect do |keys|
568 ((0...keys.size).collect do |k|
569 p1 = @keys.index(keys[k])
570 ((0...keys.size).collect do |j|
574 p2 = @keys.index(keys[j])
579 WinLossMatrix.new(keys, matrix)
586 "size : #{@keys.size}" + "\n" +
587 @keys.inspect + "\n" +
594 #################################################
599 # After NHAFE_LIFE days value will get half.
600 # 0.693 is constant, where exp(0.693) ~ 0.5
602 if days < $options["half-life-ignore"]
605 Math::exp(-0.693/$options["half-life"]*(days-$options["half-life-ignore"]))
609 def _add_win_loss(winner, loser, time)
610 how_long_days = ($options["base-date"] - time)/(3600*24)
611 $players[winner] ||= Hash.new { GSL::Vector[0,0] }
612 $players[loser] ||= Hash.new { GSL::Vector[0,0] }
613 $players[winner][loser] += GSL::Vector[1.0*half_life(how_long_days),0]
614 $players[loser][winner] += GSL::Vector[0,1.0*half_life(how_long_days)]
617 def _add_draw(player1, player2, time)
618 how_long_days = ($options["base-date"] - time)/(3600*24)
619 $players[player1] ||= Hash.new { GSL::Vector[0,0] }
620 $players[player2] ||= Hash.new { GSL::Vector[0,0] }
621 $players[player1][player2] += GSL::Vector[0.5*half_life(how_long_days),0.5*half_life(how_long_days)]
622 $players[player2][player1] += GSL::Vector[0.5*half_life(how_long_days),0.5*half_life(how_long_days)]
625 def _add_time(player, time)
626 $players_time[player] = time if $players_time[player] < time
629 def add(black_mark, black_name, white_name, white_mark, time)
630 if black_mark == WIN_MARK && white_mark == LOSS_MARK
631 _add_win_loss(black_name, white_name, time)
632 elsif black_mark == LOSS_MARK && white_mark == WIN_MARK
633 _add_win_loss(white_name, black_name, time)
634 elsif black_mark == DRAW_MARK && white_mark == DRAW_MARK
635 if $options["skip-draw-games"]
638 _add_draw(black_name, white_name, time)
641 raise "Never reached!"
643 _add_time(black_name, time)
644 _add_time(white_name, time)
648 if /@NORATE\+/ =~ id # the player having @NORATE in the name should not be rated
651 id.gsub(/@.*?\+/,"+")
654 # Parse a game result line
657 time, state, black_mark, black_id, white_id, white_mark, file = line.split("\t")
658 unless time && state && black_mark && black_id &&
659 white_id && white_mark && file
660 $stderr.puts "Failed to parse the line : #{line}"
664 return if state == "abnormal"
665 time = Time.parse(time)
666 return if $options["base-date"] < time
667 black_id = identify_id(black_id)
668 white_id = identify_id(white_id)
670 if black_id && white_id && (black_id != white_id) &&
671 black_mark && white_mark
672 add(black_mark, black_id, white_id, white_mark, time)
677 yaml["players"].each do |group_key, group|
678 group.each do |player_key, player|
679 rate = player['rate']
681 if rate > 10000 || rate < -10000
691 USAGE: #{$0} [options] GAME_RESULTS_FILE [...]
695 a path to a file listing results of games, which is genrated by the
696 mk_game_results command.
697 In the second style above, the file content can be read from the stdin.
700 --base-date a base time point for this calicuration (default now). Ex. '2009-10-31'
701 --half-life n [days] (default 60)
702 --half-life-ignore m [days] (default 7)
703 after m days, half-life effect works
704 --fixed-rate-player player whose rate is fixed at the rate
706 --skip-draw-games skip draw games. [default: draw games are counted in
707 as 0.5 win and 0.5 lost]
708 --help show this message
714 parser = GetoptLong.new(
715 ["--base-date", GetoptLong::REQUIRED_ARGUMENT],
716 ["--half-life", GetoptLong::REQUIRED_ARGUMENT],
717 ["--half-life-ignore", GetoptLong::REQUIRED_ARGUMENT],
718 ["--help", "-h", GetoptLong::NO_ARGUMENT],
719 ["--fixed-rate-player", GetoptLong::REQUIRED_ARGUMENT],
720 ["--fixed-rate", GetoptLong::REQUIRED_ARGUMENT],
721 ["--skip-draw-games", GetoptLong::NO_ARGUMENT])
724 parser.each_option do |name, arg|
726 $options[name] = arg.dup
728 if ( $options["fixed-rate-player"] && !$options["fixed-rate"]) ||
729 (!$options["fixed-rate-player"] && $options["fixed-rate"]) ||
730 ( $options["fixed-rate-player"] && $options["fixed-rate"].to_i <= 0)
736 raise parser.error_message
742 if $options["base-date"]
743 $options["base-date"] = Time::parse $options["base-date"]
745 $options["base-date"] = Time.now
747 $options["half-life"] ||= 60
748 $options["half-life"] = $options["half-life"].to_i
749 $options["half-life-ignore"] ||= 7
750 $options["half-life-ignore"] = $options["half-life-ignore"].to_i
751 $options["fixed-rate"] = $options["fixed-rate"].to_i if $options["fixed-rate"]
754 while line = $stdin.gets do
758 while file = ARGV.shift do
759 File.open(file) do |f|
760 f.each_line do |line|
771 obj = WinLossMatrix::mk_win_loss_matrix($players)
772 obj.connected_subsets.each do |win_loss_matrix|
773 yaml["players"][rating_group] = {}
775 rating = Rating.new(win_loss_matrix.matrix)
777 rating.average!(Rating::AVERAGE_RATE)
780 if $options["fixed-rate-player"]
781 # first, try exact match
782 index = win_loss_matrix.keys.index($options["fixed-rate-player"])
783 # second, try regular match
785 win_loss_matrix.keys.each_with_index do |p, i|
786 if %r!#{$options["fixed-rate-player"]}! =~ p
792 the_rate = rating.rate[index]
793 rating.translate!($options["fixed-rate"] - the_rate)
797 win_loss_matrix.keys.each_with_index do |p, i| # player_id, index#
798 win = win_loss_matrix.matrix.row(i).sum
799 loss = win_loss_matrix.matrix.col(i).sum
801 yaml["players"][rating_group][p] =
802 { 'name' => p.split("+")[0],
803 'rating_group' => rating_group,
804 'rate' => rating.rate[i],
805 'last_modified' => $players_time[p].dup,
813 non_rated_group = 999 # large enough
814 yaml["players"][non_rated_group] = {}
815 $players.each_key do |id|
816 # skip players who have already been rated
818 (0..rating_group).each do |i|
819 found = true if yaml["players"][i][id]
824 v = GSL::Vector[0, 0]
825 $players[id].each_value {|value| v += value}
826 next if v[0] < 1 && v[1] < 1
828 yaml["players"][non_rated_group][id] =
829 { 'name' => id.split("+")[0],
830 'rating_group' => non_rated_group,
832 'last_modified' => $players_time[id].dup,
836 unless validate(yaml)
837 $stderr.puts "Aborted. It did not result in valid ratings."
838 $stderr.puts yaml.to_yaml if $DEBUG
848 # vim: ts=2 sw=2 sts=0