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