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