OSDN Git Service

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