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