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