Added result_class parameter to tab_double and updated all callers. Removed tab_fixed
[pspp] / src / language / stats / correlations.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2009, 2010, 2011 Free Software Foundation, Inc.
3
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.
8
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.
13
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/>. */
16
17 #include <config.h>
18
19 #include <gsl/gsl_cdf.h>
20 #include <gsl/gsl_matrix.h>
21 #include <math.h>
22
23 #include "data/casegrouper.h"
24 #include "data/casereader.h"
25 #include "data/dataset.h"
26 #include "data/dictionary.h"
27 #include "data/format.h"
28 #include "data/variable.h"
29 #include "language/command.h"
30 #include "language/dictionary/split-file.h"
31 #include "language/lexer/lexer.h"
32 #include "language/lexer/variable-parser.h"
33 #include "libpspp/assertion.h"
34 #include "libpspp/message.h"
35 #include "libpspp/misc.h"
36 #include "math/correlation.h"
37 #include "math/covariance.h"
38 #include "math/moments.h"
39 #include "output/tab.h"
40
41 #include "gl/xalloc.h"
42 #include "gl/minmax.h"
43
44 #include "gettext.h"
45 #define _(msgid) gettext (msgid)
46 #define N_(msgid) msgid
47
48
49 struct corr
50 {
51   size_t n_vars_total;
52   size_t n_vars1;
53
54   const struct variable **vars;
55 };
56
57
58 /* Handling of missing values. */
59 enum corr_missing_type
60   {
61     CORR_PAIRWISE,       /* Handle missing values on a per-variable-pair basis. */
62     CORR_LISTWISE        /* Discard entire case if any variable is missing. */
63   };
64
65 enum stats_opts
66   {
67     STATS_DESCRIPTIVES = 0x01,
68     STATS_XPROD = 0x02,
69     STATS_ALL = STATS_XPROD | STATS_DESCRIPTIVES
70   };
71
72 struct corr_opts
73 {
74   enum corr_missing_type missing_type;
75   enum mv_class exclude;      /* Classes of missing values to exclude. */
76
77   bool sig;   /* Flag significant values or not */
78   int tails;  /* Report significance with how many tails ? */
79   enum stats_opts statistics;
80
81   const struct variable *wv;  /* The weight variable (if any) */
82 };
83
84
85 static void
86 output_descriptives (const struct corr *corr, const gsl_matrix *means,
87                      const gsl_matrix *vars, const gsl_matrix *ns)
88 {
89   const int nr = corr->n_vars_total + 1;
90   const int nc = 4;
91   int c, r;
92
93   const int heading_columns = 1;
94   const int heading_rows = 1;
95
96   struct tab_table *t = tab_create (nc, nr);
97   tab_title (t, _("Descriptive Statistics"));
98
99   tab_headers (t, heading_columns, 0, heading_rows, 0);
100
101   /* Outline the box */
102   tab_box (t,
103            TAL_2, TAL_2,
104            -1, -1,
105            0, 0,
106            nc - 1, nr - 1);
107
108   /* Vertical lines */
109   tab_box (t,
110            -1, -1,
111            -1, TAL_1,
112            heading_columns, 0,
113            nc - 1, nr - 1);
114
115   tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
116   tab_hline (t, TAL_1, 0, nc - 1, heading_rows);
117
118   tab_text (t, 1, 0, TAB_CENTER | TAT_TITLE, _("Mean"));
119   tab_text (t, 2, 0, TAB_CENTER | TAT_TITLE, _("Std. Deviation"));
120   tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("N"));
121
122   for (r = 0 ; r < corr->n_vars_total ; ++r)
123     {
124       const struct variable *v = corr->vars[r];
125       tab_text (t, 0, r + heading_rows, TAB_LEFT | TAT_TITLE, var_to_string (v));
126
127       for (c = 1 ; c < nc ; ++c)
128         {
129           double x ;
130           double n;
131           switch (c)
132             {
133             case 1:
134               x = gsl_matrix_get (means, r, 0);
135               break;
136             case 2:
137               x = gsl_matrix_get (vars, r, 0);
138
139               /* Here we want to display the non-biased estimator */
140               n = gsl_matrix_get (ns, r, 0);
141               x *= n / (n -1);
142
143               x = sqrt (x);
144               break;
145             case 3:
146               x = gsl_matrix_get (ns, r, 0);
147               break;
148             default: 
149               NOT_REACHED ();
150             };
151           
152           tab_double (t, c, r + heading_rows, 0, x, NULL, RC_OTHER);
153         }
154     }
155
156   tab_submit (t);
157 }
158
159 static void
160 output_correlation (const struct corr *corr, const struct corr_opts *opts,
161                     const gsl_matrix *cm, const gsl_matrix *samples,
162                     const gsl_matrix *cv)
163 {
164   int r, c;
165   struct tab_table *t;
166   int matrix_cols;
167   int nr = corr->n_vars1;
168   int nc = matrix_cols = corr->n_vars_total > corr->n_vars1 ?
169     corr->n_vars_total - corr->n_vars1 : corr->n_vars1;
170
171   const struct fmt_spec *wfmt = opts->wv ? var_get_print_format (opts->wv) : & F_8_0;
172
173   const int heading_columns = 2;
174   const int heading_rows = 1;
175
176   int rows_per_variable = opts->missing_type == CORR_LISTWISE ? 2 : 3;
177
178   if (opts->statistics & STATS_XPROD)
179     rows_per_variable += 2;
180
181   /* Two header columns */
182   nc += heading_columns;
183
184   /* Three data per variable */
185   nr *= rows_per_variable;
186
187   /* One header row */
188   nr += heading_rows;
189
190   t = tab_create (nc, nr);
191   tab_set_format (t, RC_WEIGHT, wfmt);
192   tab_title (t, _("Correlations"));
193
194   tab_headers (t, heading_columns, 0, heading_rows, 0);
195
196   /* Outline the box */
197   tab_box (t,
198            TAL_2, TAL_2,
199            -1, -1,
200            0, 0,
201            nc - 1, nr - 1);
202
203   /* Vertical lines */
204   tab_box (t,
205            -1, -1,
206            -1, TAL_1,
207            heading_columns, 0,
208            nc - 1, nr - 1);
209
210   tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
211
212   tab_vline (t, TAL_1, 1, heading_rows, nr - 1);
213
214   /* Row Headers */
215   for (r = 0 ; r < corr->n_vars1 ; ++r)
216     {
217       tab_text (t, 0, 1 + r * rows_per_variable, TAB_LEFT | TAT_TITLE, 
218                 var_to_string (corr->vars[r]));
219
220       tab_text (t, 1, 1 + r * rows_per_variable, TAB_LEFT | TAT_TITLE, _("Pearson Correlation"));
221       tab_text (t, 1, 2 + r * rows_per_variable, TAB_LEFT | TAT_TITLE, 
222                 (opts->tails == 2) ? _("Sig. (2-tailed)") : _("Sig. (1-tailed)"));
223
224       if (opts->statistics & STATS_XPROD)
225         {
226           tab_text (t, 1, 3 + r * rows_per_variable, TAB_LEFT | TAT_TITLE, _("Cross-products"));
227           tab_text (t, 1, 4 + r * rows_per_variable, TAB_LEFT | TAT_TITLE, _("Covariance"));
228         }
229
230       if ( opts->missing_type != CORR_LISTWISE )
231         tab_text (t, 1, rows_per_variable + r * rows_per_variable, TAB_LEFT | TAT_TITLE, _("N"));
232
233       tab_hline (t, TAL_1, 0, nc - 1, r * rows_per_variable + 1);
234     }
235
236   /* Column Headers */
237   for (c = 0 ; c < matrix_cols ; ++c)
238     {
239       const struct variable *v = corr->n_vars_total > corr->n_vars1 ?
240         corr->vars[corr->n_vars1 + c] : corr->vars[c];
241       tab_text (t, heading_columns + c, 0, TAB_LEFT | TAT_TITLE, var_to_string (v));      
242     }
243
244   for (r = 0 ; r < corr->n_vars1 ; ++r)
245     {
246       const int row = r * rows_per_variable + heading_rows;
247       for (c = 0 ; c < matrix_cols ; ++c)
248         {
249           unsigned char flags = 0; 
250           const int col_index = corr->n_vars_total > corr->n_vars1 ? 
251             corr->n_vars1 + c : 
252             c;
253           double pearson = gsl_matrix_get (cm, r, col_index);
254           double w = gsl_matrix_get (samples, r, col_index);
255           double sig = opts->tails * significance_of_correlation (pearson, w);
256
257           if ( opts->missing_type != CORR_LISTWISE )
258             tab_double (t, c + heading_columns, row + rows_per_variable - 1, 0, w, NULL, RC_WEIGHT);
259
260           if ( col_index != r)
261             tab_double (t, c + heading_columns, row + 1, 0,  sig, NULL, RC_PVALUE);
262
263           if ( opts->sig && col_index != r && sig < 0.05)
264             flags = TAB_EMPH;
265           
266           tab_double (t, c + heading_columns, row, flags, pearson, NULL, RC_OTHER);
267
268           if (opts->statistics & STATS_XPROD)
269             {
270               double cov = gsl_matrix_get (cv, r, col_index);
271               const double xprod_dev = cov * w;
272               cov *= w / (w - 1.0);
273
274               tab_double (t, c + heading_columns, row + 2, 0, xprod_dev, NULL, RC_OTHER);
275               tab_double (t, c + heading_columns, row + 3, 0, cov, NULL, RC_OTHER);
276             }
277         }
278     }
279
280   tab_submit (t);
281 }
282
283
284 static void
285 run_corr (struct casereader *r, const struct corr_opts *opts, const struct corr *corr)
286 {
287   struct ccase *c;
288   const gsl_matrix *var_matrix,  *samples_matrix, *mean_matrix;
289   gsl_matrix *cov_matrix;
290   gsl_matrix *corr_matrix;
291   struct covariance *cov = covariance_2pass_create (corr->n_vars_total, corr->vars,
292                                                     NULL,
293                                                     opts->wv, opts->exclude);
294
295   struct casereader *rc = casereader_clone (r);
296   for ( ; (c = casereader_read (r) ); case_unref (c))
297     {
298       covariance_accumulate_pass1 (cov, c);
299     }
300
301   for ( ; (c = casereader_read (rc) ); case_unref (c))
302     {
303       covariance_accumulate_pass2 (cov, c);
304     }
305
306   cov_matrix = covariance_calculate (cov);
307
308   casereader_destroy (rc);
309
310   samples_matrix = covariance_moments (cov, MOMENT_NONE);
311   var_matrix = covariance_moments (cov, MOMENT_VARIANCE);
312   mean_matrix = covariance_moments (cov, MOMENT_MEAN);
313
314   corr_matrix = correlation_from_covariance (cov_matrix, var_matrix);
315
316   if ( opts->statistics & STATS_DESCRIPTIVES) 
317     output_descriptives (corr, mean_matrix, var_matrix, samples_matrix);
318
319   output_correlation (corr, opts, corr_matrix,
320                       samples_matrix, cov_matrix);
321
322   covariance_destroy (cov);
323   gsl_matrix_free (corr_matrix);
324   gsl_matrix_free (cov_matrix);
325 }
326
327 int
328 cmd_correlation (struct lexer *lexer, struct dataset *ds)
329 {
330   int i;
331   int n_all_vars = 0; /* Total number of variables involved in this command */
332   const struct variable **all_vars ;
333   const struct dictionary *dict = dataset_dict (ds);
334   bool ok = true;
335
336   struct casegrouper *grouper;
337   struct casereader *group;
338
339   struct corr *corr = NULL;
340   size_t n_corrs = 0;
341
342   struct corr_opts opts;
343   opts.missing_type = CORR_PAIRWISE;
344   opts.wv = dict_get_weight (dict);
345   opts.tails = 2;
346   opts.sig = false;
347   opts.exclude = MV_ANY;
348   opts.statistics = 0;
349
350   /* Parse CORRELATIONS. */
351   while (lex_token (lexer) != T_ENDCMD)
352     {
353       lex_match (lexer, T_SLASH);
354       if (lex_match_id (lexer, "MISSING"))
355         {
356           lex_match (lexer, T_EQUALS);
357           while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
358             {
359               if (lex_match_id (lexer, "PAIRWISE"))
360                 opts.missing_type = CORR_PAIRWISE;
361               else if (lex_match_id (lexer, "LISTWISE"))
362                 opts.missing_type = CORR_LISTWISE;
363
364               else if (lex_match_id (lexer, "INCLUDE"))
365                 opts.exclude = MV_SYSTEM;
366               else if (lex_match_id (lexer, "EXCLUDE"))
367                 opts.exclude = MV_ANY;
368               else
369                 {
370                   lex_error (lexer, NULL);
371                   goto error;
372                 }
373               lex_match (lexer, T_COMMA);
374             }
375         }
376       else if (lex_match_id (lexer, "PRINT"))
377         {
378           lex_match (lexer, T_EQUALS);
379           while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
380             {
381               if ( lex_match_id (lexer, "TWOTAIL"))
382                 opts.tails = 2;
383               else if (lex_match_id (lexer, "ONETAIL"))
384                 opts.tails = 1;
385               else if (lex_match_id (lexer, "SIG"))
386                 opts.sig = false;
387               else if (lex_match_id (lexer, "NOSIG"))
388                 opts.sig = true;
389               else
390                 {
391                   lex_error (lexer, NULL);
392                   goto error;
393                 }
394
395               lex_match (lexer, T_COMMA);
396             }
397         }
398       else if (lex_match_id (lexer, "STATISTICS"))
399         {
400           lex_match (lexer, T_EQUALS);
401           while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
402             {
403               if ( lex_match_id (lexer, "DESCRIPTIVES"))
404                 opts.statistics = STATS_DESCRIPTIVES;
405               else if (lex_match_id (lexer, "XPROD"))
406                 opts.statistics = STATS_XPROD;
407               else if (lex_token (lexer) == T_ALL)
408                 {
409                   opts.statistics = STATS_ALL;
410                   lex_get (lexer);
411                 }
412               else 
413                 {
414                   lex_error (lexer, NULL);
415                   goto error;
416                 }
417
418               lex_match (lexer, T_COMMA);
419             }
420         }
421       else
422         {
423           if (lex_match_id (lexer, "VARIABLES"))
424             {
425               lex_match (lexer, T_EQUALS);
426             }
427
428           corr = xrealloc (corr, sizeof (*corr) * (n_corrs + 1));
429           corr[n_corrs].n_vars_total = corr[n_corrs].n_vars1 = 0;
430       
431           if ( ! parse_variables_const (lexer, dict, &corr[n_corrs].vars, 
432                                         &corr[n_corrs].n_vars_total,
433                                         PV_NUMERIC))
434             {
435               ok = false;
436               break;
437             }
438
439
440           corr[n_corrs].n_vars1 = corr[n_corrs].n_vars_total;
441
442           if ( lex_match (lexer, T_WITH))
443             {
444               if ( ! parse_variables_const (lexer, dict,
445                                             &corr[n_corrs].vars, &corr[n_corrs].n_vars_total,
446                                             PV_NUMERIC | PV_APPEND))
447                 {
448                   ok = false;
449                   break;
450                 }
451             }
452
453           n_all_vars += corr[n_corrs].n_vars_total;
454
455           n_corrs++;
456         }
457     }
458
459   if (n_corrs == 0)
460     {
461       msg (SE, _("No variables specified."));
462       goto error;
463     }
464
465
466   all_vars = xmalloc (sizeof (*all_vars) * n_all_vars);
467
468   {
469     /* FIXME:  Using a hash here would make more sense */
470     const struct variable **vv = all_vars;
471
472     for (i = 0 ; i < n_corrs; ++i)
473       {
474         int v;
475         const struct corr *c = &corr[i];
476         for (v = 0 ; v < c->n_vars_total; ++v)
477           *vv++ = c->vars[v];
478       }
479   }
480
481   grouper = casegrouper_create_splits (proc_open (ds), dict);
482
483   while (casegrouper_get_next_group (grouper, &group))
484     {
485       for (i = 0 ; i < n_corrs; ++i)
486         {
487           /* FIXME: No need to iterate the data multiple times */
488           struct casereader *r = casereader_clone (group);
489
490           if ( opts.missing_type == CORR_LISTWISE)
491             r = casereader_create_filter_missing (r, all_vars, n_all_vars,
492                                                   opts.exclude, NULL, NULL);
493
494
495           run_corr (r, &opts,  &corr[i]);
496           casereader_destroy (r);
497         }
498       casereader_destroy (group);
499     }
500
501   ok = casegrouper_destroy (grouper);
502   ok = proc_commit (ds) && ok;
503
504   free (all_vars);
505
506
507   /* Done. */
508   free (corr->vars);
509   free (corr);
510
511   return ok ? CMD_SUCCESS : CMD_CASCADING_FAILURE;
512
513  error:
514   free (corr->vars);
515   free (corr);
516   return CMD_FAILURE;
517 }