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