1f8290cf2c696d418b28d3c92a039dfecbd800a7
[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_headers (t, 0, 0, 1, 0);
290
291   for (x = 0; x < 6; x++)
292     tab_text (t, x, 0, TAB_CENTER | TAT_TITLE, gettext (headings[x]));
293
294   r = 1;
295   for (f = ft->valid; f < ft->missing; f++)
296     {
297       const char *label;
298       double percent, valid_percent;
299
300       cum_freq += f->count;
301
302       percent = f->count / ft->total_cases * 100.0;
303       valid_percent = f->count / ft->valid_cases * 100.0;
304       cum_total += valid_percent;
305
306       label = var_lookup_value_label (vf->var, &f->value);
307       if (label != NULL)
308         tab_text (t, 0, r, TAB_LEFT, label);
309
310       tab_value (t, 1, r, TAB_NONE, &f->value, vf->var, NULL);
311       tab_double (t, 2, r, TAB_NONE, f->count, wfmt);
312       tab_double (t, 3, r, TAB_NONE, percent, NULL);
313       tab_double (t, 4, r, TAB_NONE, valid_percent, NULL);
314       tab_double (t, 5, r, TAB_NONE, cum_total, NULL);
315       r++;
316     }
317   for (; f < &ft->valid[n_categories]; f++)
318     {
319       const char *label;
320
321       cum_freq += f->count;
322
323       label = var_lookup_value_label (vf->var, &f->value);
324       if (label != NULL)
325         tab_text (t, 0, r, TAB_LEFT, label);
326
327       tab_value (t, 1, r, TAB_NONE, &f->value, vf->var, NULL);
328       tab_double (t, 2, r, TAB_NONE, f->count, wfmt);
329       tab_double (t, 3, r, TAB_NONE,
330                      f->count / ft->total_cases * 100.0, NULL);
331       tab_text (t, 4, r, TAB_NONE, _("Missing"));
332       r++;
333     }
334
335   tab_box (t, TAL_1, TAL_1, -1, TAL_1, 0, 0, 5, r);
336   tab_hline (t, TAL_2, 0, 5, 1);
337   tab_hline (t, TAL_2, 0, 5, r);
338   tab_joint_text (t, 0, r, 1, r, TAB_RIGHT | TAT_TITLE, _("Total"));
339   tab_vline (t, TAL_0, 1, r, r);
340   tab_double (t, 2, r, TAB_NONE, cum_freq, wfmt);
341   tab_fixed (t, 3, r, TAB_NONE, 100.0, 5, 1);
342   tab_fixed (t, 4, r, TAB_NONE, 100.0, 5, 1);
343
344   tab_title (t, "%s", var_to_string (vf->var));
345   tab_submit (t);
346 }
347 \f
348 /* Statistical display. */
349
350 static double
351 calc_percentile (double p, double valid_cases, double x1, double x2)
352 {
353   double s, dummy;
354
355   s = (settings_get_algorithm () != COMPATIBLE
356        ? modf ((valid_cases - 1) * p, &dummy)
357        : modf ((valid_cases + 1) * p - 1, &dummy));
358
359   return x1 + (x2 - x1) * s;
360 }
361
362 /* Calculates all of the percentiles for VF within FRQ. */
363 static void
364 calc_percentiles (const struct frq_proc *frq, const struct var_freqs *vf)
365 {
366   const struct freq_tab *ft = &vf->tab;
367   double W = ft->valid_cases;
368   const struct freq *f;
369   int percentile_idx;
370   double rank;
371
372   assert (ft->n_valid > 0);
373
374   rank = 0;
375   percentile_idx = 0;
376   for (f = ft->valid; f < ft->missing; f++)
377     {
378       rank += f->count;
379       for (; percentile_idx < frq->n_percentiles; percentile_idx++)
380         {
381           struct percentile *pc = &frq->percentiles[percentile_idx];
382           double tp;
383
384           tp = (settings_get_algorithm () == ENHANCED
385                 ? (W - 1) * pc->p
386                 : (W + 1) * pc->p - 1);
387
388           if (rank <= tp)
389             break;
390
391           if (tp + 1 < rank || f + 1 >= ft->missing)
392             pc->value = f->value.f;
393           else
394             pc->value = calc_percentile (pc->p, W, f->value.f, f[1].value.f);
395         }
396     }
397   for (; percentile_idx < frq->n_percentiles; percentile_idx++)
398     {
399       struct percentile *pc = &frq->percentiles[percentile_idx];
400       pc->value = ft->valid[ft->n_valid - 1].value.f;
401     }
402 }
403
404 /* Returns true iff the value in struct freq F is non-missing
405    for variable V. */
406 static bool
407 not_missing (const void *f_, const void *v_)
408 {
409   const struct freq *f = f_;
410   const struct variable *v = v_;
411
412   return !var_is_value_missing (v, &f->value, MV_ANY);
413 }
414
415
416 /* Summarizes the frequency table data for variable V. */
417 static void
418 postprocess_freq_tab (const struct frq_proc *frq, struct var_freqs *vf)
419 {
420   struct freq_tab *ft = &vf->tab;
421   struct freq_compare_aux aux;
422   size_t count;
423   struct freq *freqs, *f;
424   size_t i;
425
426   /* Extract data from hash table. */
427   count = hmap_count (&ft->data);
428   freqs = freq_hmap_extract (&ft->data);
429
430   /* Put data into ft. */
431   ft->valid = freqs;
432   ft->n_valid = partition (freqs, count, sizeof *freqs, not_missing, vf->var);
433   ft->missing = freqs + ft->n_valid;
434   ft->n_missing = count - ft->n_valid;
435
436   /* Sort data. */
437   aux.by_freq = frq->sort == FRQ_AFREQ || frq->sort == FRQ_DFREQ;
438   aux.ascending_freq = frq->sort != FRQ_DFREQ;
439   aux.width = vf->width;
440   aux.ascending_value = frq->sort != FRQ_DVALUE;
441   sort (ft->valid, ft->n_valid, sizeof *ft->valid, compare_freq, &aux);
442   sort (ft->missing, ft->n_missing, sizeof *ft->missing, compare_freq, &aux);
443
444   /* Summary statistics. */
445   ft->valid_cases = 0.0;
446   for(i = 0 ;  i < ft->n_valid ; ++i )
447     {
448       f = &ft->valid[i];
449       ft->valid_cases += f->count;
450
451     }
452
453   ft->total_cases = ft->valid_cases ;
454   for(i = 0 ;  i < ft->n_missing ; ++i )
455     {
456       f = &ft->missing[i];
457       ft->total_cases += f->count;
458     }
459
460 }
461
462 /* Frees the frequency table for variable V. */
463 static void
464 cleanup_freq_tab (struct var_freqs *vf)
465 {
466   free (vf->tab.valid);
467   freq_hmap_destroy (&vf->tab.data, vf->width);
468 }
469
470 /* Add data from case C to the frequency table. */
471 static void
472 calc (struct frq_proc *frq, const struct ccase *c, const struct dataset *ds)
473 {
474   double weight = dict_get_case_weight (dataset_dict (ds), c, NULL);
475   size_t i;
476
477   for (i = 0; i < frq->n_vars; i++)
478     {
479       struct var_freqs *vf = &frq->vars[i];
480       const union value *value = case_data (c, vf->var);
481       size_t hash = value_hash (value, vf->width, 0);
482       struct freq *f;
483
484       f = freq_hmap_search (&vf->tab.data, value, vf->width, hash);
485       if (f == NULL)
486         f = freq_hmap_insert (&vf->tab.data, value, vf->width, hash);
487
488       f->count += weight;
489     }
490 }
491
492 /* Prepares each variable that is the target of FREQUENCIES by setting
493    up its hash table. */
494 static void
495 precalc (struct frq_proc *frq, struct casereader *input, struct dataset *ds)
496 {
497   struct ccase *c;
498   size_t i;
499
500   c = casereader_peek (input, 0);
501   if (c != NULL)
502     {
503       output_split_file_values (ds, c);
504       case_unref (c);
505     }
506
507   for (i = 0; i < frq->n_vars; i++)
508     hmap_init (&frq->vars[i].tab.data);
509 }
510
511 /* Finishes up with the variables after frequencies have been
512    calculated.  Displays statistics, percentiles, ... */
513 static void
514 postcalc (struct frq_proc *frq, const struct dataset *ds)
515 {
516   const struct dictionary *dict = dataset_dict (ds);
517   const struct variable *wv = dict_get_weight (dict);
518   size_t i;
519
520   for (i = 0; i < frq->n_vars; i++)
521     {
522       struct var_freqs *vf = &frq->vars[i];
523
524       postprocess_freq_tab (frq, vf);
525
526       /* Frequencies tables. */
527       if (vf->tab.n_valid + vf->tab.n_missing <= frq->max_categories)
528         dump_freq_table (vf, wv);
529
530       calc_percentiles (frq, vf);
531
532       /* Statistics. */
533       if (frq->n_stats)
534         dump_statistics (frq, vf, wv);
535
536       if (frq->hist && var_is_numeric (vf->var) && vf->tab.n_valid > 0)
537         {
538           double d[FRQ_ST_count];
539           struct histogram *histogram;
540
541           calc_stats (vf, d);
542
543           histogram = freq_tab_to_hist (frq, &vf->tab, vf->var);
544
545           if ( histogram)
546             {
547               chart_item_submit (histogram_chart_create (
548                                histogram->gsl_hist, var_to_string(vf->var),
549                                vf->tab.valid_cases,
550                                d[FRQ_ST_MEAN],
551                                d[FRQ_ST_STDDEV],
552                                frq->hist->draw_normal));
553
554               statistic_destroy (&histogram->parent);
555             }
556         }
557
558       if (frq->pie)
559         do_piechart(frq->pie, vf->var, &vf->tab);
560
561       cleanup_freq_tab (vf);
562     }
563 }
564
565 int
566 cmd_frequencies (struct lexer *lexer, struct dataset *ds)
567 {
568   int i;
569   struct frq_proc frq;
570   const struct variable **vars;
571
572   bool sbc_barchart = false;
573   bool sbc_piechart = false;
574   bool sbc_histogram = false;
575
576   double pie_min = -DBL_MAX;
577   double pie_max = DBL_MAX;
578   bool pie_missing = false;
579
580   double hi_min = -DBL_MAX;
581   double hi_max = DBL_MAX;
582   int hi_scale = FRQ_FREQ;
583   int hi_freq = INT_MIN;
584   int hi_pcnt = INT_MIN;
585   int hi_norm = FRQ_NONORMAL;
586
587   frq.pool = pool_create ();
588   frq.sort = FRQ_AVALUE;
589
590   frq.vars = NULL;
591   frq.n_vars = 0;
592   
593   frq.stats = BIT_INDEX (FRQ_ST_MEAN) 
594     | BIT_INDEX (FRQ_ST_STDDEV) 
595     | BIT_INDEX (FRQ_ST_MINIMUM)
596     | BIT_INDEX (FRQ_ST_MAXIMUM);
597
598   frq.n_stats = 4;
599
600   frq.max_categories = INT_MAX;
601
602   frq.percentiles = NULL;
603   frq.n_percentiles = 0;
604   frq.n_show_percentiles = 0;
605
606   frq.hist = NULL;
607   frq.pie = NULL;
608
609
610   /* Accept an optional, completely pointless "/VARIABLES=" */
611   lex_match (lexer, T_SLASH);
612   if (lex_match_id  (lexer, "VARIABLES"))
613     {
614       if (! lex_force_match (lexer, T_EQUALS) )
615         goto error;
616     }
617
618   if (!parse_variables_const (lexer, dataset_dict (ds),
619                               &vars,
620                               &frq.n_vars,
621                               PV_NO_DUPLICATE))
622     goto error;
623
624   frq.vars = xzalloc (frq.n_vars * sizeof (*frq.vars));
625   for (i = 0; i < frq.n_vars; ++i)
626     {
627       frq.vars[i].var = vars[i];
628     }
629
630   while (lex_token (lexer) != T_ENDCMD)
631     {
632       lex_match (lexer, T_SLASH);
633
634       if (lex_match_id (lexer, "STATISTICS"))
635         {
636           lex_match (lexer, T_EQUALS);
637
638           frq.stats = 0;
639           frq.n_stats = 0;
640
641           while (lex_token (lexer) != T_ENDCMD
642                  && lex_token (lexer) != T_SLASH)
643             {
644               if (lex_match_id (lexer, "DEFAULT"))
645                 {
646                   frq.stats = BIT_INDEX (FRQ_ST_MEAN) 
647                     | BIT_INDEX (FRQ_ST_STDDEV) 
648                     | BIT_INDEX (FRQ_ST_MINIMUM)
649                     | BIT_INDEX (FRQ_ST_MAXIMUM);
650
651                   frq.n_stats = 4;
652                 }
653               else if (lex_match_id (lexer, "MEAN"))
654                 {
655                   frq.stats |= BIT_INDEX (FRQ_ST_MEAN);
656                   frq.n_stats++;
657                 }
658               else if (lex_match_id (lexer, "SEMEAN"))
659                 {
660                   frq.stats |= BIT_INDEX (FRQ_ST_SEMEAN);
661                   frq.n_stats++;
662                 }
663               else if (lex_match_id (lexer, "MEDIAN"))
664                 {
665                   frq.stats |= BIT_INDEX (FRQ_ST_MEDIAN);
666                   frq.n_stats++;
667                 }
668               else if (lex_match_id (lexer, "MODE"))
669                 {
670                   frq.stats |= BIT_INDEX (FRQ_ST_MODE);
671                   frq.n_stats++;
672                 }
673               else if (lex_match_id (lexer, "STDDEV"))
674                 {
675                   frq.stats |= BIT_INDEX (FRQ_ST_STDDEV);
676                   frq.n_stats++;
677                 }
678               else if (lex_match_id (lexer, "VARIANCE"))
679                 {
680                   frq.stats |= BIT_INDEX (FRQ_ST_MEAN);
681                   frq.n_stats++;
682                 }
683               else if (lex_match_id (lexer, "KURTOSIS"))
684                 {
685                   frq.stats |= BIT_INDEX (FRQ_ST_KURTOSIS);
686                   frq.n_stats++;
687                 }
688               else if (lex_match_id (lexer, "SKEWNESS"))
689                 {
690                   frq.stats |= BIT_INDEX (FRQ_ST_SKEWNESS);
691                   frq.n_stats++;
692                 }
693               else if (lex_match_id (lexer, "RANGE"))
694                 {
695                   frq.stats |= BIT_INDEX (FRQ_ST_RANGE);
696                   frq.n_stats++;
697                 }
698               else if (lex_match_id (lexer, "MINIMUM"))
699                 {
700                   frq.stats |= BIT_INDEX (FRQ_ST_MINIMUM);
701                   frq.n_stats++;
702                 }
703               else if (lex_match_id (lexer, "MAXIMUM"))
704                 {
705                   frq.stats |= BIT_INDEX (FRQ_ST_MAXIMUM);
706                   frq.n_stats++;
707                 }
708               else if (lex_match_id (lexer, "SUM"))
709                 {
710                   frq.stats |= BIT_INDEX (FRQ_ST_SUM);
711                   frq.n_stats++;
712                 }
713               else if (lex_match_id (lexer, "SESKEWNESS"))
714                 {
715                   frq.stats |= BIT_INDEX (FRQ_ST_SESKEWNESS);
716                   frq.n_stats++;
717                 }
718               else if (lex_match_id (lexer, "SEKURTOSIS"))
719                 {
720                   frq.stats |= BIT_INDEX (FRQ_ST_SEKURTOSIS);
721                   frq.n_stats++;
722                 }
723               else if (lex_match_id (lexer, "NONE"))
724                 {
725                   frq.stats = 0;
726                   frq.n_stats = 0;
727                 }
728               else if (lex_match (lexer, T_ALL))
729                 {
730                   frq.stats = ~0;
731                   frq.n_stats = FRQ_ST_count;
732                 }
733               else
734                 {
735                   lex_error (lexer, NULL);
736                   goto error;
737                 }
738             }
739         }
740       else if (lex_match_id (lexer, "PERCENTILES"))
741         {
742           lex_match (lexer, T_EQUALS);
743           while (lex_token (lexer) != T_ENDCMD
744                  && lex_token (lexer) != T_SLASH)
745             {
746               if (lex_force_num (lexer))
747                 {
748                   frq.percentiles =
749                     xrealloc (frq.percentiles, 
750                               (frq.n_percentiles + 1)
751                               * sizeof (*frq.percentiles));
752                   frq.percentiles[frq.n_percentiles].p = lex_number (lexer)  / 100.0;
753                   frq.percentiles[frq.n_percentiles].show = true;
754                   lex_get (lexer);
755                   frq.n_percentiles++;
756                   frq.n_show_percentiles++;
757                 }
758               else
759                 {
760                   lex_error (lexer, NULL);
761                   goto error;
762                 }
763             }
764         }
765       else if (lex_match_id (lexer, "FORMAT"))
766         {
767           lex_match (lexer, T_EQUALS);
768           while (lex_token (lexer) != T_ENDCMD
769                  && lex_token (lexer) != T_SLASH)
770             {
771               if (lex_match_id (lexer, "TABLE"))
772                 {
773                   
774                 }
775               else if (lex_match_id (lexer, "NOTABLE"))
776                 {
777                   frq.max_categories = 0;
778                 }
779               else if (lex_match_id (lexer, "AVALUE"))
780                 {
781                   frq.sort = FRQ_AVALUE;
782                 }
783               else if (lex_match_id (lexer, "DVALUE"))
784                 {
785                   frq.sort = FRQ_DVALUE;
786                 }
787               else if (lex_match_id (lexer, "AFREQ"))
788                 {
789                   frq.sort = FRQ_AFREQ;
790                 }
791               else if (lex_match_id (lexer, "DFREQ"))
792                 {
793                   frq.sort = FRQ_DFREQ;
794                 }
795               else
796                 {
797                   lex_error (lexer, NULL);
798                   goto error;
799                 }
800             }
801         }
802       else if (lex_match_id (lexer, "NTILES"))
803         {
804           lex_match (lexer, T_EQUALS);
805
806           if (lex_force_int (lexer))
807             {
808               int i;
809               int n = lex_integer (lexer);
810               lex_get (lexer);
811               for (i = 0; i < n + 1; ++i)
812                 {
813                   frq.percentiles =
814                     xrealloc (frq.percentiles, 
815                               (frq.n_percentiles + 1)
816                               * sizeof (*frq.percentiles));
817                   frq.percentiles[frq.n_percentiles].p =
818                     i / (double) n ;
819                   frq.percentiles[frq.n_percentiles].show = true;
820
821                   frq.n_percentiles++;
822                   frq.n_show_percentiles++;
823                 }
824             }
825           else
826             {
827               lex_error (lexer, NULL);
828               goto error;
829             }
830         }
831       else if (lex_match_id (lexer, "ALGORITHM"))
832         {
833           lex_match (lexer, T_EQUALS);
834
835           if (lex_match_id (lexer, "COMPATIBLE"))
836             {
837               settings_set_cmd_algorithm (COMPATIBLE);
838             }
839           else if (lex_match_id (lexer, "ENHANCED"))
840             {
841               settings_set_cmd_algorithm (ENHANCED);
842             }
843           else
844             {
845               lex_error (lexer, NULL);
846               goto error;
847             }
848         }
849       else if (lex_match_id (lexer, "HISTOGRAM"))
850         {
851           lex_match (lexer, T_EQUALS);
852           sbc_histogram = true;
853
854           while (lex_token (lexer) != T_ENDCMD
855                  && lex_token (lexer) != T_SLASH)
856             {
857               if (lex_match_id (lexer, "NORMAL"))
858                 {
859                   hi_norm = FRQ_NORMAL;
860                 }
861               else if (lex_match_id (lexer, "NONORMAL"))
862                 {
863                   hi_norm = FRQ_NONORMAL;
864                 }
865               else if (lex_match_id (lexer, "FREQ"))
866                 {
867                   hi_scale = FRQ_FREQ;
868                   if (lex_match (lexer, T_LPAREN))
869                     {
870                       if (lex_force_int (lexer))
871                         {
872                           hi_freq = lex_integer (lexer);
873                           if (hi_freq <= 0)
874                             {
875                               lex_error (lexer, _("Histogram frequency must be greater than zero."));
876                             }
877                           lex_get (lexer);
878                           lex_force_match (lexer, T_RPAREN);
879                         }
880                     }
881                 }
882               else if (lex_match_id (lexer, "PERCENT"))
883                 {
884                   hi_scale = FRQ_PERCENT;
885                   if (lex_match (lexer, T_LPAREN))
886                     {
887                       if (lex_force_int (lexer))
888                         {
889                           hi_pcnt = lex_integer (lexer);
890                           if (hi_pcnt <= 0)
891                             {
892                               lex_error (lexer, _("Histogram percentaage must be greater than zero."));
893                             }
894                           lex_get (lexer);
895                           lex_force_match (lexer, T_RPAREN);
896                         }
897                     }
898                 }
899               else if (lex_match_id (lexer, "MINIMUM"))
900                 {
901                   lex_force_match (lexer, T_LPAREN);
902                   if (lex_force_num (lexer))
903                     {
904                       hi_min = lex_number (lexer);
905                       lex_get (lexer);
906                     }
907                   lex_force_match (lexer, T_RPAREN);
908                 }
909               else if (lex_match_id (lexer, "MAXIMUM"))
910                 {
911                   lex_force_match (lexer, T_LPAREN);
912                   if (lex_force_num (lexer))
913                     {
914                       hi_max = lex_number (lexer);
915                       lex_get (lexer);
916                     }
917                   lex_force_match (lexer, T_RPAREN);
918                 }
919               else
920                 {
921                   lex_error (lexer, NULL);
922                   goto error;
923                 }
924             }
925         }
926       else if (lex_match_id (lexer, "PIECHART"))
927         {
928           lex_match (lexer, T_EQUALS);
929           while (lex_token (lexer) != T_ENDCMD
930                  && lex_token (lexer) != T_SLASH)
931             {
932               if (lex_match_id (lexer, "MINIMUM"))
933                 {
934                   lex_force_match (lexer, T_LPAREN);
935                   if (lex_force_num (lexer))
936                     {
937                       pie_min = lex_number (lexer);
938                       lex_get (lexer);
939                     }
940                   lex_force_match (lexer, T_RPAREN);
941                 }
942               else if (lex_match_id (lexer, "MAXIMUM"))
943                 {
944                   lex_force_match (lexer, T_LPAREN);
945                   if (lex_force_num (lexer))
946                     {
947                       pie_max = lex_number (lexer);
948                       lex_get (lexer);
949                     }
950                   lex_force_match (lexer, T_RPAREN);
951                 }
952               else if (lex_match_id (lexer, "MISSING"))
953                 {
954                   pie_missing = true;
955                 }
956               else if (lex_match_id (lexer, "NOMISSING"))
957                 {
958                   pie_missing = false;
959                 }
960               else
961                 {
962                   lex_error (lexer, NULL);
963                   goto error;
964                 }
965             }
966           sbc_piechart = true;
967         }
968       else if (lex_match_id (lexer, "MISSING"))
969         {
970           lex_match (lexer, T_EQUALS);
971
972           while (lex_token (lexer) != T_ENDCMD
973                  && lex_token (lexer) != T_SLASH)
974             {
975               if (lex_match_id (lexer, "EXCLUDE"))
976                 {
977                 }
978               else if (lex_match_id (lexer, "INCLUDE"))
979                 {
980                 }
981               else
982                 {
983                   lex_error (lexer, NULL);
984                   goto error;
985                 }
986             }
987         }
988       else
989         {
990           lex_error (lexer, NULL);
991           goto error;
992         }
993     }
994
995   if (frq.stats & FRQ_ST_MEDIAN)
996     {
997         frq.percentiles =
998           xrealloc (frq.percentiles, 
999                     (frq.n_percentiles + 1)
1000                     * sizeof (*frq.percentiles));
1001         
1002         frq.percentiles[frq.n_percentiles].p = 0.50;
1003         frq.percentiles[frq.n_percentiles].show = true;
1004
1005         frq.n_percentiles++;
1006     }
1007
1008
1009 /* Figure out which charts the user requested.  */
1010
1011   {
1012     if (sbc_barchart)
1013       msg (SW, _("Bar charts are not implemented."));
1014
1015     if (sbc_histogram)
1016       {
1017         struct frq_chart *hist;
1018
1019         hist = frq.hist = xmalloc (sizeof *frq.hist);
1020         hist->x_min = hi_min;
1021         hist->x_max = hi_max;
1022         hist->y_scale = hi_scale;
1023         hist->y_max = hi_scale == FRQ_FREQ ? hi_freq : hi_pcnt;
1024         hist->draw_normal = hi_norm != FRQ_NONORMAL;
1025         hist->include_missing = false;
1026
1027         if (hist->x_min != SYSMIS && hist->x_max != SYSMIS
1028             && hist->x_min >= hist->x_max)
1029           {
1030             msg (SE, _("%s for histogram must be greater than or equal to %s, "
1031                        "but %s was specified as %.15g and %s as %.15g.  "
1032                        "%s and %s will be ignored."),
1033                  "MAX", "MIN", 
1034                  "MIN", hist->x_min, 
1035                  "MAX", hist->x_max,
1036                  "MIN", "MAX");
1037             hist->x_min = hist->x_max = SYSMIS;
1038           }
1039
1040         frq.percentiles =
1041           xrealloc (frq.percentiles, 
1042                     (frq.n_percentiles + 2)
1043                     * sizeof (*frq.percentiles));
1044         
1045         frq.percentiles[frq.n_percentiles].p = 0.25;
1046         frq.percentiles[frq.n_percentiles].show = false;
1047
1048         frq.percentiles[frq.n_percentiles + 1].p = 0.75;
1049         frq.percentiles[frq.n_percentiles + 1].show = false;
1050         
1051         frq.n_percentiles+=2;
1052       }
1053
1054     if (sbc_piechart)
1055       {
1056         struct frq_chart *pie;
1057
1058         pie = frq.pie = xmalloc (sizeof *frq.pie);
1059         pie->x_min = pie_min;
1060         pie->x_max = pie_max;
1061         pie->include_missing = pie_missing;
1062
1063         if (pie->x_min != SYSMIS && pie->x_max != SYSMIS
1064             && pie->x_min >= pie->x_max)
1065           {
1066             msg (SE, _("%s for pie chart must be greater than or equal to %s, "
1067                        "but %s was specified as %.15g and %s as %.15g.  "
1068                        "%s and %s will be ignored."), 
1069                  "MAX", "MIN", 
1070                  "MIN", pie->x_min,
1071                  "MAX", pie->x_max,
1072                  "MIN", "MAX");
1073             pie->x_min = pie->x_max = SYSMIS;
1074           }
1075       }
1076   }
1077
1078   {
1079     int i,o;
1080     double previous_p = -1;
1081     qsort (frq.percentiles, frq.n_percentiles,
1082            sizeof (*frq.percentiles), 
1083            ptile_3way);
1084
1085     frq.n_show_percentiles = 0;
1086     for (i = o = 0; i < frq.n_percentiles; ++i)
1087       {
1088         frq.percentiles[o].p = frq.percentiles[i].p;
1089
1090         if (frq.percentiles[i].show)
1091           frq.percentiles[o].show = true;
1092
1093         if (frq.percentiles[i].p != previous_p)
1094           {
1095             if (frq.percentiles[i].show)
1096               frq.n_show_percentiles++;
1097
1098             o++;
1099           }
1100
1101         previous_p = frq.percentiles[i].p;
1102       }
1103
1104     frq.n_percentiles = o;
1105   }
1106
1107   {
1108     struct casegrouper *grouper;
1109     struct casereader *group;
1110     bool ok;
1111
1112     grouper = casegrouper_create_splits (proc_open (ds), dataset_dict (ds));
1113     while (casegrouper_get_next_group (grouper, &group))
1114       {
1115         struct ccase *c;
1116         precalc (&frq, group, ds);
1117         for (; (c = casereader_read (group)) != NULL; case_unref (c))
1118           calc (&frq, c, ds);
1119         postcalc (&frq, ds);
1120       }
1121     ok = casegrouper_destroy (grouper);
1122     ok = proc_commit (ds) && ok;
1123   }
1124
1125
1126   return CMD_SUCCESS;
1127
1128  error:
1129
1130   return CMD_FAILURE;
1131 }
1132
1133 static double
1134 calculate_iqr (const struct frq_proc *frq)
1135 {
1136   double q1 = SYSMIS;
1137   double q3 = SYSMIS;
1138   int i;
1139
1140   /* This cannot work unless the 25th and 75th percentile are calculated */
1141   assert (frq->n_percentiles >= 2);
1142   for (i = 0; i < frq->n_percentiles; i++)
1143     {
1144       struct percentile *pc = &frq->percentiles[i];
1145
1146       if (fabs (0.25 - pc->p) < DBL_EPSILON)
1147         q1 = pc->value;
1148       else if (fabs (0.75 - pc->p) < DBL_EPSILON)
1149         q3 = pc->value;
1150     }
1151
1152   return q1 == SYSMIS || q3 == SYSMIS ? SYSMIS : q3 - q1;
1153 }
1154
1155 static bool
1156 chart_includes_value (const struct frq_chart *chart,
1157                       const struct variable *var,
1158                       const union value *value)
1159 {
1160   if (!chart->include_missing && var_is_value_missing (var, value, MV_ANY))
1161     return false;
1162
1163   if (var_is_numeric (var)
1164       && ((chart->x_min != SYSMIS && value->f < chart->x_min)
1165           || (chart->x_max != SYSMIS && value->f > chart->x_max)))
1166     return false;
1167
1168   return true;
1169 }
1170
1171 /* Create a gsl_histogram from a freq_tab */
1172 static struct histogram *
1173 freq_tab_to_hist (const struct frq_proc *frq, const struct freq_tab *ft,
1174                   const struct variable *var)
1175 {
1176   double x_min, x_max, valid_freq;
1177   int i;
1178   double bin_width;
1179   struct histogram *histogram;
1180   double iqr;
1181
1182   /* Find out the extremes of the x value, within the range to be included in
1183      the histogram, and sum the total frequency of those values. */
1184   x_min = DBL_MAX;
1185   x_max = -DBL_MAX;
1186   valid_freq = 0;
1187   for (i = 0; i < ft->n_valid; i++)
1188     {
1189       const struct freq *f = &ft->valid[i];
1190       if (chart_includes_value (frq->hist, var, &f->value))
1191         {
1192           x_min = MIN (x_min, f->value.f);
1193           x_max = MAX (x_max, f->value.f);
1194           valid_freq += f->count;
1195         }
1196     }
1197
1198   /* Freedman-Diaconis' choice of bin width. */
1199   iqr = calculate_iqr (frq);
1200   bin_width = 2 * iqr / pow (valid_freq, 1.0 / 3.0);
1201
1202   histogram = histogram_create (bin_width, x_min, x_max);
1203
1204   if ( histogram == NULL)
1205     return NULL;
1206
1207   for (i = 0; i < ft->n_valid; i++)
1208     {
1209       const struct freq *f = &ft->valid[i];
1210       if (chart_includes_value (frq->hist, var, &f->value))
1211         histogram_add (histogram, f->value.f, f->count);
1212     }
1213
1214   return histogram;
1215 }
1216
1217 static int
1218 add_slice (const struct frq_chart *pie, const struct freq *freq,
1219            const struct variable *var, struct slice *slice)
1220 {
1221   if (chart_includes_value (pie, var, &freq->value))
1222     {
1223       ds_init_empty (&slice->label);
1224       var_append_value_name (var, &freq->value, &slice->label);
1225       slice->magnitude = freq->count;
1226       return 1;
1227     }
1228   else
1229     return 0;
1230 }
1231
1232 /* Allocate an array of slices and fill them from the data in frq_tab
1233    n_slices will contain the number of slices allocated.
1234    The caller is responsible for freeing slices
1235 */
1236 static struct slice *
1237 freq_tab_to_slice_array(const struct frq_chart *pie,
1238                         const struct freq_tab *frq_tab,
1239                         const struct variable *var,
1240                         int *n_slicesp)
1241 {
1242   struct slice *slices;
1243   int n_slices;
1244   int i;
1245
1246   slices = xnmalloc (frq_tab->n_valid + frq_tab->n_missing, sizeof *slices);
1247   n_slices = 0;
1248
1249   for (i = 0; i < frq_tab->n_valid; i++)
1250     n_slices += add_slice (pie, &frq_tab->valid[i], var, &slices[n_slices]);
1251   for (i = 0; i < frq_tab->n_missing; i++)
1252     n_slices += add_slice (pie, &frq_tab->missing[i], var, &slices[n_slices]);
1253
1254   *n_slicesp = n_slices;
1255   return slices;
1256 }
1257
1258
1259 static void
1260 do_piechart(const struct frq_chart *pie, const struct variable *var,
1261             const struct freq_tab *frq_tab)
1262 {
1263   struct slice *slices;
1264   int n_slices, i;
1265
1266   slices = freq_tab_to_slice_array (pie, frq_tab, var, &n_slices);
1267
1268   if (n_slices < 2)
1269     msg (SW, _("Omitting pie chart for %s, which has only %d unique values."),
1270          var_get_name (var), n_slices);
1271   else if (n_slices > 50)
1272     msg (SW, _("Omitting pie chart for %s, which has over 50 unique values."),
1273          var_get_name (var));
1274   else
1275     chart_item_submit (piechart_create (var_to_string(var), slices, n_slices));
1276
1277   for (i = 0; i < n_slices; i++)
1278     ds_destroy (&slices[i].label);
1279   free (slices);
1280 }
1281
1282 /* Calculates all the pertinent statistics for VF, putting them in array
1283    D[]. */
1284 static void
1285 calc_stats (const struct var_freqs *vf, double d[FRQ_ST_count])
1286 {
1287   const struct freq_tab *ft = &vf->tab;
1288   double W = ft->valid_cases;
1289   const struct freq *f;
1290   struct moments *m;
1291   int most_often;
1292   double X_mode;
1293
1294   assert (ft->n_valid > 0);
1295
1296   /* Calculate the mode. */
1297   most_often = -1;
1298   X_mode = SYSMIS;
1299   for (f = ft->valid; f < ft->missing; f++)
1300     {
1301       if (most_often < f->count)
1302         {
1303           most_often = f->count;
1304           X_mode = f->value.f;
1305         }
1306       else if (most_often == f->count)
1307         {
1308           /* A duplicate mode is undefined.
1309              FIXME: keep track of *all* the modes. */
1310           X_mode = SYSMIS;
1311         }
1312     }
1313
1314   /* Calculate moments. */
1315   m = moments_create (MOMENT_KURTOSIS);
1316   for (f = ft->valid; f < ft->missing; f++)
1317     moments_pass_one (m, f->value.f, f->count);
1318   for (f = ft->valid; f < ft->missing; f++)
1319     moments_pass_two (m, f->value.f, f->count);
1320   moments_calculate (m, NULL, &d[FRQ_ST_MEAN], &d[FRQ_ST_VARIANCE],
1321                      &d[FRQ_ST_SKEWNESS], &d[FRQ_ST_KURTOSIS]);
1322   moments_destroy (m);
1323
1324   /* Formulas below are taken from _SPSS Statistical Algorithms_. */
1325   d[FRQ_ST_MINIMUM] = ft->valid[0].value.f;
1326   d[FRQ_ST_MAXIMUM] = ft->valid[ft->n_valid - 1].value.f;
1327   d[FRQ_ST_MODE] = X_mode;
1328   d[FRQ_ST_RANGE] = d[FRQ_ST_MAXIMUM] - d[FRQ_ST_MINIMUM];
1329   d[FRQ_ST_SUM] = d[FRQ_ST_MEAN] * W;
1330   d[FRQ_ST_STDDEV] = sqrt (d[FRQ_ST_VARIANCE]);
1331   d[FRQ_ST_SEMEAN] = d[FRQ_ST_STDDEV] / sqrt (W);
1332   d[FRQ_ST_SESKEWNESS] = calc_seskew (W);
1333   d[FRQ_ST_SEKURTOSIS] = calc_sekurt (W);
1334 }
1335
1336 /* Displays a table of all the statistics requested for variable V. */
1337 static void
1338 dump_statistics (const struct frq_proc *frq, const struct var_freqs *vf,
1339                  const struct variable *wv)
1340 {
1341   const struct fmt_spec *wfmt = wv ? var_get_print_format (wv) : &F_8_0;
1342   const struct freq_tab *ft = &vf->tab;
1343   double stat_value[FRQ_ST_count];
1344   struct tab_table *t;
1345   int i, r;
1346
1347   if (var_is_alpha (vf->var))
1348     return;
1349
1350   if (ft->n_valid == 0)
1351     {
1352       msg (SW, _("No valid data for variable %s; statistics not displayed."),
1353            var_get_name (vf->var));
1354       return;
1355     }
1356   calc_stats (vf, stat_value);
1357
1358   t = tab_create (3, ((frq->stats & FRQ_ST_MEDIAN) ? frq->n_stats - 1 : frq->n_stats) + frq->n_show_percentiles + 2);
1359
1360   tab_box (t, TAL_1, TAL_1, -1, -1 , 0 , 0 , 2, tab_nr(t) - 1) ;
1361
1362
1363   tab_vline (t, TAL_1 , 2, 0, tab_nr(t) - 1);
1364   tab_vline (t, TAL_GAP , 1, 0, tab_nr(t) - 1 ) ;
1365
1366   r = 2; /* N missing and N valid are always dumped */
1367
1368   for (i = 0; i < FRQ_ST_count; i++)
1369     {
1370       if (FRQ_ST_MEDIAN == i)
1371         continue;
1372
1373       if (frq->stats & BIT_INDEX (i))
1374       {
1375         tab_text (t, 0, r, TAB_LEFT | TAT_TITLE,
1376                       gettext (st_name[i]));
1377         tab_double (t, 2, r, TAB_NONE, stat_value[i], NULL);
1378         r++;
1379       }
1380     }
1381
1382   tab_text (t, 0, 0, TAB_LEFT | TAT_TITLE, _("N"));
1383   tab_text (t, 1, 0, TAB_LEFT | TAT_TITLE, _("Valid"));
1384   tab_text (t, 1, 1, TAB_LEFT | TAT_TITLE, _("Missing"));
1385
1386   tab_double (t, 2, 0, TAB_NONE, ft->valid_cases, wfmt);
1387   tab_double (t, 2, 1, TAB_NONE, ft->total_cases - ft->valid_cases, wfmt);
1388
1389   for (i = 0; i < frq->n_percentiles; i++)
1390     {
1391       const struct percentile *pc = &frq->percentiles[i];
1392
1393       if (!pc->show)
1394         continue;
1395
1396       if ( i == 0 )
1397         {
1398           tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, _("Percentiles"));
1399         }
1400
1401       if (pc->p == 0.5)
1402         tab_text (t, 1, r, TAB_LEFT, _("50 (Median)"));
1403       else
1404         tab_fixed (t, 1, r, TAB_LEFT, pc->p * 100, 3, 0);
1405       tab_double (t, 2, r, TAB_NONE, pc->value,
1406                   var_get_print_format (vf->var));
1407       r++;
1408     }
1409
1410   tab_title (t, "%s", var_to_string (vf->var));
1411
1412   tab_submit (t);
1413 }
1414