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