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