FREQUENCIES: Fix percentiles and median calculation for multiple variables.
[pspp] / src / language / stats / frequencies.c
1 /*
2   PSPP - a program for statistical analysis.
3   Copyright (C) 1997-9, 2000, 2007, 2009, 2010, 2011, 2014, 2015 Free Software Foundation, Inc.
4
5   This program is free software: you can redistribute it and/or modify
6   it under the terms of the GNU General Public License as published by
7   the Free Software Foundation, either version 3 of the License, or
8   (at your option) any later version.
9
10   This program is distributed in the hope that it will be useful,
11   but WITHOUT ANY WARRANTY; without even the implied warranty of
12   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   GNU 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, see <http://www.gnu.org/licenses/>.
17 */
18
19 #include <config.h>
20 #include <stdlib.h>
21 #include <gsl/gsl_histogram.h>
22
23
24 #include "data/case.h"
25 #include "data/casegrouper.h"
26 #include "data/casereader.h"
27 #include "data/dataset.h"
28 #include "data/dictionary.h"
29 #include "data/format.h"
30 #include "data/missing-values.h"
31 #include "data/settings.h"
32 #include "data/value-labels.h"
33 #include "data/variable.h"
34
35 #include "language/dictionary/split-file.h"
36
37 #include "language/command.h"
38 #include "language/lexer/lexer.h"
39 #include "language/lexer/variable-parser.h"
40 #include "language/stats/freq.h"
41
42 #include "libpspp/array.h"
43 #include "libpspp/bit-vector.h"
44 #include "libpspp/compiler.h"
45 #include "libpspp/hmap.h"
46 #include "libpspp/message.h"
47 #include "libpspp/misc.h"
48
49 #include "math/histogram.h"
50 #include "math/moments.h"
51 #include "math/chart-geometry.h"
52
53
54 #include "output/charts/barchart.h"
55 #include "output/charts/piechart.h"
56 #include "output/charts/plot-hist.h"
57 #include "output/pivot-table.h"
58
59 #include "gl/minmax.h"
60 #include "gl/xalloc.h"
61
62 #include "gettext.h"
63 #define _(msgid) gettext (msgid)
64 #define N_(msgid) msgid
65
66 /* Percentiles to calculate. */
67
68 struct percentile
69 {
70   double p;        /* the %ile to be calculated */
71   bool show;       /* True to show this percentile in the statistics box. */
72 };
73
74 static int
75 ptile_3way (const void *_p1, const void *_p2)
76 {
77   const struct percentile *p1 = _p1;
78   const struct percentile *p2 = _p2;
79
80   if (p1->p < p2->p)
81     return -1;
82
83   if (p1->p == p2->p)
84     {
85       if (p1->show > p2->show)
86         return -1;
87
88       return (p1->show < p2->show);
89     }
90
91   return (p1->p > p2->p);
92 }
93
94
95 enum
96   {
97     FRQ_NONORMAL,
98     FRQ_NORMAL
99   };
100
101 enum
102   {
103     FRQ_FREQ,
104     FRQ_PERCENT
105   };
106
107 enum sortprops
108   {
109     FRQ_AFREQ,
110     FRQ_DFREQ,
111     FRQ_AVALUE,
112     FRQ_DVALUE
113   };
114
115 /* Array indices for STATISTICS subcommand. */
116 enum
117   {
118     FRQ_ST_MEAN,
119     FRQ_ST_SEMEAN,
120     FRQ_ST_MEDIAN,
121     FRQ_ST_MODE,
122     FRQ_ST_STDDEV,
123     FRQ_ST_VARIANCE,
124     FRQ_ST_KURTOSIS,
125     FRQ_ST_SEKURTOSIS,
126     FRQ_ST_SKEWNESS,
127     FRQ_ST_SESKEWNESS,
128     FRQ_ST_RANGE,
129     FRQ_ST_MINIMUM,
130     FRQ_ST_MAXIMUM,
131     FRQ_ST_SUM,
132     FRQ_ST_count
133   };
134
135 /* Description of statistics. */
136 static const char *st_name[FRQ_ST_count] =
137 {
138    N_("Mean"),
139    N_("S.E. Mean"),
140    N_("Median"),
141    N_("Mode"),
142    N_("Std Dev"),
143    N_("Variance"),
144    N_("Kurtosis"),
145    N_("S.E. Kurt"),
146    N_("Skewness"),
147    N_("S.E. Skew"),
148    N_("Range"),
149    N_("Minimum"),
150    N_("Maximum"),
151    N_("Sum")
152 };
153
154 struct freq_tab
155   {
156     struct hmap data;           /* Hash table for accumulating counts. */
157     struct freq *valid;         /* Valid freqs. */
158     int n_valid;                /* Number of total freqs. */
159     const struct dictionary *dict; /* Source of entries in the table. */
160
161     struct freq *missing;       /* Missing freqs. */
162     int n_missing;              /* Number of missing freqs. */
163
164     /* Statistics. */
165     double total_cases;         /* Sum of weights of all cases. */
166     double valid_cases;         /* Sum of weights of valid cases. */
167   };
168
169 struct frq_chart
170   {
171     double x_min;               /* X axis minimum value. */
172     double x_max;               /* X axis maximum value. */
173     int y_scale;                /* Y axis scale: FRQ_FREQ or FRQ_PERCENT. */
174
175     /* Histograms only. */
176     double y_max;               /* Y axis maximum value. */
177     bool draw_normal;           /* Whether to draw normal curve. */
178
179     /* Pie charts only. */
180     bool include_missing;       /* Whether to include missing values. */
181   };
182
183 /* Per-variable frequency data. */
184 struct var_freqs
185   {
186     const struct variable *var;
187
188     /* Freqency table. */
189     struct freq_tab tab;        /* Frequencies table to use. */
190
191     /* Statistics. */
192     double stat[FRQ_ST_count];
193     double *percentiles;
194
195     /* Variable attributes. */
196     int width;
197   };
198
199 struct frq_proc
200   {
201     struct var_freqs *vars;
202     size_t n_vars;
203
204     /* Percentiles to calculate and possibly display. */
205     struct percentile *percentiles;
206     size_t median_idx;
207     size_t n_percentiles;
208
209     /* Frequency table display. */
210     long int max_categories;         /* Maximum categories to show. */
211     int sort;                   /* FRQ_AVALUE or FRQ_DVALUE
212                                    or FRQ_AFREQ or FRQ_DFREQ. */
213
214     /* Statistics; number of statistics. */
215     unsigned long stats;
216     int n_stats;
217
218     /* Histogram and pie chart settings. */
219     struct frq_chart *hist, *pie, *bar;
220
221     bool warn;
222   };
223
224
225 struct freq_compare_aux
226   {
227     bool by_freq;
228     bool ascending_freq;
229
230     int width;
231     bool ascending_value;
232   };
233
234 static void calc_stats (const struct frq_proc *,
235                         const struct var_freqs *, double d[FRQ_ST_count]);
236
237 static void do_piechart(const struct frq_chart *pie,
238                         const struct variable *var,
239                         const struct freq_tab *frq_tab);
240
241 static void do_barchart(const struct frq_chart *bar,
242                         const struct variable **var,
243                         const struct freq_tab *frq_tab);
244
245 static void dump_statistics (const struct frq_proc *frq,
246                              const struct variable *wv);
247
248 static int
249 compare_freq (const void *a_, const void *b_, const void *aux_)
250 {
251   const struct freq_compare_aux *aux = aux_;
252   const struct freq *a = a_;
253   const struct freq *b = b_;
254
255   if (aux->by_freq && a->count != b->count)
256     {
257       int cmp = a->count > b->count ? 1 : -1;
258       return aux->ascending_freq ? cmp : -cmp;
259     }
260   else
261     {
262       int cmp = value_compare_3way (a->values, b->values, aux->width);
263       return aux->ascending_value ? cmp : -cmp;
264     }
265 }
266
267 /* Create a gsl_histogram from a freq_tab */
268 static struct histogram *freq_tab_to_hist (const struct frq_proc *,
269                                            const struct var_freqs *);
270
271 static void
272 put_freq_row (struct pivot_table *table, int var_idx,
273               double frequency, double percent,
274               double valid_percent, double cum_percent)
275 {
276   double entries[] = { frequency, percent, valid_percent, cum_percent };
277   for (size_t i = 0; i < sizeof entries / sizeof *entries; i++)
278     if (entries[i] != SYSMIS)
279       pivot_table_put2 (table, i, var_idx,
280                         pivot_value_new_number (entries[i]));
281 }
282
283 /* Displays a full frequency table for variable V. */
284 static void
285 dump_freq_table (const struct var_freqs *vf, const struct variable *wv)
286 {
287   const struct freq_tab *ft = &vf->tab;
288
289   struct pivot_table *table = pivot_table_create__ (pivot_value_new_variable (
290                                                       vf->var), "Frequencies");
291   pivot_table_set_weight_var (table, wv);
292
293   pivot_dimension_create (table, PIVOT_AXIS_COLUMN, N_("Statistics"),
294                           N_("Frequency"), PIVOT_RC_COUNT,
295                           N_("Percent"), PIVOT_RC_PERCENT,
296                           N_("Valid Percent"), PIVOT_RC_PERCENT,
297                           N_("Cumulative Percent"), PIVOT_RC_PERCENT);
298
299   struct pivot_dimension *variable = pivot_dimension_create__ (
300     table, PIVOT_AXIS_ROW, pivot_value_new_variable (vf->var));
301
302   double cum_freq = 0.0;
303   double cum_percent = 0.0;
304   struct pivot_category *valid = NULL;
305   for (const struct freq *f = ft->valid; f < ft->missing; f++)
306     {
307       cum_freq += f->count;
308       double valid_percent = f->count / ft->valid_cases * 100.0;
309       cum_percent += valid_percent;
310
311       if (!valid)
312         valid = pivot_category_create_group (variable->root, N_("Valid"));
313       int var_idx = pivot_category_create_leaf (
314         valid, pivot_value_new_var_value (vf->var, &f->values[0]));
315       put_freq_row (table, var_idx, f->count,
316                     f->count / ft->total_cases * 100.0,
317                     valid_percent, cum_percent);
318     }
319
320   struct pivot_category *missing = NULL;
321   size_t n_categories = ft->n_valid + ft->n_missing;
322   for (const struct freq *f = ft->missing; f < &ft->valid[n_categories]; f++)
323     {
324       cum_freq += f->count;
325
326       if (!missing)
327         missing = pivot_category_create_group (variable->root, N_("Missing"));
328       int var_idx = pivot_category_create_leaf (
329         missing, pivot_value_new_var_value (vf->var, &f->values[0]));
330       put_freq_row (table, var_idx, f->count,
331                     f->count / ft->total_cases * 100.0, SYSMIS, SYSMIS);
332     }
333
334   int var_idx = pivot_category_create_leaf (
335     variable->root, pivot_value_new_text (N_("Total")));
336   put_freq_row (table, var_idx, cum_freq, cum_percent, SYSMIS, SYSMIS);
337
338   pivot_table_submit (table);
339 }
340 \f
341 /* Statistical display. */
342
343 static double
344 calc_percentile (double p, double valid_cases, double x1, double x2)
345 {
346   double s, dummy;
347
348   s = (settings_get_algorithm () != COMPATIBLE
349        ? modf ((valid_cases - 1) * p, &dummy)
350        : modf ((valid_cases + 1) * p - 1, &dummy));
351
352   return x1 + (x2 - x1) * s;
353 }
354
355 /* Calculates all of the percentiles for VF within FRQ. */
356 static void
357 calc_percentiles (const struct frq_proc *frq, struct var_freqs *vf)
358 {
359   if (!frq->n_percentiles)
360     return;
361
362   vf->percentiles = xnmalloc (frq->n_percentiles, sizeof *vf->percentiles);
363
364   const struct freq_tab *ft = &vf->tab;
365   const double W = ft->valid_cases;
366   size_t idx = 0;
367
368   double rank = 0;
369   for (const struct freq *f = ft->valid; f < ft->missing; f++)
370     {
371       rank += f->count;
372       for (; idx < frq->n_percentiles; idx++)
373         {
374           struct percentile *pc = &frq->percentiles[idx];
375           double tp;
376
377           tp = (settings_get_algorithm () == ENHANCED
378                 ? (W - 1) * pc->p
379                 : (W + 1) * pc->p - 1);
380
381           if (rank <= tp)
382             break;
383
384           if (tp + 1 < rank || f + 1 >= ft->missing)
385             vf->percentiles[idx] = f->values[0].f;
386           else
387             vf->percentiles[idx] = calc_percentile (pc->p, W, f->values[0].f,
388                                                     f[1].values[0].f);
389         }
390     }
391   for (; idx < frq->n_percentiles; idx++)
392     vf->percentiles[idx] = (ft->n_valid > 0
393                             ? ft->valid[ft->n_valid - 1].values[0].f
394                             : SYSMIS);
395 }
396
397 /* Returns true iff the value in struct freq F is non-missing
398    for variable V. */
399 static bool
400 not_missing (const void *f_, const void *v_)
401 {
402   const struct freq *f = f_;
403   const struct variable *v = v_;
404
405   return !var_is_value_missing (v, f->values);
406 }
407
408
409 /* Summarizes the frequency table data for variable V. */
410 static void
411 postprocess_freq_tab (const struct frq_proc *frq, struct var_freqs *vf)
412 {
413   struct freq_tab *ft = &vf->tab;
414   struct freq_compare_aux aux;
415   size_t count;
416   struct freq *freqs, *f;
417   size_t i;
418
419   /* Extract data from hash table. */
420   count = hmap_count (&ft->data);
421   freqs = freq_hmap_extract (&ft->data);
422
423   /* Put data into ft. */
424   ft->valid = freqs;
425   ft->n_valid = partition (freqs, count, sizeof *freqs, not_missing, vf->var);
426   ft->missing = freqs + ft->n_valid;
427   ft->n_missing = count - ft->n_valid;
428
429   /* Sort data. */
430   aux.by_freq = frq->sort == FRQ_AFREQ || frq->sort == FRQ_DFREQ;
431   aux.ascending_freq = frq->sort != FRQ_DFREQ;
432   aux.width = vf->width;
433   aux.ascending_value = frq->sort != FRQ_DVALUE;
434   sort (ft->valid, ft->n_valid, sizeof *ft->valid, compare_freq, &aux);
435   sort (ft->missing, ft->n_missing, sizeof *ft->missing, compare_freq, &aux);
436
437   /* Summary statistics. */
438   ft->valid_cases = 0.0;
439   for(i = 0 ;  i < ft->n_valid ; ++i)
440     {
441       f = &ft->valid[i];
442       ft->valid_cases += f->count;
443
444     }
445
446   ft->total_cases = ft->valid_cases ;
447   for(i = 0 ;  i < ft->n_missing ; ++i)
448     {
449       f = &ft->missing[i];
450       ft->total_cases += f->count;
451     }
452
453 }
454
455 /* Frees the frequency table for variable V. */
456 static void
457 cleanup_freq_tab (struct var_freqs *vf)
458 {
459   free (vf->tab.valid);
460   freq_hmap_destroy (&vf->tab.data, vf->width);
461 }
462
463 /* Add data from case C to the frequency table. */
464 static void
465 calc (struct frq_proc *frq, const struct ccase *c, const struct dataset *ds)
466 {
467   double weight = dict_get_case_weight (dataset_dict (ds), c, &frq->warn);
468   size_t i;
469
470   for (i = 0; i < frq->n_vars; i++)
471     {
472       struct var_freqs *vf = &frq->vars[i];
473       const union value *value = case_data (c, vf->var);
474       size_t hash = value_hash (value, vf->width, 0);
475       struct freq *f;
476
477       f = freq_hmap_search (&vf->tab.data, value, vf->width, hash);
478       if (f == NULL)
479         f = freq_hmap_insert (&vf->tab.data, value, vf->width, hash);
480
481       f->count += weight;
482     }
483 }
484
485 /* Prepares each variable that is the target of FREQUENCIES by setting
486    up its hash table. */
487 static void
488 precalc (struct frq_proc *frq, struct casereader *input, struct dataset *ds)
489 {
490   struct ccase *c;
491   size_t i;
492
493   c = casereader_peek (input, 0);
494   if (c != NULL)
495     {
496       output_split_file_values (ds, c);
497       case_unref (c);
498     }
499
500   for (i = 0; i < frq->n_vars; i++)
501     hmap_init (&frq->vars[i].tab.data);
502 }
503
504 /* Finishes up with the variables after frequencies have been
505    calculated.  Displays statistics, percentiles, ... */
506 static void
507 postcalc (struct frq_proc *frq, const struct dataset *ds)
508 {
509   const struct dictionary *dict = dataset_dict (ds);
510   const struct variable *wv = dict_get_weight (dict);
511   size_t i;
512
513   for (i = 0; i < frq->n_vars; i++)
514     {
515       struct var_freqs *vf = &frq->vars[i];
516       postprocess_freq_tab (frq, vf);
517       calc_percentiles (frq, vf);
518     }
519
520   if (frq->n_stats)
521     dump_statistics (frq, wv);
522
523   for (i = 0; i < frq->n_vars; i++)
524     {
525       struct var_freqs *vf = &frq->vars[i];
526
527       /* Frequencies tables. */
528       if (vf->tab.n_valid + vf->tab.n_missing <= frq->max_categories)
529         dump_freq_table (vf, wv);
530
531
532       if (frq->hist && var_is_numeric (vf->var) && vf->tab.n_valid > 0)
533         {
534           double d[FRQ_ST_count];
535           struct histogram *histogram;
536
537           calc_stats (frq, vf, d);
538
539           histogram = freq_tab_to_hist (frq, vf);
540
541           if (histogram)
542             {
543               chart_submit (histogram_chart_create (
544                               histogram->gsl_hist, var_to_string(vf->var),
545                               vf->tab.valid_cases,
546                               d[FRQ_ST_MEAN],
547                               d[FRQ_ST_STDDEV],
548                               frq->hist->draw_normal));
549
550               statistic_destroy (&histogram->parent);
551             }
552         }
553
554       if (frq->pie)
555         do_piechart(frq->pie, vf->var, &vf->tab);
556
557       if (frq->bar)
558         do_barchart(frq->bar, &vf->var, &vf->tab);
559
560       cleanup_freq_tab (vf);
561     }
562 }
563
564 int
565 cmd_frequencies (struct lexer *lexer, struct dataset *ds)
566 {
567   int i;
568   struct frq_proc frq;
569   const struct variable **vars = NULL;
570
571   bool sbc_barchart = false;
572   bool sbc_piechart = false;
573   bool sbc_histogram = false;
574
575   double pie_min = -DBL_MAX;
576   double pie_max = DBL_MAX;
577   bool pie_missing = true;
578
579   double bar_min = -DBL_MAX;
580   double bar_max = DBL_MAX;
581   bool bar_freq = true;
582
583   double hi_min = -DBL_MAX;
584   double hi_max = DBL_MAX;
585   int hi_scale = FRQ_FREQ;
586   int hi_freq = INT_MIN;
587   int hi_pcnt = INT_MIN;
588   int hi_norm = FRQ_NONORMAL;
589
590   frq.sort = FRQ_AVALUE;
591
592   frq.vars = NULL;
593   frq.n_vars = 0;
594
595   frq.stats = BIT_INDEX (FRQ_ST_MEAN)
596     | BIT_INDEX (FRQ_ST_STDDEV)
597     | BIT_INDEX (FRQ_ST_MINIMUM)
598     | BIT_INDEX (FRQ_ST_MAXIMUM);
599
600   frq.n_stats = 4;
601
602   frq.max_categories = LONG_MAX;
603
604   frq.percentiles = NULL;
605   frq.n_percentiles = 0;
606
607   frq.hist = NULL;
608   frq.pie = NULL;
609   frq.bar = NULL;
610   frq.warn = true;
611
612
613   /* Accept an optional, completely pointless "/VARIABLES=" */
614   lex_match (lexer, T_SLASH);
615   if (lex_match_id  (lexer, "VARIABLES"))
616     {
617       if (! lex_force_match (lexer, T_EQUALS))
618         goto error;
619     }
620
621   if (!parse_variables_const (lexer, dataset_dict (ds),
622                               &vars,
623                               &frq.n_vars,
624                               PV_NO_DUPLICATE))
625     goto error;
626
627   frq.vars = xcalloc (frq.n_vars, sizeof (*frq.vars));
628   for (i = 0; i < frq.n_vars; ++i)
629     {
630       frq.vars[i].var = vars[i];
631       frq.vars[i].width = var_get_width (vars[i]);
632     }
633
634   while (lex_token (lexer) != T_ENDCMD)
635     {
636       lex_match (lexer, T_SLASH);
637
638       if (lex_match_id (lexer, "STATISTICS"))
639         {
640           frq.stats = BIT_INDEX (FRQ_ST_MEAN)
641             | BIT_INDEX (FRQ_ST_STDDEV)
642             | BIT_INDEX (FRQ_ST_MINIMUM)
643             | BIT_INDEX (FRQ_ST_MAXIMUM);
644
645           frq.n_stats = 4;
646
647           if (lex_match (lexer, T_EQUALS))
648             {
649               frq.n_stats = 0;
650               frq.stats = 0;
651             }
652
653           while (lex_token (lexer) != T_ENDCMD
654                  && lex_token (lexer) != T_SLASH)
655             {
656               if (lex_match_id (lexer, "DEFAULT"))
657                 {
658                   frq.stats = BIT_INDEX (FRQ_ST_MEAN)
659                     | BIT_INDEX (FRQ_ST_STDDEV)
660                     | BIT_INDEX (FRQ_ST_MINIMUM)
661                     | BIT_INDEX (FRQ_ST_MAXIMUM);
662
663                   frq.n_stats = 4;
664                 }
665               else if (lex_match_id (lexer, "MEAN"))
666                 {
667                   frq.stats |= BIT_INDEX (FRQ_ST_MEAN);
668                   frq.n_stats++;
669                 }
670               else if (lex_match_id (lexer, "SEMEAN"))
671                 {
672                   frq.stats |= BIT_INDEX (FRQ_ST_SEMEAN);
673                   frq.n_stats++;
674                 }
675               else if (lex_match_id (lexer, "MEDIAN"))
676                 {
677                   frq.stats |= BIT_INDEX (FRQ_ST_MEDIAN);
678                   frq.n_stats++;
679                 }
680               else if (lex_match_id (lexer, "MODE"))
681                 {
682                   frq.stats |= BIT_INDEX (FRQ_ST_MODE);
683                   frq.n_stats++;
684                 }
685               else if (lex_match_id (lexer, "STDDEV"))
686                 {
687                   frq.stats |= BIT_INDEX (FRQ_ST_STDDEV);
688                   frq.n_stats++;
689                 }
690               else if (lex_match_id (lexer, "VARIANCE"))
691                 {
692                   frq.stats |= BIT_INDEX (FRQ_ST_VARIANCE);
693                   frq.n_stats++;
694                 }
695               else if (lex_match_id (lexer, "KURTOSIS"))
696                 {
697                   frq.stats |= BIT_INDEX (FRQ_ST_KURTOSIS);
698                   frq.n_stats++;
699                 }
700               else if (lex_match_id (lexer, "SKEWNESS"))
701                 {
702                   frq.stats |= BIT_INDEX (FRQ_ST_SKEWNESS);
703                   frq.n_stats++;
704                 }
705               else if (lex_match_id (lexer, "RANGE"))
706                 {
707                   frq.stats |= BIT_INDEX (FRQ_ST_RANGE);
708                   frq.n_stats++;
709                 }
710               else if (lex_match_id (lexer, "MINIMUM"))
711                 {
712                   frq.stats |= BIT_INDEX (FRQ_ST_MINIMUM);
713                   frq.n_stats++;
714                 }
715               else if (lex_match_id (lexer, "MAXIMUM"))
716                 {
717                   frq.stats |= BIT_INDEX (FRQ_ST_MAXIMUM);
718                   frq.n_stats++;
719                 }
720               else if (lex_match_id (lexer, "SUM"))
721                 {
722                   frq.stats |= BIT_INDEX (FRQ_ST_SUM);
723                   frq.n_stats++;
724                 }
725               else if (lex_match_id (lexer, "SESKEWNESS"))
726                 {
727                   frq.stats |= BIT_INDEX (FRQ_ST_SESKEWNESS);
728                   frq.n_stats++;
729                 }
730               else if (lex_match_id (lexer, "SEKURTOSIS"))
731                 {
732                   frq.stats |= BIT_INDEX (FRQ_ST_SEKURTOSIS);
733                   frq.n_stats++;
734                 }
735               else if (lex_match_id (lexer, "NONE"))
736                 {
737                   frq.stats = 0;
738                   frq.n_stats = 0;
739                 }
740               else if (lex_match (lexer, T_ALL))
741                 {
742                   frq.stats = ~0;
743                   frq.n_stats = FRQ_ST_count;
744                 }
745               else
746                 {
747                   lex_error (lexer, NULL);
748                   goto error;
749                 }
750             }
751         }
752       else if (lex_match_id (lexer, "PERCENTILES"))
753         {
754           lex_match (lexer, T_EQUALS);
755           while (lex_token (lexer) != T_ENDCMD
756                  && lex_token (lexer) != T_SLASH)
757             {
758               if (lex_force_num (lexer))
759                 {
760                   frq.percentiles =
761                     xrealloc (frq.percentiles,
762                               (frq.n_percentiles + 1)
763                               * sizeof (*frq.percentiles));
764                   frq.percentiles[frq.n_percentiles].p = lex_number (lexer)  / 100.0;
765                   frq.percentiles[frq.n_percentiles].show = true;
766                   lex_get (lexer);
767                   frq.n_percentiles++;
768                 }
769               else
770                 {
771                   lex_error (lexer, NULL);
772                   goto error;
773                 }
774               lex_match (lexer, T_COMMA);
775             }
776         }
777       else if (lex_match_id (lexer, "FORMAT"))
778         {
779           lex_match (lexer, T_EQUALS);
780           while (lex_token (lexer) != T_ENDCMD
781                  && lex_token (lexer) != T_SLASH)
782             {
783               if (lex_match_id (lexer, "TABLE"))
784                 {
785                 }
786               else if (lex_match_id (lexer, "NOTABLE"))
787                 {
788                   frq.max_categories = 0;
789                 }
790               else if (lex_match_id (lexer, "LIMIT"))
791                 {
792                   if (!lex_force_match (lexer, T_LPAREN)
793                       || !lex_force_int_range (lexer, "LIMIT", 0, INT_MAX))
794                     goto error;
795
796                   frq.max_categories = lex_integer (lexer);
797                   lex_get (lexer);
798
799                   if (!lex_force_match (lexer, T_RPAREN))
800                     goto error;
801                 }
802               else if (lex_match_id (lexer, "AVALUE"))
803                 {
804                   frq.sort = FRQ_AVALUE;
805                 }
806               else if (lex_match_id (lexer, "DVALUE"))
807                 {
808                   frq.sort = FRQ_DVALUE;
809                 }
810               else if (lex_match_id (lexer, "AFREQ"))
811                 {
812                   frq.sort = FRQ_AFREQ;
813                 }
814               else if (lex_match_id (lexer, "DFREQ"))
815                 {
816                   frq.sort = FRQ_DFREQ;
817                 }
818               else
819                 {
820                   lex_error (lexer, NULL);
821                   goto error;
822                 }
823             }
824         }
825       else if (lex_match_id (lexer, "NTILES"))
826         {
827           lex_match (lexer, T_EQUALS);
828
829           if (lex_force_int_range (lexer, "NTILES", 0, INT_MAX))
830             {
831               int n = lex_integer (lexer);
832               lex_get (lexer);
833               for (int i = 0; i < n + 1; ++i)
834                 {
835                   frq.percentiles =
836                     xrealloc (frq.percentiles,
837                               (frq.n_percentiles + 1)
838                               * sizeof (*frq.percentiles));
839                   frq.percentiles[frq.n_percentiles].p =
840                     i / (double) n ;
841                   frq.percentiles[frq.n_percentiles].show = true;
842
843                   frq.n_percentiles++;
844                 }
845             }
846           else
847             {
848               lex_error (lexer, NULL);
849               goto error;
850             }
851         }
852       else if (lex_match_id (lexer, "ALGORITHM"))
853         {
854           lex_match (lexer, T_EQUALS);
855
856           if (lex_match_id (lexer, "COMPATIBLE"))
857             {
858               settings_set_cmd_algorithm (COMPATIBLE);
859             }
860           else if (lex_match_id (lexer, "ENHANCED"))
861             {
862               settings_set_cmd_algorithm (ENHANCED);
863             }
864           else
865             {
866               lex_error (lexer, NULL);
867               goto error;
868             }
869         }
870       else if (lex_match_id (lexer, "HISTOGRAM"))
871         {
872           lex_match (lexer, T_EQUALS);
873           sbc_histogram = true;
874
875           while (lex_token (lexer) != T_ENDCMD
876                  && lex_token (lexer) != T_SLASH)
877             {
878               if (lex_match_id (lexer, "NORMAL"))
879                 {
880                   hi_norm = FRQ_NORMAL;
881                 }
882               else if (lex_match_id (lexer, "NONORMAL"))
883                 {
884                   hi_norm = FRQ_NONORMAL;
885                 }
886               else if (lex_match_id (lexer, "FREQ"))
887                 {
888                   hi_scale = FRQ_FREQ;
889                   if (lex_match (lexer, T_LPAREN))
890                     {
891                       if (lex_force_int_range (lexer, "FREQ", 1, INT_MAX))
892                         {
893                           hi_freq = lex_integer (lexer);
894                           lex_get (lexer);
895                           if (! lex_force_match (lexer, T_RPAREN))
896                             goto error;
897                         }
898                     }
899                 }
900               else if (lex_match_id (lexer, "PERCENT"))
901                 {
902                   hi_scale = FRQ_PERCENT;
903                   if (lex_match (lexer, T_LPAREN))
904                     {
905                       if (lex_force_int_range (lexer, "PERCENT", 1, INT_MAX))
906                         {
907                           hi_pcnt = lex_integer (lexer);
908                           lex_get (lexer);
909                           if (! lex_force_match (lexer, T_RPAREN))
910                             goto error;
911                         }
912                     }
913                 }
914               else if (lex_match_id (lexer, "MINIMUM"))
915                 {
916                   if (! lex_force_match (lexer, T_LPAREN))
917                     goto error;
918                   if (lex_force_num (lexer))
919                     {
920                       hi_min = lex_number (lexer);
921                       lex_get (lexer);
922                     }
923                   if (! lex_force_match (lexer, T_RPAREN))
924                     goto error;
925                 }
926               else if (lex_match_id (lexer, "MAXIMUM"))
927                 {
928                   if (! lex_force_match (lexer, T_LPAREN))
929                     goto error;
930                   if (lex_force_num (lexer))
931                     {
932                       hi_max = lex_number (lexer);
933                       lex_get (lexer);
934                     }
935                   if (! lex_force_match (lexer, T_RPAREN))
936                     goto error;
937                 }
938               else
939                 {
940                   lex_error (lexer, NULL);
941                   goto error;
942                 }
943             }
944         }
945       else if (lex_match_id (lexer, "PIECHART"))
946         {
947           lex_match (lexer, T_EQUALS);
948           while (lex_token (lexer) != T_ENDCMD
949                  && lex_token (lexer) != T_SLASH)
950             {
951               if (lex_match_id (lexer, "MINIMUM"))
952                 {
953                   if (! lex_force_match (lexer, T_LPAREN))
954                     goto error;
955                   if (lex_force_num (lexer))
956                     {
957                       pie_min = lex_number (lexer);
958                       lex_get (lexer);
959                     }
960                   if (! lex_force_match (lexer, T_RPAREN))
961                     goto error;
962                 }
963               else if (lex_match_id (lexer, "MAXIMUM"))
964                 {
965                   if (! lex_force_match (lexer, T_LPAREN))
966                     goto error;
967                   if (lex_force_num (lexer))
968                     {
969                       pie_max = lex_number (lexer);
970                       lex_get (lexer);
971                     }
972                   if (! lex_force_match (lexer, T_RPAREN))
973                     goto error;
974                 }
975               else if (lex_match_id (lexer, "MISSING"))
976                 {
977                   pie_missing = true;
978                 }
979               else if (lex_match_id (lexer, "NOMISSING"))
980                 {
981                   pie_missing = false;
982                 }
983               else
984                 {
985                   lex_error (lexer, NULL);
986                   goto error;
987                 }
988             }
989           sbc_piechart = true;
990         }
991       else if (lex_match_id (lexer, "BARCHART"))
992         {
993           lex_match (lexer, T_EQUALS);
994           while (lex_token (lexer) != T_ENDCMD
995                  && lex_token (lexer) != T_SLASH)
996             {
997               if (lex_match_id (lexer, "MINIMUM"))
998                 {
999                   if (! lex_force_match (lexer, T_LPAREN))
1000                     goto error;
1001                   if (lex_force_num (lexer))
1002                     {
1003                       bar_min = lex_number (lexer);
1004                       lex_get (lexer);
1005                     }
1006                   if (! lex_force_match (lexer, T_RPAREN))
1007                     goto error;
1008                 }
1009               else if (lex_match_id (lexer, "MAXIMUM"))
1010                 {
1011                   if (! lex_force_match (lexer, T_LPAREN))
1012                     goto error;
1013                   if (lex_force_num (lexer))
1014                     {
1015                       bar_max = lex_number (lexer);
1016                       lex_get (lexer);
1017                     }
1018                   if (! lex_force_match (lexer, T_RPAREN))
1019                     goto error;
1020                 }
1021               else if (lex_match_id (lexer, "FREQ"))
1022                 {
1023                   if (lex_match (lexer, T_LPAREN))
1024                     {
1025                       if (lex_force_num (lexer))
1026                         {
1027                           lex_number (lexer);
1028                           lex_get (lexer);
1029                         }
1030                       if (! lex_force_match (lexer, T_RPAREN))
1031                         goto error;
1032                     }
1033                   bar_freq = true;
1034                 }
1035               else if (lex_match_id (lexer, "PERCENT"))
1036                 {
1037                   if (lex_match (lexer, T_LPAREN))
1038                     {
1039                       if (lex_force_num (lexer))
1040                         {
1041                           lex_number (lexer);
1042                           lex_get (lexer);
1043                         }
1044                       if (! lex_force_match (lexer, T_RPAREN))
1045                         goto error;
1046                     }
1047                   bar_freq = false;
1048                 }
1049               else
1050                 {
1051                   lex_error (lexer, NULL);
1052                   goto error;
1053                 }
1054             }
1055           sbc_barchart = true;
1056         }
1057       else if (lex_match_id (lexer, "MISSING"))
1058         {
1059           lex_match (lexer, T_EQUALS);
1060
1061           while (lex_token (lexer) != T_ENDCMD
1062                  && lex_token (lexer) != T_SLASH)
1063             {
1064               if (lex_match_id (lexer, "EXCLUDE"))
1065                 {
1066                 }
1067               else if (lex_match_id (lexer, "INCLUDE"))
1068                 {
1069                 }
1070               else
1071                 {
1072                   lex_error (lexer, NULL);
1073                   goto error;
1074                 }
1075             }
1076         }
1077       else if (lex_match_id (lexer, "ORDER"))
1078         {
1079           lex_match (lexer, T_EQUALS);
1080           if (!lex_match_id (lexer, "ANALYSIS"))
1081             lex_match_id (lexer, "VARIABLE");
1082         }
1083       else
1084         {
1085           lex_error (lexer, NULL);
1086           goto error;
1087         }
1088     }
1089
1090   if (frq.stats & BIT_INDEX (FRQ_ST_MEDIAN))
1091     {
1092         frq.percentiles =
1093           xrealloc (frq.percentiles,
1094                     (frq.n_percentiles + 1)
1095                     * sizeof (*frq.percentiles));
1096
1097         frq.percentiles[frq.n_percentiles].p = 0.50;
1098         frq.percentiles[frq.n_percentiles].show = false;
1099
1100         frq.n_percentiles++;
1101     }
1102
1103
1104 /* Figure out which charts the user requested.  */
1105
1106   {
1107     if (sbc_histogram)
1108       {
1109         struct frq_chart *hist;
1110
1111         hist = frq.hist = xmalloc (sizeof *frq.hist);
1112         hist->x_min = hi_min;
1113         hist->x_max = hi_max;
1114         hist->y_scale = hi_scale;
1115         hist->y_max = hi_scale == FRQ_FREQ ? hi_freq : hi_pcnt;
1116         hist->draw_normal = hi_norm != FRQ_NONORMAL;
1117         hist->include_missing = false;
1118
1119         if (hist->x_min != SYSMIS && hist->x_max != SYSMIS
1120             && hist->x_min >= hist->x_max)
1121           {
1122             msg (SE, _("%s for histogram must be greater than or equal to %s, "
1123                        "but %s was specified as %.15g and %s as %.15g.  "
1124                        "%s and %s will be ignored."),
1125                  "MAX", "MIN",
1126                  "MIN", hist->x_min,
1127                  "MAX", hist->x_max,
1128                  "MIN", "MAX");
1129             hist->x_min = hist->x_max = SYSMIS;
1130           }
1131
1132         frq.percentiles =
1133           xrealloc (frq.percentiles,
1134                     (frq.n_percentiles + 2)
1135                     * sizeof (*frq.percentiles));
1136
1137         frq.percentiles[frq.n_percentiles].p = 0.25;
1138         frq.percentiles[frq.n_percentiles].show = false;
1139
1140         frq.percentiles[frq.n_percentiles + 1].p = 0.75;
1141         frq.percentiles[frq.n_percentiles + 1].show = false;
1142
1143         frq.n_percentiles+=2;
1144       }
1145
1146     if (sbc_barchart)
1147       {
1148         frq.bar = xmalloc (sizeof *frq.bar);
1149         frq.bar->x_min = bar_min;
1150         frq.bar->x_max = bar_max;
1151         frq.bar->include_missing = false;
1152         frq.bar->y_scale = bar_freq ? FRQ_FREQ : FRQ_PERCENT;
1153       }
1154
1155     if (sbc_piechart)
1156       {
1157         struct frq_chart *pie;
1158
1159         pie = frq.pie = xmalloc (sizeof *frq.pie);
1160         pie->x_min = pie_min;
1161         pie->x_max = pie_max;
1162         pie->include_missing = pie_missing;
1163
1164         if (pie->x_min != SYSMIS && pie->x_max != SYSMIS
1165             && pie->x_min >= pie->x_max)
1166           {
1167             msg (SE, _("%s for pie chart must be greater than or equal to %s, "
1168                        "but %s was specified as %.15g and %s as %.15g.  "
1169                        "%s and %s will be ignored."),
1170                  "MAX", "MIN",
1171                  "MIN", pie->x_min,
1172                  "MAX", pie->x_max,
1173                  "MIN", "MAX");
1174             pie->x_min = pie->x_max = SYSMIS;
1175           }
1176       }
1177   }
1178
1179   {
1180     int i,o;
1181     double previous_p = -1;
1182     qsort (frq.percentiles, frq.n_percentiles,
1183            sizeof (*frq.percentiles),
1184            ptile_3way);
1185
1186     for (i = o = 0; i < frq.n_percentiles; ++i)
1187       {
1188         if (frq.percentiles[i].p != previous_p)
1189           {
1190             frq.percentiles[o].p = frq.percentiles[i].p;
1191             frq.percentiles[o].show = frq.percentiles[i].show;
1192             o++;
1193           }
1194         else if (frq.percentiles[i].show &&
1195                  !frq.percentiles[o].show)
1196           {
1197             frq.percentiles[o].show = true;
1198           }
1199         previous_p = frq.percentiles[i].p;
1200       }
1201
1202     frq.n_percentiles = o;
1203
1204     frq.median_idx = SIZE_MAX;
1205     for (i = 0; i < frq.n_percentiles; i++)
1206       if (frq.percentiles[i].p == 0.5)
1207         {
1208           frq.median_idx = i;
1209           break;
1210         }
1211   }
1212
1213   {
1214     struct casegrouper *grouper;
1215     struct casereader *group;
1216     bool ok;
1217
1218     grouper = casegrouper_create_splits (proc_open (ds), dataset_dict (ds));
1219     while (casegrouper_get_next_group (grouper, &group))
1220       {
1221         struct ccase *c;
1222         precalc (&frq, group, ds);
1223
1224         for (; (c = casereader_read (group)) != NULL; case_unref (c))
1225           calc (&frq, c, ds);
1226         postcalc (&frq, ds);
1227         casereader_destroy (group);
1228       }
1229     ok = casegrouper_destroy (grouper);
1230     ok = proc_commit (ds) && ok;
1231   }
1232
1233   free (vars);
1234   for (size_t i = 0; i < frq.n_vars; i++)
1235     free (frq.vars[i].percentiles);
1236   free (frq.vars);
1237   free (frq.bar);
1238   free (frq.pie);
1239   free (frq.hist);
1240   free (frq.percentiles);
1241
1242   return CMD_SUCCESS;
1243
1244  error:
1245
1246   free (vars);
1247   free (frq.vars);
1248   for (size_t i = 0; i < frq.n_vars; i++)
1249     free (frq.vars[i].percentiles);
1250   free (frq.bar);
1251   free (frq.pie);
1252   free (frq.hist);
1253   free (frq.percentiles);
1254
1255   return CMD_FAILURE;
1256 }
1257
1258 static double
1259 calculate_iqr (const struct frq_proc *frq, const struct var_freqs *vf)
1260 {
1261   double q1 = SYSMIS;
1262   double q3 = SYSMIS;
1263   int i;
1264
1265   /* This cannot work unless the 25th and 75th percentile are calculated */
1266   assert (frq->n_percentiles >= 2);
1267   for (i = 0; i < frq->n_percentiles; i++)
1268     {
1269       struct percentile *pc = &frq->percentiles[i];
1270
1271       if (fabs (0.25 - pc->p) < DBL_EPSILON)
1272         q1 = vf->percentiles[i];
1273       else if (fabs (0.75 - pc->p) < DBL_EPSILON)
1274         q3 = vf->percentiles[i];
1275     }
1276
1277   return q1 == SYSMIS || q3 == SYSMIS ? SYSMIS : q3 - q1;
1278 }
1279
1280 static bool
1281 chart_includes_value (const struct frq_chart *chart,
1282                       const struct variable *var,
1283                       const union value *value)
1284 {
1285   if (!chart->include_missing && var_is_value_missing (var, value))
1286     return false;
1287
1288   if (var_is_numeric (var)
1289       && ((chart->x_min != SYSMIS && value->f < chart->x_min)
1290           || (chart->x_max != SYSMIS && value->f > chart->x_max)))
1291     return false;
1292
1293   return true;
1294 }
1295
1296 /* Create a gsl_histogram from a freq_tab */
1297 static struct histogram *
1298 freq_tab_to_hist (const struct frq_proc *frq, const struct var_freqs *vf)
1299 {
1300   /* Find out the extremes of the x value, within the range to be included in
1301      the histogram, and sum the total frequency of those values. */
1302   double x_min = DBL_MAX;
1303   double x_max = -DBL_MAX;
1304   double valid_freq = 0;
1305   for (int i = 0; i < vf->tab.n_valid; i++)
1306     {
1307       const struct freq *f = &vf->tab.valid[i];
1308       if (chart_includes_value (frq->hist, vf->var, f->values))
1309         {
1310           x_min = MIN (x_min, f->values[0].f);
1311           x_max = MAX (x_max, f->values[0].f);
1312           valid_freq += f->count;
1313         }
1314     }
1315
1316   if (valid_freq <= 0)
1317     return NULL;
1318
1319   double iqr = calculate_iqr (frq, vf);
1320
1321   double bin_width =
1322     (iqr > 0
1323      ? 2 * iqr / pow (valid_freq, 1.0 / 3.0)       /* Freedman-Diaconis. */
1324      : (x_max - x_min) / (1 + log2 (valid_freq))); /* Sturges */
1325
1326   struct histogram *histogram = histogram_create (bin_width, x_min, x_max);
1327   if (histogram == NULL)
1328     return NULL;
1329
1330   for (int i = 0; i < vf->tab.n_valid; i++)
1331     {
1332       const struct freq *f = &vf->tab.valid[i];
1333       if (chart_includes_value (frq->hist, vf->var, f->values))
1334         histogram_add (histogram, f->values[0].f, f->count);
1335     }
1336
1337   return histogram;
1338 }
1339
1340
1341 /* Allocate an array of struct freqs and fill them from the data in FRQ_TAB,
1342    according to the parameters of CATCHART
1343    N_SLICES will contain the number of slices allocated.
1344    The caller is responsible for freeing slices
1345 */
1346 static struct freq *
1347 pick_cat_counts (const struct frq_chart *catchart,
1348                  const struct freq_tab *frq_tab,
1349                  int *n_slicesp)
1350 {
1351   int n_slices = 0;
1352   int i;
1353   struct freq *slices = xnmalloc (frq_tab->n_valid + frq_tab->n_missing, sizeof *slices);
1354
1355   for (i = 0; i < frq_tab->n_valid; i++)
1356     {
1357       const struct freq *f = &frq_tab->valid[i];
1358       if (f->count > catchart->x_max)
1359         continue;
1360
1361       if (f->count < catchart->x_min)
1362         continue;
1363
1364       slices[n_slices] = *f;
1365
1366       n_slices++;
1367     }
1368
1369   if (catchart->include_missing)
1370     {
1371       for (i = 0; i < frq_tab->n_missing; i++)
1372         {
1373           const struct freq *f = &frq_tab->missing[i];
1374           slices[n_slices].count += f->count;
1375
1376           if (i == 0)
1377             slices[n_slices].values[0] = f->values[0];
1378         }
1379
1380       if (frq_tab->n_missing > 0)
1381         n_slices++;
1382     }
1383
1384   *n_slicesp = n_slices;
1385   return slices;
1386 }
1387
1388
1389 /* Allocate an array of struct freqs and fill them from the data in FRQ_TAB,
1390    according to the parameters of CATCHART
1391    N_SLICES will contain the number of slices allocated.
1392    The caller is responsible for freeing slices
1393 */
1394 static struct freq **
1395 pick_cat_counts_ptr (const struct frq_chart *catchart,
1396                      const struct freq_tab *frq_tab,
1397                      int *n_slicesp)
1398 {
1399   int n_slices = 0;
1400   int i;
1401   struct freq **slices = xnmalloc (frq_tab->n_valid + frq_tab->n_missing, sizeof *slices);
1402
1403   for (i = 0; i < frq_tab->n_valid; i++)
1404     {
1405       struct freq *f = &frq_tab->valid[i];
1406       if (f->count > catchart->x_max)
1407         continue;
1408
1409       if (f->count < catchart->x_min)
1410         continue;
1411
1412       slices[n_slices] = f;
1413
1414       n_slices++;
1415     }
1416
1417   if (catchart->include_missing)
1418     {
1419       for (i = 0; i < frq_tab->n_missing; i++)
1420         {
1421           const struct freq *f = &frq_tab->missing[i];
1422           if (i == 0)
1423             {
1424               slices[n_slices] = xmalloc (sizeof (struct freq));
1425               slices[n_slices]->values[0] = f->values[0];
1426             }
1427
1428           slices[n_slices]->count += f->count;
1429
1430         }
1431     }
1432
1433   *n_slicesp = n_slices;
1434   return slices;
1435 }
1436
1437
1438
1439 static void
1440 do_piechart(const struct frq_chart *pie, const struct variable *var,
1441             const struct freq_tab *frq_tab)
1442 {
1443   int n_slices;
1444   struct freq *slices = pick_cat_counts (pie, frq_tab, &n_slices);
1445
1446   if (n_slices < 2)
1447     msg (SW, _("Omitting pie chart for %s, which has only %d unique values."),
1448          var_get_name (var), n_slices);
1449   else if (n_slices > 50)
1450     msg (SW, _("Omitting pie chart for %s, which has over 50 unique values."),
1451          var_get_name (var));
1452   else
1453     chart_submit (piechart_create (var, slices, n_slices));
1454
1455   free (slices);
1456 }
1457
1458
1459 static void
1460 do_barchart(const struct frq_chart *bar, const struct variable **var,
1461             const struct freq_tab *frq_tab)
1462 {
1463   int n_slices;
1464   struct freq **slices = pick_cat_counts_ptr (bar, frq_tab, &n_slices);
1465
1466   if (n_slices < 1)
1467     msg (SW, _("Omitting bar chart, which has no values."));
1468   else
1469     chart_submit (barchart_create (var, 1,
1470                                    (bar->y_scale == FRQ_FREQ) ? _("Count") : _("Percent"),
1471                                    (bar->y_scale == FRQ_PERCENT),
1472                                    slices, n_slices));
1473   free (slices);
1474 }
1475
1476
1477 /* Calculates all the pertinent statistics for VF, putting them in array
1478    D[]. */
1479 static void
1480 calc_stats (const struct frq_proc *frq, const struct var_freqs *vf,
1481             double d[FRQ_ST_count])
1482 {
1483   const struct freq_tab *ft = &vf->tab;
1484   double W = ft->valid_cases;
1485   const struct freq *f;
1486   struct moments *m;
1487   int most_often = -1;
1488   double X_mode = SYSMIS;
1489
1490   /* Calculate the mode. */
1491   for (f = ft->valid; f < ft->missing; f++)
1492     {
1493       if (most_often < f->count)
1494         {
1495           most_often = f->count;
1496           X_mode = f->values[0].f;
1497         }
1498       else if (most_often == f->count)
1499         {
1500           /* A duplicate mode is undefined.
1501              FIXME: keep track of *all* the modes. */
1502           X_mode = SYSMIS;
1503         }
1504     }
1505
1506   /* Calculate moments. */
1507   m = moments_create (MOMENT_KURTOSIS);
1508   for (f = ft->valid; f < ft->missing; f++)
1509     moments_pass_one (m, f->values[0].f, f->count);
1510   for (f = ft->valid; f < ft->missing; f++)
1511     moments_pass_two (m, f->values[0].f, f->count);
1512   moments_calculate (m, NULL, &d[FRQ_ST_MEAN], &d[FRQ_ST_VARIANCE],
1513                      &d[FRQ_ST_SKEWNESS], &d[FRQ_ST_KURTOSIS]);
1514   moments_destroy (m);
1515
1516   /* Formulae below are taken from _SPSS Statistical Algorithms_. */
1517   if (ft->n_valid > 0)
1518     {
1519       d[FRQ_ST_MINIMUM] = ft->valid[0].values[0].f;
1520       d[FRQ_ST_MAXIMUM] = ft->valid[ft->n_valid - 1].values[0].f;
1521       d[FRQ_ST_RANGE] = d[FRQ_ST_MAXIMUM] - d[FRQ_ST_MINIMUM];
1522     }
1523   else
1524     {
1525       d[FRQ_ST_MINIMUM] = SYSMIS;
1526       d[FRQ_ST_MAXIMUM] = SYSMIS;
1527       d[FRQ_ST_RANGE] = SYSMIS;
1528     }
1529   d[FRQ_ST_MODE] = X_mode;
1530   d[FRQ_ST_SUM] = d[FRQ_ST_MEAN] * W;
1531   d[FRQ_ST_STDDEV] = sqrt (d[FRQ_ST_VARIANCE]);
1532   d[FRQ_ST_SEMEAN] = d[FRQ_ST_STDDEV] / sqrt (W);
1533   d[FRQ_ST_SESKEWNESS] = calc_seskew (W);
1534   d[FRQ_ST_SEKURTOSIS] = calc_sekurt (W);
1535   d[FRQ_ST_MEDIAN] = (frq->median_idx != SIZE_MAX
1536                       ? vf->percentiles[frq->median_idx]
1537                       : SYSMIS);
1538 }
1539
1540 static bool
1541 all_string_variables (const struct frq_proc *frq)
1542 {
1543   for (size_t i = 0; i < frq->n_vars; i++)
1544     if (var_is_numeric (frq->vars[i].var))
1545       return false;
1546
1547   return true;
1548 }
1549
1550 /* Displays a table of all the statistics requested. */
1551 static void
1552 dump_statistics (const struct frq_proc *frq, const struct variable *wv)
1553 {
1554   if (all_string_variables (frq))
1555     return;
1556
1557   struct pivot_table *table = pivot_table_create (N_("Statistics"));
1558   pivot_table_set_weight_var (table, wv);
1559
1560   struct pivot_dimension *variables
1561     = pivot_dimension_create (table, PIVOT_AXIS_COLUMN, N_("Variables"));
1562
1563   struct pivot_dimension *statistics = pivot_dimension_create (
1564     table, PIVOT_AXIS_ROW, N_("Statistics"));
1565   struct pivot_category *n = pivot_category_create_group (
1566     statistics->root, N_("N"));
1567   pivot_category_create_leaves (n,
1568                                 N_("Valid"), PIVOT_RC_COUNT,
1569                                 N_("Missing"), PIVOT_RC_COUNT);
1570   for (int i = 0; i < FRQ_ST_count; i++)
1571     if (frq->stats & BIT_INDEX (i))
1572       pivot_category_create_leaf (statistics->root,
1573                                   pivot_value_new_text (st_name[i]));
1574   struct pivot_category *percentiles = NULL;
1575   for (size_t i = 0; i < frq->n_percentiles; i++)
1576     {
1577       const struct percentile *pc = &frq->percentiles[i];
1578
1579       if (!pc->show)
1580         continue;
1581
1582       if (!percentiles)
1583         percentiles = pivot_category_create_group (
1584           statistics->root, N_("Percentiles"));
1585       pivot_category_create_leaf (percentiles, pivot_value_new_integer (
1586                                     pc->p * 100.0));
1587     }
1588
1589   for (size_t i = 0; i < frq->n_vars; i++)
1590     {
1591       struct var_freqs *vf = &frq->vars[i];
1592       if (var_is_alpha (vf->var))
1593         continue;
1594
1595       const struct freq_tab *ft = &vf->tab;
1596
1597       int var_idx = pivot_category_create_leaf (
1598         variables->root, pivot_value_new_variable (vf->var));
1599
1600       int row = 0;
1601       pivot_table_put2 (table, var_idx, row++,
1602                         pivot_value_new_number (ft->valid_cases));
1603       pivot_table_put2 (table, var_idx, row++,
1604                         pivot_value_new_number (
1605                           ft->total_cases - ft->valid_cases));
1606
1607       double stat_values[FRQ_ST_count];
1608       calc_stats (frq, vf, stat_values);
1609       for (int j = 0; j < FRQ_ST_count; j++)
1610         {
1611           if (!(frq->stats & BIT_INDEX (j)))
1612             continue;
1613
1614           union value v = { .f = vf->tab.n_valid ? stat_values[j] : SYSMIS };
1615           struct pivot_value *pv
1616             = (j == FRQ_ST_MODE || j == FRQ_ST_MINIMUM || j == FRQ_ST_MAXIMUM
1617                ? pivot_value_new_var_value (vf->var, &v)
1618                : pivot_value_new_number (v.f));
1619           pivot_table_put2 (table, var_idx, row++, pv);
1620         }
1621
1622       for (size_t j = 0; j < frq->n_percentiles; j++)
1623         {
1624           const struct percentile *pc = &frq->percentiles[j];
1625           if (!pc->show)
1626             continue;
1627
1628           union value v = {
1629             .f = vf->tab.n_valid ? vf->percentiles[j] : SYSMIS
1630           };
1631           pivot_table_put2 (table, var_idx, row++,
1632                             pivot_value_new_var_value (vf->var, &v));
1633         }
1634     }
1635
1636   pivot_table_submit (table);
1637 }