1 /* PSPP - computes sample statistics.
2 Copyright (C) 1997-9, 2000 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License as
6 published by the Free Software Foundation; either version 2 of the
7 License, or (at your option) any later version.
9 This program is distributed in the hope that it will be useful, but
10 WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22 * Remember that histograms, bar charts need mean, stddev.
29 #include <gsl/gsl_histogram.h>
31 #include <data/case.h>
32 #include <data/dictionary.h>
33 #include <data/format.h>
34 #include <data/procedure.h>
35 #include <data/settings.h>
36 #include <data/value-labels.h>
37 #include <data/variable.h>
38 #include <language/command.h>
39 #include <language/dictionary/split-file.h>
40 #include <language/lexer/lexer.h>
41 #include <libpspp/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 const 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];
260 /* Width and format for analysis and display.
261 This is normally the same as "width" and "print" in struct
262 variable, but in SPSS-compatible mode only the first
263 MAX_SHORT_STRING bytes of long string variables are
266 struct fmt_spec print;
269 static inline struct var_freqs *
270 get_var_freqs (const struct variable *v)
272 return var_get_aux (v);
275 static void determine_charts (void);
277 static void calc_stats (struct variable *v, double d[frq_n_stats]);
279 static void precalc (const struct ccase *, void *, const struct dataset *);
280 static bool calc (const struct ccase *, void *, const struct dataset *);
281 static bool postcalc (void *, const struct dataset *);
283 static void postprocess_freq_tab (struct variable *);
284 static void dump_full (struct variable *);
285 static void dump_condensed (struct variable *);
286 static void dump_statistics (struct variable *, int show_varname);
287 static void cleanup_freq_tab (struct variable *);
289 static hsh_hash_func hash_value_numeric, hash_value_alpha;
290 static hsh_compare_func compare_value_numeric_a, compare_value_alpha_a;
291 static hsh_compare_func compare_value_numeric_d, compare_value_alpha_d;
292 static hsh_compare_func compare_freq_numeric_a, compare_freq_alpha_a;
293 static hsh_compare_func compare_freq_numeric_d, compare_freq_alpha_d;
296 static void do_piechart(const struct variable *var,
297 const struct freq_tab *frq_tab);
300 freq_tab_to_hist(const struct freq_tab *ft, const struct variable *var);
304 /* Parser and outline. */
306 static int internal_cmd_frequencies (struct lexer *lexer, struct dataset *ds);
309 cmd_frequencies (struct lexer *lexer, struct dataset *ds)
313 int_pool = pool_create ();
314 result = internal_cmd_frequencies (lexer, ds);
315 pool_destroy (int_pool);
317 pool_destroy (gen_pool);
325 internal_cmd_frequencies (struct lexer *lexer, struct dataset *ds)
336 if (!parse_frequencies (lexer, ds, &cmd, NULL))
339 if (cmd.onepage_limit == NOT_LONG)
340 cmd.onepage_limit = 50;
342 /* Figure out statistics to calculate. */
344 if (cmd.a_statistics[FRQ_ST_DEFAULT] || !cmd.sbc_statistics)
345 stats |= frq_default;
346 if (cmd.a_statistics[FRQ_ST_ALL])
348 if (cmd.sort != FRQ_AVALUE && cmd.sort != FRQ_DVALUE)
349 stats &= ~frq_median;
350 for (i = 0; i < frq_n_stats; i++)
351 if (cmd.a_statistics[st_name[i].st_indx])
352 stats |= BIT_INDEX (i);
353 if (stats & frq_kurt)
355 if (stats & frq_skew)
358 /* Calculate n_stats. */
360 for (i = 0; i < frq_n_stats; i++)
361 if ((stats & BIT_INDEX (i)))
366 if (chart != GFT_NONE || cmd.sbc_ntiles)
367 cmd.sort = FRQ_AVALUE;
369 /* Work out what percentiles need to be calculated */
370 if ( cmd.sbc_percentiles )
372 for ( i = 0 ; i < MAXLISTS ; ++i )
375 subc_list_double *ptl_list = &cmd.dl_percentiles[i];
376 for ( pl = 0 ; pl < subc_list_double_count(ptl_list); ++pl)
377 add_percentile (subc_list_double_at(ptl_list, pl) / 100.0 );
380 if ( cmd.sbc_ntiles )
382 for ( i = 0 ; i < cmd.sbc_ntiles ; ++i )
385 for (j = 0; j <= cmd.n_ntiles[i]; ++j )
386 add_percentile (j / (double) cmd.n_ntiles[i]);
392 ok = procedure_with_splits (ds, precalc, calc, postcalc, NULL);
394 free_frequencies(&cmd);
396 return ok ? CMD_SUCCESS : CMD_CASCADING_FAILURE;
399 /* Figure out which charts the user requested. */
401 determine_charts (void)
403 int count = (!!cmd.sbc_histogram) + (!!cmd.sbc_barchart) +
404 (!!cmd.sbc_hbar) + (!!cmd.sbc_piechart);
414 msg (SW, _("At most one of BARCHART, HISTOGRAM, or HBAR should be "
415 "given. HBAR will be assumed. Argument values will be "
416 "given precedence increasing along the order given."));
418 else if (cmd.sbc_histogram)
420 else if (cmd.sbc_barchart)
422 else if (cmd.sbc_piechart)
433 if (cmd.sbc_barchart)
435 if (cmd.ba_min != SYSMIS)
437 if (cmd.ba_max != SYSMIS)
439 if (cmd.ba_scale == FRQ_FREQ)
444 else if (cmd.ba_scale == FRQ_PERCENT)
446 format = FRQ_PERCENT;
451 if (cmd.sbc_histogram)
453 if (cmd.hi_min != SYSMIS)
455 if (cmd.hi_max != SYSMIS)
457 if (cmd.hi_scale == FRQ_FREQ)
462 else if (cmd.hi_scale == FRQ_PERCENT)
464 format = FRQ_PERCENT;
467 if (cmd.hi_norm != FRQ_NONORMAL )
469 if (cmd.hi_incr == FRQ_INCREMENT)
475 if (cmd.hb_min != SYSMIS)
477 if (cmd.hb_max != SYSMIS)
479 if (cmd.hb_scale == FRQ_FREQ)
484 else if (cmd.hb_scale == FRQ_PERCENT)
486 format = FRQ_PERCENT;
491 if (cmd.hb_incr == FRQ_INCREMENT)
495 if (min != SYSMIS && max != SYSMIS && min >= max)
497 msg (SE, _("MAX must be greater than or equal to MIN, if both are "
498 "specified. However, MIN was specified as %g and MAX as %g. "
499 "MIN and MAX will be ignored."), min, max);
504 /* Add data from case C to the frequency table. */
506 calc (const struct ccase *c, void *aux UNUSED, const struct dataset *ds)
510 bool bad_warn = true;
512 weight = dict_get_case_weight (dataset_dict (ds), c, &bad_warn);
514 for (i = 0; i < n_variables; i++)
516 const struct variable *v = v_variables[i];
517 const union value *val = case_data (c, v);
518 struct var_freqs *vf = get_var_freqs (v);
519 struct freq_tab *ft = &vf->tab;
529 target.v = (union value *) val;
530 fpp = (struct freq **) hsh_probe (ft->data, &target);
536 struct freq *fp = pool_alloc (gen_pool, sizeof *fp);
538 fp->v = pool_clone (gen_pool,
539 val, MAX (MAX_SHORT_STRING, vf->width));
546 if (val->f == SYSMIS)
547 ft->sysmis += weight;
548 else if (val->f > INT_MIN+1 && val->f < INT_MAX-1)
551 if (i >= ft->min && i <= ft->max)
552 ft->vector[i - ft->min] += weight;
555 ft->out_of_range += weight;
564 /* Prepares each variable that is the target of FREQUENCIES by setting
565 up its hash table. */
567 precalc (const struct ccase *first, void *aux UNUSED, const struct dataset *ds)
571 output_split_file_values (ds, first);
573 pool_destroy (gen_pool);
574 gen_pool = pool_create ();
576 for (i = 0; i < n_variables; i++)
578 struct variable *v = v_variables[i];
579 struct freq_tab *ft = &get_var_freqs (v)->tab;
581 if (ft->mode == FRQM_GENERAL)
584 hsh_compare_func *compare;
586 if (var_is_numeric (v))
588 hash = hash_value_numeric;
589 compare = compare_value_numeric_a;
593 hash = hash_value_alpha;
594 compare = compare_value_alpha_a;
596 ft->data = hsh_create (16, compare, hash, NULL, v);
602 for (j = (ft->max - ft->min); j >= 0; j--)
604 ft->out_of_range = 0.0;
610 /* Finishes up with the variables after frequencies have been
611 calculated. Displays statistics, percentiles, ... */
613 postcalc (void *aux UNUSED, const struct dataset *ds UNUSED)
617 for (i = 0; i < n_variables; i++)
619 struct variable *v = v_variables[i];
620 struct var_freqs *vf = get_var_freqs (v);
621 struct freq_tab *ft = &vf->tab;
623 int dumped_freq_tab = 1;
625 postprocess_freq_tab (v);
627 /* Frequencies tables. */
628 n_categories = ft->n_valid + ft->n_missing;
629 if (cmd.table == FRQ_TABLE
630 || (cmd.table == FRQ_LIMIT && n_categories <= cmd.limit))
640 if (n_categories > cmd.onepage_limit)
653 dump_statistics (v, !dumped_freq_tab);
657 if ( chart == GFT_HIST)
659 double d[frq_n_stats];
660 struct normal_curve norm;
661 gsl_histogram *hist ;
664 norm.N = vf->tab.valid_cases;
667 norm.mean = d[frq_mean];
668 norm.stddev = d[frq_stddev];
670 hist = freq_tab_to_hist(ft,v);
672 histogram_plot(hist, var_to_string(v), &norm, normal);
674 gsl_histogram_free(hist);
678 if ( chart == GFT_PIE)
680 do_piechart(v_variables[i], ft);
685 cleanup_freq_tab (v);
692 /* Returns the comparison function that should be used for
693 sorting a frequency table by FRQ_SORT using VAR_TYPE
695 static hsh_compare_func *
696 get_freq_comparator (int frq_sort, enum var_type var_type)
698 bool is_numeric = var_type == VAR_NUMERIC;
702 return is_numeric ? compare_value_numeric_a : compare_value_alpha_a;
704 return is_numeric ? compare_value_numeric_d : compare_value_alpha_d;
706 return is_numeric ? compare_freq_numeric_a : compare_freq_alpha_a;
708 return is_numeric ? compare_freq_numeric_d : compare_freq_alpha_d;
714 /* Returns true iff the value in struct freq F is non-missing
717 not_missing (const void *f_, const void *v_)
719 const struct freq *f = f_;
720 const struct variable *v = v_;
722 return !var_is_value_missing (v, f->v);
725 /* Summarizes the frequency table data for variable V. */
727 postprocess_freq_tab (struct variable *v)
729 hsh_compare_func *compare;
733 struct freq *freqs, *f;
736 ft = &get_var_freqs (v)->tab;
737 assert (ft->mode == FRQM_GENERAL);
738 compare = get_freq_comparator (cmd.sort, var_get_type (v));
740 /* Extract data from hash table. */
741 count = hsh_count (ft->data);
742 data = hsh_data (ft->data);
744 /* Copy dereferenced data into freqs. */
745 freqs = xnmalloc (count, sizeof *freqs);
746 for (i = 0; i < count; i++)
748 struct freq *f = data[i];
752 /* Put data into ft. */
754 ft->n_valid = partition (freqs, count, sizeof *freqs, not_missing, v);
755 ft->missing = freqs + ft->n_valid;
756 ft->n_missing = count - ft->n_valid;
759 sort (ft->valid, ft->n_valid, sizeof *ft->valid, compare, v);
760 sort (ft->missing, ft->n_missing, sizeof *ft->missing, compare, v);
762 /* Summary statistics. */
763 ft->valid_cases = 0.0;
764 for(i = 0 ; i < ft->n_valid ; ++i )
767 ft->valid_cases += f->c;
771 ft->total_cases = ft->valid_cases ;
772 for(i = 0 ; i < ft->n_missing ; ++i )
775 ft->total_cases += f->c;
780 /* Frees the frequency table for variable V. */
782 cleanup_freq_tab (struct variable *v)
784 struct freq_tab *ft = &get_var_freqs (v)->tab;
785 assert (ft->mode == FRQM_GENERAL);
787 hsh_destroy (ft->data);
790 /* Parses the VARIABLES subcommand, adding to
791 {n_variables,v_variables}. */
793 frq_custom_variables (struct lexer *lexer, struct dataset *ds, struct cmd_frequencies *cmd UNUSED, void *aux UNUSED)
796 int min = 0, max = 0;
798 size_t old_n_variables = n_variables;
801 lex_match (lexer, '=');
802 if (lex_token (lexer) != T_ALL && (lex_token (lexer) != T_ID
803 || dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) == NULL))
806 if (!parse_variables (lexer, dataset_dict (ds), &v_variables, &n_variables,
807 PV_APPEND | PV_NO_SCRATCH))
810 if (!lex_match (lexer, '('))
815 if (!lex_force_int (lexer))
817 min = lex_integer (lexer);
819 if (!lex_force_match (lexer, ','))
821 if (!lex_force_int (lexer))
823 max = lex_integer (lexer);
825 if (!lex_force_match (lexer, ')'))
829 msg (SE, _("Upper limit of integer mode value range must be "
830 "greater than lower limit."));
835 for (i = old_n_variables; i < n_variables; i++)
837 struct variable *v = v_variables[i];
838 struct var_freqs *vf;
840 if (var_get_aux (v) != NULL)
842 msg (SE, _("Variable %s specified multiple times on VARIABLES "
843 "subcommand."), var_get_name (v));
846 if (mode == FRQM_INTEGER && !var_is_numeric (v))
848 msg (SE, _("Integer mode specified, but %s is not a numeric "
849 "variable."), var_get_name (v));
853 vf = var_attach_aux (v, xmalloc (sizeof *vf), var_dtor_free);
855 vf->tab.valid = vf->tab.missing = NULL;
856 if (mode == FRQM_INTEGER)
860 vf->tab.vector = pool_nalloc (int_pool,
861 max - min + 1, sizeof *vf->tab.vector);
864 vf->tab.vector = NULL;
867 vf->width = var_get_width (v);
868 vf->print = *var_get_print_format (v);
869 if (vf->width > MAX_SHORT_STRING && get_algorithm () == COMPATIBLE)
871 enum fmt_type type = var_get_print_format (v)->type;
872 vf->width = MAX_SHORT_STRING;
873 vf->print.w = MAX_SHORT_STRING * (type == FMT_AHEX ? 2 : 1);
879 /* Parses the GROUPED subcommand, setting the n_grouped, grouped
880 fields of specified variables. */
882 frq_custom_grouped (struct lexer *lexer, struct dataset *ds, struct cmd_frequencies *cmd UNUSED, void *aux UNUSED)
884 lex_match (lexer, '=');
885 if ((lex_token (lexer) == T_ID && dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) != NULL)
886 || lex_token (lexer) == T_ID)
891 /* Max, current size of list; list itself. */
899 if (!parse_variables (lexer, dataset_dict (ds), &v, &n,
900 PV_NO_DUPLICATE | PV_NUMERIC))
902 if (lex_match (lexer, '('))
906 while (lex_integer (lexer))
911 dl = pool_nrealloc (int_pool, dl, ml, sizeof *dl);
913 dl[nl++] = lex_tokval (lexer);
915 lex_match (lexer, ',');
917 /* Note that nl might still be 0 and dl might still be
918 NULL. That's okay. */
919 if (!lex_match (lexer, ')'))
922 msg (SE, _("`)' expected after GROUPED interval list."));
932 for (i = 0; i < n; i++)
933 if (var_get_aux (v[i]) == NULL)
934 msg (SE, _("Variables %s specified on GROUPED but not on "
935 "VARIABLES."), var_get_name (v[i]));
938 struct var_freqs *vf = get_var_freqs (v[i]);
940 if (vf->groups != NULL)
941 msg (SE, _("Variables %s specified multiple times on GROUPED "
942 "subcommand."), var_get_name (v[i]));
950 if (!lex_match (lexer, '/'))
952 if ((lex_token (lexer) != T_ID || dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) != NULL)
953 && lex_token (lexer) != T_ALL)
955 lex_put_back (lexer, '/');
963 /* Adds X to the list of percentiles, keeping the list in proper
966 add_percentile (double x)
970 for (i = 0; i < n_percentiles; i++)
972 /* Do nothing if it's already in the list */
973 if ( fabs(x - percentiles[i].p) < DBL_EPSILON )
976 if (x < percentiles[i].p)
980 if (i >= n_percentiles || x != percentiles[i].p)
982 percentiles = pool_nrealloc (int_pool, percentiles,
983 n_percentiles + 1, sizeof *percentiles);
985 if (i < n_percentiles)
986 memmove (&percentiles[i + 1], &percentiles[i],
987 (n_percentiles - i) * sizeof (struct percentile) );
989 percentiles[i].p = x;
994 /* Comparison functions. */
996 /* Hash of numeric values. */
998 hash_value_numeric (const void *value_, const void *aux UNUSED)
1000 const struct freq *value = value_;
1001 return hsh_hash_double (value->v[0].f);
1004 /* Hash of string values. */
1006 hash_value_alpha (const void *value_, const void *v_)
1008 const struct freq *value = value_;
1009 const struct variable *v = v_;
1010 struct var_freqs *vf = get_var_freqs (v);
1012 return hsh_hash_bytes (value->v[0].s, vf->width);
1015 /* Ascending numeric compare of values. */
1017 compare_value_numeric_a (const void *a_, const void *b_, const void *aux UNUSED)
1019 const struct freq *a = a_;
1020 const struct freq *b = b_;
1022 if (a->v[0].f > b->v[0].f)
1024 else if (a->v[0].f < b->v[0].f)
1030 /* Ascending string compare of values. */
1032 compare_value_alpha_a (const void *a_, const void *b_, const void *v_)
1034 const struct freq *a = a_;
1035 const struct freq *b = b_;
1036 const struct variable *v = v_;
1037 struct var_freqs *vf = get_var_freqs (v);
1039 return memcmp (a->v[0].s, b->v[0].s, vf->width);
1042 /* Descending numeric compare of values. */
1044 compare_value_numeric_d (const void *a, const void *b, const void *aux UNUSED)
1046 return -compare_value_numeric_a (a, b, aux);
1049 /* Descending string compare of values. */
1051 compare_value_alpha_d (const void *a, const void *b, const void *v)
1053 return -compare_value_alpha_a (a, b, v);
1056 /* Ascending numeric compare of frequency;
1057 secondary key on ascending numeric value. */
1059 compare_freq_numeric_a (const void *a_, const void *b_, const void *aux UNUSED)
1061 const struct freq *a = a_;
1062 const struct freq *b = b_;
1066 else if (a->c < b->c)
1069 if (a->v[0].f > b->v[0].f)
1071 else if (a->v[0].f < b->v[0].f)
1077 /* Ascending numeric compare of frequency;
1078 secondary key on ascending string value. */
1080 compare_freq_alpha_a (const void *a_, const void *b_, const void *v_)
1082 const struct freq *a = a_;
1083 const struct freq *b = b_;
1084 const struct variable *v = v_;
1085 struct var_freqs *vf = get_var_freqs (v);
1089 else if (a->c < b->c)
1092 return memcmp (a->v[0].s, b->v[0].s, vf->width);
1095 /* Descending numeric compare of frequency;
1096 secondary key on ascending numeric value. */
1098 compare_freq_numeric_d (const void *a_, const void *b_, const void *aux UNUSED)
1100 const struct freq *a = a_;
1101 const struct freq *b = b_;
1105 else if (a->c < b->c)
1108 if (a->v[0].f > b->v[0].f)
1110 else if (a->v[0].f < b->v[0].f)
1116 /* Descending numeric compare of frequency;
1117 secondary key on ascending string value. */
1119 compare_freq_alpha_d (const void *a_, const void *b_, const void *v_)
1121 const struct freq *a = a_;
1122 const struct freq *b = b_;
1123 const struct variable *v = v_;
1124 struct var_freqs *vf = get_var_freqs (v);
1128 else if (a->c < b->c)
1131 return memcmp (a->v[0].s, b->v[0].s, vf->width);
1134 /* Frequency table display. */
1136 /* Sets the widths of all the columns and heights of all the rows in
1137 table T for driver D. */
1139 full_dim (struct tab_table *t, struct outp_driver *d)
1141 int lab = cmd.labels == FRQ_LABELS;
1145 t->w[0] = MIN (tab_natural_width (t, d, 0), d->prop_em_width * 15);
1146 for (i = lab; i < lab + 5; i++)
1147 t->w[i] = MAX (tab_natural_width (t, d, i), d->prop_em_width * 8);
1148 for (i = 0; i < t->nr; i++)
1149 t->h[i] = d->font_height;
1152 /* Displays a full frequency table for variable V. */
1154 dump_full (struct variable *v)
1157 struct var_freqs *vf;
1158 struct freq_tab *ft;
1160 struct tab_table *t;
1162 double cum_total = 0.0;
1163 double cum_freq = 0.0;
1171 const struct init *p;
1173 static const struct init vec[] =
1175 {4, 0, N_("Valid")},
1177 {1, 1, N_("Value")},
1178 {2, 1, N_("Frequency")},
1179 {3, 1, N_("Percent")},
1180 {4, 1, N_("Percent")},
1181 {5, 1, N_("Percent")},
1189 int lab = cmd.labels == FRQ_LABELS;
1191 vf = get_var_freqs (v);
1193 n_categories = ft->n_valid + ft->n_missing;
1194 t = tab_create (5 + lab, n_categories + 3, 0);
1195 tab_headers (t, 0, 0, 2, 0);
1196 tab_dim (t, full_dim);
1199 tab_text (t, 0, 1, TAB_CENTER | TAT_TITLE, _("Value Label"));
1200 for (p = vec; p->s; p++)
1201 tab_text (t, p->c - (p->r ? !lab : 0), p->r,
1202 TAB_CENTER | TAT_TITLE, gettext (p->s));
1205 for (f = ft->valid; f < ft->missing; f++)
1207 double percent, valid_percent;
1211 percent = f->c / ft->total_cases * 100.0;
1212 valid_percent = f->c / ft->valid_cases * 100.0;
1213 cum_total += valid_percent;
1217 const char *label = var_lookup_value_label (v, &f->v[0]);
1219 tab_text (t, 0, r, TAB_LEFT, label);
1222 tab_value (t, 0 + lab, r, TAB_NONE, f->v, &vf->print);
1223 tab_float (t, 1 + lab, r, TAB_NONE, f->c, 8, 0);
1224 tab_float (t, 2 + lab, r, TAB_NONE, percent, 5, 1);
1225 tab_float (t, 3 + lab, r, TAB_NONE, valid_percent, 5, 1);
1226 tab_float (t, 4 + lab, r, TAB_NONE, cum_total, 5, 1);
1229 for (; f < &ft->valid[n_categories]; f++)
1235 const char *label = var_lookup_value_label (v, &f->v[0]);
1237 tab_text (t, 0, r, TAB_LEFT, label);
1240 tab_value (t, 0 + lab, r, TAB_NONE, f->v, &vf->print);
1241 tab_float (t, 1 + lab, r, TAB_NONE, f->c, 8, 0);
1242 tab_float (t, 2 + lab, r, TAB_NONE,
1243 f->c / ft->total_cases * 100.0, 5, 1);
1244 tab_text (t, 3 + lab, r, TAB_NONE, _("Missing"));
1248 tab_box (t, TAL_1, TAL_1,
1249 cmd.spaces == FRQ_SINGLE ? -1 : TAL_GAP, TAL_1,
1251 tab_hline (t, TAL_2, 0, 4 + lab, 2);
1252 tab_hline (t, TAL_2, 0, 4 + lab, r);
1253 tab_joint_text (t, 0, r, 0 + lab, r, TAB_RIGHT | TAT_TITLE, _("Total"));
1254 tab_vline (t, TAL_0, 1, r, r);
1255 tab_float (t, 1 + lab, r, TAB_NONE, cum_freq, 8, 0);
1256 tab_float (t, 2 + lab, r, TAB_NONE, 100.0, 5, 1);
1257 tab_float (t, 3 + lab, r, TAB_NONE, 100.0, 5, 1);
1259 tab_title (t, "%s", var_to_string (v));
1263 /* Sets the widths of all the columns and heights of all the rows in
1264 table T for driver D. */
1266 condensed_dim (struct tab_table *t, struct outp_driver *d)
1268 int cum_w = MAX (outp_string_width (d, _("Cum"), OUTP_PROPORTIONAL),
1269 MAX (outp_string_width (d, _("Cum"), OUTP_PROPORTIONAL),
1270 outp_string_width (d, "000", OUTP_PROPORTIONAL)));
1274 for (i = 0; i < 2; i++)
1275 t->w[i] = MAX (tab_natural_width (t, d, i), d->prop_em_width * 8);
1276 for (i = 2; i < 4; i++)
1278 for (i = 0; i < t->nr; i++)
1279 t->h[i] = d->font_height;
1282 /* Display condensed frequency table for variable V. */
1284 dump_condensed (struct variable *v)
1287 struct var_freqs *vf;
1288 struct freq_tab *ft;
1290 struct tab_table *t;
1292 double cum_total = 0.0;
1294 vf = get_var_freqs (v);
1296 n_categories = ft->n_valid + ft->n_missing;
1297 t = tab_create (4, n_categories + 2, 0);
1299 tab_headers (t, 0, 0, 2, 0);
1300 tab_text (t, 0, 1, TAB_CENTER | TAT_TITLE, _("Value"));
1301 tab_text (t, 1, 1, TAB_CENTER | TAT_TITLE, _("Freq"));
1302 tab_text (t, 2, 1, TAB_CENTER | TAT_TITLE, _("Pct"));
1303 tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("Cum"));
1304 tab_text (t, 3, 1, TAB_CENTER | TAT_TITLE, _("Pct"));
1305 tab_dim (t, condensed_dim);
1308 for (f = ft->valid; f < ft->missing; f++)
1312 percent = f->c / ft->total_cases * 100.0;
1313 cum_total += f->c / ft->valid_cases * 100.0;
1315 tab_value (t, 0, r, TAB_NONE, f->v, &vf->print);
1316 tab_float (t, 1, r, TAB_NONE, f->c, 8, 0);
1317 tab_float (t, 2, r, TAB_NONE, percent, 3, 0);
1318 tab_float (t, 3, r, TAB_NONE, cum_total, 3, 0);
1321 for (; f < &ft->valid[n_categories]; f++)
1323 tab_value (t, 0, r, TAB_NONE, f->v, &vf->print);
1324 tab_float (t, 1, r, TAB_NONE, f->c, 8, 0);
1325 tab_float (t, 2, r, TAB_NONE,
1326 f->c / ft->total_cases * 100.0, 3, 0);
1330 tab_box (t, TAL_1, TAL_1,
1331 cmd.spaces == FRQ_SINGLE ? -1 : TAL_GAP, TAL_1,
1333 tab_hline (t, TAL_2, 0, 3, 2);
1334 tab_title (t, "%s", var_to_string (v));
1335 tab_columns (t, SOM_COL_DOWN, 1);
1339 /* Statistical display. */
1341 /* Calculates all the pertinent statistics for variable V, putting
1342 them in array D[]. FIXME: This could be made much more optimal. */
1344 calc_stats (struct variable *v, double d[frq_n_stats])
1346 struct freq_tab *ft = &get_var_freqs (v)->tab;
1347 double W = ft->valid_cases;
1356 double *median_value;
1358 /* Calculate percentiles. */
1360 /* If the 50th percentile was not explicitly requested then we must
1361 calculate it anyway --- it's the median */
1363 for (i = 0; i < n_percentiles; i++)
1365 if (percentiles[i].p == 0.5)
1367 median_value = &percentiles[i].value;
1372 if ( 0 == median_value )
1374 add_percentile (0.5);
1378 for (i = 0; i < n_percentiles; i++)
1380 percentiles[i].flag = 0;
1381 percentiles[i].flag2 = 0;
1385 for (idx = 0; idx < ft->n_valid; ++idx)
1387 static double prev_value = SYSMIS;
1388 f = &ft->valid[idx];
1390 for (i = 0; i < n_percentiles; i++)
1393 if ( percentiles[i].flag2 ) continue ;
1395 if ( get_algorithm() != COMPATIBLE )
1397 (ft->valid_cases - 1) * percentiles[i].p;
1400 (ft->valid_cases + 1) * percentiles[i].p - 1;
1402 if ( percentiles[i].flag )
1404 percentiles[i].x2 = f->v[0].f;
1405 percentiles[i].x1 = prev_value;
1406 percentiles[i].flag2 = 1;
1412 if ( f->c > 1 && rank - (f->c - 1) > tp )
1414 percentiles[i].x2 = percentiles[i].x1 = f->v[0].f;
1415 percentiles[i].flag2 = 1;
1419 percentiles[i].flag=1;
1425 prev_value = f->v[0].f;
1428 for (i = 0; i < n_percentiles; i++)
1430 /* Catches the case when p == 100% */
1431 if ( ! percentiles[i].flag2 )
1432 percentiles[i].x1 = percentiles[i].x2 = f->v[0].f;
1435 printf("percentile %d (p==%.2f); X1 = %g; X2 = %g\n",
1436 i,percentiles[i].p,percentiles[i].x1,percentiles[i].x2);
1440 for (i = 0; i < n_percentiles; i++)
1442 struct freq_tab *ft = &get_var_freqs (v)->tab;
1446 if ( get_algorithm() != COMPATIBLE )
1448 s = modf((ft->valid_cases - 1) * percentiles[i].p , &dummy);
1452 s = modf((ft->valid_cases + 1) * percentiles[i].p -1, &dummy);
1455 percentiles[i].value = percentiles[i].x1 +
1456 ( percentiles[i].x2 - percentiles[i].x1) * s ;
1458 if ( percentiles[i].p == 0.50)
1459 median_value = &percentiles[i].value;
1463 /* Calculate the mode. */
1466 for (f = ft->valid; f < ft->missing; f++)
1468 if (most_often < f->c)
1473 else if (most_often == f->c)
1475 /* A duplicate mode is undefined.
1476 FIXME: keep track of *all* the modes. */
1481 /* Calculate moments. */
1482 m = moments_create (MOMENT_KURTOSIS);
1483 for (f = ft->valid; f < ft->missing; f++)
1484 moments_pass_one (m, f->v[0].f, f->c);
1485 for (f = ft->valid; f < ft->missing; f++)
1486 moments_pass_two (m, f->v[0].f, f->c);
1487 moments_calculate (m, NULL, &d[frq_mean], &d[frq_variance],
1488 &d[frq_skew], &d[frq_kurt]);
1489 moments_destroy (m);
1491 /* Formulas below are taken from _SPSS Statistical Algorithms_. */
1492 d[frq_min] = ft->valid[0].v[0].f;
1493 d[frq_max] = ft->valid[ft->n_valid - 1].v[0].f;
1494 d[frq_mode] = X_mode;
1495 d[frq_range] = d[frq_max] - d[frq_min];
1496 d[frq_median] = *median_value;
1497 d[frq_sum] = d[frq_mean] * W;
1498 d[frq_stddev] = sqrt (d[frq_variance]);
1499 d[frq_semean] = d[frq_stddev] / sqrt (W);
1500 d[frq_seskew] = calc_seskew (W);
1501 d[frq_sekurt] = calc_sekurt (W);
1504 /* Displays a table of all the statistics requested for variable V. */
1506 dump_statistics (struct variable *v, int show_varname)
1508 struct freq_tab *ft;
1509 double stat_value[frq_n_stats];
1510 struct tab_table *t;
1513 int n_explicit_percentiles = n_percentiles;
1515 if ( implicit_50th && n_percentiles > 0 )
1518 if (var_is_alpha (v))
1520 ft = &get_var_freqs (v)->tab;
1521 if (ft->n_valid == 0)
1523 msg (SW, _("No valid data for variable %s; statistics not displayed."),
1527 calc_stats (v, stat_value);
1529 t = tab_create (3, n_stats + n_explicit_percentiles + 2, 0);
1530 tab_dim (t, tab_natural_dimensions);
1532 tab_box (t, TAL_1, TAL_1, -1, -1 , 0 , 0 , 2, tab_nr(t) - 1) ;
1535 tab_vline (t, TAL_1 , 2, 0, tab_nr(t) - 1);
1536 tab_vline (t, TAL_GAP , 1, 0, tab_nr(t) - 1 ) ;
1538 r=2; /* N missing and N valid are always dumped */
1540 for (i = 0; i < frq_n_stats; i++)
1541 if (stats & BIT_INDEX (i))
1543 tab_text (t, 0, r, TAB_LEFT | TAT_TITLE,
1544 gettext (st_name[i].s10));
1545 tab_float (t, 2, r, TAB_NONE, stat_value[i], 11, 3);
1549 tab_text (t, 0, 0, TAB_LEFT | TAT_TITLE, _("N"));
1550 tab_text (t, 1, 0, TAB_LEFT | TAT_TITLE, _("Valid"));
1551 tab_text (t, 1, 1, TAB_LEFT | TAT_TITLE, _("Missing"));
1553 tab_float(t, 2, 0, TAB_NONE, ft->valid_cases, 11, 0);
1554 tab_float(t, 2, 1, TAB_NONE, ft->total_cases - ft->valid_cases, 11, 0);
1557 for (i = 0; i < n_explicit_percentiles; i++, r++)
1561 tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, _("Percentiles"));
1564 tab_float (t, 1, r, TAB_LEFT, percentiles[i].p * 100, 3, 0 );
1565 tab_float (t, 2, r, TAB_NONE, percentiles[i].value, 11, 3);
1569 tab_columns (t, SOM_COL_DOWN, 1);
1571 tab_title (t, "%s", var_to_string (v));
1573 tab_flags (t, SOMF_NO_TITLE);
1580 /* Create a gsl_histogram from a freq_tab */
1582 freq_tab_to_hist(const struct freq_tab *ft, const struct variable *var)
1585 double x_min = DBL_MAX;
1586 double x_max = -DBL_MAX;
1588 gsl_histogram *hist;
1589 const double bins = 11;
1591 struct hsh_iterator hi;
1592 struct hsh_table *fh = ft->data;
1595 /* Find out the extremes of the x value */
1596 for ( frq = hsh_first(fh, &hi); frq != 0; frq = hsh_next(fh, &hi) )
1598 if ( var_is_value_missing(var, frq->v))
1601 if ( frq->v[0].f < x_min ) x_min = frq->v[0].f ;
1602 if ( frq->v[0].f > x_max ) x_max = frq->v[0].f ;
1605 hist = histogram_create(bins, x_min, x_max);
1607 for( i = 0 ; i < ft->n_valid ; ++i )
1609 frq = &ft->valid[i];
1610 gsl_histogram_accumulate(hist, frq->v[0].f, frq->c);
1617 static struct slice *
1618 freq_tab_to_slice_array(const struct freq_tab *frq_tab,
1619 const struct variable *var,
1623 /* Allocate an array of slices and fill them from the data in frq_tab
1624 n_slices will contain the number of slices allocated.
1625 The caller is responsible for freeing slices
1627 static struct slice *
1628 freq_tab_to_slice_array(const struct freq_tab *frq_tab,
1629 const struct variable *var,
1633 struct slice *slices;
1635 *n_slices = frq_tab->n_valid;
1637 slices = xnmalloc (*n_slices, sizeof *slices);
1639 for (i = 0 ; i < *n_slices ; ++i )
1641 const struct freq *frq = &frq_tab->valid[i];
1643 slices[i].label = var_get_value_name (var, frq->v);
1645 slices[i].magnetude = frq->c;
1655 do_piechart(const struct variable *var, const struct freq_tab *frq_tab)
1657 struct slice *slices;
1660 slices = freq_tab_to_slice_array(frq_tab, var, &n_slices);
1662 piechart_plot(var_to_string(var), slices, n_slices);