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