4899fd039b8959efde0baa06edea851305f2cfac
[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 <math/design-matrix.h>
20 #include <gsl/gsl_matrix.h>
21 #include <data/casegrouper.h>
22 #include <data/casereader.h>
23 #include <data/dictionary.h>
24 #include <data/procedure.h>
25 #include <data/variable.h>
26 #include <language/command.h>
27 #include <language/dictionary/split-file.h>
28 #include <language/lexer/lexer.h>
29 #include <language/lexer/variable-parser.h>
30 #include <output/manager.h>
31 #include <output/table.h>
32 #include <libpspp/message.h>
33 #include <data/format.h>
34
35 #include <math.h>
36 #include "xalloc.h"
37 #include "minmax.h"
38 #include <libpspp/misc.h>
39 #include <gsl/gsl_cdf.h>
40
41 #include "gettext.h"
42 #define _(msgid) gettext (msgid)
43 #define N_(msgid) msgid
44
45 /* Returns the correlation matrix corresponding to the covariance
46 matrix COV.  The return value must be freed with gsl_matrix_free
47 when no longer required.
48 */
49 static gsl_matrix *
50 covariance_to_correlation (const gsl_matrix *cov)
51 {
52   size_t r, c;
53   gsl_matrix *corr = gsl_matrix_alloc (cov->size1, cov->size2);
54
55   for (r = 0 ; r < cov->size1; ++r)
56     {
57       for (c = 0 ; c < cov->size2 ; ++c)
58         {
59           double x = gsl_matrix_get (cov, r, c);
60           x /= sqrt (gsl_matrix_get (cov, r, r)
61             * gsl_matrix_get (cov, c, c) );
62           gsl_matrix_set (corr, r, c, x);
63         }
64     }
65
66   return corr;
67 }
68
69 static double
70 significance_of_correlation (double rho, double w)
71 {
72   double t = w - 2;
73   t /= 1 - MIN (1, pow2 (rho));
74   t = sqrt (t);
75   t *= rho;
76   
77   if (t > 0)
78     return  gsl_cdf_tdist_Q (t, w - 2);
79   else
80     return  gsl_cdf_tdist_P (t, w - 2);
81 }
82
83
84 struct corr
85 {
86   size_t n_vars_total;
87   size_t n_vars1;
88
89   const struct variable **vars;
90 };
91
92
93 /* Handling of missing values. */
94 enum corr_missing_type
95   {
96     CORR_PAIRWISE,       /* Handle missing values on a per-variable-pair basis. */
97     CORR_LISTWISE        /* Discard entire case if any variable is missing. */
98   };
99
100 struct corr_opts
101 {
102   enum corr_missing_type missing_type;
103   enum mv_class exclude;      /* Classes of missing values to exclude. */
104
105   bool sig;   /* Flag significant values or not */
106   int tails;  /* Report significance with how many tails ? */
107
108   const struct variable *wv;  /* The weight variable (if any) */
109 };
110
111
112 static void
113 output_correlation (const struct corr *corr, const struct corr_opts *opts,
114                     const gsl_matrix *cm, const gsl_matrix *samples)
115 {
116   int r, c;
117   struct tab_table *t;
118   int matrix_cols;
119   int nr = corr->n_vars1;
120   int nc = matrix_cols = corr->n_vars_total > corr->n_vars1 ?
121     corr->n_vars_total - corr->n_vars1 : corr->n_vars1;
122
123   const struct fmt_spec *wfmt = opts->wv ? var_get_print_format (opts->wv) : & F_8_0;
124
125   const int heading_columns = 2;
126   const int heading_rows = 1;
127
128   const int rows_per_variable = opts->missing_type == CORR_LISTWISE ? 2 : 3;
129
130   /* Two header columns */
131   nc += heading_columns;
132
133   /* Three data per variable */
134   nr *= rows_per_variable;
135
136   /* One header row */
137   nr += heading_rows;
138
139   t = tab_create (nc, nr, 0);
140   tab_title (t, _("Correlations"));
141   tab_dim (t, tab_natural_dimensions, NULL);
142
143   tab_headers (t, heading_columns, 0, heading_rows, 0);
144
145   /* Outline the box */
146   tab_box (t,
147            TAL_2, TAL_2,
148            -1, -1,
149            0, 0,
150            nc - 1, nr - 1);
151
152   /* Vertical lines */
153   tab_box (t,
154            -1, -1,
155            -1, TAL_1,
156            heading_columns, 0,
157            nc - 1, nr - 1);
158
159   tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
160   tab_vline (t, TAL_1, 1, heading_rows, nr - 1);
161
162   for (r = 0 ; r < corr->n_vars1 ; ++r)
163     {
164       tab_text (t, 0, 1 + r * rows_per_variable, TAB_LEFT | TAT_TITLE, 
165                 var_to_string (corr->vars[r]));
166
167       tab_text (t, 1, 1 + r * rows_per_variable, TAB_LEFT | TAT_TITLE, _("Pearson Correlation"));
168       tab_text (t, 1, 2 + r * rows_per_variable, TAB_LEFT | TAT_TITLE, 
169                 (opts->tails == 2) ? _("Sig. (2-tailed)") : _("Sig. (1-tailed)"));
170       if ( opts->missing_type != CORR_LISTWISE )
171         tab_text (t, 1, 3 + r * rows_per_variable, TAB_LEFT | TAT_TITLE, _("N"));
172       tab_hline (t, TAL_1, 0, nc - 1, r * rows_per_variable + 1);
173     }
174
175   for (c = 0 ; c < matrix_cols ; ++c)
176     {
177       const struct variable *v = corr->n_vars_total > corr->n_vars1 ? corr->vars[corr->n_vars_total - corr->n_vars1 + c] : corr->vars[c];
178       tab_text (t, heading_columns + c, 0, TAB_LEFT | TAT_TITLE, var_to_string (v));      
179     }
180
181   for (r = 0 ; r < corr->n_vars1 ; ++r)
182     {
183       const int row = r * rows_per_variable + heading_rows;
184       for (c = 0 ; c < matrix_cols ; ++c)
185         {
186           unsigned char flags = 0; 
187           int col_index = corr->n_vars_total - corr->n_vars1 + c;
188           double pearson = gsl_matrix_get (cm, r, col_index);
189           double w = gsl_matrix_get (samples, r, col_index);
190           double sig = opts->tails * significance_of_correlation (pearson, w);
191
192           if ( opts->missing_type != CORR_LISTWISE )
193             tab_double (t, c + heading_columns, row + 2, 0, w, wfmt);
194
195           if ( c != r)
196             tab_double (t, c + heading_columns, row + 1, 0,  sig, NULL);
197
198           if ( opts->sig && c != r && sig < 0.05)
199             flags = TAB_EMPH;
200           
201           tab_double (t, c + heading_columns, row, flags, pearson, NULL);
202         }
203     }
204
205   tab_submit (t);
206 }
207
208 static void
209 run_corr (struct casereader *r, const struct corr_opts *opts, const struct corr *corr)
210 {
211   struct ccase *c;
212   const struct design_matrix *cov_matrix;
213   const gsl_matrix *samples_matrix;
214
215   for ( ; (c = casereader_read (r) ); case_unref (c))
216     {
217
218     }
219
220
221   output_correlation (corr, opts,
222                       covariance_to_correlation (cov_matrix->m),
223                       samples_matrix );
224 }
225
226 int
227 cmd_correlation (struct lexer *lexer, struct dataset *ds)
228 {
229   int n_all_vars = 0; /* Total number of variables involved in this command */
230   const struct dictionary *dict = dataset_dict (ds);
231   bool ok = true;
232
233   struct casegrouper *grouper;
234   struct casereader *group;
235
236   struct corr *corr = NULL;
237   size_t n_corrs = 0;
238
239   struct corr_opts opts;
240   opts.missing_type = CORR_PAIRWISE;
241   opts.wv = dict_get_weight (dict);
242   opts.tails = 2;
243   opts.sig = false;
244   opts.exclude = MV_ANY;
245
246   /* Parse CORRELATIONS. */
247   while (lex_token (lexer) != '.')
248     {
249       lex_match (lexer, '/');
250       if (lex_match_id (lexer, "MISSING"))
251         {
252           lex_match (lexer, '=');
253           while (lex_token (lexer) != '.' && lex_token (lexer) != '/')
254             {
255               if (lex_match_id (lexer, "PAIRWISE"))
256                 opts.missing_type = CORR_PAIRWISE;
257               else if (lex_match_id (lexer, "LISTWISE"))
258                 opts.missing_type = CORR_LISTWISE;
259
260               else if (lex_match_id (lexer, "INCLUDE"))
261                 opts.exclude = MV_SYSTEM;
262               else if (lex_match_id (lexer, "EXCLUDE"))
263                 opts.exclude = MV_ANY;
264               else
265                 {
266                   lex_error (lexer, NULL);
267                   goto error;
268                 }
269               lex_match (lexer, ',');
270             }
271         }
272       else if (lex_match_id (lexer, "PRINT"))
273         {
274           lex_match (lexer, '=');
275           while (lex_token (lexer) != '.' && lex_token (lexer) != '/')
276             {
277               if ( lex_match_id (lexer, "TWOTAIL"))
278                 opts.tails = 2;
279               else if (lex_match_id (lexer, "ONETAIL"))
280                 opts.tails = 1;
281               else if (lex_match_id (lexer, "SIG"))
282                 opts.sig = false;
283               else if (lex_match_id (lexer, "NOSIG"))
284                 opts.sig = true;
285               else
286                 {
287                   lex_error (lexer, NULL);
288                   goto error;
289                 }
290
291               lex_match (lexer, ',');
292             }
293         }
294       else
295         {
296           if (lex_match_id (lexer, "VARIABLES"))
297             {
298               lex_match (lexer, '=');
299             }
300
301           corr = xrealloc (corr, sizeof (*corr) * (n_corrs + 1));
302           corr[n_corrs].n_vars_total = corr[n_corrs].n_vars1 = 0;
303       
304           if ( ! parse_variables_const (lexer, dict, &corr[n_corrs].vars, 
305                                         &corr[n_corrs].n_vars_total,
306                                         PV_NUMERIC))
307             {
308               ok = false;
309               break;
310             }
311
312
313           corr[n_corrs].n_vars1 = corr[n_corrs].n_vars_total;
314
315           if ( lex_match (lexer, T_WITH))
316             {
317               if ( ! parse_variables_const (lexer, dict,
318                                             &corr[n_corrs].vars, &corr[n_corrs].n_vars_total,
319                                             PV_NUMERIC | PV_APPEND))
320                 {
321                   ok = false;
322                   break;
323                 }
324             }
325
326           n_all_vars += corr[n_corrs].n_vars_total;
327
328           n_corrs++;
329         }
330     }
331
332   if (n_corrs == 0)
333     {
334       msg (SE, _("No variables specified."));
335       goto error;
336     }
337
338
339   const struct variable **all_vars = xmalloc (sizeof (*all_vars) * n_all_vars);
340   int i;
341
342   {
343     /* FIXME:  Using a hash here would make more sense */
344     const struct variable **vv = all_vars;
345
346     for (i = 0 ; i < n_corrs; ++i)
347       {
348         int v;
349         const struct corr *c = &corr[i];
350         for (v = 0 ; v < c->n_vars_total; ++v)
351           *vv++ = c->vars[v];
352       }
353   }
354
355   grouper = casegrouper_create_splits (proc_open (ds), dict);
356
357   while (casegrouper_get_next_group (grouper, &group))
358     {
359       for (i = 0 ; i < n_corrs; ++i)
360         {
361           /* FIXME: No need to iterate the data multiple times */
362           struct casereader *r = casereader_clone (group);
363
364           if ( opts.missing_type == CORR_LISTWISE)
365             r = casereader_create_filter_missing (r, all_vars, n_all_vars,
366                                                   opts.exclude, NULL, NULL);
367
368           run_corr (r, &opts,  &corr[i]);
369           casereader_destroy (r);
370         }
371       casereader_destroy (group);
372     }
373
374   ok = casegrouper_destroy (grouper);
375   ok = proc_commit (ds) && ok;
376
377   free (all_vars);
378
379
380   /* Done. */
381   free (corr);
382   return ok ? CMD_SUCCESS : CMD_CASCADING_FAILURE;
383
384  error:
385   free (corr);
386   return CMD_FAILURE;
387 }