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