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
44 # --fixed-rate-player::
45 # player whose rate is fixed at the rate
55 # Sample Command lines that isntall prerequires will work on Debian.
59 # $ sudo aptitude install ruby1.8
63 # $ sudo aptitude install rubygems
65 # * Ruby bindings for the GNU Scientific Library (GSL[http://rb-gsl.rubyforge.org/])
67 # $ sudo aptitude install libgsl-ruby1.8
69 # * RGL: {Ruby Graph Library}[http://rubyforge.org/projects/rgl/]
71 # $ sudo gem install rgl
75 # $ ./mk_rate . > players.yaml
77 # or, if you do not want the file to be update in case of errors,
79 # $ ./mk_rate . && ./mk_rate . > players.yaml
81 # == How players are rated
83 # The conditions that games and players are rated as following:
85 # * Rated games, which were played by both rated players.
86 # * Rated players, who logged in the server with a name followed by a trip: "name,trip".
87 # * (Rated) players, who played more than $GAMES_LIMIT [15] (rated) games.
96 require 'rgl/adjacency'
97 require 'rgl/connected_components'
99 #################################################
103 # Count out players who play less games than $GAMES_LIMIT
104 $GAMES_LIMIT = $DEBUG ? 0 : 15
111 # Holds the last time when a player gamed
112 $players_time = Hash.new { Time.at(0) }
115 #################################################
116 # Keeps the value of the lowest key
124 if @lowest.empty? || key < @lowest[0]
125 @lowest = [key, value]
138 #################################################
139 # Calculates rates of every player from a Win Loss GSL::Matrix
144 # The model of the win possibility is 1/(1 + 10^(-d/400)).
145 # The equation in this class is 1/(1 + e^(-Kd)).
146 # So, K should be calculated like this.
147 K = Math.log(10.0) / 400.0
149 # Convergence limit to stop Newton method.
151 # Stop Newton method after this iterations.
154 # Average rate among the players
163 # Calcurates the average of the vector.
165 def Rating.average(vector, mean=0.0)
166 sum = Array(vector).inject(0.0) {|sum, n| sum + n}
167 vector -= GSL::Vector[*Array.new(vector.size, sum/vector.size - mean)]
174 def initialize(win_loss_matrix)
178 when GSL::Matrix, GSL::Matrix::Int
187 attr_reader :rate, :n
191 (0...@size).collect {|k| yield k}
196 (0...@size).each {|k| yield k}
200 # The possibility that the player k will beet the player i.
203 1.0/(1.0 + exp(@rate[i]-@rate[k]))
207 # Most possible equation
214 sum += @n[k,i] * win_rate(i,k) - @n[i,k] * win_rate(k,i)
221 # / f0/R0 f0/R1 f0/R2 ... \
222 # dfk/dRj = | f1/R0 f1/R1 f1/R2 ... |
223 # \ f2/R0 f2/R1 f2/R2 ... /
229 sum += win_rate(i,k) * win_rate(k,i) * (@n[k,i] + @n[i,k])
233 sum = 2.0 * win_rate(j,k) * win_rate(k,j) * (@n[k,j] + @n[j,k])
239 # Jacobi matrix of the func().
245 (0...@size).collect do |k|
246 (0...@size).collect do |j|
254 # The initial value of the rate, which is of very importance for Newton
255 # method. This is based on my huristics; the higher the win probablity of
256 # a player is, the greater points he takes.
261 v = GSL::Vector[0, 0]
264 v += GSL::Vector[@n[k,i], @n[i,k]]
266 v.nrm2 < 1 ? 0 : v[0] / (v[0] + v[1])
268 rank = possibility.sort_index
269 @rate = player_vector do |k|
270 K*500 * (rank[k]+1) / @size
276 # Resets @rate as the higher the current win probablity of a player is,
277 # the greater points he takes.
280 @rate = @record.get || @rate
281 rank = @rate.sort_index
282 @rate = player_vector do |k|
283 K*@count*1.5 * (rank[k]+1) / @size
288 # mu is the deaccelrating parameter in Deaccelerated Newton method
289 def deaccelrate(mu, old_rate, a, old_f_nrm2)
290 @rate = old_rate - a * mu
291 if func_vector.nrm2 < (1 - mu / 4.0 ) * old_f_nrm2 then
295 @record.set(func_vector.nrm2, @rate)
299 $stderr.puts "mu: %f " % [mu] if $DEBUG
300 deaccelrate(mu*0.5, old_rate, a, old_f_nrm2)
304 # Main process to calculate ratings.
307 # Counter to stop the process.
308 # Calulation in Newton method may fall in an infinite loop
313 # Solve the equation:
315 # @rate_(n+1) = @rate_(n) - a
317 # f.nrm2 should approach to zero.
321 # $stderr.puts "j: %s" % [j.inspect] if $DEBUG
322 $stderr.puts "f: %s -> %f" % [f.to_a.inspect, f.nrm2] if $DEBUG
324 # GSL::Linalg::LU.solve or GSL::Linalg::HH.solve would be available instead.
325 #a = GSL::Linalg::HH.solve(j, f)
326 a, = GSL::MultiFit::linear(j, f)
327 a = self.class.average(a)
328 # $stderr.puts "a: %s -> %f" % [a.to_a.inspect, a.nrm2] if $DEBUG
330 # Deaccelerated Newton method
331 # GSL::Vector object should be immutable.
334 old_f_nrm2 = old_f.nrm2
335 deaccelrate(1.0, old_rate, a, old_f_nrm2)
336 @record.set(func_vector.nrm2, @rate)
338 $stderr.printf "|error| : %5.2e\n", a.nrm2 if $DEBUG
341 if @count > COUNT_MAX
342 $stderr.puts "Values seem to oscillate. Stopped the process."
343 $stderr.puts "f: %s -> %f" % [func_vector.to_a.inspect, func_vector.nrm2]
347 end while (a.nrm2 > ERROR_LIMIT * @rate.nrm2)
350 $stderr.puts "resolved f: %s -> %f" %
351 [func_vector.to_a.inspect, func_vector.nrm2] if $DEBUG
359 # Make the values of @rate finite.
362 @rate = @rate.collect do |a|
364 a.infinite? * AVERAGE_RATE * 100
372 # Flatten the values of @rate.
374 def average!(mean=0.0)
375 @rate = self.class.average(@rate, mean)
381 def translate!(value)
386 # Make the values of @rate integer.
389 @rate = @rate.collect do |a|
395 a.infinite? * AVERAGE_RATE * 100
401 #################################################
402 # Encapsulate a pair of keys and win loss matrix.
403 # - keys is an array of player IDs; [gps+123, foo+234, ...]
404 # - matrix holds games # where player i (row index) beats player j (column index).
405 # The row and column indexes match with the keys.
407 # This object should be immutable. If an internal state is being modified, a
408 # new object is always returned.
416 def self.mk_matrix(players)
417 keys = players.keys.sort
421 ((0...size).collect do |k|
423 p1_hash = players[p1]
424 ((0...size).collect do |j|
429 v = p1_hash[p2] || Vector[0,0]
434 return WinLossMatrix.new(keys, matrix)
437 def self.mk_win_loss_matrix(players)
438 obj = mk_matrix(players)
440 obj, ret = obj.filter
450 # an array of player IDs; [gps+123, foo+234, ...]
453 # matrix holds games # where player i (row index) beats player j (column index).
454 # The row and column indexes match with the keys.
457 def initialize(keys, matrix)
463 # Returns the size of the keys/matrix
474 # Removes the delete_index'th player and returns a new object.
476 # [ 1 0 0 * [ 1 2 3 * [ 1 0 = [ 1 3
477 # 0 0 1 ] 4 5 6 0 0 7 9 ]
480 def delete_row(delete_index)
482 if delete_index == 0 && @matrix.size1 == 1 && @matrix.size2 == 1
483 new_matrix = GSL::Matrix.new
487 next if i == delete_index
488 v = Array.new(size, 0)
492 m1 = GSL::Matrix[*a1]
495 new_matrix = m1 * @matrix * m2
498 new_keys = @keys.clone
499 new_keys.delete_at(delete_index)
502 raise "The new matrix is null!"
505 return WinLossMatrix.new(new_keys, new_matrix)
509 # Removes players in a rows; [1,3,5]
511 def delete_rows(rows)
513 rows.sort.reverse.each do |index|
514 obj = obj.delete_row(index)
520 # Removes players who do not pass a criteria to be rated, and returns a
524 $stderr.puts @keys.inspect if $DEBUG
525 $stderr.puts @matrix.inspect if $DEBUG
527 (0...size).each do |i|
532 if win < 1 || loss < 1 || win + loss < $GAMES_LIMIT
537 # The recursion ends if there is nothing to delete
538 return [self, true] if delete.empty?
540 new_obj = delete_rows(delete)
541 return [new_obj, false]
545 # Cuts self into connecting groups such as each player in a group has at least
546 # one game with other players in the group. Returns them as an array.
548 def connected_subsets
549 g = RGL::AdjacencyGraph.new
550 (0...size).each do |k|
551 (0...size).each do |i|
560 g.each_connected_component do |c|
563 new_keys << keys[v.to_s.to_i]
568 subsets = subsets.sort {|a,b| b.size <=> a.size}
570 result = subsets.collect do |keys|
573 ((0...keys.size).collect do |k|
574 p1 = @keys.index(keys[k])
575 ((0...keys.size).collect do |j|
579 p2 = @keys.index(keys[j])
584 WinLossMatrix.new(keys, matrix)
591 "size : #{@keys.size}" + "\n" +
592 @keys.inspect + "\n" +
599 #################################################
604 # After NHAFE_LIFE days value will get half.
605 # 0.693 is constant, where exp(0.693) ~ 0.5
607 if days < $options["half-life-ignore"]
610 Math::exp(-0.693/$options["half-life"]*(days-$options["half-life-ignore"]))
614 def _add_win_loss(winner, loser, time)
615 how_long_days = (Time.now - time)/(3600*24)
616 $players[winner] ||= Hash.new { GSL::Vector[0,0] }
617 $players[loser] ||= Hash.new { GSL::Vector[0,0] }
618 $players[winner][loser] += GSL::Vector[1.0*half_life(how_long_days),0]
619 $players[loser][winner] += GSL::Vector[0,1.0*half_life(how_long_days)]
622 def _add_time(player, time)
623 $players_time[player] = time if $players_time[player] < time
626 def add(black_mark, black_name, white_name, white_mark, time)
627 if black_mark == WIN_MARK && white_mark == LOSS_MARK
628 _add_win_loss(black_name, white_name, time)
629 elsif black_mark == LOSS_MARK && white_mark == WIN_MARK
630 _add_win_loss(white_name, black_name, time)
631 elsif black_mark == DRAW_MARK && white_mark == DRAW_MARK
634 raise "Never reached!"
636 _add_time(black_name, time)
637 _add_time(white_name, time)
641 if /@NORATE\+/ =~ id # the player having @NORATE in the name should not be rated
644 id.gsub(/@.*?\+/,"+")
656 lines = StringIO.new File.open(file).read
658 lines.each_line do |str|
661 black_name = $1.strip
663 white_name = $1.strip
664 when /^'summary:(.*)$/
665 state, p1, p2 = $1.split(":").map {|a| a.strip}
666 return if state == "abnormal"
667 p1_name, p1_mark = p1.split(" ")
668 p2_name, p2_mark = p2.split(" ")
669 if p1_name == black_name
670 black_name, black_mark = p1_name, p1_mark
671 white_name, white_mark = p2_name, p2_mark
672 elsif p2_name == black_name
673 black_name, black_mark = p2_name, p2_mark
674 white_name, white_mark = p1_name, p1_mark
676 raise "Never reach!: #{black} #{white} #{p3} #{p2}"
678 when /^'\$END_TIME:(.*)$/
679 time = Time.parse($1.strip)
683 if /^'rating:(.*)$/ =~ lines.string
684 black_id, white_id = $1.split(":").map {|a| a.strip}
685 black_id = identify_id(black_id)
686 white_id = identify_id(white_id)
687 if black_id && white_id && (black_id != white_id) &&
688 black_mark && white_mark
689 add(black_mark, black_id, white_id, white_mark, time)
696 USAGE: #{$0} dir [...]
702 yaml["players"].each do |group_key, group|
703 group.each do |player_key, player|
704 rate = player['rate']
706 if rate > 10000 || rate < -10000
716 USAGE: #{$0} [options] DIR..
717 DIR where CSA files are looked up recursively
719 --half-life n [days] (default 60)
720 --half-life-ignore m [days] (default 7)
721 after m days, half-life effect works
722 --fixed-rate-player player whose rate is fixed at the rate
724 --help show this message
730 parser = GetoptLong.new(
731 ["--half-life", GetoptLong::REQUIRED_ARGUMENT],
732 ["--half-life-ignore", GetoptLong::REQUIRED_ARGUMENT],
733 ["--help", "-h", GetoptLong::NO_ARGUMENT],
734 ["--fixed-rate-player", GetoptLong::REQUIRED_ARGUMENT],
735 ["--fixed-rate", GetoptLong::REQUIRED_ARGUMENT])
738 parser.each_option do |name, arg|
740 $options[name] = arg.dup
742 if ( $options["fixed-rate-player"] && !$options["fixed-rate"]) ||
743 (!$options["fixed-rate-player"] && $options["fixed-rate"]) ||
744 ( $options["fixed-rate-player"] && $options["fixed-rate"].to_i <= 0)
750 raise parser.error_message
756 $options["half-life"] ||= 60
757 $options["half-life"] = $options["half-life"].to_i
758 $options["half-life-ignore"] ||= 7
759 $options["half-life-ignore"] = $options["half-life-ignore"].to_i
760 $options["fixed-rate"] = $options["fixed-rate"].to_i if $options["fixed-rate"]
762 while dir = ARGV.shift do
763 Dir.glob( File.join(dir, "**", "*.csa") ) {|f| grep(f)}
770 obj = WinLossMatrix::mk_win_loss_matrix($players)
771 obj.connected_subsets.each do |win_loss_matrix|
772 yaml["players"][rating_group] = {}
774 rating = Rating.new(win_loss_matrix.matrix)
776 rating.average!(Rating::AVERAGE_RATE)
779 if $options["fixed-rate-player"]
780 # first, try exact match
781 index = win_loss_matrix.keys.index($options["fixed-rate-player"])
782 # second, try regular match
784 win_loss_matrix.keys.each_with_index do |p, i|
785 if %r!#{$options["fixed-rate-player"]}! =~ p
791 the_rate = rating.rate[index]
792 rating.translate!($options["fixed-rate"] - the_rate)
796 win_loss_matrix.keys.each_with_index do |p, i| # player_id, index#
797 win = win_loss_matrix.matrix.row(i).sum
798 loss = win_loss_matrix.matrix.col(i).sum
800 yaml["players"][rating_group][p] =
801 { 'name' => p.split("+")[0],
802 'rating_group' => rating_group,
803 'rate' => rating.rate[i],
804 'last_modified' => $players_time[p].dup,
812 non_rated_group = 999 # large enough
813 yaml["players"][non_rated_group] = {}
814 $players.each_key do |id|
815 # skip players who have already been rated
817 (0..rating_group).each do |i|
818 found = true if yaml["players"][i][id]
823 v = GSL::Vector[0, 0]
824 $players[id].each_value {|value| v += value}
825 next if v[0] < 1 && v[1] < 1
827 yaml["players"][non_rated_group][id] =
828 { 'name' => id.split("+")[0],
829 'rating_group' => non_rated_group,
831 'last_modified' => $players_time[id].dup,
835 unless validate(yaml)
836 $stderr.puts "Aborted. It did not result in valid ratings."
837 $stderr.puts yaml.to_yaml if $DEBUG
847 # vim: ts=2 sw=2 sts=0