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.
30 #include <gsl/gsl_histogram.h>
32 #include <data/case.h>
33 #include <data/dictionary.h>
34 #include <data/procedure.h>
35 #include <data/settings.h>
36 #include <data/value-labels.h>
37 #include <data/variable.h>
38 #include <language/command.h>
39 #include <language/dictionary/split-file.h>
40 #include <language/lexer/lexer.h>
41 #include <libpspp/alloc.h>
42 #include <libpspp/array.h>
43 #include <libpspp/bit-vector.h>
44 #include <libpspp/compiler.h>
45 #include <libpspp/hash.h>
46 #include <libpspp/magic.h>
47 #include <libpspp/message.h>
48 #include <libpspp/message.h>
49 #include <libpspp/misc.h>
50 #include <libpspp/pool.h>
51 #include <libpspp/str.h>
52 #include <math/histogram.h>
53 #include <math/moments.h>
54 #include <output/chart.h>
55 #include <output/charts/piechart.h>
56 #include <output/charts/plot-hist.h>
57 #include <output/manager.h>
58 #include <output/output.h>
59 #include <output/table.h>
64 #define _(msgid) gettext (msgid)
65 #define N_(msgid) msgid
72 format=cond:condense/onepage(*n:onepage_limit,"%s>=0")/!standard,
73 table:limit(n:limit,"%s>0")/notable/!table,
74 labels:!labels/nolabels,
75 sort:!avalue/dvalue/afreq/dfreq,
76 spaces:!single/double,
77 paging:newpage/!oldpage;
78 missing=miss:include/!exclude;
79 barchart(ba_)=:minimum(d:min),
81 scale:freq(*n:freq,"%s>0")/percent(*n:pcnt,"%s>0");
82 piechart(pie_)=:minimum(d:min),
84 missing:missing/!nomissing;
85 histogram(hi_)=:minimum(d:min),
87 scale:freq(*n:freq,"%s>0")/percent(*n:pcnt,"%s>0"),
88 norm:!nonormal/normal,
89 incr:increment(d:inc,"%s>0");
90 hbar(hb_)=:minimum(d:min),
92 scale:freq(*n:freq,"%s>0")/percent(*n:pcnt,"%s>0"),
93 norm:!nonormal/normal,
94 incr:increment(d:inc,"%s>0");
97 +percentiles = double list;
98 statistics[st_]=1|mean,2|semean,3|median,4|mode,5|stddev,6|variance,
99 7|kurtosis,8|skewness,9|range,10|minimum,11|maximum,12|sum,
100 13|default,14|seskewness,15|sekurtosis,all,none.
108 frq_mean = 0, frq_semean, frq_median, frq_mode, frq_stddev, frq_variance,
109 frq_kurt, frq_sekurt, frq_skew, frq_seskew, frq_range, frq_min, frq_max,
113 /* Description of a statistic. */
116 int st_indx; /* Index into a_statistics[]. */
117 const char *s10; /* Identifying string. */
120 /* Table of statistics, indexed by dsc_*. */
121 static struct frq_info st_name[frq_n_stats + 1] =
123 {FRQ_ST_MEAN, N_("Mean")},
124 {FRQ_ST_SEMEAN, N_("S.E. Mean")},
125 {FRQ_ST_MEDIAN, N_("Median")},
126 {FRQ_ST_MODE, N_("Mode")},
127 {FRQ_ST_STDDEV, N_("Std Dev")},
128 {FRQ_ST_VARIANCE, N_("Variance")},
129 {FRQ_ST_KURTOSIS, N_("Kurtosis")},
130 {FRQ_ST_SEKURTOSIS, N_("S.E. Kurt")},
131 {FRQ_ST_SKEWNESS, N_("Skewness")},
132 {FRQ_ST_SESKEWNESS, N_("S.E. Skew")},
133 {FRQ_ST_RANGE, N_("Range")},
134 {FRQ_ST_MINIMUM, N_("Minimum")},
135 {FRQ_ST_MAXIMUM, N_("Maximum")},
136 {FRQ_ST_SUM, N_("Sum")},
140 /* Percentiles to calculate. */
144 double p; /* the %ile to be calculated */
145 double value; /* the %ile's value */
146 double x1; /* The datum value <= the percentile */
147 double x2; /* The datum value >= the percentile */
149 int flag2; /* Set to 1 if this percentile value has been found */
153 static void add_percentile (double x) ;
155 static struct percentile *percentiles;
156 static int n_percentiles;
158 static int implicit_50th ;
160 /* Groups of statistics. */
162 #define frq_default \
163 (BI (frq_mean) | BI (frq_stddev) | BI (frq_min) | BI (frq_max))
165 (BI (frq_sum) | BI(frq_min) | BI(frq_max) \
166 | BI(frq_mean) | BI(frq_semean) | BI(frq_stddev) \
167 | BI(frq_variance) | BI(frq_kurt) | BI(frq_sekurt) \
168 | BI(frq_skew) | BI(frq_seskew) | BI(frq_range) \
169 | BI(frq_range) | BI(frq_mode) | BI(frq_median))
171 /* Statistics; number of statistics. */
172 static unsigned long stats;
175 /* Types of graphs. */
178 GFT_NONE, /* Don't draw graphs. */
179 GFT_BAR, /* Draw bar charts. */
180 GFT_HIST, /* Draw histograms. */
181 GFT_PIE, /* Draw piechart */
182 GFT_HBAR /* Draw bar charts or histograms at our discretion. */
185 /* Parsed command. */
186 static struct cmd_frequencies cmd;
188 /* Summary of the barchart, histogram, and hbar subcommands. */
189 /* FIXME: These should not be mututally exclusive */
190 static int chart; /* NONE/BAR/HIST/HBAR/PIE. */
191 static double min, max; /* Minimum, maximum on y axis. */
192 static int format; /* FREQ/PERCENT: Scaling of y axis. */
193 static double scale, incr; /* FIXME */
194 static int normal; /* FIXME */
196 /* Variables for which to calculate statistics. */
197 static size_t n_variables;
198 static struct variable **v_variables;
200 /* Arenas used to store semi-permanent storage. */
201 static struct pool *int_pool; /* Integer mode. */
202 static struct pool *gen_pool; /* General mode. */
204 /* Frequency tables. */
206 /* Frequency table entry. */
209 union value v; /* The value. */
210 double c; /* The number of occurrences of the value. */
213 /* Types of frequency tables. */
220 /* Entire frequency table. */
223 int mode; /* FRQM_GENERAL or FRQM_INTEGER. */
226 struct hsh_table *data; /* Undifferentiated data. */
229 double *vector; /* Frequencies proper. */
230 int min, max; /* The boundaries of the table. */
231 double out_of_range; /* Sum of weights of out-of-range values. */
232 double sysmis; /* Sum of weights of SYSMIS values. */
235 struct freq *valid; /* Valid freqs. */
236 int n_valid; /* Number of total freqs. */
238 struct freq *missing; /* Missing freqs. */
239 int n_missing; /* Number of missing freqs. */
242 double total_cases; /* Sum of weights of all cases. */
243 double valid_cases; /* Sum of weights of valid cases. */
247 /* Per-variable frequency data. */
250 /* Freqency table. */
251 struct freq_tab tab; /* Frequencies table to use. */
254 int n_groups; /* Number of groups. */
255 double *groups; /* Groups. */
258 double stat[frq_n_stats];
261 static inline struct var_freqs *
262 get_var_freqs (struct variable *v)
265 assert (v->aux != NULL);
269 static void determine_charts (void);
271 static void calc_stats (struct variable *v, double d[frq_n_stats]);
273 static void precalc (const struct ccase *, void *);
274 static bool calc (const struct ccase *, void *);
275 static void postcalc (void *);
277 static void postprocess_freq_tab (struct variable *);
278 static void dump_full (struct variable *);
279 static void dump_condensed (struct variable *);
280 static void dump_statistics (struct variable *, int show_varname);
281 static void cleanup_freq_tab (struct variable *);
283 static hsh_hash_func hash_value_numeric, hash_value_alpha;
284 static hsh_compare_func compare_value_numeric_a, compare_value_alpha_a;
285 static hsh_compare_func compare_value_numeric_d, compare_value_alpha_d;
286 static hsh_compare_func compare_freq_numeric_a, compare_freq_alpha_a;
287 static hsh_compare_func compare_freq_numeric_d, compare_freq_alpha_d;
290 static void do_piechart(const struct variable *var,
291 const struct freq_tab *frq_tab);
294 freq_tab_to_hist(const struct freq_tab *ft, const struct variable *var);
298 /* Parser and outline. */
300 static int internal_cmd_frequencies (void);
303 cmd_frequencies (void)
307 int_pool = pool_create ();
308 result = internal_cmd_frequencies ();
309 pool_destroy (int_pool);
311 pool_destroy (gen_pool);
319 internal_cmd_frequencies (void)
330 if (!parse_frequencies (&cmd))
333 if (cmd.onepage_limit == NOT_LONG)
334 cmd.onepage_limit = 50;
336 /* Figure out statistics to calculate. */
338 if (cmd.a_statistics[FRQ_ST_DEFAULT] || !cmd.sbc_statistics)
339 stats |= frq_default;
340 if (cmd.a_statistics[FRQ_ST_ALL])
342 if (cmd.sort != FRQ_AVALUE && cmd.sort != FRQ_DVALUE)
343 stats &= ~frq_median;
344 for (i = 0; i < frq_n_stats; i++)
345 if (cmd.a_statistics[st_name[i].st_indx])
346 stats |= BIT_INDEX (i);
347 if (stats & frq_kurt)
349 if (stats & frq_skew)
352 /* Calculate n_stats. */
354 for (i = 0; i < frq_n_stats; i++)
355 if ((stats & BIT_INDEX (i)))
360 if (chart != GFT_NONE || cmd.sbc_ntiles)
361 cmd.sort = FRQ_AVALUE;
363 /* Work out what percentiles need to be calculated */
364 if ( cmd.sbc_percentiles )
366 for ( i = 0 ; i < MAXLISTS ; ++i )
369 subc_list_double *ptl_list = &cmd.dl_percentiles[i];
370 for ( pl = 0 ; pl < subc_list_double_count(ptl_list); ++pl)
371 add_percentile(subc_list_double_at(ptl_list,pl) / 100.0 );
374 if ( cmd.sbc_ntiles )
376 for ( i = 0 ; i < cmd.sbc_ntiles ; ++i )
379 for (j = 0; j <= cmd.n_ntiles[i]; ++j )
380 add_percentile(j / (double) cmd.n_ntiles[i]);
386 ok = procedure_with_splits (precalc, calc, postcalc, NULL);
388 free_frequencies(&cmd);
390 return ok ? CMD_SUCCESS : CMD_CASCADING_FAILURE;
393 /* Figure out which charts the user requested. */
395 determine_charts (void)
397 int count = (!!cmd.sbc_histogram) + (!!cmd.sbc_barchart) +
398 (!!cmd.sbc_hbar) + (!!cmd.sbc_piechart);
408 msg (SW, _("At most one of BARCHART, HISTOGRAM, or HBAR should be "
409 "given. HBAR will be assumed. Argument values will be "
410 "given precedence increasing along the order given."));
412 else if (cmd.sbc_histogram)
414 else if (cmd.sbc_barchart)
416 else if (cmd.sbc_piechart)
427 if (cmd.sbc_barchart)
429 if (cmd.ba_min != SYSMIS)
431 if (cmd.ba_max != SYSMIS)
433 if (cmd.ba_scale == FRQ_FREQ)
438 else if (cmd.ba_scale == FRQ_PERCENT)
440 format = FRQ_PERCENT;
445 if (cmd.sbc_histogram)
447 if (cmd.hi_min != SYSMIS)
449 if (cmd.hi_max != SYSMIS)
451 if (cmd.hi_scale == FRQ_FREQ)
456 else if (cmd.hi_scale == FRQ_PERCENT)
458 format = FRQ_PERCENT;
461 if (cmd.hi_norm != FRQ_NONORMAL )
463 if (cmd.hi_incr == FRQ_INCREMENT)
469 if (cmd.hb_min != SYSMIS)
471 if (cmd.hb_max != SYSMIS)
473 if (cmd.hb_scale == FRQ_FREQ)
478 else if (cmd.hb_scale == FRQ_PERCENT)
480 format = FRQ_PERCENT;
485 if (cmd.hb_incr == FRQ_INCREMENT)
489 if (min != SYSMIS && max != SYSMIS && min >= max)
491 msg (SE, _("MAX must be greater than or equal to MIN, if both are "
492 "specified. However, MIN was specified as %g and MAX as %g. "
493 "MIN and MAX will be ignored."), min, max);
498 /* Add data from case C to the frequency table. */
500 calc (const struct ccase *c, void *aux UNUSED)
506 weight = dict_get_case_weight (default_dict, c, &bad_warn);
508 for (i = 0; i < n_variables; i++)
510 struct variable *v = v_variables[i];
511 const union value *val = case_data (c, v->fv);
512 struct freq_tab *ft = &get_var_freqs (v)->tab;
520 struct freq **fpp = (struct freq **) hsh_probe (ft->data, val);
526 struct freq *fp = *fpp = pool_alloc (gen_pool, sizeof *fp);
534 if (val->f == SYSMIS)
535 ft->sysmis += weight;
536 else if (val->f > INT_MIN+1 && val->f < INT_MAX-1)
539 if (i >= ft->min && i <= ft->max)
540 ft->vector[i - ft->min] += weight;
543 ft->out_of_range += weight;
552 /* Prepares each variable that is the target of FREQUENCIES by setting
553 up its hash table. */
555 precalc (const struct ccase *first, void *aux UNUSED)
559 output_split_file_values (first);
561 pool_destroy (gen_pool);
562 gen_pool = pool_create ();
564 for (i = 0; i < n_variables; i++)
566 struct variable *v = v_variables[i];
567 struct freq_tab *ft = &get_var_freqs (v)->tab;
569 if (ft->mode == FRQM_GENERAL)
572 hsh_compare_func *compare;
574 if (v->type == NUMERIC)
576 hash = hash_value_numeric;
577 compare = compare_value_numeric_a;
581 hash = hash_value_alpha;
582 compare = compare_value_alpha_a;
584 ft->data = hsh_create (16, compare, hash, NULL, v);
590 for (j = (ft->max - ft->min); j >= 0; j--)
592 ft->out_of_range = 0.0;
598 /* Finishes up with the variables after frequencies have been
599 calculated. Displays statistics, percentiles, ... */
601 postcalc (void *aux UNUSED)
605 for (i = 0; i < n_variables; i++)
607 struct variable *v = v_variables[i];
608 struct var_freqs *vf = get_var_freqs (v);
609 struct freq_tab *ft = &vf->tab;
611 int dumped_freq_tab = 1;
613 postprocess_freq_tab (v);
615 /* Frequencies tables. */
616 n_categories = ft->n_valid + ft->n_missing;
617 if (cmd.table == FRQ_TABLE
618 || (cmd.table == FRQ_LIMIT && n_categories <= cmd.limit))
628 if (n_categories > cmd.onepage_limit)
641 dump_statistics (v, !dumped_freq_tab);
645 if ( chart == GFT_HIST)
647 double d[frq_n_stats];
648 struct normal_curve norm;
649 gsl_histogram *hist ;
652 norm.N = vf->tab.valid_cases;
655 norm.mean = d[frq_mean];
656 norm.stddev = d[frq_stddev];
658 hist = freq_tab_to_hist(ft,v);
660 histogram_plot(hist, var_to_string(v), &norm, normal);
662 gsl_histogram_free(hist);
666 if ( chart == GFT_PIE)
668 do_piechart(v_variables[i], ft);
673 cleanup_freq_tab (v);
678 /* Returns the comparison function that should be used for
679 sorting a frequency table by FRQ_SORT using VAR_TYPE
681 static hsh_compare_func *
682 get_freq_comparator (int frq_sort, int var_type)
684 /* Note that q2c generates tags beginning with 1000. */
685 switch (frq_sort | (var_type << 16))
687 case FRQ_AVALUE | (NUMERIC << 16): return compare_value_numeric_a;
688 case FRQ_AVALUE | (ALPHA << 16): return compare_value_alpha_a;
689 case FRQ_DVALUE | (NUMERIC << 16): return compare_value_numeric_d;
690 case FRQ_DVALUE | (ALPHA << 16): return compare_value_alpha_d;
691 case FRQ_AFREQ | (NUMERIC << 16): return compare_freq_numeric_a;
692 case FRQ_AFREQ | (ALPHA << 16): return compare_freq_alpha_a;
693 case FRQ_DFREQ | (NUMERIC << 16): return compare_freq_numeric_d;
694 case FRQ_DFREQ | (ALPHA << 16): return compare_freq_alpha_d;
701 /* Returns nonzero iff the value in struct freq F is non-missing
704 not_missing (const void *f_, void *v_)
706 const struct freq *f = f_;
707 struct variable *v = v_;
709 return !mv_is_value_missing (&v->miss, &f->v);
712 /* Summarizes the frequency table data for variable V. */
714 postprocess_freq_tab (struct variable *v)
716 hsh_compare_func *compare;
720 struct freq *freqs, *f;
723 ft = &get_var_freqs (v)->tab;
724 assert (ft->mode == FRQM_GENERAL);
725 compare = get_freq_comparator (cmd.sort, v->type);
727 /* Extract data from hash table. */
728 count = hsh_count (ft->data);
729 data = hsh_data (ft->data);
731 /* Copy dereferenced data into freqs. */
732 freqs = xnmalloc (count, sizeof *freqs);
733 for (i = 0; i < count; i++)
735 struct freq *f = data[i];
739 /* Put data into ft. */
741 ft->n_valid = partition (freqs, count, sizeof *freqs, not_missing, v);
742 ft->missing = freqs + ft->n_valid;
743 ft->n_missing = count - ft->n_valid;
746 sort (ft->valid, ft->n_valid, sizeof *ft->valid, compare, v);
747 sort (ft->missing, ft->n_missing, sizeof *ft->missing, compare, v);
749 /* Summary statistics. */
750 ft->valid_cases = 0.0;
751 for(i = 0 ; i < ft->n_valid ; ++i )
754 ft->valid_cases += f->c;
758 ft->total_cases = ft->valid_cases ;
759 for(i = 0 ; i < ft->n_missing ; ++i )
762 ft->total_cases += f->c;
767 /* Frees the frequency table for variable V. */
769 cleanup_freq_tab (struct variable *v)
771 struct freq_tab *ft = &get_var_freqs (v)->tab;
772 assert (ft->mode == FRQM_GENERAL);
774 hsh_destroy (ft->data);
777 /* Parses the VARIABLES subcommand, adding to
778 {n_variables,v_variables}. */
780 frq_custom_variables (struct cmd_frequencies *cmd UNUSED)
783 int min = 0, max = 0;
785 size_t old_n_variables = n_variables;
789 if (token != T_ALL && (token != T_ID
790 || dict_lookup_var (default_dict, tokid) == NULL))
793 if (!parse_variables (default_dict, &v_variables, &n_variables,
794 PV_APPEND | PV_NO_SCRATCH))
797 if (!lex_match ('('))
802 if (!lex_force_int ())
804 min = lex_integer ();
806 if (!lex_force_match (','))
808 if (!lex_force_int ())
810 max = lex_integer ();
812 if (!lex_force_match (')'))
816 msg (SE, _("Upper limit of integer mode value range must be "
817 "greater than lower limit."));
822 for (i = old_n_variables; i < n_variables; i++)
824 struct variable *v = v_variables[i];
825 struct var_freqs *vf;
829 msg (SE, _("Variable %s specified multiple times on VARIABLES "
830 "subcommand."), v->name);
833 if (mode == FRQM_INTEGER && v->type != NUMERIC)
835 msg (SE, _("Integer mode specified, but %s is not a numeric "
836 "variable."), v->name);
840 vf = var_attach_aux (v, xmalloc (sizeof *vf), var_dtor_free);
842 vf->tab.valid = vf->tab.missing = NULL;
843 if (mode == FRQM_INTEGER)
847 vf->tab.vector = pool_nalloc (int_pool,
848 max - min + 1, sizeof *vf->tab.vector);
851 vf->tab.vector = NULL;
858 /* Parses the GROUPED subcommand, setting the n_grouped, grouped
859 fields of specified variables. */
861 frq_custom_grouped (struct cmd_frequencies *cmd UNUSED)
864 if ((token == T_ID && dict_lookup_var (default_dict, tokid) != NULL)
870 /* Max, current size of list; list itself. */
878 if (!parse_variables (default_dict, &v, &n,
879 PV_NO_DUPLICATE | PV_NUMERIC))
885 while (lex_integer ())
890 dl = pool_nrealloc (int_pool, dl, ml, sizeof *dl);
896 /* Note that nl might still be 0 and dl might still be
897 NULL. That's okay. */
898 if (!lex_match (')'))
901 msg (SE, _("`)' expected after GROUPED interval list."));
911 for (i = 0; i < n; i++)
912 if (v[i]->aux == NULL)
913 msg (SE, _("Variables %s specified on GROUPED but not on "
914 "VARIABLES."), v[i]->name);
917 struct var_freqs *vf = get_var_freqs (v[i]);
919 if (vf->groups != NULL)
920 msg (SE, _("Variables %s specified multiple times on GROUPED "
921 "subcommand."), v[i]->name);
929 if (!lex_match ('/'))
931 if ((token != T_ID || dict_lookup_var (default_dict, tokid) != NULL)
942 /* Adds X to the list of percentiles, keeping the list in proper
945 add_percentile (double x)
949 for (i = 0; i < n_percentiles; i++)
951 /* Do nothing if it's already in the list */
952 if ( fabs(x - percentiles[i].p) < DBL_EPSILON )
955 if (x < percentiles[i].p)
959 if (i >= n_percentiles || tokval != percentiles[i].p)
961 percentiles = pool_nrealloc (int_pool, percentiles,
962 n_percentiles + 1, sizeof *percentiles);
964 if (i < n_percentiles)
965 memmove (&percentiles[i + 1], &percentiles[i],
966 (n_percentiles - i) * sizeof (struct percentile) );
968 percentiles[i].p = x;
973 /* Comparison functions. */
975 /* Hash of numeric values. */
977 hash_value_numeric (const void *value_, void *foo UNUSED)
979 const struct freq *value = value_;
980 return hsh_hash_double (value->v.f);
983 /* Hash of string values. */
985 hash_value_alpha (const void *value_, void *v_)
987 const struct freq *value = value_;
988 struct variable *v = v_;
990 return hsh_hash_bytes (value->v.s, MIN (MAX_SHORT_STRING, v->width));
993 /* Ascending numeric compare of values. */
995 compare_value_numeric_a (const void *a_, const void *b_, void *foo UNUSED)
997 const struct freq *a = a_;
998 const struct freq *b = b_;
1000 if (a->v.f > b->v.f)
1002 else if (a->v.f < b->v.f)
1008 /* Ascending string compare of values. */
1010 compare_value_alpha_a (const void *a_, const void *b_, void *v_)
1012 const struct freq *a = a_;
1013 const struct freq *b = b_;
1014 const struct variable *v = v_;
1016 return memcmp (a->v.s, b->v.s, MIN (MAX_SHORT_STRING, v->width));
1019 /* Descending numeric compare of values. */
1021 compare_value_numeric_d (const void *a, const void *b, void *foo UNUSED)
1023 return -compare_value_numeric_a (a, b, foo);
1026 /* Descending string compare of values. */
1028 compare_value_alpha_d (const void *a, const void *b, void *v)
1030 return -compare_value_alpha_a (a, b, v);
1033 /* Ascending numeric compare of frequency;
1034 secondary key on ascending numeric value. */
1036 compare_freq_numeric_a (const void *a_, const void *b_, void *foo UNUSED)
1038 const struct freq *a = a_;
1039 const struct freq *b = b_;
1043 else if (a->c < b->c)
1046 if (a->v.f > b->v.f)
1048 else if (a->v.f < b->v.f)
1054 /* Ascending numeric compare of frequency;
1055 secondary key on ascending string value. */
1057 compare_freq_alpha_a (const void *a_, const void *b_, void *v_)
1059 const struct freq *a = a_;
1060 const struct freq *b = b_;
1061 const struct variable *v = v_;
1065 else if (a->c < b->c)
1068 return memcmp (a->v.s, b->v.s, MIN (MAX_SHORT_STRING, v->width));
1071 /* Descending numeric compare of frequency;
1072 secondary key on ascending numeric value. */
1074 compare_freq_numeric_d (const void *a_, const void *b_, void *foo UNUSED)
1076 const struct freq *a = a_;
1077 const struct freq *b = b_;
1081 else if (a->c < b->c)
1084 if (a->v.f > b->v.f)
1086 else if (a->v.f < b->v.f)
1092 /* Descending numeric compare of frequency;
1093 secondary key on ascending string value. */
1095 compare_freq_alpha_d (const void *a_, const void *b_, void *v_)
1097 const struct freq *a = a_;
1098 const struct freq *b = b_;
1099 const struct variable *v = v_;
1103 else if (a->c < b->c)
1106 return memcmp (a->v.s, b->v.s, MIN (MAX_SHORT_STRING, v->width));
1109 /* Frequency table display. */
1111 /* Sets the widths of all the columns and heights of all the rows in
1112 table T for driver D. */
1114 full_dim (struct tab_table *t, struct outp_driver *d)
1116 int lab = cmd.labels == FRQ_LABELS;
1120 t->w[0] = min (tab_natural_width (t, d, 0), d->prop_em_width * 15);
1121 for (i = lab; i < lab + 5; i++)
1122 t->w[i] = max (tab_natural_width (t, d, i), d->prop_em_width * 8);
1123 for (i = 0; i < t->nr; i++)
1124 t->h[i] = d->font_height;
1127 /* Displays a full frequency table for variable V. */
1129 dump_full (struct variable *v)
1132 struct freq_tab *ft;
1134 struct tab_table *t;
1136 double cum_total = 0.0;
1137 double cum_freq = 0.0;
1138 struct fmt_spec fmt;
1148 static struct init vec[] =
1150 {4, 0, N_("Valid")},
1152 {1, 1, N_("Value")},
1153 {2, 1, N_("Frequency")},
1154 {3, 1, N_("Percent")},
1155 {4, 1, N_("Percent")},
1156 {5, 1, N_("Percent")},
1164 int lab = cmd.labels == FRQ_LABELS;
1166 ft = &get_var_freqs (v)->tab;
1167 n_categories = ft->n_valid + ft->n_missing;
1168 t = tab_create (5 + lab, n_categories + 3, 0);
1169 tab_headers (t, 0, 0, 2, 0);
1170 tab_dim (t, full_dim);
1173 tab_text (t, 0, 1, TAB_CENTER | TAT_TITLE, _("Value Label"));
1174 for (p = vec; p->s; p++)
1175 tab_text (t, p->c - (p->r ? !lab : 0), p->r,
1176 TAB_CENTER | TAT_TITLE, gettext (p->s));
1179 if (v->width > MAX_SHORT_STRING)
1180 fmt.w = MAX_SHORT_STRING * (fmt.type == FMT_AHEX ? 2 : 1);
1183 for (f = ft->valid; f < ft->missing; f++)
1185 double percent, valid_percent;
1189 percent = f->c / ft->total_cases * 100.0;
1190 valid_percent = f->c / ft->valid_cases * 100.0;
1191 cum_total += valid_percent;
1195 const char *label = val_labs_find (v->val_labs, f->v);
1197 tab_text (t, 0, r, TAB_LEFT, label);
1200 tab_value (t, 0 + lab, r, TAB_NONE, &f->v, &fmt);
1201 tab_float (t, 1 + lab, r, TAB_NONE, f->c, 8, 0);
1202 tab_float (t, 2 + lab, r, TAB_NONE, percent, 5, 1);
1203 tab_float (t, 3 + lab, r, TAB_NONE, valid_percent, 5, 1);
1204 tab_float (t, 4 + lab, r, TAB_NONE, cum_total, 5, 1);
1207 for (; f < &ft->valid[n_categories]; f++)
1213 const char *label = val_labs_find (v->val_labs, f->v);
1215 tab_text (t, 0, r, TAB_LEFT, label);
1218 tab_value (t, 0 + lab, r, TAB_NONE, &f->v, &fmt);
1219 tab_float (t, 1 + lab, r, TAB_NONE, f->c, 8, 0);
1220 tab_float (t, 2 + lab, r, TAB_NONE,
1221 f->c / ft->total_cases * 100.0, 5, 1);
1222 tab_text (t, 3 + lab, r, TAB_NONE, _("Missing"));
1226 tab_box (t, TAL_1, TAL_1,
1227 cmd.spaces == FRQ_SINGLE ? -1 : TAL_GAP, TAL_1,
1229 tab_hline (t, TAL_2, 0, 4 + lab, 2);
1230 tab_hline (t, TAL_2, 0, 4 + lab, r);
1231 tab_joint_text (t, 0, r, 0 + lab, r, TAB_RIGHT | TAT_TITLE, _("Total"));
1232 tab_vline (t, TAL_0, 1, r, r);
1233 tab_float (t, 1 + lab, r, TAB_NONE, cum_freq, 8, 0);
1234 tab_float (t, 2 + lab, r, TAB_NONE, 100.0, 5, 1);
1235 tab_float (t, 3 + lab, r, TAB_NONE, 100.0, 5, 1);
1237 tab_title (t, "%s: %s", v->name, v->label ? v->label : "");
1242 /* Sets the widths of all the columns and heights of all the rows in
1243 table T for driver D. */
1245 condensed_dim (struct tab_table *t, struct outp_driver *d)
1247 int cum_w = max (outp_string_width (d, _("Cum"), OUTP_PROPORTIONAL),
1248 max (outp_string_width (d, _("Cum"), OUTP_PROPORTIONAL),
1249 outp_string_width (d, "000", OUTP_PROPORTIONAL)));
1253 for (i = 0; i < 2; i++)
1254 t->w[i] = max (tab_natural_width (t, d, i), d->prop_em_width * 8);
1255 for (i = 2; i < 4; i++)
1257 for (i = 0; i < t->nr; i++)
1258 t->h[i] = d->font_height;
1261 /* Display condensed frequency table for variable V. */
1263 dump_condensed (struct variable *v)
1266 struct freq_tab *ft;
1268 struct tab_table *t;
1270 double cum_total = 0.0;
1271 struct fmt_spec fmt;
1273 ft = &get_var_freqs (v)->tab;
1274 n_categories = ft->n_valid + ft->n_missing;
1275 t = tab_create (4, n_categories + 2, 0);
1277 tab_headers (t, 0, 0, 2, 0);
1278 tab_text (t, 0, 1, TAB_CENTER | TAT_TITLE, _("Value"));
1279 tab_text (t, 1, 1, TAB_CENTER | TAT_TITLE, _("Freq"));
1280 tab_text (t, 2, 1, TAB_CENTER | TAT_TITLE, _("Pct"));
1281 tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("Cum"));
1282 tab_text (t, 3, 1, TAB_CENTER | TAT_TITLE, _("Pct"));
1283 tab_dim (t, condensed_dim);
1286 if (v->width > MAX_SHORT_STRING)
1287 fmt.w = MAX_SHORT_STRING * (fmt.type == FMT_AHEX ? 2 : 1);
1290 for (f = ft->valid; f < ft->missing; f++)
1294 percent = f->c / ft->total_cases * 100.0;
1295 cum_total += f->c / ft->valid_cases * 100.0;
1297 tab_value (t, 0, r, TAB_NONE, &f->v, &fmt);
1298 tab_float (t, 1, r, TAB_NONE, f->c, 8, 0);
1299 tab_float (t, 2, r, TAB_NONE, percent, 3, 0);
1300 tab_float (t, 3, r, TAB_NONE, cum_total, 3, 0);
1303 for (; f < &ft->valid[n_categories]; f++)
1305 tab_value (t, 0, r, TAB_NONE, &f->v, &fmt);
1306 tab_float (t, 1, r, TAB_NONE, f->c, 8, 0);
1307 tab_float (t, 2, r, TAB_NONE,
1308 f->c / ft->total_cases * 100.0, 3, 0);
1312 tab_box (t, TAL_1, TAL_1,
1313 cmd.spaces == FRQ_SINGLE ? -1 : TAL_GAP, TAL_1,
1315 tab_hline (t, TAL_2, 0, 3, 2);
1316 tab_title (t, "%s: %s", v->name, v->label ? v->label : "");
1317 tab_columns (t, SOM_COL_DOWN, 1);
1321 /* Statistical display. */
1323 /* Calculates all the pertinent statistics for variable V, putting
1324 them in array D[]. FIXME: This could be made much more optimal. */
1326 calc_stats (struct variable *v, double d[frq_n_stats])
1328 struct freq_tab *ft = &get_var_freqs (v)->tab;
1329 double W = ft->valid_cases;
1338 double *median_value;
1340 /* Calculate percentiles. */
1342 /* If the 50th percentile was not explicitly requested then we must
1343 calculate it anyway --- it's the median */
1345 for (i = 0; i < n_percentiles; i++)
1347 if (percentiles[i].p == 0.5)
1349 median_value = &percentiles[i].value;
1354 if ( 0 == median_value )
1356 add_percentile (0.5);
1360 for (i = 0; i < n_percentiles; i++)
1362 percentiles[i].flag = 0;
1363 percentiles[i].flag2 = 0;
1367 for (idx = 0; idx < ft->n_valid; ++idx)
1369 static double prev_value = SYSMIS;
1370 f = &ft->valid[idx];
1372 for (i = 0; i < n_percentiles; i++)
1375 if ( percentiles[i].flag2 ) continue ;
1377 if ( get_algorithm() != COMPATIBLE )
1379 (ft->valid_cases - 1) * percentiles[i].p;
1382 (ft->valid_cases + 1) * percentiles[i].p - 1;
1384 if ( percentiles[i].flag )
1386 percentiles[i].x2 = f->v.f;
1387 percentiles[i].x1 = prev_value;
1388 percentiles[i].flag2 = 1;
1394 if ( f->c > 1 && rank - (f->c - 1) > tp )
1396 percentiles[i].x2 = percentiles[i].x1 = f->v.f;
1397 percentiles[i].flag2 = 1;
1401 percentiles[i].flag=1;
1407 prev_value = f->v.f;
1410 for (i = 0; i < n_percentiles; i++)
1412 /* Catches the case when p == 100% */
1413 if ( ! percentiles[i].flag2 )
1414 percentiles[i].x1 = percentiles[i].x2 = f->v.f;
1417 printf("percentile %d (p==%.2f); X1 = %g; X2 = %g\n",
1418 i,percentiles[i].p,percentiles[i].x1,percentiles[i].x2);
1422 for (i = 0; i < n_percentiles; i++)
1424 struct freq_tab *ft = &get_var_freqs (v)->tab;
1428 if ( get_algorithm() != COMPATIBLE )
1430 s = modf((ft->valid_cases - 1) * percentiles[i].p , &dummy);
1434 s = modf((ft->valid_cases + 1) * percentiles[i].p -1, &dummy);
1437 percentiles[i].value = percentiles[i].x1 +
1438 ( percentiles[i].x2 - percentiles[i].x1) * s ;
1440 if ( percentiles[i].p == 0.50)
1441 median_value = &percentiles[i].value;
1445 /* Calculate the mode. */
1448 for (f = ft->valid; f < ft->missing; f++)
1450 if (most_often < f->c)
1455 else if (most_often == f->c)
1457 /* A duplicate mode is undefined.
1458 FIXME: keep track of *all* the modes. */
1463 /* Calculate moments. */
1464 m = moments_create (MOMENT_KURTOSIS);
1465 for (f = ft->valid; f < ft->missing; f++)
1466 moments_pass_one (m, f->v.f, f->c);
1467 for (f = ft->valid; f < ft->missing; f++)
1468 moments_pass_two (m, f->v.f, f->c);
1469 moments_calculate (m, NULL, &d[frq_mean], &d[frq_variance],
1470 &d[frq_skew], &d[frq_kurt]);
1471 moments_destroy (m);
1473 /* Formulas below are taken from _SPSS Statistical Algorithms_. */
1474 d[frq_min] = ft->valid[0].v.f;
1475 d[frq_max] = ft->valid[ft->n_valid - 1].v.f;
1476 d[frq_mode] = X_mode;
1477 d[frq_range] = d[frq_max] - d[frq_min];
1478 d[frq_median] = *median_value;
1479 d[frq_sum] = d[frq_mean] * W;
1480 d[frq_stddev] = sqrt (d[frq_variance]);
1481 d[frq_semean] = d[frq_stddev] / sqrt (W);
1482 d[frq_seskew] = calc_seskew (W);
1483 d[frq_sekurt] = calc_sekurt (W);
1486 /* Displays a table of all the statistics requested for variable V. */
1488 dump_statistics (struct variable *v, int show_varname)
1490 struct freq_tab *ft;
1491 double stat_value[frq_n_stats];
1492 struct tab_table *t;
1495 int n_explicit_percentiles = n_percentiles;
1497 if ( implicit_50th && n_percentiles > 0 )
1500 if (v->type == ALPHA)
1502 ft = &get_var_freqs (v)->tab;
1503 if (ft->n_valid == 0)
1505 msg (SW, _("No valid data for variable %s; statistics not displayed."),
1509 calc_stats (v, stat_value);
1511 t = tab_create (3, n_stats + n_explicit_percentiles + 2, 0);
1512 tab_dim (t, tab_natural_dimensions);
1514 tab_box (t, TAL_1, TAL_1, -1, -1 , 0 , 0 , 2, tab_nr(t) - 1) ;
1517 tab_vline (t, TAL_1 , 2, 0, tab_nr(t) - 1);
1518 tab_vline (t, TAL_GAP , 1, 0, tab_nr(t) - 1 ) ;
1520 r=2; /* N missing and N valid are always dumped */
1522 for (i = 0; i < frq_n_stats; i++)
1523 if (stats & BIT_INDEX (i))
1525 tab_text (t, 0, r, TAB_LEFT | TAT_TITLE,
1526 gettext (st_name[i].s10));
1527 tab_float (t, 2, r, TAB_NONE, stat_value[i], 11, 3);
1531 tab_text (t, 0, 0, TAB_LEFT | TAT_TITLE, _("N"));
1532 tab_text (t, 1, 0, TAB_LEFT | TAT_TITLE, _("Valid"));
1533 tab_text (t, 1, 1, TAB_LEFT | TAT_TITLE, _("Missing"));
1535 tab_float(t, 2, 0, TAB_NONE, ft->valid_cases, 11, 0);
1536 tab_float(t, 2, 1, TAB_NONE, ft->total_cases - ft->valid_cases, 11, 0);
1539 for (i = 0; i < n_explicit_percentiles; i++, r++)
1543 tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, _("Percentiles"));
1546 tab_float (t, 1, r, TAB_LEFT, percentiles[i].p * 100, 3, 0 );
1547 tab_float (t, 2, r, TAB_NONE, percentiles[i].value, 11, 3);
1551 tab_columns (t, SOM_COL_DOWN, 1);
1555 tab_title (t, "%s: %s", v->name, v->label);
1557 tab_title (t, "%s", v->name);
1560 tab_flags (t, SOMF_NO_TITLE);
1567 /* Create a gsl_histogram from a freq_tab */
1569 freq_tab_to_hist(const struct freq_tab *ft, const struct variable *var)
1572 double x_min = DBL_MAX;
1573 double x_max = -DBL_MAX;
1575 gsl_histogram *hist;
1576 const double bins = 11;
1578 struct hsh_iterator hi;
1579 struct hsh_table *fh = ft->data;
1582 /* Find out the extremes of the x value */
1583 for ( frq = hsh_first(fh, &hi); frq != 0; frq = hsh_next(fh, &hi) )
1585 if ( mv_is_value_missing(&var->miss, &frq->v))
1588 if ( frq->v.f < x_min ) x_min = frq->v.f ;
1589 if ( frq->v.f > x_max ) x_max = frq->v.f ;
1592 hist = histogram_create(bins, x_min, x_max);
1594 for( i = 0 ; i < ft->n_valid ; ++i )
1596 frq = &ft->valid[i];
1597 gsl_histogram_accumulate(hist, frq->v.f, frq->c);
1604 static struct slice *
1605 freq_tab_to_slice_array(const struct freq_tab *frq_tab,
1606 const struct variable *var,
1610 /* Allocate an array of slices and fill them from the data in frq_tab
1611 n_slices will contain the number of slices allocated.
1612 The caller is responsible for freeing slices
1614 static struct slice *
1615 freq_tab_to_slice_array(const struct freq_tab *frq_tab,
1616 const struct variable *var,
1620 struct slice *slices;
1622 *n_slices = frq_tab->n_valid;
1624 slices = xnmalloc (*n_slices, sizeof *slices);
1626 for (i = 0 ; i < *n_slices ; ++i )
1628 const struct freq *frq = &frq_tab->valid[i];
1630 slices[i].label = value_to_string(&frq->v, var);
1632 slices[i].magnetude = frq->c;
1642 do_piechart(const struct variable *var, const struct freq_tab *frq_tab)
1644 struct slice *slices;
1647 slices = freq_tab_to_slice_array(frq_tab, var, &n_slices);
1649 piechart_plot(var_to_string(var), slices, n_slices);