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 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 (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 (struct variable *);
279 static void dump_full (struct variable *);
280 static void dump_condensed (struct variable *);
281 static void dump_statistics (struct variable *, int show_varname);
282 static void cleanup_freq_tab (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 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 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);
706 /* Summarizes the frequency table data for variable V. */
708 postprocess_freq_tab (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 (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 (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 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. */
880 if (!parse_variables (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)
1103 int lab = cmd.labels == FRQ_LABELS;
1107 t->w[0] = MIN (tab_natural_width (t, d, 0), d->prop_em_width * 15);
1108 for (i = lab; i < lab + 5; i++)
1109 t->w[i] = MAX (tab_natural_width (t, d, i), d->prop_em_width * 8);
1110 for (i = 0; i < t->nr; i++)
1111 t->h[i] = d->font_height;
1114 /* Displays a full frequency table for variable V. */
1116 dump_full (struct variable *v)
1119 struct var_freqs *vf;
1120 struct freq_tab *ft;
1122 struct tab_table *t;
1124 double cum_total = 0.0;
1125 double cum_freq = 0.0;
1133 const struct init *p;
1135 static const struct init vec[] =
1137 {4, 0, N_("Valid")},
1139 {1, 1, N_("Value")},
1140 {2, 1, N_("Frequency")},
1141 {3, 1, N_("Percent")},
1142 {4, 1, N_("Percent")},
1143 {5, 1, N_("Percent")},
1151 int lab = cmd.labels == FRQ_LABELS;
1153 vf = get_var_freqs (v);
1155 n_categories = ft->n_valid + ft->n_missing;
1156 t = tab_create (5 + lab, n_categories + 3, 0);
1157 tab_headers (t, 0, 0, 2, 0);
1158 tab_dim (t, full_dim);
1161 tab_text (t, 0, 1, TAB_CENTER | TAT_TITLE, _("Value Label"));
1162 for (p = vec; p->s; p++)
1163 tab_text (t, p->c - (p->r ? !lab : 0), p->r,
1164 TAB_CENTER | TAT_TITLE, gettext (p->s));
1167 for (f = ft->valid; f < ft->missing; f++)
1169 double percent, valid_percent;
1171 cum_freq += f->count;
1173 percent = f->count / ft->total_cases * 100.0;
1174 valid_percent = f->count / ft->valid_cases * 100.0;
1175 cum_total += valid_percent;
1180 <<<<<<< frequencies.q
1181 const char *label = val_labs_find (v->val_labs, f->value[0]);
1184 const char *label = var_lookup_value_label (v, &f->value[0]);
1186 tab_text (t, 0, r, TAB_LEFT, label);
1189 tab_value (t, 0 + lab, r, TAB_NONE, f->value, &vf->print);
1190 tab_float (t, 1 + lab, r, TAB_NONE, f->count, 8, 0);
1191 tab_float (t, 2 + lab, r, TAB_NONE, percent, 5, 1);
1192 tab_float (t, 3 + lab, r, TAB_NONE, valid_percent, 5, 1);
1193 tab_float (t, 4 + lab, r, TAB_NONE, cum_total, 5, 1);
1196 for (; f < &ft->valid[n_categories]; f++)
1198 cum_freq += f->count;
1202 const char *label = var_lookup_value_label (v, &f->value[0]);
1204 tab_text (t, 0, r, TAB_LEFT, label);
1207 tab_value (t, 0 + lab, r, TAB_NONE, f->value, &vf->print);
1208 tab_float (t, 1 + lab, r, TAB_NONE, f->count, 8, 0);
1209 tab_float (t, 2 + lab, r, TAB_NONE,
1210 f->count / ft->total_cases * 100.0, 5, 1);
1211 tab_text (t, 3 + lab, r, TAB_NONE, _("Missing"));
1215 tab_box (t, TAL_1, TAL_1,
1216 cmd.spaces == FRQ_SINGLE ? -1 : TAL_GAP, TAL_1,
1218 tab_hline (t, TAL_2, 0, 4 + lab, 2);
1219 tab_hline (t, TAL_2, 0, 4 + lab, r);
1220 tab_joint_text (t, 0, r, 0 + lab, r, TAB_RIGHT | TAT_TITLE, _("Total"));
1221 tab_vline (t, TAL_0, 1, r, r);
1222 tab_float (t, 1 + lab, r, TAB_NONE, cum_freq, 8, 0);
1223 tab_float (t, 2 + lab, r, TAB_NONE, 100.0, 5, 1);
1224 tab_float (t, 3 + lab, r, TAB_NONE, 100.0, 5, 1);
1226 tab_title (t, "%s", var_to_string (v));
1230 /* Sets the widths of all the columns and heights of all the rows in
1231 table T for driver D. */
1233 condensed_dim (struct tab_table *t, struct outp_driver *d)
1235 int cum_w = MAX (outp_string_width (d, _("Cum"), OUTP_PROPORTIONAL),
1236 MAX (outp_string_width (d, _("Cum"), OUTP_PROPORTIONAL),
1237 outp_string_width (d, "000", OUTP_PROPORTIONAL)));
1241 for (i = 0; i < 2; i++)
1242 t->w[i] = MAX (tab_natural_width (t, d, i), d->prop_em_width * 8);
1243 for (i = 2; i < 4; i++)
1245 for (i = 0; i < t->nr; i++)
1246 t->h[i] = d->font_height;
1249 /* Display condensed frequency table for variable V. */
1251 dump_condensed (struct variable *v)
1254 struct var_freqs *vf;
1255 struct freq_tab *ft;
1257 struct tab_table *t;
1259 double cum_total = 0.0;
1261 vf = get_var_freqs (v);
1263 n_categories = ft->n_valid + ft->n_missing;
1264 t = tab_create (4, n_categories + 2, 0);
1266 tab_headers (t, 0, 0, 2, 0);
1267 tab_text (t, 0, 1, TAB_CENTER | TAT_TITLE, _("Value"));
1268 tab_text (t, 1, 1, TAB_CENTER | TAT_TITLE, _("Freq"));
1269 tab_text (t, 2, 1, TAB_CENTER | TAT_TITLE, _("Pct"));
1270 tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("Cum"));
1271 tab_text (t, 3, 1, TAB_CENTER | TAT_TITLE, _("Pct"));
1272 tab_dim (t, condensed_dim);
1275 for (f = ft->valid; f < ft->missing; f++)
1279 percent = f->count / ft->total_cases * 100.0;
1280 cum_total += f->count / ft->valid_cases * 100.0;
1282 tab_value (t, 0, r, TAB_NONE, f->value, &vf->print);
1283 tab_float (t, 1, r, TAB_NONE, f->count, 8, 0);
1284 tab_float (t, 2, r, TAB_NONE, percent, 3, 0);
1285 tab_float (t, 3, r, TAB_NONE, cum_total, 3, 0);
1288 for (; f < &ft->valid[n_categories]; f++)
1290 tab_value (t, 0, r, TAB_NONE, f->value, &vf->print);
1291 tab_float (t, 1, r, TAB_NONE, f->count, 8, 0);
1292 tab_float (t, 2, r, TAB_NONE,
1293 f->count / ft->total_cases * 100.0, 3, 0);
1297 tab_box (t, TAL_1, TAL_1,
1298 cmd.spaces == FRQ_SINGLE ? -1 : TAL_GAP, TAL_1,
1300 tab_hline (t, TAL_2, 0, 3, 2);
1301 tab_title (t, "%s", var_to_string (v));
1302 tab_columns (t, SOM_COL_DOWN, 1);
1306 /* Statistical display. */
1308 /* Calculates all the pertinent statistics for variable V, putting
1309 them in array D[]. FIXME: This could be made much more optimal. */
1311 calc_stats (struct variable *v, double d[frq_n_stats])
1313 struct freq_tab *ft = &get_var_freqs (v)->tab;
1314 double W = ft->valid_cases;
1323 double *median_value;
1325 /* Calculate percentiles. */
1327 /* If the 50th percentile was not explicitly requested then we must
1328 calculate it anyway --- it's the median */
1330 for (i = 0; i < n_percentiles; i++)
1332 if (percentiles[i].p == 0.5)
1334 median_value = &percentiles[i].value;
1339 if ( 0 == median_value )
1341 add_percentile (0.5);
1345 for (i = 0; i < n_percentiles; i++)
1347 percentiles[i].flag = 0;
1348 percentiles[i].flag2 = 0;
1352 for (idx = 0; idx < ft->n_valid; ++idx)
1354 static double prev_value = SYSMIS;
1355 f = &ft->valid[idx];
1357 for (i = 0; i < n_percentiles; i++)
1360 if ( percentiles[i].flag2 ) continue ;
1362 if ( get_algorithm() != COMPATIBLE )
1364 (ft->valid_cases - 1) * percentiles[i].p;
1367 (ft->valid_cases + 1) * percentiles[i].p - 1;
1369 if ( percentiles[i].flag )
1371 percentiles[i].x2 = f->value[0].f;
1372 percentiles[i].x1 = prev_value;
1373 percentiles[i].flag2 = 1;
1379 if ( f->count > 1 && rank - (f->count - 1) > tp )
1381 percentiles[i].x2 = percentiles[i].x1 = f->value[0].f;
1382 percentiles[i].flag2 = 1;
1386 percentiles[i].flag=1;
1392 prev_value = f->value[0].f;
1395 for (i = 0; i < n_percentiles; i++)
1397 /* Catches the case when p == 100% */
1398 if ( ! percentiles[i].flag2 )
1399 percentiles[i].x1 = percentiles[i].x2 = f->value[0].f;
1402 printf("percentile %d (p==%.2f); X1 = %g; X2 = %g\n",
1403 i,percentiles[i].p,percentiles[i].x1,percentiles[i].x2);
1407 for (i = 0; i < n_percentiles; i++)
1409 struct freq_tab *ft = &get_var_freqs (v)->tab;
1413 if ( get_algorithm() != COMPATIBLE )
1415 s = modf((ft->valid_cases - 1) * percentiles[i].p , &dummy);
1419 s = modf((ft->valid_cases + 1) * percentiles[i].p -1, &dummy);
1422 percentiles[i].value = percentiles[i].x1 +
1423 ( percentiles[i].x2 - percentiles[i].x1) * s ;
1425 if ( percentiles[i].p == 0.50)
1426 median_value = &percentiles[i].value;
1430 /* Calculate the mode. */
1433 for (f = ft->valid; f < ft->missing; f++)
1435 if (most_often < f->count)
1437 most_often = f->count;
1438 X_mode = f->value[0].f;
1440 else if (most_often == f->count)
1442 /* A duplicate mode is undefined.
1443 FIXME: keep track of *all* the modes. */
1448 /* Calculate moments. */
1449 m = moments_create (MOMENT_KURTOSIS);
1450 for (f = ft->valid; f < ft->missing; f++)
1451 moments_pass_one (m, f->value[0].f, f->count);
1452 for (f = ft->valid; f < ft->missing; f++)
1453 moments_pass_two (m, f->value[0].f, f->count);
1454 moments_calculate (m, NULL, &d[frq_mean], &d[frq_variance],
1455 &d[frq_skew], &d[frq_kurt]);
1456 moments_destroy (m);
1458 /* Formulas below are taken from _SPSS Statistical Algorithms_. */
1459 d[frq_min] = ft->valid[0].value[0].f;
1460 d[frq_max] = ft->valid[ft->n_valid - 1].value[0].f;
1461 d[frq_mode] = X_mode;
1462 d[frq_range] = d[frq_max] - d[frq_min];
1463 d[frq_median] = *median_value;
1464 d[frq_sum] = d[frq_mean] * W;
1465 d[frq_stddev] = sqrt (d[frq_variance]);
1466 d[frq_semean] = d[frq_stddev] / sqrt (W);
1467 d[frq_seskew] = calc_seskew (W);
1468 d[frq_sekurt] = calc_sekurt (W);
1471 /* Displays a table of all the statistics requested for variable V. */
1473 dump_statistics (struct variable *v, int show_varname)
1475 struct freq_tab *ft;
1476 double stat_value[frq_n_stats];
1477 struct tab_table *t;
1480 int n_explicit_percentiles = n_percentiles;
1482 if ( implicit_50th && n_percentiles > 0 )
1485 if (var_is_alpha (v))
1487 ft = &get_var_freqs (v)->tab;
1488 if (ft->n_valid == 0)
1490 msg (SW, _("No valid data for variable %s; statistics not displayed."),
1494 calc_stats (v, stat_value);
1496 t = tab_create (3, n_stats + n_explicit_percentiles + 2, 0);
1497 tab_dim (t, tab_natural_dimensions);
1499 tab_box (t, TAL_1, TAL_1, -1, -1 , 0 , 0 , 2, tab_nr(t) - 1) ;
1502 tab_vline (t, TAL_1 , 2, 0, tab_nr(t) - 1);
1503 tab_vline (t, TAL_GAP , 1, 0, tab_nr(t) - 1 ) ;
1505 r=2; /* N missing and N valid are always dumped */
1507 for (i = 0; i < frq_n_stats; i++)
1508 if (stats & BIT_INDEX (i))
1510 tab_text (t, 0, r, TAB_LEFT | TAT_TITLE,
1511 gettext (st_name[i].s10));
1512 tab_float (t, 2, r, TAB_NONE, stat_value[i], 11, 3);
1516 tab_text (t, 0, 0, TAB_LEFT | TAT_TITLE, _("N"));
1517 tab_text (t, 1, 0, TAB_LEFT | TAT_TITLE, _("Valid"));
1518 tab_text (t, 1, 1, TAB_LEFT | TAT_TITLE, _("Missing"));
1520 tab_float(t, 2, 0, TAB_NONE, ft->valid_cases, 11, 0);
1521 tab_float(t, 2, 1, TAB_NONE, ft->total_cases - ft->valid_cases, 11, 0);
1524 for (i = 0; i < n_explicit_percentiles; i++, r++)
1528 tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, _("Percentiles"));
1531 tab_float (t, 1, r, TAB_LEFT, percentiles[i].p * 100, 3, 0 );
1532 tab_float (t, 2, r, TAB_NONE, percentiles[i].value, 11, 3);
1536 tab_columns (t, SOM_COL_DOWN, 1);
1538 tab_title (t, "%s", var_to_string (v));
1540 tab_flags (t, SOMF_NO_TITLE);
1547 /* Create a gsl_histogram from a freq_tab */
1549 freq_tab_to_hist(const struct freq_tab *ft, const struct variable *var)
1552 double x_min = DBL_MAX;
1553 double x_max = -DBL_MAX;
1555 gsl_histogram *hist;
1556 const double bins = 11;
1558 struct hsh_iterator hi;
1559 struct hsh_table *fh = ft->data;
1562 /* Find out the extremes of the x value */
1563 for ( frq = hsh_first(fh, &hi); frq != 0; frq = hsh_next(fh, &hi) )
1565 if ( var_is_value_missing(var, frq->value))
1568 if ( frq->value[0].f < x_min ) x_min = frq->value[0].f ;
1569 if ( frq->value[0].f > x_max ) x_max = frq->value[0].f ;
1572 hist = histogram_create(bins, x_min, x_max);
1574 for( i = 0 ; i < ft->n_valid ; ++i )
1576 frq = &ft->valid[i];
1577 gsl_histogram_accumulate(hist, frq->value[0].f, frq->count);
1584 static struct slice *
1585 freq_tab_to_slice_array(const struct freq_tab *frq_tab,
1586 const struct variable *var,
1590 /* Allocate an array of slices and fill them from the data in frq_tab
1591 n_slices will contain the number of slices allocated.
1592 The caller is responsible for freeing slices
1594 static struct slice *
1595 freq_tab_to_slice_array(const struct freq_tab *frq_tab,
1596 const struct variable *var,
1600 struct slice *slices;
1602 *n_slices = frq_tab->n_valid;
1604 slices = xnmalloc (*n_slices, sizeof *slices);
1606 for (i = 0 ; i < *n_slices ; ++i )
1608 const struct freq *frq = &frq_tab->valid[i];
1610 slices[i].label = var_get_value_name (var, frq->value);
1611 slices[i].magnetude = frq->count;
1621 do_piechart(const struct variable *var, const struct freq_tab *frq_tab)
1623 struct slice *slices;
1626 slices = freq_tab_to_slice_array(frq_tab, var, &n_slices);
1628 piechart_plot(var_to_string(var), slices, n_slices);