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