OSDN Git Service

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