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., 51 Franklin Street, Fifth Floor, Boston, MA
23 * Remember that histograms, bar charts need mean, stddev.
27 #include <libpspp/message.h>
30 #include <gsl/gsl_histogram.h>
32 #include <libpspp/alloc.h>
33 #include <libpspp/bit-vector.h>
34 #include <data/case.h>
35 #include <libpspp/compiler.h>
36 #include <data/dictionary.h>
37 #include <libpspp/hash.h>
38 #include <libpspp/pool.h>
39 #include <language/command.h>
40 #include <language/lexer/lexer.h>
41 #include <math/moments.h>
42 #include <libpspp/message.h>
43 #include <libpspp/array.h>
44 #include <libpspp/magic.h>
45 #include <libpspp/misc.h>
46 #include <output/output.h>
47 #include <output/manager.h>
48 #include <libpspp/str.h>
49 #include <output/table.h>
50 #include <data/value-labels.h>
51 #include <data/variable.h>
52 #include <procedure.h>
53 #include <data/settings.h>
54 #include <output/charts/piechart.h>
55 #include <output/chart.h>
56 #include <output/charts/plot-hist.h>
57 #include <math/histogram.h>
60 #define _(msgid) gettext (msgid)
61 #define N_(msgid) msgid
65 #include <libpspp/debug-print.h>
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),
79 scale:freq(*n:freq,"%s>0")/percent(*n:pcnt,"%s>0");
80 piechart(pie_)=:minimum(d:min),
82 missing:missing/!nomissing;
83 histogram(hi_)=:minimum(d:min),
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),
90 scale:freq(*n:freq,"%s>0")/percent(*n:pcnt,"%s>0"),
91 norm:!nonormal/normal,
92 incr:increment(d:inc,"%s>0");
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.
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,
111 /* Description of a statistic. */
114 int st_indx; /* Index into a_statistics[]. */
115 const char *s10; /* Identifying string. */
118 /* Table of statistics, indexed by dsc_*. */
119 static struct frq_info st_name[frq_n_stats + 1] =
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")},
138 /* Percentiles to calculate. */
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 */
147 int flag2; /* Set to 1 if this percentile value has been found */
151 static void add_percentile (double x) ;
153 static struct percentile *percentiles;
154 static int n_percentiles;
156 static int implicit_50th ;
158 /* Groups of statistics. */
160 #define frq_default \
161 (BI (frq_mean) | BI (frq_stddev) | BI (frq_min) | BI (frq_max))
163 (BI (frq_sum) | BI(frq_min) | BI(frq_max) \
164 | BI(frq_mean) | BI(frq_semean) | BI(frq_stddev) \
165 | BI(frq_variance) | BI(frq_kurt) | BI(frq_sekurt) \
166 | BI(frq_skew) | BI(frq_seskew) | BI(frq_range) \
167 | BI(frq_range) | BI(frq_mode) | BI(frq_median))
169 /* Statistics; number of statistics. */
170 static unsigned long stats;
173 /* Types of graphs. */
176 GFT_NONE, /* Don't draw graphs. */
177 GFT_BAR, /* Draw bar charts. */
178 GFT_HIST, /* Draw histograms. */
179 GFT_PIE, /* Draw piechart */
180 GFT_HBAR /* Draw bar charts or histograms at our discretion. */
183 /* Parsed command. */
184 static struct cmd_frequencies cmd;
186 /* Summary of the barchart, histogram, and hbar subcommands. */
187 /* FIXME: These should not be mututally exclusive */
188 static int chart; /* NONE/BAR/HIST/HBAR/PIE. */
189 static double min, max; /* Minimum, maximum on y axis. */
190 static int format; /* FREQ/PERCENT: Scaling of y axis. */
191 static double scale, incr; /* FIXME */
192 static int normal; /* FIXME */
194 /* Variables for which to calculate statistics. */
195 static size_t n_variables;
196 static struct variable **v_variables;
198 /* Arenas used to store semi-permanent storage. */
199 static struct pool *int_pool; /* Integer mode. */
200 static struct pool *gen_pool; /* General mode. */
202 /* Frequency tables. */
204 /* Frequency table entry. */
207 union value v; /* The value. */
208 double c; /* The number of occurrences of the value. */
211 /* Types of frequency tables. */
218 /* Entire frequency table. */
221 int mode; /* FRQM_GENERAL or FRQM_INTEGER. */
224 struct hsh_table *data; /* Undifferentiated data. */
227 double *vector; /* Frequencies proper. */
228 int min, max; /* The boundaries of the table. */
229 double out_of_range; /* Sum of weights of out-of-range values. */
230 double sysmis; /* Sum of weights of SYSMIS values. */
233 struct freq *valid; /* Valid freqs. */
234 int n_valid; /* Number of total freqs. */
236 struct freq *missing; /* Missing freqs. */
237 int n_missing; /* Number of missing freqs. */
240 double total_cases; /* Sum of weights of all cases. */
241 double valid_cases; /* Sum of weights of valid cases. */
245 /* Per-variable frequency data. */
248 /* Freqency table. */
249 struct freq_tab tab; /* Frequencies table to use. */
252 int n_groups; /* Number of groups. */
253 double *groups; /* Groups. */
256 double stat[frq_n_stats];
259 static inline struct var_freqs *
260 get_var_freqs (struct variable *v)
263 assert (v->aux != NULL);
267 static void determine_charts (void);
269 static void calc_stats (struct variable *v, double d[frq_n_stats]);
271 static void precalc (void *);
272 static bool calc (struct ccase *, void *);
273 static void postcalc (void *);
275 static void postprocess_freq_tab (struct variable *);
276 static void dump_full (struct variable *);
277 static void dump_condensed (struct variable *);
278 static void dump_statistics (struct variable *, int show_varname);
279 static void cleanup_freq_tab (struct variable *);
281 static hsh_hash_func hash_value_numeric, hash_value_alpha;
282 static hsh_compare_func compare_value_numeric_a, compare_value_alpha_a;
283 static hsh_compare_func compare_value_numeric_d, compare_value_alpha_d;
284 static hsh_compare_func compare_freq_numeric_a, compare_freq_alpha_a;
285 static hsh_compare_func compare_freq_numeric_d, compare_freq_alpha_d;
288 static void do_piechart(const struct variable *var,
289 const struct freq_tab *frq_tab);
292 freq_tab_to_hist(const struct freq_tab *ft, const struct variable *var);
296 /* Parser and outline. */
298 static int internal_cmd_frequencies (void);
301 cmd_frequencies (void)
305 int_pool = pool_create ();
306 result = internal_cmd_frequencies ();
307 pool_destroy (int_pool);
309 pool_destroy (gen_pool);
317 internal_cmd_frequencies (void)
328 if (!parse_frequencies (&cmd))
331 if (cmd.onepage_limit == NOT_LONG)
332 cmd.onepage_limit = 50;
334 /* Figure out statistics to calculate. */
336 if (cmd.a_statistics[FRQ_ST_DEFAULT] || !cmd.sbc_statistics)
337 stats |= frq_default;
338 if (cmd.a_statistics[FRQ_ST_ALL])
340 if (cmd.sort != FRQ_AVALUE && cmd.sort != FRQ_DVALUE)
341 stats &= ~frq_median;
342 for (i = 0; i < frq_n_stats; i++)
343 if (cmd.a_statistics[st_name[i].st_indx])
344 stats |= BIT_INDEX (i);
345 if (stats & frq_kurt)
347 if (stats & frq_skew)
350 /* Calculate n_stats. */
352 for (i = 0; i < frq_n_stats; i++)
353 if ((stats & BIT_INDEX (i)))
358 if (chart != GFT_NONE || cmd.sbc_ntiles)
359 cmd.sort = FRQ_AVALUE;
361 /* Work out what percentiles need to be calculated */
362 if ( cmd.sbc_percentiles )
364 for ( i = 0 ; i < MAXLISTS ; ++i )
367 subc_list_double *ptl_list = &cmd.dl_percentiles[i];
368 for ( pl = 0 ; pl < subc_list_double_count(ptl_list); ++pl)
369 add_percentile(subc_list_double_at(ptl_list,pl) / 100.0 );
372 if ( cmd.sbc_ntiles )
374 for ( i = 0 ; i < cmd.sbc_ntiles ; ++i )
377 for (j = 0; j <= cmd.n_ntiles[i]; ++j )
378 add_percentile(j / (double) cmd.n_ntiles[i]);
384 ok = procedure_with_splits (precalc, calc, postcalc, NULL);
386 free_frequencies(&cmd);
388 return ok ? CMD_SUCCESS : CMD_CASCADING_FAILURE;
391 /* Figure out which charts the user requested. */
393 determine_charts (void)
395 int count = (!!cmd.sbc_histogram) + (!!cmd.sbc_barchart) +
396 (!!cmd.sbc_hbar) + (!!cmd.sbc_piechart);
406 msg (SW, _("At most one of BARCHART, HISTOGRAM, or HBAR should be "
407 "given. HBAR will be assumed. Argument values will be "
408 "given precedence increasing along the order given."));
410 else if (cmd.sbc_histogram)
412 else if (cmd.sbc_barchart)
414 else if (cmd.sbc_piechart)
425 if (cmd.sbc_barchart)
427 if (cmd.ba_min != SYSMIS)
429 if (cmd.ba_max != SYSMIS)
431 if (cmd.ba_scale == FRQ_FREQ)
436 else if (cmd.ba_scale == FRQ_PERCENT)
438 format = FRQ_PERCENT;
443 if (cmd.sbc_histogram)
445 if (cmd.hi_min != SYSMIS)
447 if (cmd.hi_max != SYSMIS)
449 if (cmd.hi_scale == FRQ_FREQ)
454 else if (cmd.hi_scale == FRQ_PERCENT)
456 format = FRQ_PERCENT;
459 if (cmd.hi_norm != FRQ_NONORMAL )
461 if (cmd.hi_incr == FRQ_INCREMENT)
467 if (cmd.hb_min != SYSMIS)
469 if (cmd.hb_max != SYSMIS)
471 if (cmd.hb_scale == FRQ_FREQ)
476 else if (cmd.hb_scale == FRQ_PERCENT)
478 format = FRQ_PERCENT;
483 if (cmd.hb_incr == FRQ_INCREMENT)
487 if (min != SYSMIS && max != SYSMIS && min >= max)
489 msg (SE, _("MAX must be greater than or equal to MIN, if both are "
490 "specified. However, MIN was specified as %g and MAX as %g. "
491 "MIN and MAX will be ignored."), min, max);
496 /* Add data from case C to the frequency table. */
498 calc (struct ccase *c, void *aux UNUSED)
504 weight = dict_get_case_weight (default_dict, c, &bad_warn);
506 for (i = 0; i < n_variables; i++)
508 struct variable *v = v_variables[i];
509 const union value *val = case_data (c, v->fv);
510 struct freq_tab *ft = &get_var_freqs (v)->tab;
518 struct freq **fpp = (struct freq **) hsh_probe (ft->data, val);
524 struct freq *fp = *fpp = pool_alloc (gen_pool, sizeof *fp);
532 if (val->f == SYSMIS)
533 ft->sysmis += weight;
534 else if (val->f > INT_MIN+1 && val->f < INT_MAX-1)
537 if (i >= ft->min && i <= ft->max)
538 ft->vector[i - ft->min] += weight;
541 ft->out_of_range += weight;
550 /* Prepares each variable that is the target of FREQUENCIES by setting
551 up its hash table. */
553 precalc (void *aux UNUSED)
557 pool_destroy (gen_pool);
558 gen_pool = pool_create ();
560 for (i = 0; i < n_variables; i++)
562 struct variable *v = v_variables[i];
563 struct freq_tab *ft = &get_var_freqs (v)->tab;
565 if (ft->mode == FRQM_GENERAL)
568 hsh_compare_func *compare;
570 if (v->type == NUMERIC)
572 hash = hash_value_numeric;
573 compare = compare_value_numeric_a;
577 hash = hash_value_alpha;
578 compare = compare_value_alpha_a;
580 ft->data = hsh_create (16, compare, hash, NULL, v);
586 for (j = (ft->max - ft->min); j >= 0; j--)
588 ft->out_of_range = 0.0;
594 /* Finishes up with the variables after frequencies have been
595 calculated. Displays statistics, percentiles, ... */
597 postcalc (void *aux UNUSED)
601 for (i = 0; i < n_variables; i++)
603 struct variable *v = v_variables[i];
604 struct var_freqs *vf = get_var_freqs (v);
605 struct freq_tab *ft = &vf->tab;
607 int dumped_freq_tab = 1;
609 postprocess_freq_tab (v);
611 /* Frequencies tables. */
612 n_categories = ft->n_valid + ft->n_missing;
613 if (cmd.table == FRQ_TABLE
614 || (cmd.table == FRQ_LIMIT && n_categories <= cmd.limit))
624 if (n_categories > cmd.onepage_limit)
637 dump_statistics (v, !dumped_freq_tab);
641 if ( chart == GFT_HIST)
643 double d[frq_n_stats];
644 struct normal_curve norm;
645 gsl_histogram *hist ;
648 norm.N = vf->tab.valid_cases;
651 norm.mean = d[frq_mean];
652 norm.stddev = d[frq_stddev];
654 hist = freq_tab_to_hist(ft,v);
656 histogram_plot(hist, var_to_string(v), &norm, normal);
658 gsl_histogram_free(hist);
662 if ( chart == GFT_PIE)
664 do_piechart(v_variables[i], ft);
669 cleanup_freq_tab (v);
674 /* Returns the comparison function that should be used for
675 sorting a frequency table by FRQ_SORT using VAR_TYPE
677 static hsh_compare_func *
678 get_freq_comparator (int frq_sort, int var_type)
680 /* Note that q2c generates tags beginning with 1000. */
681 switch (frq_sort | (var_type << 16))
683 case FRQ_AVALUE | (NUMERIC << 16): return compare_value_numeric_a;
684 case FRQ_AVALUE | (ALPHA << 16): return compare_value_alpha_a;
685 case FRQ_DVALUE | (NUMERIC << 16): return compare_value_numeric_d;
686 case FRQ_DVALUE | (ALPHA << 16): return compare_value_alpha_d;
687 case FRQ_AFREQ | (NUMERIC << 16): return compare_freq_numeric_a;
688 case FRQ_AFREQ | (ALPHA << 16): return compare_freq_alpha_a;
689 case FRQ_DFREQ | (NUMERIC << 16): return compare_freq_numeric_d;
690 case FRQ_DFREQ | (ALPHA << 16): return compare_freq_alpha_d;
697 /* Returns nonzero iff the value in struct freq F is non-missing
700 not_missing (const void *f_, void *v_)
702 const struct freq *f = f_;
703 struct variable *v = v_;
705 return !mv_is_value_missing (&v->miss, &f->v);
708 /* Summarizes the frequency table data for variable V. */
710 postprocess_freq_tab (struct variable *v)
712 hsh_compare_func *compare;
716 struct freq *freqs, *f;
719 ft = &get_var_freqs (v)->tab;
720 assert (ft->mode == FRQM_GENERAL);
721 compare = get_freq_comparator (cmd.sort, v->type);
723 /* Extract data from hash table. */
724 count = hsh_count (ft->data);
725 data = hsh_data (ft->data);
727 /* Copy dereferenced data into freqs. */
728 freqs = xnmalloc (count, sizeof *freqs);
729 for (i = 0; i < count; i++)
731 struct freq *f = data[i];
735 /* Put data into ft. */
737 ft->n_valid = partition (freqs, count, sizeof *freqs, not_missing, v);
738 ft->missing = freqs + ft->n_valid;
739 ft->n_missing = count - ft->n_valid;
742 sort (ft->valid, ft->n_valid, sizeof *ft->valid, compare, v);
743 sort (ft->missing, ft->n_missing, sizeof *ft->missing, compare, v);
745 /* Summary statistics. */
746 ft->valid_cases = 0.0;
747 for(i = 0 ; i < ft->n_valid ; ++i )
750 ft->valid_cases += f->c;
754 ft->total_cases = ft->valid_cases ;
755 for(i = 0 ; i < ft->n_missing ; ++i )
758 ft->total_cases += f->c;
763 /* Frees the frequency table for variable V. */
765 cleanup_freq_tab (struct variable *v)
767 struct freq_tab *ft = &get_var_freqs (v)->tab;
768 assert (ft->mode == FRQM_GENERAL);
770 hsh_destroy (ft->data);
773 /* Parses the VARIABLES subcommand, adding to
774 {n_variables,v_variables}. */
776 frq_custom_variables (struct cmd_frequencies *cmd UNUSED)
779 int min = 0, max = 0;
781 size_t old_n_variables = n_variables;
785 if (token != T_ALL && (token != T_ID
786 || dict_lookup_var (default_dict, tokid) == NULL))
789 if (!parse_variables (default_dict, &v_variables, &n_variables,
790 PV_APPEND | PV_NO_SCRATCH))
793 if (!lex_match ('('))
798 if (!lex_force_int ())
800 min = lex_integer ();
802 if (!lex_force_match (','))
804 if (!lex_force_int ())
806 max = lex_integer ();
808 if (!lex_force_match (')'))
812 msg (SE, _("Upper limit of integer mode value range must be "
813 "greater than lower limit."));
818 for (i = old_n_variables; i < n_variables; i++)
820 struct variable *v = v_variables[i];
821 struct var_freqs *vf;
825 msg (SE, _("Variable %s specified multiple times on VARIABLES "
826 "subcommand."), v->name);
829 if (mode == FRQM_INTEGER && v->type != NUMERIC)
831 msg (SE, _("Integer mode specified, but %s is not a numeric "
832 "variable."), v->name);
836 vf = var_attach_aux (v, xmalloc (sizeof *vf), var_dtor_free);
838 vf->tab.valid = vf->tab.missing = NULL;
839 if (mode == FRQM_INTEGER)
843 vf->tab.vector = pool_nalloc (int_pool,
844 max - min + 1, sizeof *vf->tab.vector);
847 vf->tab.vector = NULL;
854 /* Parses the GROUPED subcommand, setting the n_grouped, grouped
855 fields of specified variables. */
857 frq_custom_grouped (struct cmd_frequencies *cmd UNUSED)
860 if ((token == T_ID && dict_lookup_var (default_dict, tokid) != NULL)
866 /* Max, current size of list; list itself. */
874 if (!parse_variables (default_dict, &v, &n,
875 PV_NO_DUPLICATE | PV_NUMERIC))
881 while (lex_integer ())
886 dl = pool_nrealloc (int_pool, dl, ml, sizeof *dl);
892 /* Note that nl might still be 0 and dl might still be
893 NULL. That's okay. */
894 if (!lex_match (')'))
897 msg (SE, _("`)' expected after GROUPED interval list."));
907 for (i = 0; i < n; i++)
908 if (v[i]->aux == NULL)
909 msg (SE, _("Variables %s specified on GROUPED but not on "
910 "VARIABLES."), v[i]->name);
913 struct var_freqs *vf = get_var_freqs (v[i]);
915 if (vf->groups != NULL)
916 msg (SE, _("Variables %s specified multiple times on GROUPED "
917 "subcommand."), v[i]->name);
925 if (!lex_match ('/'))
927 if ((token != T_ID || dict_lookup_var (default_dict, tokid) != NULL)
938 /* Adds X to the list of percentiles, keeping the list in proper
941 add_percentile (double x)
945 for (i = 0; i < n_percentiles; i++)
947 /* Do nothing if it's already in the list */
948 if ( fabs(x - percentiles[i].p) < DBL_EPSILON )
951 if (x < percentiles[i].p)
955 if (i >= n_percentiles || tokval != percentiles[i].p)
957 percentiles = pool_nrealloc (int_pool, percentiles,
958 n_percentiles + 1, sizeof *percentiles);
960 if (i < n_percentiles)
961 memmove (&percentiles[i + 1], &percentiles[i],
962 (n_percentiles - i) * sizeof (struct percentile) );
964 percentiles[i].p = x;
969 /* Comparison functions. */
971 /* Hash of numeric values. */
973 hash_value_numeric (const void *value_, void *foo UNUSED)
975 const struct freq *value = value_;
976 return hsh_hash_double (value->v.f);
979 /* Hash of string values. */
981 hash_value_alpha (const void *value_, void *v_)
983 const struct freq *value = value_;
984 struct variable *v = v_;
986 return hsh_hash_bytes (value->v.s, v->width);
989 /* Ascending numeric compare of values. */
991 compare_value_numeric_a (const void *a_, const void *b_, void *foo UNUSED)
993 const struct freq *a = a_;
994 const struct freq *b = b_;
998 else if (a->v.f < b->v.f)
1004 /* Ascending string compare of values. */
1006 compare_value_alpha_a (const void *a_, const void *b_, void *v_)
1008 const struct freq *a = a_;
1009 const struct freq *b = b_;
1010 const struct variable *v = v_;
1012 return memcmp (a->v.s, b->v.s, v->width);
1015 /* Descending numeric compare of values. */
1017 compare_value_numeric_d (const void *a, const void *b, void *foo UNUSED)
1019 return -compare_value_numeric_a (a, b, foo);
1022 /* Descending string compare of values. */
1024 compare_value_alpha_d (const void *a, const void *b, void *v)
1026 return -compare_value_alpha_a (a, b, v);
1029 /* Ascending numeric compare of frequency;
1030 secondary key on ascending numeric value. */
1032 compare_freq_numeric_a (const void *a_, const void *b_, void *foo UNUSED)
1034 const struct freq *a = a_;
1035 const struct freq *b = b_;
1039 else if (a->c < b->c)
1042 if (a->v.f > b->v.f)
1044 else if (a->v.f < b->v.f)
1050 /* Ascending numeric compare of frequency;
1051 secondary key on ascending string value. */
1053 compare_freq_alpha_a (const void *a_, const void *b_, void *v_)
1055 const struct freq *a = a_;
1056 const struct freq *b = b_;
1057 const struct variable *v = v_;
1061 else if (a->c < b->c)
1064 return memcmp (a->v.s, b->v.s, v->width);
1067 /* Descending numeric compare of frequency;
1068 secondary key on ascending numeric value. */
1070 compare_freq_numeric_d (const void *a_, const void *b_, void *foo UNUSED)
1072 const struct freq *a = a_;
1073 const struct freq *b = b_;
1077 else if (a->c < b->c)
1080 if (a->v.f > b->v.f)
1082 else if (a->v.f < b->v.f)
1088 /* Descending numeric compare of frequency;
1089 secondary key on ascending string value. */
1091 compare_freq_alpha_d (const void *a_, const void *b_, void *v_)
1093 const struct freq *a = a_;
1094 const struct freq *b = b_;
1095 const struct variable *v = v_;
1099 else if (a->c < b->c)
1102 return memcmp (a->v.s, b->v.s, v->width);
1105 /* Frequency table display. */
1107 /* Sets the widths of all the columns and heights of all the rows in
1108 table T for driver D. */
1110 full_dim (struct tab_table *t, struct outp_driver *d)
1112 int lab = cmd.labels == FRQ_LABELS;
1116 t->w[0] = min (tab_natural_width (t, d, 0), d->prop_em_width * 15);
1117 for (i = lab; i < lab + 5; i++)
1118 t->w[i] = max (tab_natural_width (t, d, i), d->prop_em_width * 8);
1119 for (i = 0; i < t->nr; i++)
1120 t->h[i] = d->font_height;
1123 /* Displays a full frequency table for variable V. */
1125 dump_full (struct variable *v)
1128 struct freq_tab *ft;
1130 struct tab_table *t;
1132 double cum_total = 0.0;
1133 double cum_freq = 0.0;
1143 static struct init vec[] =
1145 {4, 0, N_("Valid")},
1147 {1, 1, N_("Value")},
1148 {2, 1, N_("Frequency")},
1149 {3, 1, N_("Percent")},
1150 {4, 1, N_("Percent")},
1151 {5, 1, N_("Percent")},
1159 int lab = cmd.labels == FRQ_LABELS;
1161 ft = &get_var_freqs (v)->tab;
1162 n_categories = ft->n_valid + ft->n_missing;
1163 t = tab_create (5 + lab, n_categories + 3, 0);
1164 tab_headers (t, 0, 0, 2, 0);
1165 tab_dim (t, full_dim);
1168 tab_text (t, 0, 1, TAB_CENTER | TAT_TITLE, _("Value Label"));
1169 for (p = vec; p->s; p++)
1170 tab_text (t, p->c - (p->r ? !lab : 0), p->r,
1171 TAB_CENTER | TAT_TITLE, gettext (p->s));
1174 for (f = ft->valid; f < ft->missing; f++)
1176 double percent, valid_percent;
1180 percent = f->c / ft->total_cases * 100.0;
1181 valid_percent = f->c / ft->valid_cases * 100.0;
1182 cum_total += valid_percent;
1186 const char *label = val_labs_find (v->val_labs, f->v);
1188 tab_text (t, 0, r, TAB_LEFT, label);
1191 tab_value (t, 0 + lab, r, TAB_NONE, &f->v, &v->print);
1192 tab_float (t, 1 + lab, r, TAB_NONE, f->c, 8, 0);
1193 tab_float (t, 2 + lab, r, TAB_NONE, percent, 5, 1);
1194 tab_float (t, 3 + lab, r, TAB_NONE, valid_percent, 5, 1);
1195 tab_float (t, 4 + lab, r, TAB_NONE, cum_total, 5, 1);
1198 for (; f < &ft->valid[n_categories]; f++)
1204 const char *label = val_labs_find (v->val_labs, f->v);
1206 tab_text (t, 0, r, TAB_LEFT, label);
1209 tab_value (t, 0 + lab, r, TAB_NONE, &f->v, &v->print);
1210 tab_float (t, 1 + lab, r, TAB_NONE, f->c, 8, 0);
1211 tab_float (t, 2 + lab, r, TAB_NONE,
1212 f->c / ft->total_cases * 100.0, 5, 1);
1213 tab_text (t, 3 + lab, r, TAB_NONE, _("Missing"));
1217 tab_box (t, TAL_1, TAL_1,
1218 cmd.spaces == FRQ_SINGLE ? -1 : TAL_GAP, TAL_1,
1220 tab_hline (t, TAL_2, 0, 4 + lab, 2);
1221 tab_hline (t, TAL_2, 0, 4 + lab, r);
1222 tab_joint_text (t, 0, r, 0 + lab, r, TAB_RIGHT | TAT_TITLE, _("Total"));
1223 tab_vline (t, TAL_0, 1, r, r);
1224 tab_float (t, 1 + lab, r, TAB_NONE, cum_freq, 8, 0);
1225 tab_float (t, 2 + lab, r, TAB_NONE, 100.0, 5, 1);
1226 tab_float (t, 3 + lab, r, TAB_NONE, 100.0, 5, 1);
1228 tab_title (t, "%s: %s", v->name, v->label ? v->label : "");
1233 /* Sets the widths of all the columns and heights of all the rows in
1234 table T for driver D. */
1236 condensed_dim (struct tab_table *t, struct outp_driver *d)
1238 int cum_w = max (outp_string_width (d, _("Cum"), OUTP_PROPORTIONAL),
1239 max (outp_string_width (d, _("Cum"), OUTP_PROPORTIONAL),
1240 outp_string_width (d, "000", OUTP_PROPORTIONAL)));
1244 for (i = 0; i < 2; i++)
1245 t->w[i] = max (tab_natural_width (t, d, i), d->prop_em_width * 8);
1246 for (i = 2; i < 4; i++)
1248 for (i = 0; i < t->nr; i++)
1249 t->h[i] = d->font_height;
1252 /* Display condensed frequency table for variable V. */
1254 dump_condensed (struct variable *v)
1257 struct freq_tab *ft;
1259 struct tab_table *t;
1261 double cum_total = 0.0;
1263 ft = &get_var_freqs (v)->tab;
1264 n_categories = ft->n_valid + ft->n_missing;
1265 t = tab_create (4, n_categories + 2, 0);
1267 tab_headers (t, 0, 0, 2, 0);
1268 tab_text (t, 0, 1, TAB_CENTER | TAT_TITLE, _("Value"));
1269 tab_text (t, 1, 1, TAB_CENTER | TAT_TITLE, _("Freq"));
1270 tab_text (t, 2, 1, TAB_CENTER | TAT_TITLE, _("Pct"));
1271 tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("Cum"));
1272 tab_text (t, 3, 1, TAB_CENTER | TAT_TITLE, _("Pct"));
1273 tab_dim (t, condensed_dim);
1276 for (f = ft->valid; f < ft->missing; f++)
1280 percent = f->c / ft->total_cases * 100.0;
1281 cum_total += f->c / ft->valid_cases * 100.0;
1283 tab_value (t, 0, r, TAB_NONE, &f->v, &v->print);
1284 tab_float (t, 1, r, TAB_NONE, f->c, 8, 0);
1285 tab_float (t, 2, r, TAB_NONE, percent, 3, 0);
1286 tab_float (t, 3, r, TAB_NONE, cum_total, 3, 0);
1289 for (; f < &ft->valid[n_categories]; f++)
1291 tab_value (t, 0, r, TAB_NONE, &f->v, &v->print);
1292 tab_float (t, 1, r, TAB_NONE, f->c, 8, 0);
1293 tab_float (t, 2, r, TAB_NONE,
1294 f->c / ft->total_cases * 100.0, 3, 0);
1298 tab_box (t, TAL_1, TAL_1,
1299 cmd.spaces == FRQ_SINGLE ? -1 : TAL_GAP, TAL_1,
1301 tab_hline (t, TAL_2, 0, 3, 2);
1302 tab_title (t, "%s: %s", v->name, v->label ? v->label : "");
1303 tab_columns (t, SOM_COL_DOWN, 1);
1307 /* Statistical display. */
1309 /* Calculates all the pertinent statistics for variable V, putting
1310 them in array D[]. FIXME: This could be made much more optimal. */
1312 calc_stats (struct variable *v, double d[frq_n_stats])
1314 struct freq_tab *ft = &get_var_freqs (v)->tab;
1315 double W = ft->valid_cases;
1324 double *median_value;
1326 /* Calculate percentiles. */
1328 /* If the 50th percentile was not explicitly requested then we must
1329 calculate it anyway --- it's the median */
1331 for (i = 0; i < n_percentiles; i++)
1333 if (percentiles[i].p == 0.5)
1335 median_value = &percentiles[i].value;
1340 if ( 0 == median_value )
1342 add_percentile (0.5);
1346 for (i = 0; i < n_percentiles; i++)
1348 percentiles[i].flag = 0;
1349 percentiles[i].flag2 = 0;
1353 for (idx = 0; idx < ft->n_valid; ++idx)
1355 static double prev_value = SYSMIS;
1356 f = &ft->valid[idx];
1358 for (i = 0; i < n_percentiles; i++)
1361 if ( percentiles[i].flag2 ) continue ;
1363 if ( get_algorithm() != COMPATIBLE )
1365 (ft->valid_cases - 1) * percentiles[i].p;
1368 (ft->valid_cases + 1) * percentiles[i].p - 1;
1370 if ( percentiles[i].flag )
1372 percentiles[i].x2 = f->v.f;
1373 percentiles[i].x1 = prev_value;
1374 percentiles[i].flag2 = 1;
1380 if ( f->c > 1 && rank - (f->c - 1) > tp )
1382 percentiles[i].x2 = percentiles[i].x1 = f->v.f;
1383 percentiles[i].flag2 = 1;
1387 percentiles[i].flag=1;
1393 prev_value = f->v.f;
1396 for (i = 0; i < n_percentiles; i++)
1398 /* Catches the case when p == 100% */
1399 if ( ! percentiles[i].flag2 )
1400 percentiles[i].x1 = percentiles[i].x2 = f->v.f;
1403 printf("percentile %d (p==%.2f); X1 = %g; X2 = %g\n",
1404 i,percentiles[i].p,percentiles[i].x1,percentiles[i].x2);
1408 for (i = 0; i < n_percentiles; i++)
1410 struct freq_tab *ft = &get_var_freqs (v)->tab;
1414 if ( get_algorithm() != COMPATIBLE )
1416 s = modf((ft->valid_cases - 1) * percentiles[i].p , &dummy);
1420 s = modf((ft->valid_cases + 1) * percentiles[i].p -1, &dummy);
1423 percentiles[i].value = percentiles[i].x1 +
1424 ( percentiles[i].x2 - percentiles[i].x1) * s ;
1426 if ( percentiles[i].p == 0.50)
1427 median_value = &percentiles[i].value;
1431 /* Calculate the mode. */
1434 for (f = ft->valid; f < ft->missing; f++)
1436 if (most_often < f->c)
1441 else if (most_often == f->c)
1443 /* A duplicate mode is undefined.
1444 FIXME: keep track of *all* the modes. */
1449 /* Calculate moments. */
1450 m = moments_create (MOMENT_KURTOSIS);
1451 for (f = ft->valid; f < ft->missing; f++)
1452 moments_pass_one (m, f->v.f, f->c);
1453 for (f = ft->valid; f < ft->missing; f++)
1454 moments_pass_two (m, f->v.f, f->c);
1455 moments_calculate (m, NULL, &d[frq_mean], &d[frq_variance],
1456 &d[frq_skew], &d[frq_kurt]);
1457 moments_destroy (m);
1459 /* Formulas below are taken from _SPSS Statistical Algorithms_. */
1460 d[frq_min] = ft->valid[0].v.f;
1461 d[frq_max] = ft->valid[ft->n_valid - 1].v.f;
1462 d[frq_mode] = X_mode;
1463 d[frq_range] = d[frq_max] - d[frq_min];
1464 d[frq_median] = *median_value;
1465 d[frq_sum] = d[frq_mean] * W;
1466 d[frq_stddev] = sqrt (d[frq_variance]);
1467 d[frq_semean] = d[frq_stddev] / sqrt (W);
1468 d[frq_seskew] = calc_seskew (W);
1469 d[frq_sekurt] = calc_sekurt (W);
1472 /* Displays a table of all the statistics requested for variable V. */
1474 dump_statistics (struct variable *v, int show_varname)
1476 struct freq_tab *ft;
1477 double stat_value[frq_n_stats];
1478 struct tab_table *t;
1481 int n_explicit_percentiles = n_percentiles;
1483 if ( implicit_50th && n_percentiles > 0 )
1486 if (v->type == ALPHA)
1488 ft = &get_var_freqs (v)->tab;
1489 if (ft->n_valid == 0)
1491 msg (SW, _("No valid data for variable %s; statistics not displayed."),
1495 calc_stats (v, stat_value);
1497 t = tab_create (3, n_stats + n_explicit_percentiles + 2, 0);
1498 tab_dim (t, tab_natural_dimensions);
1500 tab_box (t, TAL_1, TAL_1, -1, -1 , 0 , 0 , 2, tab_nr(t) - 1) ;
1503 tab_vline (t, TAL_1 , 2, 0, tab_nr(t) - 1);
1504 tab_vline (t, TAL_GAP , 1, 0, tab_nr(t) - 1 ) ;
1506 r=2; /* N missing and N valid are always dumped */
1508 for (i = 0; i < frq_n_stats; i++)
1509 if (stats & BIT_INDEX (i))
1511 tab_text (t, 0, r, TAB_LEFT | TAT_TITLE,
1512 gettext (st_name[i].s10));
1513 tab_float (t, 2, r, TAB_NONE, stat_value[i], 11, 3);
1517 tab_text (t, 0, 0, TAB_LEFT | TAT_TITLE, _("N"));
1518 tab_text (t, 1, 0, TAB_LEFT | TAT_TITLE, _("Valid"));
1519 tab_text (t, 1, 1, TAB_LEFT | TAT_TITLE, _("Missing"));
1521 tab_float(t, 2, 0, TAB_NONE, ft->valid_cases, 11, 0);
1522 tab_float(t, 2, 1, TAB_NONE, ft->total_cases - ft->valid_cases, 11, 0);
1525 for (i = 0; i < n_explicit_percentiles; i++, r++)
1529 tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, _("Percentiles"));
1532 tab_float (t, 1, r, TAB_LEFT, percentiles[i].p * 100, 3, 0 );
1533 tab_float (t, 2, r, TAB_NONE, percentiles[i].value, 11, 3);
1537 tab_columns (t, SOM_COL_DOWN, 1);
1541 tab_title (t, "%s: %s", v->name, v->label);
1543 tab_title (t, "%s", v->name);
1546 tab_flags (t, SOMF_NO_TITLE);
1553 /* Create a gsl_histogram from a freq_tab */
1555 freq_tab_to_hist(const struct freq_tab *ft, const struct variable *var)
1558 double x_min = DBL_MAX;
1559 double x_max = -DBL_MAX;
1561 gsl_histogram *hist;
1562 const double bins = 11;
1564 struct hsh_iterator hi;
1565 struct hsh_table *fh = ft->data;
1568 /* Find out the extremes of the x value */
1569 for ( frq = hsh_first(fh, &hi); frq != 0; frq = hsh_next(fh, &hi) )
1571 if ( mv_is_value_missing(&var->miss, &frq->v))
1574 if ( frq->v.f < x_min ) x_min = frq->v.f ;
1575 if ( frq->v.f > x_max ) x_max = frq->v.f ;
1578 hist = histogram_create(bins, x_min, x_max);
1580 for( i = 0 ; i < ft->n_valid ; ++i )
1582 frq = &ft->valid[i];
1583 gsl_histogram_accumulate(hist, frq->v.f, frq->c);
1590 static struct slice *
1591 freq_tab_to_slice_array(const struct freq_tab *frq_tab,
1592 const struct variable *var,
1596 /* Allocate an array of slices and fill them from the data in frq_tab
1597 n_slices will contain the number of slices allocated.
1598 The caller is responsible for freeing slices
1600 static struct slice *
1601 freq_tab_to_slice_array(const struct freq_tab *frq_tab,
1602 const struct variable *var,
1606 struct slice *slices;
1608 *n_slices = frq_tab->n_valid;
1610 slices = xnmalloc (*n_slices, sizeof *slices);
1612 for (i = 0 ; i < *n_slices ; ++i )
1614 const struct freq *frq = &frq_tab->valid[i];
1616 slices[i].label = value_to_string(&frq->v, var);
1618 slices[i].magnetude = frq->c;
1628 do_piechart(const struct variable *var, const struct freq_tab *frq_tab)
1630 struct slice *slices;
1633 slices = freq_tab_to_slice_array(frq_tab, var, &n_slices);
1635 piechart_plot(var_to_string(var), slices, n_slices);