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