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 *syntax_pool; /* For syntax-related data. */
183 /* Frequency tables. */
185 /* Entire frequency table. */
188 struct hmap data; /* Hash table for accumulating counts. */
189 struct freq *valid; /* Valid freqs. */
190 int n_valid; /* Number of total freqs. */
191 const struct dictionary *dict; /* Source of entries in the table. */
193 struct freq *missing; /* Missing freqs. */
194 int n_missing; /* Number of missing freqs. */
197 double total_cases; /* Sum of weights of all cases. */
198 double valid_cases; /* Sum of weights of valid cases. */
201 /* Per-variable frequency data. */
204 /* Freqency table. */
205 struct freq_tab tab; /* Frequencies table to use. */
208 int n_groups; /* Number of groups. */
209 double *groups; /* Groups. */
212 double stat[FRQ_N_STATS];
214 /* Variable attributes. */
216 struct fmt_spec print;
219 static inline struct var_freqs *
220 get_var_freqs (const struct variable *v)
222 return var_get_aux (v);
225 static void determine_charts (void);
227 static void calc_stats (const struct variable *v, double d[FRQ_N_STATS]);
229 static void precalc (struct casereader *, struct dataset *);
230 static void calc (const struct ccase *, const struct dataset *);
231 static void postcalc (const struct dataset *);
233 static void postprocess_freq_tab (const struct variable *);
234 static void dump_freq_table (const struct variable *, const struct variable *);
235 static void dump_statistics (const struct variable *, const struct variable *);
236 static void cleanup_freq_tab (const struct variable *);
238 static algo_compare_func compare_value_numeric_a, compare_value_alpha_a;
239 static algo_compare_func compare_value_numeric_d, compare_value_alpha_d;
240 static algo_compare_func compare_freq_numeric_a, compare_freq_alpha_a;
241 static algo_compare_func compare_freq_numeric_d, compare_freq_alpha_d;
244 static void do_piechart(const struct variable *var,
245 const struct freq_tab *frq_tab);
248 freq_tab_to_hist(const struct freq_tab *ft, const struct variable *var);
252 /* Parser and outline. */
254 static int internal_cmd_frequencies (struct lexer *lexer, struct dataset *ds);
257 cmd_frequencies (struct lexer *lexer, struct dataset *ds)
261 syntax_pool = pool_create ();
262 result = internal_cmd_frequencies (lexer, ds);
263 pool_destroy (syntax_pool);
271 internal_cmd_frequencies (struct lexer *lexer, struct dataset *ds)
273 struct casegrouper *grouper;
274 struct casereader *input, *group;
279 n_show_percentiles = 0;
285 if (!parse_frequencies (lexer, ds, &cmd, NULL))
288 /* Figure out statistics to calculate. */
290 if (cmd.a_statistics[FRQ_ST_DEFAULT] || !cmd.sbc_statistics)
291 stats |= FRQ_DEFAULT;
292 if (cmd.a_statistics[FRQ_ST_ALL])
294 if (cmd.sort != FRQ_AVALUE && cmd.sort != FRQ_DVALUE)
295 stats &= ~BIT_INDEX (FRQ_MEDIAN);
296 for (i = 0; i < FRQ_N_STATS; i++)
297 if (cmd.a_statistics[st_name[i].st_indx])
298 stats |= BIT_INDEX (i);
299 if (stats & FRQ_KURT)
300 stats |= BIT_INDEX (FRQ_SEKURT);
301 if (stats & FRQ_SKEW)
302 stats |= BIT_INDEX (FRQ_SESKEW);
304 /* Calculate n_stats. */
306 for (i = 0; i < FRQ_N_STATS; i++)
307 if ((stats & BIT_INDEX (i)))
312 if (cmd.sbc_histogram || cmd.sbc_piechart || cmd.sbc_ntiles)
313 cmd.sort = FRQ_AVALUE;
315 /* Work out what percentiles need to be calculated */
316 if ( cmd.sbc_percentiles )
318 for ( i = 0 ; i < MAXLISTS ; ++i )
321 subc_list_double *ptl_list = &cmd.dl_percentiles[i];
322 for ( pl = 0 ; pl < subc_list_double_count(ptl_list); ++pl)
323 add_percentile (subc_list_double_at(ptl_list, pl) / 100.0, true);
326 if ( cmd.sbc_ntiles )
328 for ( i = 0 ; i < cmd.sbc_ntiles ; ++i )
331 for (j = 0; j <= cmd.n_ntiles[i]; ++j )
332 add_percentile (j / (double) cmd.n_ntiles[i], true);
335 if (stats & BIT_INDEX (FRQ_MEDIAN))
337 /* Treat the median as the 50% percentile.
338 We output it in the percentiles table as "50 (Median)." */
339 add_percentile (0.5, true);
340 stats &= ~BIT_INDEX (FRQ_MEDIAN);
343 if (cmd.sbc_histogram)
345 add_percentile (0.25, false);
346 add_percentile (0.75, false);
350 input = casereader_create_filter_weight (proc_open (ds), dataset_dict (ds),
352 grouper = casegrouper_create_splits (input, dataset_dict (ds));
353 for (; casegrouper_get_next_group (grouper, &group);
354 casereader_destroy (group))
359 for (; (c = casereader_read (group)) != NULL; case_unref (c))
363 ok = casegrouper_destroy (grouper);
364 ok = proc_commit (ds) && ok;
366 free_frequencies(&cmd);
368 return ok ? CMD_SUCCESS : CMD_CASCADING_FAILURE;
371 /* Figure out which charts the user requested. */
373 determine_charts (void)
375 if (cmd.sbc_barchart)
376 msg (SW, _("Bar charts are not implemented."));
378 if (cmd.sbc_histogram)
380 hist.x_min = cmd.hi_min;
381 hist.x_max = cmd.hi_max;
382 hist.y_scale = cmd.hi_scale;
383 hist.y_max = cmd.hi_scale == FRQ_FREQ ? cmd.hi_freq : cmd.hi_pcnt;
384 hist.draw_normal = cmd.hi_norm != FRQ_NONORMAL;
385 hist.include_missing = false;
387 if (hist.x_min != SYSMIS && hist.x_max != SYSMIS
388 && hist.x_min >= hist.x_max)
390 msg (SE, _("MAX for histogram must be greater than or equal to MIN, "
391 "but MIN was specified as %.15g and MAX as %.15g. "
392 "MIN and MAX will be ignored."), hist.x_min, hist.x_max);
393 hist.x_min = hist.x_max = SYSMIS;
397 if (cmd.sbc_piechart)
399 pie.x_min = cmd.pie_min;
400 pie.x_max = cmd.pie_max;
401 pie.y_scale = cmd.pie_scale;
402 pie.include_missing = cmd.pie_missing == FRQ_MISSING;
404 if (pie.x_min != SYSMIS && pie.x_max != SYSMIS
405 && pie.x_min >= pie.x_max)
407 msg (SE, _("MAX for pie chart must be greater than or equal to MIN, "
408 "but MIN was specified as %.15g and MAX as %.15g. "
409 "MIN and MAX will be ignored."), pie.x_min, pie.x_max);
410 pie.x_min = pie.x_max = SYSMIS;
416 /* Add data from case C to the frequency table. */
418 calc (const struct ccase *c, const struct dataset *ds)
420 double weight = dict_get_case_weight (dataset_dict (ds), c, NULL);
423 for (i = 0; i < n_variables; i++)
425 const struct variable *var = v_variables[i];
426 int width = var_get_width (var);
428 const union value *value = case_data (c, var);
429 size_t hash = value_hash (value, width, 0);
431 struct hmap *hmap = &get_var_freqs (var)->tab.data;
434 f = freq_hmap_search (hmap, value, width, hash);
436 f = freq_hmap_insert (hmap, value, width, hash);
442 /* Prepares each variable that is the target of FREQUENCIES by setting
443 up its hash table. */
445 precalc (struct casereader *input, struct dataset *ds)
450 c = casereader_peek (input, 0);
453 output_split_file_values (ds, c);
457 for (i = 0; i < n_variables; i++)
459 const struct variable *v = v_variables[i];
460 struct freq_tab *ft = &get_var_freqs (v)->tab;
462 hmap_init (&ft->data);
466 /* Finishes up with the variables after frequencies have been
467 calculated. Displays statistics, percentiles, ... */
469 postcalc (const struct dataset *ds)
471 const struct dictionary *dict = dataset_dict (ds);
472 const struct variable *wv = dict_get_weight (dict);
475 for (i = 0; i < n_variables; i++)
477 const struct variable *v = v_variables[i];
478 struct var_freqs *vf = get_var_freqs (v);
479 struct freq_tab *ft = &vf->tab;
482 postprocess_freq_tab (v);
484 /* Frequencies tables. */
485 n_categories = ft->n_valid + ft->n_missing;
486 if (cmd.table == FRQ_TABLE
487 || (cmd.table == FRQ_LIMIT && n_categories <= cmd.limit))
488 dump_freq_table (v, wv);
492 dump_statistics (v, wv);
494 if (cmd.sbc_histogram && var_is_numeric (v) && ft->n_valid > 0)
496 double d[FRQ_N_STATS];
497 struct histogram *histogram;
501 histogram = freq_tab_to_hist (ft, v);
503 chart_item_submit (histogram_chart_create (
504 histogram->gsl_hist, var_to_string(v),
510 statistic_destroy (&histogram->parent);
513 if (cmd.sbc_piechart)
514 do_piechart(v_variables[i], ft);
516 cleanup_freq_tab (v);
521 /* Returns the comparison function that should be used for
522 sorting a frequency table by FRQ_SORT using VAL_TYPE
524 static algo_compare_func *
525 get_freq_comparator (int frq_sort, enum val_type val_type)
527 bool is_numeric = val_type == VAL_NUMERIC;
531 return is_numeric ? compare_value_numeric_a : compare_value_alpha_a;
533 return is_numeric ? compare_value_numeric_d : compare_value_alpha_d;
535 return is_numeric ? compare_freq_numeric_a : compare_freq_alpha_a;
537 return is_numeric ? compare_freq_numeric_d : compare_freq_alpha_d;
543 /* Returns true iff the value in struct freq F is non-missing
546 not_missing (const void *f_, const void *v_)
548 const struct freq *f = f_;
549 const struct variable *v = v_;
551 return !var_is_value_missing (v, &f->value, MV_ANY);
554 /* Summarizes the frequency table data for variable V. */
556 postprocess_freq_tab (const struct variable *v)
558 algo_compare_func *compare;
561 struct freq *freqs, *f;
564 ft = &get_var_freqs (v)->tab;
565 compare = get_freq_comparator (cmd.sort, var_get_type (v));
567 /* Extract data from hash table. */
568 count = hmap_count (&ft->data);
569 freqs = freq_hmap_extract (&ft->data);
571 /* Put data into ft. */
573 ft->n_valid = partition (freqs, count, sizeof *freqs, not_missing, v);
574 ft->missing = freqs + ft->n_valid;
575 ft->n_missing = count - ft->n_valid;
578 sort (ft->valid, ft->n_valid, sizeof *ft->valid, compare, v);
579 sort (ft->missing, ft->n_missing, sizeof *ft->missing, compare, v);
581 /* Summary statistics. */
582 ft->valid_cases = 0.0;
583 for(i = 0 ; i < ft->n_valid ; ++i )
586 ft->valid_cases += f->count;
590 ft->total_cases = ft->valid_cases ;
591 for(i = 0 ; i < ft->n_missing ; ++i )
594 ft->total_cases += f->count;
599 /* Frees the frequency table for variable V. */
601 cleanup_freq_tab (const struct variable *v)
603 struct var_freqs *vf = get_var_freqs (v);
604 free (vf->tab.valid);
605 freq_hmap_destroy (&vf->tab.data, vf->width);
608 /* Parses the VARIABLES subcommand, adding to
609 {n_variables,v_variables}. */
611 frq_custom_variables (struct lexer *lexer, struct dataset *ds, struct cmd_frequencies *cmd UNUSED, void *aux UNUSED)
613 size_t old_n_variables = n_variables;
616 lex_match (lexer, '=');
617 if (lex_token (lexer) != T_ALL && (lex_token (lexer) != T_ID
618 || dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) == NULL))
621 if (!parse_variables_const (lexer, dataset_dict (ds), &v_variables, &n_variables,
622 PV_APPEND | PV_NO_SCRATCH))
625 for (i = old_n_variables; i < n_variables; i++)
627 const struct variable *v = v_variables[i];
628 struct var_freqs *vf;
630 if (var_get_aux (v) != NULL)
632 msg (SE, _("Variable %s specified multiple times on VARIABLES "
633 "subcommand."), var_get_name (v));
636 vf = var_attach_aux (v, xmalloc (sizeof *vf), var_dtor_free);
637 vf->tab.valid = vf->tab.missing = NULL;
638 vf->tab.dict = dataset_dict (ds);
641 vf->width = var_get_width (v);
642 vf->print = *var_get_print_format (v);
647 /* Parses the GROUPED subcommand, setting the n_grouped, grouped
648 fields of specified variables. */
650 frq_custom_grouped (struct lexer *lexer, struct dataset *ds, struct cmd_frequencies *cmd UNUSED, void *aux UNUSED)
652 lex_match (lexer, '=');
653 if ((lex_token (lexer) == T_ID && dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) != NULL)
654 || lex_token (lexer) == T_ID)
659 /* Max, current size of list; list itself. */
665 const struct variable **v;
667 if (!parse_variables_const (lexer, dataset_dict (ds), &v, &n,
668 PV_NO_DUPLICATE | PV_NUMERIC))
670 if (lex_match (lexer, '('))
674 while (lex_integer (lexer))
679 dl = pool_nrealloc (syntax_pool, dl, ml, sizeof *dl);
681 dl[nl++] = lex_tokval (lexer);
683 lex_match (lexer, ',');
685 /* Note that nl might still be 0 and dl might still be
686 NULL. That's okay. */
687 if (!lex_match (lexer, ')'))
690 msg (SE, _("`)' expected after GROUPED interval list."));
700 for (i = 0; i < n; i++)
701 if (var_get_aux (v[i]) == NULL)
702 msg (SE, _("Variables %s specified on GROUPED but not on "
703 "VARIABLES."), var_get_name (v[i]));
706 struct var_freqs *vf = get_var_freqs (v[i]);
708 if (vf->groups != NULL)
709 msg (SE, _("Variables %s specified multiple times on GROUPED "
710 "subcommand."), var_get_name (v[i]));
718 if (!lex_match (lexer, '/'))
720 if ((lex_token (lexer) != T_ID || dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) != NULL)
721 && lex_token (lexer) != T_ALL)
723 lex_put_back (lexer, '/');
731 /* Adds X to the list of percentiles, keeping the list in proper
732 order. If SHOW is true, the percentile will be shown in the statistics
733 box, otherwise it will be hidden. */
735 add_percentile (double x, bool show)
739 for (i = 0; i < n_percentiles; i++)
741 /* Do nothing if it's already in the list */
742 if ( fabs(x - percentiles[i].p) < DBL_EPSILON )
744 if (show && !percentiles[i].show)
746 n_show_percentiles++;
747 percentiles[i].show = true;
752 if (x < percentiles[i].p)
756 if (i >= n_percentiles || x != percentiles[i].p)
758 percentiles = pool_nrealloc (syntax_pool, percentiles,
759 n_percentiles + 1, sizeof *percentiles);
760 insert_element (percentiles, n_percentiles, sizeof *percentiles, i);
761 percentiles[i].p = x;
762 percentiles[i].show = show;
765 n_show_percentiles++;
769 /* Comparison functions. */
771 /* Ascending numeric compare of values. */
773 compare_value_numeric_a (const void *a_, const void *b_, const void *aux UNUSED)
775 const struct freq *a = a_;
776 const struct freq *b = b_;
778 if (a->value.f > b->value.f)
780 else if (a->value.f < b->value.f)
786 /* Ascending string compare of values. */
788 compare_value_alpha_a (const void *a_, const void *b_, const void *v_)
790 const struct freq *a = a_;
791 const struct freq *b = b_;
792 const struct variable *v = v_;
793 struct var_freqs *vf = get_var_freqs (v);
795 return value_compare_3way (&a->value, &b->value, vf->width);
798 /* Descending numeric compare of values. */
800 compare_value_numeric_d (const void *a, const void *b, const void *aux UNUSED)
802 return -compare_value_numeric_a (a, b, aux);
805 /* Descending string compare of values. */
807 compare_value_alpha_d (const void *a, const void *b, const void *v)
809 return -compare_value_alpha_a (a, b, v);
812 /* Ascending numeric compare of frequency;
813 secondary key on ascending numeric value. */
815 compare_freq_numeric_a (const void *a_, const void *b_, const void *aux UNUSED)
817 const struct freq *a = a_;
818 const struct freq *b = b_;
820 if (a->count > b->count)
822 else if (a->count < b->count)
825 if (a->value.f > b->value.f)
827 else if (a->value.f < b->value.f)
833 /* Ascending numeric compare of frequency;
834 secondary key on ascending string value. */
836 compare_freq_alpha_a (const void *a_, const void *b_, const void *v_)
838 const struct freq *a = a_;
839 const struct freq *b = b_;
840 const struct variable *v = v_;
841 struct var_freqs *vf = get_var_freqs (v);
843 if (a->count > b->count)
845 else if (a->count < b->count)
848 return value_compare_3way (&a->value, &b->value, vf->width);
851 /* Descending numeric compare of frequency;
852 secondary key on ascending numeric value. */
854 compare_freq_numeric_d (const void *a_, const void *b_, const void *aux UNUSED)
856 const struct freq *a = a_;
857 const struct freq *b = b_;
859 if (a->count > b->count)
861 else if (a->count < b->count)
864 if (a->value.f > b->value.f)
866 else if (a->value.f < b->value.f)
872 /* Descending numeric compare of frequency;
873 secondary key on ascending string value. */
875 compare_freq_alpha_d (const void *a_, const void *b_, const void *v_)
877 const struct freq *a = a_;
878 const struct freq *b = b_;
879 const struct variable *v = v_;
880 struct var_freqs *vf = get_var_freqs (v);
882 if (a->count > b->count)
884 else if (a->count < b->count)
887 return value_compare_3way (&a->value, &b->value, vf->width);
890 /* Frequency table display. */
892 /* Displays a full frequency table for variable V. */
894 dump_freq_table (const struct variable *v, const struct variable *wv)
896 const struct fmt_spec *wfmt = wv ? var_get_print_format (wv) : &F_8_0;
898 struct var_freqs *vf;
903 double cum_total = 0.0;
904 double cum_freq = 0.0;
906 static const char *headings[] = {
915 vf = get_var_freqs (v);
917 n_categories = ft->n_valid + ft->n_missing;
918 t = tab_create (6, n_categories + 2);
919 tab_headers (t, 0, 0, 1, 0);
921 for (x = 0; x < 6; x++)
922 tab_text (t, x, 0, TAB_CENTER | TAT_TITLE, gettext (headings[x]));
925 for (f = ft->valid; f < ft->missing; f++)
928 double percent, valid_percent;
930 cum_freq += f->count;
932 percent = f->count / ft->total_cases * 100.0;
933 valid_percent = f->count / ft->valid_cases * 100.0;
934 cum_total += valid_percent;
936 label = var_lookup_value_label (v, &f->value);
938 tab_text (t, 0, r, TAB_LEFT, label);
940 tab_value (t, 1, r, TAB_NONE, &f->value, ft->dict, &vf->print);
941 tab_double (t, 2, r, TAB_NONE, f->count, wfmt);
942 tab_double (t, 3, r, TAB_NONE, percent, NULL);
943 tab_double (t, 4, r, TAB_NONE, valid_percent, NULL);
944 tab_double (t, 5, r, TAB_NONE, cum_total, NULL);
947 for (; f < &ft->valid[n_categories]; f++)
951 cum_freq += f->count;
953 label = var_lookup_value_label (v, &f->value);
955 tab_text (t, 0, r, TAB_LEFT, label);
957 tab_value (t, 1, r, TAB_NONE, &f->value, ft->dict, &vf->print);
958 tab_double (t, 2, r, TAB_NONE, f->count, wfmt);
959 tab_double (t, 3, r, TAB_NONE,
960 f->count / ft->total_cases * 100.0, NULL);
961 tab_text (t, 4, r, TAB_NONE, _("Missing"));
965 tab_box (t, TAL_1, TAL_1, -1, TAL_1, 0, 0, 5, r);
966 tab_hline (t, TAL_2, 0, 5, 1);
967 tab_hline (t, TAL_2, 0, 5, r);
968 tab_joint_text (t, 0, r, 1, r, TAB_RIGHT | TAT_TITLE, _("Total"));
969 tab_vline (t, TAL_0, 1, r, r);
970 tab_double (t, 2, r, TAB_NONE, cum_freq, wfmt);
971 tab_fixed (t, 3, r, TAB_NONE, 100.0, 5, 1);
972 tab_fixed (t, 4, r, TAB_NONE, 100.0, 5, 1);
974 tab_title (t, "%s", var_to_string (v));
978 /* Statistical display. */
980 /* Calculates all the pertinent statistics for variable V, putting them in
983 calc_stats (const struct variable *v, double d[FRQ_N_STATS])
985 struct freq_tab *ft = &get_var_freqs (v)->tab;
986 double W = ft->valid_cases;
996 /* Calculate percentiles. */
998 assert (ft->n_valid > 0);
1000 for (i = 0; i < n_percentiles; i++)
1002 percentiles[i].flag = 0;
1003 percentiles[i].flag2 = 0;
1007 for (idx = 0; idx < ft->n_valid; ++idx)
1009 static double prev_value = SYSMIS;
1010 f = &ft->valid[idx];
1012 for (i = 0; i < n_percentiles; i++)
1015 if ( percentiles[i].flag2 ) continue ;
1017 if ( settings_get_algorithm () != COMPATIBLE )
1019 (ft->valid_cases - 1) * percentiles[i].p;
1022 (ft->valid_cases + 1) * percentiles[i].p - 1;
1024 if ( percentiles[i].flag )
1026 percentiles[i].x2 = f->value.f;
1027 percentiles[i].x1 = prev_value;
1028 percentiles[i].flag2 = 1;
1034 if ( f->count > 1 && rank - (f->count - 1) > tp )
1036 percentiles[i].x2 = percentiles[i].x1 = f->value.f;
1037 percentiles[i].flag2 = 1;
1041 percentiles[i].flag=1;
1047 prev_value = f->value.f;
1050 for (i = 0; i < n_percentiles; i++)
1052 /* Catches the case when p == 100% */
1053 if ( ! percentiles[i].flag2 )
1054 percentiles[i].x1 = percentiles[i].x2 = f->value.f;
1057 printf("percentile %d (p==%.2f); X1 = %g; X2 = %g\n",
1058 i,percentiles[i].p,percentiles[i].x1,percentiles[i].x2);
1062 for (i = 0; i < n_percentiles; i++)
1064 struct freq_tab *ft = &get_var_freqs (v)->tab;
1068 if ( settings_get_algorithm () != COMPATIBLE )
1070 s = modf((ft->valid_cases - 1) * percentiles[i].p , &dummy);
1074 s = modf((ft->valid_cases + 1) * percentiles[i].p -1, &dummy);
1077 percentiles[i].value = percentiles[i].x1 +
1078 ( percentiles[i].x2 - percentiles[i].x1) * s ;
1082 /* Calculate the mode. */
1085 for (f = ft->valid; f < ft->missing; f++)
1087 if (most_often < f->count)
1089 most_often = f->count;
1090 X_mode = f->value.f;
1092 else if (most_often == f->count)
1094 /* A duplicate mode is undefined.
1095 FIXME: keep track of *all* the modes. */
1100 /* Calculate moments. */
1101 m = moments_create (MOMENT_KURTOSIS);
1102 for (f = ft->valid; f < ft->missing; f++)
1103 moments_pass_one (m, f->value.f, f->count);
1104 for (f = ft->valid; f < ft->missing; f++)
1105 moments_pass_two (m, f->value.f, f->count);
1106 moments_calculate (m, NULL, &d[FRQ_MEAN], &d[FRQ_VARIANCE],
1107 &d[FRQ_SKEW], &d[FRQ_KURT]);
1108 moments_destroy (m);
1110 /* Formulas below are taken from _SPSS Statistical Algorithms_. */
1111 d[FRQ_MIN] = ft->valid[0].value.f;
1112 d[FRQ_MAX] = ft->valid[ft->n_valid - 1].value.f;
1113 d[FRQ_MODE] = X_mode;
1114 d[FRQ_RANGE] = d[FRQ_MAX] - d[FRQ_MIN];
1115 d[FRQ_SUM] = d[FRQ_MEAN] * W;
1116 d[FRQ_STDDEV] = sqrt (d[FRQ_VARIANCE]);
1117 d[FRQ_SEMEAN] = d[FRQ_STDDEV] / sqrt (W);
1118 d[FRQ_SESKEW] = calc_seskew (W);
1119 d[FRQ_SEKURT] = calc_sekurt (W);
1122 /* Displays a table of all the statistics requested for variable V. */
1124 dump_statistics (const struct variable *v, const struct variable *wv)
1126 const struct fmt_spec *wfmt = wv ? var_get_print_format (wv) : &F_8_0;
1127 struct freq_tab *ft;
1128 double stat_value[FRQ_N_STATS];
1129 struct tab_table *t;
1132 if (var_is_alpha (v))
1134 ft = &get_var_freqs (v)->tab;
1135 if (ft->n_valid == 0)
1137 msg (SW, _("No valid data for variable %s; statistics not displayed."),
1141 calc_stats (v, stat_value);
1143 t = tab_create (3, n_stats + n_show_percentiles + 2);
1145 tab_box (t, TAL_1, TAL_1, -1, -1 , 0 , 0 , 2, tab_nr(t) - 1) ;
1148 tab_vline (t, TAL_1 , 2, 0, tab_nr(t) - 1);
1149 tab_vline (t, TAL_GAP , 1, 0, tab_nr(t) - 1 ) ;
1151 r=2; /* N missing and N valid are always dumped */
1153 for (i = 0; i < FRQ_N_STATS; i++)
1154 if (stats & BIT_INDEX (i))
1156 tab_text (t, 0, r, TAB_LEFT | TAT_TITLE,
1157 gettext (st_name[i].s10));
1158 tab_double (t, 2, r, TAB_NONE, stat_value[i], NULL);
1162 tab_text (t, 0, 0, TAB_LEFT | TAT_TITLE, _("N"));
1163 tab_text (t, 1, 0, TAB_LEFT | TAT_TITLE, _("Valid"));
1164 tab_text (t, 1, 1, TAB_LEFT | TAT_TITLE, _("Missing"));
1166 tab_double (t, 2, 0, TAB_NONE, ft->valid_cases, wfmt);
1167 tab_double (t, 2, 1, TAB_NONE, ft->total_cases - ft->valid_cases, wfmt);
1169 for (i = 0; i < n_percentiles; i++, r++)
1171 if (!percentiles[i].show)
1176 tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, _("Percentiles"));
1179 if (percentiles[i].p == 0.5)
1180 tab_text (t, 1, r, TAB_LEFT, _("50 (Median)"));
1182 tab_fixed (t, 1, r, TAB_LEFT, percentiles[i].p * 100, 3, 0);
1183 tab_double (t, 2, r, TAB_NONE, percentiles[i].value,
1184 var_get_print_format (v));
1187 tab_title (t, "%s", var_to_string (v));
1193 calculate_iqr (void)
1199 for (i = 0; i < n_percentiles; i++)
1201 if (fabs (0.25 - percentiles[i].p) < DBL_EPSILON)
1202 q1 = percentiles[i].value;
1203 else if (fabs (0.75 - percentiles[i].p) < DBL_EPSILON)
1204 q3 = percentiles[i].value;
1207 return q1 == SYSMIS || q3 == SYSMIS ? SYSMIS : q3 - q1;
1211 chart_includes_value (const struct frq_chart *chart,
1212 const struct variable *var,
1213 const union value *value)
1215 if (!chart->include_missing && var_is_value_missing (var, value, MV_ANY))
1218 if (var_is_numeric (var)
1219 && ((chart->x_min != SYSMIS && value->f < chart->x_min)
1220 || (chart->x_max != SYSMIS && value->f > chart->x_max)))
1226 /* Create a gsl_histogram from a freq_tab */
1228 freq_tab_to_hist (const struct freq_tab *ft, const struct variable *var)
1230 double x_min, x_max, valid_freq;
1233 struct histogram *histogram;
1237 /* Find out the extremes of the x value, within the range to be included in
1238 the histogram, and sum the total frequency of those values. */
1242 for (i = 0; i < ft->n_valid; i++)
1244 const struct freq *frq = &ft->valid[i];
1245 if (chart_includes_value (&hist, var, &frq->value))
1247 x_min = MIN (x_min, frq->value.f);
1248 x_max = MAX (x_max, frq->value.f);
1249 valid_freq += frq->count;
1253 /* Freedman-Diaconis' choice of bin width. */
1254 iqr = calculate_iqr ();
1257 double bin_width = 2 * iqr / pow (valid_freq, 1.0 / 3.0);
1258 bins = (x_max - x_min) / bin_width;
1261 else if (bins > 400)
1267 histogram = histogram_create (bins, x_min, x_max);
1268 for (i = 0; i < ft->n_valid; i++)
1270 const struct freq *frq = &ft->valid[i];
1271 if (chart_includes_value (&hist, var, &frq->value))
1272 histogram_add (histogram, frq->value.f, frq->count);
1279 add_slice (const struct freq *freq, const struct variable *var,
1280 struct slice *slice)
1282 if (chart_includes_value (&pie, var, &freq->value))
1284 ds_init_empty (&slice->label);
1285 var_append_value_name (var, &freq->value, &slice->label);
1286 slice->magnitude = freq->count;
1293 /* Allocate an array of slices and fill them from the data in frq_tab
1294 n_slices will contain the number of slices allocated.
1295 The caller is responsible for freeing slices
1297 static struct slice *
1298 freq_tab_to_slice_array(const struct freq_tab *frq_tab,
1299 const struct variable *var,
1302 struct slice *slices;
1306 slices = xnmalloc (frq_tab->n_valid + frq_tab->n_missing, sizeof *slices);
1309 for (i = 0; i < frq_tab->n_valid; i++)
1310 n_slices += add_slice (&frq_tab->valid[i], var, &slices[n_slices]);
1311 for (i = 0; i < frq_tab->n_missing; i++)
1312 n_slices += add_slice (&frq_tab->missing[i], var, &slices[n_slices]);
1314 *n_slicesp = n_slices;
1322 do_piechart(const struct variable *var, const struct freq_tab *frq_tab)
1324 struct slice *slices;
1327 slices = freq_tab_to_slice_array (frq_tab, var, &n_slices);
1330 msg (SW, _("Omitting pie chart for %s, which has only %d unique values."),
1331 var_get_name (var), n_slices);
1332 else if (n_slices > 50)
1333 msg (SW, _("Omitting pie chart for %s, which has over 50 unique values."),
1334 var_get_name (var));
1336 chart_item_submit (piechart_create (var_to_string(var), slices, n_slices));
1338 for (i = 0; i < n_slices; i++)
1339 ds_destroy (&slices[i].label);