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