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