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