FREQUENCIES: Use newer hmap library instead of older hsh_table library.
[pspp] / src / language / stats / frequencies.q
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2007, 2009, 2010 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16
17 #include <config.h>
18
19 #include <math.h>
20 #include <stdlib.h>
21 #include <gsl/gsl_histogram.h>
22
23 #include "data/case.h"
24 #include "data/casegrouper.h"
25 #include "data/casereader.h"
26 #include "data/dictionary.h"
27 #include "data/format.h"
28 #include "data/procedure.h"
29 #include "data/settings.h"
30 #include "data/value-labels.h"
31 #include "data/variable.h"
32 #include "language/command.h"
33 #include "language/dictionary/split-file.h"
34 #include "language/lexer/lexer.h"
35 #include "language/stats/freq.h"
36 #include "libpspp/array.h"
37 #include "libpspp/bit-vector.h"
38 #include "libpspp/compiler.h"
39 #include "libpspp/hmap.h"
40 #include "libpspp/message.h"
41 #include "libpspp/misc.h"
42 #include "libpspp/pool.h"
43 #include "libpspp/str.h"
44 #include "math/histogram.h"
45 #include "math/moments.h"
46 #include "output/chart-item.h"
47 #include "output/charts/piechart.h"
48 #include "output/charts/plot-hist.h"
49 #include "output/tab.h"
50
51 #include "gl/minmax.h"
52 #include "gl/xalloc.h"
53
54 #include "gettext.h"
55 #define _(msgid) gettext (msgid)
56 #define N_(msgid) msgid
57
58 /* (headers) */
59
60 /* (specification)
61    FREQUENCIES (frq_):
62      *+variables=custom;
63      +format=table:limit(n:limit,"%s>0")/notable/!table,
64              sort:!avalue/dvalue/afreq/dfreq;
65      missing=miss:include/!exclude;
66      barchart(ba_)=:minimum(d:min),
67             :maximum(d:max),
68             scale:freq(*n:freq,"%s>0")/percent(*n:pcnt,"%s>0");
69      piechart(pie_)=:minimum(d:min),
70             :maximum(d:max),
71             missing:missing/!nomissing,
72             scale:!freq/percent;
73      histogram(hi_)=:minimum(d:min),
74             :maximum(d:max),
75             scale:freq(*n:freq,"%s>0")/percent(*n:pcnt,"%s>0"),
76             norm:!nonormal/normal;
77      +grouped=custom;
78      +ntiles=integer;
79      +percentiles = double list;
80      +statistics[st_]=mean,semean,median,mode,stddev,variance,
81             kurtosis,skewness,range,minimum,maximum,sum,
82             default,seskewness,sekurtosis,all,none.
83 */
84 /* (declarations) */
85 /* (functions) */
86
87 /* Statistics. */
88 enum
89   {
90     frq_mean = 0, frq_semean, frq_median, frq_mode, frq_stddev, frq_variance,
91     frq_kurt, frq_sekurt, frq_skew, frq_seskew, frq_range, frq_min, frq_max,
92     frq_sum, frq_n_stats
93   };
94
95 /* Description of a statistic. */
96 struct frq_info
97   {
98     int st_indx;                /* Index into a_statistics[]. */
99     const char *s10;            /* Identifying string. */
100   };
101
102 /* Table of statistics, indexed by dsc_*. */
103 static const struct frq_info st_name[frq_n_stats + 1] =
104 {
105   {FRQ_ST_MEAN, N_("Mean")},
106   {FRQ_ST_SEMEAN, N_("S.E. Mean")},
107   {FRQ_ST_MEDIAN, N_("Median")},
108   {FRQ_ST_MODE, N_("Mode")},
109   {FRQ_ST_STDDEV, N_("Std Dev")},
110   {FRQ_ST_VARIANCE, N_("Variance")},
111   {FRQ_ST_KURTOSIS, N_("Kurtosis")},
112   {FRQ_ST_SEKURTOSIS, N_("S.E. Kurt")},
113   {FRQ_ST_SKEWNESS, N_("Skewness")},
114   {FRQ_ST_SESKEWNESS, N_("S.E. Skew")},
115   {FRQ_ST_RANGE, N_("Range")},
116   {FRQ_ST_MINIMUM, N_("Minimum")},
117   {FRQ_ST_MAXIMUM, N_("Maximum")},
118   {FRQ_ST_SUM, N_("Sum")},
119   {-1, 0},
120 };
121
122 /* Percentiles to calculate. */
123
124 struct percentile
125 {
126   double p;        /* the %ile to be calculated */
127   double value;    /* the %ile's value */
128   double x1;       /* The datum value <= the percentile */
129   double x2;       /* The datum value >= the percentile */
130   int flag;
131   int flag2;       /* Set to 1 if this percentile value has been found */
132   bool show;       /* True to show this percentile in the statistics box. */
133 };
134
135
136 static void add_percentile (double x, bool show);
137
138 static struct percentile *percentiles;
139 static int n_percentiles, n_show_percentiles;
140
141 /* Groups of statistics. */
142 #define BI          BIT_INDEX
143 #define frq_default                                                     \
144         (BI (frq_mean) | BI (frq_stddev) | BI (frq_min) | BI (frq_max))
145 #define frq_all                                                 \
146         (BI (frq_sum) | BI(frq_min) | BI(frq_max)               \
147          | BI(frq_mean) | BI(frq_semean) | BI(frq_stddev)       \
148          | BI(frq_variance) | BI(frq_kurt) | BI(frq_sekurt)     \
149          | BI(frq_skew) | BI(frq_seskew) | BI(frq_range)        \
150          | BI(frq_range) | BI(frq_mode) | BI(frq_median))
151
152 /* Statistics; number of statistics. */
153 static unsigned long stats;
154 static int n_stats;
155
156 struct frq_chart
157   {
158     double x_min;               /* X axis minimum value. */
159     double x_max;               /* X axis maximum value. */
160     int y_scale;                /* Y axis scale: FRQ_FREQ or FRQ_PERCENT. */
161
162     /* Histograms only. */
163     double y_max;               /* Y axis maximum value. */
164     bool draw_normal;           /* Whether to draw normal curve. */
165
166     /* Pie charts only. */
167     bool include_missing;       /* Whether to include missing values. */
168   };
169
170 /* Histogram and pie chart settings. */
171 static struct frq_chart hist, pie;
172
173 /* Parsed command. */
174 static struct cmd_frequencies cmd;
175
176 /* Variables for which to calculate statistics. */
177 static size_t n_variables;
178 static const struct variable **v_variables;
179
180 /* Pools. */
181 static struct pool *data_pool;          /* For per-SPLIT FILE group data. */
182 static struct pool *syntax_pool;        /* For syntax-related data. */
183
184 /* Frequency tables. */
185
186 /* Entire frequency table. */
187 struct freq_tab
188   {
189     struct hmap data;           /* Hash table for accumulating counts. */
190     struct freq *valid;         /* Valid freqs. */
191     int n_valid;                /* Number of total freqs. */
192     const struct dictionary *dict; /* Source of entries in the table. */
193
194     struct freq *missing;       /* Missing freqs. */
195     int n_missing;              /* Number of missing freqs. */
196
197     /* Statistics. */
198     double total_cases;         /* Sum of weights of all cases. */
199     double valid_cases;         /* Sum of weights of valid cases. */
200   };
201
202 /* Per-variable frequency data. */
203 struct var_freqs
204   {
205     /* Freqency table. */
206     struct freq_tab tab;        /* Frequencies table to use. */
207
208     /* Percentiles. */
209     int n_groups;               /* Number of groups. */
210     double *groups;             /* Groups. */
211
212     /* Statistics. */
213     double stat[frq_n_stats];
214
215     /* Variable attributes. */
216     int width;
217     struct fmt_spec print;
218   };
219
220 static inline struct var_freqs *
221 get_var_freqs (const struct variable *v)
222 {
223   return var_get_aux (v);
224 }
225
226 static void determine_charts (void);
227
228 static void calc_stats (const struct variable *v, double d[frq_n_stats]);
229
230 static void precalc (struct casereader *, struct dataset *);
231 static void calc (const struct ccase *, const struct dataset *);
232 static void postcalc (const struct dataset *);
233
234 static void postprocess_freq_tab (const struct variable *);
235 static void dump_freq_table (const struct variable *, const struct variable *);
236 static void dump_statistics (const struct variable *, const struct variable *);
237 static void cleanup_freq_tab (const struct variable *);
238
239 static algo_compare_func compare_value_numeric_a, compare_value_alpha_a;
240 static algo_compare_func compare_value_numeric_d, compare_value_alpha_d;
241 static algo_compare_func compare_freq_numeric_a, compare_freq_alpha_a;
242 static algo_compare_func compare_freq_numeric_d, compare_freq_alpha_d;
243
244
245 static void do_piechart(const struct variable *var,
246                         const struct freq_tab *frq_tab);
247
248 struct histogram *
249 freq_tab_to_hist(const struct freq_tab *ft, const struct variable *var);
250
251
252 \f
253 /* Parser and outline. */
254
255 static int internal_cmd_frequencies (struct lexer *lexer, struct dataset *ds);
256
257 int
258 cmd_frequencies (struct lexer *lexer, struct dataset *ds)
259 {
260   int result;
261
262   syntax_pool = pool_create ();
263   result = internal_cmd_frequencies (lexer, ds);
264   pool_destroy (syntax_pool);
265   syntax_pool=0;
266   pool_destroy (data_pool);
267   data_pool=0;
268   free (v_variables);
269   v_variables=0;
270   return result;
271 }
272
273 static int
274 internal_cmd_frequencies (struct lexer *lexer, struct dataset *ds)
275 {
276   struct casegrouper *grouper;
277   struct casereader *input, *group;
278   bool ok;
279   int i;
280
281   n_percentiles = 0;
282   n_show_percentiles = 0;
283   percentiles = NULL;
284
285   n_variables = 0;
286   v_variables = NULL;
287
288   if (!parse_frequencies (lexer, ds, &cmd, NULL))
289     return CMD_FAILURE;
290
291   /* Figure out statistics to calculate. */
292   stats = 0;
293   if (cmd.a_statistics[FRQ_ST_DEFAULT] || !cmd.sbc_statistics)
294     stats |= frq_default;
295   if (cmd.a_statistics[FRQ_ST_ALL])
296     stats |= frq_all;
297   if (cmd.sort != FRQ_AVALUE && cmd.sort != FRQ_DVALUE)
298     stats &= ~BIT_INDEX (frq_median);
299   for (i = 0; i < frq_n_stats; i++)
300     if (cmd.a_statistics[st_name[i].st_indx])
301       stats |= BIT_INDEX (i);
302   if (stats & frq_kurt)
303     stats |= BIT_INDEX (frq_sekurt);
304   if (stats & frq_skew)
305     stats |= BIT_INDEX (frq_seskew);
306
307   /* Calculate n_stats. */
308   n_stats = 0;
309   for (i = 0; i < frq_n_stats; i++)
310     if ((stats & BIT_INDEX (i)))
311       n_stats++;
312
313   /* Charting. */
314   determine_charts ();
315   if (cmd.sbc_histogram || cmd.sbc_piechart || cmd.sbc_ntiles)
316     cmd.sort = FRQ_AVALUE;
317
318   /* Work out what percentiles need to be calculated */
319   if ( cmd.sbc_percentiles )
320     {
321       for ( i = 0 ; i < MAXLISTS ; ++i )
322         {
323           int pl;
324           subc_list_double *ptl_list = &cmd.dl_percentiles[i];
325           for ( pl = 0 ; pl < subc_list_double_count(ptl_list); ++pl)
326             add_percentile (subc_list_double_at(ptl_list, pl) / 100.0, true);
327         }
328     }
329   if ( cmd.sbc_ntiles )
330     {
331       for ( i = 0 ; i < cmd.sbc_ntiles ; ++i )
332         {
333           int j;
334           for (j = 0; j <= cmd.n_ntiles[i]; ++j )
335             add_percentile (j / (double) cmd.n_ntiles[i], true);
336         }
337     }
338   if (stats & BIT_INDEX (frq_median))
339     {
340       /* Treat the median as the 50% percentile.
341          We output it in the percentiles table as "50 (Median)." */
342       add_percentile (0.5, true);
343       stats &= ~BIT_INDEX (frq_median);
344       n_stats--;
345     }
346   if (cmd.sbc_histogram)
347     {
348       add_percentile (0.25, false);
349       add_percentile (0.75, false);
350     }
351
352   /* Do it! */
353   input = casereader_create_filter_weight (proc_open (ds), dataset_dict (ds),
354                                            NULL, NULL);
355   grouper = casegrouper_create_splits (input, dataset_dict (ds));
356   for (; casegrouper_get_next_group (grouper, &group);
357        casereader_destroy (group))
358     {
359       struct ccase *c;
360
361       precalc (group, ds);
362       for (; (c = casereader_read (group)) != NULL; case_unref (c))
363         calc (c, ds);
364       postcalc (ds);
365     }
366   ok = casegrouper_destroy (grouper);
367   ok = proc_commit (ds) && ok;
368
369   free_frequencies(&cmd);
370
371   return ok ? CMD_SUCCESS : CMD_CASCADING_FAILURE;
372 }
373
374 /* Figure out which charts the user requested.  */
375 static void
376 determine_charts (void)
377 {
378   if (cmd.sbc_barchart)
379     msg (SW, _("Bar charts are not implemented."));
380
381   if (cmd.sbc_histogram)
382     {
383       hist.x_min = cmd.hi_min;
384       hist.x_max = cmd.hi_max;
385       hist.y_scale = cmd.hi_scale;
386       hist.y_max = cmd.hi_scale == FRQ_FREQ ? cmd.hi_freq : cmd.hi_pcnt;
387       hist.draw_normal = cmd.hi_norm != FRQ_NONORMAL;
388       hist.include_missing = false;
389
390       if (hist.x_min != SYSMIS && hist.x_max != SYSMIS
391           && hist.x_min >= hist.x_max)
392         {
393           msg (SE, _("MAX for histogram must be greater than or equal to MIN, "
394                      "but MIN was specified as %.15g and MAX as %.15g.  "
395                      "MIN and MAX will be ignored."), hist.x_min, hist.x_max);
396           hist.x_min = hist.x_max = SYSMIS;
397         }
398     }
399
400   if (cmd.sbc_piechart)
401     {
402       pie.x_min = cmd.pie_min;
403       pie.x_max = cmd.pie_max;
404       pie.y_scale = cmd.pie_scale;
405       pie.include_missing = cmd.pie_missing == FRQ_MISSING;
406
407       if (pie.x_min != SYSMIS && pie.x_max != SYSMIS
408           && pie.x_min >= pie.x_max)
409         {
410           msg (SE, _("MAX for pie chart must be greater than or equal to MIN, "
411                      "but MIN was specified as %.15g and MAX as %.15g.  "
412                      "MIN and MAX will be ignored."), pie.x_min, pie.x_max);
413           pie.x_min = pie.x_max = SYSMIS;
414         }
415     }
416
417 }
418
419 /* Add data from case C to the frequency table. */
420 static void
421 calc (const struct ccase *c, const struct dataset *ds)
422 {
423   double weight = dict_get_case_weight (dataset_dict (ds), c, NULL);
424   size_t i;
425
426   for (i = 0; i < n_variables; i++)
427     {
428       const struct variable *var = v_variables[i];
429       int width = var_get_width (var);
430
431       const union value *value = case_data (c, var);
432       size_t hash = value_hash (value, width, 0);
433
434       struct hmap *hmap = &get_var_freqs (var)->tab.data;
435       struct freq *f;
436
437       f = freq_hmap_search (hmap, value, width, hash);
438       if (f == NULL)
439         f = freq_hmap_insert (hmap, value, width, hash);
440
441       f->count += weight;
442     }
443 }
444
445 /* Prepares each variable that is the target of FREQUENCIES by setting
446    up its hash table. */
447 static void
448 precalc (struct casereader *input, struct dataset *ds)
449 {
450   struct ccase *c;
451   size_t i;
452
453   c = casereader_peek (input, 0);
454   if (c != NULL)
455     {
456       output_split_file_values (ds, c);
457       case_unref (c);
458     }
459
460   pool_destroy (data_pool);
461   data_pool = pool_create ();
462
463   for (i = 0; i < n_variables; i++)
464     {
465       const struct variable *v = v_variables[i];
466       struct freq_tab *ft = &get_var_freqs (v)->tab;
467
468       hmap_init (&ft->data);
469     }
470 }
471
472 /* Finishes up with the variables after frequencies have been
473    calculated.  Displays statistics, percentiles, ... */
474 static void
475 postcalc (const struct dataset *ds)
476 {
477   const struct dictionary *dict = dataset_dict (ds);
478   const struct variable *wv = dict_get_weight (dict);
479   size_t i;
480
481   for (i = 0; i < n_variables; i++)
482     {
483       const struct variable *v = v_variables[i];
484       struct var_freqs *vf = get_var_freqs (v);
485       struct freq_tab *ft = &vf->tab;
486       int n_categories;
487
488       postprocess_freq_tab (v);
489
490       /* Frequencies tables. */
491       n_categories = ft->n_valid + ft->n_missing;
492       if  (cmd.table == FRQ_TABLE
493            || (cmd.table == FRQ_LIMIT && n_categories <= cmd.limit))
494         dump_freq_table (v, wv);
495
496       /* Statistics. */
497       if (n_stats)
498         dump_statistics (v, wv);
499
500       if (cmd.sbc_histogram && var_is_numeric (v) && ft->n_valid > 0)
501         {
502           double d[frq_n_stats];
503           struct histogram *histogram;
504
505           calc_stats (v, d);
506
507           histogram = freq_tab_to_hist (ft, v);
508
509           chart_item_submit (histogram_chart_create (
510                                histogram->gsl_hist, var_to_string(v),
511                                vf->tab.valid_cases,
512                                d[frq_mean],
513                                d[frq_stddev],
514                                hist.draw_normal));
515
516           statistic_destroy (&histogram->parent);
517         }
518
519       if (cmd.sbc_piechart)
520         do_piechart(v_variables[i], ft);
521
522       cleanup_freq_tab (v);
523
524     }
525 }
526
527 /* Returns the comparison function that should be used for
528    sorting a frequency table by FRQ_SORT using VAL_TYPE
529    values. */
530 static algo_compare_func *
531 get_freq_comparator (int frq_sort, enum val_type val_type)
532 {
533   bool is_numeric = val_type == VAL_NUMERIC;
534   switch (frq_sort)
535     {
536     case FRQ_AVALUE:
537       return is_numeric ? compare_value_numeric_a : compare_value_alpha_a;
538     case FRQ_DVALUE:
539       return is_numeric ? compare_value_numeric_d : compare_value_alpha_d;
540     case FRQ_AFREQ:
541       return is_numeric ? compare_freq_numeric_a : compare_freq_alpha_a;
542     case FRQ_DFREQ:
543       return is_numeric ? compare_freq_numeric_d : compare_freq_alpha_d;
544     default:
545       NOT_REACHED ();
546     }
547 }
548
549 /* Returns true iff the value in struct freq F is non-missing
550    for variable V. */
551 static bool
552 not_missing (const void *f_, const void *v_)
553 {
554   const struct freq *f = f_;
555   const struct variable *v = v_;
556
557   return !var_is_value_missing (v, &f->value, MV_ANY);
558 }
559
560 /* Summarizes the frequency table data for variable V. */
561 static void
562 postprocess_freq_tab (const struct variable *v)
563 {
564   algo_compare_func *compare;
565   struct freq_tab *ft;
566   size_t count;
567   struct freq *freqs, *f;
568   size_t i;
569
570   ft = &get_var_freqs (v)->tab;
571   compare = get_freq_comparator (cmd.sort, var_get_type (v));
572
573   /* Extract data from hash table. */
574   count = hmap_count (&ft->data);
575   freqs = freq_hmap_extract (&ft->data);
576
577   /* Put data into ft. */
578   ft->valid = freqs;
579   ft->n_valid = partition (freqs, count, sizeof *freqs, not_missing, v);
580   ft->missing = freqs + ft->n_valid;
581   ft->n_missing = count - ft->n_valid;
582
583   /* Sort data. */
584   sort (ft->valid, ft->n_valid, sizeof *ft->valid, compare, v);
585   sort (ft->missing, ft->n_missing, sizeof *ft->missing, compare, v);
586
587   /* Summary statistics. */
588   ft->valid_cases = 0.0;
589   for(i = 0 ;  i < ft->n_valid ; ++i )
590     {
591       f = &ft->valid[i];
592       ft->valid_cases += f->count;
593
594     }
595
596   ft->total_cases = ft->valid_cases ;
597   for(i = 0 ;  i < ft->n_missing ; ++i )
598     {
599       f = &ft->missing[i];
600       ft->total_cases += f->count;
601     }
602
603 }
604
605 /* Frees the frequency table for variable V. */
606 static void
607 cleanup_freq_tab (const struct variable *v)
608 {
609   struct var_freqs *vf = get_var_freqs (v);
610   free (vf->tab.valid);
611   freq_hmap_destroy (&vf->tab.data, vf->width);
612 }
613
614 /* Parses the VARIABLES subcommand, adding to
615    {n_variables,v_variables}. */
616 static int
617 frq_custom_variables (struct lexer *lexer, struct dataset *ds, struct cmd_frequencies *cmd UNUSED, void *aux UNUSED)
618 {
619   size_t old_n_variables = n_variables;
620   size_t i;
621
622   lex_match (lexer, '=');
623   if (lex_token (lexer) != T_ALL && (lex_token (lexer) != T_ID
624                          || dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) == NULL))
625     return 2;
626
627   if (!parse_variables_const (lexer, dataset_dict (ds), &v_variables, &n_variables,
628                         PV_APPEND | PV_NO_SCRATCH))
629     return 0;
630
631   for (i = old_n_variables; i < n_variables; i++)
632     {
633       const struct variable *v = v_variables[i];
634       struct var_freqs *vf;
635
636       if (var_get_aux (v) != NULL)
637         {
638           msg (SE, _("Variable %s specified multiple times on VARIABLES "
639                      "subcommand."), var_get_name (v));
640           return 0;
641         }
642       vf = var_attach_aux (v, xmalloc (sizeof *vf), var_dtor_free);
643       vf->tab.valid = vf->tab.missing = NULL;
644       vf->tab.dict = dataset_dict (ds);
645       vf->n_groups = 0;
646       vf->groups = NULL;
647       vf->width = var_get_width (v);
648       vf->print = *var_get_print_format (v);
649     }
650   return 1;
651 }
652
653 /* Parses the GROUPED subcommand, setting the n_grouped, grouped
654    fields of specified variables. */
655 static int
656 frq_custom_grouped (struct lexer *lexer, struct dataset *ds, struct cmd_frequencies *cmd UNUSED, void *aux UNUSED)
657 {
658   lex_match (lexer, '=');
659   if ((lex_token (lexer) == T_ID && dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) != NULL)
660       || lex_token (lexer) == T_ID)
661     for (;;)
662       {
663         size_t i;
664
665         /* Max, current size of list; list itself. */
666         int nl, ml;
667         double *dl;
668
669         /* Variable list. */
670         size_t n;
671         const struct variable **v;
672
673         if (!parse_variables_const (lexer, dataset_dict (ds), &v, &n,
674                               PV_NO_DUPLICATE | PV_NUMERIC))
675           return 0;
676         if (lex_match (lexer, '('))
677           {
678             nl = ml = 0;
679             dl = NULL;
680             while (lex_integer (lexer))
681               {
682                 if (nl >= ml)
683                   {
684                     ml += 16;
685                     dl = pool_nrealloc (syntax_pool, dl, ml, sizeof *dl);
686                   }
687                 dl[nl++] = lex_tokval (lexer);
688                 lex_get (lexer);
689                 lex_match (lexer, ',');
690               }
691             /* Note that nl might still be 0 and dl might still be
692                NULL.  That's okay. */
693             if (!lex_match (lexer, ')'))
694               {
695                 free (v);
696                 msg (SE, _("`)' expected after GROUPED interval list."));
697                 return 0;
698               }
699           }
700         else
701           {
702             nl = 0;
703             dl = NULL;
704           }
705
706         for (i = 0; i < n; i++)
707           if (var_get_aux (v[i]) == NULL)
708             msg (SE, _("Variables %s specified on GROUPED but not on "
709                        "VARIABLES."), var_get_name (v[i]));
710           else
711             {
712               struct var_freqs *vf = get_var_freqs (v[i]);
713
714               if (vf->groups != NULL)
715                 msg (SE, _("Variables %s specified multiple times on GROUPED "
716                            "subcommand."), var_get_name (v[i]));
717               else
718                 {
719                   vf->n_groups = nl;
720                   vf->groups = dl;
721                 }
722             }
723         free (v);
724         if (!lex_match (lexer, '/'))
725           break;
726         if ((lex_token (lexer) != T_ID || dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) != NULL)
727             && lex_token (lexer) != T_ALL)
728           {
729             lex_put_back (lexer, '/');
730             break;
731           }
732       }
733
734   return 1;
735 }
736
737 /* Adds X to the list of percentiles, keeping the list in proper
738    order.  If SHOW is true, the percentile will be shown in the statistics
739    box, otherwise it will be hidden. */
740 static void
741 add_percentile (double x, bool show)
742 {
743   int i;
744
745   for (i = 0; i < n_percentiles; i++)
746     {
747       /* Do nothing if it's already in the list */
748       if ( fabs(x - percentiles[i].p) < DBL_EPSILON )
749         {
750           if (show && !percentiles[i].show)
751             {
752               n_show_percentiles++;
753               percentiles[i].show = true;
754             }
755           return;
756         }
757
758       if (x < percentiles[i].p)
759         break;
760     }
761
762   if (i >= n_percentiles || x != percentiles[i].p)
763     {
764       percentiles = pool_nrealloc (syntax_pool, percentiles,
765                                    n_percentiles + 1, sizeof *percentiles);
766       insert_element (percentiles, n_percentiles, sizeof *percentiles, i);
767       percentiles[i].p = x;
768       percentiles[i].show = show;
769       n_percentiles++;
770       if (show)
771         n_show_percentiles++;
772     }
773 }
774
775 /* Comparison functions. */
776
777 /* Ascending numeric compare of values. */
778 static int
779 compare_value_numeric_a (const void *a_, const void *b_, const void *aux UNUSED)
780 {
781   const struct freq *a = a_;
782   const struct freq *b = b_;
783
784   if (a->value.f > b->value.f)
785     return 1;
786   else if (a->value.f < b->value.f)
787     return -1;
788   else
789     return 0;
790 }
791
792 /* Ascending string compare of values. */
793 static int
794 compare_value_alpha_a (const void *a_, const void *b_, const void *v_)
795 {
796   const struct freq *a = a_;
797   const struct freq *b = b_;
798   const struct variable *v = v_;
799   struct var_freqs *vf = get_var_freqs (v);
800
801   return value_compare_3way (&a->value, &b->value, vf->width);
802 }
803
804 /* Descending numeric compare of values. */
805 static int
806 compare_value_numeric_d (const void *a, const void *b, const void *aux UNUSED)
807 {
808   return -compare_value_numeric_a (a, b, aux);
809 }
810
811 /* Descending string compare of values. */
812 static int
813 compare_value_alpha_d (const void *a, const void *b, const void *v)
814 {
815   return -compare_value_alpha_a (a, b, v);
816 }
817
818 /* Ascending numeric compare of frequency;
819    secondary key on ascending numeric value. */
820 static int
821 compare_freq_numeric_a (const void *a_, const void *b_, const void *aux UNUSED)
822 {
823   const struct freq *a = a_;
824   const struct freq *b = b_;
825
826   if (a->count > b->count)
827     return 1;
828   else if (a->count < b->count)
829     return -1;
830
831   if (a->value.f > b->value.f)
832     return 1;
833   else if (a->value.f < b->value.f)
834     return -1;
835   else
836     return 0;
837 }
838
839 /* Ascending numeric compare of frequency;
840    secondary key on ascending string value. */
841 static int
842 compare_freq_alpha_a (const void *a_, const void *b_, const void *v_)
843 {
844   const struct freq *a = a_;
845   const struct freq *b = b_;
846   const struct variable *v = v_;
847   struct var_freqs *vf = get_var_freqs (v);
848
849   if (a->count > b->count)
850     return 1;
851   else if (a->count < b->count)
852     return -1;
853   else
854     return value_compare_3way (&a->value, &b->value, vf->width);
855 }
856
857 /* Descending numeric compare of frequency;
858    secondary key on ascending numeric value. */
859 static int
860 compare_freq_numeric_d (const void *a_, const void *b_, const void *aux UNUSED)
861 {
862   const struct freq *a = a_;
863   const struct freq *b = b_;
864
865   if (a->count > b->count)
866     return -1;
867   else if (a->count < b->count)
868     return 1;
869
870   if (a->value.f > b->value.f)
871     return 1;
872   else if (a->value.f < b->value.f)
873     return -1;
874   else
875     return 0;
876 }
877
878 /* Descending numeric compare of frequency;
879    secondary key on ascending string value. */
880 static int
881 compare_freq_alpha_d (const void *a_, const void *b_, const void *v_)
882 {
883   const struct freq *a = a_;
884   const struct freq *b = b_;
885   const struct variable *v = v_;
886   struct var_freqs *vf = get_var_freqs (v);
887
888   if (a->count > b->count)
889     return -1;
890   else if (a->count < b->count)
891     return 1;
892   else
893     return value_compare_3way (&a->value, &b->value, vf->width);
894 }
895 \f
896 /* Frequency table display. */
897
898 /* Displays a full frequency table for variable V. */
899 static void
900 dump_freq_table (const struct variable *v, const struct variable *wv)
901 {
902   const struct fmt_spec *wfmt = wv ? var_get_print_format (wv) : &F_8_0;
903   int n_categories;
904   struct var_freqs *vf;
905   struct freq_tab *ft;
906   struct freq *f;
907   struct tab_table *t;
908   int r, x;
909   double cum_total = 0.0;
910   double cum_freq = 0.0;
911
912   static const char *headings[] = {
913     N_("Value Label"),
914     N_("Value"),
915     N_("Frequency"),
916     N_("Percent"),
917     N_("Valid Percent"),
918     N_("Cum Percent")
919   };
920
921   vf = get_var_freqs (v);
922   ft = &vf->tab;
923   n_categories = ft->n_valid + ft->n_missing;
924   t = tab_create (6, n_categories + 2);
925   tab_headers (t, 0, 0, 1, 0);
926
927   for (x = 0; x < 6; x++)
928     tab_text (t, x, 0, TAB_CENTER | TAT_TITLE, gettext (headings[x]));
929
930   r = 1;
931   for (f = ft->valid; f < ft->missing; f++)
932     {
933       const char *label;
934       double percent, valid_percent;
935
936       cum_freq += f->count;
937
938       percent = f->count / ft->total_cases * 100.0;
939       valid_percent = f->count / ft->valid_cases * 100.0;
940       cum_total += valid_percent;
941
942       label = var_lookup_value_label (v, &f->value);
943       if (label != NULL)
944         tab_text (t, 0, r, TAB_LEFT, label);
945
946       tab_value (t, 1, r, TAB_NONE, &f->value, ft->dict, &vf->print);
947       tab_double (t, 2, r, TAB_NONE, f->count, wfmt);
948       tab_double (t, 3, r, TAB_NONE, percent, NULL);
949       tab_double (t, 4, r, TAB_NONE, valid_percent, NULL);
950       tab_double (t, 5, r, TAB_NONE, cum_total, NULL);
951       r++;
952     }
953   for (; f < &ft->valid[n_categories]; f++)
954     {
955       const char *label;
956
957       cum_freq += f->count;
958
959       label = var_lookup_value_label (v, &f->value);
960       if (label != NULL)
961         tab_text (t, 0, r, TAB_LEFT, label);
962
963       tab_value (t, 1, r, TAB_NONE, &f->value, ft->dict, &vf->print);
964       tab_double (t, 2, r, TAB_NONE, f->count, wfmt);
965       tab_double (t, 3, r, TAB_NONE,
966                      f->count / ft->total_cases * 100.0, NULL);
967       tab_text (t, 4, r, TAB_NONE, _("Missing"));
968       r++;
969     }
970
971   tab_box (t, TAL_1, TAL_1, -1, TAL_1, 0, 0, 5, r);
972   tab_hline (t, TAL_2, 0, 5, 1);
973   tab_hline (t, TAL_2, 0, 5, r);
974   tab_joint_text (t, 0, r, 1, r, TAB_RIGHT | TAT_TITLE, _("Total"));
975   tab_vline (t, TAL_0, 1, r, r);
976   tab_double (t, 2, r, TAB_NONE, cum_freq, wfmt);
977   tab_fixed (t, 3, r, TAB_NONE, 100.0, 5, 1);
978   tab_fixed (t, 4, r, TAB_NONE, 100.0, 5, 1);
979
980   tab_title (t, "%s", var_to_string (v));
981   tab_submit (t);
982 }
983 \f
984 /* Statistical display. */
985
986 /* Calculates all the pertinent statistics for variable V, putting them in
987    array D[]. */
988 static void
989 calc_stats (const struct variable *v, double d[frq_n_stats])
990 {
991   struct freq_tab *ft = &get_var_freqs (v)->tab;
992   double W = ft->valid_cases;
993   struct moments *m;
994   struct freq *f=0;
995   int most_often;
996   double X_mode;
997
998   double rank;
999   int i = 0;
1000   int idx;
1001
1002   /* Calculate percentiles. */
1003
1004   assert (ft->n_valid > 0);
1005
1006   for (i = 0; i < n_percentiles; i++)
1007     {
1008       percentiles[i].flag = 0;
1009       percentiles[i].flag2 = 0;
1010     }
1011
1012   rank = 0;
1013   for (idx = 0; idx < ft->n_valid; ++idx)
1014     {
1015       static double prev_value = SYSMIS;
1016       f = &ft->valid[idx];
1017       rank += f->count ;
1018       for (i = 0; i < n_percentiles; i++)
1019         {
1020           double tp;
1021           if ( percentiles[i].flag2  ) continue ;
1022
1023           if ( settings_get_algorithm () != COMPATIBLE )
1024             tp =
1025               (ft->valid_cases - 1) *  percentiles[i].p;
1026           else
1027             tp =
1028               (ft->valid_cases + 1) *  percentiles[i].p - 1;
1029
1030           if ( percentiles[i].flag )
1031             {
1032               percentiles[i].x2 = f->value.f;
1033               percentiles[i].x1 = prev_value;
1034               percentiles[i].flag2 = 1;
1035               continue;
1036             }
1037
1038           if (rank >  tp )
1039           {
1040             if ( f->count > 1 && rank - (f->count - 1) > tp )
1041               {
1042                 percentiles[i].x2 = percentiles[i].x1 = f->value.f;
1043                 percentiles[i].flag2 = 1;
1044               }
1045             else
1046               {
1047                 percentiles[i].flag=1;
1048               }
1049
1050             continue;
1051           }
1052         }
1053       prev_value = f->value.f;
1054     }
1055
1056   for (i = 0; i < n_percentiles; i++)
1057     {
1058       /* Catches the case when p == 100% */
1059       if ( ! percentiles[i].flag2 )
1060         percentiles[i].x1 = percentiles[i].x2 = f->value.f;
1061
1062       /*
1063       printf("percentile %d (p==%.2f); X1 = %g; X2 = %g\n",
1064              i,percentiles[i].p,percentiles[i].x1,percentiles[i].x2);
1065       */
1066     }
1067
1068   for (i = 0; i < n_percentiles; i++)
1069     {
1070       struct freq_tab *ft = &get_var_freqs (v)->tab;
1071       double s;
1072
1073       double dummy;
1074       if ( settings_get_algorithm () != COMPATIBLE )
1075         {
1076           s = modf((ft->valid_cases - 1) * percentiles[i].p , &dummy);
1077         }
1078       else
1079         {
1080           s = modf((ft->valid_cases + 1) * percentiles[i].p -1, &dummy);
1081         }
1082
1083       percentiles[i].value = percentiles[i].x1 +
1084         ( percentiles[i].x2 - percentiles[i].x1) * s ;
1085     }
1086
1087
1088   /* Calculate the mode. */
1089   most_often = -1;
1090   X_mode = SYSMIS;
1091   for (f = ft->valid; f < ft->missing; f++)
1092     {
1093       if (most_often < f->count)
1094         {
1095           most_often = f->count;
1096           X_mode = f->value.f;
1097         }
1098       else if (most_often == f->count)
1099         {
1100           /* A duplicate mode is undefined.
1101              FIXME: keep track of *all* the modes. */
1102           X_mode = SYSMIS;
1103         }
1104     }
1105
1106   /* Calculate moments. */
1107   m = moments_create (MOMENT_KURTOSIS);
1108   for (f = ft->valid; f < ft->missing; f++)
1109     moments_pass_one (m, f->value.f, f->count);
1110   for (f = ft->valid; f < ft->missing; f++)
1111     moments_pass_two (m, f->value.f, f->count);
1112   moments_calculate (m, NULL, &d[frq_mean], &d[frq_variance],
1113                      &d[frq_skew], &d[frq_kurt]);
1114   moments_destroy (m);
1115
1116   /* Formulas below are taken from _SPSS Statistical Algorithms_. */
1117   d[frq_min] = ft->valid[0].value.f;
1118   d[frq_max] = ft->valid[ft->n_valid - 1].value.f;
1119   d[frq_mode] = X_mode;
1120   d[frq_range] = d[frq_max] - d[frq_min];
1121   d[frq_sum] = d[frq_mean] * W;
1122   d[frq_stddev] = sqrt (d[frq_variance]);
1123   d[frq_semean] = d[frq_stddev] / sqrt (W);
1124   d[frq_seskew] = calc_seskew (W);
1125   d[frq_sekurt] = calc_sekurt (W);
1126 }
1127
1128 /* Displays a table of all the statistics requested for variable V. */
1129 static void
1130 dump_statistics (const struct variable *v, const struct variable *wv)
1131 {
1132   const struct fmt_spec *wfmt = wv ? var_get_print_format (wv) : &F_8_0;
1133   struct freq_tab *ft;
1134   double stat_value[frq_n_stats];
1135   struct tab_table *t;
1136   int i, r;
1137
1138   if (var_is_alpha (v))
1139     return;
1140   ft = &get_var_freqs (v)->tab;
1141   if (ft->n_valid == 0)
1142     {
1143       msg (SW, _("No valid data for variable %s; statistics not displayed."),
1144            var_get_name (v));
1145       return;
1146     }
1147   calc_stats (v, stat_value);
1148
1149   t = tab_create (3, n_stats + n_show_percentiles + 2);
1150
1151   tab_box (t, TAL_1, TAL_1, -1, -1 , 0 , 0 , 2, tab_nr(t) - 1) ;
1152
1153
1154   tab_vline (t, TAL_1 , 2, 0, tab_nr(t) - 1);
1155   tab_vline (t, TAL_GAP , 1, 0, tab_nr(t) - 1 ) ;
1156
1157   r=2; /* N missing and N valid are always dumped */
1158
1159   for (i = 0; i < frq_n_stats; i++)
1160     if (stats & BIT_INDEX (i))
1161       {
1162         tab_text (t, 0, r, TAB_LEFT | TAT_TITLE,
1163                       gettext (st_name[i].s10));
1164         tab_double (t, 2, r, TAB_NONE, stat_value[i], NULL);
1165         r++;
1166       }
1167
1168   tab_text (t, 0, 0, TAB_LEFT | TAT_TITLE, _("N"));
1169   tab_text (t, 1, 0, TAB_LEFT | TAT_TITLE, _("Valid"));
1170   tab_text (t, 1, 1, TAB_LEFT | TAT_TITLE, _("Missing"));
1171
1172   tab_double (t, 2, 0, TAB_NONE, ft->valid_cases, wfmt);
1173   tab_double (t, 2, 1, TAB_NONE, ft->total_cases - ft->valid_cases, wfmt);
1174
1175   for (i = 0; i < n_percentiles; i++, r++)
1176     {
1177       if (!percentiles[i].show)
1178         continue;
1179
1180       if ( i == 0 )
1181         {
1182           tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, _("Percentiles"));
1183         }
1184
1185       if (percentiles[i].p == 0.5)
1186         tab_text (t, 1, r, TAB_LEFT, _("50 (Median)"));
1187       else
1188         tab_fixed (t, 1, r, TAB_LEFT, percentiles[i].p * 100, 3, 0);
1189       tab_double (t, 2, r, TAB_NONE, percentiles[i].value,
1190                   var_get_print_format (v));
1191     }
1192
1193   tab_title (t, "%s", var_to_string (v));
1194
1195   tab_submit (t);
1196 }
1197
1198 static double
1199 calculate_iqr (void)
1200 {
1201   double q1 = SYSMIS;
1202   double q3 = SYSMIS;
1203   int i;
1204
1205   for (i = 0; i < n_percentiles; i++)
1206     {
1207       if (fabs (0.25 - percentiles[i].p) < DBL_EPSILON)
1208         q1 = percentiles[i].value;
1209       else if (fabs (0.75 - percentiles[i].p) < DBL_EPSILON)
1210         q3 = percentiles[i].value;
1211     }
1212
1213   return q1 == SYSMIS || q3 == SYSMIS ? SYSMIS : q3 - q1;
1214 }
1215
1216 static bool
1217 chart_includes_value (const struct frq_chart *chart,
1218                       const struct variable *var,
1219                       const union value *value)
1220 {
1221   if (!chart->include_missing && var_is_value_missing (var, value, MV_ANY))
1222     return false;
1223
1224   if (var_is_numeric (var)
1225       && ((chart->x_min != SYSMIS && value->f < chart->x_min)
1226           || (chart->x_max != SYSMIS && value->f > chart->x_max)))
1227     return false;
1228
1229   return true;
1230 }
1231
1232 /* Create a gsl_histogram from a freq_tab */
1233 struct histogram *
1234 freq_tab_to_hist (const struct freq_tab *ft, const struct variable *var)
1235 {
1236   double x_min, x_max, valid_freq;
1237   int i;
1238
1239   struct histogram *histogram;
1240   double iqr;
1241   int bins;
1242
1243   /* Find out the extremes of the x value, within the range to be included in
1244      the histogram, and sum the total frequency of those values. */
1245   x_min = DBL_MAX;
1246   x_max = -DBL_MAX;
1247   valid_freq = 0;
1248   for (i = 0; i < ft->n_valid; i++)
1249     {
1250       const struct freq *frq = &ft->valid[i];
1251       if (chart_includes_value (&hist, var, &frq->value))
1252         {
1253           x_min = MIN (x_min, frq->value.f);
1254           x_max = MAX (x_max, frq->value.f);
1255           valid_freq += frq->count;
1256         }
1257     }
1258
1259   /* Freedman-Diaconis' choice of bin width. */
1260   iqr = calculate_iqr ();
1261   if (iqr != SYSMIS)
1262     {
1263       double bin_width = 2 * iqr / pow (valid_freq, 1.0 / 3.0);
1264       bins = (x_max - x_min) / bin_width;
1265       if (bins < 5)
1266         bins = 5;
1267       else if (bins > 400)
1268         bins = 400;
1269     }
1270   else
1271     bins = 5;
1272
1273   histogram = histogram_create (bins, x_min, x_max);
1274   for (i = 0; i < ft->n_valid; i++)
1275     {
1276       const struct freq *frq = &ft->valid[i];
1277       if (chart_includes_value (&hist, var, &frq->value))
1278         histogram_add (histogram, frq->value.f, frq->count);
1279     }
1280
1281   return histogram;
1282 }
1283
1284 static int
1285 add_slice (const struct freq *freq, const struct variable *var,
1286            struct slice *slice)
1287 {
1288   if (chart_includes_value (&pie, var, &freq->value))
1289     {
1290       ds_init_empty (&slice->label);
1291       var_append_value_name (var, &freq->value, &slice->label);
1292       slice->magnitude = freq->count;
1293       return 1;
1294     }
1295   else
1296     return 0;
1297 }
1298
1299 /* Allocate an array of slices and fill them from the data in frq_tab
1300    n_slices will contain the number of slices allocated.
1301    The caller is responsible for freeing slices
1302 */
1303 static struct slice *
1304 freq_tab_to_slice_array(const struct freq_tab *frq_tab,
1305                         const struct variable *var,
1306                         int *n_slicesp)
1307 {
1308   struct slice *slices;
1309   int n_slices;
1310   int i;
1311
1312   slices = xnmalloc (frq_tab->n_valid + frq_tab->n_missing, sizeof *slices);
1313   n_slices = 0;
1314
1315   for (i = 0; i < frq_tab->n_valid; i++)
1316     n_slices += add_slice (&frq_tab->valid[i], var, &slices[n_slices]);
1317   for (i = 0; i < frq_tab->n_missing; i++)
1318     n_slices += add_slice (&frq_tab->missing[i], var, &slices[n_slices]);
1319
1320   *n_slicesp = n_slices;
1321   return slices;
1322 }
1323
1324
1325
1326
1327 static void
1328 do_piechart(const struct variable *var, const struct freq_tab *frq_tab)
1329 {
1330   struct slice *slices;
1331   int n_slices, i;
1332
1333   slices = freq_tab_to_slice_array (frq_tab, var, &n_slices);
1334
1335   if (n_slices < 2)
1336     msg (SW, _("Omitting pie chart for %s, which has only %d unique values."),
1337          var_get_name (var), n_slices);
1338   else if (n_slices > 50)
1339     msg (SW, _("Omitting pie chart for %s, which has over 50 unique values."),
1340          var_get_name (var));
1341   else
1342     chart_item_submit (piechart_create (var_to_string(var), slices, n_slices));
1343
1344   for (i = 0; i < n_slices; i++)
1345     ds_destroy (&slices[i].label);
1346   free (slices);
1347 }
1348
1349
1350 /*
1351    Local Variables:
1352    mode: c
1353    End:
1354 */