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