1 /* PSPP - computes sample statistics.
2 Copyright (C) 1997-9, 2000 Free Software Foundation, Inc.
3 Written by Ben Pfaff <blp@gnu.org>.
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.
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.
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., 59 Temple Place - Suite 330, Boston, MA
23 * Remember that histograms, bar charts need mean, stddev.
30 #include <gsl/gsl_histogram.h>
33 #include "bitvector.h"
35 #include "dictionary.h"
42 #include "algorithm.h"
49 #include "value-labels.h"
56 #include "debug-print.h"
61 format=cond:condense/onepage(*n:onepage_limit,"%s>=0")/!standard,
62 table:limit(n:limit,"%s>0")/notable/!table,
63 labels:!labels/nolabels,
64 sort:!avalue/dvalue/afreq/dfreq,
65 spaces:!single/double,
66 paging:newpage/!oldpage;
67 missing=miss:include/!exclude;
68 barchart(ba_)=:minimum(d:min),
70 scale:freq(*n:freq,"%s>0")/percent(*n:pcnt,"%s>0");
71 piechart(pie_)=:minimum(d:min),
73 missing:missing/!nomissing;
74 histogram(hi_)=:minimum(d:min),
76 scale:freq(*n:freq,"%s>0")/percent(*n:pcnt,"%s>0"),
77 norm:!nonormal/normal,
78 incr:increment(d:inc,"%s>0");
79 hbar(hb_)=:minimum(d:min),
81 scale:freq(*n:freq,"%s>0")/percent(*n:pcnt,"%s>0"),
82 norm:!nonormal/normal,
83 incr:increment(d:inc,"%s>0");
86 +percentiles = double list;
87 statistics[st_]=1|mean,2|semean,3|median,4|mode,5|stddev,6|variance,
88 7|kurtosis,8|skewness,9|range,10|minimum,11|maximum,12|sum,
89 13|default,14|seskewness,15|sekurtosis,all,none.
97 frq_mean = 0, frq_semean, frq_median, frq_mode, frq_stddev, frq_variance,
98 frq_kurt, frq_sekurt, frq_skew, frq_seskew, frq_range, frq_min, frq_max,
102 /* Description of a statistic. */
105 int st_indx; /* Index into a_statistics[]. */
106 const char *s10; /* Identifying string. */
109 /* Table of statistics, indexed by dsc_*. */
110 static struct frq_info st_name[frq_n_stats + 1] =
112 {FRQ_ST_MEAN, N_("Mean")},
113 {FRQ_ST_SEMEAN, N_("S.E. Mean")},
114 {FRQ_ST_MEDIAN, N_("Median")},
115 {FRQ_ST_MODE, N_("Mode")},
116 {FRQ_ST_STDDEV, N_("Std Dev")},
117 {FRQ_ST_VARIANCE, N_("Variance")},
118 {FRQ_ST_KURTOSIS, N_("Kurtosis")},
119 {FRQ_ST_SEKURTOSIS, N_("S.E. Kurt")},
120 {FRQ_ST_SKEWNESS, N_("Skewness")},
121 {FRQ_ST_SESKEWNESS, N_("S.E. Skew")},
122 {FRQ_ST_RANGE, N_("Range")},
123 {FRQ_ST_MINIMUM, N_("Minimum")},
124 {FRQ_ST_MAXIMUM, N_("Maximum")},
125 {FRQ_ST_SUM, N_("Sum")},
129 /* Percentiles to calculate. */
133 double p; /* the %ile to be calculated */
134 double value; /* the %ile's value */
135 double x1; /* The datum value <= the percentile */
136 double x2; /* The datum value >= the percentile */
138 int flag2; /* Set to 1 if this percentile value has been found */
142 static void add_percentile (double x) ;
144 static struct percentile *percentiles;
145 static int n_percentiles;
147 static int implicit_50th ;
149 /* Groups of statistics. */
151 #define frq_default \
152 (BI (frq_mean) | BI (frq_stddev) | BI (frq_min) | BI (frq_max))
154 (BI (frq_sum) | BI(frq_min) | BI(frq_max) \
155 | BI(frq_mean) | BI(frq_semean) | BI(frq_stddev) \
156 | BI(frq_variance) | BI(frq_kurt) | BI(frq_sekurt) \
157 | BI(frq_skew) | BI(frq_seskew) | BI(frq_range) \
158 | BI(frq_range) | BI(frq_mode) | BI(frq_median))
160 /* Statistics; number of statistics. */
161 static unsigned long stats;
164 /* Types of graphs. */
167 GFT_NONE, /* Don't draw graphs. */
168 GFT_BAR, /* Draw bar charts. */
169 GFT_HIST, /* Draw histograms. */
170 GFT_PIE, /* Draw piechart */
171 GFT_HBAR /* Draw bar charts or histograms at our discretion. */
174 /* Parsed command. */
175 static struct cmd_frequencies cmd;
177 /* Summary of the barchart, histogram, and hbar subcommands. */
178 /* FIXME: These should not be mututally exclusive */
179 static int chart; /* NONE/BAR/HIST/HBAR/PIE. */
180 static double min, max; /* Minimum, maximum on y axis. */
181 static int format; /* FREQ/PERCENT: Scaling of y axis. */
182 static double scale, incr; /* FIXME */
183 static int normal; /* FIXME */
185 /* Variables for which to calculate statistics. */
186 static int n_variables;
187 static struct variable **v_variables;
189 /* Arenas used to store semi-permanent storage. */
190 static struct pool *int_pool; /* Integer mode. */
191 static struct pool *gen_pool; /* General mode. */
193 /* Frequency tables. */
195 /* Frequency table entry. */
198 union value v; /* The value. */
199 double c; /* The number of occurrences of the value. */
202 /* Types of frequency tables. */
209 /* Entire frequency table. */
212 int mode; /* FRQM_GENERAL or FRQM_INTEGER. */
215 struct hsh_table *data; /* Undifferentiated data. */
218 double *vector; /* Frequencies proper. */
219 int min, max; /* The boundaries of the table. */
220 double out_of_range; /* Sum of weights of out-of-range values. */
221 double sysmis; /* Sum of weights of SYSMIS values. */
224 struct freq *valid; /* Valid freqs. */
225 int n_valid; /* Number of total freqs. */
227 struct freq *missing; /* Missing freqs. */
228 int n_missing; /* Number of missing freqs. */
231 double total_cases; /* Sum of weights of all cases. */
232 double valid_cases; /* Sum of weights of valid cases. */
236 /* Per-variable frequency data. */
239 /* Freqency table. */
240 struct freq_tab tab; /* Frequencies table to use. */
243 int n_groups; /* Number of groups. */
244 double *groups; /* Groups. */
247 double stat[frq_n_stats];
250 static inline struct var_freqs *
251 get_var_freqs (struct variable *v)
254 assert (v->aux != NULL);
258 static void determine_charts (void);
260 static void calc_stats (struct variable *v, double d[frq_n_stats]);
262 static void precalc (void *);
263 static int calc (struct ccase *, void *);
264 static void postcalc (void *);
266 static void postprocess_freq_tab (struct variable *);
267 static void dump_full (struct variable *);
268 static void dump_condensed (struct variable *);
269 static void dump_statistics (struct variable *, int show_varname);
270 static void cleanup_freq_tab (struct variable *);
272 static hsh_hash_func hash_value_numeric, hash_value_alpha;
273 static hsh_compare_func compare_value_numeric_a, compare_value_alpha_a;
274 static hsh_compare_func compare_value_numeric_d, compare_value_alpha_d;
275 static hsh_compare_func compare_freq_numeric_a, compare_freq_alpha_a;
276 static hsh_compare_func compare_freq_numeric_d, compare_freq_alpha_d;
279 static void do_piechart(const struct variable *var,
280 const struct freq_tab *frq_tab);
283 freq_tab_to_hist(const struct freq_tab *ft, const struct variable *var);
287 /* Parser and outline. */
289 static int internal_cmd_frequencies (void);
292 cmd_frequencies (void)
296 int_pool = pool_create ();
297 result = internal_cmd_frequencies ();
298 pool_destroy (int_pool);
300 pool_destroy (gen_pool);
308 internal_cmd_frequencies (void)
318 if (!parse_frequencies (&cmd))
321 if (cmd.onepage_limit == NOT_LONG)
322 cmd.onepage_limit = 50;
324 /* Figure out statistics to calculate. */
326 if (cmd.a_statistics[FRQ_ST_DEFAULT] || !cmd.sbc_statistics)
327 stats |= frq_default;
328 if (cmd.a_statistics[FRQ_ST_ALL])
330 if (cmd.sort != FRQ_AVALUE && cmd.sort != FRQ_DVALUE)
331 stats &= ~frq_median;
332 for (i = 0; i < frq_n_stats; i++)
333 if (cmd.a_statistics[st_name[i].st_indx])
334 stats |= BIT_INDEX (i);
335 if (stats & frq_kurt)
337 if (stats & frq_skew)
340 /* Calculate n_stats. */
342 for (i = 0; i < frq_n_stats; i++)
343 if ((stats & BIT_INDEX (i)))
348 if (chart != GFT_NONE || cmd.sbc_ntiles)
349 cmd.sort = FRQ_AVALUE;
351 /* Work out what percentiles need to be calculated */
352 if ( cmd.sbc_percentiles )
354 for ( i = 0 ; i < MAXLISTS ; ++i )
357 subc_list_double *ptl_list = &cmd.dl_percentiles[i];
358 for ( pl = 0 ; pl < subc_list_double_count(ptl_list); ++pl)
359 add_percentile(subc_list_double_at(ptl_list,pl) / 100.0 );
362 if ( cmd.sbc_ntiles )
364 for ( i = 0 ; i < cmd.sbc_ntiles ; ++i )
367 for (j = 0; j <= cmd.n_ntiles[i]; ++j )
368 add_percentile(j / (double) cmd.n_ntiles[i]);
374 procedure_with_splits (precalc, calc, postcalc, NULL);
376 free_frequencies(&cmd);
381 /* Figure out which charts the user requested. */
383 determine_charts (void)
385 int count = (!!cmd.sbc_histogram) + (!!cmd.sbc_barchart) +
386 (!!cmd.sbc_hbar) + (!!cmd.sbc_piechart);
396 msg (SW, _("At most one of BARCHART, HISTOGRAM, or HBAR should be "
397 "given. HBAR will be assumed. Argument values will be "
398 "given precedence increasing along the order given."));
400 else if (cmd.sbc_histogram)
402 else if (cmd.sbc_barchart)
404 else if (cmd.sbc_piechart)
415 if (cmd.sbc_barchart)
417 if (cmd.ba_min != SYSMIS)
419 if (cmd.ba_max != SYSMIS)
421 if (cmd.ba_scale == FRQ_FREQ)
426 else if (cmd.ba_scale == FRQ_PERCENT)
428 format = FRQ_PERCENT;
433 if (cmd.sbc_histogram)
435 if (cmd.hi_min != SYSMIS)
437 if (cmd.hi_max != SYSMIS)
439 if (cmd.hi_scale == FRQ_FREQ)
444 else if (cmd.hi_scale == FRQ_PERCENT)
446 format = FRQ_PERCENT;
449 if (cmd.hi_norm != FRQ_NONORMAL )
451 if (cmd.hi_incr == FRQ_INCREMENT)
457 if (cmd.hb_min != SYSMIS)
459 if (cmd.hb_max != SYSMIS)
461 if (cmd.hb_scale == FRQ_FREQ)
466 else if (cmd.hb_scale == FRQ_PERCENT)
468 format = FRQ_PERCENT;
473 if (cmd.hb_incr == FRQ_INCREMENT)
477 if (min != SYSMIS && max != SYSMIS && min >= max)
479 msg (SE, _("MAX must be greater than or equal to MIN, if both are "
480 "specified. However, MIN was specified as %g and MAX as %g. "
481 "MIN and MAX will be ignored."), min, max);
486 /* Add data from case C to the frequency table. */
488 calc (struct ccase *c, void *aux UNUSED)
494 weight = dict_get_case_weight (default_dict, c, &bad_warn);
496 for (i = 0; i < n_variables; i++)
498 struct variable *v = v_variables[i];
499 const union value *val = case_data (c, v->fv);
500 struct freq_tab *ft = &get_var_freqs (v)->tab;
508 struct freq **fpp = (struct freq **) hsh_probe (ft->data, val);
514 struct freq *fp = *fpp = pool_alloc (gen_pool, sizeof *fp);
522 if (val->f == SYSMIS)
523 ft->sysmis += weight;
524 else if (val->f > INT_MIN+1 && val->f < INT_MAX-1)
527 if (i >= ft->min && i <= ft->max)
528 ft->vector[i - ft->min] += weight;
531 ft->out_of_range += weight;
540 /* Prepares each variable that is the target of FREQUENCIES by setting
541 up its hash table. */
543 precalc (void *aux UNUSED)
547 pool_destroy (gen_pool);
548 gen_pool = pool_create ();
550 for (i = 0; i < n_variables; i++)
552 struct variable *v = v_variables[i];
553 struct freq_tab *ft = &get_var_freqs (v)->tab;
555 if (ft->mode == FRQM_GENERAL)
558 hsh_compare_func *compare;
560 if (v->type == NUMERIC)
562 hash = hash_value_numeric;
563 compare = compare_value_numeric_a;
567 hash = hash_value_alpha;
568 compare = compare_value_alpha_a;
570 ft->data = hsh_create (16, compare, hash, NULL, v);
576 for (j = (ft->max - ft->min); j >= 0; j--)
578 ft->out_of_range = 0.0;
584 /* Finishes up with the variables after frequencies have been
585 calculated. Displays statistics, percentiles, ... */
587 postcalc (void *aux UNUSED)
591 for (i = 0; i < n_variables; i++)
593 struct variable *v = v_variables[i];
594 struct var_freqs *vf = get_var_freqs (v);
595 struct freq_tab *ft = &vf->tab;
597 int dumped_freq_tab = 1;
599 postprocess_freq_tab (v);
601 /* Frequencies tables. */
602 n_categories = ft->n_valid + ft->n_missing;
603 if (cmd.table == FRQ_TABLE
604 || (cmd.table == FRQ_LIMIT && n_categories <= cmd.limit))
614 if (n_categories > cmd.onepage_limit)
627 dump_statistics (v, !dumped_freq_tab);
630 if ( chart == GFT_HIST)
632 double d[frq_n_stats];
633 struct normal_curve norm;
634 gsl_histogram *hist ;
637 norm.N = vf->tab.valid_cases;
640 norm.mean = d[frq_mean];
641 norm.stddev = d[frq_stddev];
643 hist = freq_tab_to_hist(ft,v);
645 histogram_plot(hist, var_to_string(v), &norm, normal);
647 gsl_histogram_free(hist);
651 if ( chart == GFT_PIE)
653 do_piechart(v_variables[i], ft);
657 cleanup_freq_tab (v);
662 /* Returns the comparison function that should be used for
663 sorting a frequency table by FRQ_SORT using VAR_TYPE
665 static hsh_compare_func *
666 get_freq_comparator (int frq_sort, int var_type)
668 /* Note that q2c generates tags beginning with 1000. */
669 switch (frq_sort | (var_type << 16))
671 case FRQ_AVALUE | (NUMERIC << 16): return compare_value_numeric_a;
672 case FRQ_AVALUE | (ALPHA << 16): return compare_value_alpha_a;
673 case FRQ_DVALUE | (NUMERIC << 16): return compare_value_numeric_d;
674 case FRQ_DVALUE | (ALPHA << 16): return compare_value_alpha_d;
675 case FRQ_AFREQ | (NUMERIC << 16): return compare_freq_numeric_a;
676 case FRQ_AFREQ | (ALPHA << 16): return compare_freq_alpha_a;
677 case FRQ_DFREQ | (NUMERIC << 16): return compare_freq_numeric_d;
678 case FRQ_DFREQ | (ALPHA << 16): return compare_freq_alpha_d;
685 /* Returns nonzero iff the value in struct freq F is non-missing
688 not_missing (const void *f_, void *v_)
690 const struct freq *f = f_;
691 struct variable *v = v_;
693 return !is_missing (&f->v, v);
696 /* Summarizes the frequency table data for variable V. */
698 postprocess_freq_tab (struct variable *v)
700 hsh_compare_func *compare;
704 struct freq *freqs, *f;
707 ft = &get_var_freqs (v)->tab;
708 assert (ft->mode == FRQM_GENERAL);
709 compare = get_freq_comparator (cmd.sort, v->type);
711 /* Extract data from hash table. */
712 count = hsh_count (ft->data);
713 data = hsh_data (ft->data);
715 /* Copy dereferenced data into freqs. */
716 freqs = xmalloc (count * sizeof *freqs);
717 for (i = 0; i < count; i++)
719 struct freq *f = data[i];
723 /* Put data into ft. */
725 ft->n_valid = partition (freqs, count, sizeof *freqs, not_missing, v);
726 ft->missing = freqs + ft->n_valid;
727 ft->n_missing = count - ft->n_valid;
730 sort (ft->valid, ft->n_valid, sizeof *ft->valid, compare, v);
731 sort (ft->missing, ft->n_missing, sizeof *ft->missing, compare, v);
733 /* Summary statistics. */
734 ft->valid_cases = 0.0;
735 for(i = 0 ; i < ft->n_valid ; ++i )
738 ft->valid_cases += f->c;
742 ft->total_cases = ft->valid_cases ;
743 for(i = 0 ; i < ft->n_missing ; ++i )
746 ft->total_cases += f->c;
751 /* Frees the frequency table for variable V. */
753 cleanup_freq_tab (struct variable *v)
755 struct freq_tab *ft = &get_var_freqs (v)->tab;
756 assert (ft->mode == FRQM_GENERAL);
758 hsh_destroy (ft->data);
761 /* Parses the VARIABLES subcommand, adding to
762 {n_variables,v_variables}. */
764 frq_custom_variables (struct cmd_frequencies *cmd UNUSED)
767 int min = 0, max = 0;
769 int old_n_variables = n_variables;
773 if (token != T_ALL && (token != T_ID
774 || dict_lookup_var (default_dict, tokid) == NULL))
777 if (!parse_variables (default_dict, &v_variables, &n_variables,
778 PV_APPEND | PV_NO_SCRATCH))
781 if (!lex_match ('('))
786 if (!lex_force_int ())
788 min = lex_integer ();
790 if (!lex_force_match (','))
792 if (!lex_force_int ())
794 max = lex_integer ();
796 if (!lex_force_match (')'))
800 msg (SE, _("Upper limit of integer mode value range must be "
801 "greater than lower limit."));
806 for (i = old_n_variables; i < n_variables; i++)
808 struct variable *v = v_variables[i];
809 struct var_freqs *vf;
813 msg (SE, _("Variable %s specified multiple times on VARIABLES "
814 "subcommand."), v->name);
817 if (mode == FRQM_INTEGER && v->type != NUMERIC)
819 msg (SE, _("Integer mode specified, but %s is not a numeric "
820 "variable."), v->name);
824 vf = var_attach_aux (v, xmalloc (sizeof *vf), var_dtor_free);
826 vf->tab.valid = vf->tab.missing = NULL;
827 if (mode == FRQM_INTEGER)
831 vf->tab.vector = pool_alloc (int_pool,
832 sizeof (struct freq) * (max - min + 1));
835 vf->tab.vector = NULL;
842 /* Parses the GROUPED subcommand, setting the n_grouped, grouped
843 fields of specified variables. */
845 frq_custom_grouped (struct cmd_frequencies *cmd UNUSED)
848 if ((token == T_ID && dict_lookup_var (default_dict, tokid) != NULL)
854 /* Max, current size of list; list itself. */
862 if (!parse_variables (default_dict, &v, &n,
863 PV_NO_DUPLICATE | PV_NUMERIC))
869 while (token == T_NUM)
874 dl = pool_realloc (int_pool, dl, ml * sizeof (double));
880 /* Note that nl might still be 0 and dl might still be
881 NULL. That's okay. */
882 if (!lex_match (')'))
885 msg (SE, _("`)' expected after GROUPED interval list."));
895 for (i = 0; i < n; i++)
896 if (v[i]->aux == NULL)
897 msg (SE, _("Variables %s specified on GROUPED but not on "
898 "VARIABLES."), v[i]->name);
901 struct var_freqs *vf = get_var_freqs (v[i]);
903 if (vf->groups != NULL)
904 msg (SE, _("Variables %s specified multiple times on GROUPED "
905 "subcommand."), v[i]->name);
913 if (!lex_match ('/'))
915 if ((token != T_ID || dict_lookup_var (default_dict, tokid) != NULL)
926 /* Adds X to the list of percentiles, keeping the list in proper
929 add_percentile (double x)
933 for (i = 0; i < n_percentiles; i++)
935 /* Do nothing if it's already in the list */
936 if ( fabs(x - percentiles[i].p) < DBL_EPSILON )
939 if (x < percentiles[i].p)
943 if (i >= n_percentiles || tokval != percentiles[i].p)
946 = pool_realloc (int_pool, percentiles,
947 (n_percentiles + 1) * sizeof (struct percentile ));
949 if (i < n_percentiles)
950 memmove (&percentiles[i + 1], &percentiles[i],
951 (n_percentiles - i) * sizeof (struct percentile) );
953 percentiles[i].p = x;
958 /* Comparison functions. */
960 /* Hash of numeric values. */
962 hash_value_numeric (const void *value_, void *foo UNUSED)
964 const struct freq *value = value_;
965 return hsh_hash_double (value->v.f);
968 /* Hash of string values. */
970 hash_value_alpha (const void *value_, void *v_)
972 const struct freq *value = value_;
973 struct variable *v = v_;
975 return hsh_hash_bytes (value->v.s, v->width);
978 /* Ascending numeric compare of values. */
980 compare_value_numeric_a (const void *a_, const void *b_, void *foo UNUSED)
982 const struct freq *a = a_;
983 const struct freq *b = b_;
987 else if (a->v.f < b->v.f)
993 /* Ascending string compare of values. */
995 compare_value_alpha_a (const void *a_, const void *b_, void *v_)
997 const struct freq *a = a_;
998 const struct freq *b = b_;
999 const struct variable *v = v_;
1001 return memcmp (a->v.s, b->v.s, v->width);
1004 /* Descending numeric compare of values. */
1006 compare_value_numeric_d (const void *a, const void *b, void *foo UNUSED)
1008 return -compare_value_numeric_a (a, b, foo);
1011 /* Descending string compare of values. */
1013 compare_value_alpha_d (const void *a, const void *b, void *v)
1015 return -compare_value_alpha_a (a, b, v);
1018 /* Ascending numeric compare of frequency;
1019 secondary key on ascending numeric value. */
1021 compare_freq_numeric_a (const void *a_, const void *b_, void *foo UNUSED)
1023 const struct freq *a = a_;
1024 const struct freq *b = b_;
1028 else if (a->c < b->c)
1031 if (a->v.f > b->v.f)
1033 else if (a->v.f < b->v.f)
1039 /* Ascending numeric compare of frequency;
1040 secondary key on ascending string value. */
1042 compare_freq_alpha_a (const void *a_, const void *b_, void *v_)
1044 const struct freq *a = a_;
1045 const struct freq *b = b_;
1046 const struct variable *v = v_;
1050 else if (a->c < b->c)
1053 return memcmp (a->v.s, b->v.s, v->width);
1056 /* Descending numeric compare of frequency;
1057 secondary key on ascending numeric value. */
1059 compare_freq_numeric_d (const void *a_, const void *b_, void *foo UNUSED)
1061 const struct freq *a = a_;
1062 const struct freq *b = b_;
1066 else if (a->c < b->c)
1069 if (a->v.f > b->v.f)
1071 else if (a->v.f < b->v.f)
1077 /* Descending numeric compare of frequency;
1078 secondary key on ascending string value. */
1080 compare_freq_alpha_d (const void *a_, const void *b_, void *v_)
1082 const struct freq *a = a_;
1083 const struct freq *b = b_;
1084 const struct variable *v = v_;
1088 else if (a->c < b->c)
1091 return memcmp (a->v.s, b->v.s, v->width);
1094 /* Frequency table display. */
1096 /* Sets the widths of all the columns and heights of all the rows in
1097 table T for driver D. */
1099 full_dim (struct tab_table *t, struct outp_driver *d)
1101 int lab = cmd.labels == FRQ_LABELS;
1105 t->w[0] = min (tab_natural_width (t, d, 0), d->prop_em_width * 15);
1106 for (i = lab; i < lab + 5; i++)
1107 t->w[i] = max (tab_natural_width (t, d, i), d->prop_em_width * 8);
1108 for (i = 0; i < t->nr; i++)
1109 t->h[i] = d->font_height;
1112 /* Displays a full frequency table for variable V. */
1114 dump_full (struct variable *v)
1117 struct freq_tab *ft;
1119 struct tab_table *t;
1121 double cum_total = 0.0;
1122 double cum_freq = 0.0;
1132 static struct init vec[] =
1134 {4, 0, N_("Valid")},
1136 {1, 1, N_("Value")},
1137 {2, 1, N_("Frequency")},
1138 {3, 1, N_("Percent")},
1139 {4, 1, N_("Percent")},
1140 {5, 1, N_("Percent")},
1148 int lab = cmd.labels == FRQ_LABELS;
1150 ft = &get_var_freqs (v)->tab;
1151 n_categories = ft->n_valid + ft->n_missing;
1152 t = tab_create (5 + lab, n_categories + 3, 0);
1153 tab_headers (t, 0, 0, 2, 0);
1154 tab_dim (t, full_dim);
1157 tab_text (t, 0, 1, TAB_CENTER | TAT_TITLE, _("Value Label"));
1158 for (p = vec; p->s; p++)
1159 tab_text (t, p->c - (p->r ? !lab : 0), p->r,
1160 TAB_CENTER | TAT_TITLE, gettext (p->s));
1163 for (f = ft->valid; f < ft->missing; f++)
1165 double percent, valid_percent;
1169 percent = f->c / ft->total_cases * 100.0;
1170 valid_percent = f->c / ft->valid_cases * 100.0;
1171 cum_total += valid_percent;
1175 const char *label = val_labs_find (v->val_labs, f->v);
1177 tab_text (t, 0, r, TAB_LEFT, label);
1180 tab_value (t, 0 + lab, r, TAB_NONE, &f->v, &v->print);
1181 tab_float (t, 1 + lab, r, TAB_NONE, f->c, 8, 0);
1182 tab_float (t, 2 + lab, r, TAB_NONE, percent, 5, 1);
1183 tab_float (t, 3 + lab, r, TAB_NONE, valid_percent, 5, 1);
1184 tab_float (t, 4 + lab, r, TAB_NONE, cum_total, 5, 1);
1187 for (; f < &ft->valid[n_categories]; f++)
1193 const char *label = val_labs_find (v->val_labs, f->v);
1195 tab_text (t, 0, r, TAB_LEFT, label);
1198 tab_value (t, 0 + lab, r, TAB_NONE, &f->v, &v->print);
1199 tab_float (t, 1 + lab, r, TAB_NONE, f->c, 8, 0);
1200 tab_float (t, 2 + lab, r, TAB_NONE,
1201 f->c / ft->total_cases * 100.0, 5, 1);
1202 tab_text (t, 3 + lab, r, TAB_NONE, _("Missing"));
1206 tab_box (t, TAL_1, TAL_1,
1207 cmd.spaces == FRQ_SINGLE ? -1 : (TAL_1 | TAL_SPACING), TAL_1,
1209 tab_hline (t, TAL_2, 0, 4 + lab, 2);
1210 tab_hline (t, TAL_2, 0, 4 + lab, r);
1211 tab_joint_text (t, 0, r, 0 + lab, r, TAB_RIGHT | TAT_TITLE, _("Total"));
1212 tab_vline (t, TAL_0, 1, r, r);
1213 tab_float (t, 1 + lab, r, TAB_NONE, cum_freq, 8, 0);
1214 tab_float (t, 2 + lab, r, TAB_NONE, 100.0, 5, 1);
1215 tab_float (t, 3 + lab, r, TAB_NONE, 100.0, 5, 1);
1217 tab_title (t, 1, "%s: %s", v->name, v->label ? v->label : "");
1222 /* Sets the widths of all the columns and heights of all the rows in
1223 table T for driver D. */
1225 condensed_dim (struct tab_table *t, struct outp_driver *d)
1227 int cum_w = max (outp_string_width (d, _("Cum")),
1228 max (outp_string_width (d, _("Cum")),
1229 outp_string_width (d, "000")));
1233 for (i = 0; i < 2; i++)
1234 t->w[i] = max (tab_natural_width (t, d, i), d->prop_em_width * 8);
1235 for (i = 2; i < 4; i++)
1237 for (i = 0; i < t->nr; i++)
1238 t->h[i] = d->font_height;
1241 /* Display condensed frequency table for variable V. */
1243 dump_condensed (struct variable *v)
1246 struct freq_tab *ft;
1248 struct tab_table *t;
1250 double cum_total = 0.0;
1252 ft = &get_var_freqs (v)->tab;
1253 n_categories = ft->n_valid + ft->n_missing;
1254 t = tab_create (4, n_categories + 2, 0);
1256 tab_headers (t, 0, 0, 2, 0);
1257 tab_text (t, 0, 1, TAB_CENTER | TAT_TITLE, _("Value"));
1258 tab_text (t, 1, 1, TAB_CENTER | TAT_TITLE, _("Freq"));
1259 tab_text (t, 2, 1, TAB_CENTER | TAT_TITLE, _("Pct"));
1260 tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("Cum"));
1261 tab_text (t, 3, 1, TAB_CENTER | TAT_TITLE, _("Pct"));
1262 tab_dim (t, condensed_dim);
1265 for (f = ft->valid; f < ft->missing; f++)
1269 percent = f->c / ft->total_cases * 100.0;
1270 cum_total += f->c / ft->valid_cases * 100.0;
1272 tab_value (t, 0, r, TAB_NONE, &f->v, &v->print);
1273 tab_float (t, 1, r, TAB_NONE, f->c, 8, 0);
1274 tab_float (t, 2, r, TAB_NONE, percent, 3, 0);
1275 tab_float (t, 3, r, TAB_NONE, cum_total, 3, 0);
1278 for (; f < &ft->valid[n_categories]; f++)
1280 tab_value (t, 0, r, TAB_NONE, &f->v, &v->print);
1281 tab_float (t, 1, r, TAB_NONE, f->c, 8, 0);
1282 tab_float (t, 2, r, TAB_NONE,
1283 f->c / ft->total_cases * 100.0, 3, 0);
1287 tab_box (t, TAL_1, TAL_1,
1288 cmd.spaces == FRQ_SINGLE ? -1 : (TAL_1 | TAL_SPACING), TAL_1,
1290 tab_hline (t, TAL_2, 0, 3, 2);
1291 tab_title (t, 1, "%s: %s", v->name, v->label ? v->label : "");
1292 tab_columns (t, SOM_COL_DOWN, 1);
1296 /* Statistical display. */
1298 /* Calculates all the pertinent statistics for variable V, putting
1299 them in array D[]. FIXME: This could be made much more optimal. */
1301 calc_stats (struct variable *v, double d[frq_n_stats])
1303 struct freq_tab *ft = &get_var_freqs (v)->tab;
1304 double W = ft->valid_cases;
1313 double *median_value;
1315 /* Calculate percentiles. */
1317 /* If the 50th percentile was not explicitly requested then we must
1318 calculate it anyway --- it's the median */
1320 for (i = 0; i < n_percentiles; i++)
1322 if (percentiles[i].p == 0.5)
1324 median_value = &percentiles[i].value;
1329 if ( 0 == median_value )
1331 add_percentile (0.5);
1335 for (i = 0; i < n_percentiles; i++)
1337 percentiles[i].flag = 0;
1338 percentiles[i].flag2 = 0;
1342 for (idx = 0; idx < ft->n_valid; ++idx)
1344 static double prev_value = SYSMIS;
1345 f = &ft->valid[idx];
1347 for (i = 0; i < n_percentiles; i++)
1350 if ( percentiles[i].flag2 ) continue ;
1352 if ( get_algorithm() != COMPATIBLE )
1354 (ft->valid_cases - 1) * percentiles[i].p;
1357 (ft->valid_cases + 1) * percentiles[i].p - 1;
1359 if ( percentiles[i].flag )
1361 percentiles[i].x2 = f->v.f;
1362 percentiles[i].x1 = prev_value;
1363 percentiles[i].flag2 = 1;
1369 if ( f->c > 1 && rank - (f->c - 1) > tp )
1371 percentiles[i].x2 = percentiles[i].x1 = f->v.f;
1372 percentiles[i].flag2 = 1;
1376 percentiles[i].flag=1;
1382 prev_value = f->v.f;
1385 for (i = 0; i < n_percentiles; i++)
1387 /* Catches the case when p == 100% */
1388 if ( ! percentiles[i].flag2 )
1389 percentiles[i].x1 = percentiles[i].x2 = f->v.f;
1392 printf("percentile %d (p==%.2f); X1 = %g; X2 = %g\n",
1393 i,percentiles[i].p,percentiles[i].x1,percentiles[i].x2);
1397 for (i = 0; i < n_percentiles; i++)
1399 struct freq_tab *ft = &get_var_freqs (v)->tab;
1403 if ( get_algorithm() != COMPATIBLE )
1405 s = modf((ft->valid_cases - 1) * percentiles[i].p , &dummy);
1409 s = modf((ft->valid_cases + 1) * percentiles[i].p -1, &dummy);
1412 percentiles[i].value = percentiles[i].x1 +
1413 ( percentiles[i].x2 - percentiles[i].x1) * s ;
1415 if ( percentiles[i].p == 0.50)
1416 median_value = &percentiles[i].value;
1420 /* Calculate the mode. */
1423 for (f = ft->valid; f < ft->missing; f++)
1425 if (most_often < f->c)
1430 else if (most_often == f->c)
1432 /* A duplicate mode is undefined.
1433 FIXME: keep track of *all* the modes. */
1438 /* Calculate moments. */
1439 m = moments_create (MOMENT_KURTOSIS);
1440 for (f = ft->valid; f < ft->missing; f++)
1441 moments_pass_one (m, f->v.f, f->c);
1442 for (f = ft->valid; f < ft->missing; f++)
1443 moments_pass_two (m, f->v.f, f->c);
1444 moments_calculate (m, NULL, &d[frq_mean], &d[frq_variance],
1445 &d[frq_skew], &d[frq_kurt]);
1446 moments_destroy (m);
1448 /* Formulas below are taken from _SPSS Statistical Algorithms_. */
1449 d[frq_min] = ft->valid[0].v.f;
1450 d[frq_max] = ft->valid[ft->n_valid - 1].v.f;
1451 d[frq_mode] = X_mode;
1452 d[frq_range] = d[frq_max] - d[frq_min];
1453 d[frq_median] = *median_value;
1454 d[frq_sum] = d[frq_mean] * W;
1455 d[frq_stddev] = sqrt (d[frq_variance]);
1456 d[frq_semean] = d[frq_stddev] / sqrt (W);
1457 d[frq_seskew] = calc_seskew (W);
1458 d[frq_sekurt] = calc_sekurt (W);
1461 /* Displays a table of all the statistics requested for variable V. */
1463 dump_statistics (struct variable *v, int show_varname)
1465 struct freq_tab *ft;
1466 double stat_value[frq_n_stats];
1467 struct tab_table *t;
1470 int n_explicit_percentiles = n_percentiles;
1472 if ( implicit_50th && n_percentiles > 0 )
1475 if (v->type == ALPHA)
1477 ft = &get_var_freqs (v)->tab;
1478 if (ft->n_valid == 0)
1480 msg (SW, _("No valid data for variable %s; statistics not displayed."),
1484 calc_stats (v, stat_value);
1486 t = tab_create (3, n_stats + n_explicit_percentiles + 2, 0);
1487 tab_dim (t, tab_natural_dimensions);
1489 tab_box (t, TAL_1, TAL_1, -1, -1 , 0 , 0 , 2, tab_nr(t) - 1) ;
1492 tab_vline (t, TAL_1 , 2, 0, tab_nr(t) - 1);
1493 tab_vline (t, TAL_1 | TAL_SPACING , 1, 0, tab_nr(t) - 1 ) ;
1495 r=2; /* N missing and N valid are always dumped */
1497 for (i = 0; i < frq_n_stats; i++)
1498 if (stats & BIT_INDEX (i))
1500 tab_text (t, 0, r, TAB_LEFT | TAT_TITLE,
1501 gettext (st_name[i].s10));
1502 tab_float (t, 2, r, TAB_NONE, stat_value[i], 11, 3);
1506 tab_text (t, 0, 0, TAB_LEFT | TAT_TITLE, _("N"));
1507 tab_text (t, 1, 0, TAB_LEFT | TAT_TITLE, _("Valid"));
1508 tab_text (t, 1, 1, TAB_LEFT | TAT_TITLE, _("Missing"));
1510 tab_float(t, 2, 0, TAB_NONE, ft->valid_cases, 11, 0);
1511 tab_float(t, 2, 1, TAB_NONE, ft->total_cases - ft->valid_cases, 11, 0);
1514 for (i = 0; i < n_explicit_percentiles; i++, r++)
1518 tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, _("Percentiles"));
1521 tab_float (t, 1, r, TAB_LEFT, percentiles[i].p * 100, 3, 0 );
1522 tab_float (t, 2, r, TAB_NONE, percentiles[i].value, 11, 3);
1526 tab_columns (t, SOM_COL_DOWN, 1);
1530 tab_title (t, 1, "%s: %s", v->name, v->label);
1532 tab_title (t, 0, v->name);
1535 tab_flags (t, SOMF_NO_TITLE);
1542 /* Create a gsl_histogram from a freq_tab */
1544 freq_tab_to_hist(const struct freq_tab *ft, const struct variable *var)
1547 double x_min = DBL_MAX;
1548 double x_max = -DBL_MAX;
1550 gsl_histogram *hist;
1551 const double bins = 11;
1553 struct hsh_iterator hi;
1554 struct hsh_table *fh = ft->data;
1557 /* Find out the extremes of the x value */
1558 for ( frq = hsh_first(fh, &hi); frq != 0; frq = hsh_next(fh, &hi) )
1560 if ( is_missing(&frq->v, var))
1563 if ( frq->v.f < x_min ) x_min = frq->v.f ;
1564 if ( frq->v.f > x_max ) x_max = frq->v.f ;
1567 hist = histogram_create(bins, x_min, x_max);
1569 for( i = 0 ; i < ft->n_valid ; ++i )
1571 frq = &ft->valid[i];
1572 gsl_histogram_accumulate(hist, frq->v.f, frq->c);
1579 static struct slice *
1580 freq_tab_to_slice_array(const struct freq_tab *frq_tab,
1581 const struct variable *var,
1585 /* Allocate an array of slices and fill them from the data in frq_tab
1586 n_slices will contain the number of slices allocated.
1587 The caller is responsible for freeing slices
1589 static struct slice *
1590 freq_tab_to_slice_array(const struct freq_tab *frq_tab,
1591 const struct variable *var,
1595 struct slice *slices;
1597 *n_slices = frq_tab->n_valid;
1599 slices = xmalloc ( *n_slices * sizeof (struct slice ) );
1601 for (i = 0 ; i < *n_slices ; ++i )
1603 const struct freq *frq = &frq_tab->valid[i];
1605 slices[i].label = value_to_string(&frq->v, var);
1607 slices[i].magnetude = frq->c;
1616 do_piechart(const struct variable *var, const struct freq_tab *frq_tab)
1618 struct slice *slices;
1621 slices = freq_tab_to_slice_array(frq_tab, var, &n_slices);
1623 piechart_plot(var_to_string(var), slices, n_slices);