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