1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 1997-9, 2000, 2007, 2009, 2010 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-item.h>
52 #include <output/charts/piechart.h>
53 #include <output/charts/plot-hist.h>
54 #include <output/tab.h>
62 #define _(msgid) gettext (msgid)
63 #define N_(msgid) msgid
70 +format=cond:condense/onepage(*n:onepage_limit,"%s>=0")/!standard,
71 table:limit(n:limit,"%s>0")/notable/!table,
72 labels:!labels/nolabels,
73 sort:!avalue/dvalue/afreq/dfreq,
74 spaces:!single/double,
75 paging:newpage/!oldpage;
76 missing=miss:include/!exclude;
77 barchart(ba_)=:minimum(d:min),
79 scale:freq(*n:freq,"%s>0")/percent(*n:pcnt,"%s>0");
80 piechart(pie_)=:minimum(d:min),
82 missing:missing/!nomissing;
83 histogram(hi_)=:minimum(d:min),
85 scale:freq(*n:freq,"%s>0")/percent(*n:pcnt,"%s>0"),
86 norm:!nonormal/normal,
87 incr:increment(d:inc,"%s>0");
88 hbar(hb_)=:minimum(d:min),
90 scale:freq(*n:freq,"%s>0")/percent(*n:pcnt,"%s>0"),
91 norm:!nonormal/normal,
92 incr:increment(d:inc,"%s>0");
95 +percentiles = double list;
96 +statistics[st_]=1|mean,2|semean,3|median,4|mode,5|stddev,6|variance,
97 7|kurtosis,8|skewness,9|range,10|minimum,11|maximum,12|sum,
98 13|default,14|seskewness,15|sekurtosis,all,none.
106 frq_mean = 0, frq_semean, frq_median, frq_mode, frq_stddev, frq_variance,
107 frq_kurt, frq_sekurt, frq_skew, frq_seskew, frq_range, frq_min, frq_max,
111 /* Description of a statistic. */
114 int st_indx; /* Index into a_statistics[]. */
115 const char *s10; /* Identifying string. */
118 /* Table of statistics, indexed by dsc_*. */
119 static const struct frq_info st_name[frq_n_stats + 1] =
121 {FRQ_ST_MEAN, N_("Mean")},
122 {FRQ_ST_SEMEAN, N_("S.E. Mean")},
123 {FRQ_ST_MEDIAN, N_("Median")},
124 {FRQ_ST_MODE, N_("Mode")},
125 {FRQ_ST_STDDEV, N_("Std Dev")},
126 {FRQ_ST_VARIANCE, N_("Variance")},
127 {FRQ_ST_KURTOSIS, N_("Kurtosis")},
128 {FRQ_ST_SEKURTOSIS, N_("S.E. Kurt")},
129 {FRQ_ST_SKEWNESS, N_("Skewness")},
130 {FRQ_ST_SESKEWNESS, N_("S.E. Skew")},
131 {FRQ_ST_RANGE, N_("Range")},
132 {FRQ_ST_MINIMUM, N_("Minimum")},
133 {FRQ_ST_MAXIMUM, N_("Maximum")},
134 {FRQ_ST_SUM, N_("Sum")},
138 /* Percentiles to calculate. */
142 double p; /* the %ile to be calculated */
143 double value; /* the %ile's value */
144 double x1; /* The datum value <= the percentile */
145 double x2; /* The datum value >= the percentile */
147 int flag2; /* Set to 1 if this percentile value has been found */
148 bool show; /* True to show this percentile in the statistics box. */
152 static void add_percentile (double x, bool show);
154 static struct percentile *percentiles;
155 static int n_percentiles, n_show_percentiles;
157 /* Groups of statistics. */
159 #define frq_default \
160 (BI (frq_mean) | BI (frq_stddev) | BI (frq_min) | BI (frq_max))
162 (BI (frq_sum) | BI(frq_min) | BI(frq_max) \
163 | BI(frq_mean) | BI(frq_semean) | BI(frq_stddev) \
164 | BI(frq_variance) | BI(frq_kurt) | BI(frq_sekurt) \
165 | BI(frq_skew) | BI(frq_seskew) | BI(frq_range) \
166 | BI(frq_range) | BI(frq_mode) | BI(frq_median))
168 /* Statistics; number of statistics. */
169 static unsigned long stats;
172 /* Types of graphs. */
175 GFT_NONE, /* Don't draw graphs. */
176 GFT_BAR, /* Draw bar charts. */
177 GFT_HIST, /* Draw histograms. */
178 GFT_PIE, /* Draw piechart */
179 GFT_HBAR /* Draw bar charts or histograms at our discretion. */
182 /* Parsed command. */
183 static struct cmd_frequencies cmd;
185 /* Summary of the barchart, histogram, and hbar subcommands. */
186 /* FIXME: These should not be mututally exclusive */
187 static int chart; /* NONE/BAR/HIST/HBAR/PIE. */
188 static double min, max; /* Minimum, maximum on y axis. */
189 static int format; /* FREQ/PERCENT: Scaling of y axis. */
190 static double scale, incr; /* FIXME */
191 static int normal; /* FIXME */
193 /* Variables for which to calculate statistics. */
194 static size_t n_variables;
195 static const struct variable **v_variables;
198 static struct pool *data_pool; /* For per-SPLIT FILE group data. */
199 static struct pool *syntax_pool; /* For syntax-related data. */
201 /* Frequency tables. */
203 /* Entire frequency table. */
206 struct hsh_table *data; /* Undifferentiated data. */
207 struct freq_mutable *valid; /* Valid freqs. */
208 int n_valid; /* Number of total freqs. */
209 const struct dictionary *dict; /* The dict from whence entries in the table
212 struct freq_mutable *missing; /* Missing freqs. */
213 int n_missing; /* Number of missing freqs. */
216 double total_cases; /* Sum of weights of all cases. */
217 double valid_cases; /* Sum of weights of valid cases. */
221 /* Per-variable frequency data. */
224 /* Freqency table. */
225 struct freq_tab tab; /* Frequencies table to use. */
228 int n_groups; /* Number of groups. */
229 double *groups; /* Groups. */
232 double stat[frq_n_stats];
234 /* Variable attributes. */
236 struct fmt_spec print;
239 static inline struct var_freqs *
240 get_var_freqs (const struct variable *v)
242 return var_get_aux (v);
245 static void determine_charts (void);
247 static void calc_stats (const struct variable *v, double d[frq_n_stats]);
249 static void precalc (struct casereader *, struct dataset *);
250 static void calc (const struct ccase *, const struct dataset *);
251 static void postcalc (const struct dataset *);
253 static void postprocess_freq_tab (const struct variable *);
254 static void dump_full ( const struct variable *, const struct variable *);
255 static void dump_condensed (const struct variable *, const struct variable *);
256 static void dump_statistics (const struct variable *, bool show_varname, const struct variable *);
257 static void cleanup_freq_tab (const struct variable *);
259 static hsh_compare_func compare_value_numeric_a, compare_value_alpha_a;
260 static hsh_compare_func compare_value_numeric_d, compare_value_alpha_d;
261 static hsh_compare_func compare_freq_numeric_a, compare_freq_alpha_a;
262 static hsh_compare_func compare_freq_numeric_d, compare_freq_alpha_d;
265 static void do_piechart(const struct variable *var,
266 const struct freq_tab *frq_tab);
269 freq_tab_to_hist(const struct freq_tab *ft, const struct variable *var);
273 /* Parser and outline. */
275 static int internal_cmd_frequencies (struct lexer *lexer, struct dataset *ds);
278 cmd_frequencies (struct lexer *lexer, struct dataset *ds)
282 syntax_pool = pool_create ();
283 result = internal_cmd_frequencies (lexer, ds);
284 pool_destroy (syntax_pool);
286 pool_destroy (data_pool);
294 internal_cmd_frequencies (struct lexer *lexer, struct dataset *ds)
296 struct casegrouper *grouper;
297 struct casereader *input, *group;
302 n_show_percentiles = 0;
308 if (!parse_frequencies (lexer, ds, &cmd, NULL))
311 if (cmd.onepage_limit == LONG_MIN)
312 cmd.onepage_limit = 50;
314 /* Figure out statistics to calculate. */
316 if (cmd.a_statistics[FRQ_ST_DEFAULT] || !cmd.sbc_statistics)
317 stats |= frq_default;
318 if (cmd.a_statistics[FRQ_ST_ALL])
320 if (cmd.sort != FRQ_AVALUE && cmd.sort != FRQ_DVALUE)
321 stats &= ~BIT_INDEX (frq_median);
322 for (i = 0; i < frq_n_stats; i++)
323 if (cmd.a_statistics[st_name[i].st_indx])
324 stats |= BIT_INDEX (i);
325 if (stats & frq_kurt)
326 stats |= BIT_INDEX (frq_sekurt);
327 if (stats & frq_skew)
328 stats |= BIT_INDEX (frq_seskew);
330 /* Calculate n_stats. */
332 for (i = 0; i < frq_n_stats; i++)
333 if ((stats & BIT_INDEX (i)))
338 if (chart != GFT_NONE || cmd.sbc_ntiles)
339 cmd.sort = FRQ_AVALUE;
341 /* Work out what percentiles need to be calculated */
342 if ( cmd.sbc_percentiles )
344 for ( i = 0 ; i < MAXLISTS ; ++i )
347 subc_list_double *ptl_list = &cmd.dl_percentiles[i];
348 for ( pl = 0 ; pl < subc_list_double_count(ptl_list); ++pl)
349 add_percentile (subc_list_double_at(ptl_list, pl) / 100.0, true);
352 if ( cmd.sbc_ntiles )
354 for ( i = 0 ; i < cmd.sbc_ntiles ; ++i )
357 for (j = 0; j <= cmd.n_ntiles[i]; ++j )
358 add_percentile (j / (double) cmd.n_ntiles[i], true);
361 if (stats & BIT_INDEX (frq_median))
363 /* Treat the median as the 50% percentile.
364 We output it in the percentiles table as "50 (Median)." */
365 add_percentile (0.5, true);
366 stats &= ~BIT_INDEX (frq_median);
371 input = casereader_create_filter_weight (proc_open (ds), dataset_dict (ds),
373 grouper = casegrouper_create_splits (input, dataset_dict (ds));
374 for (; casegrouper_get_next_group (grouper, &group);
375 casereader_destroy (group))
380 for (; (c = casereader_read (group)) != NULL; case_unref (c))
384 ok = casegrouper_destroy (grouper);
385 ok = proc_commit (ds) && ok;
387 free_frequencies(&cmd);
389 return ok ? CMD_SUCCESS : CMD_CASCADING_FAILURE;
392 /* Figure out which charts the user requested. */
394 determine_charts (void)
396 int count = (!!cmd.sbc_histogram) + (!!cmd.sbc_barchart) +
397 (!!cmd.sbc_hbar) + (!!cmd.sbc_piechart);
407 msg (SW, _("At most one of BARCHART, HISTOGRAM, or HBAR should be "
408 "given. HBAR will be assumed. Argument values will be "
409 "given precedence increasing along the order given."));
411 else if (cmd.sbc_histogram)
413 else if (cmd.sbc_barchart)
415 else if (cmd.sbc_piechart)
426 if (cmd.sbc_barchart)
428 if (cmd.ba_min != SYSMIS)
430 if (cmd.ba_max != SYSMIS)
432 if (cmd.ba_scale == FRQ_FREQ)
437 else if (cmd.ba_scale == FRQ_PERCENT)
439 format = FRQ_PERCENT;
444 if (cmd.sbc_histogram)
446 if (cmd.hi_min != SYSMIS)
448 if (cmd.hi_max != SYSMIS)
450 if (cmd.hi_scale == FRQ_FREQ)
455 else if (cmd.hi_scale == FRQ_PERCENT)
457 format = FRQ_PERCENT;
460 if (cmd.hi_norm != FRQ_NONORMAL )
462 if (cmd.hi_incr == FRQ_INCREMENT)
468 if (cmd.hb_min != SYSMIS)
470 if (cmd.hb_max != SYSMIS)
472 if (cmd.hb_scale == FRQ_FREQ)
477 else if (cmd.hb_scale == FRQ_PERCENT)
479 format = FRQ_PERCENT;
484 if (cmd.hb_incr == FRQ_INCREMENT)
488 if (min != SYSMIS && max != SYSMIS && min >= max)
490 msg (SE, _("MAX must be greater than or equal to MIN, if both are "
491 "specified. However, MIN was specified as %g and MAX as %g. "
492 "MIN and MAX will be ignored."), min, max);
497 /* Add data from case C to the frequency table. */
499 calc (const struct ccase *c, const struct dataset *ds)
501 double weight = dict_get_case_weight (dataset_dict (ds), c, NULL);
504 for (i = 0; i < n_variables; i++)
506 const struct variable *v = v_variables[i];
507 const union value *val = case_data (c, v);
508 struct var_freqs *vf = get_var_freqs (v);
509 struct freq_tab *ft = &vf->tab;
511 struct freq_mutable target;
512 struct freq_mutable **fpp;
515 fpp = (struct freq_mutable **) hsh_probe (ft->data, &target);
518 (*fpp)->count += weight;
521 struct freq_mutable *fp = pool_alloc (data_pool, sizeof *fp);
523 value_init_pool (data_pool, &fp->value, vf->width);
524 value_copy (&fp->value, val, vf->width);
530 /* Prepares each variable that is the target of FREQUENCIES by setting
531 up its hash table. */
533 precalc (struct casereader *input, struct dataset *ds)
538 c = casereader_peek (input, 0);
541 output_split_file_values (ds, c);
545 pool_destroy (data_pool);
546 data_pool = pool_create ();
548 for (i = 0; i < n_variables; i++)
550 const struct variable *v = v_variables[i];
551 struct freq_tab *ft = &get_var_freqs (v)->tab;
553 ft->data = hsh_create (16, compare_freq, hash_freq, NULL, v);
557 /* Finishes up with the variables after frequencies have been
558 calculated. Displays statistics, percentiles, ... */
560 postcalc (const struct dataset *ds)
562 const struct dictionary *dict = dataset_dict (ds);
563 const struct variable *wv = dict_get_weight (dict);
566 for (i = 0; i < n_variables; i++)
568 const struct variable *v = v_variables[i];
569 struct var_freqs *vf = get_var_freqs (v);
570 struct freq_tab *ft = &vf->tab;
572 int dumped_freq_tab = 1;
574 postprocess_freq_tab (v);
576 /* Frequencies tables. */
577 n_categories = ft->n_valid + ft->n_missing;
578 if (cmd.table == FRQ_TABLE
579 || (cmd.table == FRQ_LIMIT && n_categories <= cmd.limit))
583 dump_condensed (v, wv);
589 if (n_categories > cmd.onepage_limit)
590 dump_condensed (v, wv);
602 dump_statistics (v, !dumped_freq_tab, wv);
606 if ( chart == GFT_HIST && var_is_numeric (v) && ft->n_valid > 0)
608 double d[frq_n_stats];
609 struct histogram *hist ;
613 hist = freq_tab_to_hist (ft,v);
615 chart_item_submit (histogram_chart_create (
616 hist->gsl_hist, var_to_string(v),
622 statistic_destroy (&hist->parent);
625 if ( chart == GFT_PIE)
627 do_piechart(v_variables[i], ft);
630 cleanup_freq_tab (v);
635 /* Returns the comparison function that should be used for
636 sorting a frequency table by FRQ_SORT using VAL_TYPE
638 static hsh_compare_func *
639 get_freq_comparator (int frq_sort, enum val_type val_type)
641 bool is_numeric = val_type == VAL_NUMERIC;
645 return is_numeric ? compare_value_numeric_a : compare_value_alpha_a;
647 return is_numeric ? compare_value_numeric_d : compare_value_alpha_d;
649 return is_numeric ? compare_freq_numeric_a : compare_freq_alpha_a;
651 return is_numeric ? compare_freq_numeric_d : compare_freq_alpha_d;
657 /* Returns true iff the value in struct freq_mutable F is non-missing
660 not_missing (const void *f_, const void *v_)
662 const struct freq_mutable *f = f_;
663 const struct variable *v = v_;
665 return !var_is_value_missing (v, &f->value, MV_ANY);
668 /* Summarizes the frequency table data for variable V. */
670 postprocess_freq_tab (const struct variable *v)
672 hsh_compare_func *compare;
676 struct freq_mutable *freqs, *f;
679 ft = &get_var_freqs (v)->tab;
680 compare = get_freq_comparator (cmd.sort, var_get_type (v));
682 /* Extract data from hash table. */
683 count = hsh_count (ft->data);
684 data = hsh_data (ft->data);
686 /* Copy dereferenced data into freqs. */
687 freqs = xnmalloc (count, sizeof *freqs);
688 for (i = 0; i < count; i++)
690 struct freq_mutable *f = data[i];
694 /* Put data into ft. */
696 ft->n_valid = partition (freqs, count, sizeof *freqs, not_missing, v);
697 ft->missing = freqs + ft->n_valid;
698 ft->n_missing = count - ft->n_valid;
701 sort (ft->valid, ft->n_valid, sizeof *ft->valid, compare, v);
702 sort (ft->missing, ft->n_missing, sizeof *ft->missing, compare, v);
704 /* Summary statistics. */
705 ft->valid_cases = 0.0;
706 for(i = 0 ; i < ft->n_valid ; ++i )
709 ft->valid_cases += f->count;
713 ft->total_cases = ft->valid_cases ;
714 for(i = 0 ; i < ft->n_missing ; ++i )
717 ft->total_cases += f->count;
722 /* Frees the frequency table for variable V. */
724 cleanup_freq_tab (const struct variable *v)
726 struct freq_tab *ft = &get_var_freqs (v)->tab;
728 hsh_destroy (ft->data);
731 /* Parses the VARIABLES subcommand, adding to
732 {n_variables,v_variables}. */
734 frq_custom_variables (struct lexer *lexer, struct dataset *ds, struct cmd_frequencies *cmd UNUSED, void *aux UNUSED)
736 size_t old_n_variables = n_variables;
739 lex_match (lexer, '=');
740 if (lex_token (lexer) != T_ALL && (lex_token (lexer) != T_ID
741 || dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) == NULL))
744 if (!parse_variables_const (lexer, dataset_dict (ds), &v_variables, &n_variables,
745 PV_APPEND | PV_NO_SCRATCH))
748 for (i = old_n_variables; i < n_variables; i++)
750 const struct variable *v = v_variables[i];
751 struct var_freqs *vf;
753 if (var_get_aux (v) != NULL)
755 msg (SE, _("Variable %s specified multiple times on VARIABLES "
756 "subcommand."), var_get_name (v));
759 vf = var_attach_aux (v, xmalloc (sizeof *vf), var_dtor_free);
760 vf->tab.valid = vf->tab.missing = NULL;
761 vf->tab.dict = dataset_dict (ds);
764 vf->width = var_get_width (v);
765 vf->print = *var_get_print_format (v);
770 /* Parses the GROUPED subcommand, setting the n_grouped, grouped
771 fields of specified variables. */
773 frq_custom_grouped (struct lexer *lexer, struct dataset *ds, struct cmd_frequencies *cmd UNUSED, void *aux UNUSED)
775 lex_match (lexer, '=');
776 if ((lex_token (lexer) == T_ID && dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) != NULL)
777 || lex_token (lexer) == T_ID)
782 /* Max, current size of list; list itself. */
788 const struct variable **v;
790 if (!parse_variables_const (lexer, dataset_dict (ds), &v, &n,
791 PV_NO_DUPLICATE | PV_NUMERIC))
793 if (lex_match (lexer, '('))
797 while (lex_integer (lexer))
802 dl = pool_nrealloc (syntax_pool, dl, ml, sizeof *dl);
804 dl[nl++] = lex_tokval (lexer);
806 lex_match (lexer, ',');
808 /* Note that nl might still be 0 and dl might still be
809 NULL. That's okay. */
810 if (!lex_match (lexer, ')'))
813 msg (SE, _("`)' expected after GROUPED interval list."));
823 for (i = 0; i < n; i++)
824 if (var_get_aux (v[i]) == NULL)
825 msg (SE, _("Variables %s specified on GROUPED but not on "
826 "VARIABLES."), var_get_name (v[i]));
829 struct var_freqs *vf = get_var_freqs (v[i]);
831 if (vf->groups != NULL)
832 msg (SE, _("Variables %s specified multiple times on GROUPED "
833 "subcommand."), var_get_name (v[i]));
841 if (!lex_match (lexer, '/'))
843 if ((lex_token (lexer) != T_ID || dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) != NULL)
844 && lex_token (lexer) != T_ALL)
846 lex_put_back (lexer, '/');
854 /* Adds X to the list of percentiles, keeping the list in proper
855 order. If SHOW is true, the percentile will be shown in the statistics
856 box, otherwise it will be hidden. */
858 add_percentile (double x, bool show)
862 for (i = 0; i < n_percentiles; i++)
864 /* Do nothing if it's already in the list */
865 if ( fabs(x - percentiles[i].p) < DBL_EPSILON )
867 if (show && !percentiles[i].show)
869 n_show_percentiles++;
870 percentiles[i].show = true;
875 if (x < percentiles[i].p)
879 if (i >= n_percentiles || x != percentiles[i].p)
881 percentiles = pool_nrealloc (syntax_pool, percentiles,
882 n_percentiles + 1, sizeof *percentiles);
883 insert_element (percentiles, n_percentiles, sizeof *percentiles, i);
884 percentiles[i].p = x;
885 percentiles[i].show = show;
888 n_show_percentiles++;
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_mutable *a = a_;
899 const struct freq_mutable *b = b_;
901 if (a->value.f > b->value.f)
903 else if (a->value.f < b->value.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_mutable *a = a_;
914 const struct freq_mutable *b = b_;
915 const struct variable *v = v_;
916 struct var_freqs *vf = get_var_freqs (v);
918 return value_compare_3way (&a->value, &b->value, 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_mutable *a = a_;
941 const struct freq_mutable *b = b_;
943 if (a->count > b->count)
945 else if (a->count < b->count)
948 if (a->value.f > b->value.f)
950 else if (a->value.f < b->value.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_mutable *a = a_;
962 const struct freq_mutable *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 value_compare_3way (&a->value, &b->value, 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_mutable *a = a_;
980 const struct freq_mutable *b = b_;
982 if (a->count > b->count)
984 else if (a->count < b->count)
987 if (a->value.f > b->value.f)
989 else if (a->value.f < b->value.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_mutable *a = a_;
1001 const struct freq_mutable *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 value_compare_3way (&a->value, &b->value, vf->width);
1013 /* Frequency table display. */
1015 /* Displays a full frequency table for variable V. */
1017 dump_full (const struct variable *v, const struct variable *wv)
1019 const struct fmt_spec *wfmt = wv ? var_get_print_format (wv) : &F_8_0;
1021 struct var_freqs *vf;
1022 struct freq_tab *ft;
1023 struct freq_mutable *f;
1024 struct tab_table *t;
1026 double cum_total = 0.0;
1027 double cum_freq = 0.0;
1029 static const char *headings[] = {
1033 N_("Valid Percent"),
1037 const bool lab = (cmd.labels == FRQ_LABELS);
1039 vf = get_var_freqs (v);
1041 n_categories = ft->n_valid + ft->n_missing;
1042 t = tab_create (5 + lab, n_categories + 2);
1043 tab_headers (t, 0, 0, 1, 0);
1046 tab_text (t, 0, 0, TAB_CENTER | TAT_TITLE, _("Value Label"));
1048 for (x = 0; x < 5; x++)
1049 tab_text (t, lab + x, 0, TAB_CENTER | TAT_TITLE, gettext (headings[x]));
1052 for (f = ft->valid; f < ft->missing; f++)
1054 double percent, valid_percent;
1056 cum_freq += f->count;
1058 percent = f->count / ft->total_cases * 100.0;
1059 valid_percent = f->count / ft->valid_cases * 100.0;
1060 cum_total += valid_percent;
1064 const char *label = var_lookup_value_label (v, &f->value);
1066 tab_text (t, 0, r, TAB_LEFT, label);
1069 tab_value (t, 0 + lab, r, TAB_NONE, &f->value, ft->dict, &vf->print);
1070 tab_double (t, 1 + lab, r, TAB_NONE, f->count, wfmt);
1071 tab_double (t, 2 + lab, r, TAB_NONE, percent, NULL);
1072 tab_double (t, 3 + lab, r, TAB_NONE, valid_percent, NULL);
1073 tab_double (t, 4 + lab, r, TAB_NONE, cum_total, NULL);
1076 for (; f < &ft->valid[n_categories]; f++)
1078 cum_freq += f->count;
1082 const char *label = var_lookup_value_label (v, &f->value);
1084 tab_text (t, 0, r, TAB_LEFT, label);
1087 tab_value (t, 0 + lab, r, TAB_NONE, &f->value, ft->dict, &vf->print);
1088 tab_double (t, 1 + lab, r, TAB_NONE, f->count, wfmt);
1089 tab_double (t, 2 + lab, r, TAB_NONE,
1090 f->count / ft->total_cases * 100.0, NULL);
1091 tab_text (t, 3 + lab, r, TAB_NONE, _("Missing"));
1095 tab_box (t, TAL_1, TAL_1,
1096 cmd.spaces == FRQ_SINGLE ? -1 : TAL_GAP, TAL_1,
1098 tab_hline (t, TAL_2, 0, 4 + lab, 1);
1099 tab_hline (t, TAL_2, 0, 4 + lab, r);
1100 tab_joint_text (t, 0, r, 0 + lab, r, TAB_RIGHT | TAT_TITLE, _("Total"));
1101 tab_vline (t, TAL_0, 1, r, r);
1102 tab_double (t, 1 + lab, r, TAB_NONE, cum_freq, wfmt);
1103 tab_fixed (t, 2 + lab, r, TAB_NONE, 100.0, 5, 1);
1104 tab_fixed (t, 3 + lab, r, TAB_NONE, 100.0, 5, 1);
1106 tab_title (t, "%s", var_to_string (v));
1110 /* Display condensed frequency table for variable V. */
1112 dump_condensed (const struct variable *v, const struct variable *wv)
1114 const struct fmt_spec *wfmt = wv ? var_get_print_format (wv) : &F_8_0;
1116 struct var_freqs *vf;
1117 struct freq_tab *ft;
1118 struct freq_mutable *f;
1119 struct tab_table *t;
1121 double cum_total = 0.0;
1123 vf = get_var_freqs (v);
1125 n_categories = ft->n_valid + ft->n_missing;
1126 t = tab_create (4, n_categories + 2);
1128 tab_headers (t, 0, 0, 2, 0);
1129 tab_text (t, 0, 1, TAB_CENTER | TAT_TITLE, _("Value"));
1130 tab_text (t, 1, 1, TAB_CENTER | TAT_TITLE, _("Freq"));
1131 tab_text (t, 2, 1, TAB_CENTER | TAT_TITLE, _("Pct"));
1132 tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("Cum"));
1133 tab_text (t, 3, 1, TAB_CENTER | TAT_TITLE, _("Pct"));
1136 for (f = ft->valid; f < ft->missing; f++)
1140 percent = f->count / ft->total_cases * 100.0;
1141 cum_total += f->count / ft->valid_cases * 100.0;
1143 tab_value (t, 0, r, TAB_NONE, &f->value, ft->dict, &vf->print);
1144 tab_double (t, 1, r, TAB_NONE, f->count, wfmt);
1145 tab_double (t, 2, r, TAB_NONE, percent, NULL);
1146 tab_double (t, 3, r, TAB_NONE, cum_total, NULL);
1149 for (; f < &ft->valid[n_categories]; f++)
1151 tab_value (t, 0, r, TAB_NONE, &f->value, ft->dict, &vf->print);
1152 tab_double (t, 1, r, TAB_NONE, f->count, wfmt);
1153 tab_double (t, 2, r, TAB_NONE,
1154 f->count / ft->total_cases * 100.0, NULL);
1158 tab_box (t, TAL_1, TAL_1,
1159 cmd.spaces == FRQ_SINGLE ? -1 : TAL_GAP, TAL_1,
1161 tab_hline (t, TAL_2, 0, 3, 2);
1162 tab_title (t, "%s", var_to_string (v));
1166 /* Statistical display. */
1168 /* Calculates all the pertinent statistics for variable V, putting them in
1171 calc_stats (const struct variable *v, double d[frq_n_stats])
1173 struct freq_tab *ft = &get_var_freqs (v)->tab;
1174 double W = ft->valid_cases;
1176 struct freq_mutable *f=0;
1184 /* Calculate percentiles. */
1186 assert (ft->n_valid > 0);
1188 for (i = 0; i < n_percentiles; i++)
1190 percentiles[i].flag = 0;
1191 percentiles[i].flag2 = 0;
1195 for (idx = 0; idx < ft->n_valid; ++idx)
1197 static double prev_value = SYSMIS;
1198 f = &ft->valid[idx];
1200 for (i = 0; i < n_percentiles; i++)
1203 if ( percentiles[i].flag2 ) continue ;
1205 if ( settings_get_algorithm () != COMPATIBLE )
1207 (ft->valid_cases - 1) * percentiles[i].p;
1210 (ft->valid_cases + 1) * percentiles[i].p - 1;
1212 if ( percentiles[i].flag )
1214 percentiles[i].x2 = f->value.f;
1215 percentiles[i].x1 = prev_value;
1216 percentiles[i].flag2 = 1;
1222 if ( f->count > 1 && rank - (f->count - 1) > tp )
1224 percentiles[i].x2 = percentiles[i].x1 = f->value.f;
1225 percentiles[i].flag2 = 1;
1229 percentiles[i].flag=1;
1235 prev_value = f->value.f;
1238 for (i = 0; i < n_percentiles; i++)
1240 /* Catches the case when p == 100% */
1241 if ( ! percentiles[i].flag2 )
1242 percentiles[i].x1 = percentiles[i].x2 = f->value.f;
1245 printf("percentile %d (p==%.2f); X1 = %g; X2 = %g\n",
1246 i,percentiles[i].p,percentiles[i].x1,percentiles[i].x2);
1250 for (i = 0; i < n_percentiles; i++)
1252 struct freq_tab *ft = &get_var_freqs (v)->tab;
1256 if ( settings_get_algorithm () != COMPATIBLE )
1258 s = modf((ft->valid_cases - 1) * percentiles[i].p , &dummy);
1262 s = modf((ft->valid_cases + 1) * percentiles[i].p -1, &dummy);
1265 percentiles[i].value = percentiles[i].x1 +
1266 ( percentiles[i].x2 - percentiles[i].x1) * s ;
1270 /* Calculate the mode. */
1273 for (f = ft->valid; f < ft->missing; f++)
1275 if (most_often < f->count)
1277 most_often = f->count;
1278 X_mode = f->value.f;
1280 else if (most_often == f->count)
1282 /* A duplicate mode is undefined.
1283 FIXME: keep track of *all* the modes. */
1288 /* Calculate moments. */
1289 m = moments_create (MOMENT_KURTOSIS);
1290 for (f = ft->valid; f < ft->missing; f++)
1291 moments_pass_one (m, f->value.f, f->count);
1292 for (f = ft->valid; f < ft->missing; f++)
1293 moments_pass_two (m, f->value.f, f->count);
1294 moments_calculate (m, NULL, &d[frq_mean], &d[frq_variance],
1295 &d[frq_skew], &d[frq_kurt]);
1296 moments_destroy (m);
1298 /* Formulas below are taken from _SPSS Statistical Algorithms_. */
1299 d[frq_min] = ft->valid[0].value.f;
1300 d[frq_max] = ft->valid[ft->n_valid - 1].value.f;
1301 d[frq_mode] = X_mode;
1302 d[frq_range] = d[frq_max] - d[frq_min];
1303 d[frq_sum] = d[frq_mean] * W;
1304 d[frq_stddev] = sqrt (d[frq_variance]);
1305 d[frq_semean] = d[frq_stddev] / sqrt (W);
1306 d[frq_seskew] = calc_seskew (W);
1307 d[frq_sekurt] = calc_sekurt (W);
1310 /* Displays a table of all the statistics requested for variable V. */
1312 dump_statistics (const struct variable *v, bool show_varname,
1313 const struct variable *wv)
1315 const struct fmt_spec *wfmt = wv ? var_get_print_format (wv) : &F_8_0;
1316 struct freq_tab *ft;
1317 double stat_value[frq_n_stats];
1318 struct tab_table *t;
1321 if (var_is_alpha (v))
1323 ft = &get_var_freqs (v)->tab;
1324 if (ft->n_valid == 0)
1326 msg (SW, _("No valid data for variable %s; statistics not displayed."),
1330 calc_stats (v, stat_value);
1332 t = tab_create (3, n_stats + n_show_percentiles + 2);
1334 tab_box (t, TAL_1, TAL_1, -1, -1 , 0 , 0 , 2, tab_nr(t) - 1) ;
1337 tab_vline (t, TAL_1 , 2, 0, tab_nr(t) - 1);
1338 tab_vline (t, TAL_GAP , 1, 0, tab_nr(t) - 1 ) ;
1340 r=2; /* N missing and N valid are always dumped */
1342 for (i = 0; i < frq_n_stats; i++)
1343 if (stats & BIT_INDEX (i))
1345 tab_text (t, 0, r, TAB_LEFT | TAT_TITLE,
1346 gettext (st_name[i].s10));
1347 tab_double (t, 2, r, TAB_NONE, stat_value[i], NULL);
1351 tab_text (t, 0, 0, TAB_LEFT | TAT_TITLE, _("N"));
1352 tab_text (t, 1, 0, TAB_LEFT | TAT_TITLE, _("Valid"));
1353 tab_text (t, 1, 1, TAB_LEFT | TAT_TITLE, _("Missing"));
1355 tab_double (t, 2, 0, TAB_NONE, ft->valid_cases, wfmt);
1356 tab_double (t, 2, 1, TAB_NONE, ft->total_cases - ft->valid_cases, wfmt);
1358 for (i = 0; i < n_percentiles; i++, r++)
1360 if (!percentiles[i].show)
1365 tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, _("Percentiles"));
1368 if (percentiles[i].p == 0.5)
1369 tab_text (t, 1, r, TAB_LEFT, _("50 (Median)"));
1371 tab_fixed (t, 1, r, TAB_LEFT, percentiles[i].p * 100, 3, 0);
1372 tab_double (t, 2, r, TAB_NONE, percentiles[i].value,
1373 var_get_print_format (v));
1377 tab_title (t, "%s", var_to_string (v));
1384 /* Create a gsl_histogram from a freq_tab */
1386 freq_tab_to_hist (const struct freq_tab *ft, const struct variable *var)
1389 double x_min = DBL_MAX;
1390 double x_max = -DBL_MAX;
1392 struct histogram *hist;
1395 struct hsh_iterator hi;
1396 struct hsh_table *fh = ft->data;
1397 struct freq_mutable *frq;
1399 /* Find out the extremes of the x value */
1400 for ( frq = hsh_first(fh, &hi); frq != 0; frq = hsh_next(fh, &hi) )
1402 if (var_is_value_missing(var, &frq->value, MV_ANY))
1405 if ( frq->value.f < x_min ) x_min = frq->value.f ;
1406 if ( frq->value.f > x_max ) x_max = frq->value.f ;
1409 /* Sturges' formula. */
1410 bins = ceil (log (ft->valid_cases) / log (2) + 1);
1414 hist = histogram_create (bins, x_min, x_max);
1416 for( i = 0 ; i < ft->n_valid ; ++i )
1418 frq = &ft->valid[i];
1419 histogram_add (hist, frq->value.f, frq->count);
1426 static struct slice *
1427 freq_tab_to_slice_array(const struct freq_tab *frq_tab,
1428 const struct variable *var,
1432 /* Allocate an array of slices and fill them from the data in frq_tab
1433 n_slices will contain the number of slices allocated.
1434 The caller is responsible for freeing slices
1436 static struct slice *
1437 freq_tab_to_slice_array(const struct freq_tab *frq_tab,
1438 const struct variable *var,
1442 struct slice *slices;
1444 *n_slices = frq_tab->n_valid;
1446 slices = xnmalloc (*n_slices, sizeof *slices);
1448 for (i = 0 ; i < *n_slices ; ++i )
1450 const struct freq_mutable *frq = &frq_tab->valid[i];
1452 ds_init_empty (&slices[i].label);
1453 var_append_value_name (var, &frq->value, &slices[i].label);
1454 slices[i].magnitude = frq->count;
1464 do_piechart(const struct variable *var, const struct freq_tab *frq_tab)
1466 struct slice *slices;
1469 slices = freq_tab_to_slice_array(frq_tab, var, &n_slices);
1471 chart_item_submit (piechart_create (var_to_string(var), slices, n_slices));
1473 for (i = 0 ; i < n_slices ; ++i )
1474 ds_destroy (&slices[i].label);