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);
282 void freq_tab_to_hist(const struct freq_tab *ft, gsl_histogram *hist);
285 /* Parser and outline. */
287 static int internal_cmd_frequencies (void);
290 cmd_frequencies (void)
294 int_pool = pool_create ();
295 result = internal_cmd_frequencies ();
296 pool_destroy (int_pool);
298 pool_destroy (gen_pool);
306 internal_cmd_frequencies (void)
316 if (!parse_frequencies (&cmd))
319 if (cmd.onepage_limit == NOT_LONG)
320 cmd.onepage_limit = 50;
322 /* Figure out statistics to calculate. */
324 if (cmd.a_statistics[FRQ_ST_DEFAULT] || !cmd.sbc_statistics)
325 stats |= frq_default;
326 if (cmd.a_statistics[FRQ_ST_ALL])
328 if (cmd.sort != FRQ_AVALUE && cmd.sort != FRQ_DVALUE)
329 stats &= ~frq_median;
330 for (i = 0; i < frq_n_stats; i++)
331 if (cmd.a_statistics[st_name[i].st_indx])
332 stats |= BIT_INDEX (i);
333 if (stats & frq_kurt)
335 if (stats & frq_skew)
338 /* Calculate n_stats. */
340 for (i = 0; i < frq_n_stats; i++)
341 if ((stats & BIT_INDEX (i)))
346 if (chart != GFT_NONE || cmd.sbc_ntiles)
347 cmd.sort = FRQ_AVALUE;
349 /* Work out what percentiles need to be calculated */
350 if ( cmd.sbc_percentiles )
352 for ( i = 0 ; i < MAXLISTS ; ++i )
355 subc_list_double *ptl_list = &cmd.dl_percentiles[i];
356 for ( pl = 0 ; pl < subc_list_double_count(ptl_list); ++pl)
357 add_percentile(subc_list_double_at(ptl_list,pl) / 100.0 );
360 if ( cmd.sbc_ntiles )
362 for ( i = 0 ; i < cmd.sbc_ntiles ; ++i )
365 for (j = 0; j <= cmd.n_ntiles[i]; ++j )
366 add_percentile(j / (double) cmd.n_ntiles[i]);
372 procedure_with_splits (precalc, calc, postcalc, NULL);
374 free_frequencies(&cmd);
379 /* Figure out which charts the user requested. */
381 determine_charts (void)
383 int count = (!!cmd.sbc_histogram) + (!!cmd.sbc_barchart) +
384 (!!cmd.sbc_hbar) + (!!cmd.sbc_piechart);
394 msg (SW, _("At most one of BARCHART, HISTOGRAM, or HBAR should be "
395 "given. HBAR will be assumed. Argument values will be "
396 "given precedence increasing along the order given."));
398 else if (cmd.sbc_histogram)
400 else if (cmd.sbc_barchart)
402 else if (cmd.sbc_piechart)
413 if (cmd.sbc_barchart)
415 if (cmd.ba_min != SYSMIS)
417 if (cmd.ba_max != SYSMIS)
419 if (cmd.ba_scale == FRQ_FREQ)
424 else if (cmd.ba_scale == FRQ_PERCENT)
426 format = FRQ_PERCENT;
431 if (cmd.sbc_histogram)
433 if (cmd.hi_min != SYSMIS)
435 if (cmd.hi_max != SYSMIS)
437 if (cmd.hi_scale == FRQ_FREQ)
442 else if (cmd.hi_scale == FRQ_PERCENT)
444 format = FRQ_PERCENT;
447 if (cmd.hi_norm != FRQ_NONORMAL )
449 if (cmd.hi_incr == FRQ_INCREMENT)
455 if (cmd.hb_min != SYSMIS)
457 if (cmd.hb_max != SYSMIS)
459 if (cmd.hb_scale == FRQ_FREQ)
464 else if (cmd.hb_scale == FRQ_PERCENT)
466 format = FRQ_PERCENT;
471 if (cmd.hb_incr == FRQ_INCREMENT)
475 if (min != SYSMIS && max != SYSMIS && min >= max)
477 msg (SE, _("MAX must be greater than or equal to MIN, if both are "
478 "specified. However, MIN was specified as %g and MAX as %g. "
479 "MIN and MAX will be ignored."), min, max);
484 /* Add data from case C to the frequency table. */
486 calc (struct ccase *c, void *aux UNUSED)
492 weight = dict_get_case_weight (default_dict, c, &bad_warn);
494 for (i = 0; i < n_variables; i++)
496 struct variable *v = v_variables[i];
497 const union value *val = case_data (c, v->fv);
498 struct freq_tab *ft = &get_var_freqs (v)->tab;
506 struct freq **fpp = (struct freq **) hsh_probe (ft->data, val);
512 struct freq *fp = *fpp = pool_alloc (gen_pool, sizeof *fp);
520 if (val->f == SYSMIS)
521 ft->sysmis += weight;
522 else if (val->f > INT_MIN+1 && val->f < INT_MAX-1)
525 if (i >= ft->min && i <= ft->max)
526 ft->vector[i - ft->min] += weight;
529 ft->out_of_range += weight;
538 /* Prepares each variable that is the target of FREQUENCIES by setting
539 up its hash table. */
541 precalc (void *aux UNUSED)
545 pool_destroy (gen_pool);
546 gen_pool = pool_create ();
548 for (i = 0; i < n_variables; i++)
550 struct variable *v = v_variables[i];
551 struct freq_tab *ft = &get_var_freqs (v)->tab;
553 if (ft->mode == FRQM_GENERAL)
556 hsh_compare_func *compare;
558 if (v->type == NUMERIC)
560 hash = hash_value_numeric;
561 compare = compare_value_numeric_a;
565 hash = hash_value_alpha;
566 compare = compare_value_alpha_a;
568 ft->data = hsh_create (16, compare, hash, NULL, v);
574 for (j = (ft->max - ft->min); j >= 0; j--)
576 ft->out_of_range = 0.0;
582 /* Finishes up with the variables after frequencies have been
583 calculated. Displays statistics, percentiles, ... */
585 postcalc (void *aux UNUSED)
589 for (i = 0; i < n_variables; i++)
591 struct variable *v = v_variables[i];
592 struct var_freqs *vf = get_var_freqs (v);
593 struct freq_tab *ft = &vf->tab;
595 int dumped_freq_tab = 1;
597 postprocess_freq_tab (v);
599 /* Frequencies tables. */
600 n_categories = ft->n_valid + ft->n_missing;
601 if (cmd.table == FRQ_TABLE
602 || (cmd.table == FRQ_LIMIT && n_categories <= cmd.limit))
612 if (n_categories > cmd.onepage_limit)
625 dump_statistics (v, !dumped_freq_tab);
628 if ( chart == GFT_HIST)
630 double d[frq_n_stats];
631 struct normal_curve norm;
633 gsl_histogram *hist = gsl_histogram_alloc(7);
635 norm.N = vf->tab.total_cases;
638 norm.mean = d[frq_mean];
639 norm.stddev = d[frq_stddev];
641 freq_tab_to_hist(ft, hist);
643 histogram_plot(hist, var_to_string(v), &norm, normal);
645 gsl_histogram_free(hist);
649 if ( chart == GFT_PIE)
651 do_piechart(v_variables[i], ft);
655 cleanup_freq_tab (v);
660 /* Returns the comparison function that should be used for
661 sorting a frequency table by FRQ_SORT using VAR_TYPE
663 static hsh_compare_func *
664 get_freq_comparator (int frq_sort, int var_type)
666 /* Note that q2c generates tags beginning with 1000. */
667 switch (frq_sort | (var_type << 16))
669 case FRQ_AVALUE | (NUMERIC << 16): return compare_value_numeric_a;
670 case FRQ_AVALUE | (ALPHA << 16): return compare_value_alpha_a;
671 case FRQ_DVALUE | (NUMERIC << 16): return compare_value_numeric_d;
672 case FRQ_DVALUE | (ALPHA << 16): return compare_value_alpha_d;
673 case FRQ_AFREQ | (NUMERIC << 16): return compare_freq_numeric_a;
674 case FRQ_AFREQ | (ALPHA << 16): return compare_freq_alpha_a;
675 case FRQ_DFREQ | (NUMERIC << 16): return compare_freq_numeric_d;
676 case FRQ_DFREQ | (ALPHA << 16): return compare_freq_alpha_d;
683 /* Returns nonzero iff the value in struct freq F is non-missing
686 not_missing (const void *f_, void *v_)
688 const struct freq *f = f_;
689 struct variable *v = v_;
691 return !is_missing (&f->v, v);
694 /* Summarizes the frequency table data for variable V. */
696 postprocess_freq_tab (struct variable *v)
698 hsh_compare_func *compare;
702 struct freq *freqs, *f;
705 ft = &get_var_freqs (v)->tab;
706 assert (ft->mode == FRQM_GENERAL);
707 compare = get_freq_comparator (cmd.sort, v->type);
709 /* Extract data from hash table. */
710 count = hsh_count (ft->data);
711 data = hsh_data (ft->data);
713 /* Copy dereferenced data into freqs. */
714 freqs = xmalloc (count * sizeof *freqs);
715 for (i = 0; i < count; i++)
717 struct freq *f = data[i];
721 /* Put data into ft. */
723 ft->n_valid = partition (freqs, count, sizeof *freqs, not_missing, v);
724 ft->missing = freqs + ft->n_valid;
725 ft->n_missing = count - ft->n_valid;
728 sort (ft->valid, ft->n_valid, sizeof *ft->valid, compare, v);
729 sort (ft->missing, ft->n_missing, sizeof *ft->missing, compare, v);
731 /* Summary statistics. */
732 ft->valid_cases = 0.0;
733 for(i = 0 ; i < ft->n_valid ; ++i )
736 ft->valid_cases += f->c;
740 ft->total_cases = ft->valid_cases ;
741 for(i = 0 ; i < ft->n_missing ; ++i )
744 ft->total_cases += f->c;
749 /* Frees the frequency table for variable V. */
751 cleanup_freq_tab (struct variable *v)
753 struct freq_tab *ft = &get_var_freqs (v)->tab;
754 assert (ft->mode == FRQM_GENERAL);
756 hsh_destroy (ft->data);
759 /* Parses the VARIABLES subcommand, adding to
760 {n_variables,v_variables}. */
762 frq_custom_variables (struct cmd_frequencies *cmd UNUSED)
765 int min = 0, max = 0;
767 int old_n_variables = n_variables;
771 if (token != T_ALL && (token != T_ID
772 || dict_lookup_var (default_dict, tokid) == NULL))
775 if (!parse_variables (default_dict, &v_variables, &n_variables,
776 PV_APPEND | PV_NO_SCRATCH))
779 if (!lex_match ('('))
784 if (!lex_force_int ())
786 min = lex_integer ();
788 if (!lex_force_match (','))
790 if (!lex_force_int ())
792 max = lex_integer ();
794 if (!lex_force_match (')'))
798 msg (SE, _("Upper limit of integer mode value range must be "
799 "greater than lower limit."));
804 for (i = old_n_variables; i < n_variables; i++)
806 struct variable *v = v_variables[i];
807 struct var_freqs *vf;
811 msg (SE, _("Variable %s specified multiple times on VARIABLES "
812 "subcommand."), v->name);
815 if (mode == FRQM_INTEGER && v->type != NUMERIC)
817 msg (SE, _("Integer mode specified, but %s is not a numeric "
818 "variable."), v->name);
822 vf = var_attach_aux (v, xmalloc (sizeof *vf), var_dtor_free);
824 vf->tab.valid = vf->tab.missing = NULL;
825 if (mode == FRQM_INTEGER)
829 vf->tab.vector = pool_alloc (int_pool,
830 sizeof (struct freq) * (max - min + 1));
833 vf->tab.vector = NULL;
840 /* Parses the GROUPED subcommand, setting the n_grouped, grouped
841 fields of specified variables. */
843 frq_custom_grouped (struct cmd_frequencies *cmd UNUSED)
846 if ((token == T_ID && dict_lookup_var (default_dict, tokid) != NULL)
852 /* Max, current size of list; list itself. */
860 if (!parse_variables (default_dict, &v, &n,
861 PV_NO_DUPLICATE | PV_NUMERIC))
867 while (token == T_NUM)
872 dl = pool_realloc (int_pool, dl, ml * sizeof (double));
878 /* Note that nl might still be 0 and dl might still be
879 NULL. That's okay. */
880 if (!lex_match (')'))
883 msg (SE, _("`)' expected after GROUPED interval list."));
893 for (i = 0; i < n; i++)
894 if (v[i]->aux == NULL)
895 msg (SE, _("Variables %s specified on GROUPED but not on "
896 "VARIABLES."), v[i]->name);
899 struct var_freqs *vf = get_var_freqs (v[i]);
901 if (vf->groups != NULL)
902 msg (SE, _("Variables %s specified multiple times on GROUPED "
903 "subcommand."), v[i]->name);
911 if (!lex_match ('/'))
913 if ((token != T_ID || dict_lookup_var (default_dict, tokid) != NULL)
924 /* Adds X to the list of percentiles, keeping the list in proper
927 add_percentile (double x)
931 for (i = 0; i < n_percentiles; i++)
933 /* Do nothing if it's already in the list */
934 if ( fabs(x - percentiles[i].p) < DBL_EPSILON )
937 if (x < percentiles[i].p)
941 if (i >= n_percentiles || tokval != percentiles[i].p)
944 = pool_realloc (int_pool, percentiles,
945 (n_percentiles + 1) * sizeof (struct percentile ));
947 if (i < n_percentiles)
948 memmove (&percentiles[i + 1], &percentiles[i],
949 (n_percentiles - i) * sizeof (struct percentile) );
951 percentiles[i].p = x;
956 /* Comparison functions. */
958 /* Hash of numeric values. */
960 hash_value_numeric (const void *value_, void *foo UNUSED)
962 const struct freq *value = value_;
963 return hsh_hash_double (value->v.f);
966 /* Hash of string values. */
968 hash_value_alpha (const void *value_, void *v_)
970 const struct freq *value = value_;
971 struct variable *v = v_;
973 return hsh_hash_bytes (value->v.s, v->width);
976 /* Ascending numeric compare of values. */
978 compare_value_numeric_a (const void *a_, const void *b_, void *foo UNUSED)
980 const struct freq *a = a_;
981 const struct freq *b = b_;
985 else if (a->v.f < b->v.f)
991 /* Ascending string compare of values. */
993 compare_value_alpha_a (const void *a_, const void *b_, void *v_)
995 const struct freq *a = a_;
996 const struct freq *b = b_;
997 const struct variable *v = v_;
999 return memcmp (a->v.s, b->v.s, v->width);
1002 /* Descending numeric compare of values. */
1004 compare_value_numeric_d (const void *a, const void *b, void *foo UNUSED)
1006 return -compare_value_numeric_a (a, b, foo);
1009 /* Descending string compare of values. */
1011 compare_value_alpha_d (const void *a, const void *b, void *v)
1013 return -compare_value_alpha_a (a, b, v);
1016 /* Ascending numeric compare of frequency;
1017 secondary key on ascending numeric value. */
1019 compare_freq_numeric_a (const void *a_, const void *b_, void *foo UNUSED)
1021 const struct freq *a = a_;
1022 const struct freq *b = b_;
1026 else if (a->c < b->c)
1029 if (a->v.f > b->v.f)
1031 else if (a->v.f < b->v.f)
1037 /* Ascending numeric compare of frequency;
1038 secondary key on ascending string value. */
1040 compare_freq_alpha_a (const void *a_, const void *b_, void *v_)
1042 const struct freq *a = a_;
1043 const struct freq *b = b_;
1044 const struct variable *v = v_;
1048 else if (a->c < b->c)
1051 return memcmp (a->v.s, b->v.s, v->width);
1054 /* Descending numeric compare of frequency;
1055 secondary key on ascending numeric value. */
1057 compare_freq_numeric_d (const void *a_, const void *b_, void *foo UNUSED)
1059 const struct freq *a = a_;
1060 const struct freq *b = b_;
1064 else if (a->c < b->c)
1067 if (a->v.f > b->v.f)
1069 else if (a->v.f < b->v.f)
1075 /* Descending numeric compare of frequency;
1076 secondary key on ascending string value. */
1078 compare_freq_alpha_d (const void *a_, const void *b_, void *v_)
1080 const struct freq *a = a_;
1081 const struct freq *b = b_;
1082 const struct variable *v = v_;
1086 else if (a->c < b->c)
1089 return memcmp (a->v.s, b->v.s, v->width);
1092 /* Frequency table display. */
1094 /* Sets the widths of all the columns and heights of all the rows in
1095 table T for driver D. */
1097 full_dim (struct tab_table *t, struct outp_driver *d)
1099 int lab = cmd.labels == FRQ_LABELS;
1103 t->w[0] = min (tab_natural_width (t, d, 0), d->prop_em_width * 15);
1104 for (i = lab; i < lab + 5; i++)
1105 t->w[i] = max (tab_natural_width (t, d, i), d->prop_em_width * 8);
1106 for (i = 0; i < t->nr; i++)
1107 t->h[i] = d->font_height;
1110 /* Displays a full frequency table for variable V. */
1112 dump_full (struct variable *v)
1115 struct freq_tab *ft;
1117 struct tab_table *t;
1119 double cum_total = 0.0;
1120 double cum_freq = 0.0;
1130 static struct init vec[] =
1132 {4, 0, N_("Valid")},
1134 {1, 1, N_("Value")},
1135 {2, 1, N_("Frequency")},
1136 {3, 1, N_("Percent")},
1137 {4, 1, N_("Percent")},
1138 {5, 1, N_("Percent")},
1146 int lab = cmd.labels == FRQ_LABELS;
1148 ft = &get_var_freqs (v)->tab;
1149 n_categories = ft->n_valid + ft->n_missing;
1150 t = tab_create (5 + lab, n_categories + 3, 0);
1151 tab_headers (t, 0, 0, 2, 0);
1152 tab_dim (t, full_dim);
1155 tab_text (t, 0, 1, TAB_CENTER | TAT_TITLE, _("Value Label"));
1156 for (p = vec; p->s; p++)
1157 tab_text (t, p->c - (p->r ? !lab : 0), p->r,
1158 TAB_CENTER | TAT_TITLE, gettext (p->s));
1161 for (f = ft->valid; f < ft->missing; f++)
1163 double percent, valid_percent;
1167 percent = f->c / ft->total_cases * 100.0;
1168 valid_percent = f->c / ft->valid_cases * 100.0;
1169 cum_total += valid_percent;
1173 const char *label = val_labs_find (v->val_labs, f->v);
1175 tab_text (t, 0, r, TAB_LEFT, label);
1178 tab_value (t, 0 + lab, r, TAB_NONE, &f->v, &v->print);
1179 tab_float (t, 1 + lab, r, TAB_NONE, f->c, 8, 0);
1180 tab_float (t, 2 + lab, r, TAB_NONE, percent, 5, 1);
1181 tab_float (t, 3 + lab, r, TAB_NONE, valid_percent, 5, 1);
1182 tab_float (t, 4 + lab, r, TAB_NONE, cum_total, 5, 1);
1185 for (; f < &ft->valid[n_categories]; f++)
1191 const char *label = val_labs_find (v->val_labs, f->v);
1193 tab_text (t, 0, r, TAB_LEFT, label);
1196 tab_value (t, 0 + lab, r, TAB_NONE, &f->v, &v->print);
1197 tab_float (t, 1 + lab, r, TAB_NONE, f->c, 8, 0);
1198 tab_float (t, 2 + lab, r, TAB_NONE,
1199 f->c / ft->total_cases * 100.0, 5, 1);
1200 tab_text (t, 3 + lab, r, TAB_NONE, _("Missing"));
1204 tab_box (t, TAL_1, TAL_1,
1205 cmd.spaces == FRQ_SINGLE ? -1 : (TAL_1 | TAL_SPACING), TAL_1,
1207 tab_hline (t, TAL_2, 0, 4 + lab, 2);
1208 tab_hline (t, TAL_2, 0, 4 + lab, r);
1209 tab_joint_text (t, 0, r, 0 + lab, r, TAB_RIGHT | TAT_TITLE, _("Total"));
1210 tab_vline (t, TAL_0, 1, r, r);
1211 tab_float (t, 1 + lab, r, TAB_NONE, cum_freq, 8, 0);
1212 tab_float (t, 2 + lab, r, TAB_NONE, 100.0, 5, 1);
1213 tab_float (t, 3 + lab, r, TAB_NONE, 100.0, 5, 1);
1215 tab_title (t, 1, "%s: %s", v->name, v->label ? v->label : "");
1220 /* Sets the widths of all the columns and heights of all the rows in
1221 table T for driver D. */
1223 condensed_dim (struct tab_table *t, struct outp_driver *d)
1225 int cum_w = max (outp_string_width (d, _("Cum")),
1226 max (outp_string_width (d, _("Cum")),
1227 outp_string_width (d, "000")));
1231 for (i = 0; i < 2; i++)
1232 t->w[i] = max (tab_natural_width (t, d, i), d->prop_em_width * 8);
1233 for (i = 2; i < 4; i++)
1235 for (i = 0; i < t->nr; i++)
1236 t->h[i] = d->font_height;
1239 /* Display condensed frequency table for variable V. */
1241 dump_condensed (struct variable *v)
1244 struct freq_tab *ft;
1246 struct tab_table *t;
1248 double cum_total = 0.0;
1250 ft = &get_var_freqs (v)->tab;
1251 n_categories = ft->n_valid + ft->n_missing;
1252 t = tab_create (4, n_categories + 2, 0);
1254 tab_headers (t, 0, 0, 2, 0);
1255 tab_text (t, 0, 1, TAB_CENTER | TAT_TITLE, _("Value"));
1256 tab_text (t, 1, 1, TAB_CENTER | TAT_TITLE, _("Freq"));
1257 tab_text (t, 2, 1, TAB_CENTER | TAT_TITLE, _("Pct"));
1258 tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("Cum"));
1259 tab_text (t, 3, 1, TAB_CENTER | TAT_TITLE, _("Pct"));
1260 tab_dim (t, condensed_dim);
1263 for (f = ft->valid; f < ft->missing; f++)
1267 percent = f->c / ft->total_cases * 100.0;
1268 cum_total += f->c / ft->valid_cases * 100.0;
1270 tab_value (t, 0, r, TAB_NONE, &f->v, &v->print);
1271 tab_float (t, 1, r, TAB_NONE, f->c, 8, 0);
1272 tab_float (t, 2, r, TAB_NONE, percent, 3, 0);
1273 tab_float (t, 3, r, TAB_NONE, cum_total, 3, 0);
1276 for (; f < &ft->valid[n_categories]; f++)
1278 tab_value (t, 0, r, TAB_NONE, &f->v, &v->print);
1279 tab_float (t, 1, r, TAB_NONE, f->c, 8, 0);
1280 tab_float (t, 2, r, TAB_NONE,
1281 f->c / ft->total_cases * 100.0, 3, 0);
1285 tab_box (t, TAL_1, TAL_1,
1286 cmd.spaces == FRQ_SINGLE ? -1 : (TAL_1 | TAL_SPACING), TAL_1,
1288 tab_hline (t, TAL_2, 0, 3, 2);
1289 tab_title (t, 1, "%s: %s", v->name, v->label ? v->label : "");
1290 tab_columns (t, SOM_COL_DOWN, 1);
1294 /* Statistical display. */
1296 /* Calculates all the pertinent statistics for variable V, putting
1297 them in array D[]. FIXME: This could be made much more optimal. */
1299 calc_stats (struct variable *v, double d[frq_n_stats])
1301 struct freq_tab *ft = &get_var_freqs (v)->tab;
1302 double W = ft->valid_cases;
1311 double *median_value;
1313 /* Calculate percentiles. */
1315 /* If the 50th percentile was not explicitly requested then we must
1316 calculate it anyway --- it's the median */
1318 for (i = 0; i < n_percentiles; i++)
1320 if (percentiles[i].p == 0.5)
1322 median_value = &percentiles[i].value;
1327 if ( 0 == median_value )
1329 add_percentile (0.5);
1333 for (i = 0; i < n_percentiles; i++)
1335 percentiles[i].flag = 0;
1336 percentiles[i].flag2 = 0;
1340 for (idx = 0; idx < ft->n_valid; ++idx)
1342 static double prev_value = SYSMIS;
1343 f = &ft->valid[idx];
1345 for (i = 0; i < n_percentiles; i++)
1348 if ( percentiles[i].flag2 ) continue ;
1350 if ( get_algorithm() != COMPATIBLE )
1352 (ft->valid_cases - 1) * percentiles[i].p;
1355 (ft->valid_cases + 1) * percentiles[i].p - 1;
1357 if ( percentiles[i].flag )
1359 percentiles[i].x2 = f->v.f;
1360 percentiles[i].x1 = prev_value;
1361 percentiles[i].flag2 = 1;
1367 if ( f->c > 1 && rank - (f->c - 1) > tp )
1369 percentiles[i].x2 = percentiles[i].x1 = f->v.f;
1370 percentiles[i].flag2 = 1;
1374 percentiles[i].flag=1;
1380 prev_value = f->v.f;
1383 for (i = 0; i < n_percentiles; i++)
1385 /* Catches the case when p == 100% */
1386 if ( ! percentiles[i].flag2 )
1387 percentiles[i].x1 = percentiles[i].x2 = f->v.f;
1390 printf("percentile %d (p==%.2f); X1 = %g; X2 = %g\n",
1391 i,percentiles[i].p,percentiles[i].x1,percentiles[i].x2);
1395 for (i = 0; i < n_percentiles; i++)
1397 struct freq_tab *ft = &get_var_freqs (v)->tab;
1401 if ( get_algorithm() != COMPATIBLE )
1403 s = modf((ft->valid_cases - 1) * percentiles[i].p , &dummy);
1407 s = modf((ft->valid_cases + 1) * percentiles[i].p -1, &dummy);
1410 percentiles[i].value = percentiles[i].x1 +
1411 ( percentiles[i].x2 - percentiles[i].x1) * s ;
1413 if ( percentiles[i].p == 0.50)
1414 median_value = &percentiles[i].value;
1418 /* Calculate the mode. */
1421 for (f = ft->valid; f < ft->missing; f++)
1423 if (most_often < f->c)
1428 else if (most_often == f->c)
1430 /* A duplicate mode is undefined.
1431 FIXME: keep track of *all* the modes. */
1436 /* Calculate moments. */
1437 m = moments_create (MOMENT_KURTOSIS);
1438 for (f = ft->valid; f < ft->missing; f++)
1439 moments_pass_one (m, f->v.f, f->c);
1440 for (f = ft->valid; f < ft->missing; f++)
1441 moments_pass_two (m, f->v.f, f->c);
1442 moments_calculate (m, NULL, &d[frq_mean], &d[frq_variance],
1443 &d[frq_skew], &d[frq_kurt]);
1444 moments_destroy (m);
1446 /* Formulas below are taken from _SPSS Statistical Algorithms_. */
1447 d[frq_min] = ft->valid[0].v.f;
1448 d[frq_max] = ft->valid[ft->n_valid - 1].v.f;
1449 d[frq_mode] = X_mode;
1450 d[frq_range] = d[frq_max] - d[frq_min];
1451 d[frq_median] = *median_value;
1452 d[frq_sum] = d[frq_mean] * W;
1453 d[frq_stddev] = sqrt (d[frq_variance]);
1454 d[frq_semean] = d[frq_stddev] / sqrt (W);
1455 d[frq_seskew] = calc_seskew (W);
1456 d[frq_sekurt] = calc_sekurt (W);
1459 /* Displays a table of all the statistics requested for variable V. */
1461 dump_statistics (struct variable *v, int show_varname)
1463 struct freq_tab *ft;
1464 double stat_value[frq_n_stats];
1465 struct tab_table *t;
1468 int n_explicit_percentiles = n_percentiles;
1470 if ( implicit_50th && n_percentiles > 0 )
1473 if (v->type == ALPHA)
1475 ft = &get_var_freqs (v)->tab;
1476 if (ft->n_valid == 0)
1478 msg (SW, _("No valid data for variable %s; statistics not displayed."),
1482 calc_stats (v, stat_value);
1484 t = tab_create (3, n_stats + n_explicit_percentiles + 2, 0);
1485 tab_dim (t, tab_natural_dimensions);
1487 tab_box (t, TAL_1, TAL_1, -1, -1 , 0 , 0 , 2, tab_nr(t) - 1) ;
1490 tab_vline (t, TAL_1 , 2, 0, tab_nr(t) - 1);
1491 tab_vline (t, TAL_1 | TAL_SPACING , 1, 0, tab_nr(t) - 1 ) ;
1493 r=2; /* N missing and N valid are always dumped */
1495 for (i = 0; i < frq_n_stats; i++)
1496 if (stats & BIT_INDEX (i))
1498 tab_text (t, 0, r, TAB_LEFT | TAT_TITLE,
1499 gettext (st_name[i].s10));
1500 tab_float (t, 2, r, TAB_NONE, stat_value[i], 11, 3);
1504 tab_text (t, 0, 0, TAB_LEFT | TAT_TITLE, _("N"));
1505 tab_text (t, 1, 0, TAB_LEFT | TAT_TITLE, _("Valid"));
1506 tab_text (t, 1, 1, TAB_LEFT | TAT_TITLE, _("Missing"));
1508 tab_float(t, 2, 0, TAB_NONE, ft->valid_cases, 11, 0);
1509 tab_float(t, 2, 1, TAB_NONE, ft->total_cases - ft->valid_cases, 11, 0);
1512 for (i = 0; i < n_explicit_percentiles; i++, r++)
1516 tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, _("Percentiles"));
1519 tab_float (t, 1, r, TAB_LEFT, percentiles[i].p * 100, 3, 0 );
1520 tab_float (t, 2, r, TAB_NONE, percentiles[i].value, 11, 3);
1524 tab_columns (t, SOM_COL_DOWN, 1);
1528 tab_title (t, 1, "%s: %s", v->name, v->label);
1530 tab_title (t, 0, v->name);
1533 tab_flags (t, SOMF_NO_TITLE);
1541 /* Populate a gsl_histogram from a freq_tab */
1543 freq_tab_to_hist(const struct freq_tab *ft, gsl_histogram *hist)
1546 double x_min = DBL_MAX;
1547 double x_max = -DBL_MAX;
1549 struct hsh_iterator hi;
1550 struct hsh_table *fh = ft->data;
1553 gsl_histogram_reset(hist);
1555 /* Find out the extremes of the x value */
1557 for ( frq = hsh_first(fh, &hi);
1559 frq = hsh_next(fh, &hi) )
1561 if ( frq->v.f < x_min ) x_min = frq->v.f ;
1562 if ( frq->v.f > x_max ) x_max = frq->v.f ;
1566 gsl_histogram_set_ranges_uniform(hist, x_min, x_max);
1568 for( i = 0 ; i < ft->n_valid ; ++i )
1570 frq = &ft->valid[i];
1571 gsl_histogram_accumulate(hist, frq->v.f, frq->c);
1576 static struct slice *
1577 freq_tab_to_slice_array(const struct freq_tab *frq_tab,
1578 const struct variable *var,
1582 /* Allocate an array of slices and fill them from the data in frq_tab
1583 n_slices will contain the number of slices allocated.
1584 The caller is responsible for freeing slices
1586 static struct slice *
1587 freq_tab_to_slice_array(const struct freq_tab *frq_tab,
1588 const struct variable *var,
1592 struct slice *slices;
1594 *n_slices = frq_tab->n_valid;
1596 slices = xmalloc ( *n_slices * sizeof (struct slice ) );
1598 for (i = 0 ; i < *n_slices ; ++i )
1600 const struct freq *frq = &frq_tab->valid[i];
1602 slices[i].label = value_to_string(&frq->v, var);
1604 slices[i].magnetude = frq->c;
1615 do_piechart(const struct variable *var, const struct freq_tab *frq_tab)
1617 struct slice *slices;
1620 slices = freq_tab_to_slice_array(frq_tab, var, &n_slices);
1622 piechart_plot(var_to_string(var), slices, n_slices);