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