Rewrite PSPP output engine.
[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/correlation.h>
22 #include <math/design-matrix.h>
23 #include <gsl/gsl_matrix.h>
24 #include <data/casegrouper.h>
25 #include <data/casereader.h>
26 #include <data/dictionary.h>
27 #include <data/procedure.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 <output/tab.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 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);
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_title (t, _("Correlations"));
192
193   tab_headers (t, heading_columns, 0, heading_rows, 0);
194
195   /* Outline the box */
196   tab_box (t,
197            TAL_2, TAL_2,
198            -1, -1,
199            0, 0,
200            nc - 1, nr - 1);
201
202   /* Vertical lines */
203   tab_box (t,
204            -1, -1,
205            -1, TAL_1,
206            heading_columns, 0,
207            nc - 1, nr - 1);
208
209   tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
210   tab_vline (t, TAL_1, 1, heading_rows, nr - 1);
211
212   for (r = 0 ; r < corr->n_vars1 ; ++r)
213     {
214       tab_text (t, 0, 1 + r * rows_per_variable, TAB_LEFT | TAT_TITLE, 
215                 var_to_string (corr->vars[r]));
216
217       tab_text (t, 1, 1 + r * rows_per_variable, TAB_LEFT | TAT_TITLE, _("Pearson Correlation"));
218       tab_text (t, 1, 2 + r * rows_per_variable, TAB_LEFT | TAT_TITLE, 
219                 (opts->tails == 2) ? _("Sig. (2-tailed)") : _("Sig. (1-tailed)"));
220
221       if (opts->statistics & STATS_XPROD)
222         {
223           tab_text (t, 1, 3 + r * rows_per_variable, TAB_LEFT | TAT_TITLE, _("Cross-products"));
224           tab_text (t, 1, 4 + r * rows_per_variable, TAB_LEFT | TAT_TITLE, _("Covariance"));
225         }
226
227       if ( opts->missing_type != CORR_LISTWISE )
228         tab_text (t, 1, rows_per_variable + r * rows_per_variable, TAB_LEFT | TAT_TITLE, _("N"));
229
230       tab_hline (t, TAL_1, 0, nc - 1, r * rows_per_variable + 1);
231     }
232
233   for (c = 0 ; c < matrix_cols ; ++c)
234     {
235       const struct variable *v = corr->n_vars_total > corr->n_vars1 ? corr->vars[corr->n_vars_total - corr->n_vars1 + c] : corr->vars[c];
236       tab_text (t, heading_columns + c, 0, TAB_LEFT | TAT_TITLE, var_to_string (v));      
237     }
238
239   for (r = 0 ; r < corr->n_vars1 ; ++r)
240     {
241       const int row = r * rows_per_variable + heading_rows;
242       for (c = 0 ; c < matrix_cols ; ++c)
243         {
244           unsigned char flags = 0; 
245           const int col_index = corr->n_vars_total - corr->n_vars1 + c;
246           double pearson = gsl_matrix_get (cm, r, col_index);
247           double w = gsl_matrix_get (samples, r, col_index);
248           double sig = opts->tails * significance_of_correlation (pearson, w);
249
250           if ( opts->missing_type != CORR_LISTWISE )
251             tab_double (t, c + heading_columns, row + rows_per_variable - 1, 0, w, wfmt);
252
253           if ( c != r)
254             tab_double (t, c + heading_columns, row + 1, 0,  sig, NULL);
255
256           if ( opts->sig && c != r && sig < 0.05)
257             flags = TAB_EMPH;
258           
259           tab_double (t, c + heading_columns, row, flags, pearson, NULL);
260
261           if (opts->statistics & STATS_XPROD)
262             {
263               double cov = gsl_matrix_get (cv, r, col_index);
264               const double xprod_dev = cov * w;
265               cov *= w / (w - 1.0);
266
267               tab_double (t, c + heading_columns, row + 2, 0, xprod_dev, NULL);
268               tab_double (t, c + heading_columns, row + 3, 0, cov, NULL);
269             }
270         }
271     }
272
273   tab_submit (t);
274 }
275
276
277 static void
278 run_corr (struct casereader *r, const struct corr_opts *opts, const struct corr *corr)
279 {
280   struct ccase *c;
281   const gsl_matrix *var_matrix,  *samples_matrix, *mean_matrix;
282   const gsl_matrix *cov_matrix;
283   gsl_matrix *corr_matrix;
284   struct covariance *cov = covariance_create (corr->n_vars_total, corr->vars,
285                                               opts->wv, opts->exclude);
286
287   for ( ; (c = casereader_read (r) ); case_unref (c))
288     {
289       covariance_accumulate (cov, c);
290     }
291
292   cov_matrix = covariance_calculate (cov);
293
294   samples_matrix = covariance_moments (cov, MOMENT_NONE);
295   var_matrix = covariance_moments (cov, MOMENT_VARIANCE);
296   mean_matrix = covariance_moments (cov, MOMENT_MEAN);
297
298   corr_matrix = correlation_from_covariance (cov_matrix, var_matrix);
299
300   if ( opts->statistics & STATS_DESCRIPTIVES) 
301     output_descriptives (corr, mean_matrix, var_matrix, samples_matrix);
302
303   output_correlation (corr, opts,
304                       corr_matrix,
305                       samples_matrix,
306                       cov_matrix);
307
308   covariance_destroy (cov);
309   gsl_matrix_free (corr_matrix);
310 }
311
312 int
313 cmd_correlation (struct lexer *lexer, struct dataset *ds)
314 {
315   int i;
316   int n_all_vars = 0; /* Total number of variables involved in this command */
317   const struct variable **all_vars ;
318   const struct dictionary *dict = dataset_dict (ds);
319   bool ok = true;
320
321   struct casegrouper *grouper;
322   struct casereader *group;
323
324   struct corr *corr = NULL;
325   size_t n_corrs = 0;
326
327   struct corr_opts opts;
328   opts.missing_type = CORR_PAIRWISE;
329   opts.wv = dict_get_weight (dict);
330   opts.tails = 2;
331   opts.sig = false;
332   opts.exclude = MV_ANY;
333   opts.statistics = 0;
334
335   /* Parse CORRELATIONS. */
336   while (lex_token (lexer) != '.')
337     {
338       lex_match (lexer, '/');
339       if (lex_match_id (lexer, "MISSING"))
340         {
341           lex_match (lexer, '=');
342           while (lex_token (lexer) != '.' && lex_token (lexer) != '/')
343             {
344               if (lex_match_id (lexer, "PAIRWISE"))
345                 opts.missing_type = CORR_PAIRWISE;
346               else if (lex_match_id (lexer, "LISTWISE"))
347                 opts.missing_type = CORR_LISTWISE;
348
349               else if (lex_match_id (lexer, "INCLUDE"))
350                 opts.exclude = MV_SYSTEM;
351               else if (lex_match_id (lexer, "EXCLUDE"))
352                 opts.exclude = MV_ANY;
353               else
354                 {
355                   lex_error (lexer, NULL);
356                   goto error;
357                 }
358               lex_match (lexer, ',');
359             }
360         }
361       else if (lex_match_id (lexer, "PRINT"))
362         {
363           lex_match (lexer, '=');
364           while (lex_token (lexer) != '.' && lex_token (lexer) != '/')
365             {
366               if ( lex_match_id (lexer, "TWOTAIL"))
367                 opts.tails = 2;
368               else if (lex_match_id (lexer, "ONETAIL"))
369                 opts.tails = 1;
370               else if (lex_match_id (lexer, "SIG"))
371                 opts.sig = false;
372               else if (lex_match_id (lexer, "NOSIG"))
373                 opts.sig = true;
374               else
375                 {
376                   lex_error (lexer, NULL);
377                   goto error;
378                 }
379
380               lex_match (lexer, ',');
381             }
382         }
383       else if (lex_match_id (lexer, "STATISTICS"))
384         {
385           lex_match (lexer, '=');
386           while (lex_token (lexer) != '.' && lex_token (lexer) != '/')
387             {
388               if ( lex_match_id (lexer, "DESCRIPTIVES"))
389                 opts.statistics = STATS_DESCRIPTIVES;
390               else if (lex_match_id (lexer, "XPROD"))
391                 opts.statistics = STATS_XPROD;
392               else if (lex_token (lexer) == T_ALL)
393                 {
394                   opts.statistics = STATS_ALL;
395                   lex_get (lexer);
396                 }
397               else 
398                 {
399                   lex_error (lexer, NULL);
400                   goto error;
401                 }
402
403               lex_match (lexer, ',');
404             }
405         }
406       else
407         {
408           if (lex_match_id (lexer, "VARIABLES"))
409             {
410               lex_match (lexer, '=');
411             }
412
413           corr = xrealloc (corr, sizeof (*corr) * (n_corrs + 1));
414           corr[n_corrs].n_vars_total = corr[n_corrs].n_vars1 = 0;
415       
416           if ( ! parse_variables_const (lexer, dict, &corr[n_corrs].vars, 
417                                         &corr[n_corrs].n_vars_total,
418                                         PV_NUMERIC))
419             {
420               ok = false;
421               break;
422             }
423
424
425           corr[n_corrs].n_vars1 = corr[n_corrs].n_vars_total;
426
427           if ( lex_match (lexer, T_WITH))
428             {
429               if ( ! parse_variables_const (lexer, dict,
430                                             &corr[n_corrs].vars, &corr[n_corrs].n_vars_total,
431                                             PV_NUMERIC | PV_APPEND))
432                 {
433                   ok = false;
434                   break;
435                 }
436             }
437
438           n_all_vars += corr[n_corrs].n_vars_total;
439
440           n_corrs++;
441         }
442     }
443
444   if (n_corrs == 0)
445     {
446       msg (SE, _("No variables specified."));
447       goto error;
448     }
449
450
451   all_vars = xmalloc (sizeof (*all_vars) * n_all_vars);
452
453   {
454     /* FIXME:  Using a hash here would make more sense */
455     const struct variable **vv = all_vars;
456
457     for (i = 0 ; i < n_corrs; ++i)
458       {
459         int v;
460         const struct corr *c = &corr[i];
461         for (v = 0 ; v < c->n_vars_total; ++v)
462           *vv++ = c->vars[v];
463       }
464   }
465
466   grouper = casegrouper_create_splits (proc_open (ds), dict);
467
468   while (casegrouper_get_next_group (grouper, &group))
469     {
470       for (i = 0 ; i < n_corrs; ++i)
471         {
472           /* FIXME: No need to iterate the data multiple times */
473           struct casereader *r = casereader_clone (group);
474
475           if ( opts.missing_type == CORR_LISTWISE)
476             r = casereader_create_filter_missing (r, all_vars, n_all_vars,
477                                                   opts.exclude, NULL, NULL);
478
479
480           run_corr (r, &opts,  &corr[i]);
481           casereader_destroy (r);
482         }
483       casereader_destroy (group);
484     }
485
486   ok = casegrouper_destroy (grouper);
487   ok = proc_commit (ds) && ok;
488
489   free (all_vars);
490
491
492   /* Done. */
493   free (corr);
494   return ok ? CMD_SUCCESS : CMD_CASCADING_FAILURE;
495
496  error:
497   free (corr);
498   return CMD_FAILURE;
499 }