RANK: Put #include directives into typical order.
[pspp] / src / language / stats / rank.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2005, 2006, 2007, 2009, 2010, 2011, 2012 Free Software Foundation, Inc
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16
17 #include <config.h>
18
19 #include <math.h>
20 #include <gsl/gsl_cdf.h>
21
22 #include "data/case.h"
23 #include "data/casegrouper.h"
24 #include "data/casereader.h"
25 #include "data/dataset.h"
26 #include "data/dictionary.h"
27 #include "data/format.h"
28 #include "data/variable.h"
29 #include "data/subcase.h"
30 #include "data/casewriter.h"
31 #include "data/short-names.h"
32 #include "language/command.h"
33 #include "language/lexer/lexer.h"
34 #include "language/lexer/variable-parser.h"
35 #include "language/stats/sort-criteria.h"
36 #include "math/sort.h"
37 #include "libpspp/assertion.h"
38 #include "libpspp/message.h"
39 #include "libpspp/misc.h"
40 #include "libpspp/pool.h"
41 #include "libpspp/taint.h"
42
43 #include "output/tab.h"
44
45 #include "gettext.h"
46 #define _(msgid) gettext (msgid)
47 #define N_(msgid) (msgid)
48
49 struct rank;
50
51 typedef double (*rank_function_t) (const struct rank*, double c, double cc, double cc_1,
52                                    int i, double w);
53
54 static double rank_proportion (const struct rank *, double c, double cc, double cc_1,
55                                int i, double w);
56
57 static double rank_normal (const struct rank *, double c, double cc, double cc_1,
58                            int i, double w);
59
60 static double rank_percent (const struct rank *, double c, double cc, double cc_1,
61                             int i, double w);
62
63 static double rank_rfraction (const struct rank *, double c, double cc, double cc_1,
64                               int i, double w);
65
66 static double rank_rank (const struct rank *, double c, double cc, double cc_1,
67                          int i, double w);
68
69 static double rank_n (const struct rank *, double c, double cc, double cc_1,
70                       int i, double w);
71
72 static double rank_savage (const struct rank *, double c, double cc, double cc_1,
73                            int i, double w);
74
75 static double rank_ntiles (const struct rank *, double c, double cc, double cc_1,
76                            int i, double w);
77
78
79 enum rank_func
80   {
81     RANK,
82     NORMAL,
83     PERCENT,
84     RFRACTION,
85     PROPORTION,
86     N,
87     NTILES,
88     SAVAGE,
89     n_RANK_FUNCS
90   };
91
92 static const struct fmt_spec dest_format[n_RANK_FUNCS] = {
93   {FMT_F, 9, 3}, /* rank */
94   {FMT_F, 6, 4}, /* normal */
95   {FMT_F, 6, 2}, /* percent */
96   {FMT_F, 6, 4}, /* rfraction */
97   {FMT_F, 6, 4}, /* proportion */
98   {FMT_F, 6, 0}, /* n */
99   {FMT_F, 3, 0}, /* ntiles */
100   {FMT_F, 8, 4}  /* savage */
101 };
102
103 static const char * const function_name[n_RANK_FUNCS] = {
104   "RANK",
105   "NORMAL",
106   "PERCENT",
107   "RFRACTION",
108   "PROPORTION",
109   "N",
110   "NTILES",
111   "SAVAGE"
112 };
113
114 static const rank_function_t rank_func[n_RANK_FUNCS] = {
115   rank_rank,
116   rank_normal,
117   rank_percent,
118   rank_rfraction,
119   rank_proportion,
120   rank_n,
121   rank_ntiles,
122   rank_savage
123 };
124
125
126 enum ties
127   {
128     TIES_LOW,
129     TIES_HIGH,
130     TIES_MEAN,
131     TIES_CONDENSE
132   };
133
134 enum fraction
135   {
136     FRAC_BLOM,
137     FRAC_RANKIT,
138     FRAC_TUKEY,
139     FRAC_VW
140   };
141
142 struct rank_spec
143 {
144   enum rank_func rfunc;
145   struct variable **destvars;
146 };
147
148
149 /* Create and return a new variable in which to store the ranks of SRC_VAR
150    accoring to the rank function F.
151    VNAME is the name of the variable to be created.
152    If VNAME is NULL, then a name will be automatically chosen.
153 */
154 static struct variable *
155 create_rank_variable (struct dictionary *dict, enum rank_func f,
156                       const struct variable *src_var,
157                       const char *vname)
158 {
159   int i;
160   struct variable *var = NULL;
161   char name[SHORT_NAME_LEN + 1];
162
163   if ( vname )
164     var = dict_create_var(dict, vname, 0);
165
166   if ( NULL == var )
167     {
168       snprintf (name, SHORT_NAME_LEN + 1, "%c%s",
169                 function_name[f][0], var_get_name (src_var));
170
171       var = dict_create_var(dict, name, 0);
172     }
173   i = 1;
174   while( NULL == var )
175     {
176       char func_abb[4];
177       snprintf(func_abb, 4, "%s", function_name[f]);
178       snprintf(name, SHORT_NAME_LEN + 1, "%s%03d", func_abb,
179                i);
180
181       var = dict_create_var(dict, name, 0);
182       if (i++ >= 999)
183         break;
184     }
185
186   i = 1;
187   while ( NULL == var )
188     {
189       char func_abb[3];
190       snprintf(func_abb, 3, "%s", function_name[f]);
191
192       snprintf(name, SHORT_NAME_LEN + 1,
193                "RNK%s%02d", func_abb, i);
194
195       var = dict_create_var(dict, name, 0);
196       if ( i++ >= 99 )
197         break;
198     }
199
200   if ( NULL == var )
201     {
202       msg(ME, _("Cannot create new rank variable.  All candidates in use."));
203       return NULL;
204     }
205
206   var_set_both_formats (var, &dest_format[f]);
207
208   return var;
209 }
210
211 struct rank
212 {
213   struct dictionary *dict;
214
215   struct subcase sc;
216
217   const struct variable **vars;
218   size_t n_vars;
219
220   const struct variable **group_vars;
221   size_t n_group_vars;
222
223
224   enum mv_class exclude;
225
226   struct rank_spec *rs;
227   size_t n_rs;
228
229   enum ties ties;
230
231   enum fraction fraction;
232   int k_ntiles;
233
234   bool print;
235
236   /* Pool on which cell functions may allocate data */
237   struct pool *pool;
238 };
239
240
241 static void
242 destroy_rank (struct rank *rank)
243 {
244  free (rank->vars);
245  free (rank->group_vars);
246  subcase_destroy (&rank->sc);
247  pool_destroy (rank->pool);
248 }
249
250 static bool
251 parse_into (struct lexer *lexer, struct rank *cmd)
252 {
253   int var_count = 0;
254   struct rank_spec *rs = NULL;
255
256   cmd->rs = pool_realloc (cmd->pool, cmd->rs, sizeof (*cmd->rs) * (cmd->n_rs + 1));
257   rs = &cmd->rs[cmd->n_rs];
258       
259   if (lex_match_id (lexer, "RANK"))
260     {
261       rs->rfunc = RANK;
262     }
263   else if (lex_match_id (lexer, "NORMAL"))
264     {
265       rs->rfunc = NORMAL;
266     }
267   else if (lex_match_id (lexer, "RFRACTION"))
268     {
269       rs->rfunc = RFRACTION;
270     }
271   else if (lex_match_id (lexer, "N"))
272     {
273       rs->rfunc = N;
274     }
275   else if (lex_match_id (lexer, "SAVAGE"))
276     {
277       rs->rfunc = SAVAGE;
278     }
279   else if (lex_match_id (lexer, "PERCENT"))
280     {
281       rs->rfunc = PERCENT;
282     }
283   else if (lex_match_id (lexer, "PROPORTION"))
284     {
285       rs->rfunc = PROPORTION;
286     }
287   else if (lex_match_id (lexer, "NTILES"))
288     {
289       if ( !lex_force_match (lexer, T_LPAREN))
290         return false;
291       
292       if (! lex_force_int (lexer) )
293         return false;
294       
295       cmd->k_ntiles = lex_integer (lexer);
296       lex_get (lexer);
297       
298       if ( !lex_force_match (lexer, T_RPAREN))
299         return false;
300
301       rs->rfunc = NTILES;
302     }
303   else
304     {
305       return false;
306     }
307
308   cmd->n_rs++;
309   rs->destvars = NULL;
310   rs->destvars = pool_calloc (cmd->pool, cmd->n_vars, sizeof (*rs->destvars));
311
312   if (lex_match_id (lexer, "INTO"))
313     {
314       while( lex_token (lexer) == T_ID )
315         {
316           const char *name = lex_tokcstr (lexer);
317           if ( dict_lookup_var (cmd->dict, name) != NULL )
318             {
319               msg (SE, _("Variable %s already exists."), name);
320               return false;
321             }
322           
323           if ( var_count >= subcase_get_n_fields (&cmd->sc) )
324             {
325               msg (SE, _("Too many variables in INTO clause."));
326               return false;
327             }
328           rs->destvars[var_count] = 
329             create_rank_variable (cmd->dict, rs->rfunc, cmd->vars[var_count], name);
330           ++var_count;
331           lex_get (lexer);
332         }
333     }
334
335   return true;
336 }
337
338 /* Hardly a rank function !! */
339 static double
340 rank_n (const struct rank *cmd UNUSED, double c UNUSED, double cc UNUSED, double cc_1 UNUSED,
341         int i UNUSED, double w)
342 {
343   return w;
344 }
345
346
347 static double
348 rank_rank (const struct rank *cmd, double c, double cc, double cc_1,
349            int i, double w UNUSED)
350 {
351   double rank;
352
353   if ( c >= 1.0 )
354     {
355       switch (cmd->ties)
356         {
357         case TIES_LOW:
358           rank = cc_1 + 1;
359           break;
360         case TIES_HIGH:
361           rank = cc;
362           break;
363         case TIES_MEAN:
364           rank = cc_1 + (c + 1.0)/ 2.0;
365           break;
366         case TIES_CONDENSE:
367           rank = i;
368           break;
369         default:
370           NOT_REACHED ();
371         }
372     }
373   else
374     {
375       switch (cmd->ties)
376         {
377         case TIES_LOW:
378           rank = cc_1;
379           break;
380         case TIES_HIGH:
381           rank = cc;
382           break;
383         case TIES_MEAN:
384           rank = cc_1 + c / 2.0 ;
385           break;
386         case TIES_CONDENSE:
387           rank = i;
388           break;
389         default:
390           NOT_REACHED ();
391         }
392     }
393
394   return rank;
395 }
396
397
398 static double
399 rank_rfraction (const struct rank *cmd, double c, double cc, double cc_1,
400                 int i, double w)
401 {
402   return rank_rank (cmd, c, cc, cc_1, i, w) / w ;
403 }
404
405
406 static double
407 rank_percent (const struct rank *cmd, double c, double cc, double cc_1,
408               int i, double w)
409 {
410   return rank_rank (cmd, c, cc, cc_1, i, w) * 100.0 / w ;
411 }
412
413
414 static double
415 rank_proportion (const struct rank *cmd, double c, double cc, double cc_1,
416                  int i, double w)
417 {
418   const double r =  rank_rank (cmd, c, cc, cc_1, i, w) ;
419
420   double f;
421
422   switch ( cmd->fraction )
423     {
424     case FRAC_BLOM:
425       f =  (r - 3.0/8.0) / (w + 0.25);
426       break;
427     case FRAC_RANKIT:
428       f = (r - 0.5) / w ;
429       break;
430     case FRAC_TUKEY:
431       f = (r - 1.0/3.0) / (w + 1.0/3.0);
432       break;
433     case FRAC_VW:
434       f = r / ( w + 1.0);
435       break;
436     default:
437       NOT_REACHED ();
438     }
439
440
441   return (f > 0) ? f : SYSMIS;
442 }
443
444 static double
445 rank_normal (const struct rank *cmd, double c, double cc, double cc_1,
446              int i, double w)
447 {
448   double f = rank_proportion (cmd, c, cc, cc_1, i, w);
449
450   return gsl_cdf_ugaussian_Pinv (f);
451 }
452
453 static double
454 rank_ntiles (const struct rank *cmd, double c, double cc, double cc_1,
455              int i, double w)
456 {
457   double r = rank_rank (cmd, c, cc, cc_1, i, w);
458
459
460   return ( floor (( r * cmd->k_ntiles) / ( w + 1) ) + 1);
461 }
462
463 /* Expected value of the order statistics from an exponential distribution */
464 static double
465 ee (int j, double w_star)
466 {
467   int k;
468   double sum = 0.0;
469
470   for (k = 1 ; k <= j; k++)
471     sum += 1.0 / ( w_star + 1 - k );
472
473   return sum;
474 }
475
476
477 static double
478 rank_savage (const struct rank *cmd UNUSED, double c, double cc, double cc_1,
479              int i UNUSED, double w)
480 {
481   double int_part;
482   const int i_1 = floor (cc_1);
483   const int i_2 = floor (cc);
484
485   const double w_star = (modf (w, &int_part) == 0 ) ? w : floor (w) + 1;
486
487   const double g_1 = cc_1 - i_1;
488   const double g_2 = cc - i_2;
489
490   /* The second factor is infinite, when the first is zero.
491      Therefore, evaluate the second, only when the first is non-zero */
492   const double expr1 =  (1 - g_1) ? (1 - g_1) * ee(i_1+1, w_star) : ( 1 - g_1);
493   const double expr2 =  g_2 ? g_2 * ee (i_2+1, w_star) : g_2 ;
494
495   if ( i_1 == i_2 )
496     return ee (i_1 + 1, w_star) - 1;
497
498   if ( i_1 + 1 == i_2 )
499     return ( ( expr1 + expr2 )/c ) - 1;
500
501   if ( i_1 + 2 <= i_2 )
502     {
503       int j;
504       double sigma = 0.0;
505       for (j = i_1 + 2 ; j <= i_2; ++j )
506         sigma += ee (j, w_star);
507       return ( (expr1 + expr2 + sigma) / c) -1;
508     }
509
510   NOT_REACHED();
511 }
512
513
514 static void
515 rank_sorted_file (struct casereader *input,
516                   struct casewriter *output,
517                   const struct dictionary *dict,
518                   int dest_idx,
519                   const struct rank *cmd
520                   )
521 {
522   struct casereader *pass1, *pass2, *pass2_1;
523   struct casegrouper *tie_grouper;
524   struct ccase *c;
525   double w = 0.0;
526   double cc = 0.0;
527   int tie_group = 1;
528
529   input = casereader_create_filter_missing (input, &cmd->vars[dest_idx], 1,
530                                             cmd->exclude, NULL, output);
531   input = casereader_create_filter_weight (input, dict, NULL, output);
532
533   casereader_split (input, &pass1, &pass2);
534
535   /* Pass 1: Get total group weight. */
536   for (; (c = casereader_read (pass1)) != NULL; case_unref (c))
537     w += dict_get_case_weight (dict, c, NULL);
538   casereader_destroy (pass1);
539
540   /* Pass 2: Do ranking. */
541   tie_grouper = casegrouper_create_vars (pass2, &cmd->vars[dest_idx], 1);
542   while (casegrouper_get_next_group (tie_grouper, &pass2_1))
543     {
544       struct casereader *pass2_2;
545       double cc_1 = cc;
546       double tw = 0.0;
547       int i;
548
549       pass2_2 = casereader_clone (pass2_1);
550       taint_propagate (casereader_get_taint (pass2_2),
551                        casewriter_get_taint (output));
552
553       /* Pass 2.1: Sum up weight for tied cases. */
554       for (; (c = casereader_read (pass2_1)) != NULL; case_unref (c))
555         tw += dict_get_case_weight (dict, c, NULL);
556       cc += tw;
557       casereader_destroy (pass2_1);
558
559       /* Pass 2.2: Rank tied cases. */
560       while ((c = casereader_read (pass2_2)) != NULL)
561         {
562           c = case_unshare (c);
563           for (i = 0; i < cmd->n_rs; ++i)
564             {
565               const struct variable *dst_var = cmd->rs[i].destvars[dest_idx];
566               double *dst_value = &case_data_rw (c, dst_var)->f;
567               *dst_value = rank_func[cmd->rs[i].rfunc] (cmd, tw, cc, cc_1, tie_group, w);
568             }
569           casewriter_write (output, c);
570         }
571       casereader_destroy (pass2_2);
572
573       tie_group++;
574     }
575   casegrouper_destroy (tie_grouper);
576 }
577
578
579 /* Transformation function to enumerate all the cases */
580 static int
581 create_resort_key (void *key_var_, struct ccase **cc, casenumber case_num)
582 {
583   struct variable *key_var = key_var_;
584
585   *cc = case_unshare (*cc);
586   case_data_rw (*cc, key_var)->f = case_num;
587
588   return TRNS_CONTINUE;
589 }
590
591 static bool
592 rank_cmd (struct dataset *ds,  const struct rank *cmd);
593
594
595 static const char *
596 fraction_name (const struct rank *cmd)
597 {
598   static char name[10];
599   switch (cmd->fraction )
600     {
601     case FRAC_BLOM:
602       strcpy (name, "BLOM");
603       break;
604     case FRAC_RANKIT:
605       strcpy (name, "RANKIT");
606       break;
607     case FRAC_TUKEY:
608       strcpy (name, "TUKEY");
609       break;
610     case FRAC_VW:
611       strcpy (name, "VW");
612       break;
613     default:
614       NOT_REACHED ();
615     }
616   return name;
617 }
618
619 /* Create a label on DEST_VAR, describing its derivation from SRC_VAR and F */
620 static void
621 create_var_label (struct rank *cmd, struct variable *dest_var,
622                   const struct variable *src_var, enum rank_func f)
623 {
624   struct string label;
625   ds_init_empty (&label);
626
627   if ( cmd->n_group_vars > 0 )
628     {
629       struct string group_var_str;
630       int g;
631
632       ds_init_empty (&group_var_str);
633
634       for (g = 0 ; g < cmd->n_group_vars ; ++g )
635         {
636           if ( g > 0 ) ds_put_cstr (&group_var_str, " ");
637           ds_put_cstr (&group_var_str, var_get_name (cmd->group_vars[g]));
638         }
639
640       ds_put_format (&label, _("%s of %s by %s"), function_name[f],
641                      var_get_name (src_var), ds_cstr (&group_var_str));
642       ds_destroy (&group_var_str);
643     }
644   else
645     ds_put_format (&label, _("%s of %s"),
646                    function_name[f], var_get_name (src_var));
647
648   var_set_label (dest_var, ds_cstr (&label), false);
649   
650   ds_destroy (&label);
651 }
652
653 int
654 cmd_rank (struct lexer *lexer, struct dataset *ds)
655 {
656   struct rank rank;
657   struct variable *order;
658   bool result = true;
659   int i;
660
661   subcase_init_empty (&rank.sc);
662
663   rank.rs = NULL;
664   rank.n_rs = 0;
665   rank.exclude = MV_ANY;
666   rank.n_group_vars = 0;
667   rank.group_vars = NULL;
668   rank.dict = dataset_dict (ds);
669   rank.ties = TIES_MEAN;
670   rank.fraction = FRAC_BLOM;
671   rank.print = true;
672   rank.pool = pool_create ();
673
674   if (lex_match_id (lexer, "VARIABLES"))
675     lex_force_match (lexer, T_EQUALS);
676
677   if (!parse_sort_criteria (lexer, rank.dict,
678                             &rank.sc,
679                             &rank.vars, NULL))
680     goto error;
681
682   rank.n_vars = rank.sc.n_fields;
683
684   if (lex_match (lexer, T_BY) )
685     {
686       if ( ! parse_variables_const (lexer, rank.dict,
687                                     &rank.group_vars, &rank.n_group_vars,
688                                     PV_NO_DUPLICATE | PV_NO_SCRATCH))
689         goto error;
690     }
691
692
693   while (lex_token (lexer) != T_ENDCMD )
694     {
695       lex_force_match (lexer, T_SLASH);
696       if (lex_match_id (lexer, "TIES"))
697         {
698           lex_force_match (lexer, T_EQUALS);
699           if (lex_match_id (lexer, "MEAN"))
700             {
701               rank.ties = TIES_MEAN;
702             }
703           else if (lex_match_id (lexer, "LOW"))
704             {
705               rank.ties = TIES_LOW;
706             }
707           else if (lex_match_id (lexer, "HIGH"))
708             {
709               rank.ties = TIES_HIGH;
710             }
711           else if (lex_match_id (lexer, "CONDENSE"))
712             {
713               rank.ties = TIES_CONDENSE;
714             }
715           else
716             {
717               lex_error (lexer, NULL);
718               goto error;
719             }
720         }
721       else if (lex_match_id (lexer, "FRACTION"))
722         {
723           lex_force_match (lexer, T_EQUALS);
724           if (lex_match_id (lexer, "BLOM"))
725             {
726               rank.fraction = FRAC_BLOM;
727             }
728           else if (lex_match_id (lexer, "TUKEY"))
729             {
730               rank.fraction = FRAC_TUKEY;
731             }
732           else if (lex_match_id (lexer, "VW"))
733             {
734               rank.fraction = FRAC_VW;
735             }
736           else if (lex_match_id (lexer, "RANKIT"))
737             {
738               rank.fraction = FRAC_RANKIT;
739             }
740           else
741             {
742               lex_error (lexer, NULL);
743               goto error;
744             }
745         }
746       else if (lex_match_id (lexer, "PRINT"))
747         {
748           lex_force_match (lexer, T_EQUALS);
749           if (lex_match_id (lexer, "YES"))
750             {
751               rank.print = true;
752             }
753           else if (lex_match_id (lexer, "NO"))
754             {
755               rank.print = false;
756             }
757           else
758             {
759               lex_error (lexer, NULL);
760               goto error;
761             }
762         }
763       else if (lex_match_id (lexer, "MISSING"))
764         {
765           lex_force_match (lexer, T_EQUALS);
766           if (lex_match_id (lexer, "INCLUDE"))
767             {
768               rank.exclude = MV_SYSTEM;
769             }
770           else if (lex_match_id (lexer, "EXCLUDE"))
771             {
772               rank.exclude = MV_ANY;
773             }
774           else
775             {
776               lex_error (lexer, NULL);
777               goto error;
778             }
779         }
780       else if (! parse_into (lexer, &rank))
781         goto error;
782     }
783
784
785   /* If no rank specs are given, then apply a default */
786   if ( rank.n_rs == 0)
787     {
788       rank.rs = pool_calloc (rank.pool, 1, sizeof (*rank.rs));
789       rank.n_rs = 1;
790       rank.rs[0].rfunc = RANK;
791       rank.rs[0].destvars = pool_calloc (rank.pool, rank.n_vars, sizeof (*rank.rs[0].destvars));
792     }
793
794   /* Create variables for all rank destinations which haven't
795      already been created with INTO.
796      Add labels to all the destination variables.
797   */
798   for (i = 0 ; i <  rank.n_rs ; ++i )
799     {
800       int v;
801       struct rank_spec *rs = &rank.rs[i];
802
803       for ( v = 0 ; v < rank.n_vars ;  v ++ )
804         {
805           if ( rs->destvars[v] == NULL )
806             {
807               rs->destvars[v] =
808                 create_rank_variable (rank.dict, rs->rfunc, rank.vars[v], NULL);
809             }
810
811           create_var_label (&rank, rs->destvars[v],
812                             rank.vars[v],
813                             rs->rfunc);
814         }
815     }
816
817   if ( rank.print )
818     {
819       int v;
820
821       tab_output_text (0, _("Variables Created By RANK"));
822       tab_output_text (0, "");
823
824       for (i = 0 ; i <  rank.n_rs ; ++i )
825         {
826           for ( v = 0 ; v < rank.n_vars ;  v ++ )
827             {
828               if ( rank.n_group_vars > 0 )
829                 {
830                   struct string varlist;
831                   int g;
832
833                   ds_init_empty (&varlist);
834                   for ( g = 0 ; g < rank.n_group_vars ; ++g )
835                     {
836                       ds_put_cstr (&varlist, var_get_name (rank.group_vars[g]));
837
838                       if ( g < rank.n_group_vars - 1)
839                         ds_put_cstr (&varlist, " ");
840                     }
841
842                   if ( rank.rs[i].rfunc == NORMAL ||
843                        rank.rs[i].rfunc == PROPORTION )
844                     tab_output_text_format (0,
845                                             _("%s into %s(%s of %s using %s BY %s)"),
846                                             var_get_name (rank.vars[v]),
847                                             var_get_name (rank.rs[i].destvars[v]),
848                                             function_name[rank.rs[i].rfunc],
849                                             var_get_name (rank.vars[v]),
850                                             fraction_name (&rank),
851                                             ds_cstr (&varlist));
852
853                   else
854                     tab_output_text_format (0,
855                                             _("%s into %s(%s of %s BY %s)"),
856                                             var_get_name (rank.vars[v]),
857                                             var_get_name (rank.rs[i].destvars[v]),
858                                             function_name[rank.rs[i].rfunc],
859                                             var_get_name (rank.vars[v]),
860                                             ds_cstr (&varlist));
861                   ds_destroy (&varlist);
862                 }
863               else
864                 {
865                   if ( rank.rs[i].rfunc == NORMAL ||
866                        rank.rs[i].rfunc == PROPORTION )
867                     tab_output_text_format (0,
868                                             _("%s into %s(%s of %s using %s)"),
869                                             var_get_name (rank.vars[v]),
870                                             var_get_name (rank.rs[i].destvars[v]),
871                                             function_name[rank.rs[i].rfunc],
872                                             var_get_name (rank.vars[v]),
873                                             fraction_name (&rank));
874
875                   else
876                     tab_output_text_format (0,
877                                             _("%s into %s(%s of %s)"),
878                                             var_get_name (rank.vars[v]),
879                                             var_get_name (rank.rs[i].destvars[v]),
880                                             function_name[rank.rs[i].rfunc],
881                                             var_get_name (rank.vars[v]));
882                 }
883             }
884         }
885     }
886
887   /* Add a variable which we can sort by to get back the original
888      order */
889   order = dict_create_var_assert (dataset_dict (ds), "$ORDER_", 0);
890
891   add_transformation (ds, create_resort_key, 0, order);
892
893   /* Do the ranking */
894   result = rank_cmd (ds, &rank);
895   
896   /* Put the active dataset back in its original order.  Delete
897      our sort key, which we don't need anymore.  */
898   {
899     struct casereader *sorted;
900
901
902     /* FIXME: loses error conditions. */
903
904     proc_discard_output (ds);
905     sorted = sort_execute_1var (proc_open (ds), order);
906     result = proc_commit (ds) && result;
907
908     dict_delete_var (dataset_dict (ds), order);
909     result = dataset_set_source (ds, sorted) && result;
910     if ( result != true)
911       goto error;
912   }
913
914   destroy_rank (&rank);
915   return CMD_SUCCESS;
916
917  error:
918
919   destroy_rank (&rank);
920   return CMD_FAILURE;
921 }
922
923
924
925 static bool
926 rank_cmd (struct dataset *ds, const struct rank *cmd)
927 {
928   struct dictionary *d = dataset_dict (ds);
929   bool ok = true;
930   int i;
931
932   for (i = 0 ; i < subcase_get_n_fields (&cmd->sc) ; ++i )
933     {
934       /* Rank variable at index I in SC. */
935       struct casegrouper *split_grouper;
936       struct casereader *split_group;
937       struct casewriter *output;
938
939       proc_discard_output (ds);
940       split_grouper = casegrouper_create_splits (proc_open (ds), d);
941       output = autopaging_writer_create (dict_get_proto (d));
942
943       while (casegrouper_get_next_group (split_grouper, &split_group))
944         {
945           struct subcase ordering;
946           struct casereader *ordered;
947           struct casegrouper *by_grouper;
948           struct casereader *by_group;
949
950           /* Sort this split group by the BY variables as primary
951              keys and the rank variable as secondary key. */
952           subcase_init_vars (&ordering, cmd->group_vars, cmd->n_group_vars);
953           subcase_add_var (&ordering, cmd->vars[i],
954                            subcase_get_direction (&cmd->sc, i));
955           ordered = sort_execute (split_group, &ordering);
956           subcase_destroy (&ordering);
957
958           /* Rank the rank variable within this split group. */
959           by_grouper = casegrouper_create_vars (ordered,
960                                                 cmd->group_vars, cmd->n_group_vars);
961           while (casegrouper_get_next_group (by_grouper, &by_group))
962             {
963               /* Rank the rank variable within this BY group
964                  within the split group. */
965
966               rank_sorted_file (by_group, output, d,  i, cmd);
967
968             }
969           ok = casegrouper_destroy (by_grouper) && ok;
970         }
971       ok = casegrouper_destroy (split_grouper);
972       ok = proc_commit (ds) && ok;
973       ok = (dataset_set_source (ds, casewriter_make_reader (output))
974             && ok);
975       if (!ok)
976         break;
977     }
978
979   return ok;
980 }