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