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