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/>. */
21 #include <gsl/gsl_histogram.h>
23 #include "data/case.h"
24 #include "data/casegrouper.h"
25 #include "data/casereader.h"
26 #include "data/dictionary.h"
27 #include "data/format.h"
28 #include "data/procedure.h"
29 #include "data/settings.h"
30 #include "data/value-labels.h"
31 #include "data/variable.h"
32 #include "language/command.h"
33 #include "language/dictionary/split-file.h"
34 #include "language/lexer/lexer.h"
35 #include "language/stats/freq.h"
36 #include "libpspp/array.h"
37 #include "libpspp/bit-vector.h"
38 #include "libpspp/compiler.h"
39 #include "libpspp/hmap.h"
40 #include "libpspp/message.h"
41 #include "libpspp/misc.h"
42 #include "libpspp/pool.h"
43 #include "libpspp/str.h"
44 #include "math/histogram.h"
45 #include "math/moments.h"
46 #include "output/chart-item.h"
47 #include "output/charts/piechart.h"
48 #include "output/charts/plot-hist.h"
49 #include "output/tab.h"
51 #include "gl/minmax.h"
52 #include "gl/xalloc.h"
55 #define _(msgid) gettext (msgid)
56 #define N_(msgid) msgid
63 +format=table:limit(n:limit,"%s>0")/notable/!table,
64 sort:!avalue/dvalue/afreq/dfreq;
65 missing=miss:include/!exclude;
66 barchart(ba_)=:minimum(d:min),
68 scale:freq(*n:freq,"%s>0")/percent(*n:pcnt,"%s>0");
69 piechart(pie_)=:minimum(d:min),
71 missing:missing/!nomissing,
73 histogram(hi_)=:minimum(d:min),
75 scale:freq(*n:freq,"%s>0")/percent(*n:pcnt,"%s>0"),
76 norm:!nonormal/normal;
79 +percentiles = double list;
80 +statistics[st_]=mean,semean,median,mode,stddev,variance,
81 kurtosis,skewness,range,minimum,maximum,sum,
82 default,seskewness,sekurtosis,all,none.
90 FRQ_MEAN, FRQ_SEMEAN, FRQ_MEDIAN, FRQ_MODE, FRQ_STDDEV, FRQ_VARIANCE,
91 FRQ_KURT, FRQ_SEKURT, FRQ_SKEW, FRQ_SESKEW, FRQ_RANGE, FRQ_MIN, FRQ_MAX,
95 /* Description of a statistic. */
98 int st_indx; /* Index into a_statistics[]. */
99 const char *s10; /* Identifying string. */
102 /* Table of statistics, indexed by dsc_*. */
103 static const struct frq_info st_name[FRQ_N_STATS + 1] =
105 {FRQ_ST_MEAN, N_("Mean")},
106 {FRQ_ST_SEMEAN, N_("S.E. Mean")},
107 {FRQ_ST_MEDIAN, N_("Median")},
108 {FRQ_ST_MODE, N_("Mode")},
109 {FRQ_ST_STDDEV, N_("Std Dev")},
110 {FRQ_ST_VARIANCE, N_("Variance")},
111 {FRQ_ST_KURTOSIS, N_("Kurtosis")},
112 {FRQ_ST_SEKURTOSIS, N_("S.E. Kurt")},
113 {FRQ_ST_SKEWNESS, N_("Skewness")},
114 {FRQ_ST_SESKEWNESS, N_("S.E. Skew")},
115 {FRQ_ST_RANGE, N_("Range")},
116 {FRQ_ST_MINIMUM, N_("Minimum")},
117 {FRQ_ST_MAXIMUM, N_("Maximum")},
118 {FRQ_ST_SUM, N_("Sum")},
122 /* Percentiles to calculate. */
126 double p; /* the %ile to be calculated */
127 double value; /* the %ile's value */
128 double x1; /* The datum value <= the percentile */
129 double x2; /* The datum value >= the percentile */
131 int flag2; /* Set to 1 if this percentile value has been found */
132 bool show; /* True to show this percentile in the statistics box. */
136 static void add_percentile (double x, bool show);
138 static struct percentile *percentiles;
139 static int n_percentiles, n_show_percentiles;
141 /* Groups of statistics. */
143 #define FRQ_DEFAULT \
144 (BI (FRQ_MEAN) | BI (FRQ_STDDEV) | BI (FRQ_MIN) | BI (FRQ_MAX))
146 (BI (FRQ_SUM) | BI(FRQ_MIN) | BI(FRQ_MAX) \
147 | BI(FRQ_MEAN) | BI(FRQ_SEMEAN) | BI(FRQ_STDDEV) \
148 | BI(FRQ_VARIANCE) | BI(FRQ_KURT) | BI(FRQ_SEKURT) \
149 | BI(FRQ_SKEW) | BI(FRQ_SESKEW) | BI(FRQ_RANGE) \
150 | BI(FRQ_RANGE) | BI(FRQ_MODE) | BI(FRQ_MEDIAN))
152 /* Statistics; number of statistics. */
153 static unsigned long stats;
158 double x_min; /* X axis minimum value. */
159 double x_max; /* X axis maximum value. */
160 int y_scale; /* Y axis scale: FRQ_FREQ or FRQ_PERCENT. */
162 /* Histograms only. */
163 double y_max; /* Y axis maximum value. */
164 bool draw_normal; /* Whether to draw normal curve. */
166 /* Pie charts only. */
167 bool include_missing; /* Whether to include missing values. */
170 /* Histogram and pie chart settings. */
171 static struct frq_chart hist, pie;
173 /* Parsed command. */
174 static struct cmd_frequencies cmd;
176 /* Variables for which to calculate statistics. */
177 static size_t n_variables;
178 static const struct variable **v_variables;
181 static struct pool *data_pool; /* For per-SPLIT FILE group data. */
182 static struct pool *syntax_pool; /* For syntax-related data. */
184 /* Frequency tables. */
186 /* Entire frequency table. */
189 struct hmap data; /* Hash table for accumulating counts. */
190 struct freq *valid; /* Valid freqs. */
191 int n_valid; /* Number of total freqs. */
192 const struct dictionary *dict; /* Source of entries in the table. */
194 struct freq *missing; /* Missing freqs. */
195 int n_missing; /* Number of missing freqs. */
198 double total_cases; /* Sum of weights of all cases. */
199 double valid_cases; /* Sum of weights of valid cases. */
202 /* Per-variable frequency data. */
205 /* Freqency table. */
206 struct freq_tab tab; /* Frequencies table to use. */
209 int n_groups; /* Number of groups. */
210 double *groups; /* Groups. */
213 double stat[FRQ_N_STATS];
215 /* Variable attributes. */
217 struct fmt_spec print;
220 static inline struct var_freqs *
221 get_var_freqs (const struct variable *v)
223 return var_get_aux (v);
226 static void determine_charts (void);
228 static void calc_stats (const struct variable *v, double d[FRQ_N_STATS]);
230 static void precalc (struct casereader *, struct dataset *);
231 static void calc (const struct ccase *, const struct dataset *);
232 static void postcalc (const struct dataset *);
234 static void postprocess_freq_tab (const struct variable *);
235 static void dump_freq_table (const struct variable *, const struct variable *);
236 static void dump_statistics (const struct variable *, const struct variable *);
237 static void cleanup_freq_tab (const struct variable *);
239 static algo_compare_func compare_value_numeric_a, compare_value_alpha_a;
240 static algo_compare_func compare_value_numeric_d, compare_value_alpha_d;
241 static algo_compare_func compare_freq_numeric_a, compare_freq_alpha_a;
242 static algo_compare_func compare_freq_numeric_d, compare_freq_alpha_d;
245 static void do_piechart(const struct variable *var,
246 const struct freq_tab *frq_tab);
249 freq_tab_to_hist(const struct freq_tab *ft, const struct variable *var);
253 /* Parser and outline. */
255 static int internal_cmd_frequencies (struct lexer *lexer, struct dataset *ds);
258 cmd_frequencies (struct lexer *lexer, struct dataset *ds)
262 syntax_pool = pool_create ();
263 result = internal_cmd_frequencies (lexer, ds);
264 pool_destroy (syntax_pool);
266 pool_destroy (data_pool);
274 internal_cmd_frequencies (struct lexer *lexer, struct dataset *ds)
276 struct casegrouper *grouper;
277 struct casereader *input, *group;
282 n_show_percentiles = 0;
288 if (!parse_frequencies (lexer, ds, &cmd, NULL))
291 /* Figure out statistics to calculate. */
293 if (cmd.a_statistics[FRQ_ST_DEFAULT] || !cmd.sbc_statistics)
294 stats |= FRQ_DEFAULT;
295 if (cmd.a_statistics[FRQ_ST_ALL])
297 if (cmd.sort != FRQ_AVALUE && cmd.sort != FRQ_DVALUE)
298 stats &= ~BIT_INDEX (FRQ_MEDIAN);
299 for (i = 0; i < FRQ_N_STATS; i++)
300 if (cmd.a_statistics[st_name[i].st_indx])
301 stats |= BIT_INDEX (i);
302 if (stats & FRQ_KURT)
303 stats |= BIT_INDEX (FRQ_SEKURT);
304 if (stats & FRQ_SKEW)
305 stats |= BIT_INDEX (FRQ_SESKEW);
307 /* Calculate n_stats. */
309 for (i = 0; i < FRQ_N_STATS; i++)
310 if ((stats & BIT_INDEX (i)))
315 if (cmd.sbc_histogram || cmd.sbc_piechart || cmd.sbc_ntiles)
316 cmd.sort = FRQ_AVALUE;
318 /* Work out what percentiles need to be calculated */
319 if ( cmd.sbc_percentiles )
321 for ( i = 0 ; i < MAXLISTS ; ++i )
324 subc_list_double *ptl_list = &cmd.dl_percentiles[i];
325 for ( pl = 0 ; pl < subc_list_double_count(ptl_list); ++pl)
326 add_percentile (subc_list_double_at(ptl_list, pl) / 100.0, true);
329 if ( cmd.sbc_ntiles )
331 for ( i = 0 ; i < cmd.sbc_ntiles ; ++i )
334 for (j = 0; j <= cmd.n_ntiles[i]; ++j )
335 add_percentile (j / (double) cmd.n_ntiles[i], true);
338 if (stats & BIT_INDEX (FRQ_MEDIAN))
340 /* Treat the median as the 50% percentile.
341 We output it in the percentiles table as "50 (Median)." */
342 add_percentile (0.5, true);
343 stats &= ~BIT_INDEX (FRQ_MEDIAN);
346 if (cmd.sbc_histogram)
348 add_percentile (0.25, false);
349 add_percentile (0.75, false);
353 input = casereader_create_filter_weight (proc_open (ds), dataset_dict (ds),
355 grouper = casegrouper_create_splits (input, dataset_dict (ds));
356 for (; casegrouper_get_next_group (grouper, &group);
357 casereader_destroy (group))
362 for (; (c = casereader_read (group)) != NULL; case_unref (c))
366 ok = casegrouper_destroy (grouper);
367 ok = proc_commit (ds) && ok;
369 free_frequencies(&cmd);
371 return ok ? CMD_SUCCESS : CMD_CASCADING_FAILURE;
374 /* Figure out which charts the user requested. */
376 determine_charts (void)
378 if (cmd.sbc_barchart)
379 msg (SW, _("Bar charts are not implemented."));
381 if (cmd.sbc_histogram)
383 hist.x_min = cmd.hi_min;
384 hist.x_max = cmd.hi_max;
385 hist.y_scale = cmd.hi_scale;
386 hist.y_max = cmd.hi_scale == FRQ_FREQ ? cmd.hi_freq : cmd.hi_pcnt;
387 hist.draw_normal = cmd.hi_norm != FRQ_NONORMAL;
388 hist.include_missing = false;
390 if (hist.x_min != SYSMIS && hist.x_max != SYSMIS
391 && hist.x_min >= hist.x_max)
393 msg (SE, _("MAX for histogram must be greater than or equal to MIN, "
394 "but MIN was specified as %.15g and MAX as %.15g. "
395 "MIN and MAX will be ignored."), hist.x_min, hist.x_max);
396 hist.x_min = hist.x_max = SYSMIS;
400 if (cmd.sbc_piechart)
402 pie.x_min = cmd.pie_min;
403 pie.x_max = cmd.pie_max;
404 pie.y_scale = cmd.pie_scale;
405 pie.include_missing = cmd.pie_missing == FRQ_MISSING;
407 if (pie.x_min != SYSMIS && pie.x_max != SYSMIS
408 && pie.x_min >= pie.x_max)
410 msg (SE, _("MAX for pie chart must be greater than or equal to MIN, "
411 "but MIN was specified as %.15g and MAX as %.15g. "
412 "MIN and MAX will be ignored."), pie.x_min, pie.x_max);
413 pie.x_min = pie.x_max = SYSMIS;
419 /* Add data from case C to the frequency table. */
421 calc (const struct ccase *c, const struct dataset *ds)
423 double weight = dict_get_case_weight (dataset_dict (ds), c, NULL);
426 for (i = 0; i < n_variables; i++)
428 const struct variable *var = v_variables[i];
429 int width = var_get_width (var);
431 const union value *value = case_data (c, var);
432 size_t hash = value_hash (value, width, 0);
434 struct hmap *hmap = &get_var_freqs (var)->tab.data;
437 f = freq_hmap_search (hmap, value, width, hash);
439 f = freq_hmap_insert (hmap, value, width, hash);
445 /* Prepares each variable that is the target of FREQUENCIES by setting
446 up its hash table. */
448 precalc (struct casereader *input, struct dataset *ds)
453 c = casereader_peek (input, 0);
456 output_split_file_values (ds, c);
460 pool_destroy (data_pool);
461 data_pool = pool_create ();
463 for (i = 0; i < n_variables; i++)
465 const struct variable *v = v_variables[i];
466 struct freq_tab *ft = &get_var_freqs (v)->tab;
468 hmap_init (&ft->data);
472 /* Finishes up with the variables after frequencies have been
473 calculated. Displays statistics, percentiles, ... */
475 postcalc (const struct dataset *ds)
477 const struct dictionary *dict = dataset_dict (ds);
478 const struct variable *wv = dict_get_weight (dict);
481 for (i = 0; i < n_variables; i++)
483 const struct variable *v = v_variables[i];
484 struct var_freqs *vf = get_var_freqs (v);
485 struct freq_tab *ft = &vf->tab;
488 postprocess_freq_tab (v);
490 /* Frequencies tables. */
491 n_categories = ft->n_valid + ft->n_missing;
492 if (cmd.table == FRQ_TABLE
493 || (cmd.table == FRQ_LIMIT && n_categories <= cmd.limit))
494 dump_freq_table (v, wv);
498 dump_statistics (v, wv);
500 if (cmd.sbc_histogram && var_is_numeric (v) && ft->n_valid > 0)
502 double d[FRQ_N_STATS];
503 struct histogram *histogram;
507 histogram = freq_tab_to_hist (ft, v);
509 chart_item_submit (histogram_chart_create (
510 histogram->gsl_hist, var_to_string(v),
516 statistic_destroy (&histogram->parent);
519 if (cmd.sbc_piechart)
520 do_piechart(v_variables[i], ft);
522 cleanup_freq_tab (v);
527 /* Returns the comparison function that should be used for
528 sorting a frequency table by FRQ_SORT using VAL_TYPE
530 static algo_compare_func *
531 get_freq_comparator (int frq_sort, enum val_type val_type)
533 bool is_numeric = val_type == VAL_NUMERIC;
537 return is_numeric ? compare_value_numeric_a : compare_value_alpha_a;
539 return is_numeric ? compare_value_numeric_d : compare_value_alpha_d;
541 return is_numeric ? compare_freq_numeric_a : compare_freq_alpha_a;
543 return is_numeric ? compare_freq_numeric_d : compare_freq_alpha_d;
549 /* Returns true iff the value in struct freq F is non-missing
552 not_missing (const void *f_, const void *v_)
554 const struct freq *f = f_;
555 const struct variable *v = v_;
557 return !var_is_value_missing (v, &f->value, MV_ANY);
560 /* Summarizes the frequency table data for variable V. */
562 postprocess_freq_tab (const struct variable *v)
564 algo_compare_func *compare;
567 struct freq *freqs, *f;
570 ft = &get_var_freqs (v)->tab;
571 compare = get_freq_comparator (cmd.sort, var_get_type (v));
573 /* Extract data from hash table. */
574 count = hmap_count (&ft->data);
575 freqs = freq_hmap_extract (&ft->data);
577 /* Put data into ft. */
579 ft->n_valid = partition (freqs, count, sizeof *freqs, not_missing, v);
580 ft->missing = freqs + ft->n_valid;
581 ft->n_missing = count - ft->n_valid;
584 sort (ft->valid, ft->n_valid, sizeof *ft->valid, compare, v);
585 sort (ft->missing, ft->n_missing, sizeof *ft->missing, compare, v);
587 /* Summary statistics. */
588 ft->valid_cases = 0.0;
589 for(i = 0 ; i < ft->n_valid ; ++i )
592 ft->valid_cases += f->count;
596 ft->total_cases = ft->valid_cases ;
597 for(i = 0 ; i < ft->n_missing ; ++i )
600 ft->total_cases += f->count;
605 /* Frees the frequency table for variable V. */
607 cleanup_freq_tab (const struct variable *v)
609 struct var_freqs *vf = get_var_freqs (v);
610 free (vf->tab.valid);
611 freq_hmap_destroy (&vf->tab.data, vf->width);
614 /* Parses the VARIABLES subcommand, adding to
615 {n_variables,v_variables}. */
617 frq_custom_variables (struct lexer *lexer, struct dataset *ds, struct cmd_frequencies *cmd UNUSED, void *aux UNUSED)
619 size_t old_n_variables = n_variables;
622 lex_match (lexer, '=');
623 if (lex_token (lexer) != T_ALL && (lex_token (lexer) != T_ID
624 || dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) == NULL))
627 if (!parse_variables_const (lexer, dataset_dict (ds), &v_variables, &n_variables,
628 PV_APPEND | PV_NO_SCRATCH))
631 for (i = old_n_variables; i < n_variables; i++)
633 const struct variable *v = v_variables[i];
634 struct var_freqs *vf;
636 if (var_get_aux (v) != NULL)
638 msg (SE, _("Variable %s specified multiple times on VARIABLES "
639 "subcommand."), var_get_name (v));
642 vf = var_attach_aux (v, xmalloc (sizeof *vf), var_dtor_free);
643 vf->tab.valid = vf->tab.missing = NULL;
644 vf->tab.dict = dataset_dict (ds);
647 vf->width = var_get_width (v);
648 vf->print = *var_get_print_format (v);
653 /* Parses the GROUPED subcommand, setting the n_grouped, grouped
654 fields of specified variables. */
656 frq_custom_grouped (struct lexer *lexer, struct dataset *ds, struct cmd_frequencies *cmd UNUSED, void *aux UNUSED)
658 lex_match (lexer, '=');
659 if ((lex_token (lexer) == T_ID && dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) != NULL)
660 || lex_token (lexer) == T_ID)
665 /* Max, current size of list; list itself. */
671 const struct variable **v;
673 if (!parse_variables_const (lexer, dataset_dict (ds), &v, &n,
674 PV_NO_DUPLICATE | PV_NUMERIC))
676 if (lex_match (lexer, '('))
680 while (lex_integer (lexer))
685 dl = pool_nrealloc (syntax_pool, dl, ml, sizeof *dl);
687 dl[nl++] = lex_tokval (lexer);
689 lex_match (lexer, ',');
691 /* Note that nl might still be 0 and dl might still be
692 NULL. That's okay. */
693 if (!lex_match (lexer, ')'))
696 msg (SE, _("`)' expected after GROUPED interval list."));
706 for (i = 0; i < n; i++)
707 if (var_get_aux (v[i]) == NULL)
708 msg (SE, _("Variables %s specified on GROUPED but not on "
709 "VARIABLES."), var_get_name (v[i]));
712 struct var_freqs *vf = get_var_freqs (v[i]);
714 if (vf->groups != NULL)
715 msg (SE, _("Variables %s specified multiple times on GROUPED "
716 "subcommand."), var_get_name (v[i]));
724 if (!lex_match (lexer, '/'))
726 if ((lex_token (lexer) != T_ID || dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) != NULL)
727 && lex_token (lexer) != T_ALL)
729 lex_put_back (lexer, '/');
737 /* Adds X to the list of percentiles, keeping the list in proper
738 order. If SHOW is true, the percentile will be shown in the statistics
739 box, otherwise it will be hidden. */
741 add_percentile (double x, bool show)
745 for (i = 0; i < n_percentiles; i++)
747 /* Do nothing if it's already in the list */
748 if ( fabs(x - percentiles[i].p) < DBL_EPSILON )
750 if (show && !percentiles[i].show)
752 n_show_percentiles++;
753 percentiles[i].show = true;
758 if (x < percentiles[i].p)
762 if (i >= n_percentiles || x != percentiles[i].p)
764 percentiles = pool_nrealloc (syntax_pool, percentiles,
765 n_percentiles + 1, sizeof *percentiles);
766 insert_element (percentiles, n_percentiles, sizeof *percentiles, i);
767 percentiles[i].p = x;
768 percentiles[i].show = show;
771 n_show_percentiles++;
775 /* Comparison functions. */
777 /* Ascending numeric compare of values. */
779 compare_value_numeric_a (const void *a_, const void *b_, const void *aux UNUSED)
781 const struct freq *a = a_;
782 const struct freq *b = b_;
784 if (a->value.f > b->value.f)
786 else if (a->value.f < b->value.f)
792 /* Ascending string compare of values. */
794 compare_value_alpha_a (const void *a_, const void *b_, const void *v_)
796 const struct freq *a = a_;
797 const struct freq *b = b_;
798 const struct variable *v = v_;
799 struct var_freqs *vf = get_var_freqs (v);
801 return value_compare_3way (&a->value, &b->value, vf->width);
804 /* Descending numeric compare of values. */
806 compare_value_numeric_d (const void *a, const void *b, const void *aux UNUSED)
808 return -compare_value_numeric_a (a, b, aux);
811 /* Descending string compare of values. */
813 compare_value_alpha_d (const void *a, const void *b, const void *v)
815 return -compare_value_alpha_a (a, b, v);
818 /* Ascending numeric compare of frequency;
819 secondary key on ascending numeric value. */
821 compare_freq_numeric_a (const void *a_, const void *b_, const void *aux UNUSED)
823 const struct freq *a = a_;
824 const struct freq *b = b_;
826 if (a->count > b->count)
828 else if (a->count < b->count)
831 if (a->value.f > b->value.f)
833 else if (a->value.f < b->value.f)
839 /* Ascending numeric compare of frequency;
840 secondary key on ascending string value. */
842 compare_freq_alpha_a (const void *a_, const void *b_, const void *v_)
844 const struct freq *a = a_;
845 const struct freq *b = b_;
846 const struct variable *v = v_;
847 struct var_freqs *vf = get_var_freqs (v);
849 if (a->count > b->count)
851 else if (a->count < b->count)
854 return value_compare_3way (&a->value, &b->value, vf->width);
857 /* Descending numeric compare of frequency;
858 secondary key on ascending numeric value. */
860 compare_freq_numeric_d (const void *a_, const void *b_, const void *aux UNUSED)
862 const struct freq *a = a_;
863 const struct freq *b = b_;
865 if (a->count > b->count)
867 else if (a->count < b->count)
870 if (a->value.f > b->value.f)
872 else if (a->value.f < b->value.f)
878 /* Descending numeric compare of frequency;
879 secondary key on ascending string value. */
881 compare_freq_alpha_d (const void *a_, const void *b_, const void *v_)
883 const struct freq *a = a_;
884 const struct freq *b = b_;
885 const struct variable *v = v_;
886 struct var_freqs *vf = get_var_freqs (v);
888 if (a->count > b->count)
890 else if (a->count < b->count)
893 return value_compare_3way (&a->value, &b->value, vf->width);
896 /* Frequency table display. */
898 /* Displays a full frequency table for variable V. */
900 dump_freq_table (const struct variable *v, const struct variable *wv)
902 const struct fmt_spec *wfmt = wv ? var_get_print_format (wv) : &F_8_0;
904 struct var_freqs *vf;
909 double cum_total = 0.0;
910 double cum_freq = 0.0;
912 static const char *headings[] = {
921 vf = get_var_freqs (v);
923 n_categories = ft->n_valid + ft->n_missing;
924 t = tab_create (6, n_categories + 2);
925 tab_headers (t, 0, 0, 1, 0);
927 for (x = 0; x < 6; x++)
928 tab_text (t, x, 0, TAB_CENTER | TAT_TITLE, gettext (headings[x]));
931 for (f = ft->valid; f < ft->missing; f++)
934 double percent, valid_percent;
936 cum_freq += f->count;
938 percent = f->count / ft->total_cases * 100.0;
939 valid_percent = f->count / ft->valid_cases * 100.0;
940 cum_total += valid_percent;
942 label = var_lookup_value_label (v, &f->value);
944 tab_text (t, 0, r, TAB_LEFT, label);
946 tab_value (t, 1, r, TAB_NONE, &f->value, ft->dict, &vf->print);
947 tab_double (t, 2, r, TAB_NONE, f->count, wfmt);
948 tab_double (t, 3, r, TAB_NONE, percent, NULL);
949 tab_double (t, 4, r, TAB_NONE, valid_percent, NULL);
950 tab_double (t, 5, r, TAB_NONE, cum_total, NULL);
953 for (; f < &ft->valid[n_categories]; f++)
957 cum_freq += f->count;
959 label = var_lookup_value_label (v, &f->value);
961 tab_text (t, 0, r, TAB_LEFT, label);
963 tab_value (t, 1, r, TAB_NONE, &f->value, ft->dict, &vf->print);
964 tab_double (t, 2, r, TAB_NONE, f->count, wfmt);
965 tab_double (t, 3, r, TAB_NONE,
966 f->count / ft->total_cases * 100.0, NULL);
967 tab_text (t, 4, r, TAB_NONE, _("Missing"));
971 tab_box (t, TAL_1, TAL_1, -1, TAL_1, 0, 0, 5, r);
972 tab_hline (t, TAL_2, 0, 5, 1);
973 tab_hline (t, TAL_2, 0, 5, r);
974 tab_joint_text (t, 0, r, 1, r, TAB_RIGHT | TAT_TITLE, _("Total"));
975 tab_vline (t, TAL_0, 1, r, r);
976 tab_double (t, 2, r, TAB_NONE, cum_freq, wfmt);
977 tab_fixed (t, 3, r, TAB_NONE, 100.0, 5, 1);
978 tab_fixed (t, 4, r, TAB_NONE, 100.0, 5, 1);
980 tab_title (t, "%s", var_to_string (v));
984 /* Statistical display. */
986 /* Calculates all the pertinent statistics for variable V, putting them in
989 calc_stats (const struct variable *v, double d[FRQ_N_STATS])
991 struct freq_tab *ft = &get_var_freqs (v)->tab;
992 double W = ft->valid_cases;
1002 /* Calculate percentiles. */
1004 assert (ft->n_valid > 0);
1006 for (i = 0; i < n_percentiles; i++)
1008 percentiles[i].flag = 0;
1009 percentiles[i].flag2 = 0;
1013 for (idx = 0; idx < ft->n_valid; ++idx)
1015 static double prev_value = SYSMIS;
1016 f = &ft->valid[idx];
1018 for (i = 0; i < n_percentiles; i++)
1021 if ( percentiles[i].flag2 ) continue ;
1023 if ( settings_get_algorithm () != COMPATIBLE )
1025 (ft->valid_cases - 1) * percentiles[i].p;
1028 (ft->valid_cases + 1) * percentiles[i].p - 1;
1030 if ( percentiles[i].flag )
1032 percentiles[i].x2 = f->value.f;
1033 percentiles[i].x1 = prev_value;
1034 percentiles[i].flag2 = 1;
1040 if ( f->count > 1 && rank - (f->count - 1) > tp )
1042 percentiles[i].x2 = percentiles[i].x1 = f->value.f;
1043 percentiles[i].flag2 = 1;
1047 percentiles[i].flag=1;
1053 prev_value = f->value.f;
1056 for (i = 0; i < n_percentiles; i++)
1058 /* Catches the case when p == 100% */
1059 if ( ! percentiles[i].flag2 )
1060 percentiles[i].x1 = percentiles[i].x2 = f->value.f;
1063 printf("percentile %d (p==%.2f); X1 = %g; X2 = %g\n",
1064 i,percentiles[i].p,percentiles[i].x1,percentiles[i].x2);
1068 for (i = 0; i < n_percentiles; i++)
1070 struct freq_tab *ft = &get_var_freqs (v)->tab;
1074 if ( settings_get_algorithm () != COMPATIBLE )
1076 s = modf((ft->valid_cases - 1) * percentiles[i].p , &dummy);
1080 s = modf((ft->valid_cases + 1) * percentiles[i].p -1, &dummy);
1083 percentiles[i].value = percentiles[i].x1 +
1084 ( percentiles[i].x2 - percentiles[i].x1) * s ;
1088 /* Calculate the mode. */
1091 for (f = ft->valid; f < ft->missing; f++)
1093 if (most_often < f->count)
1095 most_often = f->count;
1096 X_mode = f->value.f;
1098 else if (most_often == f->count)
1100 /* A duplicate mode is undefined.
1101 FIXME: keep track of *all* the modes. */
1106 /* Calculate moments. */
1107 m = moments_create (MOMENT_KURTOSIS);
1108 for (f = ft->valid; f < ft->missing; f++)
1109 moments_pass_one (m, f->value.f, f->count);
1110 for (f = ft->valid; f < ft->missing; f++)
1111 moments_pass_two (m, f->value.f, f->count);
1112 moments_calculate (m, NULL, &d[FRQ_MEAN], &d[FRQ_VARIANCE],
1113 &d[FRQ_SKEW], &d[FRQ_KURT]);
1114 moments_destroy (m);
1116 /* Formulas below are taken from _SPSS Statistical Algorithms_. */
1117 d[FRQ_MIN] = ft->valid[0].value.f;
1118 d[FRQ_MAX] = ft->valid[ft->n_valid - 1].value.f;
1119 d[FRQ_MODE] = X_mode;
1120 d[FRQ_RANGE] = d[FRQ_MAX] - d[FRQ_MIN];
1121 d[FRQ_SUM] = d[FRQ_MEAN] * W;
1122 d[FRQ_STDDEV] = sqrt (d[FRQ_VARIANCE]);
1123 d[FRQ_SEMEAN] = d[FRQ_STDDEV] / sqrt (W);
1124 d[FRQ_SESKEW] = calc_seskew (W);
1125 d[FRQ_SEKURT] = calc_sekurt (W);
1128 /* Displays a table of all the statistics requested for variable V. */
1130 dump_statistics (const struct variable *v, const struct variable *wv)
1132 const struct fmt_spec *wfmt = wv ? var_get_print_format (wv) : &F_8_0;
1133 struct freq_tab *ft;
1134 double stat_value[FRQ_N_STATS];
1135 struct tab_table *t;
1138 if (var_is_alpha (v))
1140 ft = &get_var_freqs (v)->tab;
1141 if (ft->n_valid == 0)
1143 msg (SW, _("No valid data for variable %s; statistics not displayed."),
1147 calc_stats (v, stat_value);
1149 t = tab_create (3, n_stats + n_show_percentiles + 2);
1151 tab_box (t, TAL_1, TAL_1, -1, -1 , 0 , 0 , 2, tab_nr(t) - 1) ;
1154 tab_vline (t, TAL_1 , 2, 0, tab_nr(t) - 1);
1155 tab_vline (t, TAL_GAP , 1, 0, tab_nr(t) - 1 ) ;
1157 r=2; /* N missing and N valid are always dumped */
1159 for (i = 0; i < FRQ_N_STATS; i++)
1160 if (stats & BIT_INDEX (i))
1162 tab_text (t, 0, r, TAB_LEFT | TAT_TITLE,
1163 gettext (st_name[i].s10));
1164 tab_double (t, 2, r, TAB_NONE, stat_value[i], NULL);
1168 tab_text (t, 0, 0, TAB_LEFT | TAT_TITLE, _("N"));
1169 tab_text (t, 1, 0, TAB_LEFT | TAT_TITLE, _("Valid"));
1170 tab_text (t, 1, 1, TAB_LEFT | TAT_TITLE, _("Missing"));
1172 tab_double (t, 2, 0, TAB_NONE, ft->valid_cases, wfmt);
1173 tab_double (t, 2, 1, TAB_NONE, ft->total_cases - ft->valid_cases, wfmt);
1175 for (i = 0; i < n_percentiles; i++, r++)
1177 if (!percentiles[i].show)
1182 tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, _("Percentiles"));
1185 if (percentiles[i].p == 0.5)
1186 tab_text (t, 1, r, TAB_LEFT, _("50 (Median)"));
1188 tab_fixed (t, 1, r, TAB_LEFT, percentiles[i].p * 100, 3, 0);
1189 tab_double (t, 2, r, TAB_NONE, percentiles[i].value,
1190 var_get_print_format (v));
1193 tab_title (t, "%s", var_to_string (v));
1199 calculate_iqr (void)
1205 for (i = 0; i < n_percentiles; i++)
1207 if (fabs (0.25 - percentiles[i].p) < DBL_EPSILON)
1208 q1 = percentiles[i].value;
1209 else if (fabs (0.75 - percentiles[i].p) < DBL_EPSILON)
1210 q3 = percentiles[i].value;
1213 return q1 == SYSMIS || q3 == SYSMIS ? SYSMIS : q3 - q1;
1217 chart_includes_value (const struct frq_chart *chart,
1218 const struct variable *var,
1219 const union value *value)
1221 if (!chart->include_missing && var_is_value_missing (var, value, MV_ANY))
1224 if (var_is_numeric (var)
1225 && ((chart->x_min != SYSMIS && value->f < chart->x_min)
1226 || (chart->x_max != SYSMIS && value->f > chart->x_max)))
1232 /* Create a gsl_histogram from a freq_tab */
1234 freq_tab_to_hist (const struct freq_tab *ft, const struct variable *var)
1236 double x_min, x_max, valid_freq;
1239 struct histogram *histogram;
1243 /* Find out the extremes of the x value, within the range to be included in
1244 the histogram, and sum the total frequency of those values. */
1248 for (i = 0; i < ft->n_valid; i++)
1250 const struct freq *frq = &ft->valid[i];
1251 if (chart_includes_value (&hist, var, &frq->value))
1253 x_min = MIN (x_min, frq->value.f);
1254 x_max = MAX (x_max, frq->value.f);
1255 valid_freq += frq->count;
1259 /* Freedman-Diaconis' choice of bin width. */
1260 iqr = calculate_iqr ();
1263 double bin_width = 2 * iqr / pow (valid_freq, 1.0 / 3.0);
1264 bins = (x_max - x_min) / bin_width;
1267 else if (bins > 400)
1273 histogram = histogram_create (bins, x_min, x_max);
1274 for (i = 0; i < ft->n_valid; i++)
1276 const struct freq *frq = &ft->valid[i];
1277 if (chart_includes_value (&hist, var, &frq->value))
1278 histogram_add (histogram, frq->value.f, frq->count);
1285 add_slice (const struct freq *freq, const struct variable *var,
1286 struct slice *slice)
1288 if (chart_includes_value (&pie, var, &freq->value))
1290 ds_init_empty (&slice->label);
1291 var_append_value_name (var, &freq->value, &slice->label);
1292 slice->magnitude = freq->count;
1299 /* Allocate an array of slices and fill them from the data in frq_tab
1300 n_slices will contain the number of slices allocated.
1301 The caller is responsible for freeing slices
1303 static struct slice *
1304 freq_tab_to_slice_array(const struct freq_tab *frq_tab,
1305 const struct variable *var,
1308 struct slice *slices;
1312 slices = xnmalloc (frq_tab->n_valid + frq_tab->n_missing, sizeof *slices);
1315 for (i = 0; i < frq_tab->n_valid; i++)
1316 n_slices += add_slice (&frq_tab->valid[i], var, &slices[n_slices]);
1317 for (i = 0; i < frq_tab->n_missing; i++)
1318 n_slices += add_slice (&frq_tab->missing[i], var, &slices[n_slices]);
1320 *n_slicesp = n_slices;
1328 do_piechart(const struct variable *var, const struct freq_tab *frq_tab)
1330 struct slice *slices;
1333 slices = freq_tab_to_slice_array (frq_tab, var, &n_slices);
1336 msg (SW, _("Omitting pie chart for %s, which has only %d unique values."),
1337 var_get_name (var), n_slices);
1338 else if (n_slices > 50)
1339 msg (SW, _("Omitting pie chart for %s, which has over 50 unique values."),
1340 var_get_name (var));
1342 chart_item_submit (piechart_create (var_to_string(var), slices, n_slices));
1344 for (i = 0; i < n_slices; i++)
1345 ds_destroy (&slices[i].label);