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