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