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 bool show; /* True to show this percentile in the statistics box. */
131 /* Groups of statistics. */
133 #define FRQ_DEFAULT \
134 (BI (FRQ_MEAN) | BI (FRQ_STDDEV) | BI (FRQ_MIN) | BI (FRQ_MAX))
136 (BI (FRQ_SUM) | BI(FRQ_MIN) | BI(FRQ_MAX) \
137 | BI(FRQ_MEAN) | BI(FRQ_SEMEAN) | BI(FRQ_STDDEV) \
138 | BI(FRQ_VARIANCE) | BI(FRQ_KURT) | BI(FRQ_SEKURT) \
139 | BI(FRQ_SKEW) | BI(FRQ_SESKEW) | BI(FRQ_RANGE) \
140 | BI(FRQ_RANGE) | BI(FRQ_MODE) | BI(FRQ_MEDIAN))
144 double x_min; /* X axis minimum value. */
145 double x_max; /* X axis maximum value. */
146 int y_scale; /* Y axis scale: FRQ_FREQ or FRQ_PERCENT. */
148 /* Histograms only. */
149 double y_max; /* Y axis maximum value. */
150 bool draw_normal; /* Whether to draw normal curve. */
152 /* Pie charts only. */
153 bool include_missing; /* Whether to include missing values. */
156 /* Frequency tables. */
158 /* Entire frequency table. */
161 struct hmap data; /* Hash table for accumulating counts. */
162 struct freq *valid; /* Valid freqs. */
163 int n_valid; /* Number of total freqs. */
164 const struct dictionary *dict; /* Source of entries in the table. */
166 struct freq *missing; /* Missing freqs. */
167 int n_missing; /* Number of missing freqs. */
170 double total_cases; /* Sum of weights of all cases. */
171 double valid_cases; /* Sum of weights of valid cases. */
174 /* Per-variable frequency data. */
177 struct variable *var;
179 /* Freqency table. */
180 struct freq_tab tab; /* Frequencies table to use. */
183 int n_groups; /* Number of groups. */
184 double *groups; /* Groups. */
187 double stat[FRQ_N_STATS];
189 /* Variable attributes. */
191 struct fmt_spec print;
198 struct var_freqs *vars;
201 /* Percentiles to calculate and possibly display. */
202 struct percentile *percentiles;
203 int n_percentiles, n_show_percentiles;
205 /* Frequency table display. */
206 int max_categories; /* Maximum categories to show. */
207 int sort; /* FRQ_AVALUE or FRQ_DVALUE
208 or FRQ_ACOUNT or FRQ_DCOUNT. */
210 /* Statistics; number of statistics. */
214 /* Histogram and pie chart settings. */
215 struct frq_chart *hist, *pie;
218 static void determine_charts (struct frq_proc *,
219 const struct cmd_frequencies *);
221 static void calc_stats (const struct var_freqs *, double d[FRQ_N_STATS]);
222 static void calc_percentiles (const struct frq_proc *,
223 const struct var_freqs *);
225 static void precalc (struct frq_proc *, struct casereader *, struct dataset *);
226 static void calc (struct frq_proc *, const struct ccase *,
227 const struct dataset *);
228 static void postcalc (struct frq_proc *, const struct dataset *);
230 static void postprocess_freq_tab (const struct frq_proc *, struct var_freqs *);
231 static void dump_freq_table (const struct var_freqs *,
232 const struct variable *weight_var);
233 static void dump_statistics (const struct frq_proc *, const struct var_freqs *,
234 const struct variable *weight_var);
235 static void cleanup_freq_tab (struct var_freqs *);
237 static void add_percentile (struct frq_proc *, double x, bool show,
238 size_t *allocated_percentiles);
240 static void do_piechart(const struct frq_chart *, const struct variable *,
241 const struct freq_tab *);
243 struct histogram *freq_tab_to_hist(const struct frq_proc *,
244 const struct freq_tab *,
245 const struct variable *);
247 /* Parser and outline. */
250 cmd_frequencies (struct lexer *lexer, struct dataset *ds)
252 struct cmd_frequencies cmd;
254 struct casegrouper *grouper;
255 struct casereader *input, *group;
256 size_t allocated_percentiles;
260 frq.pool = pool_create ();
265 frq.percentiles = NULL;
266 frq.n_percentiles = 0;
267 frq.n_show_percentiles = 0;
272 allocated_percentiles = 0;
274 if (!parse_frequencies (lexer, ds, &cmd, &frq))
276 pool_destroy (frq.pool);
280 /* Figure out when to show frequency tables. */
281 frq.max_categories = (cmd.table == FRQ_NOTABLE ? -1
282 : cmd.table == FRQ_TABLE ? INT_MAX
286 /* Figure out statistics to calculate. */
288 if (cmd.a_statistics[FRQ_ST_DEFAULT] || !cmd.sbc_statistics)
289 frq.stats |= FRQ_DEFAULT;
290 if (cmd.a_statistics[FRQ_ST_ALL])
291 frq.stats |= FRQ_ALL;
292 if (cmd.sort != FRQ_AVALUE && cmd.sort != FRQ_DVALUE)
293 frq.stats &= ~BIT_INDEX (FRQ_MEDIAN);
294 for (i = 0; i < FRQ_N_STATS; i++)
295 if (cmd.a_statistics[st_name[i].st_indx])
296 frq.stats |= BIT_INDEX (i);
297 if (frq.stats & FRQ_KURT)
298 frq.stats |= BIT_INDEX (FRQ_SEKURT);
299 if (frq.stats & FRQ_SKEW)
300 frq.stats |= BIT_INDEX (FRQ_SESKEW);
302 /* Calculate n_stats. */
304 for (i = 0; i < FRQ_N_STATS; i++)
305 if ((frq.stats & BIT_INDEX (i)))
309 determine_charts (&frq, &cmd);
310 if (cmd.sbc_histogram || cmd.sbc_piechart || cmd.sbc_ntiles)
311 cmd.sort = FRQ_AVALUE;
313 /* Work out what percentiles need to be calculated */
314 if ( cmd.sbc_percentiles )
316 for ( i = 0 ; i < MAXLISTS ; ++i )
319 subc_list_double *ptl_list = &cmd.dl_percentiles[i];
320 for ( pl = 0 ; pl < subc_list_double_count(ptl_list); ++pl)
321 add_percentile (&frq, subc_list_double_at(ptl_list, pl) / 100.0,
322 true, &allocated_percentiles);
325 if ( cmd.sbc_ntiles )
327 for ( i = 0 ; i < cmd.sbc_ntiles ; ++i )
330 for (j = 0; j <= cmd.n_ntiles[i]; ++j )
331 add_percentile (&frq, j / (double) cmd.n_ntiles[i], true,
332 &allocated_percentiles);
335 if (frq.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 (&frq, 0.5, true, &allocated_percentiles);
340 frq.stats &= ~BIT_INDEX (FRQ_MEDIAN);
343 if (cmd.sbc_histogram)
345 add_percentile (&frq, 0.25, false, &allocated_percentiles);
346 add_percentile (&frq, 0.75, false, &allocated_percentiles);
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))
358 precalc (&frq, group, ds);
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 pool_destroy (frq.pool);
370 free (frq.percentiles);
374 return ok ? CMD_SUCCESS : CMD_CASCADING_FAILURE;
377 /* Figure out which charts the user requested. */
379 determine_charts (struct frq_proc *frq, const struct cmd_frequencies *cmd)
381 if (cmd->sbc_barchart)
382 msg (SW, _("Bar charts are not implemented."));
384 if (cmd->sbc_histogram)
386 struct frq_chart *hist;
388 hist = frq->hist = xmalloc (sizeof *frq->hist);
389 hist->x_min = cmd->hi_min;
390 hist->x_max = cmd->hi_max;
391 hist->y_scale = cmd->hi_scale;
392 hist->y_max = cmd->hi_scale == FRQ_FREQ ? cmd->hi_freq : cmd->hi_pcnt;
393 hist->draw_normal = cmd->hi_norm != FRQ_NONORMAL;
394 hist->include_missing = false;
396 if (hist->x_min != SYSMIS && hist->x_max != SYSMIS
397 && hist->x_min >= hist->x_max)
399 msg (SE, _("MAX for histogram must be greater than or equal to MIN, "
400 "but MIN was specified as %.15g and MAX as %.15g. "
401 "MIN and MAX will be ignored."),
402 hist->x_min, hist->x_max);
403 hist->x_min = hist->x_max = SYSMIS;
407 if (cmd->sbc_piechart)
409 struct frq_chart *pie;
411 pie = frq->pie = xmalloc (sizeof *frq->pie);
412 pie->x_min = cmd->pie_min;
413 pie->x_max = cmd->pie_max;
414 pie->y_scale = cmd->pie_scale;
415 pie->include_missing = cmd->pie_missing == FRQ_MISSING;
417 if (pie->x_min != SYSMIS && pie->x_max != SYSMIS
418 && pie->x_min >= pie->x_max)
420 msg (SE, _("MAX for pie chart must be greater than or equal to MIN, "
421 "but MIN was specified as %.15g and MAX as %.15g. "
422 "MIN and MAX will be ignored."), pie->x_min, pie->x_max);
423 pie->x_min = pie->x_max = SYSMIS;
428 /* Add data from case C to the frequency table. */
430 calc (struct frq_proc *frq, const struct ccase *c, const struct dataset *ds)
432 double weight = dict_get_case_weight (dataset_dict (ds), c, NULL);
435 for (i = 0; i < frq->n_vars; i++)
437 struct var_freqs *vf = &frq->vars[i];
438 const union value *value = case_data (c, vf->var);
439 size_t hash = value_hash (value, vf->width, 0);
442 f = freq_hmap_search (&vf->tab.data, value, vf->width, hash);
444 f = freq_hmap_insert (&vf->tab.data, value, vf->width, hash);
450 /* Prepares each variable that is the target of FREQUENCIES by setting
451 up its hash table. */
453 precalc (struct frq_proc *frq, struct casereader *input, struct dataset *ds)
458 c = casereader_peek (input, 0);
461 output_split_file_values (ds, c);
465 for (i = 0; i < frq->n_vars; i++)
466 hmap_init (&frq->vars[i].tab.data);
469 /* Finishes up with the variables after frequencies have been
470 calculated. Displays statistics, percentiles, ... */
472 postcalc (struct frq_proc *frq, const struct dataset *ds)
474 const struct dictionary *dict = dataset_dict (ds);
475 const struct variable *wv = dict_get_weight (dict);
478 for (i = 0; i < frq->n_vars; i++)
480 struct var_freqs *vf = &frq->vars[i];
482 postprocess_freq_tab (frq, vf);
484 /* Frequencies tables. */
485 if (vf->tab.n_valid + vf->tab.n_missing <= frq->max_categories)
486 dump_freq_table (vf, wv);
490 dump_statistics (frq, vf, wv);
492 if (frq->hist && var_is_numeric (vf->var) && vf->tab.n_valid > 0)
494 double d[FRQ_N_STATS];
495 struct histogram *histogram;
499 histogram = freq_tab_to_hist (frq, &vf->tab, vf->var);
501 chart_item_submit (histogram_chart_create (
502 histogram->gsl_hist, var_to_string(vf->var),
506 frq->hist->draw_normal));
508 statistic_destroy (&histogram->parent);
512 do_piechart(frq->pie, vf->var, &vf->tab);
514 cleanup_freq_tab (vf);
519 /* Returns true iff the value in struct freq F is non-missing
522 not_missing (const void *f_, const void *v_)
524 const struct freq *f = f_;
525 const struct variable *v = v_;
527 return !var_is_value_missing (v, &f->value, MV_ANY);
530 struct freq_compare_aux
536 bool ascending_value;
540 compare_freq (const void *a_, const void *b_, const void *aux_)
542 const struct freq_compare_aux *aux = aux_;
543 const struct freq *a = a_;
544 const struct freq *b = b_;
546 if (aux->by_freq && a->count != b->count)
548 int cmp = a->count > b->count ? 1 : -1;
549 return aux->ascending_freq ? cmp : -cmp;
553 int cmp = value_compare_3way (&a->value, &b->value, aux->width);
554 return aux->ascending_value ? cmp : -cmp;
557 /* Summarizes the frequency table data for variable V. */
559 postprocess_freq_tab (const struct frq_proc *frq, struct var_freqs *vf)
561 struct freq_tab *ft = &vf->tab;
562 struct freq_compare_aux aux;
564 struct freq *freqs, *f;
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, vf->var);
574 ft->missing = freqs + ft->n_valid;
575 ft->n_missing = count - ft->n_valid;
578 aux.by_freq = frq->sort == FRQ_AFREQ || frq->sort == FRQ_DFREQ;
579 aux.ascending_freq = frq->sort != FRQ_DFREQ;
580 aux.width = vf->width;
581 aux.ascending_value = frq->sort != FRQ_DVALUE;
582 sort (ft->valid, ft->n_valid, sizeof *ft->valid, compare_freq, &aux);
583 sort (ft->missing, ft->n_missing, sizeof *ft->missing, compare_freq, &aux);
585 /* Summary statistics. */
586 ft->valid_cases = 0.0;
587 for(i = 0 ; i < ft->n_valid ; ++i )
590 ft->valid_cases += f->count;
594 ft->total_cases = ft->valid_cases ;
595 for(i = 0 ; i < ft->n_missing ; ++i )
598 ft->total_cases += f->count;
603 /* Frees the frequency table for variable V. */
605 cleanup_freq_tab (struct var_freqs *vf)
607 free (vf->tab.valid);
608 freq_hmap_destroy (&vf->tab.data, vf->width);
611 /* Parses the VARIABLES subcommand. */
613 frq_custom_variables (struct lexer *lexer, struct dataset *ds,
614 struct cmd_frequencies *cmd UNUSED, void *frq_ UNUSED)
616 struct frq_proc *frq = frq_;
617 struct variable **vars;
621 lex_match (lexer, '=');
622 if (lex_token (lexer) != T_ALL
623 && (lex_token (lexer) != T_ID
624 || dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) == NULL))
627 /* Get list of current variables, to avoid duplicates. */
628 vars = xmalloc (frq->n_vars * sizeof *vars);
629 n_vars = frq->n_vars;
630 for (i = 0; i < frq->n_vars; i++)
631 vars[i] = frq->vars[i].var;
633 if (!parse_variables (lexer, dataset_dict (ds), &vars, &n_vars,
634 PV_APPEND | PV_NO_SCRATCH))
637 frq->vars = xrealloc (frq->vars, n_vars * sizeof *frq->vars);
638 for (i = frq->n_vars; i < n_vars; i++)
640 struct variable *var = vars[i];
641 struct var_freqs *vf = &frq->vars[i];
644 vf->tab.valid = vf->tab.missing = NULL;
645 vf->tab.dict = dataset_dict (ds);
648 vf->width = var_get_width (var);
649 vf->print = *var_get_print_format (var);
651 frq->n_vars = n_vars;
658 /* Parses the GROUPED subcommand, setting the n_grouped, grouped
659 fields of specified variables. */
661 frq_custom_grouped (struct lexer *lexer, struct dataset *ds, struct cmd_frequencies *cmd UNUSED, void *frq_ UNUSED)
663 struct frq_proc *frq = frq_;
665 lex_match (lexer, '=');
666 if ((lex_token (lexer) == T_ID && dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) != NULL)
667 || lex_token (lexer) == T_ID)
672 /* Max, current size of list; list itself. */
678 const struct variable **v;
680 if (!parse_variables_const (lexer, dataset_dict (ds), &v, &n,
681 PV_NO_DUPLICATE | PV_NUMERIC))
683 if (lex_match (lexer, '('))
687 while (lex_integer (lexer))
692 dl = pool_nrealloc (frq->pool, dl, ml, sizeof *dl);
694 dl[nl++] = lex_tokval (lexer);
696 lex_match (lexer, ',');
698 /* Note that nl might still be 0 and dl might still be
699 NULL. That's okay. */
700 if (!lex_match (lexer, ')'))
703 msg (SE, _("`)' expected after GROUPED interval list."));
713 for (i = 0; i < n; i++)
717 for (j = 0; j < frq->n_vars; j++)
719 struct var_freqs *vf = &frq->vars[j];
722 if (vf->groups != NULL)
723 msg (SE, _("Variables %s specified multiple times on "
724 "GROUPED subcommand."), var_get_name (v[i]));
733 msg (SE, _("Variables %s specified on GROUPED but not on "
734 "VARIABLES."), var_get_name (v[i]));
740 if (!lex_match (lexer, '/'))
742 if ((lex_token (lexer) != T_ID || dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) != NULL)
743 && lex_token (lexer) != T_ALL)
745 lex_put_back (lexer, '/');
753 /* Adds X to the list of percentiles, keeping the list in proper
754 order. If SHOW is true, the percentile will be shown in the statistics
755 box, otherwise it will be hidden. */
757 add_percentile (struct frq_proc *frq, double x, bool show,
758 size_t *allocated_percentiles)
762 /* Do nothing if it's already in the list */
763 for (i = 0; i < frq->n_percentiles; i++)
765 struct percentile *pc = &frq->percentiles[i];
767 if ( fabs(x - pc->p) < DBL_EPSILON )
769 if (show && !pc->show)
771 frq->n_show_percentiles++;
781 if (frq->n_percentiles >= *allocated_percentiles)
782 frq->percentiles = x2nrealloc (frq->percentiles, allocated_percentiles,
783 sizeof *frq->percentiles);
784 insert_element (frq->percentiles, frq->n_percentiles,
785 sizeof *frq->percentiles, i);
786 frq->percentiles[i].p = x;
787 frq->percentiles[i].show = show;
788 frq->n_percentiles++;
790 frq->n_show_percentiles++;
793 /* Comparison functions. */
796 /* Frequency table display. */
798 /* Displays a full frequency table for variable V. */
800 dump_freq_table (const struct var_freqs *vf, const struct variable *wv)
802 const struct fmt_spec *wfmt = wv ? var_get_print_format (wv) : &F_8_0;
803 const struct freq_tab *ft = &vf->tab;
808 double cum_total = 0.0;
809 double cum_freq = 0.0;
811 static const char *headings[] = {
820 n_categories = ft->n_valid + ft->n_missing;
821 t = tab_create (6, n_categories + 2);
822 tab_headers (t, 0, 0, 1, 0);
824 for (x = 0; x < 6; x++)
825 tab_text (t, x, 0, TAB_CENTER | TAT_TITLE, gettext (headings[x]));
828 for (f = ft->valid; f < ft->missing; f++)
831 double percent, valid_percent;
833 cum_freq += f->count;
835 percent = f->count / ft->total_cases * 100.0;
836 valid_percent = f->count / ft->valid_cases * 100.0;
837 cum_total += valid_percent;
839 label = var_lookup_value_label (vf->var, &f->value);
841 tab_text (t, 0, r, TAB_LEFT, label);
843 tab_value (t, 1, r, TAB_NONE, &f->value, ft->dict, &vf->print);
844 tab_double (t, 2, r, TAB_NONE, f->count, wfmt);
845 tab_double (t, 3, r, TAB_NONE, percent, NULL);
846 tab_double (t, 4, r, TAB_NONE, valid_percent, NULL);
847 tab_double (t, 5, r, TAB_NONE, cum_total, NULL);
850 for (; f < &ft->valid[n_categories]; f++)
854 cum_freq += f->count;
856 label = var_lookup_value_label (vf->var, &f->value);
858 tab_text (t, 0, r, TAB_LEFT, label);
860 tab_value (t, 1, r, TAB_NONE, &f->value, ft->dict, &vf->print);
861 tab_double (t, 2, r, TAB_NONE, f->count, wfmt);
862 tab_double (t, 3, r, TAB_NONE,
863 f->count / ft->total_cases * 100.0, NULL);
864 tab_text (t, 4, r, TAB_NONE, _("Missing"));
868 tab_box (t, TAL_1, TAL_1, -1, TAL_1, 0, 0, 5, r);
869 tab_hline (t, TAL_2, 0, 5, 1);
870 tab_hline (t, TAL_2, 0, 5, r);
871 tab_joint_text (t, 0, r, 1, r, TAB_RIGHT | TAT_TITLE, _("Total"));
872 tab_vline (t, TAL_0, 1, r, r);
873 tab_double (t, 2, r, TAB_NONE, cum_freq, wfmt);
874 tab_fixed (t, 3, r, TAB_NONE, 100.0, 5, 1);
875 tab_fixed (t, 4, r, TAB_NONE, 100.0, 5, 1);
877 tab_title (t, "%s", var_to_string (vf->var));
881 /* Statistical display. */
884 calc_percentile (double p, double valid_cases, double x1, double x2)
888 s = (settings_get_algorithm () != COMPATIBLE
889 ? modf ((valid_cases - 1) * p, &dummy)
890 : modf ((valid_cases + 1) * p - 1, &dummy));
892 return x1 + (x2 - x1) * s;
895 /* Calculates all of the percentiles for VF within FRQ. */
897 calc_percentiles (const struct frq_proc *frq, const struct var_freqs *vf)
899 const struct freq_tab *ft = &vf->tab;
900 double W = ft->valid_cases;
901 const struct freq *f;
905 assert (ft->n_valid > 0);
909 for (f = ft->valid; f < ft->missing; f++)
912 for (; percentile_idx < frq->n_percentiles; percentile_idx++)
914 struct percentile *pc = &frq->percentiles[percentile_idx];
917 tp = (settings_get_algorithm () == ENHANCED
919 : (W + 1) * pc->p - 1);
925 && (rank - (f->count - 1) > tp || f + 1 >= ft->missing))
926 pc->value = f->value.f;
928 pc->value = calc_percentile (pc->p, W, f->value.f, f[1].value.f);
931 for (; percentile_idx < frq->n_percentiles; percentile_idx++)
933 struct percentile *pc = &frq->percentiles[percentile_idx];
934 pc->value = ft->valid[ft->n_valid - 1].value.f;
938 /* Calculates all the pertinent statistics for VF, putting them in array
941 calc_stats (const struct var_freqs *vf, double d[FRQ_N_STATS])
943 const struct freq_tab *ft = &vf->tab;
944 double W = ft->valid_cases;
945 const struct freq *f;
950 assert (ft->n_valid > 0);
952 /* Calculate the mode. */
955 for (f = ft->valid; f < ft->missing; f++)
957 if (most_often < f->count)
959 most_often = f->count;
962 else if (most_often == f->count)
964 /* A duplicate mode is undefined.
965 FIXME: keep track of *all* the modes. */
970 /* Calculate moments. */
971 m = moments_create (MOMENT_KURTOSIS);
972 for (f = ft->valid; f < ft->missing; f++)
973 moments_pass_one (m, f->value.f, f->count);
974 for (f = ft->valid; f < ft->missing; f++)
975 moments_pass_two (m, f->value.f, f->count);
976 moments_calculate (m, NULL, &d[FRQ_MEAN], &d[FRQ_VARIANCE],
977 &d[FRQ_SKEW], &d[FRQ_KURT]);
980 /* Formulas below are taken from _SPSS Statistical Algorithms_. */
981 d[FRQ_MIN] = ft->valid[0].value.f;
982 d[FRQ_MAX] = ft->valid[ft->n_valid - 1].value.f;
983 d[FRQ_MODE] = X_mode;
984 d[FRQ_RANGE] = d[FRQ_MAX] - d[FRQ_MIN];
985 d[FRQ_SUM] = d[FRQ_MEAN] * W;
986 d[FRQ_STDDEV] = sqrt (d[FRQ_VARIANCE]);
987 d[FRQ_SEMEAN] = d[FRQ_STDDEV] / sqrt (W);
988 d[FRQ_SESKEW] = calc_seskew (W);
989 d[FRQ_SEKURT] = calc_sekurt (W);
992 /* Displays a table of all the statistics requested for variable V. */
994 dump_statistics (const struct frq_proc *frq, const struct var_freqs *vf,
995 const struct variable *wv)
997 const struct fmt_spec *wfmt = wv ? var_get_print_format (wv) : &F_8_0;
998 const struct freq_tab *ft = &vf->tab;
999 double stat_value[FRQ_N_STATS];
1000 struct tab_table *t;
1003 if (var_is_alpha (vf->var))
1006 if (ft->n_valid == 0)
1008 msg (SW, _("No valid data for variable %s; statistics not displayed."),
1009 var_get_name (vf->var));
1012 calc_stats (vf, stat_value);
1013 calc_percentiles (frq, vf);
1015 t = tab_create (3, frq->n_stats + frq->n_show_percentiles + 2);
1017 tab_box (t, TAL_1, TAL_1, -1, -1 , 0 , 0 , 2, tab_nr(t) - 1) ;
1020 tab_vline (t, TAL_1 , 2, 0, tab_nr(t) - 1);
1021 tab_vline (t, TAL_GAP , 1, 0, tab_nr(t) - 1 ) ;
1023 r=2; /* N missing and N valid are always dumped */
1025 for (i = 0; i < FRQ_N_STATS; i++)
1026 if (frq->stats & BIT_INDEX (i))
1028 tab_text (t, 0, r, TAB_LEFT | TAT_TITLE,
1029 gettext (st_name[i].s10));
1030 tab_double (t, 2, r, TAB_NONE, stat_value[i], NULL);
1034 tab_text (t, 0, 0, TAB_LEFT | TAT_TITLE, _("N"));
1035 tab_text (t, 1, 0, TAB_LEFT | TAT_TITLE, _("Valid"));
1036 tab_text (t, 1, 1, TAB_LEFT | TAT_TITLE, _("Missing"));
1038 tab_double (t, 2, 0, TAB_NONE, ft->valid_cases, wfmt);
1039 tab_double (t, 2, 1, TAB_NONE, ft->total_cases - ft->valid_cases, wfmt);
1041 for (i = 0; i < frq->n_percentiles; i++, r++)
1043 struct percentile *pc = &frq->percentiles[i];
1050 tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, _("Percentiles"));
1054 tab_text (t, 1, r, TAB_LEFT, _("50 (Median)"));
1056 tab_fixed (t, 1, r, TAB_LEFT, pc->p * 100, 3, 0);
1057 tab_double (t, 2, r, TAB_NONE, pc->value,
1058 var_get_print_format (vf->var));
1061 tab_title (t, "%s", var_to_string (vf->var));
1067 calculate_iqr (const struct frq_proc *frq)
1073 for (i = 0; i < frq->n_percentiles; i++)
1075 struct percentile *pc = &frq->percentiles[i];
1077 if (fabs (0.25 - pc->p) < DBL_EPSILON)
1079 else if (fabs (0.75 - pc->p) < DBL_EPSILON)
1083 return q1 == SYSMIS || q3 == SYSMIS ? SYSMIS : q3 - q1;
1087 chart_includes_value (const struct frq_chart *chart,
1088 const struct variable *var,
1089 const union value *value)
1091 if (!chart->include_missing && var_is_value_missing (var, value, MV_ANY))
1094 if (var_is_numeric (var)
1095 && ((chart->x_min != SYSMIS && value->f < chart->x_min)
1096 || (chart->x_max != SYSMIS && value->f > chart->x_max)))
1102 /* Create a gsl_histogram from a freq_tab */
1104 freq_tab_to_hist (const struct frq_proc *frq, const struct freq_tab *ft,
1105 const struct variable *var)
1107 double x_min, x_max, valid_freq;
1110 struct histogram *histogram;
1114 /* Find out the extremes of the x value, within the range to be included in
1115 the histogram, and sum the total frequency of those values. */
1119 for (i = 0; i < ft->n_valid; i++)
1121 const struct freq *f = &ft->valid[i];
1122 if (chart_includes_value (frq->hist, var, &f->value))
1124 x_min = MIN (x_min, f->value.f);
1125 x_max = MAX (x_max, f->value.f);
1126 valid_freq += f->count;
1130 /* Freedman-Diaconis' choice of bin width. */
1131 iqr = calculate_iqr (frq);
1134 double bin_width = 2 * iqr / pow (valid_freq, 1.0 / 3.0);
1135 bins = (x_max - x_min) / bin_width;
1138 else if (bins > 400)
1144 histogram = histogram_create (bins, x_min, x_max);
1145 for (i = 0; i < ft->n_valid; i++)
1147 const struct freq *f = &ft->valid[i];
1148 if (chart_includes_value (frq->hist, var, &f->value))
1149 histogram_add (histogram, f->value.f, f->count);
1156 add_slice (const struct frq_chart *pie, const struct freq *freq,
1157 const struct variable *var, struct slice *slice)
1159 if (chart_includes_value (pie, var, &freq->value))
1161 ds_init_empty (&slice->label);
1162 var_append_value_name (var, &freq->value, &slice->label);
1163 slice->magnitude = freq->count;
1170 /* Allocate an array of slices and fill them from the data in frq_tab
1171 n_slices will contain the number of slices allocated.
1172 The caller is responsible for freeing slices
1174 static struct slice *
1175 freq_tab_to_slice_array(const struct frq_chart *pie,
1176 const struct freq_tab *frq_tab,
1177 const struct variable *var,
1180 struct slice *slices;
1184 slices = xnmalloc (frq_tab->n_valid + frq_tab->n_missing, sizeof *slices);
1187 for (i = 0; i < frq_tab->n_valid; i++)
1188 n_slices += add_slice (pie, &frq_tab->valid[i], var, &slices[n_slices]);
1189 for (i = 0; i < frq_tab->n_missing; i++)
1190 n_slices += add_slice (pie, &frq_tab->missing[i], var, &slices[n_slices]);
1192 *n_slicesp = n_slices;
1200 do_piechart(const struct frq_chart *pie, const struct variable *var,
1201 const struct freq_tab *frq_tab)
1203 struct slice *slices;
1206 slices = freq_tab_to_slice_array (pie, frq_tab, var, &n_slices);
1209 msg (SW, _("Omitting pie chart for %s, which has only %d unique values."),
1210 var_get_name (var), n_slices);
1211 else if (n_slices > 50)
1212 msg (SW, _("Omitting pie chart for %s, which has over 50 unique values."),
1213 var_get_name (var));
1215 chart_item_submit (piechart_create (var_to_string(var), slices, n_slices));
1217 for (i = 0; i < n_slices; i++)
1218 ds_destroy (&slices[i].label);