work on pivot table and FREQUENCIES usage
[pspp] / src / language / stats / frequencies.q
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2007, 2009, 2010 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16
17 #include <config.h>
18
19 #include <math.h>
20 #include <stdlib.h>
21 #include <gsl/gsl_histogram.h>
22
23 #include "data/case.h"
24 #include "data/casegrouper.h"
25 #include "data/casereader.h"
26 #include "data/casewriter.h"
27 #include "data/dictionary.h"
28 #include "data/format.h"
29 #include "data/procedure.h"
30 #include "data/settings.h"
31 #include "data/subcase.h"
32 #include "data/value-labels.h"
33 #include "data/variable.h"
34 #include "language/command.h"
35 #include "language/dictionary/split-file.h"
36 #include "language/lexer/lexer.h"
37 #include "language/stats/freq.h"
38 #include "libpspp/array.h"
39 #include "libpspp/bit-vector.h"
40 #include "libpspp/compiler.h"
41 #include "libpspp/hmap.h"
42 #include "libpspp/message.h"
43 #include "libpspp/misc.h"
44 #include "libpspp/pool.h"
45 #include "libpspp/str.h"
46 #include "math/histogram.h"
47 #include "math/moments.h"
48 #include "math/sort.h"
49 #include "output/chart-item.h"
50 #include "output/charts/piechart.h"
51 #include "output/charts/plot-hist.h"
52 #include "output/pivot-table.h"
53 #include "output/tab.h"
54
55 #include "gl/minmax.h"
56 #include "gl/xalloc.h"
57
58 #include "gettext.h"
59 #define _(msgid) gettext (msgid)
60 #define N_(msgid) msgid
61
62 /* (headers) */
63
64 /* (specification)
65    FREQUENCIES (frq_):
66      *+variables=custom;
67      +format=table:limit(n:limit,"%s>0")/notable/!table,
68              sort:!avalue/dvalue/afreq/dfreq;
69      missing=miss:include/!exclude;
70      barchart(ba_)=:minimum(d:min),
71             :maximum(d:max),
72             scale:freq(*n:freq,"%s>0")/percent(*n:pcnt,"%s>0");
73      piechart(pie_)=:minimum(d:min),
74             :maximum(d:max),
75             missing:missing/!nomissing,
76             scale:!freq/percent;
77      histogram(hi_)=:minimum(d:min),
78             :maximum(d:max),
79             scale:freq(*n:freq,"%s>0")/percent(*n:pcnt,"%s>0"),
80             norm:!nonormal/normal;
81      +grouped=custom;
82      +ntiles=integer;
83      +percentiles = double list;
84      +statistics[st_]=mean,semean,median,mode,stddev,variance,
85             kurtosis,skewness,range,minimum,maximum,sum,
86             default,seskewness,sekurtosis,all,none.
87 */
88 /* (declarations) */
89 /* (functions) */
90
91 /* Statistics. */
92 enum
93   {
94     FRQ_MEAN, FRQ_SEMEAN, FRQ_MEDIAN, FRQ_MODE, FRQ_STDDEV, FRQ_VARIANCE,
95     FRQ_KURT, FRQ_SEKURT, FRQ_SKEW, FRQ_SESKEW, FRQ_RANGE, FRQ_MIN, FRQ_MAX,
96     FRQ_SUM, FRQ_N_STATS
97   };
98
99 /* Description of a statistic. */
100 struct frq_info
101   {
102     int st_indx;                /* Index into a_statistics[]. */
103     const char *s10;            /* Identifying string. */
104   };
105
106 /* Table of statistics, indexed by dsc_*. */
107 static const struct frq_info st_name[FRQ_N_STATS + 1] =
108 {
109   {FRQ_ST_MEAN, N_("Mean")},
110   {FRQ_ST_SEMEAN, N_("S.E. Mean")},
111   {FRQ_ST_MEDIAN, N_("Median")},
112   {FRQ_ST_MODE, N_("Mode")},
113   {FRQ_ST_STDDEV, N_("Std Dev")},
114   {FRQ_ST_VARIANCE, N_("Variance")},
115   {FRQ_ST_KURTOSIS, N_("Kurtosis")},
116   {FRQ_ST_SEKURTOSIS, N_("S.E. Kurt")},
117   {FRQ_ST_SKEWNESS, N_("Skewness")},
118   {FRQ_ST_SESKEWNESS, N_("S.E. Skew")},
119   {FRQ_ST_RANGE, N_("Range")},
120   {FRQ_ST_MINIMUM, N_("Minimum")},
121   {FRQ_ST_MAXIMUM, N_("Maximum")},
122   {FRQ_ST_SUM, N_("Sum")},
123   {-1, 0},
124 };
125
126 /* Percentiles to calculate. */
127
128 struct percentile
129 {
130   double p;        /* the %ile to be calculated */
131   double value;    /* the %ile's value */
132   bool show;       /* True to show this percentile in the statistics box. */
133 };
134
135 /* Groups of statistics. */
136 #define BI          BIT_INDEX
137 #define FRQ_DEFAULT                                                     \
138         (BI (FRQ_MEAN) | BI (FRQ_STDDEV) | BI (FRQ_MIN) | BI (FRQ_MAX))
139 #define FRQ_ALL                                                 \
140         (BI (FRQ_SUM) | BI(FRQ_MIN) | BI(FRQ_MAX)               \
141          | BI(FRQ_MEAN) | BI(FRQ_SEMEAN) | BI(FRQ_STDDEV)       \
142          | BI(FRQ_VARIANCE) | BI(FRQ_KURT) | BI(FRQ_SEKURT)     \
143          | BI(FRQ_SKEW) | BI(FRQ_SESKEW) | BI(FRQ_RANGE)        \
144          | BI(FRQ_RANGE) | BI(FRQ_MODE) | BI(FRQ_MEDIAN))
145
146 struct frq_chart
147   {
148     double x_min;               /* X axis minimum value. */
149     double x_max;               /* X axis maximum value. */
150     int y_scale;                /* Y axis scale: FRQ_FREQ or FRQ_PERCENT. */
151
152     /* Histograms only. */
153     double y_max;               /* Y axis maximum value. */
154     bool draw_normal;           /* Whether to draw normal curve. */
155
156     /* Pie charts only. */
157     bool include_missing;       /* Whether to include missing values. */
158   };
159
160 /* Frequency tables. */
161
162 /* Entire frequency table. */
163 struct freq_tab
164   {
165     struct casewriter *sorter;
166     struct casereader *data;
167
168     struct freq *valid;         /* Valid freqs. */
169     int n_valid;                /* Number of valid freqs. */
170     const struct dictionary *dict; /* Source of entries in the table. */
171
172     struct freq *missing;       /* Missing freqs. */
173     int n_missing;              /* Number of missing freqs. */
174
175     /* Statistics. */
176     double total_cases;         /* Sum of weights of all cases. */
177     double valid_cases;         /* Sum of weights of valid cases. */
178   };
179
180 /* Per-variable frequency data. */
181 struct var_freqs
182   {
183     struct variable *var;
184
185     /* Freqency table. */
186     struct freq_tab tab;        /* Frequencies table to use. */
187
188     /* Percentiles. */
189     int n_groups;               /* Number of groups. */
190     double *groups;             /* Groups. */
191
192     /* Statistics. */
193     double stat[FRQ_N_STATS];
194
195     /* Variable attributes. */
196     int width;
197     struct fmt_spec print;
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     int n_percentiles, n_show_percentiles;
210
211     /* Frequency table display. */
212     int max_categories;         /* Maximum categories to show. */
213     int sort;                   /* FRQ_AVALUE or FRQ_DVALUE
214                                    or FRQ_ACOUNT or FRQ_DCOUNT. */
215
216     /* Statistics; number of statistics. */
217     unsigned long stats;
218     int n_stats;
219
220     /* Histogram and pie chart settings. */
221     struct frq_chart *hist, *pie;
222   };
223
224 static void determine_charts (struct frq_proc *,
225                               const struct cmd_frequencies *);
226
227 static void calc_stats (const struct var_freqs *, double d[FRQ_N_STATS]);
228 static void calc_percentiles (const struct frq_proc *,
229                               const struct var_freqs *);
230
231 static void precalc (struct frq_proc *, struct casereader *, struct dataset *);
232 static void calc (struct frq_proc *, const struct ccase *,
233                   const struct dataset *);
234 static void postcalc (struct frq_proc *, const struct dataset *);
235
236 static void postprocess_freq_tab (const struct frq_proc *, struct var_freqs *);
237 static void dump_freq_table (const struct var_freqs *,
238                              const struct variable *weight_var);
239 static void dump_statistics (const struct frq_proc *, const struct var_freqs *,
240                              const struct variable *weight_var);
241 static void cleanup_freq_tab (struct var_freqs *);
242
243 static void add_percentile (struct frq_proc *, double x, bool show,
244                             size_t *allocated_percentiles);
245
246 static void do_piechart(const struct frq_chart *, const struct variable *,
247                         const struct freq_tab *);
248
249 struct histogram *freq_tab_to_hist(const struct frq_proc *,
250                                    const struct freq_tab *,
251                                    const struct variable *);
252 \f
253 /* Parser and outline. */
254
255 int
256 cmd_frequencies (struct lexer *lexer, struct dataset *ds)
257 {
258   struct cmd_frequencies cmd;
259   struct frq_proc frq;
260   struct casegrouper *grouper;
261   struct casereader *input, *group;
262   size_t allocated_percentiles;
263   bool ok;
264   int i;
265
266   frq.pool = pool_create ();
267
268   frq.vars = NULL;
269   frq.n_vars = 0;
270
271   frq.percentiles = NULL;
272   frq.n_percentiles = 0;
273   frq.n_show_percentiles = 0;
274
275   frq.hist = NULL;
276   frq.pie = NULL;
277
278   allocated_percentiles = 0;
279
280   if (!parse_frequencies (lexer, ds, &cmd, &frq))
281     {
282       pool_destroy (frq.pool);
283       return CMD_FAILURE;
284     }
285
286   /* Figure out when to show frequency tables. */
287   frq.max_categories = (cmd.table == FRQ_NOTABLE ? -1
288                         : cmd.table == FRQ_TABLE ? INT_MAX
289                         : cmd.limit);
290   frq.sort = cmd.sort;
291
292   /* Figure out statistics to calculate. */
293   frq.stats = 0;
294   if (cmd.a_statistics[FRQ_ST_DEFAULT] || !cmd.sbc_statistics)
295     frq.stats |= FRQ_DEFAULT;
296   if (cmd.a_statistics[FRQ_ST_ALL])
297     frq.stats |= FRQ_ALL;
298   if (cmd.sort != FRQ_AVALUE && cmd.sort != FRQ_DVALUE)
299     frq.stats &= ~BIT_INDEX (FRQ_MEDIAN);
300   for (i = 0; i < FRQ_N_STATS; i++)
301     if (cmd.a_statistics[st_name[i].st_indx])
302       frq.stats |= BIT_INDEX (i);
303   if (frq.stats & FRQ_KURT)
304     frq.stats |= BIT_INDEX (FRQ_SEKURT);
305   if (frq.stats & FRQ_SKEW)
306     frq.stats |= BIT_INDEX (FRQ_SESKEW);
307
308   /* Calculate n_stats. */
309   frq.n_stats = 0;
310   for (i = 0; i < FRQ_N_STATS; i++)
311     if ((frq.stats & BIT_INDEX (i)))
312       frq.n_stats++;
313
314   /* Charting. */
315   determine_charts (&frq, &cmd);
316   if (cmd.sbc_histogram || cmd.sbc_piechart || cmd.sbc_ntiles)
317     cmd.sort = FRQ_AVALUE;
318
319   /* Work out what percentiles need to be calculated */
320   if ( cmd.sbc_percentiles )
321     {
322       for ( i = 0 ; i < MAXLISTS ; ++i )
323         {
324           int pl;
325           subc_list_double *ptl_list = &cmd.dl_percentiles[i];
326           for ( pl = 0 ; pl < subc_list_double_count(ptl_list); ++pl)
327             add_percentile (&frq, subc_list_double_at(ptl_list, pl) / 100.0,
328                             true, &allocated_percentiles);
329         }
330     }
331   if ( cmd.sbc_ntiles )
332     {
333       for ( i = 0 ; i < cmd.sbc_ntiles ; ++i )
334         {
335           int j;
336           for (j = 0; j <= cmd.n_ntiles[i]; ++j )
337             add_percentile (&frq, j / (double) cmd.n_ntiles[i], true,
338                             &allocated_percentiles);
339         }
340     }
341   if (frq.stats & BIT_INDEX (FRQ_MEDIAN))
342     {
343       /* Treat the median as the 50% percentile.
344          We output it in the percentiles table as "50 (Median)." */
345       add_percentile (&frq, 0.5, true, &allocated_percentiles);
346       frq.stats &= ~BIT_INDEX (FRQ_MEDIAN);
347       frq.n_stats--;
348     }
349   if (cmd.sbc_histogram)
350     {
351       add_percentile (&frq, 0.25, false, &allocated_percentiles);
352       add_percentile (&frq, 0.75, false, &allocated_percentiles);
353     }
354
355   /* Do it! */
356   input = casereader_create_filter_weight (proc_open (ds), dataset_dict (ds),
357                                            NULL, NULL);
358   grouper = casegrouper_create_splits (input, dataset_dict (ds));
359   for (; casegrouper_get_next_group (grouper, &group);
360        casereader_destroy (group))
361     {
362       struct ccase *c;
363
364       precalc (&frq, group, ds);
365       for (; (c = casereader_read (group)) != NULL; case_unref (c))
366         calc (&frq, c, ds);
367       postcalc (&frq, ds);
368     }
369   ok = casegrouper_destroy (grouper);
370   ok = proc_commit (ds) && ok;
371
372   free_frequencies(&cmd);
373
374   pool_destroy (frq.pool);
375   free (frq.vars);
376   free (frq.percentiles);
377   free (frq.hist);
378   free (frq.pie);
379
380   return ok ? CMD_SUCCESS : CMD_CASCADING_FAILURE;
381 }
382
383 /* Figure out which charts the user requested.  */
384 static void
385 determine_charts (struct frq_proc *frq, const struct cmd_frequencies *cmd)
386 {
387   if (cmd->sbc_barchart)
388     msg (SW, _("Bar charts are not implemented."));
389
390   if (cmd->sbc_histogram)
391     {
392       struct frq_chart *hist;
393
394       hist = frq->hist = xmalloc (sizeof *frq->hist);
395       hist->x_min = cmd->hi_min;
396       hist->x_max = cmd->hi_max;
397       hist->y_scale = cmd->hi_scale;
398       hist->y_max = cmd->hi_scale == FRQ_FREQ ? cmd->hi_freq : cmd->hi_pcnt;
399       hist->draw_normal = cmd->hi_norm != FRQ_NONORMAL;
400       hist->include_missing = false;
401
402       if (hist->x_min != SYSMIS && hist->x_max != SYSMIS
403           && hist->x_min >= hist->x_max)
404         {
405           msg (SE, _("MAX for histogram must be greater than or equal to MIN, "
406                      "but MIN was specified as %.15g and MAX as %.15g.  "
407                      "MIN and MAX will be ignored."),
408                hist->x_min, hist->x_max);
409           hist->x_min = hist->x_max = SYSMIS;
410         }
411     }
412
413   if (cmd->sbc_piechart)
414     {
415       struct frq_chart *pie;
416
417       pie = frq->pie = xmalloc (sizeof *frq->pie);
418       pie->x_min = cmd->pie_min;
419       pie->x_max = cmd->pie_max;
420       pie->y_scale = cmd->pie_scale;
421       pie->include_missing = cmd->pie_missing == FRQ_MISSING;
422
423       if (pie->x_min != SYSMIS && pie->x_max != SYSMIS
424           && pie->x_min >= pie->x_max)
425         {
426           msg (SE, _("MAX for pie chart must be greater than or equal to MIN, "
427                      "but MIN was specified as %.15g and MAX as %.15g.  "
428                      "MIN and MAX will be ignored."), pie->x_min, pie->x_max);
429           pie->x_min = pie->x_max = SYSMIS;
430         }
431     }
432 }
433
434 /* Add data from case C to the frequency table. */
435 static void
436 calc (struct frq_proc *frq, const struct ccase *c, const struct dataset *ds)
437 {
438   double weight = dict_get_case_weight (dataset_dict (ds), c, NULL);
439   size_t i;
440
441   for (i = 0; i < frq->n_vars; i++)
442     {
443       struct var_freqs *vf = &frq->vars[i];
444       struct casewriter *writer = vf->tab.sorter;
445       struct ccase *f;
446
447       f = case_create (casewriter_get_proto (writer));
448       value_copy (case_data_rw_idx (f, 0), case_data (c, vf->var), vf->width);
449       case_data_rw_idx (f, 1)->f = weight;
450
451       casewriter_write (writer, f);
452     }
453 }
454
455 static struct ccase *
456 combine_freq_cases (struct ccase *a, struct ccase *b, void *aux UNUSED)
457 {
458   a = case_unshare (a);
459   case_data_rw_idx (a, 1)->f += case_data_idx (b, 1)->f;
460   case_unref (b);
461
462   return a;
463 }
464
465 /* Prepares each variable that is the target of FREQUENCIES by setting
466    up its hash table. */
467 static void
468 precalc (struct frq_proc *frq, struct casereader *input, struct dataset *ds)
469 {
470   struct ccase *c;
471   size_t i;
472
473   c = casereader_peek (input, 0);
474   if (c != NULL)
475     {
476       output_split_file_values (ds, c);
477       case_unref (c);
478     }
479
480   for (i = 0; i < frq->n_vars; i++)
481     {
482       int width = var_get_width (frq->vars[i].var);
483       struct caseproto *proto;
484       struct subcase ordering;
485
486       proto = caseproto_create ();
487       proto = caseproto_add_width (proto, width);
488       proto = caseproto_add_width (proto, 0);
489
490       subcase_init (&ordering, 0, width, SC_ASCEND);
491       frq->vars[i].tab.sorter = sort_distinct_create_writer (
492         &ordering, proto, combine_freq_cases, NULL, NULL);
493
494       caseproto_unref (proto);
495       subcase_destroy (&ordering);
496     }
497 }
498
499 /* Finishes up with the variables after frequencies have been
500    calculated.  Displays statistics, percentiles, ... */
501 static void
502 postcalc (struct frq_proc *frq, const struct dataset *ds)
503 {
504   const struct dictionary *dict = dataset_dict (ds);
505   const struct variable *wv = dict_get_weight (dict);
506   size_t i;
507
508   for (i = 0; i < frq->n_vars; i++)
509     {
510       struct var_freqs *vf = &frq->vars[i];
511
512       postprocess_freq_tab (frq, vf);
513
514       /* Frequencies tables. */
515       if (vf->tab.n_valid + vf->tab.n_missing <= frq->max_categories)
516         dump_freq_table (vf, wv);
517
518       /* Statistics. */
519       if (frq->n_stats)
520         dump_statistics (frq, vf, wv);
521
522       if (frq->hist && var_is_numeric (vf->var) && vf->tab.n_valid > 0)
523         {
524           double d[FRQ_N_STATS];
525           struct histogram *histogram;
526
527           calc_stats (vf, d);
528
529           histogram = freq_tab_to_hist (frq, &vf->tab, vf->var);
530
531           chart_item_submit (histogram_chart_create (
532                                histogram->gsl_hist, var_to_string(vf->var),
533                                vf->tab.valid_cases,
534                                d[FRQ_MEAN],
535                                d[FRQ_STDDEV],
536                                frq->hist->draw_normal));
537
538           statistic_destroy (&histogram->parent);
539         }
540
541       if (frq->pie)
542         do_piechart(frq->pie, vf->var, &vf->tab);
543
544       cleanup_freq_tab (vf);
545
546     }
547 }
548
549 /* Returns true iff the value in struct freq F is non-missing
550    for variable V. */
551 static bool
552 not_missing (const void *f_, const void *v_)
553 {
554   const struct freq *f = f_;
555   const struct variable *v = v_;
556
557   return !var_is_value_missing (v, &f->value, MV_ANY);
558 }
559
560 struct freq_compare_aux
561   {
562     bool by_freq;
563     bool ascending_freq;
564
565     int width;
566     bool ascending_value;
567   };
568
569 static int
570 compare_freq (const void *a_, const void *b_, const void *aux_)
571 {
572   const struct freq_compare_aux *aux = aux_;
573   const struct freq *a = a_;
574   const struct freq *b = b_;
575
576   if (aux->by_freq && a->count != b->count)
577     {
578       int cmp = a->count > b->count ? 1 : -1;
579       return aux->ascending_freq ? cmp : -cmp;
580     }
581   else
582     {
583       int cmp = value_compare_3way (&a->value, &b->value, aux->width);
584       return aux->ascending_value ? cmp : -cmp;
585     }
586 }
587 /* Summarizes the frequency table data for variable V. */
588 static void
589 postprocess_freq_tab (const struct frq_proc *frq, struct var_freqs *vf)
590 {
591   struct freq_tab *ft = &vf->tab;
592   struct freq_compare_aux aux;
593   struct casereader *reader;
594   struct ccase *c;
595   size_t count;
596   struct freq *freqs, *f;
597   size_t i;
598
599   /* Extract data from hash table. */
600   reader = casewriter_make_reader (ft->sorter);
601   ft->data = casereader_clone (reader);
602   freqs = xnmalloc (casereader_count_cases (reader), sizeof *freqs);
603   for (count = 0; (c = casereader_read (reader)) != NULL; count++)
604     {
605       struct freq *f = &freqs[count];
606       value_clone (&f->value, case_data_idx (c, 0), vf->width);
607       f->count = case_num_idx (c, 1);
608       case_unref (c);
609     }
610   casereader_destroy (reader);
611
612   /* Put data into ft. */
613   ft->valid = freqs;
614   ft->n_valid = partition (freqs, count, sizeof *freqs, not_missing, vf->var);
615   ft->missing = freqs + ft->n_valid;
616   ft->n_missing = count - ft->n_valid;
617
618   /* Sort data. */
619   aux.by_freq = frq->sort == FRQ_AFREQ || frq->sort == FRQ_DFREQ;
620   aux.ascending_freq = frq->sort != FRQ_DFREQ;
621   aux.width = vf->width;
622   aux.ascending_value = frq->sort != FRQ_DVALUE;
623   sort (ft->valid, ft->n_valid, sizeof *ft->valid, compare_freq, &aux);
624   sort (ft->missing, ft->n_missing, sizeof *ft->missing, compare_freq, &aux);
625
626   /* Summary statistics. */
627   ft->valid_cases = 0.0;
628   for(i = 0 ;  i < ft->n_valid ; ++i )
629     {
630       f = &ft->valid[i];
631       ft->valid_cases += f->count;
632
633     }
634
635   ft->total_cases = ft->valid_cases ;
636   for(i = 0 ;  i < ft->n_missing ; ++i )
637     {
638       f = &ft->missing[i];
639       ft->total_cases += f->count;
640     }
641
642 }
643
644 /* Frees the frequency table for variable V. */
645 static void
646 cleanup_freq_tab (struct var_freqs *vf)
647 {
648   if (value_needs_init (vf->width))
649     {
650       int i;
651
652       for (i = 0; i < vf->tab.n_valid + vf->tab.n_missing; i++)
653         value_destroy (&vf->tab.valid[i].value, vf->width);
654     }
655   casereader_destroy (vf->tab.data);
656   free (vf->tab.valid);
657 }
658
659 /* Parses the VARIABLES subcommand. */
660 static int
661 frq_custom_variables (struct lexer *lexer, struct dataset *ds,
662                       struct cmd_frequencies *cmd UNUSED, void *frq_ UNUSED)
663 {
664   struct frq_proc *frq = frq_;
665   struct variable **vars;
666   size_t n_vars;
667   size_t i;
668
669   lex_match (lexer, '=');
670   if (lex_token (lexer) != T_ALL
671       && (lex_token (lexer) != T_ID
672           || dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) == NULL))
673     return 2;
674
675   /* Get list of current variables, to avoid duplicates. */
676   vars = xmalloc (frq->n_vars * sizeof *vars);
677   n_vars = frq->n_vars;
678   for (i = 0; i < frq->n_vars; i++)
679     vars[i] = frq->vars[i].var;
680
681   if (!parse_variables (lexer, dataset_dict (ds), &vars, &n_vars,
682                         PV_APPEND | PV_NO_SCRATCH))
683     return 0;
684
685   frq->vars = xrealloc (frq->vars, n_vars * sizeof *frq->vars);
686   for (i = frq->n_vars; i < n_vars; i++)
687     {
688       struct variable *var = vars[i];
689       struct var_freqs *vf = &frq->vars[i];
690
691       vf->var = var;
692       vf->tab.valid = vf->tab.missing = NULL;
693       vf->tab.dict = dataset_dict (ds);
694       vf->n_groups = 0;
695       vf->groups = NULL;
696       vf->width = var_get_width (var);
697       vf->print = *var_get_print_format (var);
698     }
699   frq->n_vars = n_vars;
700
701   free (vars);
702
703   return 1;
704 }
705
706 /* Parses the GROUPED subcommand, setting the n_grouped, grouped
707    fields of specified variables. */
708 static int
709 frq_custom_grouped (struct lexer *lexer, struct dataset *ds, struct cmd_frequencies *cmd UNUSED, void *frq_ UNUSED)
710 {
711   struct frq_proc *frq = frq_;
712
713   lex_match (lexer, '=');
714   if ((lex_token (lexer) == T_ID && dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) != NULL)
715       || lex_token (lexer) == T_ID)
716     for (;;)
717       {
718         size_t i;
719
720         /* Max, current size of list; list itself. */
721         int nl, ml;
722         double *dl;
723
724         /* Variable list. */
725         size_t n;
726         const struct variable **v;
727
728         if (!parse_variables_const (lexer, dataset_dict (ds), &v, &n,
729                               PV_NO_DUPLICATE | PV_NUMERIC))
730           return 0;
731         if (lex_match (lexer, '('))
732           {
733             nl = ml = 0;
734             dl = NULL;
735             while (lex_integer (lexer))
736               {
737                 if (nl >= ml)
738                   {
739                     ml += 16;
740                     dl = pool_nrealloc (frq->pool, dl, ml, sizeof *dl);
741                   }
742                 dl[nl++] = lex_tokval (lexer);
743                 lex_get (lexer);
744                 lex_match (lexer, ',');
745               }
746             /* Note that nl might still be 0 and dl might still be
747                NULL.  That's okay. */
748             if (!lex_match (lexer, ')'))
749               {
750                 free (v);
751                 msg (SE, _("`)' expected after GROUPED interval list."));
752                 return 0;
753               }
754           }
755         else
756           {
757             nl = 0;
758             dl = NULL;
759           }
760
761         for (i = 0; i < n; i++)
762           {
763             size_t j;
764
765             for (j = 0; j < frq->n_vars; j++)
766               {
767                 struct var_freqs *vf = &frq->vars[j];
768                 if (vf->var == v[i])
769                   {
770                     if (vf->groups != NULL)
771                       msg (SE, _("Variables %s specified multiple times on "
772                                  "GROUPED subcommand."), var_get_name (v[i]));
773                     else
774                       {
775                         vf->n_groups = nl;
776                         vf->groups = dl;
777                       }
778                     goto found;
779                   }
780               }
781             msg (SE, _("Variables %s specified on GROUPED but not on "
782                        "VARIABLES."), var_get_name (v[i]));
783
784           found:;
785           }
786
787         free (v);
788         if (!lex_match (lexer, '/'))
789           break;
790         if ((lex_token (lexer) != T_ID || dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) != NULL)
791             && lex_token (lexer) != T_ALL)
792           {
793             lex_put_back (lexer, '/');
794             break;
795           }
796       }
797
798   return 1;
799 }
800
801 /* Adds X to the list of percentiles, keeping the list in proper
802    order.  If SHOW is true, the percentile will be shown in the statistics
803    box, otherwise it will be hidden. */
804 static void
805 add_percentile (struct frq_proc *frq, double x, bool show,
806                 size_t *allocated_percentiles)
807 {
808   int i;
809
810   /* Do nothing if it's already in the list */
811   for (i = 0; i < frq->n_percentiles; i++)
812     {
813       struct percentile *pc = &frq->percentiles[i];
814
815       if ( fabs(x - pc->p) < DBL_EPSILON )
816         {
817           if (show && !pc->show)
818             {
819               frq->n_show_percentiles++;
820               pc->show = true;
821             }
822           return;
823         }
824
825       if (x < pc->p)
826         break;
827     }
828
829   if (frq->n_percentiles >= *allocated_percentiles)
830     frq->percentiles = x2nrealloc (frq->percentiles, allocated_percentiles,
831                                    sizeof *frq->percentiles);
832   insert_element (frq->percentiles, frq->n_percentiles,
833                   sizeof *frq->percentiles, i);
834   frq->percentiles[i].p = x;
835   frq->percentiles[i].show = show;
836   frq->n_percentiles++;
837   if (show)
838     frq->n_show_percentiles++;
839 }
840
841 /* Comparison functions. */
842
843 \f
844 /* Frequency table display. */
845
846 /* Displays a full frequency table for variable V. */
847 static void
848 dump_freq_table (const struct var_freqs *vf, const struct variable *wv)
849 {
850   struct variable *value_var, *freq_var;
851   struct pivot_table *pt;
852
853   pt = xmalloc (sizeof *pt);
854
855   pt->data = casereader_clone (vf->tab.data);
856
857   pt->dict = dict_create ();
858   value_var = dict_clone_var_assert (pt->dict, vf->var);
859   if (wv != NULL)
860     freq_var = dict_clone_var_assert (pt->dict, wv);
861   else
862     {
863       freq_var = dict_create_var (pt->dict, "$Frequency", 0);
864       var_set_both_formats (freq_var, &F_8_0);
865       var_set_label (freq_var, _("Frequency"));
866     }
867
868   subcase_init_empty (&pt->split);
869   subcase_init_empty (&pt->dimensions[TABLE_HORZ]);
870   subcase_init_empty (&pt->dimensions[TABLE_VERT]);
871   subcase_add_var (&pt->dimensions[TABLE_VERT], value_var, SC_ASCEND);
872
873   pt->pane.n[TABLE_HORZ] = 4;
874   pt->pane.n[TABLE_VERT] = 1;
875   pt->pane.cells = xmalloc (sizeof *pt->pane.cells);
876   pt->pane.cells[0] = xmalloc (4 * sizeof **pt->pane.cells);
877
878   /* Frequency. */
879   pivot_cell_init (
880     &pt->pane.cells[0][0],
881     pivot_value_create (freq_var, PIVOT_SUM, 0, 0, PIVOT_INCLUDE_ALL));
882
883   /* Percent. */
884   pivot_cell_init (
885     &pt->pane.cells[0][1],
886     pivot_value_create (freq_var, PIVOT_SUM, 0, 0, PIVOT_INCLUDE_ALL));
887   pt->pane.cells[0][1].cmp = PIVOT_PERCENT;
888   pt->pane.cells[0][1].cmp_args[0] = pivot_value_create (
889     freq_var, PIVOT_SUM, 0, 1, PIVOT_INCLUDE_ALL);
890   pt->pane.cells[0][1].label = xstrdup ("Percent");
891
892   /* Valid Percent. */
893   pivot_cell_init (
894     &pt->pane.cells[0][2],
895     pivot_value_create (freq_var, PIVOT_SUM, 0, 0, PIVOT_INCLUDE_VALID));
896   pt->pane.cells[0][2].cmp = PIVOT_PERCENT;
897   pt->pane.cells[0][2].cmp_args[0] = pivot_value_create (
898     freq_var, PIVOT_SUM, 0, 1, PIVOT_INCLUDE_VALID);
899   pt->pane.cells[0][2].label = xstrdup ("Valid Percent");
900
901   /* Cumulative (Valid) Percent. */
902   pivot_cell_init (
903     &pt->pane.cells[0][3],
904     pivot_value_create (freq_var, PIVOT_SUM, 0, 0, PIVOT_INCLUDE_VALID));
905   pt->pane.cells[0][3].base->n_cum_vars[TABLE_VERT] = 1;
906   pt->pane.cells[0][3].cmp = PIVOT_PERCENT;
907   pt->pane.cells[0][3].cmp_args[0] = pivot_value_create (
908     freq_var, PIVOT_SUM, 0, 1, PIVOT_INCLUDE_VALID);
909   pt->pane.cells[0][3].label = xstrdup ("Cum Percent");
910
911   pivot_table_dump (pt);
912 }
913 \f
914 /* Statistical display. */
915
916 static double
917 calc_percentile (double p, double valid_cases, double x1, double x2)
918 {
919   double s, dummy;
920
921   s = (settings_get_algorithm () != COMPATIBLE
922        ? modf ((valid_cases - 1) * p, &dummy)
923        : modf ((valid_cases + 1) * p - 1, &dummy));
924
925   return x1 + (x2 - x1) * s;
926 }
927
928 /* Calculates all of the percentiles for VF within FRQ. */
929 static void
930 calc_percentiles (const struct frq_proc *frq, const struct var_freqs *vf)
931 {
932   const struct freq_tab *ft = &vf->tab;
933   double W = ft->valid_cases;
934   const struct freq *f;
935   int percentile_idx;
936   double rank;
937
938   assert (ft->n_valid > 0);
939
940   rank = 0;
941   percentile_idx = 0;
942   for (f = ft->valid; f < ft->missing; f++)
943     {
944       rank += f->count;
945       for (; percentile_idx < frq->n_percentiles; percentile_idx++)
946         {
947           struct percentile *pc = &frq->percentiles[percentile_idx];
948           double tp;
949
950           tp = (settings_get_algorithm () == ENHANCED
951                 ? (W - 1) * pc->p
952                 : (W + 1) * pc->p - 1);
953
954           if (rank <= tp)
955             break;
956
957           if (f->count > 1
958               && (rank - (f->count - 1) > tp || f + 1 >= ft->missing))
959             pc->value = f->value.f;
960           else
961             pc->value = calc_percentile (pc->p, W, f->value.f, f[1].value.f);
962         }
963     }
964   for (; percentile_idx < frq->n_percentiles; percentile_idx++)
965     {
966       struct percentile *pc = &frq->percentiles[percentile_idx];
967       pc->value = ft->valid[ft->n_valid - 1].value.f;
968     }
969 }
970
971 /* Calculates all the pertinent statistics for VF, putting them in array
972    D[]. */
973 static void
974 calc_stats (const struct var_freqs *vf, double d[FRQ_N_STATS])
975 {
976   const struct freq_tab *ft = &vf->tab;
977   double W = ft->valid_cases;
978   const struct freq *f;
979   struct moments *m;
980   int most_often;
981   double X_mode;
982
983   assert (ft->n_valid > 0);
984
985   /* Calculate the mode. */
986   most_often = -1;
987   X_mode = SYSMIS;
988   for (f = ft->valid; f < ft->missing; f++)
989     {
990       if (most_often < f->count)
991         {
992           most_often = f->count;
993           X_mode = f->value.f;
994         }
995       else if (most_often == f->count)
996         {
997           /* A duplicate mode is undefined.
998              FIXME: keep track of *all* the modes. */
999           X_mode = SYSMIS;
1000         }
1001     }
1002
1003   /* Calculate moments. */
1004   m = moments_create (MOMENT_KURTOSIS);
1005   for (f = ft->valid; f < ft->missing; f++)
1006     moments_pass_one (m, f->value.f, f->count);
1007   for (f = ft->valid; f < ft->missing; f++)
1008     moments_pass_two (m, f->value.f, f->count);
1009   moments_calculate (m, NULL, &d[FRQ_MEAN], &d[FRQ_VARIANCE],
1010                      &d[FRQ_SKEW], &d[FRQ_KURT]);
1011   moments_destroy (m);
1012
1013   /* Formulas below are taken from _SPSS Statistical Algorithms_. */
1014   d[FRQ_MIN] = ft->valid[0].value.f;
1015   d[FRQ_MAX] = ft->valid[ft->n_valid - 1].value.f;
1016   d[FRQ_MODE] = X_mode;
1017   d[FRQ_RANGE] = d[FRQ_MAX] - d[FRQ_MIN];
1018   d[FRQ_SUM] = d[FRQ_MEAN] * W;
1019   d[FRQ_STDDEV] = sqrt (d[FRQ_VARIANCE]);
1020   d[FRQ_SEMEAN] = d[FRQ_STDDEV] / sqrt (W);
1021   d[FRQ_SESKEW] = calc_seskew (W);
1022   d[FRQ_SEKURT] = calc_sekurt (W);
1023 }
1024
1025 /* Displays a table of all the statistics requested for variable V. */
1026 static void
1027 dump_statistics (const struct frq_proc *frq, const struct var_freqs *vf,
1028                  const struct variable *wv)
1029 {
1030   const struct fmt_spec *wfmt = wv ? var_get_print_format (wv) : &F_8_0;
1031   const struct freq_tab *ft = &vf->tab;
1032   double stat_value[FRQ_N_STATS];
1033   struct tab_table *t;
1034   int i, r;
1035
1036   if (var_is_alpha (vf->var))
1037     return;
1038
1039   if (ft->n_valid == 0)
1040     {
1041       msg (SW, _("No valid data for variable %s; statistics not displayed."),
1042            var_get_name (vf->var));
1043       return;
1044     }
1045   calc_stats (vf, stat_value);
1046   calc_percentiles (frq, vf);
1047
1048   t = tab_create (3, frq->n_stats + frq->n_show_percentiles + 2);
1049
1050   tab_box (t, TAL_1, TAL_1, -1, -1 , 0 , 0 , 2, tab_nr(t) - 1) ;
1051
1052
1053   tab_vline (t, TAL_1 , 2, 0, tab_nr(t) - 1);
1054   tab_vline (t, TAL_GAP , 1, 0, tab_nr(t) - 1 ) ;
1055
1056   r=2; /* N missing and N valid are always dumped */
1057
1058   for (i = 0; i < FRQ_N_STATS; i++)
1059     if (frq->stats & BIT_INDEX (i))
1060       {
1061         tab_text (t, 0, r, TAB_LEFT | TAT_TITLE,
1062                       gettext (st_name[i].s10));
1063         tab_double (t, 2, r, TAB_NONE, stat_value[i], NULL);
1064         r++;
1065       }
1066
1067   tab_text (t, 0, 0, TAB_LEFT | TAT_TITLE, _("N"));
1068   tab_text (t, 1, 0, TAB_LEFT | TAT_TITLE, _("Valid"));
1069   tab_text (t, 1, 1, TAB_LEFT | TAT_TITLE, _("Missing"));
1070
1071   tab_double (t, 2, 0, TAB_NONE, ft->valid_cases, wfmt);
1072   tab_double (t, 2, 1, TAB_NONE, ft->total_cases - ft->valid_cases, wfmt);
1073
1074   for (i = 0; i < frq->n_percentiles; i++, r++)
1075     {
1076       struct percentile *pc = &frq->percentiles[i];
1077
1078       if (!pc->show)
1079         continue;
1080
1081       if ( i == 0 )
1082         {
1083           tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, _("Percentiles"));
1084         }
1085
1086       if (pc->p == 0.5)
1087         tab_text (t, 1, r, TAB_LEFT, _("50 (Median)"));
1088       else
1089         tab_fixed (t, 1, r, TAB_LEFT, pc->p * 100, 3, 0);
1090       tab_double (t, 2, r, TAB_NONE, pc->value,
1091                   var_get_print_format (vf->var));
1092     }
1093
1094   tab_title (t, "%s", var_to_string (vf->var));
1095
1096   tab_submit (t);
1097 }
1098
1099 static double
1100 calculate_iqr (const struct frq_proc *frq)
1101 {
1102   double q1 = SYSMIS;
1103   double q3 = SYSMIS;
1104   int i;
1105
1106   for (i = 0; i < frq->n_percentiles; i++)
1107     {
1108       struct percentile *pc = &frq->percentiles[i];
1109
1110       if (fabs (0.25 - pc->p) < DBL_EPSILON)
1111         q1 = pc->value;
1112       else if (fabs (0.75 - pc->p) < DBL_EPSILON)
1113         q3 = pc->value;
1114     }
1115
1116   return q1 == SYSMIS || q3 == SYSMIS ? SYSMIS : q3 - q1;
1117 }
1118
1119 static bool
1120 chart_includes_value (const struct frq_chart *chart,
1121                       const struct variable *var,
1122                       const union value *value)
1123 {
1124   if (!chart->include_missing && var_is_value_missing (var, value, MV_ANY))
1125     return false;
1126
1127   if (var_is_numeric (var)
1128       && ((chart->x_min != SYSMIS && value->f < chart->x_min)
1129           || (chart->x_max != SYSMIS && value->f > chart->x_max)))
1130     return false;
1131
1132   return true;
1133 }
1134
1135 /* Create a gsl_histogram from a freq_tab */
1136 struct histogram *
1137 freq_tab_to_hist (const struct frq_proc *frq, const struct freq_tab *ft,
1138                   const struct variable *var)
1139 {
1140   double x_min, x_max, valid_freq;
1141   int i;
1142
1143   struct histogram *histogram;
1144   double iqr;
1145   int bins;
1146
1147   /* Find out the extremes of the x value, within the range to be included in
1148      the histogram, and sum the total frequency of those values. */
1149   x_min = DBL_MAX;
1150   x_max = -DBL_MAX;
1151   valid_freq = 0;
1152   for (i = 0; i < ft->n_valid; i++)
1153     {
1154       const struct freq *f = &ft->valid[i];
1155       if (chart_includes_value (frq->hist, var, &f->value))
1156         {
1157           x_min = MIN (x_min, f->value.f);
1158           x_max = MAX (x_max, f->value.f);
1159           valid_freq += f->count;
1160         }
1161     }
1162
1163   /* Freedman-Diaconis' choice of bin width. */
1164   iqr = calculate_iqr (frq);
1165   if (iqr != SYSMIS)
1166     {
1167       double bin_width = 2 * iqr / pow (valid_freq, 1.0 / 3.0);
1168       bins = (x_max - x_min) / bin_width;
1169       if (bins < 5)
1170         bins = 5;
1171       else if (bins > 400)
1172         bins = 400;
1173     }
1174   else
1175     bins = 5;
1176
1177   histogram = histogram_create (bins, x_min, x_max);
1178   for (i = 0; i < ft->n_valid; i++)
1179     {
1180       const struct freq *f = &ft->valid[i];
1181       if (chart_includes_value (frq->hist, var, &f->value))
1182         histogram_add (histogram, f->value.f, f->count);
1183     }
1184
1185   return histogram;
1186 }
1187
1188 static int
1189 add_slice (const struct frq_chart *pie, const struct freq *freq,
1190            const struct variable *var, struct slice *slice)
1191 {
1192   if (chart_includes_value (pie, var, &freq->value))
1193     {
1194       ds_init_empty (&slice->label);
1195       var_append_value_name (var, &freq->value, &slice->label);
1196       slice->magnitude = freq->count;
1197       return 1;
1198     }
1199   else
1200     return 0;
1201 }
1202
1203 /* Allocate an array of slices and fill them from the data in frq_tab
1204    n_slices will contain the number of slices allocated.
1205    The caller is responsible for freeing slices
1206 */
1207 static struct slice *
1208 freq_tab_to_slice_array(const struct frq_chart *pie,
1209                         const struct freq_tab *frq_tab,
1210                         const struct variable *var,
1211                         int *n_slicesp)
1212 {
1213   struct slice *slices;
1214   int n_slices;
1215   int i;
1216
1217   slices = xnmalloc (frq_tab->n_valid + frq_tab->n_missing, sizeof *slices);
1218   n_slices = 0;
1219
1220   for (i = 0; i < frq_tab->n_valid; i++)
1221     n_slices += add_slice (pie, &frq_tab->valid[i], var, &slices[n_slices]);
1222   for (i = 0; i < frq_tab->n_missing; i++)
1223     n_slices += add_slice (pie, &frq_tab->missing[i], var, &slices[n_slices]);
1224
1225   *n_slicesp = n_slices;
1226   return slices;
1227 }
1228
1229
1230
1231
1232 static void
1233 do_piechart(const struct frq_chart *pie, const struct variable *var,
1234             const struct freq_tab *frq_tab)
1235 {
1236   struct slice *slices;
1237   int n_slices, i;
1238
1239   slices = freq_tab_to_slice_array (pie, frq_tab, var, &n_slices);
1240
1241   if (n_slices < 2)
1242     msg (SW, _("Omitting pie chart for %s, which has only %d unique values."),
1243          var_get_name (var), n_slices);
1244   else if (n_slices > 50)
1245     msg (SW, _("Omitting pie chart for %s, which has over 50 unique values."),
1246          var_get_name (var));
1247   else
1248     chart_item_submit (piechart_create (var_to_string(var), slices, n_slices));
1249
1250   for (i = 0; i < n_slices; i++)
1251     ds_destroy (&slices[i].label);
1252   free (slices);
1253 }
1254
1255
1256 /*
1257    Local Variables:
1258    mode: c
1259    End:
1260 */