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