2 PSPP - a program for statistical analysis.
3 Copyright (C) 2012, 2013, 2015 Free Software Foundation, Inc.
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
20 * This module implements the graph command
26 #include "gl/xalloc.h"
27 #include <gsl/gsl_cdf.h>
29 #include "libpspp/assertion.h"
30 #include "libpspp/message.h"
31 #include "libpspp/pool.h"
34 #include "data/dataset.h"
35 #include "data/dictionary.h"
36 #include "data/casegrouper.h"
37 #include "data/casereader.h"
38 #include "data/casewriter.h"
39 #include "data/caseproto.h"
40 #include "data/subcase.h"
43 #include "data/format.h"
45 #include "math/chart-geometry.h"
46 #include "math/histogram.h"
47 #include "math/moments.h"
48 #include "math/sort.h"
49 #include "math/order-stats.h"
50 #include "output/charts/plot-hist.h"
51 #include "output/charts/scatterplot.h"
52 #include "output/charts/barchart.h"
54 #include "language/command.h"
55 #include "language/lexer/lexer.h"
56 #include "language/lexer/value-parser.h"
57 #include "language/lexer/variable-parser.h"
58 #include "language/stats/freq.h"
59 #include "language/stats/chart-category.h"
62 #define _(msgid) gettext (msgid)
63 #define N_(msgid) msgid
95 /* Variable index for histogram case */
102 struct exploratory_stats
115 /* The minimum weight */
125 const struct variable **dep_vars;
126 struct exploratory_stats *es;
128 enum mv_class dep_excl;
129 enum mv_class fctr_excl;
131 const struct dictionary *dict;
135 /* ------------ Graph ---------------- */
136 bool normal; /* For histograms, draw the normal curve */
138 enum chart_type chart_type;
139 enum scatter_type scatter_type;
140 enum bar_type bar_type;
141 const struct variable *by_var[2];
144 struct subcase ordering; /* Ordering for aggregation */
145 int agr; /* Index into ag_func */
147 /* A caseproto that contains the plot data */
148 struct caseproto *gr_proto;
155 calc_mom1 (double acc, double x, double w)
161 calc_mom0 (double acc, double x UNUSED, double w)
167 pre_low_extreme (void)
173 calc_max (double acc, double x, double w UNUSED)
175 return (acc > x) ? acc : x;
179 pre_high_extreme (void)
185 calc_min (double acc, double x, double w UNUSED)
187 return (acc < x) ? acc : x;
191 post_normalise (double acc, double cc)
197 post_percentage (double acc, double ccc)
199 return acc / ccc * 100.0;
203 const struct ag_func ag_func[] =
205 {"COUNT", N_("Count"), 0, 0, NULL, calc_mom0, 0, 0},
206 {"PCT", N_("Percentage"), 0, 0, NULL, calc_mom0, 0, post_percentage},
207 {"CUFREQ", N_("Cumulative Count"), 0, 1, NULL, calc_mom0, 0, 0},
208 {"CUPCT", N_("Cumulative Percent"), 0, 1, NULL, calc_mom0, 0,
211 {"MEAN", N_("Mean"), 1, 0, NULL, calc_mom1, post_normalise, 0},
212 {"SUM", N_("Sum"), 1, 0, NULL, calc_mom1, 0, 0},
213 {"MAXIMUM", N_("Maximum"), 1, 0, pre_low_extreme, calc_max, 0, 0},
214 {"MINIMUM", N_("Minimum"), 1, 0, pre_high_extreme, calc_min, 0, 0},
217 const int N_AG_FUNCS = sizeof (ag_func) / sizeof (ag_func[0]);
220 parse_function (struct lexer *lexer, struct graph *graph)
223 for (i = 0 ; i < N_AG_FUNCS; ++i)
225 if (lex_match_id (lexer, ag_func[i].name))
236 graph->n_dep_vars = ag_func[i].arity;
237 if (ag_func[i].arity > 0)
240 if (!lex_force_match (lexer, T_LPAREN))
243 graph->dep_vars = xzalloc (sizeof (graph->dep_vars) * graph->n_dep_vars);
244 for (v = 0; v < ag_func[i].arity; ++v)
246 graph->dep_vars[v] = parse_variable (lexer, graph->dict);
247 if (! graph->dep_vars[v])
251 if (!lex_force_match (lexer, T_RPAREN))
255 if (!lex_force_match (lexer, T_BY))
258 graph->by_var[0] = parse_variable (lexer, graph->dict);
259 if (!graph->by_var[0])
263 subcase_add_var (&graph->ordering, graph->by_var[0], SC_ASCEND);
266 if (lex_match (lexer, T_BY))
268 graph->by_var[1] = parse_variable (lexer, graph->dict);
269 if (!graph->by_var[1])
273 subcase_add_var (&graph->ordering, graph->by_var[1], SC_ASCEND);
280 lex_error (lexer, NULL);
286 show_scatterplot (const struct graph *cmd, struct casereader *input)
289 struct scatterplot_chart *scatterplot;
290 bool byvar_overflow = false;
292 ds_init_empty (&title);
294 if (cmd->n_by_vars > 0)
296 ds_put_format (&title, _("%s vs. %s by %s"),
297 var_to_string (cmd->dep_vars[1]),
298 var_to_string (cmd->dep_vars[0]),
299 var_to_string (cmd->by_var[0]));
303 ds_put_format (&title, _("%s vs. %s"),
304 var_to_string (cmd->dep_vars[1]),
305 var_to_string (cmd->dep_vars[0]));
308 scatterplot = scatterplot_create (input,
309 var_to_string(cmd->dep_vars[0]),
310 var_to_string(cmd->dep_vars[1]),
311 (cmd->n_by_vars > 0) ? cmd->by_var[0]
315 cmd->es[0].minimum, cmd->es[0].maximum,
316 cmd->es[1].minimum, cmd->es[1].maximum);
317 scatterplot_chart_submit (scatterplot);
322 msg (MW, _("Maximum number of scatterplot categories reached. "
323 "Your BY variable has too many distinct values. "
324 "The coloring of the plot will not be correct."));
329 show_histogr (const struct graph *cmd, struct casereader *input)
331 struct histogram *histogram;
334 if (cmd->es[0].cc <= 0)
336 casereader_destroy (input);
342 double bin_width = fabs (cmd->es[0].minimum - cmd->es[0].maximum)
343 / (1 + log2 (cmd->es[0].cc))
347 histogram_create (bin_width, cmd->es[0].minimum, cmd->es[0].maximum);
350 if (NULL == histogram)
352 casereader_destroy (input);
356 for (;(c = casereader_read (input)) != NULL; case_unref (c))
358 const double x = case_data_idx (c, HG_IDX_X)->f;
359 const double weight = case_data_idx (c, HG_IDX_WT)->f;
360 moments_pass_two (cmd->es[0].mom, x, weight);
361 histogram_add (histogram, x, weight);
363 casereader_destroy (input);
371 ds_init_cstr (&label,
372 var_to_string (cmd->dep_vars[0]));
374 moments_calculate (cmd->es[0].mom, &n, &mean, &var, NULL, NULL);
377 ( histogram_chart_create (histogram->gsl_hist,
378 ds_cstr (&label), n, mean,
379 sqrt (var), cmd->normal));
381 statistic_destroy (&histogram->parent);
387 cleanup_exploratory_stats (struct graph *cmd)
391 for (v = 0; v < cmd->n_dep_vars; ++v)
393 moments_destroy (cmd->es[v].mom);
399 run_barchart (struct graph *cmd, struct casereader *input)
401 struct casegrouper *grouper;
402 struct casereader *group;
405 if ( cmd->missing_pw == false)
406 input = casereader_create_filter_missing (input,
414 input = sort_execute (input, &cmd->ordering);
416 struct freq **cells = NULL;
419 assert (cmd->n_by_vars <= 2);
420 for (grouper = casegrouper_create_vars (input, cmd->by_var,
422 casegrouper_get_next_group (grouper, &group);
423 casereader_destroy (group))
426 struct ccase *c = casereader_peek (group, 0);
428 /* Deal with missing values in the categorical variables */
429 for (v = 0; v < cmd->n_by_vars; ++v)
431 if (var_is_value_missing (cmd->by_var[v],
432 case_data (c, cmd->by_var[v]),
437 if (v < cmd->n_by_vars)
443 cells = xrealloc (cells, sizeof (*cells) * ++n_cells);
444 cells[n_cells - 1] = xzalloc (sizeof (**cells)
445 + sizeof (union value)
446 * (cmd->n_by_vars - 1));
448 if (ag_func[cmd->agr].cumulative && n_cells >= 2)
449 cells[n_cells - 1]->count = cells[n_cells - 2]->count;
451 cells[n_cells - 1]->count = 0;
452 if (ag_func[cmd->agr].pre)
453 cells[n_cells - 1]->count = ag_func[cmd->agr].pre();
456 for (v = 0; v < cmd->n_by_vars; ++v)
458 value_clone (&cells[n_cells - 1]->values[v],
459 case_data (c, cmd->by_var[v]),
460 var_get_width (cmd->by_var[v]));
465 for (;(c = casereader_read (group)) != NULL; case_unref (c))
467 const double weight = dict_get_case_weight (cmd->dict,c,NULL);
468 const double x = (cmd->n_dep_vars > 0)
469 ? case_data (c, cmd->dep_vars[0])->f : SYSMIS;
473 cells[n_cells - 1]->count
474 = ag_func[cmd->agr].calc (cells[n_cells - 1]->count, x, weight);
477 if (ag_func[cmd->agr].post)
478 cells[n_cells - 1]->count
479 = ag_func[cmd->agr].post (cells[n_cells - 1]->count, cc);
484 casegrouper_destroy (grouper);
486 for (int i = 0; i < n_cells; ++i)
488 if (ag_func[cmd->agr].ppost)
489 cells[i]->count = ag_func[cmd->agr].ppost (cells[i]->count, ccc);
495 ds_init_empty (&label);
497 if (cmd->n_dep_vars > 0)
498 ds_put_format (&label, _("%s of %s"),
499 ag_func[cmd->agr].description,
500 var_get_name (cmd->dep_vars[0]));
503 ag_func[cmd->agr].description);
505 chart_item_submit (barchart_create (cmd->by_var, cmd->n_by_vars,
506 ds_cstr (&label), false,
512 for (int i = 0; i < n_cells; ++i)
520 run_graph (struct graph *cmd, struct casereader *input)
523 struct casereader *reader;
524 struct casewriter *writer;
526 cmd->es = pool_calloc (cmd->pool,cmd->n_dep_vars, sizeof *cmd->es);
527 for(int v=0;v<cmd->n_dep_vars;v++)
529 cmd->es[v].mom = moments_create (MOMENT_KURTOSIS);
530 cmd->es[v].cmin = DBL_MAX;
531 cmd->es[v].maximum = -DBL_MAX;
532 cmd->es[v].minimum = DBL_MAX;
534 /* Always remove cases listwise. This is correct for */
535 /* the histogram because there is only one variable */
536 /* and a simple bivariate scatterplot */
537 /* if ( cmd->missing_pw == false) */
538 input = casereader_create_filter_missing (input,
545 writer = autopaging_writer_create (cmd->gr_proto);
547 /* The case data is copied to a new writer */
548 /* The setup of the case depends on the Charttype */
549 /* For Scatterplot x is assumed in dep_vars[0] */
550 /* y is assumed in dep_vars[1] */
551 /* For Histogram x is assumed in dep_vars[0] */
552 assert(SP_IDX_X == 0 && SP_IDX_Y == 1 && HG_IDX_X == 0);
554 for (;(c = casereader_read (input)) != NULL; case_unref (c))
556 struct ccase *outcase = case_create (cmd->gr_proto);
557 const double weight = dict_get_case_weight (cmd->dict,c,NULL);
558 if (cmd->chart_type == CT_HISTOGRAM)
559 case_data_rw_idx (outcase, HG_IDX_WT)->f = weight;
560 if (cmd->chart_type == CT_SCATTERPLOT && cmd->n_by_vars > 0)
561 value_copy (case_data_rw_idx (outcase, SP_IDX_BY),
562 case_data (c, cmd->by_var[0]),
563 var_get_width (cmd->by_var[0]));
564 for(int v=0;v<cmd->n_dep_vars;v++)
566 const struct variable *var = cmd->dep_vars[v];
567 const double x = case_data (c, var)->f;
569 if (var_is_value_missing (var, case_data (c, var), cmd->dep_excl))
571 cmd->es[v].missing += weight;
574 /* Magically v value fits to SP_IDX_X, SP_IDX_Y, HG_IDX_X */
575 case_data_rw_idx (outcase, v)->f = x;
577 if (x > cmd->es[v].maximum)
578 cmd->es[v].maximum = x;
580 if (x < cmd->es[v].minimum)
581 cmd->es[v].minimum = x;
583 cmd->es[v].non_missing += weight;
585 moments_pass_one (cmd->es[v].mom, x, weight);
587 cmd->es[v].cc += weight;
589 if (cmd->es[v].cmin > weight)
590 cmd->es[v].cmin = weight;
592 casewriter_write (writer,outcase);
595 reader = casewriter_make_reader (writer);
597 switch (cmd->chart_type)
600 show_histogr (cmd,reader);
603 show_scatterplot (cmd,reader);
610 casereader_destroy (input);
611 cleanup_exploratory_stats (cmd);
616 cmd_graph (struct lexer *lexer, struct dataset *ds)
620 graph.missing_pw = false;
622 graph.pool = pool_create ();
624 graph.dep_excl = MV_ANY;
625 graph.fctr_excl = MV_ANY;
627 graph.dict = dataset_dict (ds);
629 graph.dep_vars = NULL;
630 graph.chart_type = CT_NONE;
631 graph.scatter_type = ST_BIVARIATE;
633 graph.gr_proto = caseproto_create ();
635 subcase_init_empty (&graph.ordering);
637 while (lex_token (lexer) != T_ENDCMD)
639 lex_match (lexer, T_SLASH);
641 if (lex_match_id (lexer, "HISTOGRAM"))
643 if (graph.chart_type != CT_NONE)
645 lex_error (lexer, _("Only one chart type is allowed."));
648 graph.normal = false;
649 if (lex_match (lexer, T_LPAREN))
651 if (!lex_force_match_id (lexer, "NORMAL"))
654 if (!lex_force_match (lexer, T_RPAREN))
659 if (!lex_force_match (lexer, T_EQUALS))
661 graph.chart_type = CT_HISTOGRAM;
662 if (!parse_variables_const (lexer, graph.dict,
663 &graph.dep_vars, &graph.n_dep_vars,
664 PV_NO_DUPLICATE | PV_NUMERIC))
666 if (graph.n_dep_vars > 1)
668 lex_error (lexer, _("Only one variable is allowed."));
672 else if (lex_match_id (lexer, "BAR"))
674 if (graph.chart_type != CT_NONE)
676 lex_error (lexer, _("Only one chart type is allowed."));
679 graph.chart_type = CT_BAR;
680 graph.bar_type = CBT_SIMPLE;
682 if (lex_match (lexer, T_LPAREN))
684 if (lex_match_id (lexer, "SIMPLE"))
686 /* This is the default anyway */
688 else if (lex_match_id (lexer, "GROUPED"))
690 graph.bar_type = CBT_GROUPED;
693 else if (lex_match_id (lexer, "STACKED"))
695 graph.bar_type = CBT_STACKED;
696 lex_error (lexer, _("%s is not yet implemented."), "STACKED");
699 else if (lex_match_id (lexer, "RANGE"))
701 graph.bar_type = CBT_RANGE;
702 lex_error (lexer, _("%s is not yet implemented."), "RANGE");
707 lex_error (lexer, NULL);
710 if (!lex_force_match (lexer, T_RPAREN))
714 if (!lex_force_match (lexer, T_EQUALS))
717 if (! parse_function (lexer, &graph))
720 else if (lex_match_id (lexer, "SCATTERPLOT"))
722 if (graph.chart_type != CT_NONE)
724 lex_error (lexer, _("Only one chart type is allowed."));
727 graph.chart_type = CT_SCATTERPLOT;
728 if (lex_match (lexer, T_LPAREN))
730 if (lex_match_id (lexer, "BIVARIATE"))
732 /* This is the default anyway */
734 else if (lex_match_id (lexer, "OVERLAY"))
736 lex_error (lexer, _("%s is not yet implemented."),"OVERLAY");
739 else if (lex_match_id (lexer, "MATRIX"))
741 lex_error (lexer, _("%s is not yet implemented."),"MATRIX");
744 else if (lex_match_id (lexer, "XYZ"))
746 lex_error(lexer, _("%s is not yet implemented."),"XYZ");
751 lex_error_expecting (lexer, "BIVARIATE", NULL);
754 if (!lex_force_match (lexer, T_RPAREN))
757 if (!lex_force_match (lexer, T_EQUALS))
760 if (!parse_variables_const (lexer, graph.dict,
761 &graph.dep_vars, &graph.n_dep_vars,
762 PV_NO_DUPLICATE | PV_NUMERIC))
765 if (graph.scatter_type == ST_BIVARIATE && graph.n_dep_vars != 1)
767 lex_error(lexer, _("Only one variable is allowed."));
771 if (!lex_force_match (lexer, T_WITH))
774 if (!parse_variables_const (lexer, graph.dict,
775 &graph.dep_vars, &graph.n_dep_vars,
776 PV_NO_DUPLICATE | PV_NUMERIC | PV_APPEND))
779 if (graph.scatter_type == ST_BIVARIATE && graph.n_dep_vars != 2)
781 lex_error (lexer, _("Only one variable is allowed."));
785 if (lex_match (lexer, T_BY))
787 const struct variable *v = NULL;
788 if (!lex_match_variable (lexer,graph.dict,&v))
790 lex_error (lexer, _("Variable expected"));
797 else if (lex_match_id (lexer, "LINE"))
799 lex_error (lexer, _("%s is not yet implemented."),"LINE");
802 else if (lex_match_id (lexer, "PIE"))
804 lex_error (lexer, _("%s is not yet implemented."),"PIE");
807 else if (lex_match_id (lexer, "ERRORBAR"))
809 lex_error (lexer, _("%s is not yet implemented."),"ERRORBAR");
812 else if (lex_match_id (lexer, "PARETO"))
814 lex_error (lexer, _("%s is not yet implemented."),"PARETO");
817 else if (lex_match_id (lexer, "TITLE"))
819 lex_error (lexer, _("%s is not yet implemented."),"TITLE");
822 else if (lex_match_id (lexer, "SUBTITLE"))
824 lex_error (lexer, _("%s is not yet implemented."),"SUBTITLE");
827 else if (lex_match_id (lexer, "FOOTNOTE"))
829 lex_error (lexer, _("%s is not yet implemented."),"FOOTNOTE");
830 lex_error (lexer, _("FOOTNOTE is not implemented yet for GRAPH"));
833 else if (lex_match_id (lexer, "MISSING"))
835 lex_match (lexer, T_EQUALS);
837 while (lex_token (lexer) != T_ENDCMD
838 && lex_token (lexer) != T_SLASH)
840 if (lex_match_id (lexer, "LISTWISE"))
842 graph.missing_pw = false;
844 else if (lex_match_id (lexer, "VARIABLE"))
846 graph.missing_pw = true;
848 else if (lex_match_id (lexer, "EXCLUDE"))
850 graph.dep_excl = MV_ANY;
852 else if (lex_match_id (lexer, "INCLUDE"))
854 graph.dep_excl = MV_SYSTEM;
856 else if (lex_match_id (lexer, "REPORT"))
858 graph.fctr_excl = MV_NEVER;
860 else if (lex_match_id (lexer, "NOREPORT"))
862 graph.fctr_excl = MV_ANY;
866 lex_error (lexer, NULL);
873 lex_error (lexer, NULL);
878 switch (graph.chart_type)
881 /* See scatterplot.h for the setup of the case prototype */
883 /* x value - SP_IDX_X*/
884 graph.gr_proto = caseproto_add_width (graph.gr_proto, 0);
886 /* y value - SP_IDX_Y*/
887 graph.gr_proto = caseproto_add_width (graph.gr_proto, 0);
888 /* The by_var contains the plot categories for the different xy
890 if (graph.n_by_vars > 0) /* SP_IDX_BY */
891 graph.gr_proto = caseproto_add_width (graph.gr_proto,
892 var_get_width(graph.by_var[0]));
896 graph.gr_proto = caseproto_add_width (graph.gr_proto, 0);
898 graph.gr_proto = caseproto_add_width (graph.gr_proto, 0);
903 lex_error_expecting (lexer, "HISTOGRAM", "SCATTERPLOT", "BAR", NULL);
911 struct casegrouper *grouper;
912 struct casereader *group;
915 grouper = casegrouper_create_splits (proc_open (ds), graph.dict);
916 while (casegrouper_get_next_group (grouper, &group))
918 if (graph.chart_type == CT_BAR)
919 run_barchart (&graph, group);
921 run_graph (&graph, group);
923 ok = casegrouper_destroy (grouper);
924 ok = proc_commit (ds) && ok;
927 subcase_destroy (&graph.ordering);
928 free (graph.dep_vars);
929 pool_destroy (graph.pool);
930 caseproto_unref (graph.gr_proto);
935 subcase_destroy (&graph.ordering);
936 caseproto_unref (graph.gr_proto);
937 free (graph.dep_vars);
938 pool_destroy (graph.pool);