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