d1052276dde5106954e76ed5d98d074ce749c580
[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 /*
18   TODO:
19
20   * Remember that histograms, bar charts need mean, stddev.
21 */
22
23 #include <config.h>
24
25 #include <math.h>
26 #include <stdlib.h>
27 #include <gsl/gsl_histogram.h>
28
29 #include <data/case.h>
30 #include <data/casegrouper.h>
31 #include <data/casereader.h>
32 #include <data/dictionary.h>
33 #include <data/format.h>
34 #include <data/procedure.h>
35 #include <data/settings.h>
36 #include <data/value-labels.h>
37 #include <data/variable.h>
38 #include <language/command.h>
39 #include <language/dictionary/split-file.h>
40 #include <language/lexer/lexer.h>
41 #include <libpspp/array.h>
42 #include <libpspp/bit-vector.h>
43 #include <libpspp/compiler.h>
44 #include <libpspp/hash.h>
45 #include <libpspp/message.h>
46 #include <libpspp/misc.h>
47 #include <libpspp/pool.h>
48 #include <libpspp/str.h>
49 #include <math/histogram.h>
50 #include <math/moments.h>
51 #include <output/chart-item.h>
52 #include <output/charts/piechart.h>
53 #include <output/charts/plot-hist.h>
54 #include <output/tab.h>
55
56 #include "freq.h"
57
58 #include "minmax.h"
59 #include "xalloc.h"
60
61 #include "gettext.h"
62 #define _(msgid) gettext (msgid)
63 #define N_(msgid) msgid
64
65 /* (headers) */
66
67 /* (specification)
68    FREQUENCIES (frq_):
69      *+variables=custom;
70      +format=cond:condense/onepage(*n:onepage_limit,"%s>=0")/!standard,
71              table:limit(n:limit,"%s>0")/notable/!table,
72              labels:!labels/nolabels,
73              sort:!avalue/dvalue/afreq/dfreq,
74              spaces:!single/double,
75              paging:newpage/!oldpage;
76      missing=miss:include/!exclude;
77      barchart(ba_)=:minimum(d:min),
78             :maximum(d:max),
79             scale:freq(*n:freq,"%s>0")/percent(*n:pcnt,"%s>0");
80      piechart(pie_)=:minimum(d:min),
81             :maximum(d:max),
82             missing:missing/!nomissing;
83      histogram(hi_)=:minimum(d:min),
84             :maximum(d:max),
85             scale:freq(*n:freq,"%s>0")/percent(*n:pcnt,"%s>0"),
86             norm:!nonormal/normal,
87             incr:increment(d:inc,"%s>0");
88      hbar(hb_)=:minimum(d:min),
89             :maximum(d:max),
90             scale:freq(*n:freq,"%s>0")/percent(*n:pcnt,"%s>0"),
91             norm:!nonormal/normal,
92             incr:increment(d:inc,"%s>0");
93      +grouped=custom;
94      +ntiles=integer;
95      +percentiles = double list;
96      +statistics[st_]=1|mean,2|semean,3|median,4|mode,5|stddev,6|variance,
97             7|kurtosis,8|skewness,9|range,10|minimum,11|maximum,12|sum,
98             13|default,14|seskewness,15|sekurtosis,all,none.
99 */
100 /* (declarations) */
101 /* (functions) */
102
103 /* Statistics. */
104 enum
105   {
106     frq_mean = 0, frq_semean, frq_median, frq_mode, frq_stddev, frq_variance,
107     frq_kurt, frq_sekurt, frq_skew, frq_seskew, frq_range, frq_min, frq_max,
108     frq_sum, frq_n_stats
109   };
110
111 /* Description of a statistic. */
112 struct frq_info
113   {
114     int st_indx;                /* Index into a_statistics[]. */
115     const char *s10;            /* Identifying string. */
116   };
117
118 /* Table of statistics, indexed by dsc_*. */
119 static const struct frq_info st_name[frq_n_stats + 1] =
120 {
121   {FRQ_ST_MEAN, N_("Mean")},
122   {FRQ_ST_SEMEAN, N_("S.E. Mean")},
123   {FRQ_ST_MEDIAN, N_("Median")},
124   {FRQ_ST_MODE, N_("Mode")},
125   {FRQ_ST_STDDEV, N_("Std Dev")},
126   {FRQ_ST_VARIANCE, N_("Variance")},
127   {FRQ_ST_KURTOSIS, N_("Kurtosis")},
128   {FRQ_ST_SEKURTOSIS, N_("S.E. Kurt")},
129   {FRQ_ST_SKEWNESS, N_("Skewness")},
130   {FRQ_ST_SESKEWNESS, N_("S.E. Skew")},
131   {FRQ_ST_RANGE, N_("Range")},
132   {FRQ_ST_MINIMUM, N_("Minimum")},
133   {FRQ_ST_MAXIMUM, N_("Maximum")},
134   {FRQ_ST_SUM, N_("Sum")},
135   {-1, 0},
136 };
137
138 /* Percentiles to calculate. */
139
140 struct percentile
141 {
142   double p;        /* the %ile to be calculated */
143   double value;    /* the %ile's value */
144   double x1;       /* The datum value <= the percentile */
145   double x2;       /* The datum value >= the percentile */
146   int flag;
147   int flag2;       /* Set to 1 if this percentile value has been found */
148   bool show;       /* True to show this percentile in the statistics box. */
149 };
150
151
152 static void add_percentile (double x, bool show);
153
154 static struct percentile *percentiles;
155 static int n_percentiles, n_show_percentiles;
156
157 /* Groups of statistics. */
158 #define BI          BIT_INDEX
159 #define frq_default                                                     \
160         (BI (frq_mean) | BI (frq_stddev) | BI (frq_min) | BI (frq_max))
161 #define frq_all                                                 \
162         (BI (frq_sum) | BI(frq_min) | BI(frq_max)               \
163          | BI(frq_mean) | BI(frq_semean) | BI(frq_stddev)       \
164          | BI(frq_variance) | BI(frq_kurt) | BI(frq_sekurt)     \
165          | BI(frq_skew) | BI(frq_seskew) | BI(frq_range)        \
166          | BI(frq_range) | BI(frq_mode) | BI(frq_median))
167
168 /* Statistics; number of statistics. */
169 static unsigned long stats;
170 static int n_stats;
171
172 /* Types of graphs. */
173 enum
174   {
175     GFT_NONE,                   /* Don't draw graphs. */
176     GFT_BAR,                    /* Draw bar charts. */
177     GFT_HIST,                   /* Draw histograms. */
178     GFT_PIE,                    /* Draw piechart */
179     GFT_HBAR                    /* Draw bar charts or histograms at our discretion. */
180   };
181
182 /* Parsed command. */
183 static struct cmd_frequencies cmd;
184
185 /* Summary of the barchart, histogram, and hbar subcommands. */
186 /* FIXME: These should not be mututally exclusive */
187 static int chart;               /* NONE/BAR/HIST/HBAR/PIE. */
188 static double min, max;         /* Minimum, maximum on y axis. */
189 static int format;              /* FREQ/PERCENT: Scaling of y axis. */
190 static double scale, incr;      /* FIXME */
191 static int normal;              /* FIXME */
192
193 /* Variables for which to calculate statistics. */
194 static size_t n_variables;
195 static const struct variable **v_variables;
196
197 /* Pools. */
198 static struct pool *data_pool;          /* For per-SPLIT FILE group data. */
199 static struct pool *syntax_pool;        /* For syntax-related data. */
200
201 /* Frequency tables. */
202
203 /* Entire frequency table. */
204 struct freq_tab
205   {
206     struct hsh_table *data;     /* Undifferentiated data. */
207     struct freq_mutable *valid; /* Valid freqs. */
208     int n_valid;                /* Number of total freqs. */
209     const struct dictionary *dict; /* The dict from whence entries in the table
210                                       come */
211
212     struct freq_mutable *missing; /* Missing freqs. */
213     int n_missing;              /* Number of missing freqs. */
214
215     /* Statistics. */
216     double total_cases;         /* Sum of weights of all cases. */
217     double valid_cases;         /* Sum of weights of valid cases. */
218   };
219
220
221 /* Per-variable frequency data. */
222 struct var_freqs
223   {
224     /* Freqency table. */
225     struct freq_tab tab;        /* Frequencies table to use. */
226
227     /* Percentiles. */
228     int n_groups;               /* Number of groups. */
229     double *groups;             /* Groups. */
230
231     /* Statistics. */
232     double stat[frq_n_stats];
233
234     /* Variable attributes. */
235     int width;
236     struct fmt_spec print;
237   };
238
239 static inline struct var_freqs *
240 get_var_freqs (const struct variable *v)
241 {
242   return var_get_aux (v);
243 }
244
245 static void determine_charts (void);
246
247 static void calc_stats (const struct variable *v, double d[frq_n_stats]);
248
249 static void precalc (struct casereader *, struct dataset *);
250 static void calc (const struct ccase *, const struct dataset *);
251 static void postcalc (const struct dataset *);
252
253 static void postprocess_freq_tab (const struct variable *);
254 static void dump_full ( const struct variable *, const struct variable *);
255 static void dump_condensed (const struct variable *, const struct variable *);
256 static void dump_statistics (const struct variable *, bool show_varname, const struct variable *);
257 static void cleanup_freq_tab (const struct variable *);
258
259 static hsh_compare_func compare_value_numeric_a, compare_value_alpha_a;
260 static hsh_compare_func compare_value_numeric_d, compare_value_alpha_d;
261 static hsh_compare_func compare_freq_numeric_a, compare_freq_alpha_a;
262 static hsh_compare_func compare_freq_numeric_d, compare_freq_alpha_d;
263
264
265 static void do_piechart(const struct variable *var,
266                         const struct freq_tab *frq_tab);
267
268 struct histogram *
269 freq_tab_to_hist(const struct freq_tab *ft, const struct variable *var);
270
271
272 \f
273 /* Parser and outline. */
274
275 static int internal_cmd_frequencies (struct lexer *lexer, struct dataset *ds);
276
277 int
278 cmd_frequencies (struct lexer *lexer, struct dataset *ds)
279 {
280   int result;
281
282   syntax_pool = pool_create ();
283   result = internal_cmd_frequencies (lexer, ds);
284   pool_destroy (syntax_pool);
285   syntax_pool=0;
286   pool_destroy (data_pool);
287   data_pool=0;
288   free (v_variables);
289   v_variables=0;
290   return result;
291 }
292
293 static int
294 internal_cmd_frequencies (struct lexer *lexer, struct dataset *ds)
295 {
296   struct casegrouper *grouper;
297   struct casereader *input, *group;
298   bool ok;
299   int i;
300
301   n_percentiles = 0;
302   n_show_percentiles = 0;
303   percentiles = NULL;
304
305   n_variables = 0;
306   v_variables = NULL;
307
308   if (!parse_frequencies (lexer, ds, &cmd, NULL))
309     return CMD_FAILURE;
310
311   if (cmd.onepage_limit == LONG_MIN)
312     cmd.onepage_limit = 50;
313
314   /* Figure out statistics to calculate. */
315   stats = 0;
316   if (cmd.a_statistics[FRQ_ST_DEFAULT] || !cmd.sbc_statistics)
317     stats |= frq_default;
318   if (cmd.a_statistics[FRQ_ST_ALL])
319     stats |= frq_all;
320   if (cmd.sort != FRQ_AVALUE && cmd.sort != FRQ_DVALUE)
321     stats &= ~BIT_INDEX (frq_median);
322   for (i = 0; i < frq_n_stats; i++)
323     if (cmd.a_statistics[st_name[i].st_indx])
324       stats |= BIT_INDEX (i);
325   if (stats & frq_kurt)
326     stats |= BIT_INDEX (frq_sekurt);
327   if (stats & frq_skew)
328     stats |= BIT_INDEX (frq_seskew);
329
330   /* Calculate n_stats. */
331   n_stats = 0;
332   for (i = 0; i < frq_n_stats; i++)
333     if ((stats & BIT_INDEX (i)))
334       n_stats++;
335
336   /* Charting. */
337   determine_charts ();
338   if (chart != GFT_NONE || cmd.sbc_ntiles)
339     cmd.sort = FRQ_AVALUE;
340
341   /* Work out what percentiles need to be calculated */
342   if ( cmd.sbc_percentiles )
343     {
344       for ( i = 0 ; i < MAXLISTS ; ++i )
345         {
346           int pl;
347           subc_list_double *ptl_list = &cmd.dl_percentiles[i];
348           for ( pl = 0 ; pl < subc_list_double_count(ptl_list); ++pl)
349             add_percentile (subc_list_double_at(ptl_list, pl) / 100.0, true);
350         }
351     }
352   if ( cmd.sbc_ntiles )
353     {
354       for ( i = 0 ; i < cmd.sbc_ntiles ; ++i )
355         {
356           int j;
357           for (j = 0; j <= cmd.n_ntiles[i]; ++j )
358             add_percentile (j / (double) cmd.n_ntiles[i], true);
359         }
360     }
361   if (stats & BIT_INDEX (frq_median))
362     {
363       /* Treat the median as the 50% percentile.
364          We output it in the percentiles table as "50 (Median)." */
365       add_percentile (0.5, true);
366       stats &= ~BIT_INDEX (frq_median);
367       n_stats--;
368     }
369   if (chart == GFT_HIST)
370     {
371       add_percentile (0.25, false);
372       add_percentile (0.75, false);
373     }
374
375   /* Do it! */
376   input = casereader_create_filter_weight (proc_open (ds), dataset_dict (ds),
377                                            NULL, NULL);
378   grouper = casegrouper_create_splits (input, dataset_dict (ds));
379   for (; casegrouper_get_next_group (grouper, &group);
380        casereader_destroy (group))
381     {
382       struct ccase *c;
383
384       precalc (group, ds);
385       for (; (c = casereader_read (group)) != NULL; case_unref (c))
386         calc (c, ds);
387       postcalc (ds);
388     }
389   ok = casegrouper_destroy (grouper);
390   ok = proc_commit (ds) && ok;
391
392   free_frequencies(&cmd);
393
394   return ok ? CMD_SUCCESS : CMD_CASCADING_FAILURE;
395 }
396
397 /* Figure out which charts the user requested.  */
398 static void
399 determine_charts (void)
400 {
401   int count = (!!cmd.sbc_histogram) + (!!cmd.sbc_barchart) +
402     (!!cmd.sbc_hbar) + (!!cmd.sbc_piechart);
403
404   if (!count)
405     {
406       chart = GFT_NONE;
407       return;
408     }
409   else if (count > 1)
410     {
411       chart = GFT_HBAR;
412       msg (SW, _("At most one of BARCHART, HISTOGRAM, or HBAR should be "
413            "given.  HBAR will be assumed.  Argument values will be "
414            "given precedence increasing along the order given."));
415     }
416   else if (cmd.sbc_histogram)
417     chart = GFT_HIST;
418   else if (cmd.sbc_barchart)
419     chart = GFT_BAR;
420   else if (cmd.sbc_piechart)
421     chart = GFT_PIE;
422   else
423     chart = GFT_HBAR;
424
425   min = max = SYSMIS;
426   format = FRQ_FREQ;
427   scale = SYSMIS;
428   incr = SYSMIS;
429   normal = 0;
430
431   if (cmd.sbc_barchart)
432     {
433       if (cmd.ba_min != SYSMIS)
434         min = cmd.ba_min;
435       if (cmd.ba_max != SYSMIS)
436         max = cmd.ba_max;
437       if (cmd.ba_scale == FRQ_FREQ)
438         {
439           format = FRQ_FREQ;
440           scale = cmd.ba_freq;
441         }
442       else if (cmd.ba_scale == FRQ_PERCENT)
443         {
444           format = FRQ_PERCENT;
445           scale = cmd.ba_pcnt;
446         }
447     }
448
449   if (cmd.sbc_histogram)
450     {
451       if (cmd.hi_min != SYSMIS)
452         min = cmd.hi_min;
453       if (cmd.hi_max != SYSMIS)
454         max = cmd.hi_max;
455       if (cmd.hi_scale == FRQ_FREQ)
456         {
457           format = FRQ_FREQ;
458           scale = cmd.hi_freq;
459         }
460       else if (cmd.hi_scale == FRQ_PERCENT)
461         {
462           format = FRQ_PERCENT;
463           scale = cmd.ba_pcnt;
464         }
465       if (cmd.hi_norm != FRQ_NONORMAL )
466         normal = 1;
467       if (cmd.hi_incr == FRQ_INCREMENT)
468         incr = cmd.hi_inc;
469     }
470
471   if (cmd.sbc_hbar)
472     {
473       if (cmd.hb_min != SYSMIS)
474         min = cmd.hb_min;
475       if (cmd.hb_max != SYSMIS)
476         max = cmd.hb_max;
477       if (cmd.hb_scale == FRQ_FREQ)
478         {
479           format = FRQ_FREQ;
480           scale = cmd.hb_freq;
481         }
482       else if (cmd.hb_scale == FRQ_PERCENT)
483         {
484           format = FRQ_PERCENT;
485           scale = cmd.ba_pcnt;
486         }
487       if (cmd.hb_norm)
488         normal = 1;
489       if (cmd.hb_incr == FRQ_INCREMENT)
490         incr = cmd.hb_inc;
491     }
492
493   if (min != SYSMIS && max != SYSMIS && min >= max)
494     {
495       msg (SE, _("MAX must be greater than or equal to MIN, if both are "
496            "specified.  However, MIN was specified as %g and MAX as %g.  "
497            "MIN and MAX will be ignored."), min, max);
498       min = max = SYSMIS;
499     }
500 }
501
502 /* Add data from case C to the frequency table. */
503 static void
504 calc (const struct ccase *c, const struct dataset *ds)
505 {
506   double weight = dict_get_case_weight (dataset_dict (ds), c, NULL);
507   size_t i;
508
509   for (i = 0; i < n_variables; i++)
510     {
511       const struct variable *v = v_variables[i];
512       const union value *val = case_data (c, v);
513       struct var_freqs *vf = get_var_freqs (v);
514       struct freq_tab *ft = &vf->tab;
515
516       struct freq_mutable target;
517       struct freq_mutable **fpp;
518
519       target.value = *val;
520       fpp = (struct freq_mutable **) hsh_probe (ft->data, &target);
521
522       if (*fpp != NULL)
523         (*fpp)->count += weight;
524       else
525         {
526           struct freq_mutable *fp = pool_alloc (data_pool, sizeof *fp);
527           fp->count = weight;
528           value_init_pool (data_pool, &fp->value, vf->width);
529           value_copy (&fp->value, val, vf->width);
530           *fpp = fp;
531         }
532     }
533 }
534
535 /* Prepares each variable that is the target of FREQUENCIES by setting
536    up its hash table. */
537 static void
538 precalc (struct casereader *input, struct dataset *ds)
539 {
540   struct ccase *c;
541   size_t i;
542
543   c = casereader_peek (input, 0);
544   if (c != NULL)
545     {
546       output_split_file_values (ds, c);
547       case_unref (c);
548     }
549
550   pool_destroy (data_pool);
551   data_pool = pool_create ();
552
553   for (i = 0; i < n_variables; i++)
554     {
555       const struct variable *v = v_variables[i];
556       struct freq_tab *ft = &get_var_freqs (v)->tab;
557
558       ft->data = hsh_create (16, compare_freq, hash_freq, NULL, v);
559     }
560 }
561
562 /* Finishes up with the variables after frequencies have been
563    calculated.  Displays statistics, percentiles, ... */
564 static void
565 postcalc (const struct dataset *ds)
566 {
567   const struct dictionary *dict = dataset_dict (ds);
568   const struct variable *wv = dict_get_weight (dict);
569   size_t i;
570
571   for (i = 0; i < n_variables; i++)
572     {
573       const struct variable *v = v_variables[i];
574       struct var_freqs *vf = get_var_freqs (v);
575       struct freq_tab *ft = &vf->tab;
576       int n_categories;
577       int dumped_freq_tab = 1;
578
579       postprocess_freq_tab (v);
580
581       /* Frequencies tables. */
582       n_categories = ft->n_valid + ft->n_missing;
583       if (cmd.table == FRQ_TABLE
584           || (cmd.table == FRQ_LIMIT && n_categories <= cmd.limit))
585         switch (cmd.cond)
586           {
587           case FRQ_CONDENSE:
588             dump_condensed (v, wv);
589             break;
590           case FRQ_STANDARD:
591             dump_full (v, wv);
592             break;
593           case FRQ_ONEPAGE:
594             if (n_categories > cmd.onepage_limit)
595               dump_condensed (v, wv);
596             else
597               dump_full (v, wv);
598             break;
599           default:
600             NOT_REACHED ();
601           }
602       else
603         dumped_freq_tab = 0;
604
605       /* Statistics. */
606       if (n_stats)
607         dump_statistics (v, !dumped_freq_tab, wv);
608
609
610
611       if ( chart == GFT_HIST && var_is_numeric (v) && ft->n_valid > 0)
612         {
613           double d[frq_n_stats];
614           struct histogram *hist ;
615
616           calc_stats (v, d);
617
618           hist = freq_tab_to_hist (ft,v);
619
620           chart_item_submit (histogram_chart_create (
621                                hist->gsl_hist, var_to_string(v),
622                                vf->tab.valid_cases,
623                                d[frq_mean],
624                                d[frq_stddev],
625                                normal));
626
627           statistic_destroy (&hist->parent);
628         }
629
630       if ( chart == GFT_PIE)
631         {
632           do_piechart(v_variables[i], ft);
633         }
634
635       cleanup_freq_tab (v);
636
637     }
638 }
639
640 /* Returns the comparison function that should be used for
641    sorting a frequency table by FRQ_SORT using VAL_TYPE
642    values. */
643 static hsh_compare_func *
644 get_freq_comparator (int frq_sort, enum val_type val_type)
645 {
646   bool is_numeric = val_type == VAL_NUMERIC;
647   switch (frq_sort)
648     {
649     case FRQ_AVALUE:
650       return is_numeric ? compare_value_numeric_a : compare_value_alpha_a;
651     case FRQ_DVALUE:
652       return is_numeric ? compare_value_numeric_d : compare_value_alpha_d;
653     case FRQ_AFREQ:
654       return is_numeric ? compare_freq_numeric_a : compare_freq_alpha_a;
655     case FRQ_DFREQ:
656       return is_numeric ? compare_freq_numeric_d : compare_freq_alpha_d;
657     default:
658       NOT_REACHED ();
659     }
660 }
661
662 /* Returns true iff the value in struct freq_mutable F is non-missing
663    for variable V. */
664 static bool
665 not_missing (const void *f_, const void *v_)
666 {
667   const struct freq_mutable *f = f_;
668   const struct variable *v = v_;
669
670   return !var_is_value_missing (v, &f->value, MV_ANY);
671 }
672
673 /* Summarizes the frequency table data for variable V. */
674 static void
675 postprocess_freq_tab (const struct variable *v)
676 {
677   hsh_compare_func *compare;
678   struct freq_tab *ft;
679   size_t count;
680   void *const *data;
681   struct freq_mutable *freqs, *f;
682   size_t i;
683
684   ft = &get_var_freqs (v)->tab;
685   compare = get_freq_comparator (cmd.sort, var_get_type (v));
686
687   /* Extract data from hash table. */
688   count = hsh_count (ft->data);
689   data = hsh_data (ft->data);
690
691   /* Copy dereferenced data into freqs. */
692   freqs = xnmalloc (count, sizeof *freqs);
693   for (i = 0; i < count; i++)
694     {
695       struct freq_mutable *f = data[i];
696       freqs[i] = *f;
697     }
698
699   /* Put data into ft. */
700   ft->valid = freqs;
701   ft->n_valid = partition (freqs, count, sizeof *freqs, not_missing, v);
702   ft->missing = freqs + ft->n_valid;
703   ft->n_missing = count - ft->n_valid;
704
705   /* Sort data. */
706   sort (ft->valid, ft->n_valid, sizeof *ft->valid, compare, v);
707   sort (ft->missing, ft->n_missing, sizeof *ft->missing, compare, v);
708
709   /* Summary statistics. */
710   ft->valid_cases = 0.0;
711   for(i = 0 ;  i < ft->n_valid ; ++i )
712     {
713       f = &ft->valid[i];
714       ft->valid_cases += f->count;
715
716     }
717
718   ft->total_cases = ft->valid_cases ;
719   for(i = 0 ;  i < ft->n_missing ; ++i )
720     {
721       f = &ft->missing[i];
722       ft->total_cases += f->count;
723     }
724
725 }
726
727 /* Frees the frequency table for variable V. */
728 static void
729 cleanup_freq_tab (const struct variable *v)
730 {
731   struct freq_tab *ft = &get_var_freqs (v)->tab;
732   free (ft->valid);
733   hsh_destroy (ft->data);
734 }
735
736 /* Parses the VARIABLES subcommand, adding to
737    {n_variables,v_variables}. */
738 static int
739 frq_custom_variables (struct lexer *lexer, struct dataset *ds, struct cmd_frequencies *cmd UNUSED, void *aux UNUSED)
740 {
741   size_t old_n_variables = n_variables;
742   size_t i;
743
744   lex_match (lexer, '=');
745   if (lex_token (lexer) != T_ALL && (lex_token (lexer) != T_ID
746                          || dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) == NULL))
747     return 2;
748
749   if (!parse_variables_const (lexer, dataset_dict (ds), &v_variables, &n_variables,
750                         PV_APPEND | PV_NO_SCRATCH))
751     return 0;
752
753   for (i = old_n_variables; i < n_variables; i++)
754     {
755       const struct variable *v = v_variables[i];
756       struct var_freqs *vf;
757
758       if (var_get_aux (v) != NULL)
759         {
760           msg (SE, _("Variable %s specified multiple times on VARIABLES "
761                      "subcommand."), var_get_name (v));
762           return 0;
763         }
764       vf = var_attach_aux (v, xmalloc (sizeof *vf), var_dtor_free);
765       vf->tab.valid = vf->tab.missing = NULL;
766       vf->tab.dict = dataset_dict (ds);
767       vf->n_groups = 0;
768       vf->groups = NULL;
769       vf->width = var_get_width (v);
770       vf->print = *var_get_print_format (v);
771     }
772   return 1;
773 }
774
775 /* Parses the GROUPED subcommand, setting the n_grouped, grouped
776    fields of specified variables. */
777 static int
778 frq_custom_grouped (struct lexer *lexer, struct dataset *ds, struct cmd_frequencies *cmd UNUSED, void *aux UNUSED)
779 {
780   lex_match (lexer, '=');
781   if ((lex_token (lexer) == T_ID && dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) != NULL)
782       || lex_token (lexer) == T_ID)
783     for (;;)
784       {
785         size_t i;
786
787         /* Max, current size of list; list itself. */
788         int nl, ml;
789         double *dl;
790
791         /* Variable list. */
792         size_t n;
793         const struct variable **v;
794
795         if (!parse_variables_const (lexer, dataset_dict (ds), &v, &n,
796                               PV_NO_DUPLICATE | PV_NUMERIC))
797           return 0;
798         if (lex_match (lexer, '('))
799           {
800             nl = ml = 0;
801             dl = NULL;
802             while (lex_integer (lexer))
803               {
804                 if (nl >= ml)
805                   {
806                     ml += 16;
807                     dl = pool_nrealloc (syntax_pool, dl, ml, sizeof *dl);
808                   }
809                 dl[nl++] = lex_tokval (lexer);
810                 lex_get (lexer);
811                 lex_match (lexer, ',');
812               }
813             /* Note that nl might still be 0 and dl might still be
814                NULL.  That's okay. */
815             if (!lex_match (lexer, ')'))
816               {
817                 free (v);
818                 msg (SE, _("`)' expected after GROUPED interval list."));
819                 return 0;
820               }
821           }
822         else
823           {
824             nl = 0;
825             dl = NULL;
826           }
827
828         for (i = 0; i < n; i++)
829           if (var_get_aux (v[i]) == NULL)
830             msg (SE, _("Variables %s specified on GROUPED but not on "
831                        "VARIABLES."), var_get_name (v[i]));
832           else
833             {
834               struct var_freqs *vf = get_var_freqs (v[i]);
835
836               if (vf->groups != NULL)
837                 msg (SE, _("Variables %s specified multiple times on GROUPED "
838                            "subcommand."), var_get_name (v[i]));
839               else
840                 {
841                   vf->n_groups = nl;
842                   vf->groups = dl;
843                 }
844             }
845         free (v);
846         if (!lex_match (lexer, '/'))
847           break;
848         if ((lex_token (lexer) != T_ID || dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) != NULL)
849             && lex_token (lexer) != T_ALL)
850           {
851             lex_put_back (lexer, '/');
852             break;
853           }
854       }
855
856   return 1;
857 }
858
859 /* Adds X to the list of percentiles, keeping the list in proper
860    order.  If SHOW is true, the percentile will be shown in the statistics
861    box, otherwise it will be hidden. */
862 static void
863 add_percentile (double x, bool show)
864 {
865   int i;
866
867   for (i = 0; i < n_percentiles; i++)
868     {
869       /* Do nothing if it's already in the list */
870       if ( fabs(x - percentiles[i].p) < DBL_EPSILON )
871         {
872           if (show && !percentiles[i].show)
873             {
874               n_show_percentiles++;
875               percentiles[i].show = true;
876             }
877           return;
878         }
879
880       if (x < percentiles[i].p)
881         break;
882     }
883
884   if (i >= n_percentiles || x != percentiles[i].p)
885     {
886       percentiles = pool_nrealloc (syntax_pool, percentiles,
887                                    n_percentiles + 1, sizeof *percentiles);
888       insert_element (percentiles, n_percentiles, sizeof *percentiles, i);
889       percentiles[i].p = x;
890       percentiles[i].show = show;
891       n_percentiles++;
892       if (show)
893         n_show_percentiles++;
894     }
895 }
896
897 /* Comparison functions. */
898
899 /* Ascending numeric compare of values. */
900 static int
901 compare_value_numeric_a (const void *a_, const void *b_, const void *aux UNUSED)
902 {
903   const struct freq_mutable *a = a_;
904   const struct freq_mutable *b = b_;
905
906   if (a->value.f > b->value.f)
907     return 1;
908   else if (a->value.f < b->value.f)
909     return -1;
910   else
911     return 0;
912 }
913
914 /* Ascending string compare of values. */
915 static int
916 compare_value_alpha_a (const void *a_, const void *b_, const void *v_)
917 {
918   const struct freq_mutable *a = a_;
919   const struct freq_mutable *b = b_;
920   const struct variable *v = v_;
921   struct var_freqs *vf = get_var_freqs (v);
922
923   return value_compare_3way (&a->value, &b->value, vf->width);
924 }
925
926 /* Descending numeric compare of values. */
927 static int
928 compare_value_numeric_d (const void *a, const void *b, const void *aux UNUSED)
929 {
930   return -compare_value_numeric_a (a, b, aux);
931 }
932
933 /* Descending string compare of values. */
934 static int
935 compare_value_alpha_d (const void *a, const void *b, const void *v)
936 {
937   return -compare_value_alpha_a (a, b, v);
938 }
939
940 /* Ascending numeric compare of frequency;
941    secondary key on ascending numeric value. */
942 static int
943 compare_freq_numeric_a (const void *a_, const void *b_, const void *aux UNUSED)
944 {
945   const struct freq_mutable *a = a_;
946   const struct freq_mutable *b = b_;
947
948   if (a->count > b->count)
949     return 1;
950   else if (a->count < b->count)
951     return -1;
952
953   if (a->value.f > b->value.f)
954     return 1;
955   else if (a->value.f < b->value.f)
956     return -1;
957   else
958     return 0;
959 }
960
961 /* Ascending numeric compare of frequency;
962    secondary key on ascending string value. */
963 static int
964 compare_freq_alpha_a (const void *a_, const void *b_, const void *v_)
965 {
966   const struct freq_mutable *a = a_;
967   const struct freq_mutable *b = b_;
968   const struct variable *v = v_;
969   struct var_freqs *vf = get_var_freqs (v);
970
971   if (a->count > b->count)
972     return 1;
973   else if (a->count < b->count)
974     return -1;
975   else
976     return value_compare_3way (&a->value, &b->value, vf->width);
977 }
978
979 /* Descending numeric compare of frequency;
980    secondary key on ascending numeric value. */
981 static int
982 compare_freq_numeric_d (const void *a_, const void *b_, const void *aux UNUSED)
983 {
984   const struct freq_mutable *a = a_;
985   const struct freq_mutable *b = b_;
986
987   if (a->count > b->count)
988     return -1;
989   else if (a->count < b->count)
990     return 1;
991
992   if (a->value.f > b->value.f)
993     return 1;
994   else if (a->value.f < b->value.f)
995     return -1;
996   else
997     return 0;
998 }
999
1000 /* Descending numeric compare of frequency;
1001    secondary key on ascending string value. */
1002 static int
1003 compare_freq_alpha_d (const void *a_, const void *b_, const void *v_)
1004 {
1005   const struct freq_mutable *a = a_;
1006   const struct freq_mutable *b = b_;
1007   const struct variable *v = v_;
1008   struct var_freqs *vf = get_var_freqs (v);
1009
1010   if (a->count > b->count)
1011     return -1;
1012   else if (a->count < b->count)
1013     return 1;
1014   else
1015     return value_compare_3way (&a->value, &b->value, vf->width);
1016 }
1017 \f
1018 /* Frequency table display. */
1019
1020 /* Displays a full frequency table for variable V. */
1021 static void
1022 dump_full (const struct variable *v, const struct variable *wv)
1023 {
1024   const struct fmt_spec *wfmt = wv ? var_get_print_format (wv) : &F_8_0;
1025   int n_categories;
1026   struct var_freqs *vf;
1027   struct freq_tab *ft;
1028   struct freq_mutable *f;
1029   struct tab_table *t;
1030   int r, x;
1031   double cum_total = 0.0;
1032   double cum_freq = 0.0;
1033
1034   static const char *headings[] = {
1035     N_("Value"),
1036     N_("Frequency"),
1037     N_("Percent"),
1038     N_("Valid Percent"),
1039     N_("Cum Percent")
1040   };
1041
1042   const bool lab = (cmd.labels == FRQ_LABELS);
1043
1044   vf = get_var_freqs (v);
1045   ft = &vf->tab;
1046   n_categories = ft->n_valid + ft->n_missing;
1047   t = tab_create (5 + lab, n_categories + 2);
1048   tab_headers (t, 0, 0, 1, 0);
1049
1050   if (lab)
1051     tab_text (t, 0, 0, TAB_CENTER | TAT_TITLE, _("Value Label"));
1052
1053   for (x = 0; x < 5; x++)
1054     tab_text (t, lab + x, 0, TAB_CENTER | TAT_TITLE, gettext (headings[x]));
1055
1056   r = 1;
1057   for (f = ft->valid; f < ft->missing; f++)
1058     {
1059       double percent, valid_percent;
1060
1061       cum_freq += f->count;
1062
1063       percent = f->count / ft->total_cases * 100.0;
1064       valid_percent = f->count / ft->valid_cases * 100.0;
1065       cum_total += valid_percent;
1066
1067       if (lab)
1068         {
1069           const char *label = var_lookup_value_label (v, &f->value);
1070           if (label != NULL)
1071             tab_text (t, 0, r, TAB_LEFT, label);
1072         }
1073
1074       tab_value (t, 0 + lab, r, TAB_NONE, &f->value, ft->dict, &vf->print);
1075       tab_double (t, 1 + lab, r, TAB_NONE, f->count, wfmt);
1076       tab_double (t, 2 + lab, r, TAB_NONE, percent, NULL);
1077       tab_double (t, 3 + lab, r, TAB_NONE, valid_percent, NULL);
1078       tab_double (t, 4 + lab, r, TAB_NONE, cum_total, NULL);
1079       r++;
1080     }
1081   for (; f < &ft->valid[n_categories]; f++)
1082     {
1083       cum_freq += f->count;
1084
1085       if (lab)
1086         {
1087           const char *label = var_lookup_value_label (v, &f->value);
1088           if (label != NULL)
1089             tab_text (t, 0, r, TAB_LEFT, label);
1090         }
1091
1092       tab_value (t, 0 + lab, r, TAB_NONE, &f->value, ft->dict, &vf->print);
1093       tab_double (t, 1 + lab, r, TAB_NONE, f->count, wfmt);
1094       tab_double (t, 2 + lab, r, TAB_NONE,
1095                      f->count / ft->total_cases * 100.0, NULL);
1096       tab_text (t, 3 + lab, r, TAB_NONE, _("Missing"));
1097       r++;
1098     }
1099
1100   tab_box (t, TAL_1, TAL_1,
1101            cmd.spaces == FRQ_SINGLE ? -1 : TAL_GAP, TAL_1,
1102            0, 0, 4 + lab, r);
1103   tab_hline (t, TAL_2, 0, 4 + lab, 1);
1104   tab_hline (t, TAL_2, 0, 4 + lab, r);
1105   tab_joint_text (t, 0, r, 0 + lab, r, TAB_RIGHT | TAT_TITLE, _("Total"));
1106   tab_vline (t, TAL_0, 1, r, r);
1107   tab_double (t, 1 + lab, r, TAB_NONE, cum_freq, wfmt);
1108   tab_fixed (t, 2 + lab, r, TAB_NONE, 100.0, 5, 1);
1109   tab_fixed (t, 3 + lab, r, TAB_NONE, 100.0, 5, 1);
1110
1111   tab_title (t, "%s", var_to_string (v));
1112   tab_submit (t);
1113 }
1114
1115 /* Display condensed frequency table for variable V. */
1116 static void
1117 dump_condensed (const struct variable *v, const struct variable *wv)
1118 {
1119   const struct fmt_spec *wfmt = wv ? var_get_print_format (wv) : &F_8_0;
1120   int n_categories;
1121   struct var_freqs *vf;
1122   struct freq_tab *ft;
1123   struct freq_mutable *f;
1124   struct tab_table *t;
1125   int r;
1126   double cum_total = 0.0;
1127
1128   vf = get_var_freqs (v);
1129   ft = &vf->tab;
1130   n_categories = ft->n_valid + ft->n_missing;
1131   t = tab_create (4, n_categories + 2);
1132
1133   tab_headers (t, 0, 0, 2, 0);
1134   tab_text (t, 0, 1, TAB_CENTER | TAT_TITLE, _("Value"));
1135   tab_text (t, 1, 1, TAB_CENTER | TAT_TITLE, _("Freq"));
1136   tab_text (t, 2, 1, TAB_CENTER | TAT_TITLE, _("Pct"));
1137   tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("Cum"));
1138   tab_text (t, 3, 1, TAB_CENTER | TAT_TITLE, _("Pct"));
1139
1140   r = 2;
1141   for (f = ft->valid; f < ft->missing; f++)
1142     {
1143       double percent;
1144
1145       percent = f->count / ft->total_cases * 100.0;
1146       cum_total += f->count / ft->valid_cases * 100.0;
1147
1148       tab_value (t, 0, r, TAB_NONE, &f->value, ft->dict, &vf->print);
1149       tab_double (t, 1, r, TAB_NONE, f->count, wfmt);
1150       tab_double (t, 2, r, TAB_NONE, percent, NULL);
1151       tab_double (t, 3, r, TAB_NONE, cum_total, NULL);
1152       r++;
1153     }
1154   for (; f < &ft->valid[n_categories]; f++)
1155     {
1156       tab_value (t, 0, r, TAB_NONE, &f->value, ft->dict, &vf->print);
1157       tab_double (t, 1, r, TAB_NONE, f->count, wfmt);
1158       tab_double (t, 2, r, TAB_NONE,
1159                  f->count / ft->total_cases * 100.0, NULL);
1160       r++;
1161     }
1162
1163   tab_box (t, TAL_1, TAL_1,
1164            cmd.spaces == FRQ_SINGLE ? -1 : TAL_GAP, TAL_1,
1165            0, 0, 3, r - 1);
1166   tab_hline (t, TAL_2, 0, 3, 2);
1167   tab_title (t, "%s", var_to_string (v));
1168   tab_submit (t);
1169 }
1170 \f
1171 /* Statistical display. */
1172
1173 /* Calculates all the pertinent statistics for variable V, putting them in
1174    array D[]. */
1175 static void
1176 calc_stats (const struct variable *v, double d[frq_n_stats])
1177 {
1178   struct freq_tab *ft = &get_var_freqs (v)->tab;
1179   double W = ft->valid_cases;
1180   struct moments *m;
1181   struct freq_mutable *f=0;
1182   int most_often;
1183   double X_mode;
1184
1185   double rank;
1186   int i = 0;
1187   int idx;
1188
1189   /* Calculate percentiles. */
1190
1191   assert (ft->n_valid > 0);
1192
1193   for (i = 0; i < n_percentiles; i++)
1194     {
1195       percentiles[i].flag = 0;
1196       percentiles[i].flag2 = 0;
1197     }
1198
1199   rank = 0;
1200   for (idx = 0; idx < ft->n_valid; ++idx)
1201     {
1202       static double prev_value = SYSMIS;
1203       f = &ft->valid[idx];
1204       rank += f->count ;
1205       for (i = 0; i < n_percentiles; i++)
1206         {
1207           double tp;
1208           if ( percentiles[i].flag2  ) continue ;
1209
1210           if ( settings_get_algorithm () != COMPATIBLE )
1211             tp =
1212               (ft->valid_cases - 1) *  percentiles[i].p;
1213           else
1214             tp =
1215               (ft->valid_cases + 1) *  percentiles[i].p - 1;
1216
1217           if ( percentiles[i].flag )
1218             {
1219               percentiles[i].x2 = f->value.f;
1220               percentiles[i].x1 = prev_value;
1221               percentiles[i].flag2 = 1;
1222               continue;
1223             }
1224
1225           if (rank >  tp )
1226           {
1227             if ( f->count > 1 && rank - (f->count - 1) > tp )
1228               {
1229                 percentiles[i].x2 = percentiles[i].x1 = f->value.f;
1230                 percentiles[i].flag2 = 1;
1231               }
1232             else
1233               {
1234                 percentiles[i].flag=1;
1235               }
1236
1237             continue;
1238           }
1239         }
1240       prev_value = f->value.f;
1241     }
1242
1243   for (i = 0; i < n_percentiles; i++)
1244     {
1245       /* Catches the case when p == 100% */
1246       if ( ! percentiles[i].flag2 )
1247         percentiles[i].x1 = percentiles[i].x2 = f->value.f;
1248
1249       /*
1250       printf("percentile %d (p==%.2f); X1 = %g; X2 = %g\n",
1251              i,percentiles[i].p,percentiles[i].x1,percentiles[i].x2);
1252       */
1253     }
1254
1255   for (i = 0; i < n_percentiles; i++)
1256     {
1257       struct freq_tab *ft = &get_var_freqs (v)->tab;
1258       double s;
1259
1260       double dummy;
1261       if ( settings_get_algorithm () != COMPATIBLE )
1262         {
1263           s = modf((ft->valid_cases - 1) * percentiles[i].p , &dummy);
1264         }
1265       else
1266         {
1267           s = modf((ft->valid_cases + 1) * percentiles[i].p -1, &dummy);
1268         }
1269
1270       percentiles[i].value = percentiles[i].x1 +
1271         ( percentiles[i].x2 - percentiles[i].x1) * s ;
1272     }
1273
1274
1275   /* Calculate the mode. */
1276   most_often = -1;
1277   X_mode = SYSMIS;
1278   for (f = ft->valid; f < ft->missing; f++)
1279     {
1280       if (most_often < f->count)
1281         {
1282           most_often = f->count;
1283           X_mode = f->value.f;
1284         }
1285       else if (most_often == f->count)
1286         {
1287           /* A duplicate mode is undefined.
1288              FIXME: keep track of *all* the modes. */
1289           X_mode = SYSMIS;
1290         }
1291     }
1292
1293   /* Calculate moments. */
1294   m = moments_create (MOMENT_KURTOSIS);
1295   for (f = ft->valid; f < ft->missing; f++)
1296     moments_pass_one (m, f->value.f, f->count);
1297   for (f = ft->valid; f < ft->missing; f++)
1298     moments_pass_two (m, f->value.f, f->count);
1299   moments_calculate (m, NULL, &d[frq_mean], &d[frq_variance],
1300                      &d[frq_skew], &d[frq_kurt]);
1301   moments_destroy (m);
1302
1303   /* Formulas below are taken from _SPSS Statistical Algorithms_. */
1304   d[frq_min] = ft->valid[0].value.f;
1305   d[frq_max] = ft->valid[ft->n_valid - 1].value.f;
1306   d[frq_mode] = X_mode;
1307   d[frq_range] = d[frq_max] - d[frq_min];
1308   d[frq_sum] = d[frq_mean] * W;
1309   d[frq_stddev] = sqrt (d[frq_variance]);
1310   d[frq_semean] = d[frq_stddev] / sqrt (W);
1311   d[frq_seskew] = calc_seskew (W);
1312   d[frq_sekurt] = calc_sekurt (W);
1313 }
1314
1315 /* Displays a table of all the statistics requested for variable V. */
1316 static void
1317 dump_statistics (const struct variable *v, bool show_varname,
1318                  const struct variable *wv)
1319 {
1320   const struct fmt_spec *wfmt = wv ? var_get_print_format (wv) : &F_8_0;
1321   struct freq_tab *ft;
1322   double stat_value[frq_n_stats];
1323   struct tab_table *t;
1324   int i, r;
1325
1326   if (var_is_alpha (v))
1327     return;
1328   ft = &get_var_freqs (v)->tab;
1329   if (ft->n_valid == 0)
1330     {
1331       msg (SW, _("No valid data for variable %s; statistics not displayed."),
1332            var_get_name (v));
1333       return;
1334     }
1335   calc_stats (v, stat_value);
1336
1337   t = tab_create (3, n_stats + n_show_percentiles + 2);
1338
1339   tab_box (t, TAL_1, TAL_1, -1, -1 , 0 , 0 , 2, tab_nr(t) - 1) ;
1340
1341
1342   tab_vline (t, TAL_1 , 2, 0, tab_nr(t) - 1);
1343   tab_vline (t, TAL_GAP , 1, 0, tab_nr(t) - 1 ) ;
1344
1345   r=2; /* N missing and N valid are always dumped */
1346
1347   for (i = 0; i < frq_n_stats; i++)
1348     if (stats & BIT_INDEX (i))
1349       {
1350         tab_text (t, 0, r, TAB_LEFT | TAT_TITLE,
1351                       gettext (st_name[i].s10));
1352         tab_double (t, 2, r, TAB_NONE, stat_value[i], NULL);
1353         r++;
1354       }
1355
1356   tab_text (t, 0, 0, TAB_LEFT | TAT_TITLE, _("N"));
1357   tab_text (t, 1, 0, TAB_LEFT | TAT_TITLE, _("Valid"));
1358   tab_text (t, 1, 1, TAB_LEFT | TAT_TITLE, _("Missing"));
1359
1360   tab_double (t, 2, 0, TAB_NONE, ft->valid_cases, wfmt);
1361   tab_double (t, 2, 1, TAB_NONE, ft->total_cases - ft->valid_cases, wfmt);
1362
1363   for (i = 0; i < n_percentiles; i++, r++)
1364     {
1365       if (!percentiles[i].show)
1366         continue;
1367
1368       if ( i == 0 )
1369         {
1370           tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, _("Percentiles"));
1371         }
1372
1373       if (percentiles[i].p == 0.5)
1374         tab_text (t, 1, r, TAB_LEFT, _("50 (Median)"));
1375       else
1376         tab_fixed (t, 1, r, TAB_LEFT, percentiles[i].p * 100, 3, 0);
1377       tab_double (t, 2, r, TAB_NONE, percentiles[i].value,
1378                   var_get_print_format (v));
1379     }
1380
1381   if (show_varname)
1382     tab_title (t, "%s", var_to_string (v));
1383
1384
1385   tab_submit (t);
1386 }
1387
1388 static double
1389 calculate_iqr (void)
1390 {
1391   double q1 = SYSMIS;
1392   double q3 = SYSMIS;
1393   int i;
1394
1395   for (i = 0; i < n_percentiles; i++)
1396     {
1397       if (fabs (0.25 - percentiles[i].p) < DBL_EPSILON)
1398         q1 = percentiles[i].value;
1399       else if (fabs (0.75 - percentiles[i].p) < DBL_EPSILON)
1400         q3 = percentiles[i].value;
1401     }
1402
1403   return q1 == SYSMIS || q3 == SYSMIS ? SYSMIS : q3 - q1;
1404 }
1405
1406 /* Create a gsl_histogram from a freq_tab */
1407 struct histogram *
1408 freq_tab_to_hist (const struct freq_tab *ft, const struct variable *var)
1409 {
1410   int i;
1411   double x_min = DBL_MAX;
1412   double x_max = -DBL_MAX;
1413
1414   struct histogram *hist;
1415   double iqr;
1416   int bins;
1417
1418   struct hsh_iterator hi;
1419   struct hsh_table *fh = ft->data;
1420   struct freq_mutable *frq;
1421
1422   /* Find out the extremes of the x value */
1423   for ( frq = hsh_first(fh, &hi); frq != 0; frq = hsh_next(fh, &hi) )
1424     {
1425       if (var_is_value_missing(var, &frq->value, MV_ANY))
1426         continue;
1427
1428       if ( frq->value.f < x_min ) x_min = frq->value.f ;
1429       if ( frq->value.f > x_max ) x_max = frq->value.f ;
1430     }
1431
1432   /* Freedman-Diaconis' choice of bin width. */
1433   iqr = calculate_iqr ();
1434   if (iqr != SYSMIS)
1435     {
1436       double bin_width = 2 * iqr / pow (ft->valid_cases, 1.0 / 3.0);
1437       bins = (x_max - x_min) / bin_width;
1438       if (bins < 5)
1439         bins = 5;
1440       else if (bins > 400)
1441         bins = 400;
1442     }
1443   else
1444     bins = 5;
1445
1446   hist = histogram_create (bins, x_min, x_max);
1447
1448   for( i = 0 ; i < ft->n_valid ; ++i )
1449     {
1450       frq = &ft->valid[i];
1451       histogram_add (hist, frq->value.f, frq->count);
1452     }
1453
1454   return hist;
1455 }
1456
1457
1458 static struct slice *
1459 freq_tab_to_slice_array(const struct freq_tab *frq_tab,
1460                         const struct variable *var,
1461                         int *n_slices);
1462
1463
1464 /* Allocate an array of slices and fill them from the data in frq_tab
1465    n_slices will contain the number of slices allocated.
1466    The caller is responsible for freeing slices
1467 */
1468 static struct slice *
1469 freq_tab_to_slice_array(const struct freq_tab *frq_tab,
1470                         const struct variable *var,
1471                         int *n_slices)
1472 {
1473   int i;
1474   struct slice *slices;
1475
1476   *n_slices = frq_tab->n_valid;
1477
1478   slices = xnmalloc (*n_slices, sizeof *slices);
1479
1480   for (i = 0 ; i < *n_slices ; ++i )
1481     {
1482       const struct freq_mutable *frq = &frq_tab->valid[i];
1483
1484       ds_init_empty (&slices[i].label);
1485       var_append_value_name (var, &frq->value, &slices[i].label);
1486       slices[i].magnitude = frq->count;
1487     }
1488
1489   return slices;
1490 }
1491
1492
1493
1494
1495 static void
1496 do_piechart(const struct variable *var, const struct freq_tab *frq_tab)
1497 {
1498   struct slice *slices;
1499   int n_slices, i;
1500
1501   slices = freq_tab_to_slice_array(frq_tab, var, &n_slices);
1502
1503   chart_item_submit (piechart_create (var_to_string(var), slices, n_slices));
1504
1505   for (i = 0 ; i < n_slices ; ++i )
1506     ds_destroy (&slices[i].label);
1507
1508   free (slices);
1509 }
1510
1511
1512 /*
1513    Local Variables:
1514    mode: c
1515    End:
1516 */