1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 1997-9, 2000, 2007 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU 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, see <http://www.gnu.org/licenses/>. */
20 * Remember that histograms, bar charts need mean, stddev.
27 #include <gsl/gsl_histogram.h>
29 #include <data/case.h>
30 #include <data/casegrouper.h>
31 #include <data/casereader.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/array.h>
42 #include <libpspp/bit-vector.h>
43 #include <libpspp/compiler.h>
44 #include <libpspp/hash.h>
45 #include <libpspp/message.h>
46 #include <libpspp/misc.h>
47 #include <libpspp/pool.h>
48 #include <libpspp/str.h>
49 #include <math/histogram.h>
50 #include <math/moments.h>
51 #include <output/chart.h>
52 #include <output/charts/piechart.h>
53 #include <output/charts/plot-hist.h>
54 #include <output/manager.h>
55 #include <output/output.h>
56 #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 /* Groups of statistics. */
160 #define frq_default \
161 (BI (frq_mean) | BI (frq_stddev) | BI (frq_min) | BI (frq_max))
163 (BI (frq_sum) | BI(frq_min) | BI(frq_max) \
164 | BI(frq_mean) | BI(frq_semean) | BI(frq_stddev) \
165 | BI(frq_variance) | BI(frq_kurt) | BI(frq_sekurt) \
166 | BI(frq_skew) | BI(frq_seskew) | BI(frq_range) \
167 | BI(frq_range) | BI(frq_mode) | BI(frq_median))
169 /* Statistics; number of statistics. */
170 static unsigned long stats;
173 /* Types of graphs. */
176 GFT_NONE, /* Don't draw graphs. */
177 GFT_BAR, /* Draw bar charts. */
178 GFT_HIST, /* Draw histograms. */
179 GFT_PIE, /* Draw piechart */
180 GFT_HBAR /* Draw bar charts or histograms at our discretion. */
183 /* Parsed command. */
184 static struct cmd_frequencies cmd;
186 /* Summary of the barchart, histogram, and hbar subcommands. */
187 /* FIXME: These should not be mututally exclusive */
188 static int chart; /* NONE/BAR/HIST/HBAR/PIE. */
189 static double min, max; /* Minimum, maximum on y axis. */
190 static int format; /* FREQ/PERCENT: Scaling of y axis. */
191 static double scale, incr; /* FIXME */
192 static int normal; /* FIXME */
194 /* Variables for which to calculate statistics. */
195 static size_t n_variables;
196 static const struct variable **v_variables;
199 static struct pool *data_pool; /* For per-SPLIT FILE group data. */
200 static struct pool *syntax_pool; /* For syntax-related data. */
202 /* Frequency tables. */
204 /* Entire frequency table. */
207 struct hsh_table *data; /* Undifferentiated data. */
208 struct freq *valid; /* Valid freqs. */
209 int n_valid; /* Number of total freqs. */
211 struct freq *missing; /* Missing freqs. */
212 int n_missing; /* Number of missing freqs. */
215 double total_cases; /* Sum of weights of all cases. */
216 double valid_cases; /* Sum of weights of valid cases. */
220 /* Per-variable frequency data. */
223 /* Freqency table. */
224 struct freq_tab tab; /* Frequencies table to use. */
227 int n_groups; /* Number of groups. */
228 double *groups; /* Groups. */
231 double stat[frq_n_stats];
233 /* Width and format for analysis and display.
234 This is normally the same as "width" and "print" in struct
235 variable, but in SPSS-compatible mode only the first
236 MAX_SHORT_STRING bytes of long string variables are
239 struct fmt_spec print;
242 static inline struct var_freqs *
243 get_var_freqs (const struct variable *v)
245 return var_get_aux (v);
248 static void determine_charts (void);
250 static void calc_stats (const struct variable *v, double d[frq_n_stats]);
252 static void precalc (struct casereader *, struct dataset *);
253 static void calc (const struct ccase *, const struct dataset *);
254 static void postcalc (const struct dataset *);
256 static void postprocess_freq_tab (const struct variable *);
257 static void dump_full ( const struct variable *, const struct variable *);
258 static void dump_condensed (const struct variable *, const struct variable *);
259 static void dump_statistics (const struct variable *, bool show_varname, const struct variable *);
260 static void cleanup_freq_tab (const struct variable *);
262 static hsh_compare_func compare_value_numeric_a, compare_value_alpha_a;
263 static hsh_compare_func compare_value_numeric_d, compare_value_alpha_d;
264 static hsh_compare_func compare_freq_numeric_a, compare_freq_alpha_a;
265 static hsh_compare_func compare_freq_numeric_d, compare_freq_alpha_d;
268 static void do_piechart(const struct variable *var,
269 const struct freq_tab *frq_tab);
272 freq_tab_to_hist(const struct freq_tab *ft, const struct variable *var);
276 /* Parser and outline. */
278 static int internal_cmd_frequencies (struct lexer *lexer, struct dataset *ds);
281 cmd_frequencies (struct lexer *lexer, struct dataset *ds)
285 syntax_pool = pool_create ();
286 result = internal_cmd_frequencies (lexer, ds);
287 pool_destroy (syntax_pool);
289 pool_destroy (data_pool);
297 internal_cmd_frequencies (struct lexer *lexer, struct dataset *ds)
299 struct casegrouper *grouper;
300 struct casereader *input, *group;
310 if (!parse_frequencies (lexer, ds, &cmd, NULL))
313 if (cmd.onepage_limit == LONG_MIN)
314 cmd.onepage_limit = 50;
316 /* Figure out statistics to calculate. */
318 if (cmd.a_statistics[FRQ_ST_DEFAULT] || !cmd.sbc_statistics)
319 stats |= frq_default;
320 if (cmd.a_statistics[FRQ_ST_ALL])
322 if (cmd.sort != FRQ_AVALUE && cmd.sort != FRQ_DVALUE)
323 stats &= ~BIT_INDEX (frq_median);
324 for (i = 0; i < frq_n_stats; i++)
325 if (cmd.a_statistics[st_name[i].st_indx])
326 stats |= BIT_INDEX (i);
327 if (stats & frq_kurt)
328 stats |= BIT_INDEX (frq_sekurt);
329 if (stats & frq_skew)
330 stats |= BIT_INDEX (frq_seskew);
332 /* Calculate n_stats. */
334 for (i = 0; i < frq_n_stats; i++)
335 if ((stats & BIT_INDEX (i)))
340 if (chart != GFT_NONE || cmd.sbc_ntiles)
341 cmd.sort = FRQ_AVALUE;
343 /* Work out what percentiles need to be calculated */
344 if ( cmd.sbc_percentiles )
346 for ( i = 0 ; i < MAXLISTS ; ++i )
349 subc_list_double *ptl_list = &cmd.dl_percentiles[i];
350 for ( pl = 0 ; pl < subc_list_double_count(ptl_list); ++pl)
351 add_percentile (subc_list_double_at(ptl_list, pl) / 100.0 );
354 if ( cmd.sbc_ntiles )
356 for ( i = 0 ; i < cmd.sbc_ntiles ; ++i )
359 for (j = 0; j <= cmd.n_ntiles[i]; ++j )
360 add_percentile (j / (double) cmd.n_ntiles[i]);
363 if (stats & BIT_INDEX (frq_median))
365 /* Treat the median as the 50% percentile.
366 We output it in the percentiles table as "50 (Median)." */
367 add_percentile (0.5);
368 stats &= ~BIT_INDEX (frq_median);
373 input = casereader_create_filter_weight (proc_open (ds), dataset_dict (ds),
375 grouper = casegrouper_create_splits (input, dataset_dict (ds));
376 for (; casegrouper_get_next_group (grouper, &group);
377 casereader_destroy (group))
382 for (; casereader_read (group, &c); case_destroy (&c))
386 ok = casegrouper_destroy (grouper);
387 ok = proc_commit (ds) && ok;
389 free_frequencies(&cmd);
391 return ok ? CMD_SUCCESS : CMD_CASCADING_FAILURE;
394 /* Figure out which charts the user requested. */
396 determine_charts (void)
398 int count = (!!cmd.sbc_histogram) + (!!cmd.sbc_barchart) +
399 (!!cmd.sbc_hbar) + (!!cmd.sbc_piechart);
409 msg (SW, _("At most one of BARCHART, HISTOGRAM, or HBAR should be "
410 "given. HBAR will be assumed. Argument values will be "
411 "given precedence increasing along the order given."));
413 else if (cmd.sbc_histogram)
415 else if (cmd.sbc_barchart)
417 else if (cmd.sbc_piechart)
428 if (cmd.sbc_barchart)
430 if (cmd.ba_min != SYSMIS)
432 if (cmd.ba_max != SYSMIS)
434 if (cmd.ba_scale == FRQ_FREQ)
439 else if (cmd.ba_scale == FRQ_PERCENT)
441 format = FRQ_PERCENT;
446 if (cmd.sbc_histogram)
448 if (cmd.hi_min != SYSMIS)
450 if (cmd.hi_max != SYSMIS)
452 if (cmd.hi_scale == FRQ_FREQ)
457 else if (cmd.hi_scale == FRQ_PERCENT)
459 format = FRQ_PERCENT;
462 if (cmd.hi_norm != FRQ_NONORMAL )
464 if (cmd.hi_incr == FRQ_INCREMENT)
470 if (cmd.hb_min != SYSMIS)
472 if (cmd.hb_max != SYSMIS)
474 if (cmd.hb_scale == FRQ_FREQ)
479 else if (cmd.hb_scale == FRQ_PERCENT)
481 format = FRQ_PERCENT;
486 if (cmd.hb_incr == FRQ_INCREMENT)
490 if (min != SYSMIS && max != SYSMIS && min >= max)
492 msg (SE, _("MAX must be greater than or equal to MIN, if both are "
493 "specified. However, MIN was specified as %g and MAX as %g. "
494 "MIN and MAX will be ignored."), min, max);
499 /* Add data from case C to the frequency table. */
501 calc (const struct ccase *c, const struct dataset *ds)
503 double weight = dict_get_case_weight (dataset_dict (ds), c, NULL);
506 for (i = 0; i < n_variables; i++)
508 const struct variable *v = v_variables[i];
509 const union value *val = case_data (c, v);
510 struct var_freqs *vf = get_var_freqs (v);
511 struct freq_tab *ft = &vf->tab;
516 target.value = (union value *) val;
517 fpp = (struct freq **) hsh_probe (ft->data, &target);
520 (*fpp)->count += weight;
523 struct freq *fp = pool_alloc (data_pool, sizeof *fp);
525 fp->value = pool_clone (data_pool,
527 MAX (MAX_SHORT_STRING, vf->width));
533 /* Prepares each variable that is the target of FREQUENCIES by setting
534 up its hash table. */
536 precalc (struct casereader *input, struct dataset *ds)
541 if (casereader_peek (input, 0, &c))
543 output_split_file_values (ds, &c);
547 pool_destroy (data_pool);
548 data_pool = pool_create ();
550 for (i = 0; i < n_variables; i++)
552 const struct variable *v = v_variables[i];
553 struct freq_tab *ft = &get_var_freqs (v)->tab;
555 ft->data = hsh_create (16, compare_freq, hash_freq, NULL, v);
559 /* Finishes up with the variables after frequencies have been
560 calculated. Displays statistics, percentiles, ... */
562 postcalc (const struct dataset *ds)
564 const struct dictionary *dict = dataset_dict (ds);
565 const struct variable *wv = dict_get_weight (dict);
568 for (i = 0; i < n_variables; i++)
570 const struct variable *v = v_variables[i];
571 struct var_freqs *vf = get_var_freqs (v);
572 struct freq_tab *ft = &vf->tab;
574 int dumped_freq_tab = 1;
576 postprocess_freq_tab (v);
578 /* Frequencies tables. */
579 n_categories = ft->n_valid + ft->n_missing;
580 if (cmd.table == FRQ_TABLE
581 || (cmd.table == FRQ_LIMIT && n_categories <= cmd.limit))
585 dump_condensed (v, wv);
591 if (n_categories > cmd.onepage_limit)
592 dump_condensed (v, wv);
604 dump_statistics (v, !dumped_freq_tab, wv);
608 if ( chart == GFT_HIST)
610 double d[frq_n_stats];
611 struct normal_curve norm;
612 gsl_histogram *hist ;
615 norm.N = vf->tab.valid_cases;
618 norm.mean = d[frq_mean];
619 norm.stddev = d[frq_stddev];
621 hist = freq_tab_to_hist(ft,v);
623 histogram_plot(hist, var_to_string(v), &norm, normal);
625 gsl_histogram_free(hist);
629 if ( chart == GFT_PIE)
631 do_piechart(v_variables[i], ft);
636 cleanup_freq_tab (v);
641 /* Returns the comparison function that should be used for
642 sorting a frequency table by FRQ_SORT using VAL_TYPE
644 static hsh_compare_func *
645 get_freq_comparator (int frq_sort, enum val_type val_type)
647 bool is_numeric = val_type == VAL_NUMERIC;
651 return is_numeric ? compare_value_numeric_a : compare_value_alpha_a;
653 return is_numeric ? compare_value_numeric_d : compare_value_alpha_d;
655 return is_numeric ? compare_freq_numeric_a : compare_freq_alpha_a;
657 return is_numeric ? compare_freq_numeric_d : compare_freq_alpha_d;
663 /* Returns true iff the value in struct freq F is non-missing
666 not_missing (const void *f_, const void *v_)
668 const struct freq *f = f_;
669 const struct variable *v = v_;
671 return !var_is_value_missing (v, f->value, MV_ANY);
674 /* Summarizes the frequency table data for variable V. */
676 postprocess_freq_tab (const struct variable *v)
678 hsh_compare_func *compare;
682 struct freq *freqs, *f;
685 ft = &get_var_freqs (v)->tab;
686 compare = get_freq_comparator (cmd.sort, var_get_type (v));
688 /* Extract data from hash table. */
689 count = hsh_count (ft->data);
690 data = hsh_data (ft->data);
692 /* Copy dereferenced data into freqs. */
693 freqs = xnmalloc (count, sizeof *freqs);
694 for (i = 0; i < count; i++)
696 struct freq *f = data[i];
700 /* Put data into ft. */
702 ft->n_valid = partition (freqs, count, sizeof *freqs, not_missing, v);
703 ft->missing = freqs + ft->n_valid;
704 ft->n_missing = count - ft->n_valid;
707 sort (ft->valid, ft->n_valid, sizeof *ft->valid, compare, v);
708 sort (ft->missing, ft->n_missing, sizeof *ft->missing, compare, v);
710 /* Summary statistics. */
711 ft->valid_cases = 0.0;
712 for(i = 0 ; i < ft->n_valid ; ++i )
715 ft->valid_cases += f->count;
719 ft->total_cases = ft->valid_cases ;
720 for(i = 0 ; i < ft->n_missing ; ++i )
723 ft->total_cases += f->count;
728 /* Frees the frequency table for variable V. */
730 cleanup_freq_tab (const struct variable *v)
732 struct freq_tab *ft = &get_var_freqs (v)->tab;
734 hsh_destroy (ft->data);
737 /* Parses the VARIABLES subcommand, adding to
738 {n_variables,v_variables}. */
740 frq_custom_variables (struct lexer *lexer, struct dataset *ds, struct cmd_frequencies *cmd UNUSED, void *aux UNUSED)
742 size_t old_n_variables = n_variables;
745 lex_match (lexer, '=');
746 if (lex_token (lexer) != T_ALL && (lex_token (lexer) != T_ID
747 || dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) == NULL))
750 if (!parse_variables_const (lexer, dataset_dict (ds), &v_variables, &n_variables,
751 PV_APPEND | PV_NO_SCRATCH))
754 for (i = old_n_variables; i < n_variables; i++)
756 const struct variable *v = v_variables[i];
757 struct var_freqs *vf;
759 if (var_get_aux (v) != NULL)
761 msg (SE, _("Variable %s specified multiple times on VARIABLES "
762 "subcommand."), var_get_name (v));
765 vf = var_attach_aux (v, xmalloc (sizeof *vf), var_dtor_free);
766 vf->tab.valid = vf->tab.missing = NULL;
769 vf->width = var_get_width (v);
770 vf->print = *var_get_print_format (v);
771 if (vf->width > MAX_SHORT_STRING && settings_get_algorithm () == COMPATIBLE)
773 enum fmt_type type = var_get_print_format (v)->type;
774 vf->width = MAX_SHORT_STRING;
775 vf->print.w = MAX_SHORT_STRING * (type == FMT_AHEX ? 2 : 1);
781 /* Parses the GROUPED subcommand, setting the n_grouped, grouped
782 fields of specified variables. */
784 frq_custom_grouped (struct lexer *lexer, struct dataset *ds, struct cmd_frequencies *cmd UNUSED, void *aux UNUSED)
786 lex_match (lexer, '=');
787 if ((lex_token (lexer) == T_ID && dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) != NULL)
788 || lex_token (lexer) == T_ID)
793 /* Max, current size of list; list itself. */
799 const struct variable **v;
801 if (!parse_variables_const (lexer, dataset_dict (ds), &v, &n,
802 PV_NO_DUPLICATE | PV_NUMERIC))
804 if (lex_match (lexer, '('))
808 while (lex_integer (lexer))
813 dl = pool_nrealloc (syntax_pool, dl, ml, sizeof *dl);
815 dl[nl++] = lex_tokval (lexer);
817 lex_match (lexer, ',');
819 /* Note that nl might still be 0 and dl might still be
820 NULL. That's okay. */
821 if (!lex_match (lexer, ')'))
824 msg (SE, _("`)' expected after GROUPED interval list."));
834 for (i = 0; i < n; i++)
835 if (var_get_aux (v[i]) == NULL)
836 msg (SE, _("Variables %s specified on GROUPED but not on "
837 "VARIABLES."), var_get_name (v[i]));
840 struct var_freqs *vf = get_var_freqs (v[i]);
842 if (vf->groups != NULL)
843 msg (SE, _("Variables %s specified multiple times on GROUPED "
844 "subcommand."), var_get_name (v[i]));
852 if (!lex_match (lexer, '/'))
854 if ((lex_token (lexer) != T_ID || dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) != NULL)
855 && lex_token (lexer) != T_ALL)
857 lex_put_back (lexer, '/');
865 /* Adds X to the list of percentiles, keeping the list in proper
868 add_percentile (double x)
872 for (i = 0; i < n_percentiles; i++)
874 /* Do nothing if it's already in the list */
875 if ( fabs(x - percentiles[i].p) < DBL_EPSILON )
878 if (x < percentiles[i].p)
882 if (i >= n_percentiles || x != percentiles[i].p)
884 percentiles = pool_nrealloc (syntax_pool, percentiles,
885 n_percentiles + 1, sizeof *percentiles);
886 insert_element (percentiles, n_percentiles, sizeof *percentiles, i);
887 percentiles[i].p = x;
892 /* Comparison functions. */
894 /* Ascending numeric compare of values. */
896 compare_value_numeric_a (const void *a_, const void *b_, const void *aux UNUSED)
898 const struct freq *a = a_;
899 const struct freq *b = b_;
901 if (a->value[0].f > b->value[0].f)
903 else if (a->value[0].f < b->value[0].f)
909 /* Ascending string compare of values. */
911 compare_value_alpha_a (const void *a_, const void *b_, const void *v_)
913 const struct freq *a = a_;
914 const struct freq *b = b_;
915 const struct variable *v = v_;
916 struct var_freqs *vf = get_var_freqs (v);
918 return memcmp (a->value[0].s, b->value[0].s, vf->width);
921 /* Descending numeric compare of values. */
923 compare_value_numeric_d (const void *a, const void *b, const void *aux UNUSED)
925 return -compare_value_numeric_a (a, b, aux);
928 /* Descending string compare of values. */
930 compare_value_alpha_d (const void *a, const void *b, const void *v)
932 return -compare_value_alpha_a (a, b, v);
935 /* Ascending numeric compare of frequency;
936 secondary key on ascending numeric value. */
938 compare_freq_numeric_a (const void *a_, const void *b_, const void *aux UNUSED)
940 const struct freq *a = a_;
941 const struct freq *b = b_;
943 if (a->count > b->count)
945 else if (a->count < b->count)
948 if (a->value[0].f > b->value[0].f)
950 else if (a->value[0].f < b->value[0].f)
956 /* Ascending numeric compare of frequency;
957 secondary key on ascending string value. */
959 compare_freq_alpha_a (const void *a_, const void *b_, const void *v_)
961 const struct freq *a = a_;
962 const struct freq *b = b_;
963 const struct variable *v = v_;
964 struct var_freqs *vf = get_var_freqs (v);
966 if (a->count > b->count)
968 else if (a->count < b->count)
971 return memcmp (a->value[0].s, b->value[0].s, vf->width);
974 /* Descending numeric compare of frequency;
975 secondary key on ascending numeric value. */
977 compare_freq_numeric_d (const void *a_, const void *b_, const void *aux UNUSED)
979 const struct freq *a = a_;
980 const struct freq *b = b_;
982 if (a->count > b->count)
984 else if (a->count < b->count)
987 if (a->value[0].f > b->value[0].f)
989 else if (a->value[0].f < b->value[0].f)
995 /* Descending numeric compare of frequency;
996 secondary key on ascending string value. */
998 compare_freq_alpha_d (const void *a_, const void *b_, const void *v_)
1000 const struct freq *a = a_;
1001 const struct freq *b = b_;
1002 const struct variable *v = v_;
1003 struct var_freqs *vf = get_var_freqs (v);
1005 if (a->count > b->count)
1007 else if (a->count < b->count)
1010 return memcmp (a->value[0].s, b->value[0].s, vf->width);
1013 /* Frequency table display. */
1015 /* Sets the widths of all the columns and heights of all the rows in
1016 table T for driver D. */
1018 full_dim (struct tab_table *t, struct outp_driver *d)
1023 if (cmd.labels == FRQ_LABELS)
1025 t->w[0] = MIN (tab_natural_width (t, d, 0), d->prop_em_width * 15);
1030 for (;i < columns; i++)
1031 t->w[i] = MAX (tab_natural_width (t, d, i), d->prop_em_width * 8);
1033 for (i = 0; i < t->nr; i++)
1034 t->h[i] = d->font_height;
1037 /* Displays a full frequency table for variable V. */
1039 dump_full (const struct variable *v, const struct variable *wv)
1041 const struct fmt_spec *wfmt = wv ? var_get_print_format (wv) : &F_8_0;
1043 struct var_freqs *vf;
1044 struct freq_tab *ft;
1046 struct tab_table *t;
1048 double cum_total = 0.0;
1049 double cum_freq = 0.0;
1057 const struct init *p;
1059 static const struct init vec[] =
1061 {4, 0, N_("Valid")},
1063 {1, 1, N_("Value")},
1064 {2, 1, N_("Frequency")},
1065 {3, 1, N_("Percent")},
1066 {4, 1, N_("Percent")},
1067 {5, 1, N_("Percent")},
1075 const bool lab = (cmd.labels == FRQ_LABELS);
1077 vf = get_var_freqs (v);
1079 n_categories = ft->n_valid + ft->n_missing;
1080 t = tab_create (5 + lab, n_categories + 3, 0);
1081 tab_headers (t, 0, 0, 2, 0);
1082 tab_dim (t, full_dim);
1085 tab_text (t, 0, 1, TAB_CENTER | TAT_TITLE, _("Value Label"));
1087 for (p = vec; p->s; p++)
1088 tab_text (t, lab ? p->c : p->c - 1, p->r,
1089 TAB_CENTER | TAT_TITLE, gettext (p->s));
1092 for (f = ft->valid; f < ft->missing; f++)
1094 double percent, valid_percent;
1096 cum_freq += f->count;
1098 percent = f->count / ft->total_cases * 100.0;
1099 valid_percent = f->count / ft->valid_cases * 100.0;
1100 cum_total += valid_percent;
1104 const char *label = var_lookup_value_label (v, &f->value[0]);
1106 tab_text (t, 0, r, TAB_LEFT, label);
1109 tab_value (t, 0 + lab, r, TAB_NONE, f->value, &vf->print);
1110 tab_double (t, 1 + lab, r, TAB_NONE, f->count, wfmt);
1111 tab_double (t, 2 + lab, r, TAB_NONE, percent, NULL);
1112 tab_double (t, 3 + lab, r, TAB_NONE, valid_percent, NULL);
1113 tab_double (t, 4 + lab, r, TAB_NONE, cum_total, NULL);
1116 for (; f < &ft->valid[n_categories]; f++)
1118 cum_freq += f->count;
1122 const char *label = var_lookup_value_label (v, &f->value[0]);
1124 tab_text (t, 0, r, TAB_LEFT, label);
1127 tab_value (t, 0 + lab, r, TAB_NONE, f->value, &vf->print);
1128 tab_double (t, 1 + lab, r, TAB_NONE, f->count, wfmt);
1129 tab_double (t, 2 + lab, r, TAB_NONE,
1130 f->count / ft->total_cases * 100.0, NULL);
1131 tab_text (t, 3 + lab, r, TAB_NONE, _("Missing"));
1135 tab_box (t, TAL_1, TAL_1,
1136 cmd.spaces == FRQ_SINGLE ? -1 : TAL_GAP, TAL_1,
1138 tab_hline (t, TAL_2, 0, 4 + lab, 2);
1139 tab_hline (t, TAL_2, 0, 4 + lab, r);
1140 tab_joint_text (t, 0, r, 0 + lab, r, TAB_RIGHT | TAT_TITLE, _("Total"));
1141 tab_vline (t, TAL_0, 1, r, r);
1142 tab_double (t, 1 + lab, r, TAB_NONE, cum_freq, wfmt);
1143 tab_fixed (t, 2 + lab, r, TAB_NONE, 100.0, 5, 1);
1144 tab_fixed (t, 3 + lab, r, TAB_NONE, 100.0, 5, 1);
1146 tab_title (t, "%s", var_to_string (v));
1150 /* Sets the widths of all the columns and heights of all the rows in
1151 table T for driver D. */
1153 condensed_dim (struct tab_table *t, struct outp_driver *d)
1155 int cum_w = MAX (outp_string_width (d, _("Cum"), OUTP_PROPORTIONAL),
1156 MAX (outp_string_width (d, _("Cum"), OUTP_PROPORTIONAL),
1157 outp_string_width (d, "000", OUTP_PROPORTIONAL)));
1161 for (i = 0; i < 2; i++)
1162 t->w[i] = MAX (tab_natural_width (t, d, i), d->prop_em_width * 8);
1163 for (i = 2; i < 4; i++)
1165 for (i = 0; i < t->nr; i++)
1166 t->h[i] = d->font_height;
1169 /* Display condensed frequency table for variable V. */
1171 dump_condensed (const struct variable *v, const struct variable *wv)
1173 const struct fmt_spec *wfmt = wv ? var_get_print_format (wv) : &F_8_0;
1175 struct var_freqs *vf;
1176 struct freq_tab *ft;
1178 struct tab_table *t;
1180 double cum_total = 0.0;
1182 vf = get_var_freqs (v);
1184 n_categories = ft->n_valid + ft->n_missing;
1185 t = tab_create (4, n_categories + 2, 0);
1187 tab_headers (t, 0, 0, 2, 0);
1188 tab_text (t, 0, 1, TAB_CENTER | TAT_TITLE, _("Value"));
1189 tab_text (t, 1, 1, TAB_CENTER | TAT_TITLE, _("Freq"));
1190 tab_text (t, 2, 1, TAB_CENTER | TAT_TITLE, _("Pct"));
1191 tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("Cum"));
1192 tab_text (t, 3, 1, TAB_CENTER | TAT_TITLE, _("Pct"));
1193 tab_dim (t, condensed_dim);
1196 for (f = ft->valid; f < ft->missing; f++)
1200 percent = f->count / ft->total_cases * 100.0;
1201 cum_total += f->count / ft->valid_cases * 100.0;
1203 tab_value (t, 0, r, TAB_NONE, f->value, &vf->print);
1204 tab_double (t, 1, r, TAB_NONE, f->count, wfmt);
1205 tab_double (t, 2, r, TAB_NONE, percent, NULL);
1206 tab_double (t, 3, r, TAB_NONE, cum_total, NULL);
1209 for (; f < &ft->valid[n_categories]; f++)
1211 tab_value (t, 0, r, TAB_NONE, f->value, &vf->print);
1212 tab_double (t, 1, r, TAB_NONE, f->count, wfmt);
1213 tab_double (t, 2, r, TAB_NONE,
1214 f->count / ft->total_cases * 100.0, NULL);
1218 tab_box (t, TAL_1, TAL_1,
1219 cmd.spaces == FRQ_SINGLE ? -1 : TAL_GAP, TAL_1,
1221 tab_hline (t, TAL_2, 0, 3, 2);
1222 tab_title (t, "%s", var_to_string (v));
1223 tab_columns (t, SOM_COL_DOWN, 1);
1227 /* Statistical display. */
1229 /* Calculates all the pertinent statistics for variable V, putting
1230 them in array D[]. FIXME: This could be made much more optimal. */
1232 calc_stats (const struct variable *v, double d[frq_n_stats])
1234 struct freq_tab *ft = &get_var_freqs (v)->tab;
1235 double W = ft->valid_cases;
1245 /* Calculate percentiles. */
1247 for (i = 0; i < n_percentiles; i++)
1249 percentiles[i].flag = 0;
1250 percentiles[i].flag2 = 0;
1254 for (idx = 0; idx < ft->n_valid; ++idx)
1256 static double prev_value = SYSMIS;
1257 f = &ft->valid[idx];
1259 for (i = 0; i < n_percentiles; i++)
1262 if ( percentiles[i].flag2 ) continue ;
1264 if ( settings_get_algorithm () != COMPATIBLE )
1266 (ft->valid_cases - 1) * percentiles[i].p;
1269 (ft->valid_cases + 1) * percentiles[i].p - 1;
1271 if ( percentiles[i].flag )
1273 percentiles[i].x2 = f->value[0].f;
1274 percentiles[i].x1 = prev_value;
1275 percentiles[i].flag2 = 1;
1281 if ( f->count > 1 && rank - (f->count - 1) > tp )
1283 percentiles[i].x2 = percentiles[i].x1 = f->value[0].f;
1284 percentiles[i].flag2 = 1;
1288 percentiles[i].flag=1;
1294 prev_value = f->value[0].f;
1297 for (i = 0; i < n_percentiles; i++)
1299 /* Catches the case when p == 100% */
1300 if ( ! percentiles[i].flag2 )
1301 percentiles[i].x1 = percentiles[i].x2 = f->value[0].f;
1304 printf("percentile %d (p==%.2f); X1 = %g; X2 = %g\n",
1305 i,percentiles[i].p,percentiles[i].x1,percentiles[i].x2);
1309 for (i = 0; i < n_percentiles; i++)
1311 struct freq_tab *ft = &get_var_freqs (v)->tab;
1315 if ( settings_get_algorithm () != COMPATIBLE )
1317 s = modf((ft->valid_cases - 1) * percentiles[i].p , &dummy);
1321 s = modf((ft->valid_cases + 1) * percentiles[i].p -1, &dummy);
1324 percentiles[i].value = percentiles[i].x1 +
1325 ( percentiles[i].x2 - percentiles[i].x1) * s ;
1329 /* Calculate the mode. */
1332 for (f = ft->valid; f < ft->missing; f++)
1334 if (most_often < f->count)
1336 most_often = f->count;
1337 X_mode = f->value[0].f;
1339 else if (most_often == f->count)
1341 /* A duplicate mode is undefined.
1342 FIXME: keep track of *all* the modes. */
1347 /* Calculate moments. */
1348 m = moments_create (MOMENT_KURTOSIS);
1349 for (f = ft->valid; f < ft->missing; f++)
1350 moments_pass_one (m, f->value[0].f, f->count);
1351 for (f = ft->valid; f < ft->missing; f++)
1352 moments_pass_two (m, f->value[0].f, f->count);
1353 moments_calculate (m, NULL, &d[frq_mean], &d[frq_variance],
1354 &d[frq_skew], &d[frq_kurt]);
1355 moments_destroy (m);
1357 /* Formulas below are taken from _SPSS Statistical Algorithms_. */
1358 d[frq_min] = ft->valid[0].value[0].f;
1359 d[frq_max] = ft->valid[ft->n_valid - 1].value[0].f;
1360 d[frq_mode] = X_mode;
1361 d[frq_range] = d[frq_max] - d[frq_min];
1362 d[frq_sum] = d[frq_mean] * W;
1363 d[frq_stddev] = sqrt (d[frq_variance]);
1364 d[frq_semean] = d[frq_stddev] / sqrt (W);
1365 d[frq_seskew] = calc_seskew (W);
1366 d[frq_sekurt] = calc_sekurt (W);
1369 /* Displays a table of all the statistics requested for variable V. */
1371 dump_statistics (const struct variable *v, bool show_varname,
1372 const struct variable *wv)
1374 const struct fmt_spec *wfmt = wv ? var_get_print_format (wv) : &F_8_0;
1375 struct freq_tab *ft;
1376 double stat_value[frq_n_stats];
1377 struct tab_table *t;
1380 if (var_is_alpha (v))
1382 ft = &get_var_freqs (v)->tab;
1383 if (ft->n_valid == 0)
1385 msg (SW, _("No valid data for variable %s; statistics not displayed."),
1389 calc_stats (v, stat_value);
1391 t = tab_create (3, n_stats + n_percentiles + 2, 0);
1392 tab_dim (t, tab_natural_dimensions);
1394 tab_box (t, TAL_1, TAL_1, -1, -1 , 0 , 0 , 2, tab_nr(t) - 1) ;
1397 tab_vline (t, TAL_1 , 2, 0, tab_nr(t) - 1);
1398 tab_vline (t, TAL_GAP , 1, 0, tab_nr(t) - 1 ) ;
1400 r=2; /* N missing and N valid are always dumped */
1402 for (i = 0; i < frq_n_stats; i++)
1403 if (stats & BIT_INDEX (i))
1405 tab_text (t, 0, r, TAB_LEFT | TAT_TITLE,
1406 gettext (st_name[i].s10));
1407 tab_double (t, 2, r, TAB_NONE, stat_value[i], NULL);
1411 tab_text (t, 0, 0, TAB_LEFT | TAT_TITLE, _("N"));
1412 tab_text (t, 1, 0, TAB_LEFT | TAT_TITLE, _("Valid"));
1413 tab_text (t, 1, 1, TAB_LEFT | TAT_TITLE, _("Missing"));
1415 tab_double (t, 2, 0, TAB_NONE, ft->valid_cases, wfmt);
1416 tab_double (t, 2, 1, TAB_NONE, ft->total_cases - ft->valid_cases, wfmt);
1418 for (i = 0; i < n_percentiles; i++, r++)
1422 tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, _("Percentiles"));
1425 if (percentiles[i].p == 0.5)
1426 tab_text (t, 1, r, TAB_LEFT, _("50 (Median)"));
1428 tab_fixed (t, 1, r, TAB_LEFT, percentiles[i].p * 100, 3, 0);
1429 tab_double (t, 2, r, TAB_NONE, percentiles[i].value,
1430 var_get_print_format (v));
1433 tab_columns (t, SOM_COL_DOWN, 1);
1435 tab_title (t, "%s", var_to_string (v));
1437 tab_flags (t, SOMF_NO_TITLE);
1444 /* Create a gsl_histogram from a freq_tab */
1446 freq_tab_to_hist(const struct freq_tab *ft, const struct variable *var)
1449 double x_min = DBL_MAX;
1450 double x_max = -DBL_MAX;
1452 gsl_histogram *hist;
1453 const double bins = 11;
1455 struct hsh_iterator hi;
1456 struct hsh_table *fh = ft->data;
1459 /* Find out the extremes of the x value */
1460 for ( frq = hsh_first(fh, &hi); frq != 0; frq = hsh_next(fh, &hi) )
1462 if (var_is_value_missing(var, frq->value, MV_ANY))
1465 if ( frq->value[0].f < x_min ) x_min = frq->value[0].f ;
1466 if ( frq->value[0].f > x_max ) x_max = frq->value[0].f ;
1469 hist = histogram_create(bins, x_min, x_max);
1471 for( i = 0 ; i < ft->n_valid ; ++i )
1473 frq = &ft->valid[i];
1474 gsl_histogram_accumulate(hist, frq->value[0].f, frq->count);
1481 static struct slice *
1482 freq_tab_to_slice_array(const struct freq_tab *frq_tab,
1483 const struct variable *var,
1487 /* Allocate an array of slices and fill them from the data in frq_tab
1488 n_slices will contain the number of slices allocated.
1489 The caller is responsible for freeing slices
1491 static struct slice *
1492 freq_tab_to_slice_array(const struct freq_tab *frq_tab,
1493 const struct variable *var,
1497 struct slice *slices;
1499 *n_slices = frq_tab->n_valid;
1501 slices = xnmalloc (*n_slices, sizeof *slices);
1503 for (i = 0 ; i < *n_slices ; ++i )
1505 const struct freq *frq = &frq_tab->valid[i];
1507 ds_init_empty (&slices[i].label);
1508 var_append_value_name (var, frq->value, &slices[i].label);
1509 slices[i].magnetude = frq->count;
1519 do_piechart(const struct variable *var, const struct freq_tab *frq_tab)
1521 struct slice *slices;
1524 slices = freq_tab_to_slice_array(frq_tab, var, &n_slices);
1526 piechart_plot(var_to_string(var), slices, n_slices);
1528 for (i = 0 ; i < n_slices ; ++i )
1530 ds_destroy (&slices[i].label);