OSDN Git Service

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