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