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