OSDN Git Service

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