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