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