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