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. */
135 /* Groups of statistics. */
137 #define FRQ_DEFAULT \
138 (BI (FRQ_MEAN) | BI (FRQ_STDDEV) | BI (FRQ_MIN) | BI (FRQ_MAX))
140 (BI (FRQ_SUM) | BI(FRQ_MIN) | BI(FRQ_MAX) \
141 | BI(FRQ_MEAN) | BI(FRQ_SEMEAN) | BI(FRQ_STDDEV) \
142 | BI(FRQ_VARIANCE) | BI(FRQ_KURT) | BI(FRQ_SEKURT) \
143 | BI(FRQ_SKEW) | BI(FRQ_SESKEW) | BI(FRQ_RANGE) \
144 | BI(FRQ_RANGE) | BI(FRQ_MODE) | BI(FRQ_MEDIAN))
146 /* Statistics; number of statistics. */
147 static unsigned long stats;
152 double x_min; /* X axis minimum value. */
153 double x_max; /* X axis maximum value. */
154 int y_scale; /* Y axis scale: FRQ_FREQ or FRQ_PERCENT. */
156 /* Histograms only. */
157 double y_max; /* Y axis maximum value. */
158 bool draw_normal; /* Whether to draw normal curve. */
160 /* Pie charts only. */
161 bool include_missing; /* Whether to include missing values. */
164 /* Histogram and pie chart settings. */
165 static struct frq_chart hist, pie;
167 /* Parsed command. */
168 static struct cmd_frequencies cmd;
170 /* Frequency tables. */
172 /* Entire frequency table. */
175 struct hmap data; /* Hash table for accumulating counts. */
176 struct freq *valid; /* Valid freqs. */
177 int n_valid; /* Number of total freqs. */
178 const struct dictionary *dict; /* Source of entries in the table. */
180 struct freq *missing; /* Missing freqs. */
181 int n_missing; /* Number of missing freqs. */
184 double total_cases; /* Sum of weights of all cases. */
185 double valid_cases; /* Sum of weights of valid cases. */
188 /* Per-variable frequency data. */
191 struct variable *var;
193 /* Freqency table. */
194 struct freq_tab tab; /* Frequencies table to use. */
197 int n_groups; /* Number of groups. */
198 double *groups; /* Groups. */
201 double stat[FRQ_N_STATS];
203 /* Variable attributes. */
205 struct fmt_spec print;
212 struct var_freqs *vars;
215 struct percentile *percentiles;
216 int n_percentiles, n_show_percentiles;
219 static void determine_charts (void);
221 static void calc_stats (const struct frq_proc *, const struct var_freqs *,
222 double d[FRQ_N_STATS]);
224 static void precalc (struct frq_proc *, struct casereader *, struct dataset *);
225 static void calc (struct frq_proc *, const struct ccase *,
226 const struct dataset *);
227 static void postcalc (struct frq_proc *, const struct dataset *);
229 static void postprocess_freq_tab (struct var_freqs *);
230 static void dump_freq_table (const struct var_freqs *,
231 const struct variable *weight_var);
232 static void dump_statistics (const struct frq_proc *, const struct var_freqs *,
233 const struct variable *weight_var);
234 static void cleanup_freq_tab (struct var_freqs *);
236 static algo_compare_func compare_value_numeric_a, compare_value_alpha_a;
237 static algo_compare_func compare_value_numeric_d, compare_value_alpha_d;
238 static algo_compare_func compare_freq_numeric_a, compare_freq_alpha_a;
239 static algo_compare_func compare_freq_numeric_d, compare_freq_alpha_d;
241 static void add_percentile (struct frq_proc *, double x, bool show,
242 size_t *allocated_percentiles);
244 static void do_piechart(const struct variable *var,
245 const struct freq_tab *frq_tab);
247 struct histogram *freq_tab_to_hist(const struct frq_proc *,
248 const struct freq_tab *,
249 const struct variable *);
251 /* Parser and outline. */
254 cmd_frequencies (struct lexer *lexer, struct dataset *ds)
257 struct casegrouper *grouper;
258 struct casereader *input, *group;
259 size_t allocated_percentiles;
263 frq.pool = pool_create ();
268 frq.percentiles = NULL;
269 frq.n_percentiles = 0;
270 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 statistics to calculate. */
282 if (cmd.a_statistics[FRQ_ST_DEFAULT] || !cmd.sbc_statistics)
283 stats |= FRQ_DEFAULT;
284 if (cmd.a_statistics[FRQ_ST_ALL])
286 if (cmd.sort != FRQ_AVALUE && cmd.sort != FRQ_DVALUE)
287 stats &= ~BIT_INDEX (FRQ_MEDIAN);
288 for (i = 0; i < FRQ_N_STATS; i++)
289 if (cmd.a_statistics[st_name[i].st_indx])
290 stats |= BIT_INDEX (i);
291 if (stats & FRQ_KURT)
292 stats |= BIT_INDEX (FRQ_SEKURT);
293 if (stats & FRQ_SKEW)
294 stats |= BIT_INDEX (FRQ_SESKEW);
296 /* Calculate n_stats. */
298 for (i = 0; i < FRQ_N_STATS; i++)
299 if ((stats & BIT_INDEX (i)))
304 if (cmd.sbc_histogram || cmd.sbc_piechart || cmd.sbc_ntiles)
305 cmd.sort = FRQ_AVALUE;
307 /* Work out what percentiles need to be calculated */
308 if ( cmd.sbc_percentiles )
310 for ( i = 0 ; i < MAXLISTS ; ++i )
313 subc_list_double *ptl_list = &cmd.dl_percentiles[i];
314 for ( pl = 0 ; pl < subc_list_double_count(ptl_list); ++pl)
315 add_percentile (&frq, subc_list_double_at(ptl_list, pl) / 100.0,
316 true, &allocated_percentiles);
319 if ( cmd.sbc_ntiles )
321 for ( i = 0 ; i < cmd.sbc_ntiles ; ++i )
324 for (j = 0; j <= cmd.n_ntiles[i]; ++j )
325 add_percentile (&frq, j / (double) cmd.n_ntiles[i], true,
326 &allocated_percentiles);
329 if (stats & BIT_INDEX (FRQ_MEDIAN))
331 /* Treat the median as the 50% percentile.
332 We output it in the percentiles table as "50 (Median)." */
333 add_percentile (&frq, 0.5, true, &allocated_percentiles);
334 stats &= ~BIT_INDEX (FRQ_MEDIAN);
337 if (cmd.sbc_histogram)
339 add_percentile (&frq, 0.25, false, &allocated_percentiles);
340 add_percentile (&frq, 0.75, false, &allocated_percentiles);
344 input = casereader_create_filter_weight (proc_open (ds), dataset_dict (ds),
346 grouper = casegrouper_create_splits (input, dataset_dict (ds));
347 for (; casegrouper_get_next_group (grouper, &group);
348 casereader_destroy (group))
352 precalc (&frq, group, ds);
353 for (; (c = casereader_read (group)) != NULL; case_unref (c))
357 ok = casegrouper_destroy (grouper);
358 ok = proc_commit (ds) && ok;
360 free_frequencies(&cmd);
362 pool_destroy (frq.pool);
364 free (frq.percentiles);
366 return ok ? CMD_SUCCESS : CMD_CASCADING_FAILURE;
369 /* Figure out which charts the user requested. */
371 determine_charts (void)
373 if (cmd.sbc_barchart)
374 msg (SW, _("Bar charts are not implemented."));
376 if (cmd.sbc_histogram)
378 hist.x_min = cmd.hi_min;
379 hist.x_max = cmd.hi_max;
380 hist.y_scale = cmd.hi_scale;
381 hist.y_max = cmd.hi_scale == FRQ_FREQ ? cmd.hi_freq : cmd.hi_pcnt;
382 hist.draw_normal = cmd.hi_norm != FRQ_NONORMAL;
383 hist.include_missing = false;
385 if (hist.x_min != SYSMIS && hist.x_max != SYSMIS
386 && hist.x_min >= hist.x_max)
388 msg (SE, _("MAX for histogram must be greater than or equal to MIN, "
389 "but MIN was specified as %.15g and MAX as %.15g. "
390 "MIN and MAX will be ignored."), hist.x_min, hist.x_max);
391 hist.x_min = hist.x_max = SYSMIS;
395 if (cmd.sbc_piechart)
397 pie.x_min = cmd.pie_min;
398 pie.x_max = cmd.pie_max;
399 pie.y_scale = cmd.pie_scale;
400 pie.include_missing = cmd.pie_missing == FRQ_MISSING;
402 if (pie.x_min != SYSMIS && pie.x_max != SYSMIS
403 && pie.x_min >= pie.x_max)
405 msg (SE, _("MAX for pie chart must be greater than or equal to MIN, "
406 "but MIN was specified as %.15g and MAX as %.15g. "
407 "MIN and MAX will be ignored."), pie.x_min, pie.x_max);
408 pie.x_min = pie.x_max = SYSMIS;
414 /* Add data from case C to the frequency table. */
416 calc (struct frq_proc *frq, const struct ccase *c, const struct dataset *ds)
418 double weight = dict_get_case_weight (dataset_dict (ds), c, NULL);
421 for (i = 0; i < frq->n_vars; i++)
423 struct var_freqs *vf = &frq->vars[i];
424 const union value *value = case_data (c, vf->var);
425 size_t hash = value_hash (value, vf->width, 0);
428 f = freq_hmap_search (&vf->tab.data, value, vf->width, hash);
430 f = freq_hmap_insert (&vf->tab.data, value, vf->width, hash);
436 /* Prepares each variable that is the target of FREQUENCIES by setting
437 up its hash table. */
439 precalc (struct frq_proc *frq, struct casereader *input, struct dataset *ds)
444 c = casereader_peek (input, 0);
447 output_split_file_values (ds, c);
451 for (i = 0; i < frq->n_vars; i++)
452 hmap_init (&frq->vars[i].tab.data);
455 /* Finishes up with the variables after frequencies have been
456 calculated. Displays statistics, percentiles, ... */
458 postcalc (struct frq_proc *frq, const struct dataset *ds)
460 const struct dictionary *dict = dataset_dict (ds);
461 const struct variable *wv = dict_get_weight (dict);
464 for (i = 0; i < frq->n_vars; i++)
466 struct var_freqs *vf = &frq->vars[i];
469 postprocess_freq_tab (vf);
471 /* Frequencies tables. */
472 n_categories = vf->tab.n_valid + vf->tab.n_missing;
473 if (cmd.table == FRQ_TABLE
474 || (cmd.table == FRQ_LIMIT && n_categories <= cmd.limit))
475 dump_freq_table (vf, wv);
479 dump_statistics (frq, vf, wv);
481 if (cmd.sbc_histogram && var_is_numeric (vf->var) && vf->tab.n_valid > 0)
483 double d[FRQ_N_STATS];
484 struct histogram *histogram;
486 calc_stats (frq, vf, d);
488 histogram = freq_tab_to_hist (frq, &vf->tab, vf->var);
490 chart_item_submit (histogram_chart_create (
491 histogram->gsl_hist, var_to_string(vf->var),
497 statistic_destroy (&histogram->parent);
500 if (cmd.sbc_piechart)
501 do_piechart(vf->var, &vf->tab);
503 cleanup_freq_tab (vf);
508 /* Returns the comparison function that should be used for
509 sorting a frequency table by FRQ_SORT using VAL_TYPE
511 static algo_compare_func *
512 get_freq_comparator (int frq_sort, enum val_type val_type)
514 bool is_numeric = val_type == VAL_NUMERIC;
518 return is_numeric ? compare_value_numeric_a : compare_value_alpha_a;
520 return is_numeric ? compare_value_numeric_d : compare_value_alpha_d;
522 return is_numeric ? compare_freq_numeric_a : compare_freq_alpha_a;
524 return is_numeric ? compare_freq_numeric_d : compare_freq_alpha_d;
530 /* Returns true iff the value in struct freq F is non-missing
533 not_missing (const void *f_, const void *v_)
535 const struct freq *f = f_;
536 const struct variable *v = v_;
538 return !var_is_value_missing (v, &f->value, MV_ANY);
541 /* Summarizes the frequency table data for variable V. */
543 postprocess_freq_tab (struct var_freqs *vf)
545 struct freq_tab *ft = &vf->tab;
546 algo_compare_func *compare;
548 struct freq *freqs, *f;
551 /* Extract data from hash table. */
552 count = hmap_count (&ft->data);
553 freqs = freq_hmap_extract (&ft->data);
555 /* Put data into ft. */
557 ft->n_valid = partition (freqs, count, sizeof *freqs, not_missing, vf->var);
558 ft->missing = freqs + ft->n_valid;
559 ft->n_missing = count - ft->n_valid;
562 compare = get_freq_comparator (cmd.sort, var_get_type (vf->var));
563 sort (ft->valid, ft->n_valid, sizeof *ft->valid, compare, vf);
564 sort (ft->missing, ft->n_missing, sizeof *ft->missing, compare, vf);
566 /* Summary statistics. */
567 ft->valid_cases = 0.0;
568 for(i = 0 ; i < ft->n_valid ; ++i )
571 ft->valid_cases += f->count;
575 ft->total_cases = ft->valid_cases ;
576 for(i = 0 ; i < ft->n_missing ; ++i )
579 ft->total_cases += f->count;
584 /* Frees the frequency table for variable V. */
586 cleanup_freq_tab (struct var_freqs *vf)
588 free (vf->tab.valid);
589 freq_hmap_destroy (&vf->tab.data, vf->width);
592 /* Parses the VARIABLES subcommand. */
594 frq_custom_variables (struct lexer *lexer, struct dataset *ds,
595 struct cmd_frequencies *cmd UNUSED, void *frq_ UNUSED)
597 struct frq_proc *frq = frq_;
598 struct variable **vars;
602 lex_match (lexer, '=');
603 if (lex_token (lexer) != T_ALL
604 && (lex_token (lexer) != T_ID
605 || dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) == NULL))
608 /* Get list of current variables, to avoid duplicates. */
609 vars = xmalloc (frq->n_vars * sizeof *vars);
610 n_vars = frq->n_vars;
611 for (i = 0; i < frq->n_vars; i++)
612 vars[i] = frq->vars[i].var;
614 if (!parse_variables (lexer, dataset_dict (ds), &vars, &n_vars,
615 PV_APPEND | PV_NO_SCRATCH))
618 frq->vars = xrealloc (frq->vars, n_vars * sizeof *frq->vars);
619 for (i = frq->n_vars; i < n_vars; i++)
621 struct variable *var = vars[i];
622 struct var_freqs *vf = &frq->vars[i];
625 vf->tab.valid = vf->tab.missing = NULL;
626 vf->tab.dict = dataset_dict (ds);
629 vf->width = var_get_width (var);
630 vf->print = *var_get_print_format (var);
632 frq->n_vars = n_vars;
639 /* Parses the GROUPED subcommand, setting the n_grouped, grouped
640 fields of specified variables. */
642 frq_custom_grouped (struct lexer *lexer, struct dataset *ds, struct cmd_frequencies *cmd UNUSED, void *frq_ UNUSED)
644 struct frq_proc *frq = frq_;
646 lex_match (lexer, '=');
647 if ((lex_token (lexer) == T_ID && dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) != NULL)
648 || lex_token (lexer) == T_ID)
653 /* Max, current size of list; list itself. */
659 const struct variable **v;
661 if (!parse_variables_const (lexer, dataset_dict (ds), &v, &n,
662 PV_NO_DUPLICATE | PV_NUMERIC))
664 if (lex_match (lexer, '('))
668 while (lex_integer (lexer))
673 dl = pool_nrealloc (frq->pool, dl, ml, sizeof *dl);
675 dl[nl++] = lex_tokval (lexer);
677 lex_match (lexer, ',');
679 /* Note that nl might still be 0 and dl might still be
680 NULL. That's okay. */
681 if (!lex_match (lexer, ')'))
684 msg (SE, _("`)' expected after GROUPED interval list."));
694 for (i = 0; i < n; i++)
698 for (j = 0; j < frq->n_vars; j++)
700 struct var_freqs *vf = &frq->vars[j];
703 if (vf->groups != NULL)
704 msg (SE, _("Variables %s specified multiple times on "
705 "GROUPED subcommand."), var_get_name (v[i]));
714 msg (SE, _("Variables %s specified on GROUPED but not on "
715 "VARIABLES."), var_get_name (v[i]));
721 if (!lex_match (lexer, '/'))
723 if ((lex_token (lexer) != T_ID || dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) != NULL)
724 && lex_token (lexer) != T_ALL)
726 lex_put_back (lexer, '/');
734 /* Adds X to the list of percentiles, keeping the list in proper
735 order. If SHOW is true, the percentile will be shown in the statistics
736 box, otherwise it will be hidden. */
738 add_percentile (struct frq_proc *frq, double x, bool show,
739 size_t *allocated_percentiles)
743 /* Do nothing if it's already in the list */
744 for (i = 0; i < frq->n_percentiles; i++)
746 struct percentile *pc = &frq->percentiles[i];
748 if ( fabs(x - pc->p) < DBL_EPSILON )
750 if (show && !pc->show)
752 frq->n_show_percentiles++;
762 if (frq->n_percentiles >= *allocated_percentiles)
763 frq->percentiles = x2nrealloc (frq->percentiles, allocated_percentiles,
764 sizeof *frq->percentiles);
765 insert_element (frq->percentiles, frq->n_percentiles,
766 sizeof *frq->percentiles, i);
767 frq->percentiles[i].p = x;
768 frq->percentiles[i].show = show;
769 frq->n_percentiles++;
771 frq->n_show_percentiles++;
774 /* Comparison functions. */
776 /* Ascending numeric compare of values. */
778 compare_value_numeric_a (const void *a_, const void *b_,
779 const void *vf_ 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 *vf_)
796 const struct freq *a = a_;
797 const struct freq *b = b_;
798 const struct var_freqs *vf = vf_;
800 return value_compare_3way (&a->value, &b->value, vf->width);
803 /* Descending numeric compare of values. */
805 compare_value_numeric_d (const void *a, const void *b, const void *vf_ UNUSED)
807 return -compare_value_numeric_a (a, b, vf_);
810 /* Descending string compare of values. */
812 compare_value_alpha_d (const void *a, const void *b, const void *vf_)
814 return -compare_value_alpha_a (a, b, vf_);
817 /* Ascending numeric compare of frequency;
818 secondary key on ascending numeric value. */
820 compare_freq_numeric_a (const void *a_, const void *b_, const void *vf_ UNUSED)
822 const struct freq *a = a_;
823 const struct freq *b = b_;
825 if (a->count > b->count)
827 else if (a->count < b->count)
830 if (a->value.f > b->value.f)
832 else if (a->value.f < b->value.f)
838 /* Ascending numeric compare of frequency;
839 secondary key on ascending string value. */
841 compare_freq_alpha_a (const void *a_, const void *b_, const void *vf_)
843 const struct freq *a = a_;
844 const struct freq *b = b_;
845 const struct var_freqs *vf = vf_;
847 if (a->count > b->count)
849 else if (a->count < b->count)
852 return value_compare_3way (&a->value, &b->value, vf->width);
855 /* Descending numeric compare of frequency;
856 secondary key on ascending numeric value. */
858 compare_freq_numeric_d (const void *a_, const void *b_, const void *vf_ UNUSED)
860 const struct freq *a = a_;
861 const struct freq *b = b_;
863 if (a->count > b->count)
865 else if (a->count < b->count)
868 if (a->value.f > b->value.f)
870 else if (a->value.f < b->value.f)
876 /* Descending numeric compare of frequency;
877 secondary key on ascending string value. */
879 compare_freq_alpha_d (const void *a_, const void *b_, const void *vf_)
881 const struct freq *a = a_;
882 const struct freq *b = b_;
883 const struct var_freqs *vf = vf_;
885 if (a->count > b->count)
887 else if (a->count < b->count)
890 return value_compare_3way (&a->value, &b->value, vf->width);
893 /* Frequency table display. */
895 /* Displays a full frequency table for variable V. */
897 dump_freq_table (const struct var_freqs *vf, const struct variable *wv)
899 const struct fmt_spec *wfmt = wv ? var_get_print_format (wv) : &F_8_0;
900 const struct freq_tab *ft = &vf->tab;
905 double cum_total = 0.0;
906 double cum_freq = 0.0;
908 static const char *headings[] = {
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 (vf->var, &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 (vf->var, &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 (vf->var));
978 /* Statistical display. */
980 /* Calculates all the pertinent statistics for variable V, putting them in
983 calc_stats (const struct frq_proc *frq,
984 const struct var_freqs *vf, double d[FRQ_N_STATS])
986 const struct freq_tab *ft = &vf->tab;
987 double W = ft->valid_cases;
998 /* Calculate percentiles. */
1000 assert (ft->n_valid > 0);
1002 for (i = 0; i < frq->n_percentiles; i++)
1004 struct percentile *pc = &frq->percentiles[i];
1011 prev_value = SYSMIS;
1012 for (idx = 0; idx < ft->n_valid; ++idx)
1014 f = &ft->valid[idx];
1016 for (i = 0; i < frq->n_percentiles; i++)
1018 struct percentile *pc = &frq->percentiles[i];
1021 if ( pc->flag2 ) continue ;
1023 if ( settings_get_algorithm () != COMPATIBLE )
1025 (ft->valid_cases - 1) * pc->p;
1028 (ft->valid_cases + 1) * pc->p - 1;
1032 pc->x2 = f->value.f;
1033 pc->x1 = prev_value;
1040 if ( f->count > 1 && rank - (f->count - 1) > tp )
1042 pc->x2 = pc->x1 = f->value.f;
1053 prev_value = f->value.f;
1056 for (i = 0; i < frq->n_percentiles; i++)
1058 struct percentile *pc = &frq->percentiles[i];
1060 /* Catches the case when p == 100% */
1062 pc->x1 = pc->x2 = f->value.f;
1065 printf("percentile %d (p==%.2f); X1 = %g; X2 = %g\n",
1066 i,pc->p,pc->x1,pc->x2);
1070 for (i = 0; i < frq->n_percentiles; i++)
1072 struct percentile *pc = &frq->percentiles[i];
1076 if ( settings_get_algorithm () != COMPATIBLE )
1078 s = modf((ft->valid_cases - 1) * pc->p , &dummy);
1082 s = modf((ft->valid_cases + 1) * pc->p -1, &dummy);
1085 pc->value = pc->x1 + (pc->x2 - pc->x1) * s ;
1089 /* Calculate the mode. */
1092 for (f = ft->valid; f < ft->missing; f++)
1094 if (most_often < f->count)
1096 most_often = f->count;
1097 X_mode = f->value.f;
1099 else if (most_often == f->count)
1101 /* A duplicate mode is undefined.
1102 FIXME: keep track of *all* the modes. */
1107 /* Calculate moments. */
1108 m = moments_create (MOMENT_KURTOSIS);
1109 for (f = ft->valid; f < ft->missing; f++)
1110 moments_pass_one (m, f->value.f, f->count);
1111 for (f = ft->valid; f < ft->missing; f++)
1112 moments_pass_two (m, f->value.f, f->count);
1113 moments_calculate (m, NULL, &d[FRQ_MEAN], &d[FRQ_VARIANCE],
1114 &d[FRQ_SKEW], &d[FRQ_KURT]);
1115 moments_destroy (m);
1117 /* Formulas below are taken from _SPSS Statistical Algorithms_. */
1118 d[FRQ_MIN] = ft->valid[0].value.f;
1119 d[FRQ_MAX] = ft->valid[ft->n_valid - 1].value.f;
1120 d[FRQ_MODE] = X_mode;
1121 d[FRQ_RANGE] = d[FRQ_MAX] - d[FRQ_MIN];
1122 d[FRQ_SUM] = d[FRQ_MEAN] * W;
1123 d[FRQ_STDDEV] = sqrt (d[FRQ_VARIANCE]);
1124 d[FRQ_SEMEAN] = d[FRQ_STDDEV] / sqrt (W);
1125 d[FRQ_SESKEW] = calc_seskew (W);
1126 d[FRQ_SEKURT] = calc_sekurt (W);
1129 /* Displays a table of all the statistics requested for variable V. */
1131 dump_statistics (const struct frq_proc *frq, const struct var_freqs *vf,
1132 const struct variable *wv)
1134 const struct fmt_spec *wfmt = wv ? var_get_print_format (wv) : &F_8_0;
1135 const struct freq_tab *ft = &vf->tab;
1136 double stat_value[FRQ_N_STATS];
1137 struct tab_table *t;
1140 if (var_is_alpha (vf->var))
1143 if (ft->n_valid == 0)
1145 msg (SW, _("No valid data for variable %s; statistics not displayed."),
1146 var_get_name (vf->var));
1149 calc_stats (frq, vf, stat_value);
1151 t = tab_create (3, n_stats + frq->n_show_percentiles + 2);
1153 tab_box (t, TAL_1, TAL_1, -1, -1 , 0 , 0 , 2, tab_nr(t) - 1) ;
1156 tab_vline (t, TAL_1 , 2, 0, tab_nr(t) - 1);
1157 tab_vline (t, TAL_GAP , 1, 0, tab_nr(t) - 1 ) ;
1159 r=2; /* N missing and N valid are always dumped */
1161 for (i = 0; i < FRQ_N_STATS; i++)
1162 if (stats & BIT_INDEX (i))
1164 tab_text (t, 0, r, TAB_LEFT | TAT_TITLE,
1165 gettext (st_name[i].s10));
1166 tab_double (t, 2, r, TAB_NONE, stat_value[i], NULL);
1170 tab_text (t, 0, 0, TAB_LEFT | TAT_TITLE, _("N"));
1171 tab_text (t, 1, 0, TAB_LEFT | TAT_TITLE, _("Valid"));
1172 tab_text (t, 1, 1, TAB_LEFT | TAT_TITLE, _("Missing"));
1174 tab_double (t, 2, 0, TAB_NONE, ft->valid_cases, wfmt);
1175 tab_double (t, 2, 1, TAB_NONE, ft->total_cases - ft->valid_cases, wfmt);
1177 for (i = 0; i < frq->n_percentiles; i++, r++)
1179 struct percentile *pc = &frq->percentiles[i];
1186 tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, _("Percentiles"));
1190 tab_text (t, 1, r, TAB_LEFT, _("50 (Median)"));
1192 tab_fixed (t, 1, r, TAB_LEFT, pc->p * 100, 3, 0);
1193 tab_double (t, 2, r, TAB_NONE, pc->value,
1194 var_get_print_format (vf->var));
1197 tab_title (t, "%s", var_to_string (vf->var));
1203 calculate_iqr (const struct frq_proc *frq)
1209 for (i = 0; i < frq->n_percentiles; i++)
1211 struct percentile *pc = &frq->percentiles[i];
1213 if (fabs (0.25 - pc->p) < DBL_EPSILON)
1215 else if (fabs (0.75 - pc->p) < DBL_EPSILON)
1219 return q1 == SYSMIS || q3 == SYSMIS ? SYSMIS : q3 - q1;
1223 chart_includes_value (const struct frq_chart *chart,
1224 const struct variable *var,
1225 const union value *value)
1227 if (!chart->include_missing && var_is_value_missing (var, value, MV_ANY))
1230 if (var_is_numeric (var)
1231 && ((chart->x_min != SYSMIS && value->f < chart->x_min)
1232 || (chart->x_max != SYSMIS && value->f > chart->x_max)))
1238 /* Create a gsl_histogram from a freq_tab */
1240 freq_tab_to_hist (const struct frq_proc *frq, const struct freq_tab *ft,
1241 const struct variable *var)
1243 double x_min, x_max, valid_freq;
1246 struct histogram *histogram;
1250 /* Find out the extremes of the x value, within the range to be included in
1251 the histogram, and sum the total frequency of those values. */
1255 for (i = 0; i < ft->n_valid; i++)
1257 const struct freq *frq = &ft->valid[i];
1258 if (chart_includes_value (&hist, var, &frq->value))
1260 x_min = MIN (x_min, frq->value.f);
1261 x_max = MAX (x_max, frq->value.f);
1262 valid_freq += frq->count;
1266 /* Freedman-Diaconis' choice of bin width. */
1267 iqr = calculate_iqr (frq);
1270 double bin_width = 2 * iqr / pow (valid_freq, 1.0 / 3.0);
1271 bins = (x_max - x_min) / bin_width;
1274 else if (bins > 400)
1280 histogram = histogram_create (bins, x_min, x_max);
1281 for (i = 0; i < ft->n_valid; i++)
1283 const struct freq *frq = &ft->valid[i];
1284 if (chart_includes_value (&hist, var, &frq->value))
1285 histogram_add (histogram, frq->value.f, frq->count);
1292 add_slice (const struct freq *freq, const struct variable *var,
1293 struct slice *slice)
1295 if (chart_includes_value (&pie, var, &freq->value))
1297 ds_init_empty (&slice->label);
1298 var_append_value_name (var, &freq->value, &slice->label);
1299 slice->magnitude = freq->count;
1306 /* Allocate an array of slices and fill them from the data in frq_tab
1307 n_slices will contain the number of slices allocated.
1308 The caller is responsible for freeing slices
1310 static struct slice *
1311 freq_tab_to_slice_array(const struct freq_tab *frq_tab,
1312 const struct variable *var,
1315 struct slice *slices;
1319 slices = xnmalloc (frq_tab->n_valid + frq_tab->n_missing, sizeof *slices);
1322 for (i = 0; i < frq_tab->n_valid; i++)
1323 n_slices += add_slice (&frq_tab->valid[i], var, &slices[n_slices]);
1324 for (i = 0; i < frq_tab->n_missing; i++)
1325 n_slices += add_slice (&frq_tab->missing[i], var, &slices[n_slices]);
1327 *n_slicesp = n_slices;
1335 do_piechart(const struct variable *var, const struct freq_tab *frq_tab)
1337 struct slice *slices;
1340 slices = freq_tab_to_slice_array (frq_tab, var, &n_slices);
1343 msg (SW, _("Omitting pie chart for %s, which has only %d unique values."),
1344 var_get_name (var), n_slices);
1345 else if (n_slices > 50)
1346 msg (SW, _("Omitting pie chart for %s, which has over 50 unique values."),
1347 var_get_name (var));
1349 chart_item_submit (piechart_create (var_to_string(var), slices, n_slices));
1351 for (i = 0; i < n_slices; i++)
1352 ds_destroy (&slices[i].label);