OSDN Git Service

5c8dd04aa194d0373482d2bc5bc588871f1527fa
[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-2008 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 # --half-life::
38 #   n [days] (default 60)
39 #   
40 # --half-life-ignore::
41 #   m [days] (default  7)
42 #   after m days, the half-life effect works
43 #
44 # --fixed-rate-player::
45 #   player whose rate is fixed at the rate
46 #
47 # --fixed-rate::
48 #   rate 
49 #
50 # --help::
51 #   show this message
52 #
53 # == PREREQUIRE
54 #
55 # Sample Command lines that isntall prerequires will work on Debian.
56 #
57 # * Ruby 1.8.7
58 #
59 #   $ sudo aptitude install ruby1.8
60 #
61 # * Rubygems
62 #
63 #   $ sudo aptitude install rubygems
64 #
65 # * Ruby bindings for the GNU Scientific Library (GSL[http://rb-gsl.rubyforge.org/])
66 #
67 #   $ sudo aptitude install libgsl-ruby1.8
68 #
69 # * RGL: {Ruby Graph Library}[http://rubyforge.org/projects/rgl/]
70 #
71 #   $ sudo gem install rgl
72 #
73 # == Run
74 #
75 #   $ ./mk_rate . > players.yaml
76 #
77 # or, if you do not want the file to be update in case of errors, 
78 #
79 #   $ ./mk_rate . && ./mk_rate . > players.yaml
80 #
81 # == How players are rated
82 #
83 # The conditions that games and players are rated as following:
84 #
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. 
88 #
89
90 require 'yaml'
91 require 'time'
92 require 'getoptlong'
93 require 'gsl'
94 require 'rubygems'
95 require 'rgl/adjacency'
96 require 'rgl/connected_components'
97
98 #################################################
99 # Constants
100 #
101
102 # Count out players who play less games than $GAMES_LIMIT
103 $GAMES_LIMIT = $DEBUG ? 0 : 15
104 WIN_MARK  = "win"
105 LOSS_MARK = "lose"
106 DRAW_MARK = "draw"
107
108 # Holds players
109 $players = Hash.new
110 # Holds the last time when a player gamed
111 $players_time = Hash.new { Time.at(0) }
112
113
114 #################################################
115 # Keeps the value of the lowest key
116 #
117 class Record
118   def initialize
119     @lowest = []
120   end
121
122   def set(key, value)
123     if @lowest.empty? || key < @lowest[0]
124       @lowest = [key, value]
125     end
126   end
127
128   def get
129     if @lowest.empty?
130       nil
131     else
132       @lowest[1]
133     end
134   end
135 end
136
137 #################################################
138 # Calculates rates of every player from a Win Loss GSL::Matrix
139 #
140 class Rating
141   include Math
142
143   # The model of the win possibility is 1/(1 + 10^(-d/400)).
144   # The equation in this class is 1/(1 + e^(-Kd)).
145   # So, K should be calculated like this.
146   K = Math.log(10.0) / 400.0
147   
148   # Convergence limit to stop Newton method.
149   ERROR_LIMIT = 1.0e-3
150   # Stop Newton method after this iterations.
151   COUNT_MAX = 500
152
153   # Average rate among the players
154   AVERAGE_RATE = 1000
155
156   
157   ###############
158   # Class methods
159   #  
160   
161   ##
162   # Calcurates the average of the vector.
163   #
164   def Rating.average(vector, mean=0.0)
165     sum = Array(vector).inject(0.0) {|sum, n| sum + n}
166     vector -= GSL::Vector[*Array.new(vector.size, sum/vector.size - mean)]
167     vector
168   end
169
170   ##################
171   # Instance methods
172   #
173   def initialize(win_loss_matrix)
174     @record = Record.new
175     @n = win_loss_matrix
176     case @n
177     when GSL::Matrix, GSL::Matrix::Int
178       @size = @n.size1
179     when ::Matrix
180       @size = @n.row_size
181     else
182       raise ArgumentError
183     end
184     initial_rate
185   end
186   attr_reader :rate, :n
187
188   def player_vector
189     GSL::Vector[*
190       (0...@size).collect {|k| yield k}
191     ]
192   end
193
194   def each_player
195     (0...@size).each {|k| yield k}
196   end
197
198   ##
199   # The possibility that the player k will beet the player i.
200   #
201   def win_rate(k,i)
202     1.0/(1.0 + exp(@rate[i]-@rate[k]))
203   end
204
205   ##
206   # Most possible equation
207   #
208   def func_vector
209     player_vector do|k| 
210       sum = 0.0
211       each_player do |i|
212         next if i == k
213         sum += @n[k,i] * win_rate(i,k) - @n[i,k] * win_rate(k,i) 
214       end
215       sum * 2.0
216     end
217   end
218
219   ##
220   #           / f0/R0 f0/R1 f0/R2 ... \
221   # dfk/dRj = | f1/R0 f1/R1 f1/R2 ... |
222   #           \ f2/R0 f2/R1 f2/R2 ... /
223   def d_func(k,j)
224     sum = 0.0
225     if k == j
226       each_player do |i|
227         next if i == k
228         sum += win_rate(i,k) * win_rate(k,i) * (@n[k,i] + @n[i,k])
229       end
230       sum *= -2.0
231     else # k != j
232       sum = 2.0 * win_rate(j,k) * win_rate(k,j) * (@n[k,j] + @n[j,k])
233     end
234     sum
235   end
236
237   ##
238   # Jacobi matrix of the func().
239   #   m00 m01
240   #   m10 m11
241   #
242   def j_matrix
243     GSL::Matrix[*
244       (0...@size).collect do |k|
245         (0...@size).collect do |j|
246           d_func(k,j)
247         end
248       end
249     ]
250   end
251
252   ##
253   # The initial value of the rate, which is of very importance for Newton
254   # method.  This is based on my huristics; the higher the win probablity of
255   # a player is, the greater points he takes.
256   #
257   def initial_rate
258     possibility = 
259       player_vector do |k|
260         v = GSL::Vector[0, 0]
261         each_player do |i|
262           next if k == i
263           v += GSL::Vector[@n[k,i], @n[i,k]]
264         end
265         v.nrm2 < 1 ? 0 : v[0] / (v[0] + v[1])
266       end
267     rank = possibility.sort_index
268     @rate = player_vector do |k|
269       K*500 * (rank[k]+1) / @size
270     end
271     average!
272   end
273
274   ##
275   # Resets @rate as the higher the current win probablity of a player is, 
276   # the greater points he takes. 
277   #
278   def initial_rate2
279     @rate = @record.get || @rate
280     rank = @rate.sort_index
281     @rate = player_vector do |k|
282       K*@count*1.5 * (rank[k]+1) / @size
283     end
284     average!
285   end
286
287   # mu is the deaccelrating parameter in Deaccelerated Newton method
288   def deaccelrate(mu, old_rate, a, old_f_nrm2)
289     @rate = old_rate - a * mu
290     if func_vector.nrm2 < (1 - mu / 4.0 ) * old_f_nrm2 then
291       return
292     end
293     if mu < 1e-4
294       @record.set(func_vector.nrm2, @rate)
295       initial_rate2
296       return
297     end
298     $stderr.puts "mu: %f " % [mu] if $DEBUG
299     deaccelrate(mu*0.5, old_rate, a, old_f_nrm2)
300   end
301
302   ##
303   # Main process to calculate ratings.
304   #
305   def rating
306     # Counter to stop the process. 
307     # Calulation in Newton method may fall in an infinite loop
308     @count = 0
309
310     # Main loop
311     begin
312       # Solve the equation: 
313       #   J*a=f
314       #   @rate_(n+1) = @rate_(n) - a
315       #
316       # f.nrm2 should approach to zero.
317       f = func_vector
318       j = j_matrix
319
320       # $stderr.puts "j: %s" % [j.inspect] if $DEBUG
321       $stderr.puts "f: %s -> %f" % [f.to_a.inspect, f.nrm2] if $DEBUG
322
323       # GSL::Linalg::LU.solve or GSL::Linalg::HH.solve would be available instead.
324       #a = GSL::Linalg::HH.solve(j, f)
325       a, = GSL::MultiFit::linear(j, f)
326       a = self.class.average(a)
327       # $stderr.puts "a: %s -> %f" % [a.to_a.inspect, a.nrm2] if $DEBUG
328       
329       # Deaccelerated Newton method
330       # GSL::Vector object should be immutable.
331       old_rate   = @rate
332       old_f      = f
333       old_f_nrm2 = old_f.nrm2
334       deaccelrate(1.0, old_rate, a, old_f_nrm2)
335       @record.set(func_vector.nrm2, @rate)
336
337       $stderr.printf "|error| : %5.2e\n", a.nrm2 if $DEBUG
338
339       @count += 1
340       if @count > COUNT_MAX
341         $stderr.puts "Values seem to oscillate. Stopped the process."
342         $stderr.puts "f: %s -> %f" % [func_vector.to_a.inspect, func_vector.nrm2]
343         break
344       end
345
346     end while (a.nrm2 > ERROR_LIMIT * @rate.nrm2)
347     
348     @rate = @record.get
349     $stderr.puts "resolved f: %s -> %f" %
350       [func_vector.to_a.inspect, func_vector.nrm2] if $DEBUG
351
352     @rate *= 1.0/K
353     finite!
354     self
355   end
356
357   ##
358   # Make the values of @rate finite.
359   #
360   def finite!
361     @rate = @rate.collect do |a|
362       if a.infinite?
363         a.infinite? * AVERAGE_RATE * 100
364       else
365         a
366       end
367     end
368   end
369
370   ##
371   # Flatten the values of @rate.
372   #
373   def average!(mean=0.0)
374     @rate = self.class.average(@rate, mean)
375   end
376
377   ##
378   # Translate by value
379   #
380   def translate!(value)
381     @rate += value
382   end
383
384   ##
385   # Make the values of @rate integer.
386   #
387   def integer!
388     @rate = @rate.collect do |a|
389       if a.finite?
390         a.to_i
391       elsif a.nan?
392         0
393       elsif a.infinite?
394         a.infinite? * AVERAGE_RATE * 100
395       end
396     end
397   end
398 end
399
400 #################################################
401 # Encapsulate a pair of keys and win loss matrix.
402 #   - keys is an array of player IDs; [gps+123, foo+234, ...]
403 #   - matrix holds games # where player i (row index) beats player j (column index).
404 #     The row and column indexes match with the keys.
405 #
406 # This object should be immutable. If an internal state is being modified, a
407 # new object is always returned.
408 #
409 class WinLossMatrix
410
411   ###############
412   # Class methods
413   #  
414
415   def self.mk_matrix(players)
416     keys = players.keys.sort
417     size = keys.size
418     matrix =
419       GSL::Matrix[*
420       ((0...size).collect do |k|
421         p1 = keys[k]
422         p1_hash = players[p1]
423         ((0...size).collect do |j|
424           if k == j
425             0
426           else
427             p2 = keys[j]
428             v = p1_hash[p2] || Vector[0,0]
429             v[0]
430           end
431         end)
432       end)]
433     return WinLossMatrix.new(keys, matrix)
434   end
435
436   def self.mk_win_loss_matrix(players)
437     obj = mk_matrix(players)
438     return obj.filter
439   end
440
441   ##################
442   # Instance methods
443   #
444
445   # an array of player IDs; [gps+123, foo+234, ...]
446   attr_reader :keys
447
448   # matrix holds games # where player i (row index) beats player j (column index).
449   # The row and column indexes match with the keys.
450   attr_reader :matrix
451
452   def initialize(keys, matrix)
453     @keys   = keys
454     @matrix = matrix
455   end
456
457   ##
458   # Returns the size of the keys/matrix
459   #
460   def size
461     if @keys
462       @keys.size
463     else
464       nil
465     end
466   end
467
468   ##
469   # Removes a delete_index'th player and returns a new object.
470   #
471   def delete_row(delete_index)
472     copied_cols = []
473     (0...size).each do |i|
474       next if i == delete_index
475       row = @matrix.row(i).clone
476       row.delete_at(delete_index)
477       copied_cols << row
478     end
479     if copied_cols.size == 0
480       new_matrix = GSL::Matrix.new
481     else
482       new_matrix = GSL::Matrix[*copied_cols]
483     end
484     new_keys = @keys.clone
485     new_keys.delete_at(delete_index)
486     return WinLossMatrix.new(new_keys, new_matrix)
487   end
488
489   ##
490   # Removes players in a rows; [1,3,5]
491   #
492   def delete_rows(rows)
493     obj = self
494     rows.sort.reverse.each do |index|
495       obj = obj.delete_row(index)
496     end
497     obj
498   end
499
500   ##
501   # Removes players who do not pass a criteria to be rated, and returns a
502   # new object.
503   # 
504   def filter
505     $stderr.puts @keys.inspect if $DEBUG
506     $stderr.puts @matrix.inspect if $DEBUG
507     delete = []  
508     (0...size).each do |i|
509       row = @matrix.row(i)
510       col = @matrix.col(i)
511       win  = row.sum
512       loss = col.sum
513       if win < 1 || loss < 1 || win + loss < $GAMES_LIMIT
514         delete << i
515       end
516     end
517
518     # The recursion ends if there is nothing to delete
519     return self if delete.empty?
520
521     new_obj = delete_rows(delete)
522     new_obj.filter
523   end
524
525   ##
526   # Cuts self into connecting groups such as each player in a group has at least
527   # one game with other players in the group. Returns them as an array.
528   #
529   def connected_subsets
530     g = RGL::AdjacencyGraph.new
531     (0...size).each do |k|
532       (0...size).each do |i|
533         next if k == i
534         if @matrix[k,i] > 0
535           g.add_edge(k,i)
536         end
537       end
538     end
539
540     subsets = []
541     g.each_connected_component do |c|
542       new_keys = []      
543       c.each do |v|
544         new_keys << keys[v.to_s.to_i]
545       end
546       subsets << new_keys
547     end
548
549     subsets = subsets.sort {|a,b| b.size <=> a.size}
550
551     result = subsets.collect do |keys|
552       matrix =
553         GSL::Matrix[*
554         ((0...keys.size).collect do |k|
555           p1 = @keys.index(keys[k])
556           ((0...keys.size).collect do |j|
557             if k == j
558               0
559             else
560               p2 = @keys.index(keys[j])
561               @matrix[p1,p2]
562             end
563           end)
564         end)]
565       WinLossMatrix.new(keys, matrix)
566     end
567
568     return result
569   end
570
571   def to_s
572     "size : #{@keys.size}" + "\n" +
573     @keys.inspect + "\n" + 
574     @matrix.inspect
575   end
576
577 end
578
579
580 #################################################
581 # Main methods
582 #
583
584 # Half-life effect
585 # After NHAFE_LIFE days value will get half.
586 # 0.693 is constant, where exp(0.693) ~ 0.5
587 def half_life(days)
588   if days < $options["half-life-ignore"]
589     return 1.0
590   else
591     Math::exp(-0.693/$options["half-life"]*(days-$options["half-life-ignore"]))
592   end
593 end
594
595 def _add_win_loss(winner, loser, time)
596   how_long_days = (Time.now - time)/(3600*24)
597   $players[winner] ||= Hash.new { GSL::Vector[0,0] }
598   $players[loser]  ||= Hash.new { GSL::Vector[0,0] }
599   $players[winner][loser] += GSL::Vector[1.0*half_life(how_long_days),0]
600   $players[loser][winner] += GSL::Vector[0,1.0*half_life(how_long_days)]
601 end
602
603 def _add_time(player, time)
604   $players_time[player] = time if $players_time[player] < time
605 end
606
607 def add(black_mark, black_name, white_name, white_mark, time)
608   if black_mark == WIN_MARK && white_mark == LOSS_MARK
609     _add_win_loss(black_name, white_name, time)
610   elsif black_mark == LOSS_MARK && white_mark == WIN_MARK
611     _add_win_loss(white_name, black_name, time)
612   elsif black_mark == DRAW_MARK && white_mark == DRAW_MARK
613     return
614   else
615     raise "Never reached!"
616   end
617   _add_time(black_name, time)
618   _add_time(white_name, time)
619 end
620
621 def identify_id(id)
622   if /@NORATE\+/ =~ id # the player having @NORATE in the name should not be rated
623     return nil
624   end
625   id.gsub(/@.*?\+/,"+")
626 end
627
628 def grep(file)
629   str = File.open(file).read
630
631   if /^N\+(.*)$/ =~ str then black_name = $1.strip end
632   if /^N\-(.*)$/ =~ str then white_name = $1.strip end
633
634   if /^'summary:(.*)$/ =~ str
635     state, p1, p2 = $1.split(":").map {|a| a.strip}    
636     return if state == "abnormal"
637     p1_name, p1_mark = p1.split(" ")
638     p2_name, p2_mark = p2.split(" ")
639     if p1_name == black_name
640       black_name, black_mark = p1_name, p1_mark
641       white_name, white_mark = p2_name, p2_mark
642     elsif p2_name == black_name
643       black_name, black_mark = p2_name, p2_mark
644       white_name, white_mark = p1_name, p1_mark
645     else
646       raise "Never reach!: #{black} #{white} #{p3} #{p2}"
647     end
648   end
649   if /^'\$END_TIME:(.*)$/ =~ str
650     time = Time.parse($1.strip)
651   end
652   if /^'rating:(.*)$/ =~ str
653     black_id, white_id = $1.split(":").map {|a| a.strip}
654     black_id = identify_id(black_id)
655     white_id = identify_id(white_id)
656     if black_id && white_id && (black_id != white_id)
657       add(black_mark, black_id, white_id, white_mark, time)
658     end
659   end
660 end
661
662 def usage
663   $stderr.puts <<-EOF
664 USAGE: #{$0} dir [...]
665   EOF
666   exit 1
667 end
668
669 def validate(yaml)
670   yaml["players"].each do |group_key, group|
671     group.each do |player_key, player|
672       rate = player['rate']
673       next unless rate
674       if rate > 10000 || rate < -10000
675         return false
676       end
677     end
678   end
679   return true
680 end
681
682 def usage(io)
683     io.puts <<EOF
684 USAGE: #{$0} [options] DIR..
685   DIR                where CSA files are looked up recursively
686 OPTOINS:
687   --half-life         n [days] (default 60)
688   --half-life-ignore  m [days] (default  7)
689                       after m days, half-life effect works
690   --fixed-rate-player player whose rate is fixed at the rate
691   --fixed-rate        rate 
692   --help              show this message
693 EOF
694 end
695
696 def main
697   $options = Hash::new
698   parser = GetoptLong.new(
699     ["--half-life",         GetoptLong::REQUIRED_ARGUMENT],
700     ["--half-life-ignore",  GetoptLong::REQUIRED_ARGUMENT],
701     ["--help", "-h",        GetoptLong::NO_ARGUMENT],
702     ["--fixed-rate-player", GetoptLong::REQUIRED_ARGUMENT],
703     ["--fixed-rate",        GetoptLong::REQUIRED_ARGUMENT])
704   parser.quiet = true
705   begin
706     parser.each_option do |name, arg|
707       name.sub!(/^--/, '')
708       $options[name] = arg.dup
709     end
710     if ( $options["fixed-rate-player"] && !$options["fixed-rate"]) ||
711        (!$options["fixed-rate-player"] &&  $options["fixed-rate"]) ||
712        ( $options["fixed-rate-player"] &&  $options["fixed-rate"].to_i <= 0) 
713       usage($stderr)
714       exit 1
715     end
716   rescue
717     usage($stderr)
718     raise parser.error_message
719   end
720   if $options["help"]
721     usage($stdout) 
722     exit 0
723   end
724   $options["half-life"] ||= 60
725   $options["half-life"] = $options["half-life"].to_i
726   $options["half-life-ignore"] ||= 7
727   $options["half-life-ignore"] = $options["half-life-ignore"].to_i
728   $options["fixed-rate"] = $options["fixed-rate"].to_i if $options["fixed-rate"]
729
730   while dir = ARGV.shift do
731     Dir.glob( File.join(dir, "**", "*.csa") ) {|f| grep(f)}
732   end
733
734   yaml = {} 
735   yaml["players"] = {}
736   rating_group = 0
737   if $players.size > 0
738     obj = WinLossMatrix::mk_win_loss_matrix($players)
739     obj.connected_subsets.each do |win_loss_matrix|
740       yaml["players"][rating_group] = {}
741
742       rating = Rating.new(win_loss_matrix.matrix)
743       rating.rating
744       rating.average!(Rating::AVERAGE_RATE)
745       rating.integer!
746
747       if $options["fixed-rate-player"]
748         # first, try exact match
749         index = win_loss_matrix.keys.index($options["fixed-rate-player"])
750         # second, try regular match
751         unless index
752           win_loss_matrix.keys.each_with_index do |p, i|
753             if %r!#{$options["fixed-rate-player"]}! =~ p
754               index = i
755             end
756           end
757         end
758         if index
759           the_rate = rating.rate[index]
760           rating.translate!($options["fixed-rate"] - the_rate)
761         end
762       end
763
764       win_loss_matrix.keys.each_with_index do |p, i| # player_id, index#
765         win  = win_loss_matrix.matrix.row(i).sum
766         loss = win_loss_matrix.matrix.col(i).sum
767
768         yaml["players"][rating_group][p] = 
769           { 'name' => p.split("+")[0],
770             'rating_group' => rating_group,
771             'rate' => rating.rate[i],
772             'last_modified' => $players_time[p].dup,
773             'win'  => win,
774             'loss' => loss}
775       end
776       rating_group += 1
777     end
778   end
779   rating_group -= 1
780   non_rated_group = 999 # large enough
781   yaml["players"][non_rated_group] = {}
782   $players.each_key do |id|
783     # skip players who have already been rated
784     found = false
785     (0..rating_group).each do |i|
786        found = true if yaml["players"][i][id]
787        break if found
788     end
789     next if found
790
791     v = GSL::Vector[0, 0]
792     $players[id].each_value {|value| v += value}
793     next if v[0] < 1 && v[1] < 1
794
795     yaml["players"][non_rated_group][id] =
796       { 'name' => id.split("+")[0],
797         'rating_group' => non_rated_group,
798         'rate' => 0,
799         'last_modified' => $players_time[id].dup,
800         'win'  => v[0],
801         'loss' => v[1]}
802   end
803   unless validate(yaml)
804     $stderr.puts "Aborted. It did not result in valid ratings."
805     $stderr.puts yaml.to_yaml if $DEBUG
806     exit 10
807   end
808   puts yaml.to_yaml
809 end
810
811 if __FILE__ == $0
812   main
813 end
814
815 # vim: ts=2 sw=2 sts=0