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