89c1e2f58ae7cc734bc29c61ec8d4a68d9cd0a65
[pspp] / src / language / stats / factor.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2009, 2010, 2011, 2012 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 <gsl/gsl_vector.h>
20 #include <gsl/gsl_linalg.h>
21 #include <gsl/gsl_matrix.h>
22 #include <gsl/gsl_eigen.h> 
23 #include <gsl/gsl_blas.h> 
24 #include <gsl/gsl_sort_vector.h>
25 #include <gsl/gsl_cdf.h>
26
27 #include "data/casegrouper.h"
28 #include "data/casereader.h"
29 #include "data/casewriter.h"
30 #include "data/dataset.h"
31 #include "data/dictionary.h"
32 #include "data/format.h"
33 #include "data/subcase.h"
34 #include "language/command.h"
35 #include "language/lexer/lexer.h"
36 #include "language/lexer/value-parser.h"
37 #include "language/lexer/variable-parser.h"
38 #include "libpspp/cast.h"
39 #include "libpspp/message.h"
40 #include "libpspp/misc.h"
41 #include "math/correlation.h"
42 #include "math/covariance.h"
43 #include "math/moments.h"
44 #include "output/chart-item.h"
45 #include "output/charts/scree.h"
46 #include "output/tab.h"
47
48 #include "gettext.h"
49 #define _(msgid) gettext (msgid)
50 #define N_(msgid) msgid
51
52 enum method
53   {
54     METHOD_CORR,
55     METHOD_COV
56   };
57
58 enum missing_type
59   {
60     MISS_LISTWISE,
61     MISS_PAIRWISE,
62     MISS_MEANSUB,
63   };
64
65 enum extraction_method
66   {
67     EXTRACTION_PC,
68     EXTRACTION_PAF,
69   };
70
71 enum plot_opts
72   {
73     PLOT_SCREE = 0x0001,
74     PLOT_ROTATION = 0x0002
75   };
76
77 enum print_opts
78   {
79     PRINT_UNIVARIATE  = 0x0001,
80     PRINT_DETERMINANT = 0x0002,
81     PRINT_INV         = 0x0004,
82     PRINT_AIC         = 0x0008,
83     PRINT_SIG         = 0x0010,
84     PRINT_COVARIANCE  = 0x0020,
85     PRINT_CORRELATION = 0x0040,
86     PRINT_ROTATION    = 0x0080,
87     PRINT_EXTRACTION  = 0x0100,
88     PRINT_INITIAL     = 0x0200,
89     PRINT_KMO         = 0x0400,
90     PRINT_REPR        = 0x0800, 
91     PRINT_FSCORE      = 0x1000
92   };
93
94 enum rotation_type
95   {
96     ROT_VARIMAX = 0,
97     ROT_EQUAMAX,
98     ROT_QUARTIMAX,
99     ROT_NONE
100   };
101
102 typedef void (*rotation_coefficients) (double *x, double *y,
103                                     double a, double b, double c, double d,
104                                     const gsl_matrix *loadings );
105
106
107 static void
108 varimax_coefficients (double *x, double *y,
109                       double a, double b, double c, double d,
110                       const gsl_matrix *loadings )
111 {
112   *x = d - 2 * a * b / loadings->size1;
113   *y = c - (a * a - b * b) / loadings->size1;
114 }
115
116 static void
117 equamax_coefficients (double *x, double *y,
118                       double a, double b, double c, double d,
119                       const gsl_matrix *loadings )
120 {
121   *x = d - loadings->size2 * a * b / loadings->size1;
122   *y = c - loadings->size2 * (a * a - b * b) / (2 * loadings->size1);
123 }
124
125 static void
126 quartimax_coefficients (double *x, double *y,
127                       double a UNUSED, double b UNUSED, double c, double d,
128                       const gsl_matrix *loadings UNUSED)
129 {
130   *x = d ;
131   *y = c ;
132 }
133
134 static const rotation_coefficients rotation_coeff[3] = {
135   varimax_coefficients,
136   equamax_coefficients,
137   quartimax_coefficients
138 };
139
140
141 struct cmd_factor 
142 {
143   size_t n_vars;
144   const struct variable **vars;
145
146   const struct variable *wv;
147
148   enum method method;
149   enum missing_type missing_type;
150   enum mv_class exclude;
151   enum print_opts print;
152   enum extraction_method extraction;
153   enum plot_opts plot;
154   enum rotation_type rotation;
155
156   /* Extraction Criteria */
157   int n_factors;
158   double min_eigen;
159   double econverge;
160   int iterations;
161
162   double rconverge;
163
164   /* Format */
165   double blank;
166   bool sort;
167 };
168
169 struct idata
170 {
171   /* Intermediate values used in calculation */
172
173   const gsl_matrix *corr ;  /* The correlation matrix */
174   gsl_matrix *cov ;         /* The covariance matrix */
175   const gsl_matrix *n ;     /* Matrix of number of samples */
176
177   gsl_vector *eval ;  /* The eigenvalues */
178   gsl_matrix *evec ;  /* The eigenvectors */
179
180   int n_extractions;
181
182   gsl_vector *msr ;  /* Multiple Squared Regressions */
183
184   double detR;  /* The determinant of the correlation matrix */
185 };
186
187 static struct idata *
188 idata_alloc (size_t n_vars)
189 {
190   struct idata *id = xzalloc (sizeof (*id));
191
192   id->n_extractions = 0;
193   id->msr = gsl_vector_alloc (n_vars);
194
195   id->eval = gsl_vector_alloc (n_vars);
196   id->evec = gsl_matrix_alloc (n_vars, n_vars);
197
198   return id;
199 }
200
201 static void
202 idata_free (struct idata *id)
203 {
204   gsl_vector_free (id->msr);
205   gsl_vector_free (id->eval);
206   gsl_matrix_free (id->evec);
207   if (id->cov != NULL)
208     gsl_matrix_free (id->cov);
209   if (id->corr != NULL)
210     gsl_matrix_free (CONST_CAST (gsl_matrix *, id->corr));
211
212   free (id);
213 }
214
215
216 static gsl_matrix *
217 anti_image (const gsl_matrix *m)
218 {
219   int i, j;
220   gsl_matrix *a;
221   assert (m->size1 == m->size2);
222
223   a = gsl_matrix_alloc (m->size1, m->size2);
224   
225   for (i = 0; i < m->size1; ++i)
226     {
227       for (j = 0; j < m->size2; ++j)
228         {
229           double *p = gsl_matrix_ptr (a, i, j);
230           *p = gsl_matrix_get (m, i, j);
231           *p /= gsl_matrix_get (m, i, i);
232           *p /= gsl_matrix_get (m, j, j);
233         }
234     }
235
236   return a;
237 }
238
239
240 /* Return the sum of all the elements excluding row N */
241 static double
242 ssq_od_n (const gsl_matrix *m, int n)
243 {
244   int i, j;
245   double ss = 0;
246   assert (m->size1 == m->size2);
247
248   assert (n < m->size1);
249   
250   for (i = 0; i < m->size1; ++i)
251     {
252       if (i == n ) continue;
253       for (j = 0; j < m->size2; ++j)
254         {
255           ss += pow2 (gsl_matrix_get (m, i, j));
256         }
257     }
258
259   return ss;
260 }
261
262
263
264 #if 0
265 static void
266 dump_matrix (const gsl_matrix *m)
267 {
268   size_t i, j;
269
270   for (i = 0 ; i < m->size1; ++i)
271     {
272       for (j = 0 ; j < m->size2; ++j)
273         printf ("%02f ", gsl_matrix_get (m, i, j));
274       printf ("\n");
275     }
276 }
277
278 static void
279 dump_matrix_permute (const gsl_matrix *m, const gsl_permutation *p)
280 {
281   size_t i, j;
282
283   for (i = 0 ; i < m->size1; ++i)
284     {
285       for (j = 0 ; j < m->size2; ++j)
286         printf ("%02f ", gsl_matrix_get (m, gsl_permutation_get (p, i), j));
287       printf ("\n");
288     }
289 }
290
291
292 static void
293 dump_vector (const gsl_vector *v)
294 {
295   size_t i;
296   for (i = 0 ; i < v->size; ++i)
297     {
298       printf ("%02f\n", gsl_vector_get (v, i));
299     }
300   printf ("\n");
301 }
302 #endif
303
304
305 static int 
306 n_extracted_factors (const struct cmd_factor *factor, struct idata *idata)
307 {
308   int i;
309   
310   /* If there is a cached value, then return that. */
311   if ( idata->n_extractions != 0)
312     return idata->n_extractions;
313
314   /* Otherwise, if the number of factors has been explicitly requested,
315      use that. */
316   if (factor->n_factors > 0)
317     {
318       idata->n_extractions = factor->n_factors;
319       goto finish;
320     }
321   
322   /* Use the MIN_EIGEN setting. */
323   for (i = 0 ; i < idata->eval->size; ++i)
324     {
325       double evali = fabs (gsl_vector_get (idata->eval, i));
326
327       idata->n_extractions = i;
328
329       if (evali < factor->min_eigen)
330         goto finish;
331     }
332
333  finish:
334   return idata->n_extractions;
335 }
336
337
338 /* Returns a newly allocated matrix identical to M.
339    It it the callers responsibility to free the returned value.
340 */
341 static gsl_matrix *
342 matrix_dup (const gsl_matrix *m)
343 {
344   gsl_matrix *n =  gsl_matrix_alloc (m->size1, m->size2);
345
346   gsl_matrix_memcpy (n, m);
347
348   return n;
349 }
350
351
352 struct smr_workspace
353 {
354   /* Copy of the subject */
355   gsl_matrix *m;
356   
357   gsl_matrix *inverse;
358
359   gsl_permutation *perm;
360
361   gsl_matrix *result1;
362   gsl_matrix *result2;
363 };
364
365
366 static struct smr_workspace *ws_create (const gsl_matrix *input)
367 {
368   struct smr_workspace *ws = xmalloc (sizeof (*ws));
369   
370   ws->m = gsl_matrix_alloc (input->size1, input->size2);
371   ws->inverse = gsl_matrix_calloc (input->size1 - 1, input->size2 - 1);
372   ws->perm = gsl_permutation_alloc (input->size1 - 1);
373   ws->result1 = gsl_matrix_calloc (input->size1 - 1, 1);
374   ws->result2 = gsl_matrix_calloc (1, 1);
375
376   return ws;
377 }
378
379 static void
380 ws_destroy (struct smr_workspace *ws)
381 {
382   gsl_matrix_free (ws->result2);
383   gsl_matrix_free (ws->result1);
384   gsl_permutation_free (ws->perm);
385   gsl_matrix_free (ws->inverse);
386   gsl_matrix_free (ws->m);
387
388   free (ws);
389 }
390
391
392 /* 
393    Return the square of the regression coefficient for VAR regressed against all other variables.
394  */
395 static double
396 squared_multiple_correlation (const gsl_matrix *corr, int var, struct smr_workspace *ws)
397 {
398   /* For an explanation of what this is doing, see 
399      http://www.visualstatistics.net/Visual%20Statistics%20Multimedia/multiple_regression_analysis.htm
400   */
401
402   int signum = 0;
403   gsl_matrix_view rxx;
404
405   gsl_matrix_memcpy (ws->m, corr);
406
407   gsl_matrix_swap_rows (ws->m, 0, var);
408   gsl_matrix_swap_columns (ws->m, 0, var);
409
410   rxx = gsl_matrix_submatrix (ws->m, 1, 1, ws->m->size1 - 1, ws->m->size1 - 1); 
411
412   gsl_linalg_LU_decomp (&rxx.matrix, ws->perm, &signum);
413
414   gsl_linalg_LU_invert (&rxx.matrix, ws->perm, ws->inverse);
415
416   {
417     gsl_matrix_const_view rxy = gsl_matrix_const_submatrix (ws->m, 1, 0, ws->m->size1 - 1, 1);
418     gsl_matrix_const_view ryx = gsl_matrix_const_submatrix (ws->m, 0, 1, 1, ws->m->size1 - 1);
419
420     gsl_blas_dgemm (CblasNoTrans,  CblasNoTrans,
421                     1.0, ws->inverse, &rxy.matrix, 0.0, ws->result1);
422
423     gsl_blas_dgemm (CblasNoTrans,  CblasNoTrans,
424                     1.0, &ryx.matrix, ws->result1, 0.0, ws->result2);
425   }
426
427   return gsl_matrix_get (ws->result2, 0, 0);
428 }
429
430
431
432 static double the_communality (const gsl_matrix *evec, const gsl_vector *eval, int n, int n_factors);
433
434
435 struct factor_matrix_workspace
436 {
437   size_t n_factors;
438   gsl_eigen_symmv_workspace *eigen_ws;
439
440   gsl_vector *eval ;
441   gsl_matrix *evec ;
442
443   gsl_matrix *gamma ;
444
445   gsl_matrix *r;
446 };
447
448 static struct factor_matrix_workspace *
449 factor_matrix_workspace_alloc (size_t n, size_t nf)
450 {
451   struct factor_matrix_workspace *ws = xmalloc (sizeof (*ws));
452
453   ws->n_factors = nf;
454   ws->gamma = gsl_matrix_calloc (nf, nf);
455   ws->eigen_ws = gsl_eigen_symmv_alloc (n);
456   ws->eval = gsl_vector_alloc (n);
457   ws->evec = gsl_matrix_alloc (n, n);
458   ws->r  = gsl_matrix_alloc (n, n);
459   
460   return ws;
461 }
462
463 static void
464 factor_matrix_workspace_free (struct factor_matrix_workspace *ws)
465 {
466   gsl_eigen_symmv_free (ws->eigen_ws);
467   gsl_vector_free (ws->eval);
468   gsl_matrix_free (ws->evec);
469   gsl_matrix_free (ws->gamma);
470   gsl_matrix_free (ws->r);
471   free (ws);
472 }
473
474 /*
475   Shift P left by OFFSET places, and overwrite TARGET
476   with the shifted result.
477   Positions in TARGET less than OFFSET are unchanged.
478 */
479 static void
480 perm_shift_apply (gsl_permutation *target, const gsl_permutation *p,
481                   size_t offset)
482 {
483   size_t i;
484   assert (target->size == p->size);
485   assert (offset <= target->size);
486
487   for (i = 0; i < target->size - offset; ++i)
488     {
489       target->data[i] = p->data [i + offset];
490     }
491 }
492
493
494 /* 
495    Indirectly sort the rows of matrix INPUT, storing the sort order in PERM.
496    The sort criteria are as follows:
497    
498    Rows are sorted on the first column, until the absolute value of an
499    element in a subsequent column  is greater than that of the first
500    column.  Thereafter, rows will be sorted on the second column,
501    until the absolute value of an element in a subsequent column
502    exceeds that of the second column ...
503 */
504 static void
505 sort_matrix_indirect (const gsl_matrix *input, gsl_permutation *perm)
506 {
507   const size_t n = perm->size;
508   const size_t m = input->size2;
509   int i, j;
510   gsl_matrix *mat ;
511   int column_n = 0;
512   int row_n = 0;
513   gsl_permutation *p;
514
515   assert (perm->size == input->size1);
516
517   p = gsl_permutation_alloc (n);
518
519   /* Copy INPUT into MAT, discarding the sign */
520   mat = gsl_matrix_alloc (n, m);
521   for (i = 0 ; i < mat->size1; ++i)
522     {
523       for (j = 0 ; j < mat->size2; ++j)
524         {
525           double x = gsl_matrix_get (input, i, j);
526           gsl_matrix_set (mat, i, j, fabs (x));
527         }
528     }
529
530   while (column_n < m && row_n < n) 
531     {
532       gsl_vector_const_view columni = gsl_matrix_const_column (mat, column_n);
533       gsl_sort_vector_index (p, &columni.vector);
534
535       for (i = 0 ; i < n; ++i)
536         {
537           gsl_vector_view row = gsl_matrix_row (mat, p->data[n - 1 - i]);
538           size_t maxindex = gsl_vector_max_index (&row.vector);
539           
540           if ( maxindex > column_n )
541             break;
542
543           /* All subsequent elements of this row, are of no interest.
544              So set them all to a highly negative value */
545           for (j = column_n + 1; j < row.vector.size ; ++j)
546             gsl_vector_set (&row.vector, j, -DBL_MAX);
547         }
548
549       perm_shift_apply (perm, p, row_n);
550       row_n += i;
551
552       column_n++;
553     }
554
555   gsl_permutation_free (p);
556   gsl_matrix_free (mat);
557   
558   assert ( 0 == gsl_permutation_valid (perm));
559
560   /* We want the biggest value to be first */
561   gsl_permutation_reverse (perm);    
562 }
563
564
565 static void
566 drot_go (double phi, double *l0, double *l1)
567 {
568   double r0 = cos (phi) * *l0 + sin (phi) * *l1;
569   double r1 = - sin (phi) * *l0 + cos (phi) * *l1;
570
571   *l0 = r0;
572   *l1 = r1;
573 }
574
575
576 static gsl_matrix *
577 clone_matrix (const gsl_matrix *m)
578 {
579   int j, k;
580   gsl_matrix *c = gsl_matrix_calloc (m->size1, m->size2);
581
582   for (j = 0 ; j < c->size1; ++j)
583     {
584       for (k = 0 ; k < c->size2; ++k)
585         {
586           const double *v = gsl_matrix_const_ptr (m, j, k);
587           gsl_matrix_set (c, j, k, *v);
588         }
589     }
590
591   return c;
592 }
593
594
595 static double 
596 initial_sv (const gsl_matrix *fm)
597 {
598   int j, k;
599
600   double sv = 0.0;
601   for (j = 0 ; j < fm->size2; ++j)
602     {
603       double l4s = 0;
604       double l2s = 0;
605
606       for (k = j + 1 ; k < fm->size2; ++k)
607         {
608           double lambda = gsl_matrix_get (fm, k, j);
609           double lambda_sq = lambda * lambda;
610           double lambda_4 = lambda_sq * lambda_sq;
611
612           l4s += lambda_4;
613           l2s += lambda_sq;
614         }
615       sv += ( fm->size1 * l4s - (l2s * l2s) ) / (fm->size1 * fm->size1 );
616     }
617   return sv;
618 }
619
620 static void
621 rotate (const struct cmd_factor *cf, const gsl_matrix *unrot,
622         const gsl_vector *communalities,
623         gsl_matrix *result,
624         gsl_vector *rotated_loadings
625         )
626 {
627   int j, k;
628   int i;
629   double prev_sv;
630
631   /* First get a normalised version of UNROT */
632   gsl_matrix *normalised = gsl_matrix_calloc (unrot->size1, unrot->size2);
633   gsl_matrix *h_sqrt = gsl_matrix_calloc (communalities->size, communalities->size);
634   gsl_matrix *h_sqrt_inv ;
635
636   /* H is the diagonal matrix containing the absolute values of the communalities */
637   for (i = 0 ; i < communalities->size ; ++i)
638     {
639       double *ptr = gsl_matrix_ptr (h_sqrt, i, i);
640       *ptr = fabs (gsl_vector_get (communalities, i));
641     }
642
643   /* Take the square root of the communalities */
644   gsl_linalg_cholesky_decomp (h_sqrt);
645
646
647   /* Save a copy of h_sqrt and invert it */
648   h_sqrt_inv = clone_matrix (h_sqrt);
649   gsl_linalg_cholesky_decomp (h_sqrt_inv);
650   gsl_linalg_cholesky_invert (h_sqrt_inv);
651
652   /* normalised vertion is H^{1/2} x UNROT */
653   gsl_blas_dgemm (CblasNoTrans,  CblasNoTrans, 1.0, h_sqrt_inv, unrot, 0.0, normalised);
654
655   gsl_matrix_free (h_sqrt_inv);
656
657
658   /* Now perform the rotation iterations */
659
660   prev_sv = initial_sv (normalised);
661   for (i = 0 ; i < cf->iterations ; ++i)
662     {
663       double sv = 0.0;
664       for (j = 0 ; j < normalised->size2; ++j)
665         {
666           /* These variables relate to the convergence criterium */
667           double l4s = 0;
668           double l2s = 0;
669
670           for (k = j + 1 ; k < normalised->size2; ++k)
671             {
672               int p;
673               double a = 0.0;
674               double b = 0.0;
675               double c = 0.0;
676               double d = 0.0;
677               double x, y;
678               double phi;
679
680               for (p = 0; p < normalised->size1; ++p)
681                 {
682                   double jv = gsl_matrix_get (normalised, p, j);
683                   double kv = gsl_matrix_get (normalised, p, k);
684               
685                   double u = jv * jv - kv * kv;
686                   double v = 2 * jv * kv;
687                   a += u;
688                   b += v;
689                   c +=  u * u - v * v;
690                   d += 2 * u * v;
691                 }
692
693               rotation_coeff [cf->rotation] (&x, &y, a, b, c, d, normalised);
694
695               phi = atan2 (x,  y) / 4.0 ;
696
697               /* Don't bother rotating if the angle is small */
698               if ( fabs (sin (phi) ) <= pow (10.0, -15.0))
699                   continue;
700
701               for (p = 0; p < normalised->size1; ++p)
702                 {
703                   double *lambda0 = gsl_matrix_ptr (normalised, p, j);
704                   double *lambda1 = gsl_matrix_ptr (normalised, p, k);
705                   drot_go (phi, lambda0, lambda1);
706                 }
707
708               /* Calculate the convergence criterium */
709               {
710                 double lambda = gsl_matrix_get (normalised, k, j);
711                 double lambda_sq = lambda * lambda;
712                 double lambda_4 = lambda_sq * lambda_sq;
713
714                 l4s += lambda_4;
715                 l2s += lambda_sq;
716               }
717             }
718           sv += ( normalised->size1 * l4s - (l2s * l2s) ) / (normalised->size1 * normalised->size1 );
719         }
720
721       if ( fabs (sv - prev_sv) <= cf->rconverge)
722         break;
723
724       prev_sv = sv;
725     }
726
727   gsl_blas_dgemm (CblasNoTrans,  CblasNoTrans, 1.0,
728                   h_sqrt, normalised,  0.0,   result);
729
730   gsl_matrix_free (h_sqrt);
731   gsl_matrix_free (normalised);
732
733
734   /* reflect negative sums and populate the rotated loadings vector*/
735   for (i = 0 ; i < result->size2; ++i)
736     {
737       double ssq = 0.0;
738       double sum = 0.0;
739       for (j = 0 ; j < result->size1; ++j)
740         {
741           double s = gsl_matrix_get (result, j, i);
742           ssq += s * s;
743           sum += gsl_matrix_get (result, j, i);
744         }
745
746       gsl_vector_set (rotated_loadings, i, ssq);
747
748       if ( sum < 0 )
749         for (j = 0 ; j < result->size1; ++j)
750           {
751             double *lambda = gsl_matrix_ptr (result, j, i);
752             *lambda = - *lambda;
753           }
754     }
755 }
756
757
758 /*
759   Get an approximation for the factor matrix into FACTORS, and the communalities into COMMUNALITIES.
760   R is the matrix to be analysed.
761   WS is a pointer to a structure which must have been initialised with factor_matrix_workspace_init.
762  */
763 static void
764 iterate_factor_matrix (const gsl_matrix *r, gsl_vector *communalities, gsl_matrix *factors, 
765                        struct factor_matrix_workspace *ws)
766 {
767   size_t i;
768   gsl_matrix_view mv ;
769
770   assert (r->size1 == r->size2);
771   assert (r->size1 == communalities->size);
772
773   assert (factors->size1 == r->size1);
774   assert (factors->size2 == ws->n_factors);
775
776   gsl_matrix_memcpy (ws->r, r);
777
778   /* Apply Communalities to diagonal of correlation matrix */
779   for (i = 0 ; i < communalities->size ; ++i)
780     {
781       double *x = gsl_matrix_ptr (ws->r, i, i);
782       *x = gsl_vector_get (communalities, i);
783     }
784
785   gsl_eigen_symmv (ws->r, ws->eval, ws->evec, ws->eigen_ws);
786
787   mv = gsl_matrix_submatrix (ws->evec, 0, 0, ws->evec->size1, ws->n_factors);
788
789   /* Gamma is the diagonal matrix containing the absolute values of the eigenvalues */
790   for (i = 0 ; i < ws->n_factors ; ++i)
791     {
792       double *ptr = gsl_matrix_ptr (ws->gamma, i, i);
793       *ptr = fabs (gsl_vector_get (ws->eval, i));
794     }
795
796   /* Take the square root of gamma */
797   gsl_linalg_cholesky_decomp (ws->gamma);
798
799   gsl_blas_dgemm (CblasNoTrans,  CblasNoTrans, 1.0, &mv.matrix, ws->gamma, 0.0, factors);
800
801   for (i = 0 ; i < r->size1 ; ++i)
802     {
803       double h = the_communality (ws->evec, ws->eval, i, ws->n_factors);
804       gsl_vector_set (communalities, i, h);
805     }
806 }
807
808
809
810 static bool run_factor (struct dataset *ds, const struct cmd_factor *factor);
811
812
813 int
814 cmd_factor (struct lexer *lexer, struct dataset *ds)
815 {
816   bool extraction_seen = false;
817   const struct dictionary *dict = dataset_dict (ds);
818
819   struct cmd_factor factor;
820   factor.n_vars = 0;
821   factor.vars = NULL;
822   factor.method = METHOD_CORR;
823   factor.missing_type = MISS_LISTWISE;
824   factor.exclude = MV_ANY;
825   factor.print = PRINT_INITIAL | PRINT_EXTRACTION | PRINT_ROTATION;
826   factor.extraction = EXTRACTION_PC;
827   factor.n_factors = 0;
828   factor.min_eigen = SYSMIS;
829   factor.iterations = 25;
830   factor.econverge = 0.001;
831
832   factor.blank = 0;
833   factor.sort = false;
834   factor.plot = 0;
835   factor.rotation = ROT_VARIMAX;
836
837   factor.rconverge = 0.0001;
838
839   factor.wv = dict_get_weight (dict);
840
841   lex_match (lexer, T_SLASH);
842
843   if (!lex_force_match_id (lexer, "VARIABLES"))
844     {
845       goto error;
846     }
847
848   lex_match (lexer, T_EQUALS);
849
850   if (!parse_variables_const (lexer, dict, &factor.vars, &factor.n_vars,
851                               PV_NO_DUPLICATE | PV_NUMERIC))
852     goto error;
853
854   if (factor.n_vars < 2)
855     msg (MW, _("Factor analysis on a single variable is not useful."));
856
857   while (lex_token (lexer) != T_ENDCMD)
858     {
859       lex_match (lexer, T_SLASH);
860
861       if (lex_match_id (lexer, "PLOT"))
862         {
863           lex_match (lexer, T_EQUALS);
864           while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
865             {
866               if (lex_match_id (lexer, "EIGEN"))
867                 {
868                   factor.plot |= PLOT_SCREE;
869                 }
870 #if FACTOR_FULLY_IMPLEMENTED
871               else if (lex_match_id (lexer, "ROTATION"))
872                 {
873                 }
874 #endif
875               else
876                 {
877                   lex_error (lexer, NULL);
878                   goto error;
879                 }
880             }
881         }
882       else if (lex_match_id (lexer, "METHOD"))
883         {
884           lex_match (lexer, T_EQUALS);
885           while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
886             {
887               if (lex_match_id (lexer, "COVARIANCE"))
888                 {
889                   factor.method = METHOD_COV;
890                 }
891               else if (lex_match_id (lexer, "CORRELATION"))
892                 {
893                   factor.method = METHOD_CORR;
894                 }
895               else
896                 {
897                   lex_error (lexer, NULL);
898                   goto error;
899                 }
900             }
901         }
902       else if (lex_match_id (lexer, "ROTATION"))
903         {
904           lex_match (lexer, T_EQUALS);
905           while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
906             {
907               /* VARIMAX and DEFAULT are defaults */
908               if (lex_match_id (lexer, "VARIMAX") || lex_match_id (lexer, "DEFAULT"))
909                 {
910                   factor.rotation = ROT_VARIMAX;
911                 }
912               else if (lex_match_id (lexer, "EQUAMAX"))
913                 {
914                   factor.rotation = ROT_EQUAMAX;
915                 }
916               else if (lex_match_id (lexer, "QUARTIMAX"))
917                 {
918                   factor.rotation = ROT_QUARTIMAX;
919                 }
920               else if (lex_match_id (lexer, "NOROTATE"))
921                 {
922                   factor.rotation = ROT_NONE;
923                 }
924               else
925                 {
926                   lex_error (lexer, NULL);
927                   goto error;
928                 }
929             }
930         }
931       else if (lex_match_id (lexer, "CRITERIA"))
932         {
933           lex_match (lexer, T_EQUALS);
934           while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
935             {
936               if (lex_match_id (lexer, "FACTORS"))
937                 {
938                   if ( lex_force_match (lexer, T_LPAREN))
939                     {
940                       lex_force_int (lexer);
941                       factor.n_factors = lex_integer (lexer);
942                       lex_get (lexer);
943                       lex_force_match (lexer, T_RPAREN);
944                     }
945                 }
946               else if (lex_match_id (lexer, "MINEIGEN"))
947                 {
948                   if ( lex_force_match (lexer, T_LPAREN))
949                     {
950                       lex_force_num (lexer);
951                       factor.min_eigen = lex_number (lexer);
952                       lex_get (lexer);
953                       lex_force_match (lexer, T_RPAREN);
954                     }
955                 }
956               else if (lex_match_id (lexer, "ECONVERGE"))
957                 {
958                   if ( lex_force_match (lexer, T_LPAREN))
959                     {
960                       lex_force_num (lexer);
961                       factor.econverge = lex_number (lexer);
962                       lex_get (lexer);
963                       lex_force_match (lexer, T_RPAREN);
964                     }
965                 }
966               else if (lex_match_id (lexer, "RCONVERGE"))
967                 {
968                   if ( lex_force_match (lexer, T_LPAREN))
969                     {
970                       lex_force_num (lexer);
971                       factor.rconverge = lex_number (lexer);
972                       lex_get (lexer);
973                       lex_force_match (lexer, T_RPAREN);
974                     }
975                 }
976               else if (lex_match_id (lexer, "ITERATE"))
977                 {
978                   if ( lex_force_match (lexer, T_LPAREN))
979                     {
980                       lex_force_int (lexer);
981                       factor.iterations = lex_integer (lexer);
982                       lex_get (lexer);
983                       lex_force_match (lexer, T_RPAREN);
984                     }
985                 }
986               else if (lex_match_id (lexer, "DEFAULT"))
987                 {
988                   factor.n_factors = 0;
989                   factor.min_eigen = 1;
990                   factor.iterations = 25;
991                 }
992               else
993                 {
994                   lex_error (lexer, NULL);
995                   goto error;
996                 }
997             }
998         }
999       else if (lex_match_id (lexer, "EXTRACTION"))
1000         {
1001           extraction_seen = true;
1002           lex_match (lexer, T_EQUALS);
1003           while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
1004             {
1005               if (lex_match_id (lexer, "PAF"))
1006                 {
1007                   factor.extraction = EXTRACTION_PAF;
1008                 }
1009               else if (lex_match_id (lexer, "PC"))
1010                 {
1011                   factor.extraction = EXTRACTION_PC;
1012                 }
1013               else if (lex_match_id (lexer, "PA1"))
1014                 {
1015                   factor.extraction = EXTRACTION_PC;
1016                 }
1017               else if (lex_match_id (lexer, "DEFAULT"))
1018                 {
1019                   factor.extraction = EXTRACTION_PC;
1020                 }
1021               else
1022                 {
1023                   lex_error (lexer, NULL);
1024                   goto error;
1025                 }
1026             }
1027         }
1028       else if (lex_match_id (lexer, "FORMAT"))
1029         {
1030           lex_match (lexer, T_EQUALS);
1031           while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
1032             {
1033               if (lex_match_id (lexer, "SORT"))
1034                 {
1035                   factor.sort = true;
1036                 }
1037               else if (lex_match_id (lexer, "BLANK"))
1038                 {
1039                   if ( lex_force_match (lexer, T_LPAREN))
1040                     {
1041                       lex_force_num (lexer);
1042                       factor.blank = lex_number (lexer);
1043                       lex_get (lexer);
1044                       lex_force_match (lexer, T_RPAREN);
1045                     }
1046                 }
1047               else if (lex_match_id (lexer, "DEFAULT"))
1048                 {
1049                   factor.blank = 0;
1050                   factor.sort = false;
1051                 }
1052               else
1053                 {
1054                   lex_error (lexer, NULL);
1055                   goto error;
1056                 }
1057             }
1058         }
1059       else if (lex_match_id (lexer, "PRINT"))
1060         {
1061           factor.print = 0;
1062           lex_match (lexer, T_EQUALS);
1063           while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
1064             {
1065               if (lex_match_id (lexer, "UNIVARIATE"))
1066                 {
1067                   factor.print |= PRINT_UNIVARIATE;
1068                 }
1069               else if (lex_match_id (lexer, "DET"))
1070                 {
1071                   factor.print |= PRINT_DETERMINANT;
1072                 }
1073 #if FACTOR_FULLY_IMPLEMENTED
1074               else if (lex_match_id (lexer, "INV"))
1075                 {
1076                 }
1077               else if (lex_match_id (lexer, "AIC"))
1078                 {
1079                 }
1080 #endif
1081               else if (lex_match_id (lexer, "SIG"))
1082                 {
1083                   factor.print |= PRINT_SIG;
1084                 }
1085               else if (lex_match_id (lexer, "CORRELATION"))
1086                 {
1087                   factor.print |= PRINT_CORRELATION;
1088                 }
1089 #if FACTOR_FULLY_IMPLEMENTED
1090               else if (lex_match_id (lexer, "COVARIANCE"))
1091                 {
1092                 }
1093 #endif
1094               else if (lex_match_id (lexer, "ROTATION"))
1095                 {
1096                   factor.print |= PRINT_ROTATION;
1097                 }
1098               else if (lex_match_id (lexer, "EXTRACTION"))
1099                 {
1100                   factor.print |= PRINT_EXTRACTION;
1101                 }
1102               else if (lex_match_id (lexer, "INITIAL"))
1103                 {
1104                   factor.print |= PRINT_INITIAL;
1105                 }
1106               else if (lex_match_id (lexer, "KMO"))
1107                 {
1108                   factor.print |= PRINT_KMO;
1109                 }
1110 #if FACTOR_FULLY_IMPLEMENTED
1111               else if (lex_match_id (lexer, "REPR"))
1112                 {
1113                 }
1114               else if (lex_match_id (lexer, "FSCORE"))
1115                 {
1116                 }
1117 #endif
1118               else if (lex_match (lexer, T_ALL))
1119                 {
1120                   factor.print = 0xFFFF;
1121                 }
1122               else if (lex_match_id (lexer, "DEFAULT"))
1123                 {
1124                   factor.print |= PRINT_INITIAL ;
1125                   factor.print |= PRINT_EXTRACTION ;
1126                   factor.print |= PRINT_ROTATION ;
1127                 }
1128               else
1129                 {
1130                   lex_error (lexer, NULL);
1131                   goto error;
1132                 }
1133             }
1134         }
1135       else if (lex_match_id (lexer, "MISSING"))
1136         {
1137           lex_match (lexer, T_EQUALS);
1138           while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
1139             {
1140               if (lex_match_id (lexer, "INCLUDE"))
1141                 {
1142                   factor.exclude = MV_SYSTEM;
1143                 }
1144               else if (lex_match_id (lexer, "EXCLUDE"))
1145                 {
1146                   factor.exclude = MV_ANY;
1147                 }
1148               else if (lex_match_id (lexer, "LISTWISE"))
1149                 {
1150                   factor.missing_type = MISS_LISTWISE;
1151                 }
1152               else if (lex_match_id (lexer, "PAIRWISE"))
1153                 {
1154                   factor.missing_type = MISS_PAIRWISE;
1155                 }
1156               else if (lex_match_id (lexer, "MEANSUB"))
1157                 {
1158                   factor.missing_type = MISS_MEANSUB;
1159                 }
1160               else
1161                 {
1162                   lex_error (lexer, NULL);
1163                   goto error;
1164                 }
1165             }
1166         }
1167       else
1168         {
1169           lex_error (lexer, NULL);
1170           goto error;
1171         }
1172     }
1173
1174   if ( factor.rotation == ROT_NONE )
1175     factor.print &= ~PRINT_ROTATION;
1176
1177   if ( ! run_factor (ds, &factor)) 
1178     goto error;
1179
1180   free (factor.vars);
1181   return CMD_SUCCESS;
1182
1183  error:
1184   free (factor.vars);
1185   return CMD_FAILURE;
1186 }
1187
1188 static void do_factor (const struct cmd_factor *factor, struct casereader *group);
1189
1190
1191 static bool
1192 run_factor (struct dataset *ds, const struct cmd_factor *factor)
1193 {
1194   struct dictionary *dict = dataset_dict (ds);
1195   bool ok;
1196   struct casereader *group;
1197
1198   struct casegrouper *grouper = casegrouper_create_splits (proc_open (ds), dict);
1199
1200   while (casegrouper_get_next_group (grouper, &group))
1201     {
1202       if ( factor->missing_type == MISS_LISTWISE )
1203         group  = casereader_create_filter_missing (group, factor->vars, factor->n_vars,
1204                                                    factor->exclude,
1205                                                    NULL,  NULL);
1206       do_factor (factor, group);
1207     }
1208
1209   ok = casegrouper_destroy (grouper);
1210   ok = proc_commit (ds) && ok;
1211
1212   return ok;
1213 }
1214
1215
1216 /* Return the communality of variable N, calculated to N_FACTORS */
1217 static double
1218 the_communality (const gsl_matrix *evec, const gsl_vector *eval, int n, int n_factors)
1219 {
1220   size_t i;
1221
1222   double comm = 0;
1223
1224   assert (n >= 0);
1225   assert (n < eval->size);
1226   assert (n < evec->size1);
1227   assert (n_factors <= eval->size);
1228
1229   for (i = 0 ; i < n_factors; ++i)
1230     {
1231       double evali = fabs (gsl_vector_get (eval, i));
1232
1233       double eveci = gsl_matrix_get (evec, n, i);
1234
1235       comm += pow2 (eveci) * evali;
1236     }
1237
1238   return comm;
1239 }
1240
1241 /* Return the communality of variable N, calculated to N_FACTORS */
1242 static double
1243 communality (struct idata *idata, int n, int n_factors)
1244 {
1245   return the_communality (idata->evec, idata->eval, n, n_factors);
1246 }
1247
1248
1249 static void
1250 show_scree (const struct cmd_factor *f, struct idata *idata)
1251 {
1252   struct scree *s;
1253   const char *label ;
1254
1255   if ( !(f->plot & PLOT_SCREE) )
1256     return;
1257
1258
1259   label = f->extraction == EXTRACTION_PC ? _("Component Number") : _("Factor Number");
1260
1261   s = scree_create (idata->eval, label);
1262
1263   scree_submit (s);
1264 }
1265
1266 static void
1267 show_communalities (const struct cmd_factor * factor,
1268                     const gsl_vector *initial, const gsl_vector *extracted)
1269 {
1270   int i;
1271   int c = 0;
1272   const int heading_columns = 1;
1273   int nc = heading_columns;
1274   const int heading_rows = 1;
1275   const int nr = heading_rows + factor->n_vars;
1276   struct tab_table *t;
1277
1278   if (factor->print & PRINT_EXTRACTION)
1279     nc++;
1280
1281   if (factor->print & PRINT_INITIAL)
1282     nc++;
1283
1284   /* No point having a table with only headings */
1285   if (nc <= 1)
1286     return;
1287
1288   t = tab_create (nc, nr);
1289
1290   tab_title (t, _("Communalities"));
1291
1292   tab_headers (t, heading_columns, 0, heading_rows, 0);
1293
1294   c = 1;
1295   if (factor->print & PRINT_INITIAL)
1296     tab_text (t, c++, 0, TAB_CENTER | TAT_TITLE, _("Initial"));
1297
1298   if (factor->print & PRINT_EXTRACTION)
1299     tab_text (t, c++, 0, TAB_CENTER | TAT_TITLE, _("Extraction"));
1300
1301   /* Outline the box */
1302   tab_box (t,
1303            TAL_2, TAL_2,
1304            -1, -1,
1305            0, 0,
1306            nc - 1, nr - 1);
1307
1308   /* Vertical lines */
1309   tab_box (t,
1310            -1, -1,
1311            -1, TAL_1,
1312            heading_columns, 0,
1313            nc - 1, nr - 1);
1314
1315   tab_hline (t, TAL_1, 0, nc - 1, heading_rows);
1316   tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
1317
1318   for (i = 0 ; i < factor->n_vars; ++i)
1319     {
1320       c = 0;
1321       tab_text (t, c++, i + heading_rows, TAT_TITLE, var_to_string (factor->vars[i]));
1322
1323       if (factor->print & PRINT_INITIAL)
1324         tab_double (t, c++, i + heading_rows, 0, gsl_vector_get (initial, i), NULL);
1325
1326       if (factor->print & PRINT_EXTRACTION)
1327         tab_double (t, c++, i + heading_rows, 0, gsl_vector_get (extracted, i), NULL);
1328     }
1329
1330   tab_submit (t);
1331 }
1332
1333
1334 static void
1335 show_factor_matrix (const struct cmd_factor *factor, struct idata *idata, const char *title, const gsl_matrix *fm)
1336 {
1337   int i;
1338   const int n_factors = idata->n_extractions;
1339
1340   const int heading_columns = 1;
1341   const int heading_rows = 2;
1342   const int nr = heading_rows + factor->n_vars;
1343   const int nc = heading_columns + n_factors;
1344   gsl_permutation *perm;
1345
1346   struct tab_table *t = tab_create (nc, nr);
1347
1348   /* 
1349   if ( factor->extraction == EXTRACTION_PC )
1350     tab_title (t, _("Component Matrix"));
1351   else 
1352     tab_title (t, _("Factor Matrix"));
1353   */
1354
1355   tab_title (t, "%s", title);
1356
1357   tab_headers (t, heading_columns, 0, heading_rows, 0);
1358
1359   if ( factor->extraction == EXTRACTION_PC )
1360     tab_joint_text (t,
1361                     1, 0,
1362                     nc - 1, 0,
1363                     TAB_CENTER | TAT_TITLE, _("Component"));
1364   else
1365     tab_joint_text (t,
1366                     1, 0,
1367                     nc - 1, 0,
1368                     TAB_CENTER | TAT_TITLE, _("Factor"));
1369
1370
1371   tab_hline (t, TAL_1, heading_columns, nc - 1, 1);
1372
1373
1374   /* Outline the box */
1375   tab_box (t,
1376            TAL_2, TAL_2,
1377            -1, -1,
1378            0, 0,
1379            nc - 1, nr - 1);
1380
1381   /* Vertical lines */
1382   tab_box (t,
1383            -1, -1,
1384            -1, TAL_1,
1385            heading_columns, 1,
1386            nc - 1, nr - 1);
1387
1388   tab_hline (t, TAL_1, 0, nc - 1, heading_rows);
1389   tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
1390
1391
1392   /* Initialise to the identity permutation */
1393   perm = gsl_permutation_calloc (factor->n_vars);
1394
1395   if ( factor->sort)
1396     sort_matrix_indirect (fm, perm);
1397
1398   for (i = 0 ; i < n_factors; ++i)
1399     {
1400       tab_text_format (t, heading_columns + i, 1, TAB_CENTER | TAT_TITLE, _("%d"), i + 1);
1401     }
1402
1403   for (i = 0 ; i < factor->n_vars; ++i)
1404     {
1405       int j;
1406       const int matrix_row = perm->data[i];
1407       tab_text (t, 0, i + heading_rows, TAT_TITLE, var_to_string (factor->vars[matrix_row]));
1408
1409       for (j = 0 ; j < n_factors; ++j)
1410         {
1411           double x = gsl_matrix_get (fm, matrix_row, j);
1412
1413           if ( fabs (x) < factor->blank)
1414             continue;
1415
1416           tab_double (t, heading_columns + j, heading_rows + i, 0, x, NULL);
1417         }
1418     }
1419
1420   gsl_permutation_free (perm);
1421
1422   tab_submit (t);
1423 }
1424
1425
1426 static void
1427 show_explained_variance (const struct cmd_factor * factor, struct idata *idata,
1428                          const gsl_vector *initial_eigenvalues,
1429                          const gsl_vector *extracted_eigenvalues,
1430                          const gsl_vector *rotated_loadings)
1431 {
1432   size_t i;
1433   int c = 0;
1434   const int heading_columns = 1;
1435   const int heading_rows = 2;
1436   const int nr = heading_rows + factor->n_vars;
1437
1438   struct tab_table *t ;
1439
1440   double i_total = 0.0;
1441   double i_cum = 0.0;
1442
1443   double e_total = 0.0;
1444   double e_cum = 0.0;
1445
1446   double r_cum = 0.0;
1447
1448   int nc = heading_columns;
1449
1450   if (factor->print & PRINT_EXTRACTION)
1451     nc += 3;
1452
1453   if (factor->print & PRINT_INITIAL)
1454     nc += 3;
1455
1456   if (factor->print & PRINT_ROTATION)
1457     nc += 3;
1458
1459   /* No point having a table with only headings */
1460   if ( nc <= heading_columns)
1461     return;
1462
1463   t = tab_create (nc, nr);
1464
1465   tab_title (t, _("Total Variance Explained"));
1466
1467   tab_headers (t, heading_columns, 0, heading_rows, 0);
1468
1469   /* Outline the box */
1470   tab_box (t,
1471            TAL_2, TAL_2,
1472            -1, -1,
1473            0, 0,
1474            nc - 1, nr - 1);
1475
1476   /* Vertical lines */
1477   tab_box (t,
1478            -1, -1,
1479            -1, TAL_1,
1480            heading_columns, 0,
1481            nc - 1, nr - 1);
1482
1483   tab_hline (t, TAL_1, 0, nc - 1, heading_rows);
1484   tab_hline (t, TAL_1, 1, nc - 1, 1);
1485
1486   tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
1487
1488
1489   if ( factor->extraction == EXTRACTION_PC)
1490     tab_text (t, 0, 1, TAB_LEFT | TAT_TITLE, _("Component"));
1491   else
1492     tab_text (t, 0, 1, TAB_LEFT | TAT_TITLE, _("Factor"));
1493
1494   c = 1;
1495   if (factor->print & PRINT_INITIAL)
1496     {
1497       tab_joint_text (t, c, 0, c + 2, 0, TAB_CENTER | TAT_TITLE, _("Initial Eigenvalues"));
1498       c += 3;
1499     }
1500
1501   if (factor->print & PRINT_EXTRACTION)
1502     {
1503       tab_joint_text (t, c, 0, c + 2, 0, TAB_CENTER | TAT_TITLE, _("Extraction Sums of Squared Loadings"));
1504       c += 3;
1505     }
1506
1507   if (factor->print & PRINT_ROTATION)
1508     {
1509       tab_joint_text (t, c, 0, c + 2, 0, TAB_CENTER | TAT_TITLE, _("Rotation Sums of Squared Loadings"));
1510       c += 3;
1511     }
1512
1513   for (i = 0; i < (nc - heading_columns) / 3 ; ++i)
1514     {
1515       tab_text (t, i * 3 + 1, 1, TAB_CENTER | TAT_TITLE, _("Total"));
1516       /* xgettext:no-c-format */
1517       tab_text (t, i * 3 + 2, 1, TAB_CENTER | TAT_TITLE, _("% of Variance"));
1518       tab_text (t, i * 3 + 3, 1, TAB_CENTER | TAT_TITLE, _("Cumulative %"));
1519
1520       tab_vline (t, TAL_2, heading_columns + i * 3, 0, nr - 1);
1521     }
1522
1523   for (i = 0 ; i < initial_eigenvalues->size; ++i)
1524     i_total += gsl_vector_get (initial_eigenvalues, i);
1525
1526   if ( factor->extraction == EXTRACTION_PAF)
1527     {
1528       e_total = factor->n_vars;
1529     }
1530   else
1531     {
1532       e_total = i_total;
1533     }
1534
1535   for (i = 0 ; i < factor->n_vars; ++i)
1536     {
1537       const double i_lambda = gsl_vector_get (initial_eigenvalues, i);
1538       double i_percent = 100.0 * i_lambda / i_total ;
1539
1540       const double e_lambda = gsl_vector_get (extracted_eigenvalues, i);
1541       double e_percent = 100.0 * e_lambda / e_total ;
1542
1543       c = 0;
1544
1545       tab_text_format (t, c++, i + heading_rows, TAB_LEFT | TAT_TITLE, _("%zu"), i + 1);
1546
1547       i_cum += i_percent;
1548       e_cum += e_percent;
1549
1550       /* Initial Eigenvalues */
1551       if (factor->print & PRINT_INITIAL)
1552       {
1553         tab_double (t, c++, i + heading_rows, 0, i_lambda, NULL);
1554         tab_double (t, c++, i + heading_rows, 0, i_percent, NULL);
1555         tab_double (t, c++, i + heading_rows, 0, i_cum, NULL);
1556       }
1557
1558
1559       if (factor->print & PRINT_EXTRACTION)
1560         {
1561           if (i < idata->n_extractions)
1562             {
1563               /* Sums of squared loadings */
1564               tab_double (t, c++, i + heading_rows, 0, e_lambda, NULL);
1565               tab_double (t, c++, i + heading_rows, 0, e_percent, NULL);
1566               tab_double (t, c++, i + heading_rows, 0, e_cum, NULL);
1567             }
1568         }
1569
1570       if (rotated_loadings != NULL)
1571         {
1572           const double r_lambda = gsl_vector_get (rotated_loadings, i);
1573           double r_percent = 100.0 * r_lambda / e_total ;
1574
1575           if (factor->print & PRINT_ROTATION)
1576             {
1577               if (i < idata->n_extractions)
1578                 {
1579                   r_cum += r_percent;
1580                   tab_double (t, c++, i + heading_rows, 0, r_lambda, NULL);
1581                   tab_double (t, c++, i + heading_rows, 0, r_percent, NULL);
1582                   tab_double (t, c++, i + heading_rows, 0, r_cum, NULL);
1583                 }
1584             }
1585         }
1586     }
1587
1588   tab_submit (t);
1589 }
1590
1591
1592 static void
1593 show_correlation_matrix (const struct cmd_factor *factor, const struct idata *idata)
1594 {
1595   struct tab_table *t ;
1596   size_t i, j;
1597   int y_pos_corr = -1;
1598   int y_pos_sig = -1;
1599   int suffix_rows = 0;
1600
1601   const int heading_rows = 1;
1602   const int heading_columns = 2;
1603
1604   int nc = heading_columns ;
1605   int nr = heading_rows ;
1606   int n_data_sets = 0;
1607
1608   if (factor->print & PRINT_CORRELATION)
1609     {
1610       y_pos_corr = n_data_sets;
1611       n_data_sets++;
1612       nc = heading_columns + factor->n_vars;
1613     }
1614
1615   if (factor->print & PRINT_SIG)
1616     {
1617       y_pos_sig = n_data_sets;
1618       n_data_sets++;
1619       nc = heading_columns + factor->n_vars;
1620     }
1621
1622   nr += n_data_sets * factor->n_vars;
1623
1624   if (factor->print & PRINT_DETERMINANT)
1625     suffix_rows = 1;
1626
1627   /* If the table would contain only headings, don't bother rendering it */
1628   if (nr <= heading_rows && suffix_rows == 0)
1629     return;
1630
1631   t = tab_create (nc, nr + suffix_rows);
1632
1633   tab_title (t, _("Correlation Matrix"));
1634
1635   tab_hline (t, TAL_1, 0, nc - 1, heading_rows);
1636
1637   if (nr > heading_rows)
1638     {
1639       tab_headers (t, heading_columns, 0, heading_rows, 0);
1640
1641       tab_vline (t, TAL_2, 2, 0, nr - 1);
1642
1643       /* Outline the box */
1644       tab_box (t,
1645                TAL_2, TAL_2,
1646                -1, -1,
1647                0, 0,
1648                nc - 1, nr - 1);
1649
1650       /* Vertical lines */
1651       tab_box (t,
1652                -1, -1,
1653                -1, TAL_1,
1654                heading_columns, 0,
1655                nc - 1, nr - 1);
1656
1657
1658       for (i = 0; i < factor->n_vars; ++i)
1659         tab_text (t, heading_columns + i, 0, TAT_TITLE, var_to_string (factor->vars[i]));
1660
1661
1662       for (i = 0 ; i < n_data_sets; ++i)
1663         {
1664           int y = heading_rows + i * factor->n_vars;
1665           size_t v;
1666           for (v = 0; v < factor->n_vars; ++v)
1667             tab_text (t, 1, y + v, TAT_TITLE, var_to_string (factor->vars[v]));
1668
1669           tab_hline (t, TAL_1, 0, nc - 1, y);
1670         }
1671
1672       if (factor->print & PRINT_CORRELATION)
1673         {
1674           const double y = heading_rows + y_pos_corr;
1675           tab_text (t, 0, y, TAT_TITLE, _("Correlations"));
1676
1677           for (i = 0; i < factor->n_vars; ++i)
1678             {
1679               for (j = 0; j < factor->n_vars; ++j)
1680                 tab_double (t, heading_columns + i,  y + j, 0, gsl_matrix_get (idata->corr, i, j), NULL);
1681             }
1682         }
1683
1684       if (factor->print & PRINT_SIG)
1685         {
1686           const double y = heading_rows + y_pos_sig * factor->n_vars;
1687           tab_text (t, 0, y, TAT_TITLE, _("Sig. (1-tailed)"));
1688
1689           for (i = 0; i < factor->n_vars; ++i)
1690             {
1691               for (j = 0; j < factor->n_vars; ++j)
1692                 {
1693                   double rho = gsl_matrix_get (idata->corr, i, j);
1694                   double w = gsl_matrix_get (idata->n, i, j);
1695
1696                   if (i == j)
1697                     continue;
1698
1699                   tab_double (t, heading_columns + i,  y + j, 0, significance_of_correlation (rho, w), NULL);
1700                 }
1701             }
1702         }
1703     }
1704
1705   if (factor->print & PRINT_DETERMINANT)
1706     {
1707       tab_text (t, 0, nr, TAB_LEFT | TAT_TITLE, _("Determinant"));
1708
1709       tab_double (t, 1, nr, 0, idata->detR, NULL);
1710     }
1711
1712   tab_submit (t);
1713 }
1714
1715
1716
1717 static void
1718 do_factor (const struct cmd_factor *factor, struct casereader *r)
1719 {
1720   struct ccase *c;
1721   const gsl_matrix *var_matrix;
1722   const gsl_matrix *mean_matrix;
1723
1724   const gsl_matrix *analysis_matrix;
1725   struct idata *idata = idata_alloc (factor->n_vars);
1726
1727   struct covariance *cov = covariance_1pass_create (factor->n_vars, factor->vars,
1728                                               factor->wv, factor->exclude);
1729
1730   for ( ; (c = casereader_read (r) ); case_unref (c))
1731     {
1732       covariance_accumulate (cov, c);
1733     }
1734
1735   idata->cov = covariance_calculate (cov);
1736
1737   if (idata->cov == NULL)
1738     {
1739       msg (MW, _("The dataset contains no complete observations. No analysis will be performed."));
1740       covariance_destroy (cov);
1741       goto finish;
1742     }
1743
1744   var_matrix = covariance_moments (cov, MOMENT_VARIANCE);
1745   mean_matrix = covariance_moments (cov, MOMENT_MEAN);
1746   idata->n = covariance_moments (cov, MOMENT_NONE);
1747   
1748
1749   if ( factor->method == METHOD_CORR)
1750     {
1751       idata->corr = correlation_from_covariance (idata->cov, var_matrix);
1752       
1753       analysis_matrix = idata->corr;
1754     }
1755   else
1756     analysis_matrix = idata->cov;
1757
1758
1759   if (factor->print & PRINT_DETERMINANT
1760       || factor->print & PRINT_KMO)
1761     {
1762       int sign = 0;
1763
1764       const int size = idata->corr->size1;
1765       gsl_permutation *p = gsl_permutation_calloc (size);
1766       gsl_matrix *tmp = gsl_matrix_calloc (size, size);
1767       gsl_matrix_memcpy (tmp, idata->corr);
1768
1769       gsl_linalg_LU_decomp (tmp, p, &sign);
1770       idata->detR = gsl_linalg_LU_det (tmp, sign);
1771       gsl_permutation_free (p);
1772       gsl_matrix_free (tmp);
1773     }
1774
1775   if ( factor->print & PRINT_UNIVARIATE)
1776     {
1777       const struct fmt_spec *wfmt = factor->wv ? var_get_print_format (factor->wv) : & F_8_0;
1778       const int nc = 4;
1779       int i;
1780
1781       const int heading_columns = 1;
1782       const int heading_rows = 1;
1783
1784       const int nr = heading_rows + factor->n_vars;
1785
1786       struct tab_table *t = tab_create (nc, nr);
1787       tab_title (t, _("Descriptive Statistics"));
1788
1789       tab_headers (t, heading_columns, 0, heading_rows, 0);
1790
1791       /* Outline the box */
1792       tab_box (t,
1793                TAL_2, TAL_2,
1794                -1, -1,
1795                0, 0,
1796                nc - 1, nr - 1);
1797
1798       /* Vertical lines */
1799       tab_box (t,
1800                -1, -1,
1801                -1, TAL_1,
1802                heading_columns, 0,
1803                nc - 1, nr - 1);
1804
1805       tab_hline (t, TAL_1, 0, nc - 1, heading_rows);
1806       tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
1807
1808       tab_text (t, 1, 0, TAB_CENTER | TAT_TITLE, _("Mean"));
1809       tab_text (t, 2, 0, TAB_CENTER | TAT_TITLE, _("Std. Deviation"));
1810       tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("Analysis N"));
1811
1812       for (i = 0 ; i < factor->n_vars; ++i)
1813         {
1814           const struct variable *v = factor->vars[i];
1815           tab_text (t, 0, i + heading_rows, TAB_LEFT | TAT_TITLE, var_to_string (v));
1816
1817           tab_double (t, 1, i + heading_rows, 0, gsl_matrix_get (mean_matrix, i, i), NULL);
1818           tab_double (t, 2, i + heading_rows, 0, sqrt (gsl_matrix_get (var_matrix, i, i)), NULL);
1819           tab_double (t, 3, i + heading_rows, 0, gsl_matrix_get (idata->n, i, i), wfmt);
1820         }
1821
1822       tab_submit (t);
1823     }
1824
1825   if (factor->print & PRINT_KMO)
1826     {
1827       int i;
1828       double sum_ssq_r = 0;
1829       double sum_ssq_a = 0;
1830
1831       double df = factor->n_vars * ( factor->n_vars - 1) / 2;
1832
1833       double w = 0;
1834
1835
1836       double xsq;
1837
1838       const int heading_columns = 2;
1839       const int heading_rows = 0;
1840
1841       const int nr = heading_rows + 4;
1842       const int nc = heading_columns + 1;
1843
1844       gsl_matrix *a, *x;
1845
1846       struct tab_table *t = tab_create (nc, nr);
1847       tab_title (t, _("KMO and Bartlett's Test"));
1848
1849       x  = clone_matrix (idata->corr);
1850       gsl_linalg_cholesky_decomp (x);
1851       gsl_linalg_cholesky_invert (x);
1852
1853       a = anti_image (x);
1854
1855       for (i = 0; i < x->size1; ++i)
1856         {
1857           sum_ssq_r += ssq_od_n (x, i);
1858           sum_ssq_a += ssq_od_n (a, i);
1859         }
1860
1861       gsl_matrix_free (a);
1862       gsl_matrix_free (x);
1863
1864       tab_headers (t, heading_columns, 0, heading_rows, 0);
1865
1866       /* Outline the box */
1867       tab_box (t,
1868                TAL_2, TAL_2,
1869                -1, -1,
1870                0, 0,
1871                nc - 1, nr - 1);
1872
1873       tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
1874
1875       tab_text (t, 0, 0, TAT_TITLE | TAB_LEFT, _("Kaiser-Meyer-Olkin Measure of Sampling Adequacy"));
1876
1877       tab_double (t, 2, 0, 0, sum_ssq_r /  (sum_ssq_r + sum_ssq_a), NULL);
1878
1879       tab_text (t, 0, 1, TAT_TITLE | TAB_LEFT, _("Bartlett's Test of Sphericity"));
1880
1881       tab_text (t, 1, 1, TAT_TITLE, _("Approx. Chi-Square"));
1882       tab_text (t, 1, 2, TAT_TITLE, _("df"));
1883       tab_text (t, 1, 3, TAT_TITLE, _("Sig."));
1884
1885
1886       /* The literature doesn't say what to do for the value of W when 
1887          missing values are involved.  The best thing I can think of
1888          is to take the mean average. */
1889       w = 0;
1890       for (i = 0; i < idata->n->size1; ++i)
1891         w += gsl_matrix_get (idata->n, i, i);
1892       w /= idata->n->size1;
1893
1894       xsq = w - 1 - (2 * factor->n_vars + 5) / 6.0;
1895       xsq *= -log (idata->detR);
1896
1897       tab_double (t, 2, 1, 0, xsq, NULL);
1898       tab_double (t, 2, 2, 0, df, &F_8_0);
1899       tab_double (t, 2, 3, 0, gsl_cdf_chisq_Q (xsq, df), NULL);
1900       
1901
1902       tab_submit (t);
1903     }
1904
1905   show_correlation_matrix (factor, idata);
1906   covariance_destroy (cov);
1907
1908   {
1909     gsl_matrix *am = matrix_dup (analysis_matrix);
1910     gsl_eigen_symmv_workspace *workspace = gsl_eigen_symmv_alloc (factor->n_vars);
1911     
1912     gsl_eigen_symmv (am, idata->eval, idata->evec, workspace);
1913
1914     gsl_eigen_symmv_free (workspace);
1915     gsl_matrix_free (am);
1916   }
1917
1918   gsl_eigen_symmv_sort (idata->eval, idata->evec, GSL_EIGEN_SORT_ABS_DESC);
1919
1920   idata->n_extractions = n_extracted_factors (factor, idata);
1921
1922   if (idata->n_extractions == 0)
1923     {
1924       msg (MW, _("The FACTOR criteria result in zero factors extracted. Therefore no analysis will be performed."));
1925       goto finish;
1926     }
1927
1928   if (idata->n_extractions > factor->n_vars)
1929     {
1930       msg (MW, _("The FACTOR criteria result in more factors than variables, which is not meaningful. No analysis will be performed."));
1931       goto finish;
1932     }
1933     
1934   {
1935     gsl_matrix *rotated_factors = NULL;
1936     gsl_vector *rotated_loadings = NULL;
1937
1938     const gsl_vector *extracted_eigenvalues = NULL;
1939     gsl_vector *initial_communalities = gsl_vector_alloc (factor->n_vars);
1940     gsl_vector *extracted_communalities = gsl_vector_alloc (factor->n_vars);
1941     size_t i;
1942     struct factor_matrix_workspace *fmw = factor_matrix_workspace_alloc (idata->msr->size, idata->n_extractions);
1943     gsl_matrix *factor_matrix = gsl_matrix_calloc (factor->n_vars, fmw->n_factors);
1944
1945     if ( factor->extraction == EXTRACTION_PAF)
1946       {
1947         gsl_vector *diff = gsl_vector_alloc (idata->msr->size);
1948         struct smr_workspace *ws = ws_create (analysis_matrix);
1949
1950         for (i = 0 ; i < factor->n_vars ; ++i)
1951           {
1952             double r2 = squared_multiple_correlation (analysis_matrix, i, ws);
1953
1954             gsl_vector_set (idata->msr, i, r2);
1955           }
1956         ws_destroy (ws);
1957
1958         gsl_vector_memcpy (initial_communalities, idata->msr);
1959
1960         for (i = 0; i < factor->iterations; ++i)
1961           {
1962             double min, max;
1963             gsl_vector_memcpy (diff, idata->msr);
1964
1965             iterate_factor_matrix (analysis_matrix, idata->msr, factor_matrix, fmw);
1966       
1967             gsl_vector_sub (diff, idata->msr);
1968
1969             gsl_vector_minmax (diff, &min, &max);
1970       
1971             if ( fabs (min) < factor->econverge && fabs (max) < factor->econverge)
1972               break;
1973           }
1974         gsl_vector_free (diff);
1975
1976
1977
1978         gsl_vector_memcpy (extracted_communalities, idata->msr);
1979         extracted_eigenvalues = fmw->eval;
1980       }
1981     else if (factor->extraction == EXTRACTION_PC)
1982       {
1983         for (i = 0; i < factor->n_vars; ++i)
1984           gsl_vector_set (initial_communalities, i, communality (idata, i, factor->n_vars));
1985
1986         gsl_vector_memcpy (extracted_communalities, initial_communalities);
1987
1988         iterate_factor_matrix (analysis_matrix, extracted_communalities, factor_matrix, fmw);
1989
1990
1991         extracted_eigenvalues = idata->eval;
1992       }
1993
1994
1995     show_communalities (factor, initial_communalities, extracted_communalities);
1996
1997
1998     if ( factor->rotation != ROT_NONE)
1999       {
2000         rotated_factors = gsl_matrix_calloc (factor_matrix->size1, factor_matrix->size2);
2001         rotated_loadings = gsl_vector_calloc (factor_matrix->size2);
2002
2003         rotate (factor, factor_matrix, extracted_communalities, rotated_factors, rotated_loadings);
2004       }
2005
2006     show_explained_variance (factor, idata, idata->eval, extracted_eigenvalues, rotated_loadings);
2007
2008     factor_matrix_workspace_free (fmw);
2009
2010     show_scree (factor, idata);
2011
2012     show_factor_matrix (factor, idata,
2013                         factor->extraction == EXTRACTION_PC ? _("Component Matrix") : _("Factor Matrix"),
2014                         factor_matrix);
2015
2016     if ( factor->rotation != ROT_NONE)
2017       {
2018         show_factor_matrix (factor, idata,
2019                             factor->extraction == EXTRACTION_PC ? _("Rotated Component Matrix") : _("Rotated Factor Matrix"),
2020                             rotated_factors);
2021
2022         gsl_matrix_free (rotated_factors);
2023       }
2024
2025
2026
2027     gsl_matrix_free (factor_matrix);
2028     gsl_vector_free (rotated_loadings);
2029     gsl_vector_free (initial_communalities);
2030     gsl_vector_free (extracted_communalities);
2031   }
2032
2033  finish:
2034
2035   idata_free (idata);
2036
2037   casereader_destroy (r);
2038 }
2039
2040
2041