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"
61 #include "output/tab.h"
64 #define _(msgid) gettext (msgid)
65 #define N_(msgid) msgid
97 /* Variable index for histogram case */
104 struct exploratory_stats
117 /* The minimum weight */
127 const struct variable **dep_vars;
128 struct exploratory_stats *es;
130 enum mv_class dep_excl;
131 enum mv_class fctr_excl;
133 const struct dictionary *dict;
137 /* ------------ Graph ---------------- */
138 bool normal; /* For histograms, draw the normal curve */
140 enum chart_type chart_type;
141 enum scatter_type scatter_type;
142 enum bar_type bar_type;
143 const struct variable *by_var[2];
146 struct subcase ordering; /* Ordering for aggregation */
147 int agr; /* Index into ag_func */
149 /* A caseproto that contains the plot data */
150 struct caseproto *gr_proto;
157 calc_mom1 (double acc, double x, double w)
163 calc_mom0 (double acc, double x UNUSED, double w)
169 pre_low_extreme (void)
175 calc_max (double acc, double x, double w UNUSED)
177 return (acc > x) ? acc : x;
181 pre_high_extreme (void)
187 calc_min (double acc, double x, double w UNUSED)
189 return (acc < x) ? acc : x;
193 post_normalise (double acc, double cc)
199 post_percentage (double acc, double ccc)
201 return acc / ccc * 100.0;
205 const struct ag_func ag_func[] =
207 {"COUNT", N_("Count"), 0, 0, NULL, calc_mom0, 0, 0},
208 {"PCT", N_("Percentage"), 0, 0, NULL, calc_mom0, 0, post_percentage},
209 {"CUFREQ", N_("Cumulative Count"), 0, 1, NULL, calc_mom0, 0, 0},
210 {"CUPCT", N_("Cumulative Percent"), 0, 1, NULL, calc_mom0, 0, post_percentage},
212 {"MEAN", N_("Mean"), 1, 0, NULL, calc_mom1, post_normalise, 0},
213 {"SUM", N_("Sum"), 1, 0, NULL, calc_mom1, 0, 0},
214 {"MAXIMUM", N_("Maximum"), 1, 0, pre_low_extreme, calc_max, 0, 0},
215 {"MINIMUM", N_("Minimum"), 1, 0, pre_high_extreme, calc_min, 0, 0},
218 const int N_AG_FUNCS = sizeof (ag_func) / sizeof (ag_func[0]);
221 parse_function (struct lexer *lexer, struct graph *graph)
224 for (i = 0 ; i < N_AG_FUNCS; ++i)
226 if (lex_match_id (lexer, ag_func[i].name))
237 graph->n_dep_vars = ag_func[i].arity;
238 if (ag_func[i].arity > 0)
241 if (!lex_force_match (lexer, T_LPAREN))
244 graph->dep_vars = xzalloc (sizeof (graph->dep_vars) * graph->n_dep_vars);
245 for (v = 0; v < ag_func[i].arity; ++v)
247 graph->dep_vars[v] = parse_variable (lexer, graph->dict);
250 if (!lex_force_match (lexer, T_RPAREN))
254 if (!lex_force_match (lexer, T_BY))
257 graph->by_var[0] = parse_variable (lexer, graph->dict);
258 if (!graph->by_var[0])
262 subcase_add_var (&graph->ordering, graph->by_var[0], SC_ASCEND);
265 if (lex_match (lexer, T_BY))
267 graph->by_var[1] = parse_variable (lexer, graph->dict);
268 if (!graph->by_var[1])
272 subcase_add_var (&graph->ordering, graph->by_var[1], SC_ASCEND);
279 lex_error (lexer, NULL);
285 show_scatterplot (const struct graph *cmd, struct casereader *input)
288 struct scatterplot_chart *scatterplot;
289 bool byvar_overflow = false;
291 ds_init_empty (&title);
293 if (cmd->n_by_vars > 0)
295 ds_put_format (&title, _("%s vs. %s by %s"),
296 var_to_string (cmd->dep_vars[1]),
297 var_to_string (cmd->dep_vars[0]),
298 var_to_string (cmd->by_var[0]));
302 ds_put_format (&title, _("%s vs. %s"),
303 var_to_string (cmd->dep_vars[1]),
304 var_to_string (cmd->dep_vars[0]));
307 scatterplot = scatterplot_create (input,
308 var_to_string(cmd->dep_vars[0]),
309 var_to_string(cmd->dep_vars[1]),
310 (cmd->n_by_vars > 0) ? cmd->by_var[0] : NULL,
313 cmd->es[0].minimum, cmd->es[0].maximum,
314 cmd->es[1].minimum, cmd->es[1].maximum);
315 scatterplot_chart_submit (scatterplot);
320 msg (MW, _("Maximum number of scatterplot categories reached. "
321 "Your BY variable has too many distinct values. "
322 "The coloring of the plot will not be correct."));
327 show_histogr (const struct graph *cmd, struct casereader *input)
329 struct histogram *histogram;
334 double bin_width = fabs (cmd->es[0].minimum - cmd->es[0].maximum)
335 / (1 + log2 (cmd->es[0].cc))
339 histogram_create (bin_width, cmd->es[0].minimum, cmd->es[0].maximum);
342 if (NULL == histogram)
344 casereader_destroy (input);
348 for (;(c = casereader_read (input)) != NULL; case_unref (c))
350 const double x = case_data_idx (c, HG_IDX_X)->f;
351 const double weight = case_data_idx (c, HG_IDX_WT)->f;
352 moments_pass_two (cmd->es[0].mom, x, weight);
353 histogram_add (histogram, x, weight);
355 casereader_destroy (input);
363 ds_init_cstr (&label,
364 var_to_string (cmd->dep_vars[0]));
366 moments_calculate (cmd->es[0].mom, &n, &mean, &var, NULL, NULL);
369 ( histogram_chart_create (histogram->gsl_hist,
370 ds_cstr (&label), n, mean,
371 sqrt (var), cmd->normal));
373 statistic_destroy (&histogram->parent);
379 cleanup_exploratory_stats (struct graph *cmd)
383 for (v = 0; v < cmd->n_dep_vars; ++v)
385 moments_destroy (cmd->es[v].mom);
391 run_barchart (struct graph *cmd, struct casereader *input)
393 struct casegrouper *grouper;
394 struct casereader *group;
397 if ( cmd->missing_pw == false)
398 input = casereader_create_filter_missing (input,
406 input = sort_execute (input, &cmd->ordering);
408 struct freq **freqs = NULL;
411 for (grouper = casegrouper_create_vars (input, cmd->by_var,
413 casegrouper_get_next_group (grouper, &group);
414 casereader_destroy (group))
417 struct ccase *c = casereader_peek (group, 0);
419 /* Deal with missing values in the categorical variables */
420 for (v = 0; v < cmd->n_by_vars; ++v)
422 if (var_is_value_missing (cmd->by_var[v], case_data (c, cmd->by_var[v]), cmd->fctr_excl) )
426 if (v < cmd->n_by_vars)
432 freqs = xrealloc (freqs, sizeof (*freqs) * ++n_freqs);
433 freqs[n_freqs - 1] = xzalloc (sizeof (**freqs) +
434 sizeof (union value) * (cmd->n_by_vars - 1) );
436 if (ag_func[cmd->agr].cumulative && n_freqs >= 2)
437 freqs[n_freqs - 1]->count = freqs[n_freqs - 2]->count;
439 freqs[n_freqs - 1]->count = 0;
440 if (ag_func[cmd->agr].pre)
441 freqs[n_freqs - 1]->count = ag_func[cmd->agr].pre();
444 for (v = 0; v < cmd->n_by_vars; ++v)
446 value_clone (&freqs[n_freqs - 1]->values[v], case_data (c, cmd->by_var[v]),
447 var_get_width (cmd->by_var[v])
453 for (;(c = casereader_read (group)) != NULL; case_unref (c))
455 const double weight = dict_get_case_weight (cmd->dict,c,NULL);
456 const double x = (cmd->n_dep_vars > 0) ? case_data (c, cmd->dep_vars[0])->f : SYSMIS;
460 freqs[n_freqs - 1]->count
461 = ag_func[cmd->agr].calc (freqs[n_freqs - 1]->count, x, weight);
464 if (ag_func[cmd->agr].post)
465 freqs[n_freqs - 1]->count
466 = ag_func[cmd->agr].post (freqs[n_freqs - 1]->count, cc);
471 casegrouper_destroy (grouper);
473 for (int i = 0; i < n_freqs; ++i)
475 if (ag_func[cmd->agr].ppost)
476 freqs[i]->count = ag_func[cmd->agr].ppost (freqs[i]->count, ccc);
482 ds_init_empty (&label);
484 if (cmd->n_dep_vars > 0)
485 ds_put_format (&label, _("%s of %s"),
486 ag_func[cmd->agr].description,
487 var_get_name (cmd->dep_vars[0]));
490 ag_func[cmd->agr].description);
492 chart_item_submit (barchart_create (cmd->by_var, cmd->n_by_vars,
493 ds_cstr (&label), false,
499 for (int i = 0; i < n_freqs; ++i)
507 run_graph (struct graph *cmd, struct casereader *input)
510 struct casereader *reader;
511 struct casewriter *writer;
513 cmd->es = pool_calloc (cmd->pool,cmd->n_dep_vars,sizeof(struct exploratory_stats));
514 for(int v=0;v<cmd->n_dep_vars;v++)
516 cmd->es[v].mom = moments_create (MOMENT_KURTOSIS);
517 cmd->es[v].cmin = DBL_MAX;
518 cmd->es[v].maximum = -DBL_MAX;
519 cmd->es[v].minimum = DBL_MAX;
521 /* Always remove cases listwise. This is correct for */
522 /* the histogram because there is only one variable */
523 /* and a simple bivariate scatterplot */
524 /* if ( cmd->missing_pw == false) */
525 input = casereader_create_filter_missing (input,
532 writer = autopaging_writer_create (cmd->gr_proto);
534 /* The case data is copied to a new writer */
535 /* The setup of the case depends on the Charttype */
536 /* For Scatterplot x is assumed in dep_vars[0] */
537 /* y is assumed in dep_vars[1] */
538 /* For Histogram x is assumed in dep_vars[0] */
539 assert(SP_IDX_X == 0 && SP_IDX_Y == 1 && HG_IDX_X == 0);
541 for (;(c = casereader_read (input)) != NULL; case_unref (c))
543 struct ccase *outcase = case_create (cmd->gr_proto);
544 const double weight = dict_get_case_weight (cmd->dict,c,NULL);
545 if (cmd->chart_type == CT_HISTOGRAM)
546 case_data_rw_idx (outcase, HG_IDX_WT)->f = weight;
547 if (cmd->chart_type == CT_SCATTERPLOT && cmd->n_by_vars > 0)
548 value_copy (case_data_rw_idx (outcase, SP_IDX_BY),
549 case_data (c, cmd->by_var[0]),
550 var_get_width (cmd->by_var[0]));
551 for(int v=0;v<cmd->n_dep_vars;v++)
553 const struct variable *var = cmd->dep_vars[v];
554 const double x = case_data (c, var)->f;
556 if (var_is_value_missing (var, case_data (c, var), cmd->dep_excl))
558 cmd->es[v].missing += weight;
561 /* Magically v value fits to SP_IDX_X, SP_IDX_Y, HG_IDX_X */
562 case_data_rw_idx (outcase, v)->f = x;
564 if (x > cmd->es[v].maximum)
565 cmd->es[v].maximum = x;
567 if (x < cmd->es[v].minimum)
568 cmd->es[v].minimum = x;
570 cmd->es[v].non_missing += weight;
572 moments_pass_one (cmd->es[v].mom, x, weight);
574 cmd->es[v].cc += weight;
576 if (cmd->es[v].cmin > weight)
577 cmd->es[v].cmin = weight;
579 casewriter_write (writer,outcase);
582 reader = casewriter_make_reader (writer);
584 switch (cmd->chart_type)
587 show_histogr (cmd,reader);
590 show_scatterplot (cmd,reader);
597 casereader_destroy (input);
598 cleanup_exploratory_stats (cmd);
603 cmd_graph (struct lexer *lexer, struct dataset *ds)
607 graph.missing_pw = false;
609 graph.pool = pool_create ();
611 graph.dep_excl = MV_ANY;
612 graph.fctr_excl = MV_ANY;
614 graph.dict = dataset_dict (ds);
616 graph.dep_vars = NULL;
617 graph.chart_type = CT_NONE;
618 graph.scatter_type = ST_BIVARIATE;
620 graph.gr_proto = caseproto_create ();
622 subcase_init_empty (&graph.ordering);
624 while (lex_token (lexer) != T_ENDCMD)
626 lex_match (lexer, T_SLASH);
628 if (lex_match_id (lexer, "HISTOGRAM"))
630 if (graph.chart_type != CT_NONE)
632 lex_error (lexer, _("Only one chart type is allowed."));
635 graph.normal = false;
636 if (lex_match (lexer, T_LPAREN))
638 if (!lex_force_match_id (lexer, "NORMAL"))
641 if (!lex_force_match (lexer, T_RPAREN))
646 if (!lex_force_match (lexer, T_EQUALS))
648 graph.chart_type = CT_HISTOGRAM;
649 if (!parse_variables_const (lexer, graph.dict,
650 &graph.dep_vars, &graph.n_dep_vars,
651 PV_NO_DUPLICATE | PV_NUMERIC))
653 if (graph.n_dep_vars > 1)
655 lex_error (lexer, _("Only one variable is allowed."));
659 else if (lex_match_id (lexer, "BAR"))
661 if (graph.chart_type != CT_NONE)
663 lex_error (lexer, _("Only one chart type is allowed."));
666 graph.chart_type = CT_BAR;
667 graph.bar_type = CBT_SIMPLE;
669 if (lex_match (lexer, T_LPAREN))
671 if (lex_match_id (lexer, "SIMPLE"))
673 /* This is the default anyway */
675 else if (lex_match_id (lexer, "GROUPED"))
677 graph.bar_type = CBT_GROUPED;
680 else if (lex_match_id (lexer, "STACKED"))
682 graph.bar_type = CBT_STACKED;
683 lex_error (lexer, _("%s is not yet implemented."), "STACKED");
686 else if (lex_match_id (lexer, "RANGE"))
688 graph.bar_type = CBT_RANGE;
689 lex_error (lexer, _("%s is not yet implemented."), "RANGE");
694 lex_error (lexer, NULL);
697 if (!lex_force_match (lexer, T_RPAREN))
701 if (!lex_force_match (lexer, T_EQUALS))
704 if (! parse_function (lexer, &graph))
707 else if (lex_match_id (lexer, "SCATTERPLOT"))
709 if (graph.chart_type != CT_NONE)
711 lex_error (lexer, _("Only one chart type is allowed."));
714 graph.chart_type = CT_SCATTERPLOT;
715 if (lex_match (lexer, T_LPAREN))
717 if (lex_match_id (lexer, "BIVARIATE"))
719 /* This is the default anyway */
721 else if (lex_match_id (lexer, "OVERLAY"))
723 lex_error (lexer, _("%s is not yet implemented."),"OVERLAY");
726 else if (lex_match_id (lexer, "MATRIX"))
728 lex_error (lexer, _("%s is not yet implemented."),"MATRIX");
731 else if (lex_match_id (lexer, "XYZ"))
733 lex_error(lexer, _("%s is not yet implemented."),"XYZ");
738 lex_error_expecting (lexer, "BIVARIATE", NULL);
741 if (!lex_force_match (lexer, T_RPAREN))
744 if (!lex_force_match (lexer, T_EQUALS))
747 if (!parse_variables_const (lexer, graph.dict,
748 &graph.dep_vars, &graph.n_dep_vars,
749 PV_NO_DUPLICATE | PV_NUMERIC))
752 if (graph.scatter_type == ST_BIVARIATE && graph.n_dep_vars != 1)
754 lex_error(lexer, _("Only one variable is allowed."));
758 if (!lex_force_match (lexer, T_WITH))
761 if (!parse_variables_const (lexer, graph.dict,
762 &graph.dep_vars, &graph.n_dep_vars,
763 PV_NO_DUPLICATE | PV_NUMERIC | PV_APPEND))
766 if (graph.scatter_type == ST_BIVARIATE && graph.n_dep_vars != 2)
768 lex_error (lexer, _("Only one variable is allowed."));
772 if (lex_match (lexer, T_BY))
774 const struct variable *v = NULL;
775 if (!lex_match_variable (lexer,graph.dict,&v))
777 lex_error (lexer, _("Variable expected"));
784 else if (lex_match_id (lexer, "LINE"))
786 lex_error (lexer, _("%s is not yet implemented."),"LINE");
789 else if (lex_match_id (lexer, "PIE"))
791 lex_error (lexer, _("%s is not yet implemented."),"PIE");
794 else if (lex_match_id (lexer, "ERRORBAR"))
796 lex_error (lexer, _("%s is not yet implemented."),"ERRORBAR");
799 else if (lex_match_id (lexer, "PARETO"))
801 lex_error (lexer, _("%s is not yet implemented."),"PARETO");
804 else if (lex_match_id (lexer, "TITLE"))
806 lex_error (lexer, _("%s is not yet implemented."),"TITLE");
809 else if (lex_match_id (lexer, "SUBTITLE"))
811 lex_error (lexer, _("%s is not yet implemented."),"SUBTITLE");
814 else if (lex_match_id (lexer, "FOOTNOTE"))
816 lex_error (lexer, _("%s is not yet implemented."),"FOOTNOTE");
817 lex_error (lexer, _("FOOTNOTE is not implemented yet for GRAPH"));
820 else if (lex_match_id (lexer, "MISSING"))
822 lex_match (lexer, T_EQUALS);
824 while (lex_token (lexer) != T_ENDCMD
825 && lex_token (lexer) != T_SLASH)
827 if (lex_match_id (lexer, "LISTWISE"))
829 graph.missing_pw = false;
831 else if (lex_match_id (lexer, "VARIABLE"))
833 graph.missing_pw = true;
835 else if (lex_match_id (lexer, "EXCLUDE"))
837 graph.dep_excl = MV_ANY;
839 else if (lex_match_id (lexer, "INCLUDE"))
841 graph.dep_excl = MV_SYSTEM;
843 else if (lex_match_id (lexer, "REPORT"))
845 graph.fctr_excl = MV_NEVER;
847 else if (lex_match_id (lexer, "NOREPORT"))
849 graph.fctr_excl = MV_ANY;
853 lex_error (lexer, NULL);
860 lex_error (lexer, NULL);
865 switch (graph.chart_type)
868 /* See scatterplot.h for the setup of the case prototype */
869 graph.gr_proto = caseproto_add_width (graph.gr_proto, 0); /* x value - SP_IDX_X*/
870 graph.gr_proto = caseproto_add_width (graph.gr_proto, 0); /* y value - SP_IDX_Y*/
871 /* The by_var contains the plot categories for the different xy plot colors */
872 if (graph.n_by_vars > 0) /* SP_IDX_BY */
873 graph.gr_proto = caseproto_add_width (graph.gr_proto, var_get_width(graph.by_var[0]));
876 graph.gr_proto = caseproto_add_width (graph.gr_proto, 0); /* x value */
877 graph.gr_proto = caseproto_add_width (graph.gr_proto, 0); /* weight value */
882 lex_error_expecting (lexer, "HISTOGRAM", "SCATTERPLOT", "BAR", NULL);
890 struct casegrouper *grouper;
891 struct casereader *group;
894 grouper = casegrouper_create_splits (proc_open (ds), graph.dict);
895 while (casegrouper_get_next_group (grouper, &group))
897 if (graph.chart_type == CT_BAR)
898 run_barchart (&graph, group);
900 run_graph (&graph, group);
902 ok = casegrouper_destroy (grouper);
903 ok = proc_commit (ds) && ok;
906 subcase_destroy (&graph.ordering);
907 free (graph.dep_vars);
908 pool_destroy (graph.pool);
909 caseproto_unref (graph.gr_proto);
914 subcase_destroy (&graph.ordering);
915 caseproto_unref (graph.gr_proto);
916 free (graph.dep_vars);
917 pool_destroy (graph.pool);