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