OSDN Git Service

Enhanced the CSA Login mode to accept a turn preference.
[shogi-server/shogi-server.git] / mk_rate
1 #!/usr/bin/ruby
2 # $Id$
3 #
4 # Author:: Daigo Moriwaki
5 # Homepage:: http://sourceforge.jp/projects/shogi-server/
6 #
7 #--
8 # Copyright (C) 2006-2009 Daigo Moriwaki <daigo at debian dot org>
9 #
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.
14 #
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.
19 #
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
23 #++
24 #
25 # == Synopsis
26 #
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.
29 #
30 # == Usage
31 #
32 # ./mk_rate [options] DIR..
33
34 # DIR::
35 #   CSA files are recursively looked up the directories.
36 #
37 # --base-date::
38 #   a base time point for this calicuration (default now). Ex. '2009-10-31'
39 #
40 # --half-life::
41 #   n [days] (default 60)
42 #   
43 # --half-life-ignore::
44 #   m [days] (default  7)
45 #   after m days, the half-life effect works
46 #
47 # --fixed-rate-player::
48 #   player whose rate is fixed at the rate
49 #
50 # --fixed-rate::
51 #   rate 
52 #
53 # --skip-draw-games::
54 #   skip draw games. [default: draw games are counted in as 0.5 win and 0.5
55 #   lost.]
56 #
57 # --help::
58 #   show this message
59 #
60 # == PREREQUIRE
61 #
62 # Sample Command lines that isntall prerequires will work on Debian.
63 #
64 # * Ruby 1.8.7
65 #
66 #   $ sudo aptitude install ruby1.8
67 #
68 # * Rubygems
69 #
70 #   $ sudo aptitude install rubygems
71 #
72 # * Ruby bindings for the GNU Scientific Library (GSL[http://rb-gsl.rubyforge.org/])
73 #
74 #   $ sudo aptitude install libgsl-ruby1.8
75 #
76 # * RGL: {Ruby Graph Library}[http://rubyforge.org/projects/rgl/]
77 #
78 #   $ sudo gem install rgl
79 #
80 # == Run
81 #
82 #   $ ./mk_rate . > players.yaml
83 #
84 # or, if you do not want the file to be update in case of errors, 
85 #
86 #   $ ./mk_rate . && ./mk_rate . > players.yaml
87 #
88 # == How players are rated
89 #
90 # The conditions that games and players are rated as following:
91 #
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. 
95 #
96
97 require 'yaml'
98 require 'time'
99 require 'getoptlong'
100 require 'gsl'
101 require 'rubygems'
102 require 'rgl/adjacency'
103 require 'rgl/connected_components'
104
105 #################################################
106 # Constants
107 #
108
109 # Count out players who play less games than $GAMES_LIMIT
110 $GAMES_LIMIT = $DEBUG ? 0 : 15
111 WIN_MARK  = "win"
112 LOSS_MARK = "lose"
113 DRAW_MARK = "draw"
114
115 # Holds players
116 $players = Hash.new
117 # Holds the last time when a player gamed
118 $players_time = Hash.new { Time.at(0) }
119
120
121 #################################################
122 # Keeps the value of the lowest key
123 #
124 class Record
125   def initialize
126     @lowest = []
127   end
128
129   def set(key, value)
130     if @lowest.empty? || key < @lowest[0]
131       @lowest = [key, value]
132     end
133   end
134
135   def get
136     if @lowest.empty?
137       nil
138     else
139       @lowest[1]
140     end
141   end
142 end
143
144 #################################################
145 # Calculates rates of every player from a Win Loss GSL::Matrix
146 #
147 class Rating
148   include Math
149
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
154   
155   # Convergence limit to stop Newton method.
156   ERROR_LIMIT = 1.0e-3
157   # Stop Newton method after this iterations.
158   COUNT_MAX = 500
159
160   # Average rate among the players
161   AVERAGE_RATE = 1000
162
163   
164   ###############
165   # Class methods
166   #  
167   
168   ##
169   # Calcurates the average of the vector.
170   #
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)]
174     vector
175   end
176
177   ##################
178   # Instance methods
179   #
180   def initialize(win_loss_matrix)
181     @record = Record.new
182     @n = win_loss_matrix
183     case @n
184     when GSL::Matrix, GSL::Matrix::Int
185       @size = @n.size1
186     when ::Matrix
187       @size = @n.row_size
188     else
189       raise ArgumentError
190     end
191     initial_rate
192   end
193   attr_reader :rate, :n
194
195   def player_vector
196     GSL::Vector[*
197       (0...@size).collect {|k| yield k}
198     ]
199   end
200
201   def each_player
202     (0...@size).each {|k| yield k}
203   end
204
205   ##
206   # The possibility that the player k will beet the player i.
207   #
208   def win_rate(k,i)
209     1.0/(1.0 + exp(@rate[i]-@rate[k]))
210   end
211
212   ##
213   # Most possible equation
214   #
215   def func_vector
216     player_vector do|k| 
217       sum = 0.0
218       each_player do |i|
219         next if i == k
220         sum += @n[k,i] * win_rate(i,k) - @n[i,k] * win_rate(k,i) 
221       end
222       sum * 2.0
223     end
224   end
225
226   ##
227   #           / f0/R0 f0/R1 f0/R2 ... \
228   # dfk/dRj = | f1/R0 f1/R1 f1/R2 ... |
229   #           \ f2/R0 f2/R1 f2/R2 ... /
230   def d_func(k,j)
231     sum = 0.0
232     if k == j
233       each_player do |i|
234         next if i == k
235         sum += win_rate(i,k) * win_rate(k,i) * (@n[k,i] + @n[i,k])
236       end
237       sum *= -2.0
238     else # k != j
239       sum = 2.0 * win_rate(j,k) * win_rate(k,j) * (@n[k,j] + @n[j,k])
240     end
241     sum
242   end
243
244   ##
245   # Jacobi matrix of the func().
246   #   m00 m01
247   #   m10 m11
248   #
249   def j_matrix
250     GSL::Matrix[*
251       (0...@size).collect do |k|
252         (0...@size).collect do |j|
253           d_func(k,j)
254         end
255       end
256     ]
257   end
258
259   ##
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.
263   #
264   def initial_rate
265     possibility = 
266       player_vector do |k|
267         v = GSL::Vector[0, 0]
268         each_player do |i|
269           next if k == i
270           v += GSL::Vector[@n[k,i], @n[i,k]]
271         end
272         v.nrm2 < 1 ? 0 : v[0] / (v[0] + v[1])
273       end
274     rank = possibility.sort_index
275     @rate = player_vector do |k|
276       K*500 * (rank[k]+1) / @size
277     end
278     average!
279   end
280
281   ##
282   # Resets @rate as the higher the current win probablity of a player is, 
283   # the greater points he takes. 
284   #
285   def initial_rate2
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
290     end
291     average!
292   end
293
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
298       return
299     end
300     if mu < 1e-4
301       @record.set(func_vector.nrm2, @rate)
302       initial_rate2
303       return
304     end
305     $stderr.puts "mu: %f " % [mu] if $DEBUG
306     deaccelrate(mu*0.5, old_rate, a, old_f_nrm2)
307   end
308
309   ##
310   # Main process to calculate ratings.
311   #
312   def rating
313     # Counter to stop the process. 
314     # Calulation in Newton method may fall in an infinite loop
315     @count = 0
316
317     # Main loop
318     begin
319       # Solve the equation: 
320       #   J*a=f
321       #   @rate_(n+1) = @rate_(n) - a
322       #
323       # f.nrm2 should approach to zero.
324       f = func_vector
325       j = j_matrix
326
327       # $stderr.puts "j: %s" % [j.inspect] if $DEBUG
328       $stderr.puts "f: %s -> %f" % [f.to_a.inspect, f.nrm2] if $DEBUG
329
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
335       
336       # Deaccelerated Newton method
337       # GSL::Vector object should be immutable.
338       old_rate   = @rate
339       old_f      = f
340       old_f_nrm2 = old_f.nrm2
341       deaccelrate(1.0, old_rate, a, old_f_nrm2)
342       @record.set(func_vector.nrm2, @rate)
343
344       $stderr.printf "|error| : %5.2e\n", a.nrm2 if $DEBUG
345
346       @count += 1
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]
350         break
351       end
352
353     end while (a.nrm2 > ERROR_LIMIT * @rate.nrm2)
354     
355     @rate = @record.get
356     $stderr.puts "resolved f: %s -> %f" %
357       [func_vector.to_a.inspect, func_vector.nrm2] if $DEBUG
358
359     @rate *= 1.0/K
360     finite!
361     self
362   end
363
364   ##
365   # Make the values of @rate finite.
366   #
367   def finite!
368     @rate = @rate.collect do |a|
369       if a.infinite?
370         a.infinite? * AVERAGE_RATE * 100
371       else
372         a
373       end
374     end
375   end
376
377   ##
378   # Flatten the values of @rate.
379   #
380   def average!(mean=0.0)
381     @rate = self.class.average(@rate, mean)
382   end
383
384   ##
385   # Translate by value
386   #
387   def translate!(value)
388     @rate += value
389   end
390
391   ##
392   # Make the values of @rate integer.
393   #
394   def integer!
395     @rate = @rate.collect do |a|
396       if a.finite?
397         a.to_i
398       elsif a.nan?
399         0
400       elsif a.infinite?
401         a.infinite? * AVERAGE_RATE * 100
402       end
403     end
404   end
405 end
406
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.
412 #
413 # This object should be immutable. If an internal state is being modified, a
414 # new object is always returned.
415 #
416 class WinLossMatrix
417
418   ###############
419   # Class methods
420   #  
421
422   def self.mk_matrix(players)
423     keys = players.keys.sort
424     size = keys.size
425     matrix =
426       GSL::Matrix[*
427       ((0...size).collect do |k|
428         p1 = keys[k]
429         p1_hash = players[p1]
430         ((0...size).collect do |j|
431           if k == j
432             0
433           else
434             p2 = keys[j]
435             v = p1_hash[p2] || Vector[0,0]
436             v[0]
437           end
438         end)
439       end)]
440     return WinLossMatrix.new(keys, matrix)
441   end
442
443   def self.mk_win_loss_matrix(players)
444     obj = mk_matrix(players)
445     return obj.filter
446   end
447
448   ##################
449   # Instance methods
450   #
451
452   # an array of player IDs; [gps+123, foo+234, ...]
453   attr_reader :keys
454
455   # matrix holds games # where player i (row index) beats player j (column index).
456   # The row and column indexes match with the keys.
457   attr_reader :matrix
458
459   def initialize(keys, matrix)
460     @keys   = keys
461     @matrix = matrix
462   end
463
464   ##
465   # Returns the size of the keys/matrix
466   #
467   def size
468     if @keys
469       @keys.size
470     else
471       nil
472     end
473   end
474
475   ##
476   # Removes players in a rows such as [1,3,5], and then returns a new
477   # object.
478   #
479   def delete_rows(rows)
480     rows = rows.sort.reverse
481
482     copied_cols = []
483     (0...size).each do |i|
484       next if rows.include?(i)
485       row = @matrix.row(i).clone
486       rows.each do |j|
487         row.delete_at(j)
488       end
489       copied_cols << row
490     end
491     if copied_cols.size == 0
492       new_matrix = GSL::Matrix.new
493     else
494       new_matrix = GSL::Matrix[*copied_cols]
495     end
496
497     new_keys = @keys.clone
498     rows.each do |j|
499       new_keys.delete_at(j)
500     end
501
502     return WinLossMatrix.new(new_keys, new_matrix)
503   end
504
505   ##
506   # Removes players who do not pass a criteria to be rated, and returns a
507   # new object.
508   # 
509   def filter
510     $stderr.puts @keys.inspect if $DEBUG
511     $stderr.puts @matrix.inspect if $DEBUG
512     delete = []  
513     (0...size).each do |i|
514       row = @matrix.row(i)
515       col = @matrix.col(i)
516       win  = row.sum
517       loss = col.sum
518       if win < 1 || loss < 1 || win + loss < $GAMES_LIMIT
519         delete << i
520       end
521     end
522
523     # The recursion ends if there is nothing to delete
524     return self if delete.empty?
525
526     new_obj = delete_rows(delete)
527     new_obj.filter
528   end
529
530   ##
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.
533   #
534   def connected_subsets
535     g = RGL::AdjacencyGraph.new
536     (0...size).each do |k|
537       (0...size).each do |i|
538         next if k == i
539         if @matrix[k,i] > 0
540           g.add_edge(k,i)
541         end
542       end
543     end
544
545     subsets = []
546     g.each_connected_component do |c|
547       new_keys = []      
548       c.each do |v|
549         new_keys << keys[v.to_s.to_i]
550       end
551       subsets << new_keys
552     end
553
554     subsets = subsets.sort {|a,b| b.size <=> a.size}
555
556     result = subsets.collect do |keys|
557       matrix =
558         GSL::Matrix[*
559         ((0...keys.size).collect do |k|
560           p1 = @keys.index(keys[k])
561           ((0...keys.size).collect do |j|
562             if k == j
563               0
564             else
565               p2 = @keys.index(keys[j])
566               @matrix[p1,p2]
567             end
568           end)
569         end)]
570       WinLossMatrix.new(keys, matrix)
571     end
572
573     return result
574   end
575
576   def to_s
577     "size : #{@keys.size}" + "\n" +
578     @keys.inspect + "\n" + 
579     @matrix.inspect
580   end
581
582 end
583
584
585 #################################################
586 # Main methods
587 #
588
589 # Half-life effect
590 # After NHAFE_LIFE days value will get half.
591 # 0.693 is constant, where exp(0.693) ~ 0.5
592 def half_life(days)
593   if days < $options["half-life-ignore"]
594     return 1.0
595   else
596     Math::exp(-0.693/$options["half-life"]*(days-$options["half-life-ignore"]))
597   end
598 end
599
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)]
606 end
607
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)]
614 end
615
616 def _add_time(player, time)
617   $players_time[player] = time if $players_time[player] < time
618 end
619
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"]
627       return
628     else
629       _add_draw(black_name, white_name, time)
630     end
631   else
632     raise "Never reached!"
633   end
634   _add_time(black_name, time)
635   _add_time(white_name, time)
636 end
637
638 def identify_id(id)
639   if /@NORATE\+/ =~ id # the player having @NORATE in the name should not be rated
640     return nil
641   end
642   id.gsub(/@.*?\+/,"+")
643 end
644
645 # Parse a game result line
646 #
647 def parse(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}"
652     return
653   end
654
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)
660
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)
664   end
665 end
666
667 def validate(yaml)
668   yaml["players"].each do |group_key, group|
669     group.each do |player_key, player|
670       rate = player['rate']
671       next unless rate
672       if rate > 10000 || rate < -10000
673         return false
674       end
675     end
676   end
677   return true
678 end
679
680 def usage(io)
681     io.puts <<EOF
682 USAGE: #{$0} [options] DIR..
683   DIR                where CSA files are looked up recursively
684 OPTOINS:
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
690   --fixed-rate        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
694 EOF
695 end
696
697 def main
698   $options = Hash::new
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])
707   parser.quiet = true
708   begin
709     parser.each_option do |name, arg|
710       name.sub!(/^--/, '')
711       $options[name] = arg.dup
712     end
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) 
716       usage($stderr)
717       exit 1
718     end
719   rescue
720     usage($stderr)
721     raise parser.error_message
722   end
723   if $options["help"]
724     usage($stdout) 
725     exit 0
726   end
727   if $options["base-date"]
728     $options["base-date"] = Time::parse $options["base-date"]
729   else
730     $options["base-date"] = Time.now
731   end
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"]
737
738   if ARGV.empty?
739     while line = $stdin.gets do
740       parse line.strip
741     end
742   else
743     while file = ARGV.shift do
744       File.open(file) do |f|
745         f.each_line do |line|
746           parse line.strip
747         end
748       end 
749     end
750   end
751
752   yaml = {} 
753   yaml["players"] = {}
754   rating_group = 0
755   if $players.size > 0
756     obj = WinLossMatrix::mk_win_loss_matrix($players)
757     obj.connected_subsets.each do |win_loss_matrix|
758       yaml["players"][rating_group] = {}
759
760       rating = Rating.new(win_loss_matrix.matrix)
761       rating.rating
762       rating.average!(Rating::AVERAGE_RATE)
763       rating.integer!
764
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
769         unless index
770           win_loss_matrix.keys.each_with_index do |p, i|
771             if %r!#{$options["fixed-rate-player"]}! =~ p
772               index = i
773             end
774           end
775         end
776         if index
777           the_rate = rating.rate[index]
778           rating.translate!($options["fixed-rate"] - the_rate)
779         end
780       end
781
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
785
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,
791             'win'  => win,
792             'loss' => loss}
793       end
794       rating_group += 1
795     end
796   end
797   rating_group -= 1
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
802     found = false
803     (0..rating_group).each do |i|
804        found = true if yaml["players"][i][id]
805        break if found
806     end
807     next if found
808
809     v = GSL::Vector[0, 0]
810     $players[id].each_value {|value| v += value}
811     next if v[0] < 1 && v[1] < 1
812
813     yaml["players"][non_rated_group][id] =
814       { 'name' => id.split("+")[0],
815         'rating_group' => non_rated_group,
816         'rate' => 0,
817         'last_modified' => $players_time[id].dup,
818         'win'  => v[0],
819         'loss' => v[1]}
820   end
821   unless validate(yaml)
822     $stderr.puts "Aborted. It did not result in valid ratings."
823     $stderr.puts yaml.to_yaml if $DEBUG
824     exit 10
825   end
826   puts yaml.to_yaml
827 end
828
829 if __FILE__ == $0
830   main
831 end
832
833 # vim: ts=2 sw=2 sts=0