Remove integer mode from FREQUENCIES and incidentally fix bug
[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/alloc.h>
42 #include <libpspp/array.h>
43 #include <libpspp/bit-vector.h>
44 #include <libpspp/compiler.h>
45 #include <libpspp/hash.h>
46 #include <libpspp/magic.h>
47 #include <libpspp/message.h>
48 #include <libpspp/misc.h>
49 #include <libpspp/pool.h>
50 #include <libpspp/str.h>
51 #include <math/histogram.h>
52 #include <math/moments.h>
53 #include <output/chart.h>
54 #include <output/charts/piechart.h>
55 #include <output/charts/plot-hist.h>
56 #include <output/manager.h>
57 #include <output/output.h>
58 #include <output/table.h>
59
60 #include "freq.h"
61
62 #include "minmax.h"
63
64 #include "gettext.h"
65 #define _(msgid) gettext (msgid)
66 #define N_(msgid) msgid
67
68 /* (headers) */
69
70 /* (specification)
71    FREQUENCIES (frq_):
72      *+variables=custom;
73      +format=cond:condense/onepage(*n:onepage_limit,"%s>=0")/!standard,
74              table:limit(n:limit,"%s>0")/notable/!table,
75              labels:!labels/nolabels,
76              sort:!avalue/dvalue/afreq/dfreq,
77              spaces:!single/double,
78              paging:newpage/!oldpage;
79      missing=miss:include/!exclude;
80      barchart(ba_)=:minimum(d:min),
81             :maximum(d:max),
82             scale:freq(*n:freq,"%s>0")/percent(*n:pcnt,"%s>0");
83      piechart(pie_)=:minimum(d:min),
84             :maximum(d:max),
85             missing:missing/!nomissing;
86      histogram(hi_)=:minimum(d:min),
87             :maximum(d:max),
88             scale:freq(*n:freq,"%s>0")/percent(*n:pcnt,"%s>0"),
89             norm:!nonormal/normal,
90             incr:increment(d:inc,"%s>0");
91      hbar(hb_)=:minimum(d:min),
92             :maximum(d:max),
93             scale:freq(*n:freq,"%s>0")/percent(*n:pcnt,"%s>0"),
94             norm:!nonormal/normal,
95             incr:increment(d:inc,"%s>0");
96      +grouped=custom;
97      +ntiles=integer;
98      +percentiles = double list;
99      +statistics[st_]=1|mean,2|semean,3|median,4|mode,5|stddev,6|variance,
100             7|kurtosis,8|skewness,9|range,10|minimum,11|maximum,12|sum,
101             13|default,14|seskewness,15|sekurtosis,all,none.
102 */
103 /* (declarations) */
104 /* (functions) */
105
106 /* Statistics. */
107 enum
108   {
109     frq_mean = 0, frq_semean, frq_median, frq_mode, frq_stddev, frq_variance,
110     frq_kurt, frq_sekurt, frq_skew, frq_seskew, frq_range, frq_min, frq_max,
111     frq_sum, frq_n_stats
112   };
113
114 /* Description of a statistic. */
115 struct frq_info
116   {
117     int st_indx;                /* Index into a_statistics[]. */
118     const char *s10;            /* Identifying string. */
119   };
120
121 /* Table of statistics, indexed by dsc_*. */
122 static const struct frq_info st_name[frq_n_stats + 1] =
123 {
124   {FRQ_ST_MEAN, N_("Mean")},
125   {FRQ_ST_SEMEAN, N_("S.E. Mean")},
126   {FRQ_ST_MEDIAN, N_("Median")},
127   {FRQ_ST_MODE, N_("Mode")},
128   {FRQ_ST_STDDEV, N_("Std Dev")},
129   {FRQ_ST_VARIANCE, N_("Variance")},
130   {FRQ_ST_KURTOSIS, N_("Kurtosis")},
131   {FRQ_ST_SEKURTOSIS, N_("S.E. Kurt")},
132   {FRQ_ST_SKEWNESS, N_("Skewness")},
133   {FRQ_ST_SESKEWNESS, N_("S.E. Skew")},
134   {FRQ_ST_RANGE, N_("Range")},
135   {FRQ_ST_MINIMUM, N_("Minimum")},
136   {FRQ_ST_MAXIMUM, N_("Maximum")},
137   {FRQ_ST_SUM, N_("Sum")},
138   {-1, 0},
139 };
140
141 /* Percentiles to calculate. */
142
143 struct percentile
144 {
145   double p;        /* the %ile to be calculated */
146   double value;    /* the %ile's value */
147   double x1;       /* The datum value <= the percentile */
148   double x2;       /* The datum value >= the percentile */
149   int flag;
150   int flag2;       /* Set to 1 if this percentile value has been found */
151 };
152
153
154 static void add_percentile (double x) ;
155
156 static struct percentile *percentiles;
157 static int n_percentiles;
158
159 static int implicit_50th ;
160
161 /* Groups of statistics. */
162 #define BI          BIT_INDEX
163 #define frq_default                                                     \
164         (BI (frq_mean) | BI (frq_stddev) | BI (frq_min) | BI (frq_max))
165 #define frq_all                                                 \
166         (BI (frq_sum) | BI(frq_min) | BI(frq_max)               \
167          | BI(frq_mean) | BI(frq_semean) | BI(frq_stddev)       \
168          | BI(frq_variance) | BI(frq_kurt) | BI(frq_sekurt)     \
169          | BI(frq_skew) | BI(frq_seskew) | BI(frq_range)        \
170          | BI(frq_range) | BI(frq_mode) | BI(frq_median))
171
172 /* Statistics; number of statistics. */
173 static unsigned long stats;
174 static int n_stats;
175
176 /* Types of graphs. */
177 enum
178   {
179     GFT_NONE,                   /* Don't draw graphs. */
180     GFT_BAR,                    /* Draw bar charts. */
181     GFT_HIST,                   /* Draw histograms. */
182     GFT_PIE,                    /* Draw piechart */
183     GFT_HBAR                    /* Draw bar charts or histograms at our discretion. */
184   };
185
186 /* Parsed command. */
187 static struct cmd_frequencies cmd;
188
189 /* Summary of the barchart, histogram, and hbar subcommands. */
190 /* FIXME: These should not be mututally exclusive */
191 static int chart;               /* NONE/BAR/HIST/HBAR/PIE. */
192 static double min, max;         /* Minimum, maximum on y axis. */
193 static int format;              /* FREQ/PERCENT: Scaling of y axis. */
194 static double scale, incr;      /* FIXME */
195 static int normal;              /* FIXME */
196
197 /* Variables for which to calculate statistics. */
198 static size_t n_variables;
199 static const struct variable **v_variables;
200
201 /* Pools. */
202 static struct pool *data_pool;          /* For per-SPLIT FILE group data. */
203 static struct pool *syntax_pool;        /* For syntax-related data. */
204
205 /* Frequency tables. */
206
207 /* Entire frequency table. */
208 struct freq_tab
209   {
210     struct hsh_table *data;     /* Undifferentiated data. */
211     struct freq *valid;         /* Valid freqs. */
212     int n_valid;                /* Number of total freqs. */
213
214     struct freq *missing;       /* Missing freqs. */
215     int n_missing;              /* Number of missing freqs. */
216
217     /* Statistics. */
218     double total_cases;         /* Sum of weights of all cases. */
219     double valid_cases;         /* Sum of weights of valid cases. */
220   };
221
222
223 /* Per-variable frequency data. */
224 struct var_freqs
225   {
226     /* Freqency table. */
227     struct freq_tab tab;        /* Frequencies table to use. */
228
229     /* Percentiles. */
230     int n_groups;               /* Number of groups. */
231     double *groups;             /* Groups. */
232
233     /* Statistics. */
234     double stat[frq_n_stats];
235
236     /* Width and format for analysis and display.
237        This is normally the same as "width" and "print" in struct
238        variable, but in SPSS-compatible mode only the first
239        MAX_SHORT_STRING bytes of long string variables are
240        included. */
241     int width;
242     struct fmt_spec print;
243   };
244
245 static inline struct var_freqs *
246 get_var_freqs (const struct variable *v)
247 {
248   return var_get_aux (v);
249 }
250
251 static void determine_charts (void);
252
253 static void calc_stats (const struct variable *v, double d[frq_n_stats]);
254
255 static void precalc (struct casereader *, struct dataset *);
256 static void calc (const struct ccase *, const struct dataset *);
257 static void postcalc (void);
258
259 static void postprocess_freq_tab (const struct variable *);
260 static void dump_full (const struct variable *);
261 static void dump_condensed (const struct variable *);
262 static void dump_statistics (const struct variable *, int show_varname);
263 static void cleanup_freq_tab (const struct variable *);
264
265 static hsh_compare_func compare_value_numeric_a, compare_value_alpha_a;
266 static hsh_compare_func compare_value_numeric_d, compare_value_alpha_d;
267 static hsh_compare_func compare_freq_numeric_a, compare_freq_alpha_a;
268 static hsh_compare_func compare_freq_numeric_d, compare_freq_alpha_d;
269
270
271 static void do_piechart(const struct variable *var,
272                         const struct freq_tab *frq_tab);
273
274 gsl_histogram *
275 freq_tab_to_hist(const struct freq_tab *ft, const struct variable *var);
276
277
278 \f
279 /* Parser and outline. */
280
281 static int internal_cmd_frequencies (struct lexer *lexer, struct dataset *ds);
282
283 int
284 cmd_frequencies (struct lexer *lexer, struct dataset *ds)
285 {
286   int result;
287
288   syntax_pool = pool_create ();
289   result = internal_cmd_frequencies (lexer, ds);
290   pool_destroy (syntax_pool);
291   syntax_pool=0;
292   pool_destroy (data_pool);
293   data_pool=0;
294   free (v_variables);
295   v_variables=0;
296   return result;
297 }
298
299 static int
300 internal_cmd_frequencies (struct lexer *lexer, struct dataset *ds)
301 {
302   struct casegrouper *grouper;
303   struct casereader *input, *group;
304   bool ok;
305   int i;
306
307   n_percentiles = 0;
308   percentiles = NULL;
309
310   n_variables = 0;
311   v_variables = NULL;
312
313   if (!parse_frequencies (lexer, ds, &cmd, NULL))
314     return CMD_FAILURE;
315
316   if (cmd.onepage_limit == NOT_LONG)
317     cmd.onepage_limit = 50;
318
319   /* Figure out statistics to calculate. */
320   stats = 0;
321   if (cmd.a_statistics[FRQ_ST_DEFAULT] || !cmd.sbc_statistics)
322     stats |= frq_default;
323   if (cmd.a_statistics[FRQ_ST_ALL])
324     stats |= frq_all;
325   if (cmd.sort != FRQ_AVALUE && cmd.sort != FRQ_DVALUE)
326     stats &= ~frq_median;
327   for (i = 0; i < frq_n_stats; i++)
328     if (cmd.a_statistics[st_name[i].st_indx])
329       stats |= BIT_INDEX (i);
330   if (stats & frq_kurt)
331     stats |= frq_sekurt;
332   if (stats & frq_skew)
333     stats |= frq_seskew;
334
335   /* Calculate n_stats. */
336   n_stats = 0;
337   for (i = 0; i < frq_n_stats; i++)
338     if ((stats & BIT_INDEX (i)))
339       n_stats++;
340
341   /* Charting. */
342   determine_charts ();
343   if (chart != GFT_NONE || cmd.sbc_ntiles)
344     cmd.sort = FRQ_AVALUE;
345
346   /* Work out what percentiles need to be calculated */
347   if ( cmd.sbc_percentiles )
348     {
349       for ( i = 0 ; i < MAXLISTS ; ++i )
350         {
351           int pl;
352           subc_list_double *ptl_list = &cmd.dl_percentiles[i];
353           for ( pl = 0 ; pl < subc_list_double_count(ptl_list); ++pl)
354               add_percentile (subc_list_double_at(ptl_list, pl) / 100.0 );
355         }
356     }
357   if ( cmd.sbc_ntiles )
358     {
359       for ( i = 0 ; i < cmd.sbc_ntiles ; ++i )
360         {
361           int j;
362           for (j = 0; j <= cmd.n_ntiles[i]; ++j )
363               add_percentile (j / (double) cmd.n_ntiles[i]);
364         }
365     }
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 (; casereader_read (group, &c); case_destroy (&c))
379         calc (&c, ds);
380       postcalc ();
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 target;
510       struct freq **fpp;
511
512       target.value = (union value *) val;
513       fpp = (struct freq **) hsh_probe (ft->data, &target);
514
515       if (*fpp != NULL)
516         (*fpp)->count += weight;
517       else
518         {
519           struct freq *fp = pool_alloc (data_pool, sizeof *fp);
520           fp->count = weight;
521           fp->value = pool_clone (data_pool,
522                                   val,
523                                   MAX (MAX_SHORT_STRING, vf->width));
524           *fpp = fp;
525         }
526     }
527 }
528
529 /* Prepares each variable that is the target of FREQUENCIES by setting
530    up its hash table. */
531 static void
532 precalc (struct casereader *input, struct dataset *ds)
533 {
534   struct ccase c;
535   size_t i;
536
537   if (!casereader_peek (input, 0, &c))
538     return;
539   output_split_file_values (ds, &c);
540   case_destroy (&c);
541
542   pool_destroy (data_pool);
543   data_pool = pool_create ();
544
545   for (i = 0; i < n_variables; i++)
546     {
547       const struct variable *v = v_variables[i];
548       struct freq_tab *ft = &get_var_freqs (v)->tab;
549
550       ft->data = hsh_create (16, compare_freq, hash_freq, NULL, v);
551     }
552 }
553
554 /* Finishes up with the variables after frequencies have been
555    calculated.  Displays statistics, percentiles, ... */
556 static void
557 postcalc (void)
558 {
559   size_t i;
560
561   for (i = 0; i < n_variables; i++)
562     {
563       const struct variable *v = v_variables[i];
564       struct var_freqs *vf = get_var_freqs (v);
565       struct freq_tab *ft = &vf->tab;
566       int n_categories;
567       int dumped_freq_tab = 1;
568
569       postprocess_freq_tab (v);
570
571       /* Frequencies tables. */
572       n_categories = ft->n_valid + ft->n_missing;
573       if (cmd.table == FRQ_TABLE
574           || (cmd.table == FRQ_LIMIT && n_categories <= cmd.limit))
575         switch (cmd.cond)
576           {
577           case FRQ_CONDENSE:
578             dump_condensed (v);
579             break;
580           case FRQ_STANDARD:
581             dump_full (v);
582             break;
583           case FRQ_ONEPAGE:
584             if (n_categories > cmd.onepage_limit)
585               dump_condensed (v);
586             else
587               dump_full (v);
588             break;
589           default:
590             NOT_REACHED ();
591           }
592       else
593         dumped_freq_tab = 0;
594
595       /* Statistics. */
596       if (n_stats)
597         dump_statistics (v, !dumped_freq_tab);
598
599
600
601       if ( chart == GFT_HIST)
602         {
603           double d[frq_n_stats];
604           struct normal_curve norm;
605           gsl_histogram *hist ;
606
607
608           norm.N = vf->tab.valid_cases;
609
610           calc_stats (v, d);
611           norm.mean = d[frq_mean];
612           norm.stddev = d[frq_stddev];
613
614           hist = freq_tab_to_hist(ft,v);
615
616           histogram_plot(hist, var_to_string(v), &norm, normal);
617
618           gsl_histogram_free(hist);
619         }
620
621
622       if ( chart == GFT_PIE)
623         {
624           do_piechart(v_variables[i], ft);
625         }
626
627
628
629       cleanup_freq_tab (v);
630
631     }
632 }
633
634 /* Returns the comparison function that should be used for
635    sorting a frequency table by FRQ_SORT using VAR_TYPE
636    variables. */
637 static hsh_compare_func *
638 get_freq_comparator (int frq_sort, enum var_type var_type)
639 {
640   bool is_numeric = var_type == VAR_NUMERIC;
641   switch (frq_sort)
642     {
643     case FRQ_AVALUE:
644       return is_numeric ? compare_value_numeric_a : compare_value_alpha_a;
645     case FRQ_DVALUE:
646       return is_numeric ? compare_value_numeric_d : compare_value_alpha_d;
647     case FRQ_AFREQ:
648       return is_numeric ? compare_freq_numeric_a : compare_freq_alpha_a;
649     case FRQ_DFREQ:
650       return is_numeric ? compare_freq_numeric_d : compare_freq_alpha_d;
651     default:
652       NOT_REACHED ();
653     }
654 }
655
656 /* Returns true iff the value in struct freq F is non-missing
657    for variable V. */
658 static bool
659 not_missing (const void *f_, const void *v_)
660 {
661   const struct freq *f = f_;
662   const struct variable *v = v_;
663
664   return !var_is_value_missing (v, f->value, MV_ANY);
665 }
666
667 /* Summarizes the frequency table data for variable V. */
668 static void
669 postprocess_freq_tab (const struct variable *v)
670 {
671   hsh_compare_func *compare;
672   struct freq_tab *ft;
673   size_t count;
674   void *const *data;
675   struct freq *freqs, *f;
676   size_t i;
677
678   ft = &get_var_freqs (v)->tab;
679   compare = get_freq_comparator (cmd.sort, var_get_type (v));
680
681   /* Extract data from hash table. */
682   count = hsh_count (ft->data);
683   data = hsh_data (ft->data);
684
685   /* Copy dereferenced data into freqs. */
686   freqs = xnmalloc (count, sizeof *freqs);
687   for (i = 0; i < count; i++)
688     {
689       struct freq *f = data[i];
690       freqs[i] = *f;
691     }
692
693   /* Put data into ft. */
694   ft->valid = freqs;
695   ft->n_valid = partition (freqs, count, sizeof *freqs, not_missing, v);
696   ft->missing = freqs + ft->n_valid;
697   ft->n_missing = count - ft->n_valid;
698
699   /* Sort data. */
700   sort (ft->valid, ft->n_valid, sizeof *ft->valid, compare, v);
701   sort (ft->missing, ft->n_missing, sizeof *ft->missing, compare, v);
702
703   /* Summary statistics. */
704   ft->valid_cases = 0.0;
705   for(i = 0 ;  i < ft->n_valid ; ++i )
706     {
707       f = &ft->valid[i];
708       ft->valid_cases += f->count;
709
710     }
711
712   ft->total_cases = ft->valid_cases ;
713   for(i = 0 ;  i < ft->n_missing ; ++i )
714     {
715       f = &ft->missing[i];
716       ft->total_cases += f->count;
717     }
718
719 }
720
721 /* Frees the frequency table for variable V. */
722 static void
723 cleanup_freq_tab (const struct variable *v)
724 {
725   struct freq_tab *ft = &get_var_freqs (v)->tab;
726   free (ft->valid);
727   hsh_destroy (ft->data);
728 }
729
730 /* Parses the VARIABLES subcommand, adding to
731    {n_variables,v_variables}. */
732 static int
733 frq_custom_variables (struct lexer *lexer, struct dataset *ds, struct cmd_frequencies *cmd UNUSED, void *aux UNUSED)
734 {
735   size_t old_n_variables = n_variables;
736   size_t i;
737
738   lex_match (lexer, '=');
739   if (lex_token (lexer) != T_ALL && (lex_token (lexer) != T_ID
740                          || dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) == NULL))
741     return 2;
742
743   if (!parse_variables_const (lexer, dataset_dict (ds), &v_variables, &n_variables,
744                         PV_APPEND | PV_NO_SCRATCH))
745     return 0;
746
747   for (i = old_n_variables; i < n_variables; i++)
748     {
749       const struct variable *v = v_variables[i];
750       struct var_freqs *vf;
751
752       if (var_get_aux (v) != NULL)
753         {
754           msg (SE, _("Variable %s specified multiple times on VARIABLES "
755                      "subcommand."), var_get_name (v));
756           return 0;
757         }
758       vf = var_attach_aux (v, xmalloc (sizeof *vf), var_dtor_free);
759       vf->tab.valid = vf->tab.missing = NULL;
760       vf->n_groups = 0;
761       vf->groups = NULL;
762       vf->width = var_get_width (v);
763       vf->print = *var_get_print_format (v);
764       if (vf->width > MAX_SHORT_STRING && get_algorithm () == COMPATIBLE)
765         {
766           enum fmt_type type = var_get_print_format (v)->type;
767           vf->width = MAX_SHORT_STRING;
768           vf->print.w = MAX_SHORT_STRING * (type == FMT_AHEX ? 2 : 1);
769         }
770     }
771   return 1;
772 }
773
774 /* Parses the GROUPED subcommand, setting the n_grouped, grouped
775    fields of specified variables. */
776 static int
777 frq_custom_grouped (struct lexer *lexer, struct dataset *ds, struct cmd_frequencies *cmd UNUSED, void *aux UNUSED)
778 {
779   lex_match (lexer, '=');
780   if ((lex_token (lexer) == T_ID && dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) != NULL)
781       || lex_token (lexer) == T_ID)
782     for (;;)
783       {
784         size_t i;
785
786         /* Max, current size of list; list itself. */
787         int nl, ml;
788         double *dl;
789
790         /* Variable list. */
791         size_t n;
792         const struct variable **v;
793
794         if (!parse_variables_const (lexer, dataset_dict (ds), &v, &n,
795                               PV_NO_DUPLICATE | PV_NUMERIC))
796           return 0;
797         if (lex_match (lexer, '('))
798           {
799             nl = ml = 0;
800             dl = NULL;
801             while (lex_integer (lexer))
802               {
803                 if (nl >= ml)
804                   {
805                     ml += 16;
806                     dl = pool_nrealloc (syntax_pool, dl, ml, sizeof *dl);
807                   }
808                 dl[nl++] = lex_tokval (lexer);
809                 lex_get (lexer);
810                 lex_match (lexer, ',');
811               }
812             /* Note that nl might still be 0 and dl might still be
813                NULL.  That's okay. */
814             if (!lex_match (lexer, ')'))
815               {
816                 free (v);
817                 msg (SE, _("`)' expected after GROUPED interval list."));
818                 return 0;
819               }
820           }
821         else
822           {
823             nl = 0;
824             dl = NULL;
825           }
826
827         for (i = 0; i < n; i++)
828           if (var_get_aux (v[i]) == NULL)
829             msg (SE, _("Variables %s specified on GROUPED but not on "
830                        "VARIABLES."), var_get_name (v[i]));
831           else
832             {
833               struct var_freqs *vf = get_var_freqs (v[i]);
834
835               if (vf->groups != NULL)
836                 msg (SE, _("Variables %s specified multiple times on GROUPED "
837                            "subcommand."), var_get_name (v[i]));
838               else
839                 {
840                   vf->n_groups = nl;
841                   vf->groups = dl;
842                 }
843             }
844         free (v);
845         if (!lex_match (lexer, '/'))
846           break;
847         if ((lex_token (lexer) != T_ID || dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) != NULL)
848             && lex_token (lexer) != T_ALL)
849           {
850             lex_put_back (lexer, '/');
851             break;
852           }
853       }
854
855   return 1;
856 }
857
858 /* Adds X to the list of percentiles, keeping the list in proper
859    order. */
860 static void
861 add_percentile (double x)
862 {
863   int i;
864
865   for (i = 0; i < n_percentiles; i++)
866     {
867       /* Do nothing if it's already in the list */
868       if ( fabs(x - percentiles[i].p) < DBL_EPSILON )
869         return;
870
871       if (x < percentiles[i].p)
872         break;
873     }
874
875   if (i >= n_percentiles || x != percentiles[i].p)
876     {
877       percentiles = pool_nrealloc (syntax_pool, percentiles,
878                                    n_percentiles + 1, sizeof *percentiles);
879
880       if (i < n_percentiles)
881           memmove (&percentiles[i + 1], &percentiles[i],
882                    (n_percentiles - i) * sizeof (struct percentile) );
883
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   double *median_value;
1240
1241   /* Calculate percentiles. */
1242
1243   /* If the 50th percentile was not explicitly requested then we must
1244      calculate it anyway --- it's the median */
1245   median_value = 0 ;
1246   for (i = 0; i < n_percentiles; i++)
1247     {
1248       if (percentiles[i].p == 0.5)
1249         {
1250           median_value = &percentiles[i].value;
1251           break;
1252         }
1253     }
1254
1255   if ( 0 == median_value )
1256     {
1257       add_percentile (0.5);
1258       implicit_50th = 1;
1259     }
1260
1261   for (i = 0; i < n_percentiles; i++)
1262     {
1263       percentiles[i].flag = 0;
1264       percentiles[i].flag2 = 0;
1265     }
1266
1267   rank = 0;
1268   for (idx = 0; idx < ft->n_valid; ++idx)
1269     {
1270       static double prev_value = SYSMIS;
1271       f = &ft->valid[idx];
1272       rank += f->count ;
1273       for (i = 0; i < n_percentiles; i++)
1274         {
1275           double tp;
1276           if ( percentiles[i].flag2  ) continue ;
1277
1278           if ( get_algorithm() != COMPATIBLE )
1279             tp =
1280               (ft->valid_cases - 1) *  percentiles[i].p;
1281           else
1282             tp =
1283               (ft->valid_cases + 1) *  percentiles[i].p - 1;
1284
1285           if ( percentiles[i].flag )
1286             {
1287               percentiles[i].x2 = f->value[0].f;
1288               percentiles[i].x1 = prev_value;
1289               percentiles[i].flag2 = 1;
1290               continue;
1291             }
1292
1293           if (rank >  tp )
1294           {
1295             if ( f->count > 1 && rank - (f->count - 1) > tp )
1296               {
1297                 percentiles[i].x2 = percentiles[i].x1 = f->value[0].f;
1298                 percentiles[i].flag2 = 1;
1299               }
1300             else
1301               {
1302                 percentiles[i].flag=1;
1303               }
1304
1305             continue;
1306           }
1307         }
1308       prev_value = f->value[0].f;
1309     }
1310
1311   for (i = 0; i < n_percentiles; i++)
1312     {
1313       /* Catches the case when p == 100% */
1314       if ( ! percentiles[i].flag2 )
1315         percentiles[i].x1 = percentiles[i].x2 = f->value[0].f;
1316
1317       /*
1318       printf("percentile %d (p==%.2f); X1 = %g; X2 = %g\n",
1319              i,percentiles[i].p,percentiles[i].x1,percentiles[i].x2);
1320       */
1321     }
1322
1323   for (i = 0; i < n_percentiles; i++)
1324     {
1325       struct freq_tab *ft = &get_var_freqs (v)->tab;
1326       double s;
1327
1328       double dummy;
1329       if ( get_algorithm() != COMPATIBLE )
1330         {
1331           s = modf((ft->valid_cases - 1) * percentiles[i].p , &dummy);
1332         }
1333       else
1334         {
1335           s = modf((ft->valid_cases + 1) * percentiles[i].p -1, &dummy);
1336         }
1337
1338       percentiles[i].value = percentiles[i].x1 +
1339         ( percentiles[i].x2 - percentiles[i].x1) * s ;
1340
1341       if ( percentiles[i].p == 0.50)
1342         median_value = &percentiles[i].value;
1343     }
1344
1345
1346   /* Calculate the mode. */
1347   most_often = -1;
1348   X_mode = SYSMIS;
1349   for (f = ft->valid; f < ft->missing; f++)
1350     {
1351       if (most_often < f->count)
1352         {
1353           most_often = f->count;
1354           X_mode = f->value[0].f;
1355         }
1356       else if (most_often == f->count)
1357         {
1358           /* A duplicate mode is undefined.
1359              FIXME: keep track of *all* the modes. */
1360           X_mode = SYSMIS;
1361         }
1362     }
1363
1364   /* Calculate moments. */
1365   m = moments_create (MOMENT_KURTOSIS);
1366   for (f = ft->valid; f < ft->missing; f++)
1367     moments_pass_one (m, f->value[0].f, f->count);
1368   for (f = ft->valid; f < ft->missing; f++)
1369     moments_pass_two (m, f->value[0].f, f->count);
1370   moments_calculate (m, NULL, &d[frq_mean], &d[frq_variance],
1371                      &d[frq_skew], &d[frq_kurt]);
1372   moments_destroy (m);
1373
1374   /* Formulas below are taken from _SPSS Statistical Algorithms_. */
1375   d[frq_min] = ft->valid[0].value[0].f;
1376   d[frq_max] = ft->valid[ft->n_valid - 1].value[0].f;
1377   d[frq_mode] = X_mode;
1378   d[frq_range] = d[frq_max] - d[frq_min];
1379   d[frq_median] = *median_value;
1380   d[frq_sum] = d[frq_mean] * W;
1381   d[frq_stddev] = sqrt (d[frq_variance]);
1382   d[frq_semean] = d[frq_stddev] / sqrt (W);
1383   d[frq_seskew] = calc_seskew (W);
1384   d[frq_sekurt] = calc_sekurt (W);
1385 }
1386
1387 /* Displays a table of all the statistics requested for variable V. */
1388 static void
1389 dump_statistics (const struct variable *v, int show_varname)
1390 {
1391   struct freq_tab *ft;
1392   double stat_value[frq_n_stats];
1393   struct tab_table *t;
1394   int i, r;
1395
1396   int n_explicit_percentiles = n_percentiles;
1397
1398   if ( implicit_50th && n_percentiles > 0 )
1399     --n_percentiles;
1400
1401   if (var_is_alpha (v))
1402     return;
1403   ft = &get_var_freqs (v)->tab;
1404   if (ft->n_valid == 0)
1405     {
1406       msg (SW, _("No valid data for variable %s; statistics not displayed."),
1407            var_get_name (v));
1408       return;
1409     }
1410   calc_stats (v, stat_value);
1411
1412   t = tab_create (3, n_stats + n_explicit_percentiles + 2, 0);
1413   tab_dim (t, tab_natural_dimensions);
1414
1415   tab_box (t, TAL_1, TAL_1, -1, -1 , 0 , 0 , 2, tab_nr(t) - 1) ;
1416
1417
1418   tab_vline (t, TAL_1 , 2, 0, tab_nr(t) - 1);
1419   tab_vline (t, TAL_GAP , 1, 0, tab_nr(t) - 1 ) ;
1420
1421   r=2; /* N missing and N valid are always dumped */
1422
1423   for (i = 0; i < frq_n_stats; i++)
1424     if (stats & BIT_INDEX (i))
1425       {
1426         tab_text (t, 0, r, TAB_LEFT | TAT_TITLE,
1427                       gettext (st_name[i].s10));
1428         tab_float (t, 2, r, TAB_NONE, stat_value[i], 11, 3);
1429         r++;
1430       }
1431
1432   tab_text (t, 0, 0, TAB_LEFT | TAT_TITLE, _("N"));
1433   tab_text (t, 1, 0, TAB_LEFT | TAT_TITLE, _("Valid"));
1434   tab_text (t, 1, 1, TAB_LEFT | TAT_TITLE, _("Missing"));
1435
1436   tab_float(t, 2, 0, TAB_NONE, ft->valid_cases, 11, 0);
1437   tab_float(t, 2, 1, TAB_NONE, ft->total_cases - ft->valid_cases, 11, 0);
1438
1439
1440   for (i = 0; i < n_explicit_percentiles; i++, r++)
1441     {
1442       if ( i == 0 )
1443         {
1444           tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, _("Percentiles"));
1445         }
1446
1447       tab_float (t, 1, r, TAB_LEFT, percentiles[i].p * 100, 3, 0 );
1448       tab_float (t, 2, r, TAB_NONE, percentiles[i].value, 11, 3);
1449
1450     }
1451
1452   tab_columns (t, SOM_COL_DOWN, 1);
1453   if (show_varname)
1454     tab_title (t, "%s", var_to_string (v));
1455   else
1456     tab_flags (t, SOMF_NO_TITLE);
1457
1458
1459   tab_submit (t);
1460 }
1461
1462
1463 /* Create a gsl_histogram from a freq_tab */
1464 gsl_histogram *
1465 freq_tab_to_hist(const struct freq_tab *ft, const struct variable *var)
1466 {
1467   int i;
1468   double x_min = DBL_MAX;
1469   double x_max = -DBL_MAX;
1470
1471   gsl_histogram *hist;
1472   const double bins = 11;
1473
1474   struct hsh_iterator hi;
1475   struct hsh_table *fh = ft->data;
1476   struct freq *frq;
1477
1478   /* Find out the extremes of the x value */
1479   for ( frq = hsh_first(fh, &hi); frq != 0; frq = hsh_next(fh, &hi) )
1480     {
1481       if (var_is_value_missing(var, frq->value, MV_ANY))
1482         continue;
1483
1484       if ( frq->value[0].f < x_min ) x_min = frq->value[0].f ;
1485       if ( frq->value[0].f > x_max ) x_max = frq->value[0].f ;
1486     }
1487
1488   hist = histogram_create(bins, x_min, x_max);
1489
1490   for( i = 0 ; i < ft->n_valid ; ++i )
1491     {
1492       frq = &ft->valid[i];
1493       gsl_histogram_accumulate(hist, frq->value[0].f, frq->count);
1494     }
1495
1496   return hist;
1497 }
1498
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
1506 /* Allocate an array of slices and fill them from the data in frq_tab
1507    n_slices will contain the number of slices allocated.
1508    The caller is responsible for freeing slices
1509 */
1510 static struct slice *
1511 freq_tab_to_slice_array(const struct freq_tab *frq_tab,
1512                         const struct variable *var,
1513                         int *n_slices)
1514 {
1515   int i;
1516   struct slice *slices;
1517
1518   *n_slices = frq_tab->n_valid;
1519
1520   slices = xnmalloc (*n_slices, sizeof *slices);
1521
1522   for (i = 0 ; i < *n_slices ; ++i )
1523     {
1524       const struct freq *frq = &frq_tab->valid[i];
1525
1526       slices[i].label = var_get_value_name (var, frq->value);
1527       slices[i].magnetude = frq->count;
1528     }
1529
1530   return slices;
1531 }
1532
1533
1534
1535
1536 static void
1537 do_piechart(const struct variable *var, const struct freq_tab *frq_tab)
1538 {
1539   struct slice *slices;
1540   int n_slices;
1541
1542   slices = freq_tab_to_slice_array(frq_tab, var, &n_slices);
1543
1544   piechart_plot(var_to_string(var), slices, n_slices);
1545
1546   free(slices);
1547 }
1548
1549
1550 /*
1551    Local Variables:
1552    mode: c
1553    End:
1554 */