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