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>
66 #define _(msgid) gettext (msgid)
67 #define N_(msgid) msgid
74 +format=cond:condense/onepage(*n:onepage_limit,"%s>=0")/!standard,
75 table:limit(n:limit,"%s>0")/notable/!table,
76 labels:!labels/nolabels,
77 sort:!avalue/dvalue/afreq/dfreq,
78 spaces:!single/double,
79 paging:newpage/!oldpage;
80 missing=miss:include/!exclude;
81 barchart(ba_)=:minimum(d:min),
83 scale:freq(*n:freq,"%s>0")/percent(*n:pcnt,"%s>0");
84 piechart(pie_)=:minimum(d:min),
86 missing:missing/!nomissing;
87 histogram(hi_)=:minimum(d:min),
89 scale:freq(*n:freq,"%s>0")/percent(*n:pcnt,"%s>0"),
90 norm:!nonormal/normal,
91 incr:increment(d:inc,"%s>0");
92 hbar(hb_)=:minimum(d:min),
94 scale:freq(*n:freq,"%s>0")/percent(*n:pcnt,"%s>0"),
95 norm:!nonormal/normal,
96 incr:increment(d:inc,"%s>0");
99 +percentiles = double list;
100 +statistics[st_]=1|mean,2|semean,3|median,4|mode,5|stddev,6|variance,
101 7|kurtosis,8|skewness,9|range,10|minimum,11|maximum,12|sum,
102 13|default,14|seskewness,15|sekurtosis,all,none.
110 frq_mean = 0, frq_semean, frq_median, frq_mode, frq_stddev, frq_variance,
111 frq_kurt, frq_sekurt, frq_skew, frq_seskew, frq_range, frq_min, frq_max,
115 /* Description of a statistic. */
118 int st_indx; /* Index into a_statistics[]. */
119 const char *s10; /* Identifying string. */
122 /* Table of statistics, indexed by dsc_*. */
123 static const struct frq_info st_name[frq_n_stats + 1] =
125 {FRQ_ST_MEAN, N_("Mean")},
126 {FRQ_ST_SEMEAN, N_("S.E. Mean")},
127 {FRQ_ST_MEDIAN, N_("Median")},
128 {FRQ_ST_MODE, N_("Mode")},
129 {FRQ_ST_STDDEV, N_("Std Dev")},
130 {FRQ_ST_VARIANCE, N_("Variance")},
131 {FRQ_ST_KURTOSIS, N_("Kurtosis")},
132 {FRQ_ST_SEKURTOSIS, N_("S.E. Kurt")},
133 {FRQ_ST_SKEWNESS, N_("Skewness")},
134 {FRQ_ST_SESKEWNESS, N_("S.E. Skew")},
135 {FRQ_ST_RANGE, N_("Range")},
136 {FRQ_ST_MINIMUM, N_("Minimum")},
137 {FRQ_ST_MAXIMUM, N_("Maximum")},
138 {FRQ_ST_SUM, N_("Sum")},
142 /* Percentiles to calculate. */
146 double p; /* the %ile to be calculated */
147 double value; /* the %ile's value */
148 double x1; /* The datum value <= the percentile */
149 double x2; /* The datum value >= the percentile */
151 int flag2; /* Set to 1 if this percentile value has been found */
155 static void add_percentile (double x) ;
157 static struct percentile *percentiles;
158 static int n_percentiles;
160 static int implicit_50th ;
162 /* Groups of statistics. */
164 #define frq_default \
165 (BI (frq_mean) | BI (frq_stddev) | BI (frq_min) | BI (frq_max))
167 (BI (frq_sum) | BI(frq_min) | BI(frq_max) \
168 | BI(frq_mean) | BI(frq_semean) | BI(frq_stddev) \
169 | BI(frq_variance) | BI(frq_kurt) | BI(frq_sekurt) \
170 | BI(frq_skew) | BI(frq_seskew) | BI(frq_range) \
171 | BI(frq_range) | BI(frq_mode) | BI(frq_median))
173 /* Statistics; number of statistics. */
174 static unsigned long stats;
177 /* Types of graphs. */
180 GFT_NONE, /* Don't draw graphs. */
181 GFT_BAR, /* Draw bar charts. */
182 GFT_HIST, /* Draw histograms. */
183 GFT_PIE, /* Draw piechart */
184 GFT_HBAR /* Draw bar charts or histograms at our discretion. */
187 /* Parsed command. */
188 static struct cmd_frequencies cmd;
190 /* Summary of the barchart, histogram, and hbar subcommands. */
191 /* FIXME: These should not be mututally exclusive */
192 static int chart; /* NONE/BAR/HIST/HBAR/PIE. */
193 static double min, max; /* Minimum, maximum on y axis. */
194 static int format; /* FREQ/PERCENT: Scaling of y axis. */
195 static double scale, incr; /* FIXME */
196 static int normal; /* FIXME */
198 /* Variables for which to calculate statistics. */
199 static size_t n_variables;
200 static const struct variable **v_variables;
202 /* Arenas used to store semi-permanent storage. */
203 static struct pool *int_pool; /* Integer mode. */
204 static struct pool *gen_pool; /* General mode. */
206 /* Frequency tables. */
208 /* Types of frequency tables. */
215 /* Entire frequency table. */
218 int mode; /* FRQM_GENERAL or FRQM_INTEGER. */
221 struct hsh_table *data; /* Undifferentiated data. */
224 double *vector; /* Frequencies proper. */
225 int min, max; /* The boundaries of the table. */
226 double out_of_range; /* Sum of weights of out-of-range values. */
227 double sysmis; /* Sum of weights of SYSMIS values. */
230 struct freq *valid; /* Valid freqs. */
231 int n_valid; /* Number of total freqs. */
233 struct freq *missing; /* Missing freqs. */
234 int n_missing; /* Number of missing freqs. */
237 double total_cases; /* Sum of weights of all cases. */
238 double valid_cases; /* Sum of weights of valid cases. */
242 /* Per-variable frequency data. */
245 /* Freqency table. */
246 struct freq_tab tab; /* Frequencies table to use. */
249 int n_groups; /* Number of groups. */
250 double *groups; /* Groups. */
253 double stat[frq_n_stats];
255 /* Width and format for analysis and display.
256 This is normally the same as "width" and "print" in struct
257 variable, but in SPSS-compatible mode only the first
258 MAX_SHORT_STRING bytes of long string variables are
261 struct fmt_spec print;
264 static inline struct var_freqs *
265 get_var_freqs (const struct variable *v)
267 return var_get_aux (v);
270 static void determine_charts (void);
272 static void calc_stats (const struct variable *v, double d[frq_n_stats]);
274 static void precalc (const struct ccase *, void *, const struct dataset *);
275 static bool calc (const struct ccase *, void *, const struct dataset *);
276 static bool postcalc (void *, const struct dataset *);
278 static void postprocess_freq_tab (const struct variable *);
279 static void dump_full (const struct variable *);
280 static void dump_condensed (const struct variable *);
281 static void dump_statistics (const struct variable *, int show_varname);
282 static void cleanup_freq_tab (const struct variable *);
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 (struct lexer *lexer, struct dataset *ds);
303 cmd_frequencies (struct lexer *lexer, struct dataset *ds)
307 int_pool = pool_create ();
308 result = internal_cmd_frequencies (lexer, ds);
309 pool_destroy (int_pool);
311 pool_destroy (gen_pool);
319 internal_cmd_frequencies (struct lexer *lexer, struct dataset *ds)
330 if (!parse_frequencies (lexer, ds, &cmd, NULL))
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 (ds, 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, const struct dataset *ds)
504 bool bad_warn = true;
506 weight = dict_get_case_weight (dataset_dict (ds), c, &bad_warn);
508 for (i = 0; i < n_variables; i++)
510 const struct variable *v = v_variables[i];
511 const union value *val = case_data (c, v);
512 struct var_freqs *vf = get_var_freqs (v);
513 struct freq_tab *ft = &vf->tab;
523 target.value = (union value *) val;
524 fpp = (struct freq **) hsh_probe (ft->data, &target);
527 (*fpp)->count += weight;
530 struct freq *fp = pool_alloc (gen_pool, sizeof *fp);
532 fp->value = pool_clone (gen_pool,
533 val, MAX (MAX_SHORT_STRING, vf->width));
540 if (val->f == SYSMIS)
541 ft->sysmis += weight;
542 else if (val->f > INT_MIN+1 && val->f < INT_MAX-1)
545 if (i >= ft->min && i <= ft->max)
546 ft->vector[i - ft->min] += weight;
549 ft->out_of_range += weight;
558 /* Prepares each variable that is the target of FREQUENCIES by setting
559 up its hash table. */
561 precalc (const struct ccase *first, void *aux UNUSED, const struct dataset *ds)
565 output_split_file_values (ds, first);
567 pool_destroy (gen_pool);
568 gen_pool = pool_create ();
570 for (i = 0; i < n_variables; i++)
572 const struct variable *v = v_variables[i];
573 struct freq_tab *ft = &get_var_freqs (v)->tab;
575 if (ft->mode == FRQM_GENERAL)
577 ft->data = hsh_create (16, compare_freq, hash_freq, NULL, v);
583 for (j = (ft->max - ft->min); j >= 0; j--)
585 ft->out_of_range = 0.0;
591 /* Finishes up with the variables after frequencies have been
592 calculated. Displays statistics, percentiles, ... */
594 postcalc (void *aux UNUSED, const struct dataset *ds UNUSED)
598 for (i = 0; i < n_variables; i++)
600 const struct variable *v = v_variables[i];
601 struct var_freqs *vf = get_var_freqs (v);
602 struct freq_tab *ft = &vf->tab;
604 int dumped_freq_tab = 1;
606 postprocess_freq_tab (v);
608 /* Frequencies tables. */
609 n_categories = ft->n_valid + ft->n_missing;
610 if (cmd.table == FRQ_TABLE
611 || (cmd.table == FRQ_LIMIT && n_categories <= cmd.limit))
621 if (n_categories > cmd.onepage_limit)
634 dump_statistics (v, !dumped_freq_tab);
638 if ( chart == GFT_HIST)
640 double d[frq_n_stats];
641 struct normal_curve norm;
642 gsl_histogram *hist ;
645 norm.N = vf->tab.valid_cases;
648 norm.mean = d[frq_mean];
649 norm.stddev = d[frq_stddev];
651 hist = freq_tab_to_hist(ft,v);
653 histogram_plot(hist, var_to_string(v), &norm, normal);
655 gsl_histogram_free(hist);
659 if ( chart == GFT_PIE)
661 do_piechart(v_variables[i], ft);
666 cleanup_freq_tab (v);
673 /* Returns the comparison function that should be used for
674 sorting a frequency table by FRQ_SORT using VAR_TYPE
676 static hsh_compare_func *
677 get_freq_comparator (int frq_sort, enum var_type var_type)
679 bool is_numeric = var_type == VAR_NUMERIC;
683 return is_numeric ? compare_value_numeric_a : compare_value_alpha_a;
685 return is_numeric ? compare_value_numeric_d : compare_value_alpha_d;
687 return is_numeric ? compare_freq_numeric_a : compare_freq_alpha_a;
689 return is_numeric ? compare_freq_numeric_d : compare_freq_alpha_d;
695 /* Returns true iff the value in struct freq F is non-missing
698 not_missing (const void *f_, const void *v_)
700 const struct freq *f = f_;
701 const struct variable *v = v_;
703 return !var_is_value_missing (v, f->value, MV_ANY);
706 /* Summarizes the frequency table data for variable V. */
708 postprocess_freq_tab (const struct variable *v)
710 hsh_compare_func *compare;
714 struct freq *freqs, *f;
717 ft = &get_var_freqs (v)->tab;
718 assert (ft->mode == FRQM_GENERAL);
719 compare = get_freq_comparator (cmd.sort, var_get_type (v));
721 /* Extract data from hash table. */
722 count = hsh_count (ft->data);
723 data = hsh_data (ft->data);
725 /* Copy dereferenced data into freqs. */
726 freqs = xnmalloc (count, sizeof *freqs);
727 for (i = 0; i < count; i++)
729 struct freq *f = data[i];
733 /* Put data into ft. */
735 ft->n_valid = partition (freqs, count, sizeof *freqs, not_missing, v);
736 ft->missing = freqs + ft->n_valid;
737 ft->n_missing = count - ft->n_valid;
740 sort (ft->valid, ft->n_valid, sizeof *ft->valid, compare, v);
741 sort (ft->missing, ft->n_missing, sizeof *ft->missing, compare, v);
743 /* Summary statistics. */
744 ft->valid_cases = 0.0;
745 for(i = 0 ; i < ft->n_valid ; ++i )
748 ft->valid_cases += f->count;
752 ft->total_cases = ft->valid_cases ;
753 for(i = 0 ; i < ft->n_missing ; ++i )
756 ft->total_cases += f->count;
761 /* Frees the frequency table for variable V. */
763 cleanup_freq_tab (const struct variable *v)
765 struct freq_tab *ft = &get_var_freqs (v)->tab;
766 assert (ft->mode == FRQM_GENERAL);
768 hsh_destroy (ft->data);
771 /* Parses the VARIABLES subcommand, adding to
772 {n_variables,v_variables}. */
774 frq_custom_variables (struct lexer *lexer, struct dataset *ds, struct cmd_frequencies *cmd UNUSED, void *aux UNUSED)
777 int min = 0, max = 0;
779 size_t old_n_variables = n_variables;
782 lex_match (lexer, '=');
783 if (lex_token (lexer) != T_ALL && (lex_token (lexer) != T_ID
784 || dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) == NULL))
787 if (!parse_variables_const (lexer, dataset_dict (ds), &v_variables, &n_variables,
788 PV_APPEND | PV_NO_SCRATCH))
791 if (!lex_match (lexer, '('))
796 if (!lex_force_int (lexer))
798 min = lex_integer (lexer);
800 if (!lex_force_match (lexer, ','))
802 if (!lex_force_int (lexer))
804 max = lex_integer (lexer);
806 if (!lex_force_match (lexer, ')'))
810 msg (SE, _("Upper limit of integer mode value range must be "
811 "greater than lower limit."));
816 for (i = old_n_variables; i < n_variables; i++)
818 const struct variable *v = v_variables[i];
819 struct var_freqs *vf;
821 if (var_get_aux (v) != NULL)
823 msg (SE, _("Variable %s specified multiple times on VARIABLES "
824 "subcommand."), var_get_name (v));
827 if (mode == FRQM_INTEGER && !var_is_numeric (v))
829 msg (SE, _("Integer mode specified, but %s is not a numeric "
830 "variable."), var_get_name (v));
834 vf = var_attach_aux (v, xmalloc (sizeof *vf), var_dtor_free);
836 vf->tab.valid = vf->tab.missing = NULL;
837 if (mode == FRQM_INTEGER)
841 vf->tab.vector = pool_nalloc (int_pool,
842 max - min + 1, sizeof *vf->tab.vector);
845 vf->tab.vector = NULL;
848 vf->width = var_get_width (v);
849 vf->print = *var_get_print_format (v);
850 if (vf->width > MAX_SHORT_STRING && get_algorithm () == COMPATIBLE)
852 enum fmt_type type = var_get_print_format (v)->type;
853 vf->width = MAX_SHORT_STRING;
854 vf->print.w = MAX_SHORT_STRING * (type == FMT_AHEX ? 2 : 1);
860 /* Parses the GROUPED subcommand, setting the n_grouped, grouped
861 fields of specified variables. */
863 frq_custom_grouped (struct lexer *lexer, struct dataset *ds, struct cmd_frequencies *cmd UNUSED, void *aux UNUSED)
865 lex_match (lexer, '=');
866 if ((lex_token (lexer) == T_ID && dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) != NULL)
867 || lex_token (lexer) == T_ID)
872 /* Max, current size of list; list itself. */
878 const struct variable **v;
880 if (!parse_variables_const (lexer, dataset_dict (ds), &v, &n,
881 PV_NO_DUPLICATE | PV_NUMERIC))
883 if (lex_match (lexer, '('))
887 while (lex_integer (lexer))
892 dl = pool_nrealloc (int_pool, dl, ml, sizeof *dl);
894 dl[nl++] = lex_tokval (lexer);
896 lex_match (lexer, ',');
898 /* Note that nl might still be 0 and dl might still be
899 NULL. That's okay. */
900 if (!lex_match (lexer, ')'))
903 msg (SE, _("`)' expected after GROUPED interval list."));
913 for (i = 0; i < n; i++)
914 if (var_get_aux (v[i]) == NULL)
915 msg (SE, _("Variables %s specified on GROUPED but not on "
916 "VARIABLES."), var_get_name (v[i]));
919 struct var_freqs *vf = get_var_freqs (v[i]);
921 if (vf->groups != NULL)
922 msg (SE, _("Variables %s specified multiple times on GROUPED "
923 "subcommand."), var_get_name (v[i]));
931 if (!lex_match (lexer, '/'))
933 if ((lex_token (lexer) != T_ID || dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) != NULL)
934 && lex_token (lexer) != T_ALL)
936 lex_put_back (lexer, '/');
944 /* Adds X to the list of percentiles, keeping the list in proper
947 add_percentile (double x)
951 for (i = 0; i < n_percentiles; i++)
953 /* Do nothing if it's already in the list */
954 if ( fabs(x - percentiles[i].p) < DBL_EPSILON )
957 if (x < percentiles[i].p)
961 if (i >= n_percentiles || x != percentiles[i].p)
963 percentiles = pool_nrealloc (int_pool, percentiles,
964 n_percentiles + 1, sizeof *percentiles);
966 if (i < n_percentiles)
967 memmove (&percentiles[i + 1], &percentiles[i],
968 (n_percentiles - i) * sizeof (struct percentile) );
970 percentiles[i].p = x;
975 /* Comparison functions. */
977 /* Ascending numeric compare of values. */
979 compare_value_numeric_a (const void *a_, const void *b_, const void *aux UNUSED)
981 const struct freq *a = a_;
982 const struct freq *b = b_;
984 if (a->value[0].f > b->value[0].f)
986 else if (a->value[0].f < b->value[0].f)
992 /* Ascending string compare of values. */
994 compare_value_alpha_a (const void *a_, const void *b_, const void *v_)
996 const struct freq *a = a_;
997 const struct freq *b = b_;
998 const struct variable *v = v_;
999 struct var_freqs *vf = get_var_freqs (v);
1001 return memcmp (a->value[0].s, b->value[0].s, vf->width);
1004 /* Descending numeric compare of values. */
1006 compare_value_numeric_d (const void *a, const void *b, const void *aux UNUSED)
1008 return -compare_value_numeric_a (a, b, aux);
1011 /* Descending string compare of values. */
1013 compare_value_alpha_d (const void *a, const void *b, const void *v)
1015 return -compare_value_alpha_a (a, b, v);
1018 /* Ascending numeric compare of frequency;
1019 secondary key on ascending numeric value. */
1021 compare_freq_numeric_a (const void *a_, const void *b_, const void *aux UNUSED)
1023 const struct freq *a = a_;
1024 const struct freq *b = b_;
1026 if (a->count > b->count)
1028 else if (a->count < b->count)
1031 if (a->value[0].f > b->value[0].f)
1033 else if (a->value[0].f < b->value[0].f)
1039 /* Ascending numeric compare of frequency;
1040 secondary key on ascending string value. */
1042 compare_freq_alpha_a (const void *a_, const void *b_, const void *v_)
1044 const struct freq *a = a_;
1045 const struct freq *b = b_;
1046 const struct variable *v = v_;
1047 struct var_freqs *vf = get_var_freqs (v);
1049 if (a->count > b->count)
1051 else if (a->count < b->count)
1054 return memcmp (a->value[0].s, b->value[0].s, vf->width);
1057 /* Descending numeric compare of frequency;
1058 secondary key on ascending numeric value. */
1060 compare_freq_numeric_d (const void *a_, const void *b_, const void *aux UNUSED)
1062 const struct freq *a = a_;
1063 const struct freq *b = b_;
1065 if (a->count > b->count)
1067 else if (a->count < b->count)
1070 if (a->value[0].f > b->value[0].f)
1072 else if (a->value[0].f < b->value[0].f)
1078 /* Descending numeric compare of frequency;
1079 secondary key on ascending string value. */
1081 compare_freq_alpha_d (const void *a_, const void *b_, const void *v_)
1083 const struct freq *a = a_;
1084 const struct freq *b = b_;
1085 const struct variable *v = v_;
1086 struct var_freqs *vf = get_var_freqs (v);
1088 if (a->count > b->count)
1090 else if (a->count < b->count)
1093 return memcmp (a->value[0].s, b->value[0].s, vf->width);
1096 /* Frequency table display. */
1098 /* Sets the widths of all the columns and heights of all the rows in
1099 table T for driver D. */
1101 full_dim (struct tab_table *t, struct outp_driver *d)
1106 if (cmd.labels == FRQ_LABELS)
1108 t->w[0] = MIN (tab_natural_width (t, d, 0), d->prop_em_width * 15);
1113 for (;i < columns; i++)
1114 t->w[i] = MAX (tab_natural_width (t, d, i), d->prop_em_width * 8);
1116 for (i = 0; i < t->nr; i++)
1117 t->h[i] = d->font_height;
1120 /* Displays a full frequency table for variable V. */
1122 dump_full (const struct variable *v)
1125 struct var_freqs *vf;
1126 struct freq_tab *ft;
1128 struct tab_table *t;
1130 double cum_total = 0.0;
1131 double cum_freq = 0.0;
1139 const struct init *p;
1141 static const struct init vec[] =
1143 {4, 0, N_("Valid")},
1145 {1, 1, N_("Value")},
1146 {2, 1, N_("Frequency")},
1147 {3, 1, N_("Percent")},
1148 {4, 1, N_("Percent")},
1149 {5, 1, N_("Percent")},
1157 const bool lab = (cmd.labels == FRQ_LABELS);
1159 vf = get_var_freqs (v);
1161 n_categories = ft->n_valid + ft->n_missing;
1162 t = tab_create (5 + lab, n_categories + 3, 0);
1163 tab_headers (t, 0, 0, 2, 0);
1164 tab_dim (t, full_dim);
1167 tab_text (t, 0, 1, TAB_CENTER | TAT_TITLE, _("Value Label"));
1169 for (p = vec; p->s; p++)
1170 tab_text (t, lab ? p->c : p->c - 1, p->r,
1171 TAB_CENTER | TAT_TITLE, gettext (p->s));
1174 for (f = ft->valid; f < ft->missing; f++)
1176 double percent, valid_percent;
1178 cum_freq += f->count;
1180 percent = f->count / ft->total_cases * 100.0;
1181 valid_percent = f->count / ft->valid_cases * 100.0;
1182 cum_total += valid_percent;
1186 const char *label = var_lookup_value_label (v, &f->value[0]);
1188 tab_text (t, 0, r, TAB_LEFT, label);
1191 tab_value (t, 0 + lab, r, TAB_NONE, f->value, &vf->print);
1192 tab_float (t, 1 + lab, r, TAB_NONE, f->count, 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++)
1200 cum_freq += f->count;
1204 const char *label = var_lookup_value_label (v, &f->value[0]);
1206 tab_text (t, 0, r, TAB_LEFT, label);
1209 tab_value (t, 0 + lab, r, TAB_NONE, f->value, &vf->print);
1210 tab_float (t, 1 + lab, r, TAB_NONE, f->count, 8, 0);
1211 tab_float (t, 2 + lab, r, TAB_NONE,
1212 f->count / 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", var_to_string (v));
1232 /* Sets the widths of all the columns and heights of all the rows in
1233 table T for driver D. */
1235 condensed_dim (struct tab_table *t, struct outp_driver *d)
1237 int cum_w = MAX (outp_string_width (d, _("Cum"), OUTP_PROPORTIONAL),
1238 MAX (outp_string_width (d, _("Cum"), OUTP_PROPORTIONAL),
1239 outp_string_width (d, "000", OUTP_PROPORTIONAL)));
1243 for (i = 0; i < 2; i++)
1244 t->w[i] = MAX (tab_natural_width (t, d, i), d->prop_em_width * 8);
1245 for (i = 2; i < 4; i++)
1247 for (i = 0; i < t->nr; i++)
1248 t->h[i] = d->font_height;
1251 /* Display condensed frequency table for variable V. */
1253 dump_condensed (const struct variable *v)
1256 struct var_freqs *vf;
1257 struct freq_tab *ft;
1259 struct tab_table *t;
1261 double cum_total = 0.0;
1263 vf = get_var_freqs (v);
1265 n_categories = ft->n_valid + ft->n_missing;
1266 t = tab_create (4, n_categories + 2, 0);
1268 tab_headers (t, 0, 0, 2, 0);
1269 tab_text (t, 0, 1, TAB_CENTER | TAT_TITLE, _("Value"));
1270 tab_text (t, 1, 1, TAB_CENTER | TAT_TITLE, _("Freq"));
1271 tab_text (t, 2, 1, TAB_CENTER | TAT_TITLE, _("Pct"));
1272 tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("Cum"));
1273 tab_text (t, 3, 1, TAB_CENTER | TAT_TITLE, _("Pct"));
1274 tab_dim (t, condensed_dim);
1277 for (f = ft->valid; f < ft->missing; f++)
1281 percent = f->count / ft->total_cases * 100.0;
1282 cum_total += f->count / ft->valid_cases * 100.0;
1284 tab_value (t, 0, r, TAB_NONE, f->value, &vf->print);
1285 tab_float (t, 1, r, TAB_NONE, f->count, 8, 0);
1286 tab_float (t, 2, r, TAB_NONE, percent, 3, 0);
1287 tab_float (t, 3, r, TAB_NONE, cum_total, 3, 0);
1290 for (; f < &ft->valid[n_categories]; f++)
1292 tab_value (t, 0, r, TAB_NONE, f->value, &vf->print);
1293 tab_float (t, 1, r, TAB_NONE, f->count, 8, 0);
1294 tab_float (t, 2, r, TAB_NONE,
1295 f->count / ft->total_cases * 100.0, 3, 0);
1299 tab_box (t, TAL_1, TAL_1,
1300 cmd.spaces == FRQ_SINGLE ? -1 : TAL_GAP, TAL_1,
1302 tab_hline (t, TAL_2, 0, 3, 2);
1303 tab_title (t, "%s", var_to_string (v));
1304 tab_columns (t, SOM_COL_DOWN, 1);
1308 /* Statistical display. */
1310 /* Calculates all the pertinent statistics for variable V, putting
1311 them in array D[]. FIXME: This could be made much more optimal. */
1313 calc_stats (const struct variable *v, double d[frq_n_stats])
1315 struct freq_tab *ft = &get_var_freqs (v)->tab;
1316 double W = ft->valid_cases;
1325 double *median_value;
1327 /* Calculate percentiles. */
1329 /* If the 50th percentile was not explicitly requested then we must
1330 calculate it anyway --- it's the median */
1332 for (i = 0; i < n_percentiles; i++)
1334 if (percentiles[i].p == 0.5)
1336 median_value = &percentiles[i].value;
1341 if ( 0 == median_value )
1343 add_percentile (0.5);
1347 for (i = 0; i < n_percentiles; i++)
1349 percentiles[i].flag = 0;
1350 percentiles[i].flag2 = 0;
1354 for (idx = 0; idx < ft->n_valid; ++idx)
1356 static double prev_value = SYSMIS;
1357 f = &ft->valid[idx];
1359 for (i = 0; i < n_percentiles; i++)
1362 if ( percentiles[i].flag2 ) continue ;
1364 if ( get_algorithm() != COMPATIBLE )
1366 (ft->valid_cases - 1) * percentiles[i].p;
1369 (ft->valid_cases + 1) * percentiles[i].p - 1;
1371 if ( percentiles[i].flag )
1373 percentiles[i].x2 = f->value[0].f;
1374 percentiles[i].x1 = prev_value;
1375 percentiles[i].flag2 = 1;
1381 if ( f->count > 1 && rank - (f->count - 1) > tp )
1383 percentiles[i].x2 = percentiles[i].x1 = f->value[0].f;
1384 percentiles[i].flag2 = 1;
1388 percentiles[i].flag=1;
1394 prev_value = f->value[0].f;
1397 for (i = 0; i < n_percentiles; i++)
1399 /* Catches the case when p == 100% */
1400 if ( ! percentiles[i].flag2 )
1401 percentiles[i].x1 = percentiles[i].x2 = f->value[0].f;
1404 printf("percentile %d (p==%.2f); X1 = %g; X2 = %g\n",
1405 i,percentiles[i].p,percentiles[i].x1,percentiles[i].x2);
1409 for (i = 0; i < n_percentiles; i++)
1411 struct freq_tab *ft = &get_var_freqs (v)->tab;
1415 if ( get_algorithm() != COMPATIBLE )
1417 s = modf((ft->valid_cases - 1) * percentiles[i].p , &dummy);
1421 s = modf((ft->valid_cases + 1) * percentiles[i].p -1, &dummy);
1424 percentiles[i].value = percentiles[i].x1 +
1425 ( percentiles[i].x2 - percentiles[i].x1) * s ;
1427 if ( percentiles[i].p == 0.50)
1428 median_value = &percentiles[i].value;
1432 /* Calculate the mode. */
1435 for (f = ft->valid; f < ft->missing; f++)
1437 if (most_often < f->count)
1439 most_often = f->count;
1440 X_mode = f->value[0].f;
1442 else if (most_often == f->count)
1444 /* A duplicate mode is undefined.
1445 FIXME: keep track of *all* the modes. */
1450 /* Calculate moments. */
1451 m = moments_create (MOMENT_KURTOSIS);
1452 for (f = ft->valid; f < ft->missing; f++)
1453 moments_pass_one (m, f->value[0].f, f->count);
1454 for (f = ft->valid; f < ft->missing; f++)
1455 moments_pass_two (m, f->value[0].f, f->count);
1456 moments_calculate (m, NULL, &d[frq_mean], &d[frq_variance],
1457 &d[frq_skew], &d[frq_kurt]);
1458 moments_destroy (m);
1460 /* Formulas below are taken from _SPSS Statistical Algorithms_. */
1461 d[frq_min] = ft->valid[0].value[0].f;
1462 d[frq_max] = ft->valid[ft->n_valid - 1].value[0].f;
1463 d[frq_mode] = X_mode;
1464 d[frq_range] = d[frq_max] - d[frq_min];
1465 d[frq_median] = *median_value;
1466 d[frq_sum] = d[frq_mean] * W;
1467 d[frq_stddev] = sqrt (d[frq_variance]);
1468 d[frq_semean] = d[frq_stddev] / sqrt (W);
1469 d[frq_seskew] = calc_seskew (W);
1470 d[frq_sekurt] = calc_sekurt (W);
1473 /* Displays a table of all the statistics requested for variable V. */
1475 dump_statistics (const struct variable *v, int show_varname)
1477 struct freq_tab *ft;
1478 double stat_value[frq_n_stats];
1479 struct tab_table *t;
1482 int n_explicit_percentiles = n_percentiles;
1484 if ( implicit_50th && n_percentiles > 0 )
1487 if (var_is_alpha (v))
1489 ft = &get_var_freqs (v)->tab;
1490 if (ft->n_valid == 0)
1492 msg (SW, _("No valid data for variable %s; statistics not displayed."),
1496 calc_stats (v, stat_value);
1498 t = tab_create (3, n_stats + n_explicit_percentiles + 2, 0);
1499 tab_dim (t, tab_natural_dimensions);
1501 tab_box (t, TAL_1, TAL_1, -1, -1 , 0 , 0 , 2, tab_nr(t) - 1) ;
1504 tab_vline (t, TAL_1 , 2, 0, tab_nr(t) - 1);
1505 tab_vline (t, TAL_GAP , 1, 0, tab_nr(t) - 1 ) ;
1507 r=2; /* N missing and N valid are always dumped */
1509 for (i = 0; i < frq_n_stats; i++)
1510 if (stats & BIT_INDEX (i))
1512 tab_text (t, 0, r, TAB_LEFT | TAT_TITLE,
1513 gettext (st_name[i].s10));
1514 tab_float (t, 2, r, TAB_NONE, stat_value[i], 11, 3);
1518 tab_text (t, 0, 0, TAB_LEFT | TAT_TITLE, _("N"));
1519 tab_text (t, 1, 0, TAB_LEFT | TAT_TITLE, _("Valid"));
1520 tab_text (t, 1, 1, TAB_LEFT | TAT_TITLE, _("Missing"));
1522 tab_float(t, 2, 0, TAB_NONE, ft->valid_cases, 11, 0);
1523 tab_float(t, 2, 1, TAB_NONE, ft->total_cases - ft->valid_cases, 11, 0);
1526 for (i = 0; i < n_explicit_percentiles; i++, r++)
1530 tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, _("Percentiles"));
1533 tab_float (t, 1, r, TAB_LEFT, percentiles[i].p * 100, 3, 0 );
1534 tab_float (t, 2, r, TAB_NONE, percentiles[i].value, 11, 3);
1538 tab_columns (t, SOM_COL_DOWN, 1);
1540 tab_title (t, "%s", var_to_string (v));
1542 tab_flags (t, SOMF_NO_TITLE);
1549 /* Create a gsl_histogram from a freq_tab */
1551 freq_tab_to_hist(const struct freq_tab *ft, const struct variable *var)
1554 double x_min = DBL_MAX;
1555 double x_max = -DBL_MAX;
1557 gsl_histogram *hist;
1558 const double bins = 11;
1560 struct hsh_iterator hi;
1561 struct hsh_table *fh = ft->data;
1564 /* Find out the extremes of the x value */
1565 for ( frq = hsh_first(fh, &hi); frq != 0; frq = hsh_next(fh, &hi) )
1567 if (var_is_value_missing(var, frq->value, MV_ANY))
1570 if ( frq->value[0].f < x_min ) x_min = frq->value[0].f ;
1571 if ( frq->value[0].f > x_max ) x_max = frq->value[0].f ;
1574 hist = histogram_create(bins, x_min, x_max);
1576 for( i = 0 ; i < ft->n_valid ; ++i )
1578 frq = &ft->valid[i];
1579 gsl_histogram_accumulate(hist, frq->value[0].f, frq->count);
1586 static struct slice *
1587 freq_tab_to_slice_array(const struct freq_tab *frq_tab,
1588 const struct variable *var,
1592 /* Allocate an array of slices and fill them from the data in frq_tab
1593 n_slices will contain the number of slices allocated.
1594 The caller is responsible for freeing slices
1596 static struct slice *
1597 freq_tab_to_slice_array(const struct freq_tab *frq_tab,
1598 const struct variable *var,
1602 struct slice *slices;
1604 *n_slices = frq_tab->n_valid;
1606 slices = xnmalloc (*n_slices, sizeof *slices);
1608 for (i = 0 ; i < *n_slices ; ++i )
1610 const struct freq *frq = &frq_tab->valid[i];
1612 slices[i].label = var_get_value_name (var, frq->value);
1613 slices[i].magnetude = frq->count;
1623 do_piechart(const struct variable *var, const struct freq_tab *frq_tab)
1625 struct slice *slices;
1628 slices = freq_tab_to_slice_array(frq_tab, var, &n_slices);
1630 piechart_plot(var_to_string(var), slices, n_slices);