FREQUENCIES: Fixed crash when there was no valid data
[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 Free Software Foundation, Inc.
4    
5   This program is free software: you can redistribute it and/or modify
6   it under the terms of the GNU General Public License as published by
7   the Free Software Foundation, either version 3 of the License, or
8   (at your option) any later version.
9
10   This program is distributed in the hope that it will be useful,
11   but WITHOUT ANY WARRANTY; without even the implied warranty of
12   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   GNU General Public License for more details.
14   
15   You should have received a copy of the GNU General Public License
16   along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 #include <config.h>
20 #include <stdlib.h>
21 #include <gsl/gsl_histogram.h>
22
23
24 #include "data/case.h"
25 #include "data/casegrouper.h"
26 #include "data/casereader.h"
27 #include "data/dataset.h"
28 #include "data/dictionary.h"
29 #include "data/format.h"
30 #include "data/missing-values.h"
31 #include "data/settings.h"
32 #include "data/value-labels.h"
33 #include "data/variable.h"
34
35 #include "language/dictionary/split-file.h"
36
37 #include "language/command.h"
38 #include "language/lexer/lexer.h"
39 #include "language/lexer/variable-parser.h"
40 #include "language/stats/freq.h"
41
42 #include "libpspp/array.h"
43 #include "libpspp/bit-vector.h"
44 #include "libpspp/compiler.h"
45 #include "libpspp/hmap.h"
46 #include "libpspp/message.h"
47 #include "libpspp/misc.h"
48 #include "libpspp/pool.h"
49
50 #include "math/histogram.h"
51 #include "math/moments.h"
52 #include "math/chart-geometry.h"
53
54
55 #include "output/chart-item.h"
56 #include "output/charts/piechart.h"
57 #include "output/charts/plot-hist.h"
58 #include "output/tab.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   return (p1->p > p2->p);
86 }
87
88
89 enum
90   {
91     FRQ_NONORMAL,
92     FRQ_NORMAL
93   };
94
95 enum
96   {
97     FRQ_FREQ,
98     FRQ_PERCENT
99   };
100
101 enum sortprops 
102   {
103     FRQ_AFREQ,
104     FRQ_DFREQ,
105     FRQ_AVALUE,
106     FRQ_DVALUE
107   };
108
109 /* Array indices for STATISTICS subcommand. */
110 enum
111   {
112     FRQ_ST_MEAN,
113     FRQ_ST_SEMEAN,
114     FRQ_ST_MEDIAN,
115     FRQ_ST_MODE,
116     FRQ_ST_STDDEV,
117     FRQ_ST_VARIANCE,
118     FRQ_ST_KURTOSIS,
119     FRQ_ST_SEKURTOSIS,
120     FRQ_ST_SKEWNESS,
121     FRQ_ST_SESKEWNESS,
122     FRQ_ST_RANGE,
123     FRQ_ST_MINIMUM,
124     FRQ_ST_MAXIMUM,
125     FRQ_ST_SUM,
126     FRQ_ST_count
127   };
128
129 /* Description of statistics. */
130 static const char *st_name[FRQ_ST_count] =
131 {
132    N_("Mean"),
133    N_("S.E. Mean"),
134    N_("Median"),
135    N_("Mode"),
136    N_("Std Dev"),
137    N_("Variance"),
138    N_("Kurtosis"),
139    N_("S.E. Kurt"),
140    N_("Skewness"),
141    N_("S.E. Skew"),
142    N_("Range"),
143    N_("Minimum"),
144    N_("Maximum"),
145    N_("Sum")
146 };
147
148 struct freq_tab
149   {
150     struct hmap data;           /* Hash table for accumulating counts. */
151     struct freq *valid;         /* Valid freqs. */
152     int n_valid;                /* Number of total freqs. */
153     const struct dictionary *dict; /* Source of entries in the table. */
154
155     struct freq *missing;       /* Missing freqs. */
156     int n_missing;              /* Number of missing freqs. */
157
158     /* Statistics. */
159     double total_cases;         /* Sum of weights of all cases. */
160     double valid_cases;         /* Sum of weights of valid cases. */
161   };
162
163 struct frq_chart
164   {
165     double x_min;               /* X axis minimum value. */
166     double x_max;               /* X axis maximum value. */
167     int y_scale;                /* Y axis scale: FRQ_FREQ or FRQ_PERCENT. */
168
169     /* Histograms only. */
170     double y_max;               /* Y axis maximum value. */
171     bool draw_normal;           /* Whether to draw normal curve. */
172
173     /* Pie charts only. */
174     bool include_missing;       /* Whether to include missing values. */
175   };
176
177 /* Per-variable frequency data. */
178 struct var_freqs
179   {
180     const struct variable *var;
181
182     /* Freqency table. */
183     struct freq_tab tab;        /* Frequencies table to use. */
184
185     /* Percentiles. */
186     int n_groups;               /* Number of groups. */
187     double *groups;             /* Groups. */
188
189     /* Statistics. */
190     double stat[FRQ_ST_count];
191
192     /* Variable attributes. */
193     int width;
194   };
195
196 struct frq_proc
197   {
198     struct pool *pool;
199
200     struct var_freqs *vars;
201     size_t n_vars;
202
203     /* Percentiles to calculate and possibly display. */
204     struct percentile *percentiles;
205     int n_percentiles, n_show_percentiles;
206
207     /* Frequency table display. */
208     int max_categories;         /* Maximum categories to show. */
209     int sort;                   /* FRQ_AVALUE or FRQ_DVALUE
210                                    or FRQ_AFREQ or FRQ_DFREQ. */
211
212     /* Statistics; number of statistics. */
213     unsigned long stats;
214     int n_stats;
215
216     /* Histogram and pie chart settings. */
217     struct frq_chart *hist, *pie;
218   };
219
220
221 struct freq_compare_aux
222   {
223     bool by_freq;
224     bool ascending_freq;
225
226     int width;
227     bool ascending_value;
228   };
229
230 static void calc_stats (const struct var_freqs *vf, double d[FRQ_ST_count]);
231
232 static void do_piechart(const struct frq_chart *pie, 
233                         const struct variable *var,
234                         const struct freq_tab *frq_tab);
235
236 static void dump_statistics (const struct frq_proc *frq, 
237                              const struct var_freqs *vf,
238                              const struct variable *wv);
239
240 static int
241 compare_freq (const void *a_, const void *b_, const void *aux_)
242 {
243   const struct freq_compare_aux *aux = aux_;
244   const struct freq *a = a_;
245   const struct freq *b = b_;
246
247   if (aux->by_freq && a->count != b->count)
248     {
249       int cmp = a->count > b->count ? 1 : -1;
250       return aux->ascending_freq ? cmp : -cmp;
251     }
252   else
253     {
254       int cmp = value_compare_3way (&a->value, &b->value, aux->width);
255       return aux->ascending_value ? cmp : -cmp;
256     }
257 }
258
259 /* Create a gsl_histogram from a freq_tab */
260 static struct histogram *
261 freq_tab_to_hist (const struct frq_proc *frq, const struct freq_tab *ft,
262                   const struct variable *var);
263
264
265 /* Displays a full frequency table for variable V. */
266 static void
267 dump_freq_table (const struct var_freqs *vf, const struct variable *wv)
268 {
269   const struct fmt_spec *wfmt = wv ? var_get_print_format (wv) : &F_8_0;
270   const struct freq_tab *ft = &vf->tab;
271   int n_categories;
272   struct freq *f;
273   struct tab_table *t;
274   int r, x;
275   double cum_total = 0.0;
276   double cum_freq = 0.0;
277
278   static const char *headings[] = {
279     N_("Value Label"),
280     N_("Value"),
281     N_("Frequency"),
282     N_("Percent"),
283     N_("Valid Percent"),
284     N_("Cum Percent")
285   };
286
287   n_categories = ft->n_valid + ft->n_missing;
288   t = tab_create (6, n_categories + 2);
289   tab_set_format (t, RC_WEIGHT, wfmt);
290   tab_headers (t, 0, 0, 1, 0);
291
292   for (x = 0; x < 6; x++)
293     tab_text (t, x, 0, TAB_CENTER | TAT_TITLE, gettext (headings[x]));
294
295   r = 1;
296   for (f = ft->valid; f < ft->missing; f++)
297     {
298       const char *label;
299       double percent, valid_percent;
300
301       cum_freq += f->count;
302
303       percent = f->count / ft->total_cases * 100.0;
304       valid_percent = f->count / ft->valid_cases * 100.0;
305       cum_total += valid_percent;
306
307       label = var_lookup_value_label (vf->var, &f->value);
308       if (label != NULL)
309         tab_text (t, 0, r, TAB_LEFT, label);
310
311       tab_value (t, 1, r, TAB_NONE, &f->value, vf->var, NULL);
312       tab_double (t, 2, r, TAB_NONE, f->count, NULL, RC_WEIGHT);
313       tab_double (t, 3, r, TAB_NONE, percent, NULL, RC_OTHER);
314       tab_double (t, 4, r, TAB_NONE, valid_percent, NULL, RC_OTHER);
315       tab_double (t, 5, r, TAB_NONE, cum_total, NULL, RC_OTHER);
316       r++;
317     }
318   for (; f < &ft->valid[n_categories]; f++)
319     {
320       const char *label;
321
322       cum_freq += f->count;
323
324       label = var_lookup_value_label (vf->var, &f->value);
325       if (label != NULL)
326         tab_text (t, 0, r, TAB_LEFT, label);
327
328       tab_value (t, 1, r, TAB_NONE, &f->value, vf->var, NULL);
329       tab_double (t, 2, r, TAB_NONE, f->count, NULL, RC_WEIGHT);
330       tab_double (t, 3, r, TAB_NONE,
331                   f->count / ft->total_cases * 100.0, NULL, RC_OTHER);
332       tab_text (t, 4, r, TAB_NONE, _("Missing"));
333       r++;
334     }
335
336   tab_box (t, TAL_1, TAL_1, -1, TAL_1, 0, 0, 5, r);
337   tab_hline (t, TAL_2, 0, 5, 1);
338   tab_hline (t, TAL_2, 0, 5, r);
339   tab_joint_text (t, 0, r, 1, r, TAB_RIGHT | TAT_TITLE, _("Total"));
340   tab_vline (t, TAL_0, 1, r, r);
341   tab_double (t, 2, r, TAB_NONE, cum_freq, NULL, RC_WEIGHT);
342   tab_double (t, 3, r, TAB_NONE, 100.0, &F_5_1, RC_OTHER);
343   tab_double (t, 4, r, TAB_NONE, 100.0, &F_5_1, RC_OTHER);
344
345   tab_title (t, "%s", var_to_string (vf->var));
346   tab_submit (t);
347 }
348 \f
349 /* Statistical display. */
350
351 static double
352 calc_percentile (double p, double valid_cases, double x1, double x2)
353 {
354   double s, dummy;
355
356   s = (settings_get_algorithm () != COMPATIBLE
357        ? modf ((valid_cases - 1) * p, &dummy)
358        : modf ((valid_cases + 1) * p - 1, &dummy));
359
360   return x1 + (x2 - x1) * s;
361 }
362
363 /* Calculates all of the percentiles for VF within FRQ. */
364 static void
365 calc_percentiles (const struct frq_proc *frq, const struct var_freqs *vf)
366 {
367   const struct freq_tab *ft = &vf->tab;
368   double W = ft->valid_cases;
369   const struct freq *f;
370   int percentile_idx = 0;
371   double  rank = 0;
372
373   for (f = ft->valid; f < ft->missing; f++)
374     {
375       rank += f->count;
376       for (; percentile_idx < frq->n_percentiles; percentile_idx++)
377         {
378           struct percentile *pc = &frq->percentiles[percentile_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             pc->value = f->value.f;
390           else
391             pc->value = calc_percentile (pc->p, W, f->value.f, f[1].value.f);
392         }
393     }
394   for (; percentile_idx < frq->n_percentiles; percentile_idx++)
395     {
396       struct percentile *pc = &frq->percentiles[percentile_idx];
397       pc->value = ft->valid[ft->n_valid - 1].value.f;
398     }
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->value, MV_ANY);
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 /* Frees the frequency table for variable V. */
460 static void
461 cleanup_freq_tab (struct var_freqs *vf)
462 {
463   free (vf->tab.valid);
464   freq_hmap_destroy (&vf->tab.data, vf->width);
465 }
466
467 /* Add data from case C to the frequency table. */
468 static void
469 calc (struct frq_proc *frq, const struct ccase *c, const struct dataset *ds)
470 {
471   double weight = dict_get_case_weight (dataset_dict (ds), c, NULL);
472   size_t i;
473
474   for (i = 0; i < frq->n_vars; i++)
475     {
476       struct var_freqs *vf = &frq->vars[i];
477       const union value *value = case_data (c, vf->var);
478       size_t hash = value_hash (value, vf->width, 0);
479       struct freq *f;
480
481       f = freq_hmap_search (&vf->tab.data, value, vf->width, hash);
482       if (f == NULL)
483         f = freq_hmap_insert (&vf->tab.data, value, vf->width, hash);
484
485       f->count += weight;
486     }
487 }
488
489 /* Prepares each variable that is the target of FREQUENCIES by setting
490    up its hash table. */
491 static void
492 precalc (struct frq_proc *frq, struct casereader *input, struct dataset *ds)
493 {
494   struct ccase *c;
495   size_t i;
496
497   c = casereader_peek (input, 0);
498   if (c != NULL)
499     {
500       output_split_file_values (ds, c);
501       case_unref (c);
502     }
503
504   for (i = 0; i < frq->n_vars; i++)
505     hmap_init (&frq->vars[i].tab.data);
506 }
507
508 /* Finishes up with the variables after frequencies have been
509    calculated.  Displays statistics, percentiles, ... */
510 static void
511 postcalc (struct frq_proc *frq, const struct dataset *ds)
512 {
513   const struct dictionary *dict = dataset_dict (ds);
514   const struct variable *wv = dict_get_weight (dict);
515   size_t i;
516
517   for (i = 0; i < frq->n_vars; i++)
518     {
519       struct var_freqs *vf = &frq->vars[i];
520
521       postprocess_freq_tab (frq, vf);
522
523       /* Frequencies tables. */
524       if (vf->tab.n_valid + vf->tab.n_missing <= frq->max_categories)
525         dump_freq_table (vf, wv);
526
527       calc_percentiles (frq, vf);
528
529       /* Statistics. */
530       if (frq->n_stats)
531         dump_statistics (frq, vf, wv);
532
533       if (frq->hist && var_is_numeric (vf->var) && vf->tab.n_valid > 0)
534         {
535           double d[FRQ_ST_count];
536           struct histogram *histogram;
537
538           calc_stats (vf, d);
539
540           histogram = freq_tab_to_hist (frq, &vf->tab, vf->var);
541
542           if ( histogram)
543             {
544               chart_item_submit (histogram_chart_create (
545                                histogram->gsl_hist, var_to_string(vf->var),
546                                vf->tab.valid_cases,
547                                d[FRQ_ST_MEAN],
548                                d[FRQ_ST_STDDEV],
549                                frq->hist->draw_normal));
550
551               statistic_destroy (&histogram->parent);
552             }
553         }
554
555       if (frq->pie)
556         do_piechart(frq->pie, vf->var, &vf->tab);
557
558       cleanup_freq_tab (vf);
559     }
560 }
561
562 int
563 cmd_frequencies (struct lexer *lexer, struct dataset *ds)
564 {
565   int i;
566   struct frq_proc frq;
567   const struct variable **vars;
568
569   bool sbc_barchart = false;
570   bool sbc_piechart = false;
571   bool sbc_histogram = false;
572
573   double pie_min = -DBL_MAX;
574   double pie_max = DBL_MAX;
575   bool pie_missing = false;
576
577   double hi_min = -DBL_MAX;
578   double hi_max = DBL_MAX;
579   int hi_scale = FRQ_FREQ;
580   int hi_freq = INT_MIN;
581   int hi_pcnt = INT_MIN;
582   int hi_norm = FRQ_NONORMAL;
583
584   frq.pool = pool_create ();
585   frq.sort = FRQ_AVALUE;
586
587   frq.vars = NULL;
588   frq.n_vars = 0;
589   
590   frq.stats = BIT_INDEX (FRQ_ST_MEAN) 
591     | BIT_INDEX (FRQ_ST_STDDEV) 
592     | BIT_INDEX (FRQ_ST_MINIMUM)
593     | BIT_INDEX (FRQ_ST_MAXIMUM);
594
595   frq.n_stats = 4;
596
597   frq.max_categories = INT_MAX;
598
599   frq.percentiles = NULL;
600   frq.n_percentiles = 0;
601   frq.n_show_percentiles = 0;
602
603   frq.hist = NULL;
604   frq.pie = NULL;
605
606
607   /* Accept an optional, completely pointless "/VARIABLES=" */
608   lex_match (lexer, T_SLASH);
609   if (lex_match_id  (lexer, "VARIABLES"))
610     {
611       if (! lex_force_match (lexer, T_EQUALS) )
612         goto error;
613     }
614
615   if (!parse_variables_const (lexer, dataset_dict (ds),
616                               &vars,
617                               &frq.n_vars,
618                               PV_NO_DUPLICATE))
619     goto error;
620
621   frq.vars = xzalloc (frq.n_vars * sizeof (*frq.vars));
622   for (i = 0; i < frq.n_vars; ++i)
623     {
624       frq.vars[i].var = vars[i];
625       frq.vars[i].width = var_get_width (vars[i]);
626     }
627
628   while (lex_token (lexer) != T_ENDCMD)
629     {
630       lex_match (lexer, T_SLASH);
631
632       if (lex_match_id (lexer, "STATISTICS"))
633         {
634           frq.stats = BIT_INDEX (FRQ_ST_MEAN) 
635             | BIT_INDEX (FRQ_ST_STDDEV) 
636             | BIT_INDEX (FRQ_ST_MINIMUM)
637             | BIT_INDEX (FRQ_ST_MAXIMUM);
638           
639           frq.n_stats = 4;
640
641           if (lex_match (lexer, T_EQUALS))
642             {
643               frq.n_stats = 0;
644               frq.stats = 0;
645             }
646
647           while (lex_token (lexer) != T_ENDCMD
648                  && lex_token (lexer) != T_SLASH)
649             {
650               if (lex_match_id (lexer, "DEFAULT"))
651                 {
652                   frq.stats = BIT_INDEX (FRQ_ST_MEAN) 
653                     | BIT_INDEX (FRQ_ST_STDDEV) 
654                     | BIT_INDEX (FRQ_ST_MINIMUM)
655                     | BIT_INDEX (FRQ_ST_MAXIMUM);
656
657                   frq.n_stats = 4;
658                 }
659               else if (lex_match_id (lexer, "MEAN"))
660                 {
661                   frq.stats |= BIT_INDEX (FRQ_ST_MEAN);
662                   frq.n_stats++;
663                 }
664               else if (lex_match_id (lexer, "SEMEAN"))
665                 {
666                   frq.stats |= BIT_INDEX (FRQ_ST_SEMEAN);
667                   frq.n_stats++;
668                 }
669               else if (lex_match_id (lexer, "MEDIAN"))
670                 {
671                   frq.stats |= BIT_INDEX (FRQ_ST_MEDIAN);
672                   frq.n_stats++;
673                 }
674               else if (lex_match_id (lexer, "MODE"))
675                 {
676                   frq.stats |= BIT_INDEX (FRQ_ST_MODE);
677                   frq.n_stats++;
678                 }
679               else if (lex_match_id (lexer, "STDDEV"))
680                 {
681                   frq.stats |= BIT_INDEX (FRQ_ST_STDDEV);
682                   frq.n_stats++;
683                 }
684               else if (lex_match_id (lexer, "VARIANCE"))
685                 {
686                   frq.stats |= BIT_INDEX (FRQ_ST_MEAN);
687                   frq.n_stats++;
688                 }
689               else if (lex_match_id (lexer, "KURTOSIS"))
690                 {
691                   frq.stats |= BIT_INDEX (FRQ_ST_KURTOSIS);
692                   frq.n_stats++;
693                 }
694               else if (lex_match_id (lexer, "SKEWNESS"))
695                 {
696                   frq.stats |= BIT_INDEX (FRQ_ST_SKEWNESS);
697                   frq.n_stats++;
698                 }
699               else if (lex_match_id (lexer, "RANGE"))
700                 {
701                   frq.stats |= BIT_INDEX (FRQ_ST_RANGE);
702                   frq.n_stats++;
703                 }
704               else if (lex_match_id (lexer, "MINIMUM"))
705                 {
706                   frq.stats |= BIT_INDEX (FRQ_ST_MINIMUM);
707                   frq.n_stats++;
708                 }
709               else if (lex_match_id (lexer, "MAXIMUM"))
710                 {
711                   frq.stats |= BIT_INDEX (FRQ_ST_MAXIMUM);
712                   frq.n_stats++;
713                 }
714               else if (lex_match_id (lexer, "SUM"))
715                 {
716                   frq.stats |= BIT_INDEX (FRQ_ST_SUM);
717                   frq.n_stats++;
718                 }
719               else if (lex_match_id (lexer, "SESKEWNESS"))
720                 {
721                   frq.stats |= BIT_INDEX (FRQ_ST_SESKEWNESS);
722                   frq.n_stats++;
723                 }
724               else if (lex_match_id (lexer, "SEKURTOSIS"))
725                 {
726                   frq.stats |= BIT_INDEX (FRQ_ST_SEKURTOSIS);
727                   frq.n_stats++;
728                 }
729               else if (lex_match_id (lexer, "NONE"))
730                 {
731                   frq.stats = 0;
732                   frq.n_stats = 0;
733                 }
734               else if (lex_match (lexer, T_ALL))
735                 {
736                   frq.stats = ~0;
737                   frq.n_stats = FRQ_ST_count;
738                 }
739               else
740                 {
741                   lex_error (lexer, NULL);
742                   goto error;
743                 }
744             }
745         }
746       else if (lex_match_id (lexer, "PERCENTILES"))
747         {
748           lex_match (lexer, T_EQUALS);
749           while (lex_token (lexer) != T_ENDCMD
750                  && lex_token (lexer) != T_SLASH)
751             {
752               if (lex_force_num (lexer))
753                 {
754                   frq.percentiles =
755                     xrealloc (frq.percentiles, 
756                               (frq.n_percentiles + 1)
757                               * sizeof (*frq.percentiles));
758                   frq.percentiles[frq.n_percentiles].p = lex_number (lexer)  / 100.0;
759                   frq.percentiles[frq.n_percentiles].show = true;
760                   lex_get (lexer);
761                   frq.n_percentiles++;
762                   frq.n_show_percentiles++;
763                 }
764               else
765                 {
766                   lex_error (lexer, NULL);
767                   goto error;
768                 }
769             }
770         }
771       else if (lex_match_id (lexer, "FORMAT"))
772         {
773           lex_match (lexer, T_EQUALS);
774           while (lex_token (lexer) != T_ENDCMD
775                  && lex_token (lexer) != T_SLASH)
776             {
777               if (lex_match_id (lexer, "TABLE"))
778                 {
779                   
780                 }
781               else if (lex_match_id (lexer, "NOTABLE"))
782                 {
783                   frq.max_categories = 0;
784                 }
785               else if (lex_match_id (lexer, "AVALUE"))
786                 {
787                   frq.sort = FRQ_AVALUE;
788                 }
789               else if (lex_match_id (lexer, "DVALUE"))
790                 {
791                   frq.sort = FRQ_DVALUE;
792                 }
793               else if (lex_match_id (lexer, "AFREQ"))
794                 {
795                   frq.sort = FRQ_AFREQ;
796                 }
797               else if (lex_match_id (lexer, "DFREQ"))
798                 {
799                   frq.sort = FRQ_DFREQ;
800                 }
801               else
802                 {
803                   lex_error (lexer, NULL);
804                   goto error;
805                 }
806             }
807         }
808       else if (lex_match_id (lexer, "NTILES"))
809         {
810           lex_match (lexer, T_EQUALS);
811
812           if (lex_force_int (lexer))
813             {
814               int i;
815               int n = lex_integer (lexer);
816               lex_get (lexer);
817               for (i = 0; i < n + 1; ++i)
818                 {
819                   frq.percentiles =
820                     xrealloc (frq.percentiles, 
821                               (frq.n_percentiles + 1)
822                               * sizeof (*frq.percentiles));
823                   frq.percentiles[frq.n_percentiles].p =
824                     i / (double) n ;
825                   frq.percentiles[frq.n_percentiles].show = true;
826
827                   frq.n_percentiles++;
828                   frq.n_show_percentiles++;
829                 }
830             }
831           else
832             {
833               lex_error (lexer, NULL);
834               goto error;
835             }
836         }
837       else if (lex_match_id (lexer, "ALGORITHM"))
838         {
839           lex_match (lexer, T_EQUALS);
840
841           if (lex_match_id (lexer, "COMPATIBLE"))
842             {
843               settings_set_cmd_algorithm (COMPATIBLE);
844             }
845           else if (lex_match_id (lexer, "ENHANCED"))
846             {
847               settings_set_cmd_algorithm (ENHANCED);
848             }
849           else
850             {
851               lex_error (lexer, NULL);
852               goto error;
853             }
854         }
855       else if (lex_match_id (lexer, "HISTOGRAM"))
856         {
857           lex_match (lexer, T_EQUALS);
858           sbc_histogram = true;
859
860           while (lex_token (lexer) != T_ENDCMD
861                  && lex_token (lexer) != T_SLASH)
862             {
863               if (lex_match_id (lexer, "NORMAL"))
864                 {
865                   hi_norm = FRQ_NORMAL;
866                 }
867               else if (lex_match_id (lexer, "NONORMAL"))
868                 {
869                   hi_norm = FRQ_NONORMAL;
870                 }
871               else if (lex_match_id (lexer, "FREQ"))
872                 {
873                   hi_scale = FRQ_FREQ;
874                   if (lex_match (lexer, T_LPAREN))
875                     {
876                       if (lex_force_int (lexer))
877                         {
878                           hi_freq = lex_integer (lexer);
879                           if (hi_freq <= 0)
880                             {
881                               lex_error (lexer, _("Histogram frequency must be greater than zero."));
882                             }
883                           lex_get (lexer);
884                           lex_force_match (lexer, T_RPAREN);
885                         }
886                     }
887                 }
888               else if (lex_match_id (lexer, "PERCENT"))
889                 {
890                   hi_scale = FRQ_PERCENT;
891                   if (lex_match (lexer, T_LPAREN))
892                     {
893                       if (lex_force_int (lexer))
894                         {
895                           hi_pcnt = lex_integer (lexer);
896                           if (hi_pcnt <= 0)
897                             {
898                               lex_error (lexer, _("Histogram percentage must be greater than zero."));
899                             }
900                           lex_get (lexer);
901                           lex_force_match (lexer, T_RPAREN);
902                         }
903                     }
904                 }
905               else if (lex_match_id (lexer, "MINIMUM"))
906                 {
907                   lex_force_match (lexer, T_LPAREN);
908                   if (lex_force_num (lexer))
909                     {
910                       hi_min = lex_number (lexer);
911                       lex_get (lexer);
912                     }
913                   lex_force_match (lexer, T_RPAREN);
914                 }
915               else if (lex_match_id (lexer, "MAXIMUM"))
916                 {
917                   lex_force_match (lexer, T_LPAREN);
918                   if (lex_force_num (lexer))
919                     {
920                       hi_max = lex_number (lexer);
921                       lex_get (lexer);
922                     }
923                   lex_force_match (lexer, T_RPAREN);
924                 }
925               else
926                 {
927                   lex_error (lexer, NULL);
928                   goto error;
929                 }
930             }
931         }
932       else if (lex_match_id (lexer, "PIECHART"))
933         {
934           lex_match (lexer, T_EQUALS);
935           while (lex_token (lexer) != T_ENDCMD
936                  && lex_token (lexer) != T_SLASH)
937             {
938               if (lex_match_id (lexer, "MINIMUM"))
939                 {
940                   lex_force_match (lexer, T_LPAREN);
941                   if (lex_force_num (lexer))
942                     {
943                       pie_min = lex_number (lexer);
944                       lex_get (lexer);
945                     }
946                   lex_force_match (lexer, T_RPAREN);
947                 }
948               else if (lex_match_id (lexer, "MAXIMUM"))
949                 {
950                   lex_force_match (lexer, T_LPAREN);
951                   if (lex_force_num (lexer))
952                     {
953                       pie_max = lex_number (lexer);
954                       lex_get (lexer);
955                     }
956                   lex_force_match (lexer, T_RPAREN);
957                 }
958               else if (lex_match_id (lexer, "MISSING"))
959                 {
960                   pie_missing = true;
961                 }
962               else if (lex_match_id (lexer, "NOMISSING"))
963                 {
964                   pie_missing = false;
965                 }
966               else
967                 {
968                   lex_error (lexer, NULL);
969                   goto error;
970                 }
971             }
972           sbc_piechart = true;
973         }
974       else if (lex_match_id (lexer, "MISSING"))
975         {
976           lex_match (lexer, T_EQUALS);
977
978           while (lex_token (lexer) != T_ENDCMD
979                  && lex_token (lexer) != T_SLASH)
980             {
981               if (lex_match_id (lexer, "EXCLUDE"))
982                 {
983                 }
984               else if (lex_match_id (lexer, "INCLUDE"))
985                 {
986                 }
987               else
988                 {
989                   lex_error (lexer, NULL);
990                   goto error;
991                 }
992             }
993         }
994       else
995         {
996           lex_error (lexer, NULL);
997           goto error;
998         }
999     }
1000
1001   if (frq.stats & BIT_INDEX (FRQ_ST_MEDIAN))
1002     {
1003         frq.percentiles =
1004           xrealloc (frq.percentiles, 
1005                     (frq.n_percentiles + 1)
1006                     * sizeof (*frq.percentiles));
1007         
1008         frq.percentiles[frq.n_percentiles].p = 0.50;
1009         frq.percentiles[frq.n_percentiles].show = true;
1010
1011         frq.n_percentiles++;
1012     }
1013
1014
1015 /* Figure out which charts the user requested.  */
1016
1017   {
1018     if (sbc_barchart)
1019       msg (SW, _("Bar charts are not implemented."));
1020
1021     if (sbc_histogram)
1022       {
1023         struct frq_chart *hist;
1024
1025         hist = frq.hist = xmalloc (sizeof *frq.hist);
1026         hist->x_min = hi_min;
1027         hist->x_max = hi_max;
1028         hist->y_scale = hi_scale;
1029         hist->y_max = hi_scale == FRQ_FREQ ? hi_freq : hi_pcnt;
1030         hist->draw_normal = hi_norm != FRQ_NONORMAL;
1031         hist->include_missing = false;
1032
1033         if (hist->x_min != SYSMIS && hist->x_max != SYSMIS
1034             && hist->x_min >= hist->x_max)
1035           {
1036             msg (SE, _("%s for histogram must be greater than or equal to %s, "
1037                        "but %s was specified as %.15g and %s as %.15g.  "
1038                        "%s and %s will be ignored."),
1039                  "MAX", "MIN", 
1040                  "MIN", hist->x_min, 
1041                  "MAX", hist->x_max,
1042                  "MIN", "MAX");
1043             hist->x_min = hist->x_max = SYSMIS;
1044           }
1045
1046         frq.percentiles =
1047           xrealloc (frq.percentiles, 
1048                     (frq.n_percentiles + 2)
1049                     * sizeof (*frq.percentiles));
1050         
1051         frq.percentiles[frq.n_percentiles].p = 0.25;
1052         frq.percentiles[frq.n_percentiles].show = false;
1053
1054         frq.percentiles[frq.n_percentiles + 1].p = 0.75;
1055         frq.percentiles[frq.n_percentiles + 1].show = false;
1056         
1057         frq.n_percentiles+=2;
1058       }
1059
1060     if (sbc_piechart)
1061       {
1062         struct frq_chart *pie;
1063
1064         pie = frq.pie = xmalloc (sizeof *frq.pie);
1065         pie->x_min = pie_min;
1066         pie->x_max = pie_max;
1067         pie->include_missing = pie_missing;
1068
1069         if (pie->x_min != SYSMIS && pie->x_max != SYSMIS
1070             && pie->x_min >= pie->x_max)
1071           {
1072             msg (SE, _("%s for pie chart must be greater than or equal to %s, "
1073                        "but %s was specified as %.15g and %s as %.15g.  "
1074                        "%s and %s will be ignored."), 
1075                  "MAX", "MIN", 
1076                  "MIN", pie->x_min,
1077                  "MAX", pie->x_max,
1078                  "MIN", "MAX");
1079             pie->x_min = pie->x_max = SYSMIS;
1080           }
1081       }
1082   }
1083
1084   {
1085     int i,o;
1086     double previous_p = -1;
1087     qsort (frq.percentiles, frq.n_percentiles,
1088            sizeof (*frq.percentiles), 
1089            ptile_3way);
1090
1091     frq.n_show_percentiles = 0;
1092     for (i = o = 0; i < frq.n_percentiles; ++i)
1093       {
1094         frq.percentiles[o].p = frq.percentiles[i].p;
1095
1096         if (frq.percentiles[i].show)
1097           frq.percentiles[o].show = true;
1098
1099         if (frq.percentiles[i].p != previous_p)
1100           {
1101             if (frq.percentiles[i].show)
1102               frq.n_show_percentiles++;
1103
1104             o++;
1105           }
1106
1107         previous_p = frq.percentiles[i].p;
1108       }
1109
1110     frq.n_percentiles = o;
1111   }
1112
1113   {
1114     struct casegrouper *grouper;
1115     struct casereader *group;
1116     bool ok;
1117
1118     grouper = casegrouper_create_splits (proc_open (ds), dataset_dict (ds));
1119     while (casegrouper_get_next_group (grouper, &group))
1120       {
1121         struct ccase *c;
1122         precalc (&frq, group, ds);
1123         for (; (c = casereader_read (group)) != NULL; case_unref (c))
1124           calc (&frq, c, ds);
1125         postcalc (&frq, ds);
1126       }
1127     ok = casegrouper_destroy (grouper);
1128     ok = proc_commit (ds) && ok;
1129   }
1130
1131
1132   return CMD_SUCCESS;
1133
1134  error:
1135
1136   return CMD_FAILURE;
1137 }
1138
1139 static double
1140 calculate_iqr (const struct frq_proc *frq)
1141 {
1142   double q1 = SYSMIS;
1143   double q3 = SYSMIS;
1144   int i;
1145
1146   /* This cannot work unless the 25th and 75th percentile are calculated */
1147   assert (frq->n_percentiles >= 2);
1148   for (i = 0; i < frq->n_percentiles; i++)
1149     {
1150       struct percentile *pc = &frq->percentiles[i];
1151
1152       if (fabs (0.25 - pc->p) < DBL_EPSILON)
1153         q1 = pc->value;
1154       else if (fabs (0.75 - pc->p) < DBL_EPSILON)
1155         q3 = pc->value;
1156     }
1157
1158   return q1 == SYSMIS || q3 == SYSMIS ? SYSMIS : q3 - q1;
1159 }
1160
1161 static bool
1162 chart_includes_value (const struct frq_chart *chart,
1163                       const struct variable *var,
1164                       const union value *value)
1165 {
1166   if (!chart->include_missing && var_is_value_missing (var, value, MV_ANY))
1167     return false;
1168
1169   if (var_is_numeric (var)
1170       && ((chart->x_min != SYSMIS && value->f < chart->x_min)
1171           || (chart->x_max != SYSMIS && value->f > chart->x_max)))
1172     return false;
1173
1174   return true;
1175 }
1176
1177 /* Create a gsl_histogram from a freq_tab */
1178 static struct histogram *
1179 freq_tab_to_hist (const struct frq_proc *frq, const struct freq_tab *ft,
1180                   const struct variable *var)
1181 {
1182   double x_min, x_max, valid_freq;
1183   int i;
1184   double bin_width;
1185   struct histogram *histogram;
1186   double iqr;
1187
1188   /* Find out the extremes of the x value, within the range to be included in
1189      the histogram, and sum the total frequency of those values. */
1190   x_min = DBL_MAX;
1191   x_max = -DBL_MAX;
1192   valid_freq = 0;
1193   for (i = 0; i < ft->n_valid; i++)
1194     {
1195       const struct freq *f = &ft->valid[i];
1196       if (chart_includes_value (frq->hist, var, &f->value))
1197         {
1198           x_min = MIN (x_min, f->value.f);
1199           x_max = MAX (x_max, f->value.f);
1200           valid_freq += f->count;
1201         }
1202     }
1203
1204
1205   iqr = calculate_iqr (frq);
1206
1207   if (iqr > 0)
1208     /* Freedman-Diaconis' choice of bin width. */
1209     bin_width = 2 * iqr / pow (valid_freq, 1.0 / 3.0);
1210
1211   else
1212     /* Sturges Rule */
1213     bin_width = (x_max - x_min) / (1 + log2 (valid_freq));
1214
1215   histogram = histogram_create (bin_width, x_min, x_max);
1216
1217   if ( histogram == NULL)
1218     return NULL;
1219
1220   for (i = 0; i < ft->n_valid; i++)
1221     {
1222       const struct freq *f = &ft->valid[i];
1223       if (chart_includes_value (frq->hist, var, &f->value))
1224         histogram_add (histogram, f->value.f, f->count);
1225     }
1226
1227   return histogram;
1228 }
1229
1230 static int
1231 add_slice (const struct frq_chart *pie, const struct freq *freq,
1232            const struct variable *var, struct slice *slice)
1233 {
1234   if (chart_includes_value (pie, var, &freq->value))
1235     {
1236       ds_init_empty (&slice->label);
1237       var_append_value_name (var, &freq->value, &slice->label);
1238       slice->magnitude = freq->count;
1239       return 1;
1240     }
1241   else
1242     return 0;
1243 }
1244
1245 /* Allocate an array of slices and fill them from the data in frq_tab
1246    n_slices will contain the number of slices allocated.
1247    The caller is responsible for freeing slices
1248 */
1249 static struct slice *
1250 freq_tab_to_slice_array(const struct frq_chart *pie,
1251                         const struct freq_tab *frq_tab,
1252                         const struct variable *var,
1253                         int *n_slicesp)
1254 {
1255   struct slice *slices;
1256   int n_slices;
1257   int i;
1258
1259   slices = xnmalloc (frq_tab->n_valid + frq_tab->n_missing, sizeof *slices);
1260   n_slices = 0;
1261
1262   for (i = 0; i < frq_tab->n_valid; i++)
1263     n_slices += add_slice (pie, &frq_tab->valid[i], var, &slices[n_slices]);
1264   for (i = 0; i < frq_tab->n_missing; i++)
1265     n_slices += add_slice (pie, &frq_tab->missing[i], var, &slices[n_slices]);
1266
1267   *n_slicesp = n_slices;
1268   return slices;
1269 }
1270
1271
1272 static void
1273 do_piechart(const struct frq_chart *pie, const struct variable *var,
1274             const struct freq_tab *frq_tab)
1275 {
1276   struct slice *slices;
1277   int n_slices, i;
1278
1279   slices = freq_tab_to_slice_array (pie, frq_tab, var, &n_slices);
1280
1281   if (n_slices < 2)
1282     msg (SW, _("Omitting pie chart for %s, which has only %d unique values."),
1283          var_get_name (var), n_slices);
1284   else if (n_slices > 50)
1285     msg (SW, _("Omitting pie chart for %s, which has over 50 unique values."),
1286          var_get_name (var));
1287   else
1288     chart_item_submit (piechart_create (var_to_string(var), slices, n_slices));
1289
1290   for (i = 0; i < n_slices; i++)
1291     ds_destroy (&slices[i].label);
1292   free (slices);
1293 }
1294
1295 /* Calculates all the pertinent statistics for VF, putting them in array
1296    D[]. */
1297 static void
1298 calc_stats (const struct var_freqs *vf, double d[FRQ_ST_count])
1299 {
1300   const struct freq_tab *ft = &vf->tab;
1301   double W = ft->valid_cases;
1302   const struct freq *f;
1303   struct moments *m;
1304   int most_often = -1;
1305   double X_mode = SYSMIS;
1306
1307   /* Calculate the mode. */
1308   for (f = ft->valid; f < ft->missing; f++)
1309     {
1310       if (most_often < f->count)
1311         {
1312           most_often = f->count;
1313           X_mode = f->value.f;
1314         }
1315       else if (most_often == f->count)
1316         {
1317           /* A duplicate mode is undefined.
1318              FIXME: keep track of *all* the modes. */
1319           X_mode = SYSMIS;
1320         }
1321     }
1322
1323   /* Calculate moments. */
1324   m = moments_create (MOMENT_KURTOSIS);
1325   for (f = ft->valid; f < ft->missing; f++)
1326     moments_pass_one (m, f->value.f, f->count);
1327   for (f = ft->valid; f < ft->missing; f++)
1328     moments_pass_two (m, f->value.f, f->count);
1329   moments_calculate (m, NULL, &d[FRQ_ST_MEAN], &d[FRQ_ST_VARIANCE],
1330                      &d[FRQ_ST_SKEWNESS], &d[FRQ_ST_KURTOSIS]);
1331   moments_destroy (m);
1332
1333   /* Formulae below are taken from _SPSS Statistical Algorithms_. */
1334   d[FRQ_ST_MINIMUM] = ft->valid[0].value.f;
1335   d[FRQ_ST_MAXIMUM] = ft->valid[ft->n_valid - 1].value.f;
1336   d[FRQ_ST_MODE] = X_mode;
1337   d[FRQ_ST_RANGE] = d[FRQ_ST_MAXIMUM] - d[FRQ_ST_MINIMUM];
1338   d[FRQ_ST_SUM] = d[FRQ_ST_MEAN] * W;
1339   d[FRQ_ST_STDDEV] = sqrt (d[FRQ_ST_VARIANCE]);
1340   d[FRQ_ST_SEMEAN] = d[FRQ_ST_STDDEV] / sqrt (W);
1341   d[FRQ_ST_SESKEWNESS] = calc_seskew (W);
1342   d[FRQ_ST_SEKURTOSIS] = calc_sekurt (W);
1343 }
1344
1345 /* Displays a table of all the statistics requested for variable V. */
1346 static void
1347 dump_statistics (const struct frq_proc *frq, const struct var_freqs *vf,
1348                  const struct variable *wv)
1349 {
1350   const struct fmt_spec *wfmt = wv ? var_get_print_format (wv) : &F_8_0;
1351   const struct freq_tab *ft = &vf->tab;
1352   double stat_value[FRQ_ST_count];
1353   struct tab_table *t;
1354   int i, r = 2; /* N missing and N valid are always dumped */
1355
1356   if (var_is_alpha (vf->var))
1357     return;
1358
1359   calc_stats (vf, stat_value);
1360
1361   t = tab_create (3, ((frq->stats & BIT_INDEX (FRQ_ST_MEDIAN)) ? frq->n_stats - 1 : frq->n_stats)
1362                                 + frq->n_show_percentiles + 2);
1363
1364   tab_set_format (t, RC_WEIGHT, wfmt);
1365   tab_box (t, TAL_1, TAL_1, -1, -1 , 0 , 0 , 2, tab_nr(t) - 1) ;
1366
1367   tab_vline (t, TAL_1 , 2, 0, tab_nr(t) - 1);
1368   tab_vline (t, TAL_GAP , 1, 0, tab_nr(t) - 1 ) ;
1369
1370   for (i = 0; i < FRQ_ST_count; i++)
1371     {
1372       if (FRQ_ST_MEDIAN == i)
1373         continue;
1374
1375       if (frq->stats & BIT_INDEX (i))
1376       {
1377         tab_text (t, 0, r, TAB_LEFT | TAT_TITLE,
1378                       gettext (st_name[i]));
1379
1380         if (vf->tab.n_valid <= 0 && r >= 2)
1381           tab_text (t, 2, r, 0,   ".");
1382         else
1383           tab_double (t, 2, r, TAB_NONE, stat_value[i], NULL, RC_OTHER);
1384         r++;
1385       }
1386     }
1387
1388   tab_text (t, 0, 0, TAB_LEFT | TAT_TITLE, _("N"));
1389   tab_text (t, 1, 0, TAB_LEFT | TAT_TITLE, _("Valid"));
1390   tab_text (t, 1, 1, TAB_LEFT | TAT_TITLE, _("Missing"));
1391
1392   tab_double (t, 2, 0, TAB_NONE, ft->valid_cases, NULL, RC_WEIGHT);
1393   tab_double (t, 2, 1, TAB_NONE, ft->total_cases - ft->valid_cases, NULL, RC_WEIGHT);
1394
1395   for (i = 0; i < frq->n_percentiles; i++)
1396     {
1397       const struct percentile *pc = &frq->percentiles[i];
1398
1399       if (!pc->show)
1400         continue;
1401
1402       if ( i == 0 )
1403         {
1404           tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, _("Percentiles"));
1405         }
1406
1407       if (vf->tab.n_valid <= 0)
1408         {
1409           tab_text (t, 2, r, 0,   ".");
1410           ++r;
1411           continue;
1412         }
1413
1414       if (pc->p == 0.5)
1415         tab_text (t, 1, r, TAB_LEFT, _("50 (Median)"));
1416       else
1417         tab_double (t, 1, r, TAB_LEFT, pc->p * 100, NULL, RC_INTEGER);
1418       tab_double (t, 2, r, TAB_NONE, pc->value,
1419                   var_get_print_format (vf->var), RC_OTHER);
1420
1421       ++r;
1422     }
1423
1424   tab_title (t, "%s", var_to_string (vf->var));
1425
1426   tab_submit (t);
1427 }
1428