8a4151640e39321ffaee0e42b2ed3d62f0d58749
[pspp-builds.git] / src / frequencies.q
1 /* PSPP - computes sample statistics.
2    Copyright (C) 1997-9, 2000 Free Software Foundation, Inc.
3    Written by Ben Pfaff <blp@gnu.org>.
4
5    This program is free software; you can redistribute it and/or
6    modify it under the terms of the GNU General Public License as
7    published by the Free Software Foundation; either version 2 of the
8    License, or (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful, but
11    WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13    General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, write to the Free Software
17    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
18    02111-1307, USA. */
19
20 /*
21   TODO:
22
23   * Remember that histograms, bar charts need mean, stddev.
24 */
25
26 #include <config.h>
27 #include "error.h"
28 #include <math.h>
29 #include <stdlib.h>
30 #include "alloc.h"
31 #include "bitvector.h"
32 #include "hash.h"
33 #include "pool.h"
34 #include "command.h"
35 #include "lexer.h"
36 #include "moments.h"
37 #include "error.h"
38 #include "algorithm.h"
39 #include "magic.h"
40 #include "misc.h"
41 #include "output.h"
42 #include "som.h"
43 #include "str.h"
44 #include "tab.h"
45 #include "value-labels.h"
46 #include "var.h"
47 #include "vfm.h"
48 #include "settings.h"
49
50 #include "debug-print.h"
51
52 /* (specification)
53    FREQUENCIES (frq_):
54      *variables=custom;
55      format=cond:condense/onepage(*n:onepage_limit,"%s>=0")/!standard,
56             table:limit(n:limit,"%s>0")/notable/!table, 
57             labels:!labels/nolabels,
58             sort:!avalue/dvalue/afreq/dfreq,
59             spaces:!single/double,
60             paging:newpage/!oldpage;
61      missing=miss:include/!exclude;
62      barchart(ba_)=:minimum(d:min),
63             :maximum(d:max),
64             scale:freq(*n:freq,"%s>0")/percent(*n:pcnt,"%s>0");
65      histogram(hi_)=:minimum(d:min),
66             :maximum(d:max),
67             scale:freq(*n:freq,"%s>0")/percent(*n:pcnt,"%s>0"),
68             norm:!nonormal/normal,
69             incr:increment(d:inc,"%s>0");
70      hbar(hb_)=:minimum(d:min),
71             :maximum(d:max),
72             scale:freq(*n:freq,"%s>0")/percent(*n:pcnt,"%s>0"),
73             norm:!nonormal/normal,
74             incr:increment(d:inc,"%s>0");
75      grouped=custom;
76      ntiles=custom;
77      percentiles=custom;
78      statistics[st_]=1|mean,2|semean,3|median,4|mode,5|stddev,6|variance,
79             7|kurtosis,8|skewness,9|range,10|minimum,11|maximum,12|sum,
80             13|default,14|seskewness,15|sekurtosis,all,none.
81 */
82 /* (declarations) */
83 /* (functions) */
84
85 /* Description of a statistic. */
86 struct frq_info
87   {
88     int st_indx;                /* Index into a_statistics[]. */
89     const char *s10;            /* Identifying string. */
90   };
91
92 /* Table of statistics, indexed by dsc_*. */
93 static struct frq_info st_name[frq_n_stats + 1] =
94 {
95   {FRQ_ST_MEAN, N_("Mean")},
96   {FRQ_ST_SEMEAN, N_("S.E. Mean")},
97   {FRQ_ST_MEDIAN, N_("Median")},
98   {FRQ_ST_MODE, N_("Mode")},
99   {FRQ_ST_STDDEV, N_("Std Dev")},
100   {FRQ_ST_VARIANCE, N_("Variance")},
101   {FRQ_ST_KURTOSIS, N_("Kurtosis")},
102   {FRQ_ST_SEKURTOSIS, N_("S.E. Kurt")},
103   {FRQ_ST_SKEWNESS, N_("Skewness")},
104   {FRQ_ST_SESKEWNESS, N_("S.E. Skew")},
105   {FRQ_ST_RANGE, N_("Range")},
106   {FRQ_ST_MINIMUM, N_("Minimum")},
107   {FRQ_ST_MAXIMUM, N_("Maximum")},
108   {FRQ_ST_SUM, N_("Sum")},
109   {-1, 0},
110 };
111
112 /* Percentiles to calculate. */
113
114 struct percentile
115 {
116   double p;        /* the %ile to be calculated */
117   double value;    /* the %ile's value */
118   double x1;       /* The datum value <= the percentile */
119   double x2;       /* The datum value >= the percentile */
120   int flag;        
121   int flag2;       /* Set to 1 if this percentile value has been found */
122 };
123
124 static struct percentile *percentiles;
125 static int n_percentiles;
126
127 static int implicit_50th ; 
128
129 /* Groups of statistics. */
130 #define BI          BIT_INDEX
131 #define frq_default                                                     \
132         (BI (frq_mean) | BI (frq_stddev) | BI (frq_min) | BI (frq_max))
133 #define frq_all                                                 \
134         (BI (frq_sum) | BI(frq_min) | BI(frq_max)               \
135          | BI(frq_mean) | BI(frq_semean) | BI(frq_stddev)       \
136          | BI(frq_variance) | BI(frq_kurt) | BI(frq_sekurt)     \
137          | BI(frq_skew) | BI(frq_seskew) | BI(frq_range)        \
138          | BI(frq_range) | BI(frq_mode) | BI(frq_median))
139
140 /* Statistics; number of statistics. */
141 static unsigned long stats;
142 static int n_stats;
143
144 /* Types of graphs. */
145 enum
146   {
147     GFT_NONE,                   /* Don't draw graphs. */
148     GFT_BAR,                    /* Draw bar charts. */
149     GFT_HIST,                   /* Draw histograms. */
150     GFT_HBAR                    /* Draw bar charts or histograms at our discretion. */
151   };
152
153 /* Parsed command. */
154 static struct cmd_frequencies cmd;
155
156 /* Summary of the barchart, histogram, and hbar subcommands. */
157 static int chart;               /* NONE/BAR/HIST/HBAR. */
158 static double min, max;         /* Minimum, maximum on y axis. */
159 static int format;              /* FREQ/PERCENT: Scaling of y axis. */
160 static double scale, incr;      /* FIXME */
161 static int normal;              /* FIXME */
162
163 /* Variables for which to calculate statistics. */
164 static int n_variables;
165 static struct variable **v_variables;
166
167 /* Arenas used to store semi-permanent storage. */
168 static struct pool *int_pool;   /* Integer mode. */
169 static struct pool *gen_pool;   /* General mode. */
170
171 /* Easier access to a_statistics. */
172 #define stat cmd.a_statistics
173
174 static void determine_charts (void);
175
176 static void precalc (void *);
177 static int calc (struct ccase *, void *);
178 static void postcalc (void *);
179
180 static void postprocess_freq_tab (struct variable *);
181 static void dump_full (struct variable *);
182 static void dump_condensed (struct variable *);
183 static void dump_statistics (struct variable *, int show_varname);
184 static void cleanup_freq_tab (struct variable *);
185
186 static hsh_hash_func hash_value_numeric, hash_value_alpha;
187 static hsh_compare_func compare_value_numeric_a, compare_value_alpha_a;
188 static hsh_compare_func compare_value_numeric_d, compare_value_alpha_d;
189 static hsh_compare_func compare_freq_numeric_a, compare_freq_alpha_a;
190 static hsh_compare_func compare_freq_numeric_d, compare_freq_alpha_d;
191 \f
192 /* Parser and outline. */
193
194 static int internal_cmd_frequencies (void);
195
196 int
197 cmd_frequencies (void)
198 {
199   int result;
200
201   int_pool = pool_create ();
202   result = internal_cmd_frequencies ();
203   pool_destroy (int_pool);
204   int_pool=0;
205   pool_destroy (gen_pool);
206   gen_pool=0;
207   free (v_variables);
208   v_variables=0;
209   return result;
210 }
211
212 static int
213 internal_cmd_frequencies (void)
214 {
215   int i;
216
217   n_percentiles = 0;
218   percentiles = NULL;
219
220   n_variables = 0;
221   v_variables = NULL;
222
223   for (i = 0; i < dict_get_var_cnt (default_dict); i++)
224     dict_get_var(default_dict, i)->p.frq.used = 0;
225
226   if (!parse_frequencies (&cmd))
227     return CMD_FAILURE;
228
229   if (cmd.onepage_limit == NOT_LONG)
230     cmd.onepage_limit = 50;
231
232   /* Figure out statistics to calculate. */
233   stats = 0;
234   if (stat[FRQ_ST_DEFAULT] || !cmd.sbc_statistics)
235     stats |= frq_default;
236   if (stat[FRQ_ST_ALL])
237     stats |= frq_all;
238   if (cmd.sort != FRQ_AVALUE && cmd.sort != FRQ_DVALUE)
239     stats &= ~frq_median;
240   for (i = 0; i < frq_n_stats; i++)
241     if (stat[st_name[i].st_indx])
242       stats |= BIT_INDEX (i);
243   if (stats & frq_kurt)
244     stats |= frq_sekurt;
245   if (stats & frq_skew)
246     stats |= frq_seskew;
247
248   /* Calculate n_stats. */
249   n_stats = 0;
250   for (i = 0; i < frq_n_stats; i++)
251     if ((stats & BIT_INDEX (i)))
252       n_stats++;
253
254   /* Charting. */
255   determine_charts ();
256   if (chart != GFT_NONE || cmd.sbc_ntiles)
257     cmd.sort = FRQ_AVALUE;
258
259   /* Do it! */
260   procedure_with_splits (precalc, calc, postcalc, NULL);
261
262   return CMD_SUCCESS;
263 }
264
265 /* Figure out which charts the user requested.  */
266 static void
267 determine_charts (void)
268 {
269   int count = (!!cmd.sbc_histogram) + (!!cmd.sbc_barchart) + (!!cmd.sbc_hbar);
270
271   if (!count)
272     {
273       chart = GFT_NONE;
274       return;
275     }
276   else if (count > 1)
277     {
278       chart = GFT_HBAR;
279       msg (SW, _("At most one of BARCHART, HISTOGRAM, or HBAR should be "
280            "given.  HBAR will be assumed.  Argument values will be "
281            "given precedence increasing along the order given."));
282     }
283   else if (cmd.sbc_histogram)
284     chart = GFT_HIST;
285   else if (cmd.sbc_barchart)
286     chart = GFT_BAR;
287   else
288     chart = GFT_HBAR;
289
290   min = max = SYSMIS;
291   format = FRQ_FREQ;
292   scale = SYSMIS;
293   incr = SYSMIS;
294   normal = 0;
295
296   if (cmd.sbc_barchart)
297     {
298       if (cmd.ba_min != SYSMIS)
299         min = cmd.ba_min;
300       if (cmd.ba_max != SYSMIS)
301         max = cmd.ba_max;
302       if (cmd.ba_scale == FRQ_FREQ)
303         {
304           format = FRQ_FREQ;
305           scale = cmd.ba_freq;
306         }
307       else if (cmd.ba_scale == FRQ_PERCENT)
308         {
309           format = FRQ_PERCENT;
310           scale = cmd.ba_pcnt;
311         }
312     }
313
314   if (cmd.sbc_histogram)
315     {
316       if (cmd.hi_min != SYSMIS)
317         min = cmd.hi_min;
318       if (cmd.hi_max != SYSMIS)
319         max = cmd.hi_max;
320       if (cmd.hi_scale == FRQ_FREQ)
321         {
322           format = FRQ_FREQ;
323           scale = cmd.hi_freq;
324         }
325       else if (cmd.hi_scale == FRQ_PERCENT)
326         {
327           format = FRQ_PERCENT;
328           scale = cmd.ba_pcnt;
329         }
330       if (cmd.hi_norm)
331         normal = 1;
332       if (cmd.hi_incr == FRQ_INCREMENT)
333         incr = cmd.hi_inc;
334     }
335
336   if (cmd.sbc_hbar)
337     {
338       if (cmd.hb_min != SYSMIS)
339         min = cmd.hb_min;
340       if (cmd.hb_max != SYSMIS)
341         max = cmd.hb_max;
342       if (cmd.hb_scale == FRQ_FREQ)
343         {
344           format = FRQ_FREQ;
345           scale = cmd.hb_freq;
346         }
347       else if (cmd.hb_scale == FRQ_PERCENT)
348         {
349           format = FRQ_PERCENT;
350           scale = cmd.ba_pcnt;
351         }
352       if (cmd.hb_norm)
353         normal = 1;
354       if (cmd.hb_incr == FRQ_INCREMENT)
355         incr = cmd.hb_inc;
356     }
357
358   if (min != SYSMIS && max != SYSMIS && min >= max)
359     {
360       msg (SE, _("MAX must be greater than or equal to MIN, if both are "
361            "specified.  However, MIN was specified as %g and MAX as %g.  "
362            "MIN and MAX will be ignored."), min, max);
363       min = max = SYSMIS;
364     }
365 }
366
367 /* Add data from case C to the frequency table. */
368 static int
369 calc (struct ccase *c, void *aux UNUSED)
370 {
371   double weight;
372   int i;
373   int bad_warn = 1;
374
375   weight = dict_get_case_weight (default_dict, c, &bad_warn);
376
377   for (i = 0; i < n_variables; i++)
378     {
379       struct variable *v = v_variables[i];
380       union value *val = &c->data[v->fv];
381       struct freq_tab *ft = &v->p.frq.tab;
382
383       switch (v->p.frq.tab.mode)
384         {
385           case FRQM_GENERAL:
386             {
387               /* General mode. */
388               struct freq **fpp = (struct freq **) hsh_probe (ft->data, val);
389           
390               if (*fpp != NULL)
391                 (*fpp)->c += weight;
392               else
393                 {
394                   struct freq *fp = *fpp = pool_alloc (gen_pool, sizeof *fp);
395                   fp->v = *val;
396                   fp->c = weight;
397                 }
398             }
399           break;
400         case FRQM_INTEGER:
401           /* Integer mode. */
402           if (val->f == SYSMIS)
403             v->p.frq.tab.sysmis += weight;
404           else if (val->f > INT_MIN+1 && val->f < INT_MAX-1)
405             {
406               int i = val->f;
407               if (i >= v->p.frq.tab.min && i <= v->p.frq.tab.max)
408                 v->p.frq.tab.vector[i - v->p.frq.tab.min] += weight;
409             }
410           else
411             v->p.frq.tab.out_of_range += weight;
412           break;
413         default:
414           assert (0);
415         }
416     }
417   return 1;
418 }
419
420 /* Prepares each variable that is the target of FREQUENCIES by setting
421    up its hash table. */
422 static void
423 precalc (void *aux UNUSED)
424 {
425   int i;
426
427   pool_destroy (gen_pool);
428   gen_pool = pool_create ();
429   
430   for (i = 0; i < n_variables; i++)
431     {
432       struct variable *v = v_variables[i];
433
434       if (v->p.frq.tab.mode == FRQM_GENERAL)
435         {
436           hsh_hash_func *hash;
437           hsh_compare_func *compare;
438
439           if (v->type == NUMERIC) 
440             {
441               hash = hash_value_numeric;
442               compare = compare_value_numeric_a; 
443             }
444           else 
445             {
446               hash = hash_value_alpha;
447               compare = compare_value_alpha_a;
448             }
449           v->p.frq.tab.data = hsh_create (16, compare, hash, NULL, v);
450         }
451       else
452         {
453           int j;
454
455           for (j = (v->p.frq.tab.max - v->p.frq.tab.min); j >= 0; j--)
456             v->p.frq.tab.vector[j] = 0.0;
457           v->p.frq.tab.out_of_range = 0.0;
458           v->p.frq.tab.sysmis = 0.0;
459         }
460     }
461 }
462
463 /* Finishes up with the variables after frequencies have been
464    calculated.  Displays statistics, percentiles, ... */
465 static void
466 postcalc (void *aux UNUSED)
467 {
468   int i;
469
470   for (i = 0; i < n_variables; i++)
471     {
472       struct variable *v = v_variables[i];
473       int n_categories;
474       int dumped_freq_tab = 1;
475
476       postprocess_freq_tab (v);
477
478       /* Frequencies tables. */
479       n_categories = v->p.frq.tab.n_valid + v->p.frq.tab.n_missing;
480       if (cmd.table == FRQ_TABLE
481           || (cmd.table == FRQ_LIMIT && n_categories <= cmd.limit))
482         switch (cmd.cond)
483           {
484           case FRQ_CONDENSE:
485             dump_condensed (v);
486             break;
487           case FRQ_STANDARD:
488             dump_full (v);
489             break;
490           case FRQ_ONEPAGE:
491             if (n_categories > cmd.onepage_limit)
492               dump_condensed (v);
493             else
494               dump_full (v);
495             break;
496           default:
497             assert (0);
498           }
499       else
500         dumped_freq_tab = 0;
501
502       /* Statistics. */
503       if (n_stats)
504         dump_statistics (v, !dumped_freq_tab);
505
506       cleanup_freq_tab (v);
507     }
508 }
509
510 /* Returns the comparison function that should be used for
511    sorting a frequency table by FRQ_SORT using VAR_TYPE
512    variables. */
513 static hsh_compare_func *
514 get_freq_comparator (int frq_sort, int var_type) 
515 {
516   /* Note that q2c generates tags beginning with 1000. */
517   switch (frq_sort | (var_type << 16))
518     {
519     case FRQ_AVALUE | (NUMERIC << 16):  return compare_value_numeric_a;
520     case FRQ_AVALUE | (ALPHA << 16):    return compare_value_alpha_a;
521     case FRQ_DVALUE | (NUMERIC << 16):  return compare_value_numeric_d;
522     case FRQ_DVALUE | (ALPHA << 16):    return compare_value_alpha_d;
523     case FRQ_AFREQ | (NUMERIC << 16):   return compare_freq_numeric_a;
524     case FRQ_AFREQ | (ALPHA << 16):     return compare_freq_alpha_a;
525     case FRQ_DFREQ | (NUMERIC << 16):   return compare_freq_numeric_d;
526     case FRQ_DFREQ | (ALPHA << 16):     return compare_freq_alpha_d;
527     default: assert (0);
528     }
529
530   return 0;
531 }
532
533 /* Returns nonzero iff the value in struct freq F is non-missing
534    for variable V. */
535 static int
536 not_missing (const void *f_, void *v_) 
537 {
538   const struct freq *f = f_;
539   struct variable *v = v_;
540
541   return !is_missing (&f->v, v);
542 }
543
544 /* Summarizes the frequency table data for variable V. */
545 static void
546 postprocess_freq_tab (struct variable *v)
547 {
548   hsh_compare_func *compare;
549   struct freq_tab *ft;
550   size_t count;
551   void **data;
552   struct freq *freqs, *f;
553   size_t i;
554
555   assert (v->p.frq.tab.mode == FRQM_GENERAL);
556   compare = get_freq_comparator (cmd.sort, v->type);
557   ft = &v->p.frq.tab;
558
559   /* Extract data from hash table. */
560   count = hsh_count (ft->data);
561   data = hsh_data (ft->data);
562
563   /* Copy dereferenced data into freqs. */
564   freqs = xmalloc (count* sizeof *freqs);
565   for (i = 0; i < count; i++) 
566     {
567       struct freq *f = data[i];
568       freqs[i] = *f; 
569     }
570
571   /* Put data into ft. */
572   ft->valid = freqs;
573   ft->n_valid = partition (freqs, count, sizeof *freqs, not_missing, v);
574   ft->missing = freqs + ft->n_valid;
575   ft->n_missing = count - ft->n_valid;
576
577   /* Sort data. */
578   sort (ft->valid, ft->n_valid, sizeof *ft->valid, compare, v);
579   sort (ft->missing, ft->n_missing, sizeof *ft->missing, compare, v);
580
581   /* Summary statistics. */
582   ft->valid_cases = 0.0;
583   for(i = 0 ;  i < ft->n_valid ; ++i ) 
584     {
585       f = &ft->valid[i];
586       ft->valid_cases += f->c;
587
588     }
589
590   ft->total_cases = ft->valid_cases ; 
591   for(i = 0 ;  i < ft->n_missing ; ++i ) 
592     {
593       f = &ft->missing[i];
594       ft->total_cases += f->c;
595     }
596
597 }
598
599 /* Frees the frequency table for variable V. */
600 static void
601 cleanup_freq_tab (struct variable *v)
602 {
603   assert (v->p.frq.tab.mode == FRQM_GENERAL);
604   free (v->p.frq.tab.valid);
605   hsh_destroy (v->p.frq.tab.data);
606 }
607
608 /* Parses the VARIABLES subcommand, adding to
609    {n_variables,v_variables}. */
610 static int
611 frq_custom_variables (struct cmd_frequencies *cmd UNUSED)
612 {
613   int mode;
614   int min = 0, max = 0;
615
616   int old_n_variables = n_variables;
617   int i;
618
619   lex_match ('=');
620   if (token != T_ALL && (token != T_ID
621                          || dict_lookup_var (default_dict, tokid) == NULL))
622     return 2;
623
624   if (!parse_variables (default_dict, &v_variables, &n_variables,
625                         PV_APPEND | PV_NO_SCRATCH))
626     return 0;
627
628   for (i = old_n_variables; i < n_variables; i++)
629     v_variables[i]->p.frq.tab.mode = FRQM_GENERAL;
630
631   if (!lex_match ('('))
632     mode = FRQM_GENERAL;
633   else
634     {
635       mode = FRQM_INTEGER;
636       if (!lex_force_int ())
637         return 0;
638       min = lex_integer ();
639       lex_get ();
640       if (!lex_force_match (','))
641         return 0;
642       if (!lex_force_int ())
643         return 0;
644       max = lex_integer ();
645       lex_get ();
646       if (!lex_force_match (')'))
647         return 0;
648       if (max < min)
649         {
650           msg (SE, _("Upper limit of integer mode value range must be "
651                      "greater than lower limit."));
652           return 0;
653         }
654     }
655
656   for (i = old_n_variables; i < n_variables; i++)
657     {
658       struct variable *v = v_variables[i];
659
660       if (v->p.frq.used != 0)
661         {
662           msg (SE, _("Variable %s specified multiple times on VARIABLES "
663                      "subcommand."), v->name);
664           return 0;
665         }
666       
667       v->p.frq.used = 1;                /* Used simply as a marker. */
668
669       v->p.frq.tab.valid = v->p.frq.tab.missing = NULL;
670
671       if (mode == FRQM_INTEGER)
672         {
673           if (v->type != NUMERIC)
674             {
675               msg (SE, _("Integer mode specified, but %s is not a numeric "
676                          "variable."), v->name);
677               return 0;
678             }
679           
680           v->p.frq.tab.min = min;
681           v->p.frq.tab.max = max;
682           v->p.frq.tab.vector = pool_alloc (int_pool,
683                                             sizeof (struct freq) * (max - min + 1));
684         }
685       else
686         v->p.frq.tab.vector = NULL;
687
688       v->p.frq.n_groups = 0;
689       v->p.frq.groups = NULL;
690     }
691   return 1;
692 }
693
694 /* Parses the GROUPED subcommand, setting the frq.{n_grouped,grouped}
695    fields of specified variables. */
696 static int
697 frq_custom_grouped (struct cmd_frequencies *cmd UNUSED)
698 {
699   lex_match ('=');
700   if ((token == T_ID && dict_lookup_var (default_dict, tokid) != NULL)
701       || token == T_ID)
702     for (;;)
703       {
704         int i;
705
706         /* Max, current size of list; list itself. */
707         int nl, ml;
708         double *dl;
709
710         /* Variable list. */
711         int n;
712         struct variable **v;
713
714         if (!parse_variables (default_dict, &v, &n,
715                               PV_NO_DUPLICATE | PV_NUMERIC))
716           return 0;
717         if (lex_match ('('))
718           {
719             nl = ml = 0;
720             dl = NULL;
721             while (token == T_NUM)
722               {
723                 if (nl >= ml)
724                   {
725                     ml += 16;
726                     dl = pool_realloc (int_pool, dl, ml * sizeof (double));
727                   }
728                 dl[nl++] = tokval;
729                 lex_get ();
730                 lex_match (',');
731               }
732             /* Note that nl might still be 0 and dl might still be
733                NULL.  That's okay. */
734             if (!lex_match (')'))
735               {
736                 free (v);
737                 msg (SE, _("`)' expected after GROUPED interval list."));
738                 return 0;
739               }
740           }
741         else 
742           {
743             nl = 0;
744             dl = NULL;
745           }
746
747         for (i = 0; i < n; i++)
748           {
749             if (v[i]->p.frq.used == 0)
750               msg (SE, _("Variables %s specified on GROUPED but not on "
751                    "VARIABLES."), v[i]->name);
752             if (v[i]->p.frq.groups != NULL)
753               msg (SE, _("Variables %s specified multiple times on GROUPED "
754                    "subcommand."), v[i]->name);
755             else
756               {
757                 v[i]->p.frq.n_groups = nl;
758                 v[i]->p.frq.groups = dl;
759               }
760           }
761         free (v);
762         if (!lex_match ('/'))
763           break;
764         if ((token != T_ID || dict_lookup_var (default_dict, tokid) != NULL)
765             && token != T_ALL)
766           {
767             lex_put_back ('/');
768             break;
769           }
770       }
771
772   return 1;
773 }
774
775 /* Adds X to the list of percentiles, keeping the list in proper
776    order. */
777 static void
778 add_percentile (double x)
779 {
780   int i;
781
782   for (i = 0; i < n_percentiles; i++)
783     if (x <= percentiles[i].p)
784       break;
785
786   if (i >= n_percentiles || tokval != percentiles[i].p)
787     {
788       percentiles
789         = pool_realloc (int_pool, percentiles,
790                         (n_percentiles + 1) * sizeof (struct percentile ));
791
792       if (i < n_percentiles)
793           memmove (&percentiles[i + 1], &percentiles[i],
794                    (n_percentiles - i) * sizeof (struct percentile) );
795
796       percentiles[i].p = x;
797       n_percentiles++;
798     }
799 }
800
801 /* Parses the PERCENTILES subcommand, adding user-specified
802    percentiles to the list. */
803 static int
804 frq_custom_percentiles (struct cmd_frequencies *cmd UNUSED)
805 {
806   lex_match ('=');
807   if (token != T_NUM)
808     {
809       msg (SE, _("Percentile list expected after PERCENTILES."));
810       return 0;
811     }
812   
813   do
814     {
815       if (tokval < 0 || tokval > 100)
816         {
817           msg (SE, _("Percentiles must be between 0 and 100."));
818           return 0;
819         }
820       
821       add_percentile (tokval / 100.0);
822       lex_get ();
823       lex_match (',');
824     }
825   while (token == T_NUM);
826   return 1;
827 }
828
829 /* Parses the NTILES subcommand, adding the percentiles that
830    correspond to the specified evenly-distributed ntiles. */
831 static int
832 frq_custom_ntiles (struct cmd_frequencies *cmd UNUSED)
833 {
834   int i;
835
836   lex_match ('=');
837   if (!lex_force_int ())
838     return 0;
839   for (i = 1; i < lex_integer (); i++)
840     add_percentile (1.0 / lex_integer () * i);
841   lex_get ();
842   return 1;
843 }
844 \f
845 /* Comparison functions. */
846
847 /* Hash of numeric values. */
848 static unsigned
849 hash_value_numeric (const void *value_, void *foo UNUSED)
850 {
851   const struct freq *value = value_;
852   return hsh_hash_double (value->v.f);
853 }
854
855 /* Hash of string values. */
856 static unsigned
857 hash_value_alpha (const void *value_, void *v_)
858 {
859   const struct freq *value = value_;
860   struct variable *v = v_;
861
862   return hsh_hash_bytes (value->v.s, v->width);
863 }
864
865 /* Ascending numeric compare of values. */
866 static int
867 compare_value_numeric_a (const void *a_, const void *b_, void *foo UNUSED)
868 {
869   const struct freq *a = a_;
870   const struct freq *b = b_;
871
872   if (a->v.f > b->v.f)
873     return 1;
874   else if (a->v.f < b->v.f)
875     return -1;
876   else
877     return 0;
878 }
879
880 /* Ascending string compare of values. */
881 static int
882 compare_value_alpha_a (const void *a_, const void *b_, void *v_)
883 {
884   const struct freq *a = a_;
885   const struct freq *b = b_;
886   const struct variable *v = v_;
887
888   return memcmp (a->v.s, b->v.s, v->width);
889 }
890
891 /* Descending numeric compare of values. */
892 static int
893 compare_value_numeric_d (const void *a, const void *b, void *foo UNUSED)
894 {
895   return -compare_value_numeric_a (a, b, foo);
896 }
897
898 /* Descending string compare of values. */
899 static int
900 compare_value_alpha_d (const void *a, const void *b, void *v)
901 {
902   return -compare_value_alpha_a (a, b, v);
903 }
904
905 /* Ascending numeric compare of frequency;
906    secondary key on ascending numeric value. */
907 static int
908 compare_freq_numeric_a (const void *a_, const void *b_, void *foo UNUSED)
909 {
910   const struct freq *a = a_;
911   const struct freq *b = b_;
912
913   if (a->c > b->c)
914     return 1;
915   else if (a->c < b->c)
916     return -1;
917
918   if (a->v.f > b->v.f)
919     return 1;
920   else if (a->v.f < b->v.f)
921     return -1;
922   else
923     return 0;
924 }
925
926 /* Ascending numeric compare of frequency;
927    secondary key on ascending string value. */
928 static int
929 compare_freq_alpha_a (const void *a_, const void *b_, void *v_)
930 {
931   const struct freq *a = a_;
932   const struct freq *b = b_;
933   const struct variable *v = v_;
934
935   if (a->c > b->c)
936     return 1;
937   else if (a->c < b->c)
938     return -1;
939   else
940     return memcmp (a->v.s, b->v.s, v->width);
941 }
942
943 /* Descending numeric compare of frequency;
944    secondary key on ascending numeric value. */
945 static int
946 compare_freq_numeric_d (const void *a_, const void *b_, void *foo UNUSED)
947 {
948   const struct freq *a = a_;
949   const struct freq *b = b_;
950
951   if (a->c > b->c)
952     return -1;
953   else if (a->c < b->c)
954     return 1;
955
956   if (a->v.f > b->v.f)
957     return 1;
958   else if (a->v.f < b->v.f)
959     return -1;
960   else
961     return 0;
962 }
963
964 /* Descending numeric compare of frequency;
965    secondary key on ascending string value. */
966 static int
967 compare_freq_alpha_d (const void *a_, const void *b_, void *v_)
968 {
969   const struct freq *a = a_;
970   const struct freq *b = b_;
971   const struct variable *v = v_;
972
973   if (a->c > b->c)
974     return -1;
975   else if (a->c < b->c)
976     return 1;
977   else
978     return memcmp (a->v.s, b->v.s, v->width);
979 }
980 \f
981 /* Frequency table display. */
982
983 /* Sets the widths of all the columns and heights of all the rows in
984    table T for driver D. */
985 static void
986 full_dim (struct tab_table *t, struct outp_driver *d)
987 {
988   int lab = cmd.labels == FRQ_LABELS;
989   int i;
990
991   if (lab)
992     t->w[0] = min (tab_natural_width (t, d, 0), d->prop_em_width * 15);
993   for (i = lab; i < lab + 5; i++)
994     t->w[i] = max (tab_natural_width (t, d, i), d->prop_em_width * 8);
995   for (i = 0; i < t->nr; i++)
996     t->h[i] = d->font_height;
997 }
998
999 /* Displays a full frequency table for variable V. */
1000 static void
1001 dump_full (struct variable * v)
1002 {
1003   int n_categories;
1004   struct freq *f;
1005   struct tab_table *t;
1006   int r;
1007   double cum_total = 0.0;
1008   double cum_freq = 0.0;
1009
1010   struct init
1011     {
1012       int c, r;
1013       const char *s;
1014     };
1015
1016   struct init *p;
1017
1018   static struct init vec[] =
1019   {
1020     {4, 0, N_("Valid")},
1021     {5, 0, N_("Cum")},
1022     {1, 1, N_("Value")},
1023     {2, 1, N_("Frequency")},
1024     {3, 1, N_("Percent")},
1025     {4, 1, N_("Percent")},
1026     {5, 1, N_("Percent")},
1027     {0, 0, NULL},
1028     {1, 0, NULL},
1029     {2, 0, NULL},
1030     {3, 0, NULL},
1031     {-1, -1, NULL},
1032   };
1033
1034   int lab = cmd.labels == FRQ_LABELS;
1035
1036   n_categories = v->p.frq.tab.n_valid + v->p.frq.tab.n_missing;
1037   t = tab_create (5 + lab, n_categories + 3, 0);
1038   tab_headers (t, 0, 0, 2, 0);
1039   tab_dim (t, full_dim);
1040
1041   if (lab)
1042     tab_text (t, 0, 1, TAB_CENTER | TAT_TITLE, _("Value Label"));
1043   for (p = vec; p->s; p++)
1044     tab_text (t, p->c - (p->r ? !lab : 0), p->r,
1045                   TAB_CENTER | TAT_TITLE, gettext (p->s));
1046
1047   r = 2;
1048   for (f = v->p.frq.tab.valid; f < v->p.frq.tab.missing; f++)
1049     {
1050       double percent, valid_percent;
1051
1052       cum_freq += f->c;
1053
1054       percent = f->c / v->p.frq.tab.total_cases * 100.0;
1055       valid_percent = f->c / v->p.frq.tab.valid_cases * 100.0;
1056       cum_total += valid_percent;
1057
1058       if (lab)
1059         {
1060           const char *label = val_labs_find (v->val_labs, f->v);
1061           if (label != NULL)
1062             tab_text (t, 0, r, TAB_LEFT, label);
1063         }
1064
1065       tab_value (t, 0 + lab, r, TAB_NONE, &f->v, &v->print);
1066       tab_float (t, 1 + lab, r, TAB_NONE, f->c, 8, 0);
1067       tab_float (t, 2 + lab, r, TAB_NONE, percent, 5, 1);
1068       tab_float (t, 3 + lab, r, TAB_NONE, valid_percent, 5, 1);
1069       tab_float (t, 4 + lab, r, TAB_NONE, cum_total, 5, 1);
1070       r++;
1071     }
1072   for (; f < &v->p.frq.tab.valid[n_categories]; f++)
1073     {
1074       cum_freq += f->c;
1075
1076       if (lab)
1077         {
1078           const char *label = val_labs_find (v->val_labs, f->v);
1079           if (label != NULL)
1080             tab_text (t, 0, r, TAB_LEFT, label);
1081         }
1082
1083       tab_value (t, 0 + lab, r, TAB_NONE, &f->v, &v->print);
1084       tab_float (t, 1 + lab, r, TAB_NONE, f->c, 8, 0);
1085       tab_float (t, 2 + lab, r, TAB_NONE,
1086                      f->c / v->p.frq.tab.total_cases * 100.0, 5, 1);
1087       tab_text (t, 3 + lab, r, TAB_NONE, _("Missing"));
1088       r++;
1089     }
1090
1091   tab_box (t, TAL_1, TAL_1,
1092            cmd.spaces == FRQ_SINGLE ? -1 : (TAL_1 | TAL_SPACING), TAL_1,
1093            0, 0, 4 + lab, r);
1094   tab_hline (t, TAL_2, 0, 4 + lab, 2);
1095   tab_hline (t, TAL_2, 0, 4 + lab, r);
1096   tab_joint_text (t, 0, r, 0 + lab, r, TAB_RIGHT | TAT_TITLE, _("Total"));
1097   tab_vline (t, TAL_0, 1, r, r);
1098   tab_float (t, 1 + lab, r, TAB_NONE, cum_freq, 8, 0);
1099   tab_float (t, 2 + lab, r, TAB_NONE, 100.0, 5, 1);
1100   tab_float (t, 3 + lab, r, TAB_NONE, 100.0, 5, 1);
1101
1102   tab_title (t, 1, "%s: %s", v->name, v->label ? v->label : "");
1103   tab_submit (t);
1104 }
1105
1106 /* Sets the widths of all the columns and heights of all the rows in
1107    table T for driver D. */
1108 static void
1109 condensed_dim (struct tab_table *t, struct outp_driver *d)
1110 {
1111   int cum_w = max (outp_string_width (d, _("Cum")),
1112                    max (outp_string_width (d, _("Cum")),
1113                         outp_string_width (d, "000")));
1114
1115   int i;
1116
1117   for (i = 0; i < 2; i++)
1118     t->w[i] = max (tab_natural_width (t, d, i), d->prop_em_width * 8);
1119   for (i = 2; i < 4; i++)
1120     t->w[i] = cum_w;
1121   for (i = 0; i < t->nr; i++)
1122     t->h[i] = d->font_height;
1123 }
1124
1125 /* Display condensed frequency table for variable V. */
1126 static void
1127 dump_condensed (struct variable * v)
1128 {
1129   int n_categories;
1130   struct freq *f;
1131   struct tab_table *t;
1132   int r;
1133   double cum_total = 0.0;
1134
1135   n_categories = v->p.frq.tab.n_valid + v->p.frq.tab.n_missing;
1136   t = tab_create (4, n_categories + 2, 0);
1137
1138   tab_headers (t, 0, 0, 2, 0);
1139   tab_text (t, 0, 1, TAB_CENTER | TAT_TITLE, _("Value"));
1140   tab_text (t, 1, 1, TAB_CENTER | TAT_TITLE, _("Freq"));
1141   tab_text (t, 2, 1, TAB_CENTER | TAT_TITLE, _("Pct"));
1142   tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("Cum"));
1143   tab_text (t, 3, 1, TAB_CENTER | TAT_TITLE, _("Pct"));
1144   tab_dim (t, condensed_dim);
1145
1146   r = 2;
1147   for (f = v->p.frq.tab.valid; f < v->p.frq.tab.missing; f++)
1148     {
1149       double percent;
1150
1151       percent = f->c / v->p.frq.tab.total_cases * 100.0;
1152       cum_total += f->c / v->p.frq.tab.valid_cases * 100.0;
1153
1154       tab_value (t, 0, r, TAB_NONE, &f->v, &v->print);
1155       tab_float (t, 1, r, TAB_NONE, f->c, 8, 0);
1156       tab_float (t, 2, r, TAB_NONE, percent, 3, 0);
1157       tab_float (t, 3, r, TAB_NONE, cum_total, 3, 0);
1158       r++;
1159     }
1160   for (; f < &v->p.frq.tab.valid[n_categories]; f++)
1161     {
1162       tab_value (t, 0, r, TAB_NONE, &f->v, &v->print);
1163       tab_float (t, 1, r, TAB_NONE, f->c, 8, 0);
1164       tab_float (t, 2, r, TAB_NONE,
1165                  f->c / v->p.frq.tab.total_cases * 100.0, 3, 0);
1166       r++;
1167     }
1168
1169   tab_box (t, TAL_1, TAL_1,
1170            cmd.spaces == FRQ_SINGLE ? -1 : (TAL_1 | TAL_SPACING), TAL_1,
1171            0, 0, 3, r - 1);
1172   tab_hline (t, TAL_2, 0, 3, 2);
1173   tab_title (t, 1, "%s: %s", v->name, v->label ? v->label : "");
1174   tab_columns (t, SOM_COL_DOWN, 1);
1175   tab_submit (t);
1176 }
1177 \f
1178 /* Statistical display. */
1179
1180 /* Calculates all the pertinent statistics for variable V, putting
1181    them in array D[].  FIXME: This could be made much more optimal. */
1182 static void
1183 calc_stats (struct variable * v, double d[frq_n_stats])
1184 {
1185   double W = v->p.frq.tab.valid_cases;
1186   struct moments *m;
1187   struct freq *f=0; 
1188   int most_often;
1189   double X_mode;
1190
1191   double rank;
1192   int i = 0;
1193   int idx;
1194   double *median_value;
1195
1196   /* Calculate percentiles. */
1197
1198   /* If the 50th percentile was not explicitly requested then we must 
1199      calculate it anyway --- it's the median */
1200   median_value = 0 ;
1201   for (i = 0; i < n_percentiles; i++) 
1202     {
1203       if (percentiles[i].p == 0.5)
1204         {
1205           median_value = &percentiles[i].value;
1206           break;
1207         }
1208     }
1209
1210   if ( 0 == median_value )  
1211     {
1212       add_percentile (0.5);
1213       implicit_50th = 1;
1214     }
1215
1216   for (i = 0; i < n_percentiles; i++) 
1217     {
1218       percentiles[i].flag = 0;
1219       percentiles[i].flag2 = 0;
1220     }
1221
1222   rank = 0;
1223   for (idx = 0; idx < v->p.frq.tab.n_valid; ++idx)
1224     {
1225       static double prev_value = SYSMIS;
1226       f = &v->p.frq.tab.valid[idx]; 
1227       rank += f->c ;
1228       for (i = 0; i < n_percentiles; i++) 
1229         {
1230           double tp;
1231           if ( percentiles[i].flag2  ) continue ; 
1232
1233           if ( get_algorithm() != COMPATIBLE ) 
1234             tp = 
1235               (v->p.frq.tab.valid_cases - 1) *  percentiles[i].p;
1236           else
1237             tp = 
1238               (v->p.frq.tab.valid_cases + 1) *  percentiles[i].p - 1;
1239
1240           if ( percentiles[i].flag ) 
1241             {
1242               percentiles[i].x2 = f->v.f;
1243               percentiles[i].x1 = prev_value;
1244               percentiles[i].flag2 = 1;
1245               continue;
1246             }
1247
1248           if (rank >  tp ) 
1249           {
1250             if ( f->c > 1 && rank - (f->c - 1) > tp ) 
1251               {
1252                 percentiles[i].x2 = percentiles[i].x1 = f->v.f;
1253                 percentiles[i].flag2 = 1;
1254               }
1255             else
1256               {
1257                 percentiles[i].flag=1;
1258               }
1259
1260             continue;
1261           }
1262         }
1263       prev_value = f->v.f;
1264     }
1265
1266   for (i = 0; i < n_percentiles; i++) 
1267     {
1268       /* Catches the case when p == 100% */
1269       if ( ! percentiles[i].flag2 ) 
1270         percentiles[i].x1 = percentiles[i].x2 = f->v.f;
1271
1272       /*
1273       printf("percentile %d (p==%.2f); X1 = %g; X2 = %g\n",
1274              i,percentiles[i].p,percentiles[i].x1,percentiles[i].x2);
1275       */
1276     }
1277
1278   for (i = 0; i < n_percentiles; i++) 
1279     {
1280       struct freq_tab *ft = &v->p.frq.tab;
1281       double s;
1282
1283       double dummy;
1284       if ( get_algorithm() != COMPATIBLE ) 
1285         {
1286           s = modf((ft->valid_cases - 1) *  percentiles[i].p , &dummy);
1287         }
1288       else
1289         {
1290           s = modf((ft->valid_cases + 1) *  percentiles[i].p -1, &dummy);
1291         }
1292
1293       percentiles[i].value = percentiles[i].x1 + 
1294         ( percentiles[i].x2 - percentiles[i].x1) * s ; 
1295
1296       if ( percentiles[i].p == 0.50) 
1297         median_value = &percentiles[i].value; 
1298     }
1299
1300
1301   /* Calculate the mode. */
1302   most_often = -1;
1303   X_mode = SYSMIS;
1304   for (f = v->p.frq.tab.valid; f < v->p.frq.tab.missing; f++)
1305     {
1306       if (most_often < f->c) 
1307         {
1308           most_often = f->c;
1309           X_mode = f->v.f;
1310         }
1311       else if (most_often == f->c) 
1312         {
1313           /* A duplicate mode is undefined.
1314              FIXME: keep track of *all* the modes. */
1315           X_mode = SYSMIS;
1316         }
1317     }
1318
1319   /* Calculate moments. */
1320   m = moments_create (MOMENT_KURTOSIS);
1321   for (f = v->p.frq.tab.valid; f < v->p.frq.tab.missing; f++)
1322     moments_pass_one (m, f->v.f, f->c);
1323   for (f = v->p.frq.tab.valid; f < v->p.frq.tab.missing; f++)
1324     moments_pass_two (m, f->v.f, f->c);
1325   moments_calculate (m, NULL, &d[frq_mean], &d[frq_variance],
1326                      &d[frq_skew], &d[frq_kurt]);
1327   moments_destroy (m);
1328                      
1329   /* Formulas below are taken from _SPSS Statistical Algorithms_. */
1330   d[frq_min] = v->p.frq.tab.valid[0].v.f;
1331   d[frq_max] = v->p.frq.tab.valid[v->p.frq.tab.n_valid - 1].v.f;
1332   d[frq_mode] = X_mode;
1333   d[frq_range] = d[frq_max] - d[frq_min];
1334   d[frq_median] = *median_value;
1335   d[frq_sum] = d[frq_mean] * W;
1336   d[frq_stddev] = sqrt (d[frq_variance]);
1337   d[frq_semean] = d[frq_stddev] / sqrt (W);
1338   d[frq_seskew] = calc_seskew (W);
1339   d[frq_sekurt] = calc_sekurt (W);
1340 }
1341
1342 /* Displays a table of all the statistics requested for variable V. */
1343 static void
1344 dump_statistics (struct variable * v, int show_varname)
1345 {
1346   double stat_value[frq_n_stats];
1347   struct tab_table *t;
1348   int i, r;
1349
1350   int n_explicit_percentiles = n_percentiles;
1351
1352   if ( implicit_50th && n_percentiles > 0 ) 
1353     --n_percentiles;
1354
1355   if (v->type == ALPHA)
1356     return;
1357   if (v->p.frq.tab.n_valid == 0)
1358     {
1359       msg (SW, _("No valid data for variable %s; statistics not displayed."),
1360            v->name);
1361       return;
1362     }
1363   calc_stats (v, stat_value);
1364
1365   t = tab_create (3, n_stats + n_explicit_percentiles + 2, 0);
1366   tab_dim (t, tab_natural_dimensions);
1367
1368   tab_box (t, TAL_1, TAL_1, -1, -1 , 0 , 0 , 2, tab_nr(t) - 1) ;
1369
1370
1371   tab_vline (t, TAL_1 , 2, 0, tab_nr(t) - 1);
1372   tab_vline (t, TAL_1 | TAL_SPACING , 1, 0, tab_nr(t) - 1 ) ;
1373   
1374   r=2; /* N missing and N valid are always dumped */
1375
1376   for (i = 0; i < frq_n_stats; i++)
1377     if (stats & BIT_INDEX (i))
1378       {
1379         tab_text (t, 0, r, TAB_LEFT | TAT_TITLE,
1380                       gettext (st_name[i].s10));
1381         tab_float (t, 2, r, TAB_NONE, stat_value[i], 11, 3);
1382         r++;
1383       }
1384
1385   tab_text (t, 0, 0, TAB_LEFT | TAT_TITLE, _("N"));
1386   tab_text (t, 1, 0, TAB_LEFT | TAT_TITLE, _("Valid"));
1387   tab_text (t, 1, 1, TAB_LEFT | TAT_TITLE, _("Missing"));
1388
1389   tab_float(t, 2, 0, TAB_NONE, v->p.frq.tab.valid_cases, 11, 0);
1390   tab_float(t, 2, 1, TAB_NONE, 
1391             v->p.frq.tab.total_cases - v->p.frq.tab.valid_cases, 11, 0);
1392
1393
1394   for (i = 0; i < n_explicit_percentiles; i++, r++) 
1395     {
1396       if ( i == 0 ) 
1397         { 
1398           tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, _("Percentiles"));
1399         }
1400
1401       tab_float (t, 1, r, TAB_LEFT, percentiles[i].p * 100, 3, 0 );
1402       tab_float (t, 2, r, TAB_NONE, percentiles[i].value, 11, 3);
1403
1404     }
1405
1406   tab_columns (t, SOM_COL_DOWN, 1);
1407   if (show_varname)
1408     {
1409       if (v->label)
1410         tab_title (t, 1, "%s: %s", v->name, v->label);
1411       else
1412         tab_title (t, 0, v->name);
1413     }
1414   else
1415     tab_flags (t, SOMF_NO_TITLE);
1416
1417
1418   tab_submit (t);
1419 }
1420 /* 
1421    Local Variables:
1422    mode: c
1423    End:
1424 */