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/casewriter.h"
27 #include "data/dictionary.h"
28 #include "data/format.h"
29 #include "data/procedure.h"
30 #include "data/settings.h"
31 #include "data/subcase.h"
32 #include "data/value-labels.h"
33 #include "data/variable.h"
34 #include "language/command.h"
35 #include "language/dictionary/split-file.h"
36 #include "language/lexer/lexer.h"
37 #include "language/stats/freq.h"
38 #include "libpspp/array.h"
39 #include "libpspp/bit-vector.h"
40 #include "libpspp/compiler.h"
41 #include "libpspp/hmap.h"
42 #include "libpspp/message.h"
43 #include "libpspp/misc.h"
44 #include "libpspp/pool.h"
45 #include "libpspp/str.h"
46 #include "math/histogram.h"
47 #include "math/moments.h"
48 #include "math/sort.h"
49 #include "output/chart-item.h"
50 #include "output/charts/piechart.h"
51 #include "output/charts/plot-hist.h"
52 #include "output/pivot-table.h"
53 #include "output/tab.h"
55 #include "gl/minmax.h"
56 #include "gl/xalloc.h"
59 #define _(msgid) gettext (msgid)
60 #define N_(msgid) msgid
67 +format=table:limit(n:limit,"%s>0")/notable/!table,
68 sort:!avalue/dvalue/afreq/dfreq;
69 missing=miss:include/!exclude;
70 barchart(ba_)=:minimum(d:min),
72 scale:freq(*n:freq,"%s>0")/percent(*n:pcnt,"%s>0");
73 piechart(pie_)=:minimum(d:min),
75 missing:missing/!nomissing,
77 histogram(hi_)=:minimum(d:min),
79 scale:freq(*n:freq,"%s>0")/percent(*n:pcnt,"%s>0"),
80 norm:!nonormal/normal;
83 +percentiles = double list;
84 +statistics[st_]=mean,semean,median,mode,stddev,variance,
85 kurtosis,skewness,range,minimum,maximum,sum,
86 default,seskewness,sekurtosis,all,none.
94 FRQ_MEAN, FRQ_SEMEAN, FRQ_MEDIAN, FRQ_MODE, FRQ_STDDEV, FRQ_VARIANCE,
95 FRQ_KURT, FRQ_SEKURT, FRQ_SKEW, FRQ_SESKEW, FRQ_RANGE, FRQ_MIN, FRQ_MAX,
99 /* Description of a statistic. */
102 int st_indx; /* Index into a_statistics[]. */
103 const char *s10; /* Identifying string. */
106 /* Table of statistics, indexed by dsc_*. */
107 static const struct frq_info st_name[FRQ_N_STATS + 1] =
109 {FRQ_ST_MEAN, N_("Mean")},
110 {FRQ_ST_SEMEAN, N_("S.E. Mean")},
111 {FRQ_ST_MEDIAN, N_("Median")},
112 {FRQ_ST_MODE, N_("Mode")},
113 {FRQ_ST_STDDEV, N_("Std Dev")},
114 {FRQ_ST_VARIANCE, N_("Variance")},
115 {FRQ_ST_KURTOSIS, N_("Kurtosis")},
116 {FRQ_ST_SEKURTOSIS, N_("S.E. Kurt")},
117 {FRQ_ST_SKEWNESS, N_("Skewness")},
118 {FRQ_ST_SESKEWNESS, N_("S.E. Skew")},
119 {FRQ_ST_RANGE, N_("Range")},
120 {FRQ_ST_MINIMUM, N_("Minimum")},
121 {FRQ_ST_MAXIMUM, N_("Maximum")},
122 {FRQ_ST_SUM, N_("Sum")},
126 /* Percentiles to calculate. */
130 double p; /* the %ile to be calculated */
131 double value; /* the %ile's value */
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))
148 double x_min; /* X axis minimum value. */
149 double x_max; /* X axis maximum value. */
150 int y_scale; /* Y axis scale: FRQ_FREQ or FRQ_PERCENT. */
152 /* Histograms only. */
153 double y_max; /* Y axis maximum value. */
154 bool draw_normal; /* Whether to draw normal curve. */
156 /* Pie charts only. */
157 bool include_missing; /* Whether to include missing values. */
160 /* Frequency tables. */
162 /* Entire frequency table. */
165 struct casewriter *sorter;
166 struct casereader *data;
168 struct freq *valid; /* Valid freqs. */
169 int n_valid; /* Number of valid freqs. */
170 const struct dictionary *dict; /* Source of entries in the table. */
172 struct freq *missing; /* Missing freqs. */
173 int n_missing; /* Number of missing freqs. */
176 double total_cases; /* Sum of weights of all cases. */
177 double valid_cases; /* Sum of weights of valid cases. */
180 /* Per-variable frequency data. */
183 struct variable *var;
185 /* Freqency table. */
186 struct freq_tab tab; /* Frequencies table to use. */
189 int n_groups; /* Number of groups. */
190 double *groups; /* Groups. */
193 double stat[FRQ_N_STATS];
195 /* Variable attributes. */
197 struct fmt_spec print;
204 struct var_freqs *vars;
207 /* Percentiles to calculate and possibly display. */
208 struct percentile *percentiles;
209 int n_percentiles, n_show_percentiles;
211 /* Frequency table display. */
212 int max_categories; /* Maximum categories to show. */
213 int sort; /* FRQ_AVALUE or FRQ_DVALUE
214 or FRQ_ACOUNT or FRQ_DCOUNT. */
216 /* Statistics; number of statistics. */
220 /* Histogram and pie chart settings. */
221 struct frq_chart *hist, *pie;
224 static void determine_charts (struct frq_proc *,
225 const struct cmd_frequencies *);
227 static void calc_stats (const struct var_freqs *, double d[FRQ_N_STATS]);
228 static void calc_percentiles (const struct frq_proc *,
229 const struct var_freqs *);
231 static void precalc (struct frq_proc *, struct casereader *, struct dataset *);
232 static void calc (struct frq_proc *, const struct ccase *,
233 const struct dataset *);
234 static void postcalc (struct frq_proc *, const struct dataset *);
236 static void postprocess_freq_tab (const struct frq_proc *, struct var_freqs *);
237 static void dump_freq_table (const struct var_freqs *,
238 const struct variable *weight_var);
239 static void dump_statistics (const struct frq_proc *, const struct var_freqs *,
240 const struct variable *weight_var);
241 static void cleanup_freq_tab (struct var_freqs *);
243 static void add_percentile (struct frq_proc *, double x, bool show,
244 size_t *allocated_percentiles);
246 static void do_piechart(const struct frq_chart *, const struct variable *,
247 const struct freq_tab *);
249 struct histogram *freq_tab_to_hist(const struct frq_proc *,
250 const struct freq_tab *,
251 const struct variable *);
253 /* Parser and outline. */
256 cmd_frequencies (struct lexer *lexer, struct dataset *ds)
258 struct cmd_frequencies cmd;
260 struct casegrouper *grouper;
261 struct casereader *input, *group;
262 size_t allocated_percentiles;
266 frq.pool = pool_create ();
271 frq.percentiles = NULL;
272 frq.n_percentiles = 0;
273 frq.n_show_percentiles = 0;
278 allocated_percentiles = 0;
280 if (!parse_frequencies (lexer, ds, &cmd, &frq))
282 pool_destroy (frq.pool);
286 /* Figure out when to show frequency tables. */
287 frq.max_categories = (cmd.table == FRQ_NOTABLE ? -1
288 : cmd.table == FRQ_TABLE ? INT_MAX
292 /* Figure out statistics to calculate. */
294 if (cmd.a_statistics[FRQ_ST_DEFAULT] || !cmd.sbc_statistics)
295 frq.stats |= FRQ_DEFAULT;
296 if (cmd.a_statistics[FRQ_ST_ALL])
297 frq.stats |= FRQ_ALL;
298 if (cmd.sort != FRQ_AVALUE && cmd.sort != FRQ_DVALUE)
299 frq.stats &= ~BIT_INDEX (FRQ_MEDIAN);
300 for (i = 0; i < FRQ_N_STATS; i++)
301 if (cmd.a_statistics[st_name[i].st_indx])
302 frq.stats |= BIT_INDEX (i);
303 if (frq.stats & FRQ_KURT)
304 frq.stats |= BIT_INDEX (FRQ_SEKURT);
305 if (frq.stats & FRQ_SKEW)
306 frq.stats |= BIT_INDEX (FRQ_SESKEW);
308 /* Calculate n_stats. */
310 for (i = 0; i < FRQ_N_STATS; i++)
311 if ((frq.stats & BIT_INDEX (i)))
315 determine_charts (&frq, &cmd);
316 if (cmd.sbc_histogram || cmd.sbc_piechart || cmd.sbc_ntiles)
317 cmd.sort = FRQ_AVALUE;
319 /* Work out what percentiles need to be calculated */
320 if ( cmd.sbc_percentiles )
322 for ( i = 0 ; i < MAXLISTS ; ++i )
325 subc_list_double *ptl_list = &cmd.dl_percentiles[i];
326 for ( pl = 0 ; pl < subc_list_double_count(ptl_list); ++pl)
327 add_percentile (&frq, subc_list_double_at(ptl_list, pl) / 100.0,
328 true, &allocated_percentiles);
331 if ( cmd.sbc_ntiles )
333 for ( i = 0 ; i < cmd.sbc_ntiles ; ++i )
336 for (j = 0; j <= cmd.n_ntiles[i]; ++j )
337 add_percentile (&frq, j / (double) cmd.n_ntiles[i], true,
338 &allocated_percentiles);
341 if (frq.stats & BIT_INDEX (FRQ_MEDIAN))
343 /* Treat the median as the 50% percentile.
344 We output it in the percentiles table as "50 (Median)." */
345 add_percentile (&frq, 0.5, true, &allocated_percentiles);
346 frq.stats &= ~BIT_INDEX (FRQ_MEDIAN);
349 if (cmd.sbc_histogram)
351 add_percentile (&frq, 0.25, false, &allocated_percentiles);
352 add_percentile (&frq, 0.75, false, &allocated_percentiles);
356 input = casereader_create_filter_weight (proc_open (ds), dataset_dict (ds),
358 grouper = casegrouper_create_splits (input, dataset_dict (ds));
359 for (; casegrouper_get_next_group (grouper, &group);
360 casereader_destroy (group))
364 precalc (&frq, group, ds);
365 for (; (c = casereader_read (group)) != NULL; case_unref (c))
369 ok = casegrouper_destroy (grouper);
370 ok = proc_commit (ds) && ok;
372 free_frequencies(&cmd);
374 pool_destroy (frq.pool);
376 free (frq.percentiles);
380 return ok ? CMD_SUCCESS : CMD_CASCADING_FAILURE;
383 /* Figure out which charts the user requested. */
385 determine_charts (struct frq_proc *frq, const struct cmd_frequencies *cmd)
387 if (cmd->sbc_barchart)
388 msg (SW, _("Bar charts are not implemented."));
390 if (cmd->sbc_histogram)
392 struct frq_chart *hist;
394 hist = frq->hist = xmalloc (sizeof *frq->hist);
395 hist->x_min = cmd->hi_min;
396 hist->x_max = cmd->hi_max;
397 hist->y_scale = cmd->hi_scale;
398 hist->y_max = cmd->hi_scale == FRQ_FREQ ? cmd->hi_freq : cmd->hi_pcnt;
399 hist->draw_normal = cmd->hi_norm != FRQ_NONORMAL;
400 hist->include_missing = false;
402 if (hist->x_min != SYSMIS && hist->x_max != SYSMIS
403 && hist->x_min >= hist->x_max)
405 msg (SE, _("MAX for histogram 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."),
408 hist->x_min, hist->x_max);
409 hist->x_min = hist->x_max = SYSMIS;
413 if (cmd->sbc_piechart)
415 struct frq_chart *pie;
417 pie = frq->pie = xmalloc (sizeof *frq->pie);
418 pie->x_min = cmd->pie_min;
419 pie->x_max = cmd->pie_max;
420 pie->y_scale = cmd->pie_scale;
421 pie->include_missing = cmd->pie_missing == FRQ_MISSING;
423 if (pie->x_min != SYSMIS && pie->x_max != SYSMIS
424 && pie->x_min >= pie->x_max)
426 msg (SE, _("MAX for pie chart must be greater than or equal to MIN, "
427 "but MIN was specified as %.15g and MAX as %.15g. "
428 "MIN and MAX will be ignored."), pie->x_min, pie->x_max);
429 pie->x_min = pie->x_max = SYSMIS;
434 /* Add data from case C to the frequency table. */
436 calc (struct frq_proc *frq, const struct ccase *c, const struct dataset *ds)
438 double weight = dict_get_case_weight (dataset_dict (ds), c, NULL);
441 for (i = 0; i < frq->n_vars; i++)
443 struct var_freqs *vf = &frq->vars[i];
444 struct casewriter *writer = vf->tab.sorter;
447 f = case_create (casewriter_get_proto (writer));
448 value_copy (case_data_rw_idx (f, 0), case_data (c, vf->var), vf->width);
449 case_data_rw_idx (f, 1)->f = weight;
451 casewriter_write (writer, f);
455 static struct ccase *
456 combine_freq_cases (struct ccase *a, struct ccase *b, void *aux UNUSED)
458 a = case_unshare (a);
459 case_data_rw_idx (a, 1)->f += case_data_idx (b, 1)->f;
465 /* Prepares each variable that is the target of FREQUENCIES by setting
466 up its hash table. */
468 precalc (struct frq_proc *frq, struct casereader *input, struct dataset *ds)
473 c = casereader_peek (input, 0);
476 output_split_file_values (ds, c);
480 for (i = 0; i < frq->n_vars; i++)
482 int width = var_get_width (frq->vars[i].var);
483 struct caseproto *proto;
484 struct subcase ordering;
486 proto = caseproto_create ();
487 proto = caseproto_add_width (proto, width);
488 proto = caseproto_add_width (proto, 0);
490 subcase_init (&ordering, 0, width, SC_ASCEND);
491 frq->vars[i].tab.sorter = sort_distinct_create_writer (
492 &ordering, proto, combine_freq_cases, NULL, NULL);
494 caseproto_unref (proto);
495 subcase_destroy (&ordering);
499 /* Finishes up with the variables after frequencies have been
500 calculated. Displays statistics, percentiles, ... */
502 postcalc (struct frq_proc *frq, const struct dataset *ds)
504 const struct dictionary *dict = dataset_dict (ds);
505 const struct variable *wv = dict_get_weight (dict);
508 for (i = 0; i < frq->n_vars; i++)
510 struct var_freqs *vf = &frq->vars[i];
512 postprocess_freq_tab (frq, vf);
514 /* Frequencies tables. */
515 if (vf->tab.n_valid + vf->tab.n_missing <= frq->max_categories)
516 dump_freq_table (vf, wv);
520 dump_statistics (frq, vf, wv);
522 if (frq->hist && var_is_numeric (vf->var) && vf->tab.n_valid > 0)
524 double d[FRQ_N_STATS];
525 struct histogram *histogram;
529 histogram = freq_tab_to_hist (frq, &vf->tab, vf->var);
531 chart_item_submit (histogram_chart_create (
532 histogram->gsl_hist, var_to_string(vf->var),
536 frq->hist->draw_normal));
538 statistic_destroy (&histogram->parent);
542 do_piechart(frq->pie, vf->var, &vf->tab);
544 cleanup_freq_tab (vf);
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 struct freq_compare_aux
566 bool ascending_value;
570 compare_freq (const void *a_, const void *b_, const void *aux_)
572 const struct freq_compare_aux *aux = aux_;
573 const struct freq *a = a_;
574 const struct freq *b = b_;
576 if (aux->by_freq && a->count != b->count)
578 int cmp = a->count > b->count ? 1 : -1;
579 return aux->ascending_freq ? cmp : -cmp;
583 int cmp = value_compare_3way (&a->value, &b->value, aux->width);
584 return aux->ascending_value ? cmp : -cmp;
587 /* Summarizes the frequency table data for variable V. */
589 postprocess_freq_tab (const struct frq_proc *frq, struct var_freqs *vf)
591 struct freq_tab *ft = &vf->tab;
592 struct freq_compare_aux aux;
593 struct casereader *reader;
596 struct freq *freqs, *f;
599 /* Extract data from hash table. */
600 reader = casewriter_make_reader (ft->sorter);
601 ft->data = casereader_clone (reader);
602 freqs = xnmalloc (casereader_count_cases (reader), sizeof *freqs);
603 for (count = 0; (c = casereader_read (reader)) != NULL; count++)
605 struct freq *f = &freqs[count];
606 value_clone (&f->value, case_data_idx (c, 0), vf->width);
607 f->count = case_num_idx (c, 1);
610 casereader_destroy (reader);
612 /* Put data into ft. */
614 ft->n_valid = partition (freqs, count, sizeof *freqs, not_missing, vf->var);
615 ft->missing = freqs + ft->n_valid;
616 ft->n_missing = count - ft->n_valid;
619 aux.by_freq = frq->sort == FRQ_AFREQ || frq->sort == FRQ_DFREQ;
620 aux.ascending_freq = frq->sort != FRQ_DFREQ;
621 aux.width = vf->width;
622 aux.ascending_value = frq->sort != FRQ_DVALUE;
623 sort (ft->valid, ft->n_valid, sizeof *ft->valid, compare_freq, &aux);
624 sort (ft->missing, ft->n_missing, sizeof *ft->missing, compare_freq, &aux);
626 /* Summary statistics. */
627 ft->valid_cases = 0.0;
628 for(i = 0 ; i < ft->n_valid ; ++i )
631 ft->valid_cases += f->count;
635 ft->total_cases = ft->valid_cases ;
636 for(i = 0 ; i < ft->n_missing ; ++i )
639 ft->total_cases += f->count;
644 /* Frees the frequency table for variable V. */
646 cleanup_freq_tab (struct var_freqs *vf)
648 if (value_needs_init (vf->width))
652 for (i = 0; i < vf->tab.n_valid + vf->tab.n_missing; i++)
653 value_destroy (&vf->tab.valid[i].value, vf->width);
655 casereader_destroy (vf->tab.data);
656 free (vf->tab.valid);
659 /* Parses the VARIABLES subcommand. */
661 frq_custom_variables (struct lexer *lexer, struct dataset *ds,
662 struct cmd_frequencies *cmd UNUSED, void *frq_ UNUSED)
664 struct frq_proc *frq = frq_;
665 struct variable **vars;
669 lex_match (lexer, '=');
670 if (lex_token (lexer) != T_ALL
671 && (lex_token (lexer) != T_ID
672 || dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) == NULL))
675 /* Get list of current variables, to avoid duplicates. */
676 vars = xmalloc (frq->n_vars * sizeof *vars);
677 n_vars = frq->n_vars;
678 for (i = 0; i < frq->n_vars; i++)
679 vars[i] = frq->vars[i].var;
681 if (!parse_variables (lexer, dataset_dict (ds), &vars, &n_vars,
682 PV_APPEND | PV_NO_SCRATCH))
685 frq->vars = xrealloc (frq->vars, n_vars * sizeof *frq->vars);
686 for (i = frq->n_vars; i < n_vars; i++)
688 struct variable *var = vars[i];
689 struct var_freqs *vf = &frq->vars[i];
692 vf->tab.valid = vf->tab.missing = NULL;
693 vf->tab.dict = dataset_dict (ds);
696 vf->width = var_get_width (var);
697 vf->print = *var_get_print_format (var);
699 frq->n_vars = n_vars;
706 /* Parses the GROUPED subcommand, setting the n_grouped, grouped
707 fields of specified variables. */
709 frq_custom_grouped (struct lexer *lexer, struct dataset *ds, struct cmd_frequencies *cmd UNUSED, void *frq_ UNUSED)
711 struct frq_proc *frq = frq_;
713 lex_match (lexer, '=');
714 if ((lex_token (lexer) == T_ID && dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) != NULL)
715 || lex_token (lexer) == T_ID)
720 /* Max, current size of list; list itself. */
726 const struct variable **v;
728 if (!parse_variables_const (lexer, dataset_dict (ds), &v, &n,
729 PV_NO_DUPLICATE | PV_NUMERIC))
731 if (lex_match (lexer, '('))
735 while (lex_integer (lexer))
740 dl = pool_nrealloc (frq->pool, dl, ml, sizeof *dl);
742 dl[nl++] = lex_tokval (lexer);
744 lex_match (lexer, ',');
746 /* Note that nl might still be 0 and dl might still be
747 NULL. That's okay. */
748 if (!lex_match (lexer, ')'))
751 msg (SE, _("`)' expected after GROUPED interval list."));
761 for (i = 0; i < n; i++)
765 for (j = 0; j < frq->n_vars; j++)
767 struct var_freqs *vf = &frq->vars[j];
770 if (vf->groups != NULL)
771 msg (SE, _("Variables %s specified multiple times on "
772 "GROUPED subcommand."), var_get_name (v[i]));
781 msg (SE, _("Variables %s specified on GROUPED but not on "
782 "VARIABLES."), var_get_name (v[i]));
788 if (!lex_match (lexer, '/'))
790 if ((lex_token (lexer) != T_ID || dict_lookup_var (dataset_dict (ds), lex_tokid (lexer)) != NULL)
791 && lex_token (lexer) != T_ALL)
793 lex_put_back (lexer, '/');
801 /* Adds X to the list of percentiles, keeping the list in proper
802 order. If SHOW is true, the percentile will be shown in the statistics
803 box, otherwise it will be hidden. */
805 add_percentile (struct frq_proc *frq, double x, bool show,
806 size_t *allocated_percentiles)
810 /* Do nothing if it's already in the list */
811 for (i = 0; i < frq->n_percentiles; i++)
813 struct percentile *pc = &frq->percentiles[i];
815 if ( fabs(x - pc->p) < DBL_EPSILON )
817 if (show && !pc->show)
819 frq->n_show_percentiles++;
829 if (frq->n_percentiles >= *allocated_percentiles)
830 frq->percentiles = x2nrealloc (frq->percentiles, allocated_percentiles,
831 sizeof *frq->percentiles);
832 insert_element (frq->percentiles, frq->n_percentiles,
833 sizeof *frq->percentiles, i);
834 frq->percentiles[i].p = x;
835 frq->percentiles[i].show = show;
836 frq->n_percentiles++;
838 frq->n_show_percentiles++;
841 /* Comparison functions. */
844 /* Frequency table display. */
846 /* Displays a full frequency table for variable V. */
848 dump_freq_table (const struct var_freqs *vf, const struct variable *wv)
850 struct variable *value_var, *freq_var;
851 struct pivot_table *pt;
853 pt = xmalloc (sizeof *pt);
855 pt->data = casereader_clone (vf->tab.data);
857 pt->dict = dict_create ();
858 value_var = dict_clone_var_assert (pt->dict, vf->var);
860 freq_var = dict_clone_var_assert (pt->dict, wv);
863 freq_var = dict_create_var (pt->dict, "$Frequency", 0);
864 var_set_both_formats (freq_var, &F_8_0);
865 var_set_label (freq_var, _("Frequency"));
868 subcase_init_empty (&pt->split);
869 subcase_init_empty (&pt->dimensions[TABLE_HORZ]);
870 subcase_init_empty (&pt->dimensions[TABLE_VERT]);
871 subcase_add_var (&pt->dimensions[TABLE_VERT], value_var, SC_ASCEND);
873 pt->pane.n[TABLE_HORZ] = 4;
874 pt->pane.n[TABLE_VERT] = 1;
875 pt->pane.cells = xmalloc (sizeof *pt->pane.cells);
876 pt->pane.cells[0] = xmalloc (4 * sizeof **pt->pane.cells);
880 &pt->pane.cells[0][0],
881 pivot_value_create (freq_var, PIVOT_SUM, 0, 0, PIVOT_INCLUDE_ALL));
885 &pt->pane.cells[0][1],
886 pivot_value_create (freq_var, PIVOT_SUM, 0, 0, PIVOT_INCLUDE_ALL));
887 pt->pane.cells[0][1].cmp = PIVOT_PERCENT;
888 pt->pane.cells[0][1].cmp_args[0] = pivot_value_create (
889 freq_var, PIVOT_SUM, 0, 1, PIVOT_INCLUDE_ALL);
890 pt->pane.cells[0][1].label = xstrdup ("Percent");
894 &pt->pane.cells[0][2],
895 pivot_value_create (freq_var, PIVOT_SUM, 0, 0, PIVOT_INCLUDE_VALID));
896 pt->pane.cells[0][2].cmp = PIVOT_PERCENT;
897 pt->pane.cells[0][2].cmp_args[0] = pivot_value_create (
898 freq_var, PIVOT_SUM, 0, 1, PIVOT_INCLUDE_VALID);
899 pt->pane.cells[0][2].label = xstrdup ("Valid Percent");
901 /* Cumulative (Valid) Percent. */
903 &pt->pane.cells[0][3],
904 pivot_value_create (freq_var, PIVOT_SUM, 0, 0, PIVOT_INCLUDE_VALID));
905 pt->pane.cells[0][3].base->n_cum_vars[TABLE_VERT] = 1;
906 pt->pane.cells[0][3].cmp = PIVOT_PERCENT;
907 pt->pane.cells[0][3].cmp_args[0] = pivot_value_create (
908 freq_var, PIVOT_SUM, 0, 1, PIVOT_INCLUDE_VALID);
909 pt->pane.cells[0][3].label = xstrdup ("Cum Percent");
911 pivot_table_dump (pt);
914 /* Statistical display. */
917 calc_percentile (double p, double valid_cases, double x1, double x2)
921 s = (settings_get_algorithm () != COMPATIBLE
922 ? modf ((valid_cases - 1) * p, &dummy)
923 : modf ((valid_cases + 1) * p - 1, &dummy));
925 return x1 + (x2 - x1) * s;
928 /* Calculates all of the percentiles for VF within FRQ. */
930 calc_percentiles (const struct frq_proc *frq, const struct var_freqs *vf)
932 const struct freq_tab *ft = &vf->tab;
933 double W = ft->valid_cases;
934 const struct freq *f;
938 assert (ft->n_valid > 0);
942 for (f = ft->valid; f < ft->missing; f++)
945 for (; percentile_idx < frq->n_percentiles; percentile_idx++)
947 struct percentile *pc = &frq->percentiles[percentile_idx];
950 tp = (settings_get_algorithm () == ENHANCED
952 : (W + 1) * pc->p - 1);
958 && (rank - (f->count - 1) > tp || f + 1 >= ft->missing))
959 pc->value = f->value.f;
961 pc->value = calc_percentile (pc->p, W, f->value.f, f[1].value.f);
964 for (; percentile_idx < frq->n_percentiles; percentile_idx++)
966 struct percentile *pc = &frq->percentiles[percentile_idx];
967 pc->value = ft->valid[ft->n_valid - 1].value.f;
971 /* Calculates all the pertinent statistics for VF, putting them in array
974 calc_stats (const struct var_freqs *vf, double d[FRQ_N_STATS])
976 const struct freq_tab *ft = &vf->tab;
977 double W = ft->valid_cases;
978 const struct freq *f;
983 assert (ft->n_valid > 0);
985 /* Calculate the mode. */
988 for (f = ft->valid; f < ft->missing; f++)
990 if (most_often < f->count)
992 most_often = f->count;
995 else if (most_often == f->count)
997 /* A duplicate mode is undefined.
998 FIXME: keep track of *all* the modes. */
1003 /* Calculate moments. */
1004 m = moments_create (MOMENT_KURTOSIS);
1005 for (f = ft->valid; f < ft->missing; f++)
1006 moments_pass_one (m, f->value.f, f->count);
1007 for (f = ft->valid; f < ft->missing; f++)
1008 moments_pass_two (m, f->value.f, f->count);
1009 moments_calculate (m, NULL, &d[FRQ_MEAN], &d[FRQ_VARIANCE],
1010 &d[FRQ_SKEW], &d[FRQ_KURT]);
1011 moments_destroy (m);
1013 /* Formulas below are taken from _SPSS Statistical Algorithms_. */
1014 d[FRQ_MIN] = ft->valid[0].value.f;
1015 d[FRQ_MAX] = ft->valid[ft->n_valid - 1].value.f;
1016 d[FRQ_MODE] = X_mode;
1017 d[FRQ_RANGE] = d[FRQ_MAX] - d[FRQ_MIN];
1018 d[FRQ_SUM] = d[FRQ_MEAN] * W;
1019 d[FRQ_STDDEV] = sqrt (d[FRQ_VARIANCE]);
1020 d[FRQ_SEMEAN] = d[FRQ_STDDEV] / sqrt (W);
1021 d[FRQ_SESKEW] = calc_seskew (W);
1022 d[FRQ_SEKURT] = calc_sekurt (W);
1025 /* Displays a table of all the statistics requested for variable V. */
1027 dump_statistics (const struct frq_proc *frq, const struct var_freqs *vf,
1028 const struct variable *wv)
1030 const struct fmt_spec *wfmt = wv ? var_get_print_format (wv) : &F_8_0;
1031 const struct freq_tab *ft = &vf->tab;
1032 double stat_value[FRQ_N_STATS];
1033 struct tab_table *t;
1036 if (var_is_alpha (vf->var))
1039 if (ft->n_valid == 0)
1041 msg (SW, _("No valid data for variable %s; statistics not displayed."),
1042 var_get_name (vf->var));
1045 calc_stats (vf, stat_value);
1046 calc_percentiles (frq, vf);
1048 t = tab_create (3, frq->n_stats + frq->n_show_percentiles + 2);
1050 tab_box (t, TAL_1, TAL_1, -1, -1 , 0 , 0 , 2, tab_nr(t) - 1) ;
1053 tab_vline (t, TAL_1 , 2, 0, tab_nr(t) - 1);
1054 tab_vline (t, TAL_GAP , 1, 0, tab_nr(t) - 1 ) ;
1056 r=2; /* N missing and N valid are always dumped */
1058 for (i = 0; i < FRQ_N_STATS; i++)
1059 if (frq->stats & BIT_INDEX (i))
1061 tab_text (t, 0, r, TAB_LEFT | TAT_TITLE,
1062 gettext (st_name[i].s10));
1063 tab_double (t, 2, r, TAB_NONE, stat_value[i], NULL);
1067 tab_text (t, 0, 0, TAB_LEFT | TAT_TITLE, _("N"));
1068 tab_text (t, 1, 0, TAB_LEFT | TAT_TITLE, _("Valid"));
1069 tab_text (t, 1, 1, TAB_LEFT | TAT_TITLE, _("Missing"));
1071 tab_double (t, 2, 0, TAB_NONE, ft->valid_cases, wfmt);
1072 tab_double (t, 2, 1, TAB_NONE, ft->total_cases - ft->valid_cases, wfmt);
1074 for (i = 0; i < frq->n_percentiles; i++, r++)
1076 struct percentile *pc = &frq->percentiles[i];
1083 tab_text (t, 0, r, TAB_LEFT | TAT_TITLE, _("Percentiles"));
1087 tab_text (t, 1, r, TAB_LEFT, _("50 (Median)"));
1089 tab_fixed (t, 1, r, TAB_LEFT, pc->p * 100, 3, 0);
1090 tab_double (t, 2, r, TAB_NONE, pc->value,
1091 var_get_print_format (vf->var));
1094 tab_title (t, "%s", var_to_string (vf->var));
1100 calculate_iqr (const struct frq_proc *frq)
1106 for (i = 0; i < frq->n_percentiles; i++)
1108 struct percentile *pc = &frq->percentiles[i];
1110 if (fabs (0.25 - pc->p) < DBL_EPSILON)
1112 else if (fabs (0.75 - pc->p) < DBL_EPSILON)
1116 return q1 == SYSMIS || q3 == SYSMIS ? SYSMIS : q3 - q1;
1120 chart_includes_value (const struct frq_chart *chart,
1121 const struct variable *var,
1122 const union value *value)
1124 if (!chart->include_missing && var_is_value_missing (var, value, MV_ANY))
1127 if (var_is_numeric (var)
1128 && ((chart->x_min != SYSMIS && value->f < chart->x_min)
1129 || (chart->x_max != SYSMIS && value->f > chart->x_max)))
1135 /* Create a gsl_histogram from a freq_tab */
1137 freq_tab_to_hist (const struct frq_proc *frq, const struct freq_tab *ft,
1138 const struct variable *var)
1140 double x_min, x_max, valid_freq;
1143 struct histogram *histogram;
1147 /* Find out the extremes of the x value, within the range to be included in
1148 the histogram, and sum the total frequency of those values. */
1152 for (i = 0; i < ft->n_valid; i++)
1154 const struct freq *f = &ft->valid[i];
1155 if (chart_includes_value (frq->hist, var, &f->value))
1157 x_min = MIN (x_min, f->value.f);
1158 x_max = MAX (x_max, f->value.f);
1159 valid_freq += f->count;
1163 /* Freedman-Diaconis' choice of bin width. */
1164 iqr = calculate_iqr (frq);
1167 double bin_width = 2 * iqr / pow (valid_freq, 1.0 / 3.0);
1168 bins = (x_max - x_min) / bin_width;
1171 else if (bins > 400)
1177 histogram = histogram_create (bins, x_min, x_max);
1178 for (i = 0; i < ft->n_valid; i++)
1180 const struct freq *f = &ft->valid[i];
1181 if (chart_includes_value (frq->hist, var, &f->value))
1182 histogram_add (histogram, f->value.f, f->count);
1189 add_slice (const struct frq_chart *pie, const struct freq *freq,
1190 const struct variable *var, struct slice *slice)
1192 if (chart_includes_value (pie, var, &freq->value))
1194 ds_init_empty (&slice->label);
1195 var_append_value_name (var, &freq->value, &slice->label);
1196 slice->magnitude = freq->count;
1203 /* Allocate an array of slices and fill them from the data in frq_tab
1204 n_slices will contain the number of slices allocated.
1205 The caller is responsible for freeing slices
1207 static struct slice *
1208 freq_tab_to_slice_array(const struct frq_chart *pie,
1209 const struct freq_tab *frq_tab,
1210 const struct variable *var,
1213 struct slice *slices;
1217 slices = xnmalloc (frq_tab->n_valid + frq_tab->n_missing, sizeof *slices);
1220 for (i = 0; i < frq_tab->n_valid; i++)
1221 n_slices += add_slice (pie, &frq_tab->valid[i], var, &slices[n_slices]);
1222 for (i = 0; i < frq_tab->n_missing; i++)
1223 n_slices += add_slice (pie, &frq_tab->missing[i], var, &slices[n_slices]);
1225 *n_slicesp = n_slices;
1233 do_piechart(const struct frq_chart *pie, const struct variable *var,
1234 const struct freq_tab *frq_tab)
1236 struct slice *slices;
1239 slices = freq_tab_to_slice_array (pie, frq_tab, var, &n_slices);
1242 msg (SW, _("Omitting pie chart for %s, which has only %d unique values."),
1243 var_get_name (var), n_slices);
1244 else if (n_slices > 50)
1245 msg (SW, _("Omitting pie chart for %s, which has over 50 unique values."),
1246 var_get_name (var));
1248 chart_item_submit (piechart_create (var_to_string(var), slices, n_slices));
1250 for (i = 0; i < n_slices; i++)
1251 ds_destroy (&slices[i].label);