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