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