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