OSDN Git Service

add trip in hyper-links to show-player.cgi, as well as the name of programs
[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   # Make the values of @rate integer.
341   #
342   def integer!
343     @rate = @rate.collect do |a|
344       if a.finite?
345         a.to_i
346       elsif a.nan?
347         0
348       elsif a.infinite?
349         a.infinite? * AVERAGE_RATE * 100
350       end
351     end
352   end
353 end
354
355 #################################################
356 # Encapsulate a pair of keys and win loss matrix.
357 #   - keys is an array of player IDs; [gps+123, foo+234, ...]
358 #   - matrix holds games # where player i (row index) beats player j (column index).
359 #     The row and column indexes match with the keys.
360 #
361 # This object should be immutable. If an internal state is being modified, a
362 # new object is always returned.
363 #
364 class WinLossMatrix
365
366   ###############
367   # Class methods
368   #  
369
370   def self.mk_matrix(players)
371     keys = players.keys.sort
372     size = keys.size
373     matrix =
374       GSL::Matrix[*
375       ((0...size).collect do |k|
376         p1 = keys[k]
377         p1_hash = players[p1]
378         ((0...size).collect do |j|
379           if k == j
380             0
381           else
382             p2 = keys[j]
383             v = p1_hash[p2] || Vector[0,0]
384             v[0]
385           end
386         end)
387       end)]
388     return WinLossMatrix.new(keys, matrix)
389   end
390
391   def self.mk_win_loss_matrix(players)
392     obj = mk_matrix(players)
393     return obj.filter
394   end
395
396   ##################
397   # Instance methods
398   #
399
400   # an array of player IDs; [gps+123, foo+234, ...]
401   attr_reader :keys
402
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   attr_reader :matrix
406
407   def initialize(keys, matrix)
408     @keys   = keys
409     @matrix = matrix
410   end
411
412   ##
413   # Returns the size of the keys/matrix
414   #
415   def size
416     if @keys
417       @keys.size
418     else
419       nil
420     end
421   end
422
423   ##
424   # Removes a delete_index'th player and returns a new object.
425   #
426   def delete_row(delete_index)
427     copied_cols = []
428     (0...size).each do |i|
429       next if i == delete_index
430       row = @matrix.row(i).clone
431       row.delete_at(delete_index)
432       copied_cols << row
433     end
434     if copied_cols.size == 0
435       new_matrix = GSL::Matrix.new
436     else
437       new_matrix = GSL::Matrix[*copied_cols]
438     end
439     new_keys = @keys.clone
440     new_keys.delete_at(delete_index)
441     return WinLossMatrix.new(new_keys, new_matrix)
442   end
443
444   ##
445   # Removes players in a rows; [1,3,5]
446   #
447   def delete_rows(rows)
448     obj = self
449     rows.sort.reverse.each do |index|
450       obj = obj.delete_row(index)
451     end
452     obj
453   end
454
455   ##
456   # Removes players who do not pass a criteria to be rated, and returns a
457   # new object.
458   # 
459   def filter
460     $stderr.puts @keys.inspect if $DEBUG
461     $stderr.puts @matrix.inspect if $DEBUG
462     delete = []  
463     (0...size).each do |i|
464       row = @matrix.row(i)
465       col = @matrix.col(i)
466       win  = row.sum
467       loss = col.sum
468       if win < 1 || loss < 1 || win + loss < $GAMES_LIMIT
469         delete << i
470       end
471     end
472
473     # The recursion ends if there is nothing to delete
474     return self if delete.empty?
475
476     new_obj = delete_rows(delete)
477     new_obj.filter
478   end
479
480   ##
481   # Cuts self into connecting groups such as each player in a group has at least
482   # one game with other players in the group. Returns them as an array.
483   #
484   def connected_subsets
485     g = RGL::AdjacencyGraph.new
486     (0...size).each do |k|
487       (0...size).each do |i|
488         next if k == i
489         if @matrix[k,i] > 0
490           g.add_edge(k,i)
491         end
492       end
493     end
494
495     subsets = []
496     g.each_connected_component do |c|
497       new_keys = []      
498       c.each do |v|
499         new_keys << keys[v.to_s.to_i]
500       end
501       subsets << new_keys
502     end
503
504     subsets = subsets.sort {|a,b| b.size <=> a.size}
505
506     result = subsets.collect do |keys|
507       matrix =
508         GSL::Matrix[*
509         ((0...keys.size).collect do |k|
510           p1 = @keys.index(keys[k])
511           ((0...keys.size).collect do |j|
512             if k == j
513               0
514             else
515               p2 = @keys.index(keys[j])
516               @matrix[p1,p2]
517             end
518           end)
519         end)]
520       WinLossMatrix.new(keys, matrix)
521     end
522
523     return result
524   end
525
526   def to_s
527     "size : #{@keys.size}" + "\n" +
528     @keys.inspect + "\n" + 
529     @matrix.inspect
530   end
531
532 end
533
534
535 #################################################
536 # Main methods
537 #
538
539 # Half-life effect
540 # After NHAFE_LIFE days value will get half.
541 # 0.693 is constant, where exp(0.693) ~ 0.5
542 def half_life(days)
543   if days < $options["half-life-ignore"]
544     return 1.0
545   else
546     Math::exp(-0.693/$options["half-life"]*(days-$options["half-life-ignore"]))
547   end
548 end
549
550 def _add_win_loss(winner, loser, time)
551   how_long_days = (Time.now - time)/(3600*24)
552   $players[winner] ||= Hash.new { GSL::Vector[0,0] }
553   $players[loser]  ||= Hash.new { GSL::Vector[0,0] }
554   $players[winner][loser] += GSL::Vector[1.0*half_life(how_long_days),0]
555   $players[loser][winner] += GSL::Vector[0,1.0*half_life(how_long_days)]
556 end
557
558 def _add_time(player, time)
559   $players_time[player] = time if $players_time[player] < time
560 end
561
562 def add(black_mark, black_name, white_name, white_mark, time)
563   if black_mark == WIN_MARK && white_mark == LOSS_MARK
564     _add_win_loss(black_name, white_name, time)
565   elsif black_mark == LOSS_MARK && white_mark == WIN_MARK
566     _add_win_loss(white_name, black_name, time)
567   elsif black_mark == DRAW_MARK && white_mark == DRAW_MARK
568     return
569   else
570     raise "Never reached!"
571   end
572   _add_time(black_name, time)
573   _add_time(white_name, time)
574 end
575
576 def identify_id(id)
577   if /@NORATE\+/ =~ id # the player having @NORATE in the name should not be rated
578     return nil
579   end
580   id.gsub(/@.*?\+/,"+")
581 end
582
583 def grep(file)
584   str = File.open(file).read
585
586   if /^N\+(.*)$/ =~ str then black_name = $1.strip end
587   if /^N\-(.*)$/ =~ str then white_name = $1.strip end
588
589   if /^'summary:(.*)$/ =~ str
590     state, p1, p2 = $1.split(":").map {|a| a.strip}    
591     return if state == "abnormal"
592     p1_name, p1_mark = p1.split(" ")
593     p2_name, p2_mark = p2.split(" ")
594     if p1_name == black_name
595       black_name, black_mark = p1_name, p1_mark
596       white_name, white_mark = p2_name, p2_mark
597     elsif p2_name == black_name
598       black_name, black_mark = p2_name, p2_mark
599       white_name, white_mark = p1_name, p1_mark
600     else
601       raise "Never reach!: #{black} #{white} #{p3} #{p2}"
602     end
603   end
604   if /^'\$END_TIME:(.*)$/ =~ str
605     time = Time.parse($1.strip)
606   end
607   if /^'rating:(.*)$/ =~ str
608     black_id, white_id = $1.split(":").map {|a| a.strip}
609     black_id = identify_id(black_id)
610     white_id = identify_id(white_id)
611     if black_id && white_id && (black_id != white_id)
612       add(black_mark, black_id, white_id, white_mark, time)
613     end
614   end
615 end
616
617 def usage
618   $stderr.puts <<-EOF
619 USAGE: #{$0} dir [...]
620   EOF
621   exit 1
622 end
623
624 def validate(yaml)
625   yaml["players"].each do |group_key, group|
626     group.each do |player_key, player|
627       rate = player['rate']
628       next unless rate
629       if rate > 10000 || rate < -10000
630         return false
631       end
632     end
633   end
634   return true
635 end
636
637 def usage(io)
638     io.puts <<EOF
639 USAGE: #{$0} [options] DIR..
640   DIR                where CSA files are looked up recursively
641 OPTOINS:
642   --half-life        n [days] (default 60)
643   --half-life-ignore m [days] (default  7)
644                      after m days, half-life effect works
645   --help             show this message
646 EOF
647 end
648
649 def main
650   $options = Hash::new
651   parser = GetoptLong.new(
652     ["--half-life",          GetoptLong::REQUIRED_ARGUMENT],
653     ["--half-life-ignore",   GetoptLong::REQUIRED_ARGUMENT],
654     ["--help", "-h",         GetoptLong::NO_ARGUMENT])
655   parser.quiet = true
656   begin
657     parser.each_option do |name, arg|
658       name.sub!(/^--/, '')
659       $options[name] = arg.dup
660     end
661   rescue
662     usage($stderr)
663     raise parser.error_message
664   end
665   if $options["help"]
666     usage($stdout) 
667     exit 0
668   end
669   $options["half-life"] ||= 60
670   $options["half-life"] = $options["half-life"].to_i
671   $options["half-life-ignore"] ||= 7
672   $options["half-life-ignore"] = $options["half-life-ignore"].to_i
673
674   while dir = ARGV.shift do
675     Dir.glob( File.join(dir, "**", "*.csa") ) {|f| grep(f)}
676   end
677
678   yaml = {} 
679   yaml["players"] = {}
680   rating_group = 0
681   if $players.size > 0
682     obj = WinLossMatrix::mk_win_loss_matrix($players)
683     obj.connected_subsets.each do |win_loss_matrix|
684       yaml["players"][rating_group] = {}
685
686       rating = Rating.new(win_loss_matrix.matrix)
687       rating.rating
688       rating.average!(Rating::AVERAGE_RATE)
689       rating.integer!
690
691       win_loss_matrix.keys.each_with_index do |p, i| # player_id, index#
692         win  = win_loss_matrix.matrix.row(i).sum
693         loss = win_loss_matrix.matrix.col(i).sum
694
695         yaml["players"][rating_group][p] = 
696           { 'name' => p.split("+")[0],
697             'rating_group' => rating_group,
698             'rate' => rating.rate[i],
699             'last_modified' => $players_time[p].dup,
700             'win'  => win,
701             'loss' => loss}
702       end
703       rating_group += 1
704     end
705   end
706   rating_group -= 1
707   non_rated_group = 999 # large enough
708   yaml["players"][non_rated_group] = {}
709   $players.each_key do |id|
710     # skip players who have already been rated
711     found = false
712     (0..rating_group).each do |i|
713        found = true if yaml["players"][i][id]
714        break if found
715     end
716     next if found
717
718     v = GSL::Vector[0, 0]
719     $players[id].each_value {|value| v += value}
720     next if v[0] < 1 && v[1] < 1
721
722     yaml["players"][non_rated_group][id] =
723       { 'name' => id.split("+")[0],
724         'rating_group' => non_rated_group,
725         'rate' => 0,
726         'last_modified' => $players_time[id].dup,
727         'win'  => v[0],
728         'loss' => v[1]}
729   end
730   unless validate(yaml)
731     $stderr.puts "Aborted. It did not result in valid ratings."
732     $stderr.puts yaml.to_yaml if $DEBUG
733     exit 10
734   end
735   puts yaml.to_yaml
736 end
737
738 if __FILE__ == $0
739   main
740 end
741
742 # vim: ts=2 sw=2 sts=0