FREQUENCIES: Move file-scope variables for percentiles into struct frq_proc.
[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/dictionary.h"
27 #include "data/format.h"
28 #include "data/procedure.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   double x1;       /* The datum value <= the percentile */
129   double x2;       /* The datum value >= the percentile */
130   int flag;
131   int flag2;       /* Set to 1 if this percentile value has been found */
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 /* Statistics; number of statistics. */
147 static unsigned long stats;
148 static int n_stats;
149
150 struct frq_chart
151   {
152     double x_min;               /* X axis minimum value. */
153     double x_max;               /* X axis maximum value. */
154     int y_scale;                /* Y axis scale: FRQ_FREQ or FRQ_PERCENT. */
155
156     /* Histograms only. */
157     double y_max;               /* Y axis maximum value. */
158     bool draw_normal;           /* Whether to draw normal curve. */
159
160     /* Pie charts only. */
161     bool include_missing;       /* Whether to include missing values. */
162   };
163
164 /* Histogram and pie chart settings. */
165 static struct frq_chart hist, pie;
166
167 /* Parsed command. */
168 static struct cmd_frequencies cmd;
169
170 /* Frequency tables. */
171
172 /* Entire frequency table. */
173 struct freq_tab
174   {
175     struct hmap data;           /* Hash table for accumulating counts. */
176     struct freq *valid;         /* Valid freqs. */
177     int n_valid;                /* Number of total freqs. */
178     const struct dictionary *dict; /* Source of entries in the table. */
179
180     struct freq *missing;       /* Missing freqs. */
181     int n_missing;              /* Number of missing freqs. */
182
183     /* Statistics. */
184     double total_cases;         /* Sum of weights of all cases. */
185     double valid_cases;         /* Sum of weights of valid cases. */
186   };
187
188 /* Per-variable frequency data. */
189 struct var_freqs
190   {
191     struct variable *var;
192
193     /* Freqency table. */
194     struct freq_tab tab;        /* Frequencies table to use. */
195
196     /* Percentiles. */
197     int n_groups;               /* Number of groups. */
198     double *groups;             /* Groups. */
199
200     /* Statistics. */
201     double stat[FRQ_N_STATS];
202
203     /* Variable attributes. */
204     int width;
205     struct fmt_spec print;
206   };
207
208 struct frq_proc
209   {
210     struct pool *pool;
211
212     struct var_freqs *vars;
213     size_t n_vars;
214
215     struct percentile *percentiles;
216     int n_percentiles, n_show_percentiles;
217   };
218
219 static void determine_charts (void);
220
221 static void calc_stats (const struct frq_proc *, const struct var_freqs *,
222                         double d[FRQ_N_STATS]);
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 (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 algo_compare_func compare_value_numeric_a, compare_value_alpha_a;
237 static algo_compare_func compare_value_numeric_d, compare_value_alpha_d;
238 static algo_compare_func compare_freq_numeric_a, compare_freq_alpha_a;
239 static algo_compare_func compare_freq_numeric_d, compare_freq_alpha_d;
240
241 static void add_percentile (struct frq_proc *, double x, bool show,
242                             size_t *allocated_percentiles);
243
244 static void do_piechart(const struct variable *var,
245                         const struct freq_tab *frq_tab);
246
247 struct histogram *freq_tab_to_hist(const struct frq_proc *,
248                                    const struct freq_tab *,
249                                    const struct variable *);
250 \f
251 /* Parser and outline. */
252
253 int
254 cmd_frequencies (struct lexer *lexer, struct dataset *ds)
255 {
256   struct frq_proc frq;
257   struct casegrouper *grouper;
258   struct casereader *input, *group;
259   size_t allocated_percentiles;
260   bool ok;
261   int i;
262
263   frq.pool = pool_create ();
264
265   frq.vars = NULL;
266   frq.n_vars = 0;
267
268   frq.percentiles = NULL;
269   frq.n_percentiles = 0;
270   frq.n_show_percentiles = 0;
271
272   allocated_percentiles = 0;
273
274   if (!parse_frequencies (lexer, ds, &cmd, &frq))
275     {
276       pool_destroy (frq.pool);
277       return CMD_FAILURE;
278     }
279
280   /* Figure out statistics to calculate. */
281   stats = 0;
282   if (cmd.a_statistics[FRQ_ST_DEFAULT] || !cmd.sbc_statistics)
283     stats |= FRQ_DEFAULT;
284   if (cmd.a_statistics[FRQ_ST_ALL])
285     stats |= FRQ_ALL;
286   if (cmd.sort != FRQ_AVALUE && cmd.sort != FRQ_DVALUE)
287     stats &= ~BIT_INDEX (FRQ_MEDIAN);
288   for (i = 0; i < FRQ_N_STATS; i++)
289     if (cmd.a_statistics[st_name[i].st_indx])
290       stats |= BIT_INDEX (i);
291   if (stats & FRQ_KURT)
292     stats |= BIT_INDEX (FRQ_SEKURT);
293   if (stats & FRQ_SKEW)
294     stats |= BIT_INDEX (FRQ_SESKEW);
295
296   /* Calculate n_stats. */
297   n_stats = 0;
298   for (i = 0; i < FRQ_N_STATS; i++)
299     if ((stats & BIT_INDEX (i)))
300       n_stats++;
301
302   /* Charting. */
303   determine_charts ();
304   if (cmd.sbc_histogram || cmd.sbc_piechart || cmd.sbc_ntiles)
305     cmd.sort = FRQ_AVALUE;
306
307   /* Work out what percentiles need to be calculated */
308   if ( cmd.sbc_percentiles )
309     {
310       for ( i = 0 ; i < MAXLISTS ; ++i )
311         {
312           int pl;
313           subc_list_double *ptl_list = &cmd.dl_percentiles[i];
314           for ( pl = 0 ; pl < subc_list_double_count(ptl_list); ++pl)
315             add_percentile (&frq, subc_list_double_at(ptl_list, pl) / 100.0,
316                             true, &allocated_percentiles);
317         }
318     }
319   if ( cmd.sbc_ntiles )
320     {
321       for ( i = 0 ; i < cmd.sbc_ntiles ; ++i )
322         {
323           int j;
324           for (j = 0; j <= cmd.n_ntiles[i]; ++j )
325             add_percentile (&frq, j / (double) cmd.n_ntiles[i], true,
326                             &allocated_percentiles);
327         }
328     }
329   if (stats & BIT_INDEX (FRQ_MEDIAN))
330     {
331       /* Treat the median as the 50% percentile.
332          We output it in the percentiles table as "50 (Median)." */
333       add_percentile (&frq, 0.5, true, &allocated_percentiles);
334       stats &= ~BIT_INDEX (FRQ_MEDIAN);
335       n_stats--;
336     }
337   if (cmd.sbc_histogram)
338     {
339       add_percentile (&frq, 0.25, false, &allocated_percentiles);
340       add_percentile (&frq, 0.75, false, &allocated_percentiles);
341     }
342
343   /* Do it! */
344   input = casereader_create_filter_weight (proc_open (ds), dataset_dict (ds),
345                                            NULL, NULL);
346   grouper = casegrouper_create_splits (input, dataset_dict (ds));
347   for (; casegrouper_get_next_group (grouper, &group);
348        casereader_destroy (group))
349     {
350       struct ccase *c;
351
352       precalc (&frq, group, ds);
353       for (; (c = casereader_read (group)) != NULL; case_unref (c))
354         calc (&frq, c, ds);
355       postcalc (&frq, ds);
356     }
357   ok = casegrouper_destroy (grouper);
358   ok = proc_commit (ds) && ok;
359
360   free_frequencies(&cmd);
361
362   pool_destroy (frq.pool);
363   free (frq.vars);
364   free (frq.percentiles);
365
366   return ok ? CMD_SUCCESS : CMD_CASCADING_FAILURE;
367 }
368
369 /* Figure out which charts the user requested.  */
370 static void
371 determine_charts (void)
372 {
373   if (cmd.sbc_barchart)
374     msg (SW, _("Bar charts are not implemented."));
375
376   if (cmd.sbc_histogram)
377     {
378       hist.x_min = cmd.hi_min;
379       hist.x_max = cmd.hi_max;
380       hist.y_scale = cmd.hi_scale;
381       hist.y_max = cmd.hi_scale == FRQ_FREQ ? cmd.hi_freq : cmd.hi_pcnt;
382       hist.draw_normal = cmd.hi_norm != FRQ_NONORMAL;
383       hist.include_missing = false;
384
385       if (hist.x_min != SYSMIS && hist.x_max != SYSMIS
386           && hist.x_min >= hist.x_max)
387         {
388           msg (SE, _("MAX for histogram must be greater than or equal to MIN, "
389                      "but MIN was specified as %.15g and MAX as %.15g.  "
390                      "MIN and MAX will be ignored."), hist.x_min, hist.x_max);
391           hist.x_min = hist.x_max = SYSMIS;
392         }
393     }
394
395   if (cmd.sbc_piechart)
396     {
397       pie.x_min = cmd.pie_min;
398       pie.x_max = cmd.pie_max;
399       pie.y_scale = cmd.pie_scale;
400       pie.include_missing = cmd.pie_missing == FRQ_MISSING;
401
402       if (pie.x_min != SYSMIS && pie.x_max != SYSMIS
403           && pie.x_min >= pie.x_max)
404         {
405           msg (SE, _("MAX for pie chart 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."), pie.x_min, pie.x_max);
408           pie.x_min = pie.x_max = SYSMIS;
409         }
410     }
411
412 }
413
414 /* Add data from case C to the frequency table. */
415 static void
416 calc (struct frq_proc *frq, const struct ccase *c, const struct dataset *ds)
417 {
418   double weight = dict_get_case_weight (dataset_dict (ds), c, NULL);
419   size_t i;
420
421   for (i = 0; i < frq->n_vars; i++)
422     {
423       struct var_freqs *vf = &frq->vars[i];
424       const union value *value = case_data (c, vf->var);
425       size_t hash = value_hash (value, vf->width, 0);
426       struct freq *f;
427
428       f = freq_hmap_search (&vf->tab.data, value, vf->width, hash);
429       if (f == NULL)
430         f = freq_hmap_insert (&vf->tab.data, value, vf->width, hash);
431
432       f->count += weight;
433     }
434 }
435
436 /* Prepares each variable that is the target of FREQUENCIES by setting
437    up its hash table. */
438 static void
439 precalc (struct frq_proc *frq, struct casereader *input, struct dataset *ds)
440 {
441   struct ccase *c;
442   size_t i;
443
444   c = casereader_peek (input, 0);
445   if (c != NULL)
446     {
447       output_split_file_values (ds, c);
448       case_unref (c);
449     }
450
451   for (i = 0; i < frq->n_vars; i++)
452     hmap_init (&frq->vars[i].tab.data);
453 }
454
455 /* Finishes up with the variables after frequencies have been
456    calculated.  Displays statistics, percentiles, ... */
457 static void
458 postcalc (struct frq_proc *frq, const struct dataset *ds)
459 {
460   const struct dictionary *dict = dataset_dict (ds);
461   const struct variable *wv = dict_get_weight (dict);
462   size_t i;
463
464   for (i = 0; i < frq->n_vars; i++)
465     {
466       struct var_freqs *vf = &frq->vars[i];
467       int n_categories;
468
469       postprocess_freq_tab (vf);
470
471       /* Frequencies tables. */
472       n_categories = vf->tab.n_valid + vf->tab.n_missing;
473       if  (cmd.table == FRQ_TABLE
474            || (cmd.table == FRQ_LIMIT && n_categories <= cmd.limit))
475         dump_freq_table (vf, wv);
476
477       /* Statistics. */
478       if (n_stats)
479         dump_statistics (frq, vf, wv);
480
481       if (cmd.sbc_histogram && var_is_numeric (vf->var) && vf->tab.n_valid > 0)
482         {
483           double d[FRQ_N_STATS];
484           struct histogram *histogram;
485
486           calc_stats (frq, vf, d);
487
488           histogram = freq_tab_to_hist (frq, &vf->tab, vf->var);
489
490           chart_item_submit (histogram_chart_create (
491                                histogram->gsl_hist, var_to_string(vf->var),
492                                vf->tab.valid_cases,
493                                d[FRQ_MEAN],
494                                d[FRQ_STDDEV],
495                                hist.draw_normal));
496
497           statistic_destroy (&histogram->parent);
498         }
499
500       if (cmd.sbc_piechart)
501         do_piechart(vf->var, &vf->tab);
502
503       cleanup_freq_tab (vf);
504
505     }
506 }
507
508 /* Returns the comparison function that should be used for
509    sorting a frequency table by FRQ_SORT using VAL_TYPE
510    values. */
511 static algo_compare_func *
512 get_freq_comparator (int frq_sort, enum val_type val_type)
513 {
514   bool is_numeric = val_type == VAL_NUMERIC;
515   switch (frq_sort)
516     {
517     case FRQ_AVALUE:
518       return is_numeric ? compare_value_numeric_a : compare_value_alpha_a;
519     case FRQ_DVALUE:
520       return is_numeric ? compare_value_numeric_d : compare_value_alpha_d;
521     case FRQ_AFREQ:
522       return is_numeric ? compare_freq_numeric_a : compare_freq_alpha_a;
523     case FRQ_DFREQ:
524       return is_numeric ? compare_freq_numeric_d : compare_freq_alpha_d;
525     default:
526       NOT_REACHED ();
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 /* Summarizes the frequency table data for variable V. */
542 static void
543 postprocess_freq_tab (struct var_freqs *vf)
544 {
545   struct freq_tab *ft = &vf->tab;
546   algo_compare_func *compare;
547   size_t count;
548   struct freq *freqs, *f;
549   size_t i;
550
551   /* Extract data from hash table. */
552   count = hmap_count (&ft->data);
553   freqs = freq_hmap_extract (&ft->data);
554
555   /* Put data into ft. */
556   ft->valid = freqs;
557   ft->n_valid = partition (freqs, count, sizeof *freqs, not_missing, vf->var);
558   ft->missing = freqs + ft->n_valid;
559   ft->n_missing = count - ft->n_valid;
560
561   /* Sort data. */
562   compare = get_freq_comparator (cmd.sort, var_get_type (vf->var));
563   sort (ft->valid, ft->n_valid, sizeof *ft->valid, compare, vf);
564   sort (ft->missing, ft->n_missing, sizeof *ft->missing, compare, vf);
565
566   /* Summary statistics. */
567   ft->valid_cases = 0.0;
568   for(i = 0 ;  i < ft->n_valid ; ++i )
569     {
570       f = &ft->valid[i];
571       ft->valid_cases += f->count;
572
573     }
574
575   ft->total_cases = ft->valid_cases ;
576   for(i = 0 ;  i < ft->n_missing ; ++i )
577     {
578       f = &ft->missing[i];
579       ft->total_cases += f->count;
580     }
581
582 }
583
584 /* Frees the frequency table for variable V. */
585 static void
586 cleanup_freq_tab (struct var_freqs *vf)
587 {
588   free (vf->tab.valid);
589   freq_hmap_destroy (&vf->tab.data, vf->width);
590 }
591
592 /* Parses the VARIABLES subcommand. */
593 static int
594 frq_custom_variables (struct lexer *lexer, struct dataset *ds,
595                       struct cmd_frequencies *cmd UNUSED, void *frq_ UNUSED)
596 {
597   struct frq_proc *frq = frq_;
598   struct variable **vars;
599   size_t n_vars;
600   size_t i;
601
602   lex_match (lexer, '=');
603   if (lex_token (lexer) != T_ALL
604       && (lex_token (lexer) != T_ID
605           || dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) == NULL))
606     return 2;
607
608   /* Get list of current variables, to avoid duplicates. */
609   vars = xmalloc (frq->n_vars * sizeof *vars);
610   n_vars = frq->n_vars;
611   for (i = 0; i < frq->n_vars; i++)
612     vars[i] = frq->vars[i].var;
613
614   if (!parse_variables (lexer, dataset_dict (ds), &vars, &n_vars,
615                         PV_APPEND | PV_NO_SCRATCH))
616     return 0;
617
618   frq->vars = xrealloc (frq->vars, n_vars * sizeof *frq->vars);
619   for (i = frq->n_vars; i < n_vars; i++)
620     {
621       struct variable *var = vars[i];
622       struct var_freqs *vf = &frq->vars[i];
623
624       vf->var = var;
625       vf->tab.valid = vf->tab.missing = NULL;
626       vf->tab.dict = dataset_dict (ds);
627       vf->n_groups = 0;
628       vf->groups = NULL;
629       vf->width = var_get_width (var);
630       vf->print = *var_get_print_format (var);
631     }
632   frq->n_vars = n_vars;
633
634   free (vars);
635
636   return 1;
637 }
638
639 /* Parses the GROUPED subcommand, setting the n_grouped, grouped
640    fields of specified variables. */
641 static int
642 frq_custom_grouped (struct lexer *lexer, struct dataset *ds, struct cmd_frequencies *cmd UNUSED, void *frq_ UNUSED)
643 {
644   struct frq_proc *frq = frq_;
645
646   lex_match (lexer, '=');
647   if ((lex_token (lexer) == T_ID && dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) != NULL)
648       || lex_token (lexer) == T_ID)
649     for (;;)
650       {
651         size_t i;
652
653         /* Max, current size of list; list itself. */
654         int nl, ml;
655         double *dl;
656
657         /* Variable list. */
658         size_t n;
659         const struct variable **v;
660
661         if (!parse_variables_const (lexer, dataset_dict (ds), &v, &n,
662                               PV_NO_DUPLICATE | PV_NUMERIC))
663           return 0;
664         if (lex_match (lexer, '('))
665           {
666             nl = ml = 0;
667             dl = NULL;
668             while (lex_integer (lexer))
669               {
670                 if (nl >= ml)
671                   {
672                     ml += 16;
673                     dl = pool_nrealloc (frq->pool, dl, ml, sizeof *dl);
674                   }
675                 dl[nl++] = lex_tokval (lexer);
676                 lex_get (lexer);
677                 lex_match (lexer, ',');
678               }
679             /* Note that nl might still be 0 and dl might still be
680                NULL.  That's okay. */
681             if (!lex_match (lexer, ')'))
682               {
683                 free (v);
684                 msg (SE, _("`)' expected after GROUPED interval list."));
685                 return 0;
686               }
687           }
688         else
689           {
690             nl = 0;
691             dl = NULL;
692           }
693
694         for (i = 0; i < n; i++)
695           {
696             size_t j;
697
698             for (j = 0; j < frq->n_vars; j++)
699               {
700                 struct var_freqs *vf = &frq->vars[j];
701                 if (vf->var == v[i])
702                   {
703                     if (vf->groups != NULL)
704                       msg (SE, _("Variables %s specified multiple times on "
705                                  "GROUPED subcommand."), var_get_name (v[i]));
706                     else
707                       {
708                         vf->n_groups = nl;
709                         vf->groups = dl;
710                       }
711                     goto found;
712                   }
713               }
714             msg (SE, _("Variables %s specified on GROUPED but not on "
715                        "VARIABLES."), var_get_name (v[i]));
716
717           found:;
718           }
719
720         free (v);
721         if (!lex_match (lexer, '/'))
722           break;
723         if ((lex_token (lexer) != T_ID || dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) != NULL)
724             && lex_token (lexer) != T_ALL)
725           {
726             lex_put_back (lexer, '/');
727             break;
728           }
729       }
730
731   return 1;
732 }
733
734 /* Adds X to the list of percentiles, keeping the list in proper
735    order.  If SHOW is true, the percentile will be shown in the statistics
736    box, otherwise it will be hidden. */
737 static void
738 add_percentile (struct frq_proc *frq, double x, bool show,
739                 size_t *allocated_percentiles)
740 {
741   int i;
742
743   /* Do nothing if it's already in the list */
744   for (i = 0; i < frq->n_percentiles; i++)
745     {
746       struct percentile *pc = &frq->percentiles[i];
747
748       if ( fabs(x - pc->p) < DBL_EPSILON )
749         {
750           if (show && !pc->show)
751             {
752               frq->n_show_percentiles++;
753               pc->show = true;
754             }
755           return;
756         }
757
758       if (x < pc->p)
759         break;
760     }
761
762   if (frq->n_percentiles >= *allocated_percentiles)
763     frq->percentiles = x2nrealloc (frq->percentiles, allocated_percentiles,
764                                    sizeof *frq->percentiles);
765   insert_element (frq->percentiles, frq->n_percentiles,
766                   sizeof *frq->percentiles, i);
767   frq->percentiles[i].p = x;
768   frq->percentiles[i].show = show;
769   frq->n_percentiles++;
770   if (show)
771     frq->n_show_percentiles++;
772 }
773
774 /* Comparison functions. */
775
776 /* Ascending numeric compare of values. */
777 static int
778 compare_value_numeric_a (const void *a_, const void *b_,
779                          const void *vf_ UNUSED)
780 {
781   const struct freq *a = a_;
782   const struct freq *b = b_;
783
784   if (a->value.f > b->value.f)
785     return 1;
786   else if (a->value.f < b->value.f)
787     return -1;
788   else
789     return 0;
790 }
791
792 /* Ascending string compare of values. */
793 static int
794 compare_value_alpha_a (const void *a_, const void *b_, const void *vf_)
795 {
796   const struct freq *a = a_;
797   const struct freq *b = b_;
798   const struct var_freqs *vf = vf_;
799
800   return value_compare_3way (&a->value, &b->value, vf->width);
801 }
802
803 /* Descending numeric compare of values. */
804 static int
805 compare_value_numeric_d (const void *a, const void *b, const void *vf_ UNUSED)
806 {
807   return -compare_value_numeric_a (a, b, vf_);
808 }
809
810 /* Descending string compare of values. */
811 static int
812 compare_value_alpha_d (const void *a, const void *b, const void *vf_)
813 {
814   return -compare_value_alpha_a (a, b, vf_);
815 }
816
817 /* Ascending numeric compare of frequency;
818    secondary key on ascending numeric value. */
819 static int
820 compare_freq_numeric_a (const void *a_, const void *b_, const void *vf_ UNUSED)
821 {
822   const struct freq *a = a_;
823   const struct freq *b = b_;
824
825   if (a->count > b->count)
826     return 1;
827   else if (a->count < b->count)
828     return -1;
829
830   if (a->value.f > b->value.f)
831     return 1;
832   else if (a->value.f < b->value.f)
833     return -1;
834   else
835     return 0;
836 }
837
838 /* Ascending numeric compare of frequency;
839    secondary key on ascending string value. */
840 static int
841 compare_freq_alpha_a (const void *a_, const void *b_, const void *vf_)
842 {
843   const struct freq *a = a_;
844   const struct freq *b = b_;
845   const struct var_freqs *vf = vf_;
846
847   if (a->count > b->count)
848     return 1;
849   else if (a->count < b->count)
850     return -1;
851   else
852     return value_compare_3way (&a->value, &b->value, vf->width);
853 }
854
855 /* Descending numeric compare of frequency;
856    secondary key on ascending numeric value. */
857 static int
858 compare_freq_numeric_d (const void *a_, const void *b_, const void *vf_ UNUSED)
859 {
860   const struct freq *a = a_;
861   const struct freq *b = b_;
862
863   if (a->count > b->count)
864     return -1;
865   else if (a->count < b->count)
866     return 1;
867
868   if (a->value.f > b->value.f)
869     return 1;
870   else if (a->value.f < b->value.f)
871     return -1;
872   else
873     return 0;
874 }
875
876 /* Descending numeric compare of frequency;
877    secondary key on ascending string value. */
878 static int
879 compare_freq_alpha_d (const void *a_, const void *b_, const void *vf_)
880 {
881   const struct freq *a = a_;
882   const struct freq *b = b_;
883   const struct var_freqs *vf = vf_;
884
885   if (a->count > b->count)
886     return -1;
887   else if (a->count < b->count)
888     return 1;
889   else
890     return value_compare_3way (&a->value, &b->value, vf->width);
891 }
892 \f
893 /* Frequency table display. */
894
895 /* Displays a full frequency table for variable V. */
896 static void
897 dump_freq_table (const struct var_freqs *vf, const struct variable *wv)
898 {
899   const struct fmt_spec *wfmt = wv ? var_get_print_format (wv) : &F_8_0;
900   const struct freq_tab *ft = &vf->tab;
901   int n_categories;
902   struct freq *f;
903   struct tab_table *t;
904   int r, x;
905   double cum_total = 0.0;
906   double cum_freq = 0.0;
907
908   static const char *headings[] = {
909     N_("Value Label"),
910     N_("Value"),
911     N_("Frequency"),
912     N_("Percent"),
913     N_("Valid Percent"),
914     N_("Cum Percent")
915   };
916
917   n_categories = ft->n_valid + ft->n_missing;
918   t = tab_create (6, n_categories + 2);
919   tab_headers (t, 0, 0, 1, 0);
920
921   for (x = 0; x < 6; x++)
922     tab_text (t, x, 0, TAB_CENTER | TAT_TITLE, gettext (headings[x]));
923
924   r = 1;
925   for (f = ft->valid; f < ft->missing; f++)
926     {
927       const char *label;
928       double percent, valid_percent;
929
930       cum_freq += f->count;
931
932       percent = f->count / ft->total_cases * 100.0;
933       valid_percent = f->count / ft->valid_cases * 100.0;
934       cum_total += valid_percent;
935
936       label = var_lookup_value_label (vf->var, &f->value);
937       if (label != NULL)
938         tab_text (t, 0, r, TAB_LEFT, label);
939
940       tab_value (t, 1, r, TAB_NONE, &f->value, ft->dict, &vf->print);
941       tab_double (t, 2, r, TAB_NONE, f->count, wfmt);
942       tab_double (t, 3, r, TAB_NONE, percent, NULL);
943       tab_double (t, 4, r, TAB_NONE, valid_percent, NULL);
944       tab_double (t, 5, r, TAB_NONE, cum_total, NULL);
945       r++;
946     }
947   for (; f < &ft->valid[n_categories]; f++)
948     {
949       const char *label;
950
951       cum_freq += f->count;
952
953       label = var_lookup_value_label (vf->var, &f->value);
954       if (label != NULL)
955         tab_text (t, 0, r, TAB_LEFT, label);
956
957       tab_value (t, 1, r, TAB_NONE, &f->value, ft->dict, &vf->print);
958       tab_double (t, 2, r, TAB_NONE, f->count, wfmt);
959       tab_double (t, 3, r, TAB_NONE,
960                      f->count / ft->total_cases * 100.0, NULL);
961       tab_text (t, 4, r, TAB_NONE, _("Missing"));
962       r++;
963     }
964
965   tab_box (t, TAL_1, TAL_1, -1, TAL_1, 0, 0, 5, r);
966   tab_hline (t, TAL_2, 0, 5, 1);
967   tab_hline (t, TAL_2, 0, 5, r);
968   tab_joint_text (t, 0, r, 1, r, TAB_RIGHT | TAT_TITLE, _("Total"));
969   tab_vline (t, TAL_0, 1, r, r);
970   tab_double (t, 2, r, TAB_NONE, cum_freq, wfmt);
971   tab_fixed (t, 3, r, TAB_NONE, 100.0, 5, 1);
972   tab_fixed (t, 4, r, TAB_NONE, 100.0, 5, 1);
973
974   tab_title (t, "%s", var_to_string (vf->var));
975   tab_submit (t);
976 }
977 \f
978 /* Statistical display. */
979
980 /* Calculates all the pertinent statistics for variable V, putting them in
981    array D[]. */
982 static void
983 calc_stats (const struct frq_proc *frq,
984             const struct var_freqs *vf, double d[FRQ_N_STATS])
985 {
986   const struct freq_tab *ft = &vf->tab;
987   double W = ft->valid_cases;
988   struct moments *m;
989   struct freq *f=0;
990   double prev_value;
991   int most_often;
992   double X_mode;
993
994   double rank;
995   int i = 0;
996   int idx;
997
998   /* Calculate percentiles. */
999
1000   assert (ft->n_valid > 0);
1001
1002   for (i = 0; i < frq->n_percentiles; i++)
1003     {
1004       struct percentile *pc = &frq->percentiles[i];
1005
1006       pc->flag = 0;
1007       pc->flag2 = 0;
1008     }
1009
1010   rank = 0;
1011   prev_value = SYSMIS;
1012   for (idx = 0; idx < ft->n_valid; ++idx)
1013     {
1014       f = &ft->valid[idx];
1015       rank += f->count ;
1016       for (i = 0; i < frq->n_percentiles; i++)
1017         {
1018           struct percentile *pc = &frq->percentiles[i];
1019           double tp;
1020
1021           if ( pc->flag2  ) continue ;
1022
1023           if ( settings_get_algorithm () != COMPATIBLE )
1024             tp =
1025               (ft->valid_cases - 1) *  pc->p;
1026           else
1027             tp =
1028               (ft->valid_cases + 1) *  pc->p - 1;
1029
1030           if ( pc->flag )
1031             {
1032               pc->x2 = f->value.f;
1033               pc->x1 = prev_value;
1034               pc->flag2 = 1;
1035               continue;
1036             }
1037
1038           if (rank >  tp )
1039           {
1040             if ( f->count > 1 && rank - (f->count - 1) > tp )
1041               {
1042                 pc->x2 = pc->x1 = f->value.f;
1043                 pc->flag2 = 1;
1044               }
1045             else
1046               {
1047                 pc->flag=1;
1048               }
1049
1050             continue;
1051           }
1052         }
1053       prev_value = f->value.f;
1054     }
1055
1056   for (i = 0; i < frq->n_percentiles; i++)
1057     {
1058       struct percentile *pc = &frq->percentiles[i];
1059
1060       /* Catches the case when p == 100% */
1061       if ( ! pc->flag2 )
1062         pc->x1 = pc->x2 = f->value.f;
1063
1064       /*
1065       printf("percentile %d (p==%.2f); X1 = %g; X2 = %g\n",
1066              i,pc->p,pc->x1,pc->x2);
1067       */
1068     }
1069
1070   for (i = 0; i < frq->n_percentiles; i++)
1071     {
1072       struct percentile *pc = &frq->percentiles[i];
1073       double s;
1074
1075       double dummy;
1076       if ( settings_get_algorithm () != COMPATIBLE )
1077         {
1078           s = modf((ft->valid_cases - 1) * pc->p , &dummy);
1079         }
1080       else
1081         {
1082           s = modf((ft->valid_cases + 1) * pc->p -1, &dummy);
1083         }
1084
1085       pc->value = pc->x1 + (pc->x2 - pc->x1) * s ;
1086     }
1087
1088
1089   /* Calculate the mode. */
1090   most_often = -1;
1091   X_mode = SYSMIS;
1092   for (f = ft->valid; f < ft->missing; f++)
1093     {
1094       if (most_often < f->count)
1095         {
1096           most_often = f->count;
1097           X_mode = f->value.f;
1098         }
1099       else if (most_often == f->count)
1100         {
1101           /* A duplicate mode is undefined.
1102              FIXME: keep track of *all* the modes. */
1103           X_mode = SYSMIS;
1104         }
1105     }
1106
1107   /* Calculate moments. */
1108   m = moments_create (MOMENT_KURTOSIS);
1109   for (f = ft->valid; f < ft->missing; f++)
1110     moments_pass_one (m, f->value.f, f->count);
1111   for (f = ft->valid; f < ft->missing; f++)
1112     moments_pass_two (m, f->value.f, f->count);
1113   moments_calculate (m, NULL, &d[FRQ_MEAN], &d[FRQ_VARIANCE],
1114                      &d[FRQ_SKEW], &d[FRQ_KURT]);
1115   moments_destroy (m);
1116
1117   /* Formulas below are taken from _SPSS Statistical Algorithms_. */
1118   d[FRQ_MIN] = ft->valid[0].value.f;
1119   d[FRQ_MAX] = ft->valid[ft->n_valid - 1].value.f;
1120   d[FRQ_MODE] = X_mode;
1121   d[FRQ_RANGE] = d[FRQ_MAX] - d[FRQ_MIN];
1122   d[FRQ_SUM] = d[FRQ_MEAN] * W;
1123   d[FRQ_STDDEV] = sqrt (d[FRQ_VARIANCE]);
1124   d[FRQ_SEMEAN] = d[FRQ_STDDEV] / sqrt (W);
1125   d[FRQ_SESKEW] = calc_seskew (W);
1126   d[FRQ_SEKURT] = calc_sekurt (W);
1127 }
1128
1129 /* Displays a table of all the statistics requested for variable V. */
1130 static void
1131 dump_statistics (const struct frq_proc *frq, const struct var_freqs *vf,
1132                  const struct variable *wv)
1133 {
1134   const struct fmt_spec *wfmt = wv ? var_get_print_format (wv) : &F_8_0;
1135   const struct freq_tab *ft = &vf->tab;
1136   double stat_value[FRQ_N_STATS];
1137   struct tab_table *t;
1138   int i, r;
1139
1140   if (var_is_alpha (vf->var))
1141     return;
1142
1143   if (ft->n_valid == 0)
1144     {
1145       msg (SW, _("No valid data for variable %s; statistics not displayed."),
1146            var_get_name (vf->var));
1147       return;
1148     }
1149   calc_stats (frq, vf, stat_value);
1150
1151   t = tab_create (3, n_stats + frq->n_show_percentiles + 2);
1152
1153   tab_box (t, TAL_1, TAL_1, -1, -1 , 0 , 0 , 2, tab_nr(t) - 1) ;
1154
1155
1156   tab_vline (t, TAL_1 , 2, 0, tab_nr(t) - 1);
1157   tab_vline (t, TAL_GAP , 1, 0, tab_nr(t) - 1 ) ;
1158
1159   r=2; /* N missing and N valid are always dumped */
1160
1161   for (i = 0; i < FRQ_N_STATS; i++)
1162     if (stats & BIT_INDEX (i))
1163       {
1164         tab_text (t, 0, r, TAB_LEFT | TAT_TITLE,
1165                       gettext (st_name[i].s10));
1166         tab_double (t, 2, r, TAB_NONE, stat_value[i], NULL);
1167         r++;
1168       }
1169
1170   tab_text (t, 0, 0, TAB_LEFT | TAT_TITLE, _("N"));
1171   tab_text (t, 1, 0, TAB_LEFT | TAT_TITLE, _("Valid"));
1172   tab_text (t, 1, 1, TAB_LEFT | TAT_TITLE, _("Missing"));
1173
1174   tab_double (t, 2, 0, TAB_NONE, ft->valid_cases, wfmt);
1175   tab_double (t, 2, 1, TAB_NONE, ft->total_cases - ft->valid_cases, wfmt);
1176
1177   for (i = 0; i < frq->n_percentiles; i++, r++)
1178     {
1179       struct percentile *pc = &frq->percentiles[i];
1180
1181       if (!pc->show)
1182         continue;
1183
1184       if ( i == 0 )
1185         {
1186           tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, _("Percentiles"));
1187         }
1188
1189       if (pc->p == 0.5)
1190         tab_text (t, 1, r, TAB_LEFT, _("50 (Median)"));
1191       else
1192         tab_fixed (t, 1, r, TAB_LEFT, pc->p * 100, 3, 0);
1193       tab_double (t, 2, r, TAB_NONE, pc->value,
1194                   var_get_print_format (vf->var));
1195     }
1196
1197   tab_title (t, "%s", var_to_string (vf->var));
1198
1199   tab_submit (t);
1200 }
1201
1202 static double
1203 calculate_iqr (const struct frq_proc *frq)
1204 {
1205   double q1 = SYSMIS;
1206   double q3 = SYSMIS;
1207   int i;
1208
1209   for (i = 0; i < frq->n_percentiles; i++)
1210     {
1211       struct percentile *pc = &frq->percentiles[i];
1212
1213       if (fabs (0.25 - pc->p) < DBL_EPSILON)
1214         q1 = pc->value;
1215       else if (fabs (0.75 - pc->p) < DBL_EPSILON)
1216         q3 = pc->value;
1217     }
1218
1219   return q1 == SYSMIS || q3 == SYSMIS ? SYSMIS : q3 - q1;
1220 }
1221
1222 static bool
1223 chart_includes_value (const struct frq_chart *chart,
1224                       const struct variable *var,
1225                       const union value *value)
1226 {
1227   if (!chart->include_missing && var_is_value_missing (var, value, MV_ANY))
1228     return false;
1229
1230   if (var_is_numeric (var)
1231       && ((chart->x_min != SYSMIS && value->f < chart->x_min)
1232           || (chart->x_max != SYSMIS && value->f > chart->x_max)))
1233     return false;
1234
1235   return true;
1236 }
1237
1238 /* Create a gsl_histogram from a freq_tab */
1239 struct histogram *
1240 freq_tab_to_hist (const struct frq_proc *frq, const struct freq_tab *ft,
1241                   const struct variable *var)
1242 {
1243   double x_min, x_max, valid_freq;
1244   int i;
1245
1246   struct histogram *histogram;
1247   double iqr;
1248   int bins;
1249
1250   /* Find out the extremes of the x value, within the range to be included in
1251      the histogram, and sum the total frequency of those values. */
1252   x_min = DBL_MAX;
1253   x_max = -DBL_MAX;
1254   valid_freq = 0;
1255   for (i = 0; i < ft->n_valid; i++)
1256     {
1257       const struct freq *frq = &ft->valid[i];
1258       if (chart_includes_value (&hist, var, &frq->value))
1259         {
1260           x_min = MIN (x_min, frq->value.f);
1261           x_max = MAX (x_max, frq->value.f);
1262           valid_freq += frq->count;
1263         }
1264     }
1265
1266   /* Freedman-Diaconis' choice of bin width. */
1267   iqr = calculate_iqr (frq);
1268   if (iqr != SYSMIS)
1269     {
1270       double bin_width = 2 * iqr / pow (valid_freq, 1.0 / 3.0);
1271       bins = (x_max - x_min) / bin_width;
1272       if (bins < 5)
1273         bins = 5;
1274       else if (bins > 400)
1275         bins = 400;
1276     }
1277   else
1278     bins = 5;
1279
1280   histogram = histogram_create (bins, x_min, x_max);
1281   for (i = 0; i < ft->n_valid; i++)
1282     {
1283       const struct freq *frq = &ft->valid[i];
1284       if (chart_includes_value (&hist, var, &frq->value))
1285         histogram_add (histogram, frq->value.f, frq->count);
1286     }
1287
1288   return histogram;
1289 }
1290
1291 static int
1292 add_slice (const struct freq *freq, const struct variable *var,
1293            struct slice *slice)
1294 {
1295   if (chart_includes_value (&pie, var, &freq->value))
1296     {
1297       ds_init_empty (&slice->label);
1298       var_append_value_name (var, &freq->value, &slice->label);
1299       slice->magnitude = freq->count;
1300       return 1;
1301     }
1302   else
1303     return 0;
1304 }
1305
1306 /* Allocate an array of slices and fill them from the data in frq_tab
1307    n_slices will contain the number of slices allocated.
1308    The caller is responsible for freeing slices
1309 */
1310 static struct slice *
1311 freq_tab_to_slice_array(const struct freq_tab *frq_tab,
1312                         const struct variable *var,
1313                         int *n_slicesp)
1314 {
1315   struct slice *slices;
1316   int n_slices;
1317   int i;
1318
1319   slices = xnmalloc (frq_tab->n_valid + frq_tab->n_missing, sizeof *slices);
1320   n_slices = 0;
1321
1322   for (i = 0; i < frq_tab->n_valid; i++)
1323     n_slices += add_slice (&frq_tab->valid[i], var, &slices[n_slices]);
1324   for (i = 0; i < frq_tab->n_missing; i++)
1325     n_slices += add_slice (&frq_tab->missing[i], var, &slices[n_slices]);
1326
1327   *n_slicesp = n_slices;
1328   return slices;
1329 }
1330
1331
1332
1333
1334 static void
1335 do_piechart(const struct variable *var, const struct freq_tab *frq_tab)
1336 {
1337   struct slice *slices;
1338   int n_slices, i;
1339
1340   slices = freq_tab_to_slice_array (frq_tab, var, &n_slices);
1341
1342   if (n_slices < 2)
1343     msg (SW, _("Omitting pie chart for %s, which has only %d unique values."),
1344          var_get_name (var), n_slices);
1345   else if (n_slices > 50)
1346     msg (SW, _("Omitting pie chart for %s, which has over 50 unique values."),
1347          var_get_name (var));
1348   else
1349     chart_item_submit (piechart_create (var_to_string(var), slices, n_slices));
1350
1351   for (i = 0; i < n_slices; i++)
1352     ds_destroy (&slices[i].label);
1353   free (slices);
1354 }
1355
1356
1357 /*
1358    Local Variables:
1359    mode: c
1360    End:
1361 */