OSDN Git Service

[mk_rate]
[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 'stringio'
93 require 'getoptlong'
94 require 'gsl'
95 require 'rubygems'
96 require 'rgl/adjacency'
97 require 'rgl/connected_components'
98
99 #################################################
100 # Constants
101 #
102
103 # Count out players who play less games than $GAMES_LIMIT
104 $GAMES_LIMIT = $DEBUG ? 0 : 15
105 WIN_MARK  = "win"
106 LOSS_MARK = "lose"
107 DRAW_MARK = "draw"
108
109 # Holds players
110 $players = Hash.new
111 # Holds the last time when a player gamed
112 $players_time = Hash.new { Time.at(0) }
113
114
115 #################################################
116 # Keeps the value of the lowest key
117 #
118 class Record
119   def initialize
120     @lowest = []
121   end
122
123   def set(key, value)
124     if @lowest.empty? || key < @lowest[0]
125       @lowest = [key, value]
126     end
127   end
128
129   def get
130     if @lowest.empty?
131       nil
132     else
133       @lowest[1]
134     end
135   end
136 end
137
138 #################################################
139 # Calculates rates of every player from a Win Loss GSL::Matrix
140 #
141 class Rating
142   include Math
143
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
148   
149   # Convergence limit to stop Newton method.
150   ERROR_LIMIT = 1.0e-3
151   # Stop Newton method after this iterations.
152   COUNT_MAX = 500
153
154   # Average rate among the players
155   AVERAGE_RATE = 1000
156
157   
158   ###############
159   # Class methods
160   #  
161   
162   ##
163   # Calcurates the average of the vector.
164   #
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)]
168     vector
169   end
170
171   ##################
172   # Instance methods
173   #
174   def initialize(win_loss_matrix)
175     @record = Record.new
176     @n = win_loss_matrix
177     case @n
178     when GSL::Matrix, GSL::Matrix::Int
179       @size = @n.size1
180     when ::Matrix
181       @size = @n.row_size
182     else
183       raise ArgumentError
184     end
185     initial_rate
186   end
187   attr_reader :rate, :n
188
189   def player_vector
190     GSL::Vector[*
191       (0...@size).collect {|k| yield k}
192     ]
193   end
194
195   def each_player
196     (0...@size).each {|k| yield k}
197   end
198
199   ##
200   # The possibility that the player k will beet the player i.
201   #
202   def win_rate(k,i)
203     1.0/(1.0 + exp(@rate[i]-@rate[k]))
204   end
205
206   ##
207   # Most possible equation
208   #
209   def func_vector
210     player_vector do|k| 
211       sum = 0.0
212       each_player do |i|
213         next if i == k
214         sum += @n[k,i] * win_rate(i,k) - @n[i,k] * win_rate(k,i) 
215       end
216       sum * 2.0
217     end
218   end
219
220   ##
221   #           / f0/R0 f0/R1 f0/R2 ... \
222   # dfk/dRj = | f1/R0 f1/R1 f1/R2 ... |
223   #           \ f2/R0 f2/R1 f2/R2 ... /
224   def d_func(k,j)
225     sum = 0.0
226     if k == j
227       each_player do |i|
228         next if i == k
229         sum += win_rate(i,k) * win_rate(k,i) * (@n[k,i] + @n[i,k])
230       end
231       sum *= -2.0
232     else # k != j
233       sum = 2.0 * win_rate(j,k) * win_rate(k,j) * (@n[k,j] + @n[j,k])
234     end
235     sum
236   end
237
238   ##
239   # Jacobi matrix of the func().
240   #   m00 m01
241   #   m10 m11
242   #
243   def j_matrix
244     GSL::Matrix[*
245       (0...@size).collect do |k|
246         (0...@size).collect do |j|
247           d_func(k,j)
248         end
249       end
250     ]
251   end
252
253   ##
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.
257   #
258   def initial_rate
259     possibility = 
260       player_vector do |k|
261         v = GSL::Vector[0, 0]
262         each_player do |i|
263           next if k == i
264           v += GSL::Vector[@n[k,i], @n[i,k]]
265         end
266         v.nrm2 < 1 ? 0 : v[0] / (v[0] + v[1])
267       end
268     rank = possibility.sort_index
269     @rate = player_vector do |k|
270       K*500 * (rank[k]+1) / @size
271     end
272     average!
273   end
274
275   ##
276   # Resets @rate as the higher the current win probablity of a player is, 
277   # the greater points he takes. 
278   #
279   def initial_rate2
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
284     end
285     average!
286   end
287
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
292       return
293     end
294     if mu < 1e-4
295       @record.set(func_vector.nrm2, @rate)
296       initial_rate2
297       return
298     end
299     $stderr.puts "mu: %f " % [mu] if $DEBUG
300     deaccelrate(mu*0.5, old_rate, a, old_f_nrm2)
301   end
302
303   ##
304   # Main process to calculate ratings.
305   #
306   def rating
307     # Counter to stop the process. 
308     # Calulation in Newton method may fall in an infinite loop
309     @count = 0
310
311     # Main loop
312     begin
313       # Solve the equation: 
314       #   J*a=f
315       #   @rate_(n+1) = @rate_(n) - a
316       #
317       # f.nrm2 should approach to zero.
318       f = func_vector
319       j = j_matrix
320
321       # $stderr.puts "j: %s" % [j.inspect] if $DEBUG
322       $stderr.puts "f: %s -> %f" % [f.to_a.inspect, f.nrm2] if $DEBUG
323
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
329       
330       # Deaccelerated Newton method
331       # GSL::Vector object should be immutable.
332       old_rate   = @rate
333       old_f      = f
334       old_f_nrm2 = old_f.nrm2
335       deaccelrate(1.0, old_rate, a, old_f_nrm2)
336       @record.set(func_vector.nrm2, @rate)
337
338       $stderr.printf "|error| : %5.2e\n", a.nrm2 if $DEBUG
339
340       @count += 1
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]
344         break
345       end
346
347     end while (a.nrm2 > ERROR_LIMIT * @rate.nrm2)
348     
349     @rate = @record.get
350     $stderr.puts "resolved f: %s -> %f" %
351       [func_vector.to_a.inspect, func_vector.nrm2] if $DEBUG
352
353     @rate *= 1.0/K
354     finite!
355     self
356   end
357
358   ##
359   # Make the values of @rate finite.
360   #
361   def finite!
362     @rate = @rate.collect do |a|
363       if a.infinite?
364         a.infinite? * AVERAGE_RATE * 100
365       else
366         a
367       end
368     end
369   end
370
371   ##
372   # Flatten the values of @rate.
373   #
374   def average!(mean=0.0)
375     @rate = self.class.average(@rate, mean)
376   end
377
378   ##
379   # Translate by value
380   #
381   def translate!(value)
382     @rate += value
383   end
384
385   ##
386   # Make the values of @rate integer.
387   #
388   def integer!
389     @rate = @rate.collect do |a|
390       if a.finite?
391         a.to_i
392       elsif a.nan?
393         0
394       elsif a.infinite?
395         a.infinite? * AVERAGE_RATE * 100
396       end
397     end
398   end
399 end
400
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.
406 #
407 # This object should be immutable. If an internal state is being modified, a
408 # new object is always returned.
409 #
410 class WinLossMatrix
411
412   ###############
413   # Class methods
414   #  
415
416   def self.mk_matrix(players)
417     keys = players.keys.sort
418     size = keys.size
419     matrix =
420       GSL::Matrix[*
421       ((0...size).collect do |k|
422         p1 = keys[k]
423         p1_hash = players[p1]
424         ((0...size).collect do |j|
425           if k == j
426             0
427           else
428             p2 = keys[j]
429             v = p1_hash[p2] || Vector[0,0]
430             v[0]
431           end
432         end)
433       end)]
434     return WinLossMatrix.new(keys, matrix)
435   end
436
437   def self.mk_win_loss_matrix(players)
438     obj = mk_matrix(players)
439     while true do
440       obj, ret = obj.filter
441       break if ret
442     end
443     return obj
444   end
445
446   ##################
447   # Instance methods
448   #
449
450   # an array of player IDs; [gps+123, foo+234, ...]
451   attr_reader :keys
452
453   # matrix holds games # where player i (row index) beats player j (column index).
454   # The row and column indexes match with the keys.
455   attr_reader :matrix
456
457   def initialize(keys, matrix)
458     @keys   = keys
459     @matrix = matrix
460   end
461
462   ##
463   # Returns the size of the keys/matrix
464   #
465   def size
466     if @keys
467       @keys.size
468     else
469       nil
470     end
471   end
472
473   ##
474   # Removes the delete_index'th player and returns a new object.
475   #
476   #  [ 1 0 0   * [ 1 2 3   * [ 1 0   = [ 1 3
477   #    0 0 1 ]     4 5 6       0 0       7 9 ]
478   #                7 8 9 ]     0 1 ]
479   #
480   def delete_row(delete_index)
481     new_matrix = nil
482     if delete_index == 0 && @matrix.size1 == 1 && @matrix.size2 == 1
483       new_matrix = GSL::Matrix.new
484     else
485       a1 = []
486       size.times do |i|
487         next if i == delete_index
488         v = Array.new(size, 0)
489         v[i] = 1
490         a1 << v
491       end
492       m1 = GSL::Matrix[*a1]
493       a1 = nil
494       m2 = m1.transpose
495       new_matrix = m1 * @matrix * m2
496     end
497
498     new_keys = @keys.clone
499     new_keys.delete_at(delete_index)
500
501     unless new_matrix
502       raise "The new matrix is null!"
503     end
504
505     return WinLossMatrix.new(new_keys, new_matrix)
506   end
507
508   ##
509   # Removes players in a rows; [1,3,5]
510   #
511   def delete_rows(rows)
512     obj = self
513     rows.sort.reverse.each do |index|
514       obj = obj.delete_row(index)
515     end
516     obj
517   end
518
519   ##
520   # Removes players who do not pass a criteria to be rated, and returns a
521   # new object.
522   # 
523   def filter
524     $stderr.puts @keys.inspect if $DEBUG
525     $stderr.puts @matrix.inspect if $DEBUG
526     delete = []  
527     (0...size).each do |i|
528       row = @matrix.row(i)
529       col = @matrix.col(i)
530       win  = row.sum
531       loss = col.sum
532       if win < 1 || loss < 1 || win + loss < $GAMES_LIMIT
533         delete << i
534       end
535     end
536
537     # The recursion ends if there is nothing to delete
538     return [self, true] if delete.empty?
539
540     new_obj = delete_rows(delete)
541     return [new_obj, false]
542   end
543
544   ##
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.
547   #
548   def connected_subsets
549     g = RGL::AdjacencyGraph.new
550     (0...size).each do |k|
551       (0...size).each do |i|
552         next if k == i
553         if @matrix[k,i] > 0
554           g.add_edge(k,i)
555         end
556       end
557     end
558
559     subsets = []
560     g.each_connected_component do |c|
561       new_keys = []      
562       c.each do |v|
563         new_keys << keys[v.to_s.to_i]
564       end
565       subsets << new_keys
566     end
567
568     subsets = subsets.sort {|a,b| b.size <=> a.size}
569
570     result = subsets.collect do |keys|
571       matrix =
572         GSL::Matrix[*
573         ((0...keys.size).collect do |k|
574           p1 = @keys.index(keys[k])
575           ((0...keys.size).collect do |j|
576             if k == j
577               0
578             else
579               p2 = @keys.index(keys[j])
580               @matrix[p1,p2]
581             end
582           end)
583         end)]
584       WinLossMatrix.new(keys, matrix)
585     end
586
587     return result
588   end
589
590   def to_s
591     "size : #{@keys.size}" + "\n" +
592     @keys.inspect + "\n" + 
593     @matrix.inspect
594   end
595
596 end
597
598
599 #################################################
600 # Main methods
601 #
602
603 # Half-life effect
604 # After NHAFE_LIFE days value will get half.
605 # 0.693 is constant, where exp(0.693) ~ 0.5
606 def half_life(days)
607   if days < $options["half-life-ignore"]
608     return 1.0
609   else
610     Math::exp(-0.693/$options["half-life"]*(days-$options["half-life-ignore"]))
611   end
612 end
613
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)]
620 end
621
622 def _add_time(player, time)
623   $players_time[player] = time if $players_time[player] < time
624 end
625
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
632     return
633   else
634     raise "Never reached!"
635   end
636   _add_time(black_name, time)
637   _add_time(white_name, time)
638 end
639
640 def identify_id(id)
641   if /@NORATE\+/ =~ id # the player having @NORATE in the name should not be rated
642     return nil
643   end
644   id.gsub(/@.*?\+/,"+")
645 end
646
647 def grep(file)
648   black_name = nil
649   white_name = nil
650   black_mark = nil
651   white_mark = nil
652   black_id   = nil
653   white_id   = nil
654   time       = nil
655
656   lines = StringIO.new File.open(file).read
657
658   lines.each_line do |str|
659     case str
660     when /^N\+(.*)$/
661       black_name = $1.strip 
662     when /^N\-(.*)$/
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
675       else
676         raise "Never reach!: #{black} #{white} #{p3} #{p2}"
677       end
678     when /^'\$END_TIME:(.*)$/
679       time = Time.parse($1.strip)
680     end # case
681   end # each line
682
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)
690     end
691   end
692 end
693
694 def usage
695   $stderr.puts <<-EOF
696 USAGE: #{$0} dir [...]
697   EOF
698   exit 1
699 end
700
701 def validate(yaml)
702   yaml["players"].each do |group_key, group|
703     group.each do |player_key, player|
704       rate = player['rate']
705       next unless rate
706       if rate > 10000 || rate < -10000
707         return false
708       end
709     end
710   end
711   return true
712 end
713
714 def usage(io)
715     io.puts <<EOF
716 USAGE: #{$0} [options] DIR..
717   DIR                where CSA files are looked up recursively
718 OPTOINS:
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
723   --fixed-rate        rate 
724   --help              show this message
725 EOF
726 end
727
728 def main
729   $options = Hash::new
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])
736   parser.quiet = true
737   begin
738     parser.each_option do |name, arg|
739       name.sub!(/^--/, '')
740       $options[name] = arg.dup
741     end
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) 
745       usage($stderr)
746       exit 1
747     end
748   rescue
749     usage($stderr)
750     raise parser.error_message
751   end
752   if $options["help"]
753     usage($stdout) 
754     exit 0
755   end
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"]
761
762   while dir = ARGV.shift do
763     Dir.glob( File.join(dir, "**", "*.csa") ) {|f| grep(f)}
764   end
765
766   yaml = {} 
767   yaml["players"] = {}
768   rating_group = 0
769   if $players.size > 0
770     obj = WinLossMatrix::mk_win_loss_matrix($players)
771     obj.connected_subsets.each do |win_loss_matrix|
772       yaml["players"][rating_group] = {}
773
774       rating = Rating.new(win_loss_matrix.matrix)
775       rating.rating
776       rating.average!(Rating::AVERAGE_RATE)
777       rating.integer!
778
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
783         unless index
784           win_loss_matrix.keys.each_with_index do |p, i|
785             if %r!#{$options["fixed-rate-player"]}! =~ p
786               index = i
787             end
788           end
789         end
790         if index
791           the_rate = rating.rate[index]
792           rating.translate!($options["fixed-rate"] - the_rate)
793         end
794       end
795
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
799
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,
805             'win'  => win,
806             'loss' => loss}
807       end
808       rating_group += 1
809     end
810   end
811   rating_group -= 1
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
816     found = false
817     (0..rating_group).each do |i|
818        found = true if yaml["players"][i][id]
819        break if found
820     end
821     next if found
822
823     v = GSL::Vector[0, 0]
824     $players[id].each_value {|value| v += value}
825     next if v[0] < 1 && v[1] < 1
826
827     yaml["players"][non_rated_group][id] =
828       { 'name' => id.split("+")[0],
829         'rating_group' => non_rated_group,
830         'rate' => 0,
831         'last_modified' => $players_time[id].dup,
832         'win'  => v[0],
833         'loss' => v[1]}
834   end
835   unless validate(yaml)
836     $stderr.puts "Aborted. It did not result in valid ratings."
837     $stderr.puts yaml.to_yaml if $DEBUG
838     exit 10
839   end
840   puts yaml.to_yaml
841 end
842
843 if __FILE__ == $0
844   main
845 end
846
847 # vim: ts=2 sw=2 sts=0