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