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