OSDN Git Service

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