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