Rewrite PSPP output engine.
[pspp-builds.git] / src / language / stats / frequencies.q
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2007, 2009 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/array.h>
42 #include <libpspp/bit-vector.h>
43 #include <libpspp/compiler.h>
44 #include <libpspp/hash.h>
45 #include <libpspp/message.h>
46 #include <libpspp/misc.h>
47 #include <libpspp/pool.h>
48 #include <libpspp/str.h>
49 #include <math/histogram.h>
50 #include <math/moments.h>
51 #include <output/chart-item.h>
52 #include <output/charts/piechart.h>
53 #include <output/charts/plot-hist.h>
54 #include <output/tab.h>
55
56 #include "freq.h"
57
58 #include "minmax.h"
59 #include "xalloc.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 const 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 /* Groups of statistics. */
157 #define BI          BIT_INDEX
158 #define frq_default                                                     \
159         (BI (frq_mean) | BI (frq_stddev) | BI (frq_min) | BI (frq_max))
160 #define frq_all                                                 \
161         (BI (frq_sum) | BI(frq_min) | BI(frq_max)               \
162          | BI(frq_mean) | BI(frq_semean) | BI(frq_stddev)       \
163          | BI(frq_variance) | BI(frq_kurt) | BI(frq_sekurt)     \
164          | BI(frq_skew) | BI(frq_seskew) | BI(frq_range)        \
165          | BI(frq_range) | BI(frq_mode) | BI(frq_median))
166
167 /* Statistics; number of statistics. */
168 static unsigned long stats;
169 static int n_stats;
170
171 /* Types of graphs. */
172 enum
173   {
174     GFT_NONE,                   /* Don't draw graphs. */
175     GFT_BAR,                    /* Draw bar charts. */
176     GFT_HIST,                   /* Draw histograms. */
177     GFT_PIE,                    /* Draw piechart */
178     GFT_HBAR                    /* Draw bar charts or histograms at our discretion. */
179   };
180
181 /* Parsed command. */
182 static struct cmd_frequencies cmd;
183
184 /* Summary of the barchart, histogram, and hbar subcommands. */
185 /* FIXME: These should not be mututally exclusive */
186 static int chart;               /* NONE/BAR/HIST/HBAR/PIE. */
187 static double min, max;         /* Minimum, maximum on y axis. */
188 static int format;              /* FREQ/PERCENT: Scaling of y axis. */
189 static double scale, incr;      /* FIXME */
190 static int normal;              /* FIXME */
191
192 /* Variables for which to calculate statistics. */
193 static size_t n_variables;
194 static const struct variable **v_variables;
195
196 /* Pools. */
197 static struct pool *data_pool;          /* For per-SPLIT FILE group data. */
198 static struct pool *syntax_pool;        /* For syntax-related data. */
199
200 /* Frequency tables. */
201
202 /* Entire frequency table. */
203 struct freq_tab
204   {
205     struct hsh_table *data;     /* Undifferentiated data. */
206     struct freq_mutable *valid; /* Valid freqs. */
207     int n_valid;                /* Number of total freqs. */
208     const struct dictionary *dict; /* The dict from whence entries in the table
209                                       come */
210
211     struct freq_mutable *missing; /* Missing freqs. */
212     int n_missing;              /* Number of missing freqs. */
213
214     /* Statistics. */
215     double total_cases;         /* Sum of weights of all cases. */
216     double valid_cases;         /* Sum of weights of valid cases. */
217   };
218
219
220 /* Per-variable frequency data. */
221 struct var_freqs
222   {
223     /* Freqency table. */
224     struct freq_tab tab;        /* Frequencies table to use. */
225
226     /* Percentiles. */
227     int n_groups;               /* Number of groups. */
228     double *groups;             /* Groups. */
229
230     /* Statistics. */
231     double stat[frq_n_stats];
232
233     /* Variable attributes. */
234     int width;
235     struct fmt_spec print;
236   };
237
238 static inline struct var_freqs *
239 get_var_freqs (const struct variable *v)
240 {
241   return var_get_aux (v);
242 }
243
244 static void determine_charts (void);
245
246 static void calc_stats (const struct variable *v, double d[frq_n_stats]);
247
248 static void precalc (struct casereader *, struct dataset *);
249 static void calc (const struct ccase *, const struct dataset *);
250 static void postcalc (const struct dataset *);
251
252 static void postprocess_freq_tab (const struct variable *);
253 static void dump_full ( const struct variable *, const struct variable *);
254 static void dump_condensed (const struct variable *, const struct variable *);
255 static void dump_statistics (const struct variable *, bool show_varname, const struct variable *);
256 static void cleanup_freq_tab (const struct variable *);
257
258 static hsh_compare_func compare_value_numeric_a, compare_value_alpha_a;
259 static hsh_compare_func compare_value_numeric_d, compare_value_alpha_d;
260 static hsh_compare_func compare_freq_numeric_a, compare_freq_alpha_a;
261 static hsh_compare_func compare_freq_numeric_d, compare_freq_alpha_d;
262
263
264 static void do_piechart(const struct variable *var,
265                         const struct freq_tab *frq_tab);
266
267 struct histogram *
268 freq_tab_to_hist(const struct freq_tab *ft, const struct variable *var);
269
270
271 \f
272 /* Parser and outline. */
273
274 static int internal_cmd_frequencies (struct lexer *lexer, struct dataset *ds);
275
276 int
277 cmd_frequencies (struct lexer *lexer, struct dataset *ds)
278 {
279   int result;
280
281   syntax_pool = pool_create ();
282   result = internal_cmd_frequencies (lexer, ds);
283   pool_destroy (syntax_pool);
284   syntax_pool=0;
285   pool_destroy (data_pool);
286   data_pool=0;
287   free (v_variables);
288   v_variables=0;
289   return result;
290 }
291
292 static int
293 internal_cmd_frequencies (struct lexer *lexer, struct dataset *ds)
294 {
295   struct casegrouper *grouper;
296   struct casereader *input, *group;
297   bool ok;
298   int i;
299
300   n_percentiles = 0;
301   percentiles = NULL;
302
303   n_variables = 0;
304   v_variables = NULL;
305
306   if (!parse_frequencies (lexer, ds, &cmd, NULL))
307     return CMD_FAILURE;
308
309   if (cmd.onepage_limit == LONG_MIN)
310     cmd.onepage_limit = 50;
311
312   /* Figure out statistics to calculate. */
313   stats = 0;
314   if (cmd.a_statistics[FRQ_ST_DEFAULT] || !cmd.sbc_statistics)
315     stats |= frq_default;
316   if (cmd.a_statistics[FRQ_ST_ALL])
317     stats |= frq_all;
318   if (cmd.sort != FRQ_AVALUE && cmd.sort != FRQ_DVALUE)
319     stats &= ~BIT_INDEX (frq_median);
320   for (i = 0; i < frq_n_stats; i++)
321     if (cmd.a_statistics[st_name[i].st_indx])
322       stats |= BIT_INDEX (i);
323   if (stats & frq_kurt)
324     stats |= BIT_INDEX (frq_sekurt);
325   if (stats & frq_skew)
326     stats |= BIT_INDEX (frq_seskew);
327
328   /* Calculate n_stats. */
329   n_stats = 0;
330   for (i = 0; i < frq_n_stats; i++)
331     if ((stats & BIT_INDEX (i)))
332       n_stats++;
333
334   /* Charting. */
335   determine_charts ();
336   if (chart != GFT_NONE || cmd.sbc_ntiles)
337     cmd.sort = FRQ_AVALUE;
338
339   /* Work out what percentiles need to be calculated */
340   if ( cmd.sbc_percentiles )
341     {
342       for ( i = 0 ; i < MAXLISTS ; ++i )
343         {
344           int pl;
345           subc_list_double *ptl_list = &cmd.dl_percentiles[i];
346           for ( pl = 0 ; pl < subc_list_double_count(ptl_list); ++pl)
347               add_percentile (subc_list_double_at(ptl_list, pl) / 100.0 );
348         }
349     }
350   if ( cmd.sbc_ntiles )
351     {
352       for ( i = 0 ; i < cmd.sbc_ntiles ; ++i )
353         {
354           int j;
355           for (j = 0; j <= cmd.n_ntiles[i]; ++j )
356               add_percentile (j / (double) cmd.n_ntiles[i]);
357         }
358     }
359   if (stats & BIT_INDEX (frq_median))
360     {
361       /* Treat the median as the 50% percentile.
362          We output it in the percentiles table as "50 (Median)." */
363       add_percentile (0.5);
364       stats &= ~BIT_INDEX (frq_median);
365       n_stats--;
366     }
367
368   /* Do it! */
369   input = casereader_create_filter_weight (proc_open (ds), dataset_dict (ds),
370                                            NULL, NULL);
371   grouper = casegrouper_create_splits (input, dataset_dict (ds));
372   for (; casegrouper_get_next_group (grouper, &group);
373        casereader_destroy (group))
374     {
375       struct ccase *c;
376
377       precalc (group, ds);
378       for (; (c = casereader_read (group)) != NULL; case_unref (c))
379         calc (c, ds);
380       postcalc (ds);
381     }
382   ok = casegrouper_destroy (grouper);
383   ok = proc_commit (ds) && ok;
384
385   free_frequencies(&cmd);
386
387   return ok ? CMD_SUCCESS : CMD_CASCADING_FAILURE;
388 }
389
390 /* Figure out which charts the user requested.  */
391 static void
392 determine_charts (void)
393 {
394   int count = (!!cmd.sbc_histogram) + (!!cmd.sbc_barchart) +
395     (!!cmd.sbc_hbar) + (!!cmd.sbc_piechart);
396
397   if (!count)
398     {
399       chart = GFT_NONE;
400       return;
401     }
402   else if (count > 1)
403     {
404       chart = GFT_HBAR;
405       msg (SW, _("At most one of BARCHART, HISTOGRAM, or HBAR should be "
406            "given.  HBAR will be assumed.  Argument values will be "
407            "given precedence increasing along the order given."));
408     }
409   else if (cmd.sbc_histogram)
410     chart = GFT_HIST;
411   else if (cmd.sbc_barchart)
412     chart = GFT_BAR;
413   else if (cmd.sbc_piechart)
414     chart = GFT_PIE;
415   else
416     chart = GFT_HBAR;
417
418   min = max = SYSMIS;
419   format = FRQ_FREQ;
420   scale = SYSMIS;
421   incr = SYSMIS;
422   normal = 0;
423
424   if (cmd.sbc_barchart)
425     {
426       if (cmd.ba_min != SYSMIS)
427         min = cmd.ba_min;
428       if (cmd.ba_max != SYSMIS)
429         max = cmd.ba_max;
430       if (cmd.ba_scale == FRQ_FREQ)
431         {
432           format = FRQ_FREQ;
433           scale = cmd.ba_freq;
434         }
435       else if (cmd.ba_scale == FRQ_PERCENT)
436         {
437           format = FRQ_PERCENT;
438           scale = cmd.ba_pcnt;
439         }
440     }
441
442   if (cmd.sbc_histogram)
443     {
444       if (cmd.hi_min != SYSMIS)
445         min = cmd.hi_min;
446       if (cmd.hi_max != SYSMIS)
447         max = cmd.hi_max;
448       if (cmd.hi_scale == FRQ_FREQ)
449         {
450           format = FRQ_FREQ;
451           scale = cmd.hi_freq;
452         }
453       else if (cmd.hi_scale == FRQ_PERCENT)
454         {
455           format = FRQ_PERCENT;
456           scale = cmd.ba_pcnt;
457         }
458       if (cmd.hi_norm != FRQ_NONORMAL )
459         normal = 1;
460       if (cmd.hi_incr == FRQ_INCREMENT)
461         incr = cmd.hi_inc;
462     }
463
464   if (cmd.sbc_hbar)
465     {
466       if (cmd.hb_min != SYSMIS)
467         min = cmd.hb_min;
468       if (cmd.hb_max != SYSMIS)
469         max = cmd.hb_max;
470       if (cmd.hb_scale == FRQ_FREQ)
471         {
472           format = FRQ_FREQ;
473           scale = cmd.hb_freq;
474         }
475       else if (cmd.hb_scale == FRQ_PERCENT)
476         {
477           format = FRQ_PERCENT;
478           scale = cmd.ba_pcnt;
479         }
480       if (cmd.hb_norm)
481         normal = 1;
482       if (cmd.hb_incr == FRQ_INCREMENT)
483         incr = cmd.hb_inc;
484     }
485
486   if (min != SYSMIS && max != SYSMIS && min >= max)
487     {
488       msg (SE, _("MAX must be greater than or equal to MIN, if both are "
489            "specified.  However, MIN was specified as %g and MAX as %g.  "
490            "MIN and MAX will be ignored."), min, max);
491       min = max = SYSMIS;
492     }
493 }
494
495 /* Add data from case C to the frequency table. */
496 static void
497 calc (const struct ccase *c, const struct dataset *ds)
498 {
499   double weight = dict_get_case_weight (dataset_dict (ds), c, NULL);
500   size_t i;
501
502   for (i = 0; i < n_variables; i++)
503     {
504       const struct variable *v = v_variables[i];
505       const union value *val = case_data (c, v);
506       struct var_freqs *vf = get_var_freqs (v);
507       struct freq_tab *ft = &vf->tab;
508
509       struct freq_mutable target;
510       struct freq_mutable **fpp;
511
512       target.value = *val;
513       fpp = (struct freq_mutable **) hsh_probe (ft->data, &target);
514
515       if (*fpp != NULL)
516         (*fpp)->count += weight;
517       else
518         {
519           struct freq_mutable *fp = pool_alloc (data_pool, sizeof *fp);
520           fp->count = weight;
521           value_init_pool (data_pool, &fp->value, vf->width);
522           value_copy (&fp->value, val, vf->width);
523           *fpp = fp;
524         }
525     }
526 }
527
528 /* Prepares each variable that is the target of FREQUENCIES by setting
529    up its hash table. */
530 static void
531 precalc (struct casereader *input, struct dataset *ds)
532 {
533   struct ccase *c;
534   size_t i;
535
536   c = casereader_peek (input, 0);
537   if (c != NULL)
538     {
539       output_split_file_values (ds, c);
540       case_unref (c);
541     }
542
543   pool_destroy (data_pool);
544   data_pool = pool_create ();
545
546   for (i = 0; i < n_variables; i++)
547     {
548       const struct variable *v = v_variables[i];
549       struct freq_tab *ft = &get_var_freqs (v)->tab;
550
551       ft->data = hsh_create (16, compare_freq, hash_freq, NULL, v);
552     }
553 }
554
555 /* Finishes up with the variables after frequencies have been
556    calculated.  Displays statistics, percentiles, ... */
557 static void
558 postcalc (const struct dataset *ds)
559 {
560   const struct dictionary *dict = dataset_dict (ds);
561   const struct variable *wv = dict_get_weight (dict);
562   size_t i;
563
564   for (i = 0; i < n_variables; i++)
565     {
566       const struct variable *v = v_variables[i];
567       struct var_freqs *vf = get_var_freqs (v);
568       struct freq_tab *ft = &vf->tab;
569       int n_categories;
570       int dumped_freq_tab = 1;
571
572       postprocess_freq_tab (v);
573
574       /* Frequencies tables. */
575       n_categories = ft->n_valid + ft->n_missing;
576       if (cmd.table == FRQ_TABLE
577           || (cmd.table == FRQ_LIMIT && n_categories <= cmd.limit))
578         switch (cmd.cond)
579           {
580           case FRQ_CONDENSE:
581             dump_condensed (v, wv);
582             break;
583           case FRQ_STANDARD:
584             dump_full (v, wv);
585             break;
586           case FRQ_ONEPAGE:
587             if (n_categories > cmd.onepage_limit)
588               dump_condensed (v, wv);
589             else
590               dump_full (v, wv);
591             break;
592           default:
593             NOT_REACHED ();
594           }
595       else
596         dumped_freq_tab = 0;
597
598       /* Statistics. */
599       if (n_stats)
600         dump_statistics (v, !dumped_freq_tab, wv);
601
602
603
604       if ( chart == GFT_HIST && var_is_numeric (v) )
605         {
606           double d[frq_n_stats];
607           struct histogram *hist ;
608
609           calc_stats (v, d);
610
611           hist = freq_tab_to_hist (ft,v);
612
613           chart_item_submit (histogram_chart_create (
614                                hist->gsl_hist, var_to_string(v),
615                                vf->tab.valid_cases,
616                                d[frq_mean],
617                                d[frq_stddev],
618                                normal));
619
620           statistic_destroy (&hist->parent);
621         }
622
623       if ( chart == GFT_PIE)
624         {
625           do_piechart(v_variables[i], ft);
626         }
627
628       cleanup_freq_tab (v);
629
630     }
631 }
632
633 /* Returns the comparison function that should be used for
634    sorting a frequency table by FRQ_SORT using VAL_TYPE
635    values. */
636 static hsh_compare_func *
637 get_freq_comparator (int frq_sort, enum val_type val_type)
638 {
639   bool is_numeric = val_type == VAL_NUMERIC;
640   switch (frq_sort)
641     {
642     case FRQ_AVALUE:
643       return is_numeric ? compare_value_numeric_a : compare_value_alpha_a;
644     case FRQ_DVALUE:
645       return is_numeric ? compare_value_numeric_d : compare_value_alpha_d;
646     case FRQ_AFREQ:
647       return is_numeric ? compare_freq_numeric_a : compare_freq_alpha_a;
648     case FRQ_DFREQ:
649       return is_numeric ? compare_freq_numeric_d : compare_freq_alpha_d;
650     default:
651       NOT_REACHED ();
652     }
653 }
654
655 /* Returns true iff the value in struct freq_mutable F is non-missing
656    for variable V. */
657 static bool
658 not_missing (const void *f_, const void *v_)
659 {
660   const struct freq_mutable *f = f_;
661   const struct variable *v = v_;
662
663   return !var_is_value_missing (v, &f->value, MV_ANY);
664 }
665
666 /* Summarizes the frequency table data for variable V. */
667 static void
668 postprocess_freq_tab (const struct variable *v)
669 {
670   hsh_compare_func *compare;
671   struct freq_tab *ft;
672   size_t count;
673   void *const *data;
674   struct freq_mutable *freqs, *f;
675   size_t i;
676
677   ft = &get_var_freqs (v)->tab;
678   compare = get_freq_comparator (cmd.sort, var_get_type (v));
679
680   /* Extract data from hash table. */
681   count = hsh_count (ft->data);
682   data = hsh_data (ft->data);
683
684   /* Copy dereferenced data into freqs. */
685   freqs = xnmalloc (count, sizeof *freqs);
686   for (i = 0; i < count; i++)
687     {
688       struct freq_mutable *f = data[i];
689       freqs[i] = *f;
690     }
691
692   /* Put data into ft. */
693   ft->valid = freqs;
694   ft->n_valid = partition (freqs, count, sizeof *freqs, not_missing, v);
695   ft->missing = freqs + ft->n_valid;
696   ft->n_missing = count - ft->n_valid;
697
698   /* Sort data. */
699   sort (ft->valid, ft->n_valid, sizeof *ft->valid, compare, v);
700   sort (ft->missing, ft->n_missing, sizeof *ft->missing, compare, v);
701
702   /* Summary statistics. */
703   ft->valid_cases = 0.0;
704   for(i = 0 ;  i < ft->n_valid ; ++i )
705     {
706       f = &ft->valid[i];
707       ft->valid_cases += f->count;
708
709     }
710
711   ft->total_cases = ft->valid_cases ;
712   for(i = 0 ;  i < ft->n_missing ; ++i )
713     {
714       f = &ft->missing[i];
715       ft->total_cases += f->count;
716     }
717
718 }
719
720 /* Frees the frequency table for variable V. */
721 static void
722 cleanup_freq_tab (const struct variable *v)
723 {
724   struct freq_tab *ft = &get_var_freqs (v)->tab;
725   free (ft->valid);
726   hsh_destroy (ft->data);
727 }
728
729 /* Parses the VARIABLES subcommand, adding to
730    {n_variables,v_variables}. */
731 static int
732 frq_custom_variables (struct lexer *lexer, struct dataset *ds, struct cmd_frequencies *cmd UNUSED, void *aux UNUSED)
733 {
734   size_t old_n_variables = n_variables;
735   size_t i;
736
737   lex_match (lexer, '=');
738   if (lex_token (lexer) != T_ALL && (lex_token (lexer) != T_ID
739                          || dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) == NULL))
740     return 2;
741
742   if (!parse_variables_const (lexer, dataset_dict (ds), &v_variables, &n_variables,
743                         PV_APPEND | PV_NO_SCRATCH))
744     return 0;
745
746   for (i = old_n_variables; i < n_variables; i++)
747     {
748       const struct variable *v = v_variables[i];
749       struct var_freqs *vf;
750
751       if (var_get_aux (v) != NULL)
752         {
753           msg (SE, _("Variable %s specified multiple times on VARIABLES "
754                      "subcommand."), var_get_name (v));
755           return 0;
756         }
757       vf = var_attach_aux (v, xmalloc (sizeof *vf), var_dtor_free);
758       vf->tab.valid = vf->tab.missing = NULL;
759       vf->tab.dict = dataset_dict (ds);
760       vf->n_groups = 0;
761       vf->groups = NULL;
762       vf->width = var_get_width (v);
763       vf->print = *var_get_print_format (v);
764     }
765   return 1;
766 }
767
768 /* Parses the GROUPED subcommand, setting the n_grouped, grouped
769    fields of specified variables. */
770 static int
771 frq_custom_grouped (struct lexer *lexer, struct dataset *ds, struct cmd_frequencies *cmd UNUSED, void *aux UNUSED)
772 {
773   lex_match (lexer, '=');
774   if ((lex_token (lexer) == T_ID && dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) != NULL)
775       || lex_token (lexer) == T_ID)
776     for (;;)
777       {
778         size_t i;
779
780         /* Max, current size of list; list itself. */
781         int nl, ml;
782         double *dl;
783
784         /* Variable list. */
785         size_t n;
786         const struct variable **v;
787
788         if (!parse_variables_const (lexer, dataset_dict (ds), &v, &n,
789                               PV_NO_DUPLICATE | PV_NUMERIC))
790           return 0;
791         if (lex_match (lexer, '('))
792           {
793             nl = ml = 0;
794             dl = NULL;
795             while (lex_integer (lexer))
796               {
797                 if (nl >= ml)
798                   {
799                     ml += 16;
800                     dl = pool_nrealloc (syntax_pool, dl, ml, sizeof *dl);
801                   }
802                 dl[nl++] = lex_tokval (lexer);
803                 lex_get (lexer);
804                 lex_match (lexer, ',');
805               }
806             /* Note that nl might still be 0 and dl might still be
807                NULL.  That's okay. */
808             if (!lex_match (lexer, ')'))
809               {
810                 free (v);
811                 msg (SE, _("`)' expected after GROUPED interval list."));
812                 return 0;
813               }
814           }
815         else
816           {
817             nl = 0;
818             dl = NULL;
819           }
820
821         for (i = 0; i < n; i++)
822           if (var_get_aux (v[i]) == NULL)
823             msg (SE, _("Variables %s specified on GROUPED but not on "
824                        "VARIABLES."), var_get_name (v[i]));
825           else
826             {
827               struct var_freqs *vf = get_var_freqs (v[i]);
828
829               if (vf->groups != NULL)
830                 msg (SE, _("Variables %s specified multiple times on GROUPED "
831                            "subcommand."), var_get_name (v[i]));
832               else
833                 {
834                   vf->n_groups = nl;
835                   vf->groups = dl;
836                 }
837             }
838         free (v);
839         if (!lex_match (lexer, '/'))
840           break;
841         if ((lex_token (lexer) != T_ID || dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) != NULL)
842             && lex_token (lexer) != T_ALL)
843           {
844             lex_put_back (lexer, '/');
845             break;
846           }
847       }
848
849   return 1;
850 }
851
852 /* Adds X to the list of percentiles, keeping the list in proper
853    order. */
854 static void
855 add_percentile (double x)
856 {
857   int i;
858
859   for (i = 0; i < n_percentiles; i++)
860     {
861       /* Do nothing if it's already in the list */
862       if ( fabs(x - percentiles[i].p) < DBL_EPSILON )
863         return;
864
865       if (x < percentiles[i].p)
866         break;
867     }
868
869   if (i >= n_percentiles || x != percentiles[i].p)
870     {
871       percentiles = pool_nrealloc (syntax_pool, percentiles,
872                                    n_percentiles + 1, sizeof *percentiles);
873       insert_element (percentiles, n_percentiles, sizeof *percentiles, i);
874       percentiles[i].p = x;
875       n_percentiles++;
876     }
877 }
878
879 /* Comparison functions. */
880
881 /* Ascending numeric compare of values. */
882 static int
883 compare_value_numeric_a (const void *a_, const void *b_, const void *aux UNUSED)
884 {
885   const struct freq_mutable *a = a_;
886   const struct freq_mutable *b = b_;
887
888   if (a->value.f > b->value.f)
889     return 1;
890   else if (a->value.f < b->value.f)
891     return -1;
892   else
893     return 0;
894 }
895
896 /* Ascending string compare of values. */
897 static int
898 compare_value_alpha_a (const void *a_, const void *b_, const void *v_)
899 {
900   const struct freq_mutable *a = a_;
901   const struct freq_mutable *b = b_;
902   const struct variable *v = v_;
903   struct var_freqs *vf = get_var_freqs (v);
904
905   return value_compare_3way (&a->value, &b->value, vf->width);
906 }
907
908 /* Descending numeric compare of values. */
909 static int
910 compare_value_numeric_d (const void *a, const void *b, const void *aux UNUSED)
911 {
912   return -compare_value_numeric_a (a, b, aux);
913 }
914
915 /* Descending string compare of values. */
916 static int
917 compare_value_alpha_d (const void *a, const void *b, const void *v)
918 {
919   return -compare_value_alpha_a (a, b, v);
920 }
921
922 /* Ascending numeric compare of frequency;
923    secondary key on ascending numeric value. */
924 static int
925 compare_freq_numeric_a (const void *a_, const void *b_, const void *aux UNUSED)
926 {
927   const struct freq_mutable *a = a_;
928   const struct freq_mutable *b = b_;
929
930   if (a->count > b->count)
931     return 1;
932   else if (a->count < b->count)
933     return -1;
934
935   if (a->value.f > b->value.f)
936     return 1;
937   else if (a->value.f < b->value.f)
938     return -1;
939   else
940     return 0;
941 }
942
943 /* Ascending numeric compare of frequency;
944    secondary key on ascending string value. */
945 static int
946 compare_freq_alpha_a (const void *a_, const void *b_, const void *v_)
947 {
948   const struct freq_mutable *a = a_;
949   const struct freq_mutable *b = b_;
950   const struct variable *v = v_;
951   struct var_freqs *vf = get_var_freqs (v);
952
953   if (a->count > b->count)
954     return 1;
955   else if (a->count < b->count)
956     return -1;
957   else
958     return value_compare_3way (&a->value, &b->value, vf->width);
959 }
960
961 /* Descending numeric compare of frequency;
962    secondary key on ascending numeric value. */
963 static int
964 compare_freq_numeric_d (const void *a_, const void *b_, const void *aux UNUSED)
965 {
966   const struct freq_mutable *a = a_;
967   const struct freq_mutable *b = b_;
968
969   if (a->count > b->count)
970     return -1;
971   else if (a->count < b->count)
972     return 1;
973
974   if (a->value.f > b->value.f)
975     return 1;
976   else if (a->value.f < b->value.f)
977     return -1;
978   else
979     return 0;
980 }
981
982 /* Descending numeric compare of frequency;
983    secondary key on ascending string value. */
984 static int
985 compare_freq_alpha_d (const void *a_, const void *b_, const void *v_)
986 {
987   const struct freq_mutable *a = a_;
988   const struct freq_mutable *b = b_;
989   const struct variable *v = v_;
990   struct var_freqs *vf = get_var_freqs (v);
991
992   if (a->count > b->count)
993     return -1;
994   else if (a->count < b->count)
995     return 1;
996   else
997     return value_compare_3way (&a->value, &b->value, vf->width);
998 }
999 \f
1000 /* Frequency table display. */
1001
1002 /* Displays a full frequency table for variable V. */
1003 static void
1004 dump_full (const struct variable *v, const struct variable *wv)
1005 {
1006   const struct fmt_spec *wfmt = wv ? var_get_print_format (wv) : &F_8_0;
1007   int n_categories;
1008   struct var_freqs *vf;
1009   struct freq_tab *ft;
1010   struct freq_mutable *f;
1011   struct tab_table *t;
1012   int r, x;
1013   double cum_total = 0.0;
1014   double cum_freq = 0.0;
1015
1016   static const char *headings[] = {
1017     N_("Value"),
1018     N_("Frequency"),
1019     N_("Percent"),
1020     N_("Valid Percent"),
1021     N_("Cum Percent")
1022   };
1023
1024   const bool lab = (cmd.labels == FRQ_LABELS);
1025
1026   vf = get_var_freqs (v);
1027   ft = &vf->tab;
1028   n_categories = ft->n_valid + ft->n_missing;
1029   t = tab_create (5 + lab, n_categories + 2);
1030   tab_headers (t, 0, 0, 1, 0);
1031
1032   if (lab)
1033     tab_text (t, 0, 0, TAB_CENTER | TAT_TITLE, _("Value Label"));
1034
1035   for (x = 0; x < 5; x++)
1036     tab_text (t, lab + x, 0, TAB_CENTER | TAT_TITLE, gettext (headings[x]));
1037
1038   r = 1;
1039   for (f = ft->valid; f < ft->missing; f++)
1040     {
1041       double percent, valid_percent;
1042
1043       cum_freq += f->count;
1044
1045       percent = f->count / ft->total_cases * 100.0;
1046       valid_percent = f->count / ft->valid_cases * 100.0;
1047       cum_total += valid_percent;
1048
1049       if (lab)
1050         {
1051           const char *label = var_lookup_value_label (v, &f->value);
1052           if (label != NULL)
1053             tab_text (t, 0, r, TAB_LEFT, label);
1054         }
1055
1056       tab_value (t, 0 + lab, r, TAB_NONE, &f->value, ft->dict, &vf->print);
1057       tab_double (t, 1 + lab, r, TAB_NONE, f->count, wfmt);
1058       tab_double (t, 2 + lab, r, TAB_NONE, percent, NULL);
1059       tab_double (t, 3 + lab, r, TAB_NONE, valid_percent, NULL);
1060       tab_double (t, 4 + lab, r, TAB_NONE, cum_total, NULL);
1061       r++;
1062     }
1063   for (; f < &ft->valid[n_categories]; f++)
1064     {
1065       cum_freq += f->count;
1066
1067       if (lab)
1068         {
1069           const char *label = var_lookup_value_label (v, &f->value);
1070           if (label != NULL)
1071             tab_text (t, 0, r, TAB_LEFT, label);
1072         }
1073
1074       tab_value (t, 0 + lab, r, TAB_NONE, &f->value, ft->dict, &vf->print);
1075       tab_double (t, 1 + lab, r, TAB_NONE, f->count, wfmt);
1076       tab_double (t, 2 + lab, r, TAB_NONE,
1077                      f->count / ft->total_cases * 100.0, NULL);
1078       tab_text (t, 3 + lab, r, TAB_NONE, _("Missing"));
1079       r++;
1080     }
1081
1082   tab_box (t, TAL_1, TAL_1,
1083            cmd.spaces == FRQ_SINGLE ? -1 : TAL_GAP, TAL_1,
1084            0, 0, 4 + lab, r);
1085   tab_hline (t, TAL_2, 0, 4 + lab, 1);
1086   tab_hline (t, TAL_2, 0, 4 + lab, r);
1087   tab_joint_text (t, 0, r, 0 + lab, r, TAB_RIGHT | TAT_TITLE, _("Total"));
1088   tab_vline (t, TAL_0, 1, r, r);
1089   tab_double (t, 1 + lab, r, TAB_NONE, cum_freq, wfmt);
1090   tab_fixed (t, 2 + lab, r, TAB_NONE, 100.0, 5, 1);
1091   tab_fixed (t, 3 + lab, r, TAB_NONE, 100.0, 5, 1);
1092
1093   tab_title (t, "%s", var_to_string (v));
1094   tab_submit (t);
1095 }
1096
1097 /* Display condensed frequency table for variable V. */
1098 static void
1099 dump_condensed (const struct variable *v, const struct variable *wv)
1100 {
1101   const struct fmt_spec *wfmt = wv ? var_get_print_format (wv) : &F_8_0;
1102   int n_categories;
1103   struct var_freqs *vf;
1104   struct freq_tab *ft;
1105   struct freq_mutable *f;
1106   struct tab_table *t;
1107   int r;
1108   double cum_total = 0.0;
1109
1110   vf = get_var_freqs (v);
1111   ft = &vf->tab;
1112   n_categories = ft->n_valid + ft->n_missing;
1113   t = tab_create (4, n_categories + 2);
1114
1115   tab_headers (t, 0, 0, 2, 0);
1116   tab_text (t, 0, 1, TAB_CENTER | TAT_TITLE, _("Value"));
1117   tab_text (t, 1, 1, TAB_CENTER | TAT_TITLE, _("Freq"));
1118   tab_text (t, 2, 1, TAB_CENTER | TAT_TITLE, _("Pct"));
1119   tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("Cum"));
1120   tab_text (t, 3, 1, TAB_CENTER | TAT_TITLE, _("Pct"));
1121
1122   r = 2;
1123   for (f = ft->valid; f < ft->missing; f++)
1124     {
1125       double percent;
1126
1127       percent = f->count / ft->total_cases * 100.0;
1128       cum_total += f->count / ft->valid_cases * 100.0;
1129
1130       tab_value (t, 0, r, TAB_NONE, &f->value, ft->dict, &vf->print);
1131       tab_double (t, 1, r, TAB_NONE, f->count, wfmt);
1132       tab_double (t, 2, r, TAB_NONE, percent, NULL);
1133       tab_double (t, 3, r, TAB_NONE, cum_total, NULL);
1134       r++;
1135     }
1136   for (; f < &ft->valid[n_categories]; f++)
1137     {
1138       tab_value (t, 0, r, TAB_NONE, &f->value, ft->dict, &vf->print);
1139       tab_double (t, 1, r, TAB_NONE, f->count, wfmt);
1140       tab_double (t, 2, r, TAB_NONE,
1141                  f->count / ft->total_cases * 100.0, NULL);
1142       r++;
1143     }
1144
1145   tab_box (t, TAL_1, TAL_1,
1146            cmd.spaces == FRQ_SINGLE ? -1 : TAL_GAP, TAL_1,
1147            0, 0, 3, r - 1);
1148   tab_hline (t, TAL_2, 0, 3, 2);
1149   tab_title (t, "%s", var_to_string (v));
1150   tab_submit (t);
1151 }
1152 \f
1153 /* Statistical display. */
1154
1155 /* Calculates all the pertinent statistics for variable V, putting
1156    them in array D[].  FIXME: This could be made much more optimal. */
1157 static void
1158 calc_stats (const struct variable *v, double d[frq_n_stats])
1159 {
1160   struct freq_tab *ft = &get_var_freqs (v)->tab;
1161   double W = ft->valid_cases;
1162   struct moments *m;
1163   struct freq_mutable *f=0;
1164   int most_often;
1165   double X_mode;
1166
1167   double rank;
1168   int i = 0;
1169   int idx;
1170
1171   /* Calculate percentiles. */
1172
1173   for (i = 0; i < n_percentiles; i++)
1174     {
1175       percentiles[i].flag = 0;
1176       percentiles[i].flag2 = 0;
1177     }
1178
1179   rank = 0;
1180   for (idx = 0; idx < ft->n_valid; ++idx)
1181     {
1182       static double prev_value = SYSMIS;
1183       f = &ft->valid[idx];
1184       rank += f->count ;
1185       for (i = 0; i < n_percentiles; i++)
1186         {
1187           double tp;
1188           if ( percentiles[i].flag2  ) continue ;
1189
1190           if ( settings_get_algorithm () != COMPATIBLE )
1191             tp =
1192               (ft->valid_cases - 1) *  percentiles[i].p;
1193           else
1194             tp =
1195               (ft->valid_cases + 1) *  percentiles[i].p - 1;
1196
1197           if ( percentiles[i].flag )
1198             {
1199               percentiles[i].x2 = f->value.f;
1200               percentiles[i].x1 = prev_value;
1201               percentiles[i].flag2 = 1;
1202               continue;
1203             }
1204
1205           if (rank >  tp )
1206           {
1207             if ( f->count > 1 && rank - (f->count - 1) > tp )
1208               {
1209                 percentiles[i].x2 = percentiles[i].x1 = f->value.f;
1210                 percentiles[i].flag2 = 1;
1211               }
1212             else
1213               {
1214                 percentiles[i].flag=1;
1215               }
1216
1217             continue;
1218           }
1219         }
1220       prev_value = f->value.f;
1221     }
1222
1223   for (i = 0; i < n_percentiles; i++)
1224     {
1225       /* Catches the case when p == 100% */
1226       if ( ! percentiles[i].flag2 )
1227         percentiles[i].x1 = percentiles[i].x2 = f->value.f;
1228
1229       /*
1230       printf("percentile %d (p==%.2f); X1 = %g; X2 = %g\n",
1231              i,percentiles[i].p,percentiles[i].x1,percentiles[i].x2);
1232       */
1233     }
1234
1235   for (i = 0; i < n_percentiles; i++)
1236     {
1237       struct freq_tab *ft = &get_var_freqs (v)->tab;
1238       double s;
1239
1240       double dummy;
1241       if ( settings_get_algorithm () != COMPATIBLE )
1242         {
1243           s = modf((ft->valid_cases - 1) * percentiles[i].p , &dummy);
1244         }
1245       else
1246         {
1247           s = modf((ft->valid_cases + 1) * percentiles[i].p -1, &dummy);
1248         }
1249
1250       percentiles[i].value = percentiles[i].x1 +
1251         ( percentiles[i].x2 - percentiles[i].x1) * s ;
1252     }
1253
1254
1255   /* Calculate the mode. */
1256   most_often = -1;
1257   X_mode = SYSMIS;
1258   for (f = ft->valid; f < ft->missing; f++)
1259     {
1260       if (most_often < f->count)
1261         {
1262           most_often = f->count;
1263           X_mode = f->value.f;
1264         }
1265       else if (most_often == f->count)
1266         {
1267           /* A duplicate mode is undefined.
1268              FIXME: keep track of *all* the modes. */
1269           X_mode = SYSMIS;
1270         }
1271     }
1272
1273   /* Calculate moments. */
1274   m = moments_create (MOMENT_KURTOSIS);
1275   for (f = ft->valid; f < ft->missing; f++)
1276     moments_pass_one (m, f->value.f, f->count);
1277   for (f = ft->valid; f < ft->missing; f++)
1278     moments_pass_two (m, f->value.f, f->count);
1279   moments_calculate (m, NULL, &d[frq_mean], &d[frq_variance],
1280                      &d[frq_skew], &d[frq_kurt]);
1281   moments_destroy (m);
1282
1283   /* Formulas below are taken from _SPSS Statistical Algorithms_. */
1284   d[frq_min] = ft->valid[0].value.f;
1285   d[frq_max] = ft->valid[ft->n_valid - 1].value.f;
1286   d[frq_mode] = X_mode;
1287   d[frq_range] = d[frq_max] - d[frq_min];
1288   d[frq_sum] = d[frq_mean] * W;
1289   d[frq_stddev] = sqrt (d[frq_variance]);
1290   d[frq_semean] = d[frq_stddev] / sqrt (W);
1291   d[frq_seskew] = calc_seskew (W);
1292   d[frq_sekurt] = calc_sekurt (W);
1293 }
1294
1295 /* Displays a table of all the statistics requested for variable V. */
1296 static void
1297 dump_statistics (const struct variable *v, bool show_varname,
1298                  const struct variable *wv)
1299 {
1300   const struct fmt_spec *wfmt = wv ? var_get_print_format (wv) : &F_8_0;
1301   struct freq_tab *ft;
1302   double stat_value[frq_n_stats];
1303   struct tab_table *t;
1304   int i, r;
1305
1306   if (var_is_alpha (v))
1307     return;
1308   ft = &get_var_freqs (v)->tab;
1309   if (ft->n_valid == 0)
1310     {
1311       msg (SW, _("No valid data for variable %s; statistics not displayed."),
1312            var_get_name (v));
1313       return;
1314     }
1315   calc_stats (v, stat_value);
1316
1317   t = tab_create (3, n_stats + n_percentiles + 2);
1318
1319   tab_box (t, TAL_1, TAL_1, -1, -1 , 0 , 0 , 2, tab_nr(t) - 1) ;
1320
1321
1322   tab_vline (t, TAL_1 , 2, 0, tab_nr(t) - 1);
1323   tab_vline (t, TAL_GAP , 1, 0, tab_nr(t) - 1 ) ;
1324
1325   r=2; /* N missing and N valid are always dumped */
1326
1327   for (i = 0; i < frq_n_stats; i++)
1328     if (stats & BIT_INDEX (i))
1329       {
1330         tab_text (t, 0, r, TAB_LEFT | TAT_TITLE,
1331                       gettext (st_name[i].s10));
1332         tab_double (t, 2, r, TAB_NONE, stat_value[i], NULL);
1333         r++;
1334       }
1335
1336   tab_text (t, 0, 0, TAB_LEFT | TAT_TITLE, _("N"));
1337   tab_text (t, 1, 0, TAB_LEFT | TAT_TITLE, _("Valid"));
1338   tab_text (t, 1, 1, TAB_LEFT | TAT_TITLE, _("Missing"));
1339
1340   tab_double (t, 2, 0, TAB_NONE, ft->valid_cases, wfmt);
1341   tab_double (t, 2, 1, TAB_NONE, ft->total_cases - ft->valid_cases, wfmt);
1342
1343   for (i = 0; i < n_percentiles; i++, r++)
1344     {
1345       if ( i == 0 )
1346         {
1347           tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, _("Percentiles"));
1348         }
1349
1350       if (percentiles[i].p == 0.5)
1351         tab_text (t, 1, r, TAB_LEFT, _("50 (Median)"));
1352       else
1353         tab_fixed (t, 1, r, TAB_LEFT, percentiles[i].p * 100, 3, 0);
1354       tab_double (t, 2, r, TAB_NONE, percentiles[i].value,
1355                   var_get_print_format (v));
1356     }
1357
1358   if (show_varname)
1359     tab_title (t, "%s", var_to_string (v));
1360
1361
1362   tab_submit (t);
1363 }
1364
1365
1366 /* Create a gsl_histogram from a freq_tab */
1367 struct histogram *
1368 freq_tab_to_hist (const struct freq_tab *ft, const struct variable *var)
1369 {
1370   int i;
1371   double x_min = DBL_MAX;
1372   double x_max = -DBL_MAX;
1373
1374   struct histogram *hist;
1375   const double bins = 11;
1376
1377   struct hsh_iterator hi;
1378   struct hsh_table *fh = ft->data;
1379   struct freq_mutable *frq;
1380
1381   /* Find out the extremes of the x value */
1382   for ( frq = hsh_first(fh, &hi); frq != 0; frq = hsh_next(fh, &hi) )
1383     {
1384       if (var_is_value_missing(var, &frq->value, MV_ANY))
1385         continue;
1386
1387       if ( frq->value.f < x_min ) x_min = frq->value.f ;
1388       if ( frq->value.f > x_max ) x_max = frq->value.f ;
1389     }
1390
1391   hist = histogram_create (bins, x_min, x_max);
1392
1393   for( i = 0 ; i < ft->n_valid ; ++i )
1394     {
1395       frq = &ft->valid[i];
1396       histogram_add (hist, frq->value.f, frq->count);
1397     }
1398
1399   return hist;
1400 }
1401
1402
1403 static struct slice *
1404 freq_tab_to_slice_array(const struct freq_tab *frq_tab,
1405                         const struct variable *var,
1406                         int *n_slices);
1407
1408
1409 /* Allocate an array of slices and fill them from the data in frq_tab
1410    n_slices will contain the number of slices allocated.
1411    The caller is responsible for freeing slices
1412 */
1413 static struct slice *
1414 freq_tab_to_slice_array(const struct freq_tab *frq_tab,
1415                         const struct variable *var,
1416                         int *n_slices)
1417 {
1418   int i;
1419   struct slice *slices;
1420
1421   *n_slices = frq_tab->n_valid;
1422
1423   slices = xnmalloc (*n_slices, sizeof *slices);
1424
1425   for (i = 0 ; i < *n_slices ; ++i )
1426     {
1427       const struct freq_mutable *frq = &frq_tab->valid[i];
1428
1429       ds_init_empty (&slices[i].label);
1430       var_append_value_name (var, &frq->value, &slices[i].label);
1431       slices[i].magnitude = frq->count;
1432     }
1433
1434   return slices;
1435 }
1436
1437
1438
1439
1440 static void
1441 do_piechart(const struct variable *var, const struct freq_tab *frq_tab)
1442 {
1443   struct slice *slices;
1444   int n_slices, i;
1445
1446   slices = freq_tab_to_slice_array(frq_tab, var, &n_slices);
1447
1448   chart_item_submit (piechart_create (var_to_string(var), slices, n_slices));
1449
1450   for (i = 0 ; i < n_slices ; ++i )
1451     ds_destroy (&slices[i].label);
1452
1453   free (slices);
1454 }
1455
1456
1457 /*
1458    Local Variables:
1459    mode: c
1460    End:
1461 */