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