FACTOR: Improve error messages and coding style.
[pspp] / src / language / stats / factor.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2009, 2010, 2011, 2012, 2014, 2015,
3    2016, 2017 Free Software Foundation, Inc.
4
5    This program is free software: you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation, either version 3 of the License, or
8    (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
17
18 #include <config.h>
19
20 #include <gsl/gsl_vector.h>
21 #include <gsl/gsl_linalg.h>
22 #include <gsl/gsl_matrix.h>
23 #include <gsl/gsl_eigen.h>
24 #include <gsl/gsl_blas.h>
25 #include <gsl/gsl_sort_vector.h>
26 #include <gsl/gsl_cdf.h>
27
28 #include "data/any-reader.h"
29 #include "data/casegrouper.h"
30 #include "data/casereader.h"
31 #include "data/casewriter.h"
32 #include "data/dataset.h"
33 #include "data/dictionary.h"
34 #include "data/format.h"
35 #include "data/subcase.h"
36 #include "language/command.h"
37 #include "language/lexer/lexer.h"
38 #include "language/lexer/value-parser.h"
39 #include "language/lexer/variable-parser.h"
40 #include "language/data-io/file-handle.h"
41 #include "language/data-io/matrix-reader.h"
42 #include "libpspp/cast.h"
43 #include "libpspp/message.h"
44 #include "libpspp/misc.h"
45 #include "math/correlation.h"
46 #include "math/covariance.h"
47 #include "math/moments.h"
48 #include "output/charts/scree.h"
49 #include "output/pivot-table.h"
50
51
52 #include "gettext.h"
53 #define _(msgid) gettext (msgid)
54 #define N_(msgid) msgid
55
56 enum method
57   {
58     METHOD_CORR,
59     METHOD_COV
60   };
61
62 enum missing_type
63   {
64     MISS_LISTWISE,
65     MISS_PAIRWISE,
66     MISS_MEANSUB,
67   };
68
69 enum extraction_method
70   {
71     EXTRACTION_PC,
72     EXTRACTION_PAF,
73   };
74
75 enum plot_opts
76   {
77     PLOT_SCREE = 0x0001,
78     PLOT_ROTATION = 0x0002
79   };
80
81 enum print_opts
82   {
83     PRINT_UNIVARIATE  = 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_id (lexer, "IN"))
1026         goto error;
1027       if (!lex_force_match (lexer, T_LPAREN))
1028         goto error;
1029       if (!lex_match_id (lexer, "CORR") && !lex_match_id (lexer, "COV"))
1030         {
1031           lex_error (lexer, _("Matrix input for %s must be either COV or CORR"),
1032                      "FACTOR");
1033           goto error;
1034         }
1035       if (!lex_force_match (lexer, T_EQUALS))
1036         goto error;
1037       vars_start = lex_ofs (lexer);
1038       if (lex_match (lexer, T_ASTERISK))
1039         {
1040           dict = dataset_dict (ds);
1041           matrix_reader = casereader_clone (dataset_source (ds));
1042         }
1043       else
1044         {
1045           struct file_handle *fh = fh_parse (lexer, FH_REF_FILE, NULL);
1046           if (fh == NULL)
1047             goto error;
1048
1049           matrix_reader = any_reader_open_and_decode (fh, NULL, &dict, NULL);
1050
1051           if (!(matrix_reader && dict))
1052             goto error;
1053         }
1054       vars_end = lex_ofs (lexer) - 1;
1055
1056       if (!lex_force_match (lexer, T_RPAREN))
1057         goto error;
1058
1059       mr = matrix_reader_create (dict, matrix_reader);
1060       factor.vars = xmemdup (mr->cvars, mr->n_cvars * sizeof *mr->cvars);
1061       factor.n_vars = mr->n_cvars;
1062     }
1063   else
1064     goto error;
1065
1066   while (lex_token (lexer) != T_ENDCMD)
1067     {
1068       lex_match (lexer, T_SLASH);
1069
1070       if (lex_match_id (lexer, "ANALYSIS"))
1071         {
1072           struct const_var_set *vs;
1073           const struct variable **vars;
1074           size_t n_vars;
1075
1076           lex_match (lexer, T_EQUALS);
1077
1078           vars_start = lex_ofs (lexer);
1079           vs = const_var_set_create_from_array (factor.vars, factor.n_vars);
1080           vars_end = lex_ofs (lexer) - 1;
1081           bool ok = parse_const_var_set_vars (lexer, vs, &vars, &n_vars,
1082                                               PV_NO_DUPLICATE | PV_NUMERIC);
1083           const_var_set_destroy (vs);
1084
1085           if (!ok)
1086             goto error;
1087
1088           free (factor.vars);
1089           factor.vars = vars;
1090           factor.n_vars = n_vars;
1091
1092           if (mr)
1093             {
1094               free (mr->cvars);
1095               mr->cvars = xmemdup (vars, n_vars * sizeof *vars);
1096               mr->n_cvars = n_vars;
1097             }
1098         }
1099       else if (lex_match_id (lexer, "PLOT"))
1100         {
1101           lex_match (lexer, T_EQUALS);
1102           while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
1103             {
1104               if (lex_match_id (lexer, "EIGEN"))
1105                 {
1106                   factor.plot |= PLOT_SCREE;
1107                 }
1108 #if FACTOR_FULLY_IMPLEMENTED
1109               else if (lex_match_id (lexer, "ROTATION"))
1110                 {
1111                 }
1112 #endif
1113               else
1114                 {
1115                   lex_error (lexer, NULL);
1116                   goto error;
1117                 }
1118             }
1119         }
1120       else if (lex_match_id (lexer, "METHOD"))
1121         {
1122           lex_match (lexer, T_EQUALS);
1123           while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
1124             {
1125               if (lex_match_id (lexer, "COVARIANCE"))
1126                 factor.method = METHOD_COV;
1127               else if (lex_match_id (lexer, "CORRELATION"))
1128                 factor.method = METHOD_CORR;
1129               else
1130                 {
1131                   lex_error_expecting (lexer, "COVARIANCE", "CORRELATION");
1132                   goto error;
1133                 }
1134             }
1135         }
1136       else if (lex_match_id (lexer, "ROTATION"))
1137         {
1138           lex_match (lexer, T_EQUALS);
1139           while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
1140             {
1141               /* VARIMAX and DEFAULT are defaults */
1142               if (lex_match_id (lexer, "VARIMAX") || lex_match_id (lexer, "DEFAULT"))
1143                 factor.rotation = ROT_VARIMAX;
1144               else if (lex_match_id (lexer, "EQUAMAX"))
1145                 factor.rotation = ROT_EQUAMAX;
1146               else if (lex_match_id (lexer, "QUARTIMAX"))
1147                 factor.rotation = ROT_QUARTIMAX;
1148               else if (lex_match_id (lexer, "PROMAX"))
1149                 {
1150                   factor.promax_power = 5;
1151                   if (lex_match (lexer, T_LPAREN)
1152                       && lex_force_int (lexer))
1153                     {
1154                       factor.promax_power = lex_integer (lexer);
1155                       lex_get (lexer);
1156                       if (!lex_force_match (lexer, T_RPAREN))
1157                         goto error;
1158                     }
1159                   factor.rotation = ROT_PROMAX;
1160                 }
1161               else if (lex_match_id (lexer, "NOROTATE"))
1162                 factor.rotation = ROT_NONE;
1163               else
1164                 {
1165                   lex_error_expecting (lexer, "DEFAULT", "VARIMAX", "EQUAMAX",
1166                                        "QUARTIMAX", "PROMAX", "NOROTATE");
1167                   goto error;
1168                 }
1169             }
1170           factor.rotation_iterations = n_iterations;
1171         }
1172       else if (lex_match_id (lexer, "CRITERIA"))
1173         {
1174           lex_match (lexer, T_EQUALS);
1175           while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
1176             {
1177               if (lex_match_id (lexer, "FACTORS"))
1178                 {
1179                   if (lex_force_match (lexer, T_LPAREN)
1180                       && lex_force_int (lexer))
1181                     {
1182                       factor.n_factors = lex_integer (lexer);
1183                       lex_get (lexer);
1184                       if (!lex_force_match (lexer, T_RPAREN))
1185                         goto error;
1186                     }
1187                 }
1188               else if (lex_match_id (lexer, "MINEIGEN"))
1189                 {
1190                   if (lex_force_match (lexer, T_LPAREN)
1191                       && lex_force_num (lexer))
1192                     {
1193                       factor.min_eigen = lex_number (lexer);
1194                       lex_get (lexer);
1195                       if (!lex_force_match (lexer, T_RPAREN))
1196                         goto error;
1197                     }
1198                 }
1199               else if (lex_match_id (lexer, "ECONVERGE"))
1200                 {
1201                   if (lex_force_match (lexer, T_LPAREN)
1202                       && lex_force_num (lexer))
1203                     {
1204                       factor.econverge = lex_number (lexer);
1205                       lex_get (lexer);
1206                       if (!lex_force_match (lexer, T_RPAREN))
1207                         goto error;
1208                     }
1209                 }
1210               else if (lex_match_id (lexer, "RCONVERGE"))
1211                 {
1212                   if (lex_force_match (lexer, T_LPAREN)
1213                       && lex_force_num (lexer))
1214                     {
1215                       factor.rconverge = lex_number (lexer);
1216                       lex_get (lexer);
1217                       if (!lex_force_match (lexer, T_RPAREN))
1218                         goto error;
1219                     }
1220                 }
1221               else if (lex_match_id (lexer, "ITERATE"))
1222                 {
1223                   if (lex_force_match (lexer, T_LPAREN)
1224                       && lex_force_int_range (lexer, "ITERATE", 0, INT_MAX))
1225                     {
1226                       n_iterations = lex_integer (lexer);
1227                       lex_get (lexer);
1228                       if (!lex_force_match (lexer, T_RPAREN))
1229                         goto error;
1230                     }
1231                 }
1232               else if (lex_match_id (lexer, "DEFAULT"))
1233                 {
1234                   factor.n_factors = 0;
1235                   factor.min_eigen = 1;
1236                   n_iterations = 25;
1237                 }
1238               else
1239                 {
1240                   lex_error_expecting (lexer, "FACTORS", "MINEIGEN",
1241                                        "ECONVERGE", "RCONVERGE", "ITERATE",
1242                                        "DEFAULT");
1243                   goto error;
1244                 }
1245             }
1246         }
1247       else if (lex_match_id (lexer, "EXTRACTION"))
1248         {
1249           lex_match (lexer, T_EQUALS);
1250           while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
1251             {
1252               if (lex_match_id (lexer, "PAF"))
1253                 factor.extraction = EXTRACTION_PAF;
1254               else if (lex_match_id (lexer, "PC"))
1255                 factor.extraction = EXTRACTION_PC;
1256               else if (lex_match_id (lexer, "PA1"))
1257                 factor.extraction = EXTRACTION_PC;
1258               else if (lex_match_id (lexer, "DEFAULT"))
1259                 factor.extraction = EXTRACTION_PC;
1260               else
1261                 {
1262                   lex_error_expecting (lexer, "PAF", "PC", "PA1", "DEFAULT");
1263                   goto error;
1264                 }
1265             }
1266           factor.extraction_iterations = n_iterations;
1267         }
1268       else if (lex_match_id (lexer, "FORMAT"))
1269         {
1270           lex_match (lexer, T_EQUALS);
1271           while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
1272             {
1273               if (lex_match_id (lexer, "SORT"))
1274                 factor.sort = true;
1275               else if (lex_match_id (lexer, "BLANK"))
1276                 {
1277                   if (lex_force_match (lexer, T_LPAREN)
1278                       && lex_force_num (lexer))
1279                     {
1280                       factor.blank = lex_number (lexer);
1281                       lex_get (lexer);
1282                       if (!lex_force_match (lexer, T_RPAREN))
1283                         goto error;
1284                     }
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 (lexer, NULL);
1381           goto error;
1382         }
1383     }
1384
1385   if (factor.rotation == ROT_NONE)
1386     factor.print &= ~PRINT_ROTATION;
1387
1388   if (factor.n_vars < 2)
1389     lex_ofs_msg (lexer, SW, vars_start, vars_end,
1390                  _("Factor analysis on a single variable is not useful."));
1391
1392   if (factor.n_vars < 1)
1393     {
1394       lex_ofs_error (lexer, vars_start, vars_end,
1395                      _("Factor analysis without variables is not possible."));
1396       goto error;
1397     }
1398
1399   if (matrix_reader)
1400     {
1401       struct idata *id = idata_alloc (factor.n_vars);
1402
1403       while (matrix_reader_next (&id->mm, mr, NULL))
1404         {
1405           do_factor_by_matrix (&factor, id);
1406
1407           gsl_matrix_free (id->ai_cov);
1408           id->ai_cov = NULL;
1409           gsl_matrix_free (id->ai_cor);
1410           id->ai_cor = NULL;
1411
1412           matrix_material_uninit (&id->mm);
1413         }
1414
1415       idata_free (id);
1416     }
1417   else
1418     if (!run_factor (ds, &factor))
1419       goto error;
1420
1421   matrix_reader_destroy (mr);
1422   free (factor.vars);
1423   return CMD_SUCCESS;
1424
1425 error:
1426   matrix_reader_destroy (mr);
1427   free (factor.vars);
1428   return CMD_FAILURE;
1429 }
1430
1431 static void do_factor (const struct cmd_factor *factor, struct casereader *group);
1432
1433
1434 static bool
1435 run_factor (struct dataset *ds, const struct cmd_factor *factor)
1436 {
1437   struct dictionary *dict = dataset_dict (ds);
1438   bool ok;
1439   struct casereader *group;
1440
1441   struct casegrouper *grouper = casegrouper_create_splits (proc_open (ds), dict);
1442
1443   while (casegrouper_get_next_group (grouper, &group))
1444     {
1445       if (factor->missing_type == MISS_LISTWISE)
1446         group  = casereader_create_filter_missing (group, factor->vars, factor->n_vars,
1447                                                    factor->exclude,
1448                                                    NULL,  NULL);
1449       do_factor (factor, group);
1450     }
1451
1452   ok = casegrouper_destroy (grouper);
1453   ok = proc_commit (ds) && ok;
1454
1455   return ok;
1456 }
1457
1458
1459 /* Return the communality of variable N, calculated to N_FACTORS */
1460 static double
1461 the_communality (const gsl_matrix *evec, const gsl_vector *eval, int n, int n_factors)
1462 {
1463   assert (n >= 0);
1464   assert (n < eval->size);
1465   assert (n < evec->size1);
1466   assert (n_factors <= eval->size);
1467
1468   double comm = 0;
1469   for (size_t i = 0; i < n_factors; ++i)
1470     {
1471       double evali = fabs (gsl_vector_get (eval, i));
1472
1473       double eveci = gsl_matrix_get (evec, n, i);
1474
1475       comm += pow2 (eveci) * evali;
1476     }
1477
1478   return comm;
1479 }
1480
1481 /* Return the communality of variable N, calculated to N_FACTORS */
1482 static double
1483 communality (const struct idata *idata, int n, int n_factors)
1484 {
1485   return the_communality (idata->evec, idata->eval, n, n_factors);
1486 }
1487
1488
1489 static void
1490 show_scree (const struct cmd_factor *f, const struct idata *idata)
1491 {
1492   struct scree *s;
1493   const char *label;
1494
1495   if (!(f->plot & PLOT_SCREE))
1496     return;
1497
1498
1499   label = f->extraction == EXTRACTION_PC ? _("Component Number") : _("Factor Number");
1500
1501   s = scree_create (idata->eval, label);
1502
1503   scree_submit (s);
1504 }
1505
1506 static void
1507 show_communalities (const struct cmd_factor * factor,
1508                     const gsl_vector *initial, const gsl_vector *extracted)
1509 {
1510   if (!(factor->print & (PRINT_INITIAL | PRINT_EXTRACTION)))
1511     return;
1512
1513   struct pivot_table *table = pivot_table_create (N_("Communalities"));
1514
1515   struct pivot_dimension *communalities = pivot_dimension_create (
1516     table, PIVOT_AXIS_COLUMN, N_("Communalities"));
1517   if (factor->print & PRINT_INITIAL)
1518     pivot_category_create_leaves (communalities->root, N_("Initial"));
1519   if (factor->print & PRINT_EXTRACTION)
1520     pivot_category_create_leaves (communalities->root, N_("Extraction"));
1521
1522   struct pivot_dimension *variables = pivot_dimension_create (
1523     table, PIVOT_AXIS_ROW, N_("Variables"));
1524
1525   for (size_t i = 0; i < factor->n_vars; ++i)
1526     {
1527       int row = pivot_category_create_leaf (
1528         variables->root, pivot_value_new_variable (factor->vars[i]));
1529
1530       int col = 0;
1531       if (factor->print & PRINT_INITIAL)
1532         pivot_table_put2 (table, col++, row, pivot_value_new_number (
1533                             gsl_vector_get (initial, i)));
1534       if (factor->print & PRINT_EXTRACTION)
1535         pivot_table_put2 (table, col++, row, pivot_value_new_number (
1536                             gsl_vector_get (extracted, i)));
1537     }
1538
1539   pivot_table_submit (table);
1540 }
1541
1542 static struct pivot_dimension *
1543 create_numeric_dimension (struct pivot_table *table,
1544                           enum pivot_axis_type axis_type, const char *name,
1545                           size_t n, bool show_label)
1546 {
1547   struct pivot_dimension *d = pivot_dimension_create (table, axis_type, name);
1548   d->root->show_label = show_label;
1549   for (int i = 0; i < n; ++i)
1550     pivot_category_create_leaf (d->root, pivot_value_new_integer (i + 1));
1551   return d;
1552 }
1553
1554 static void
1555 show_factor_matrix (const struct cmd_factor *factor, const struct idata *idata, const char *title, const gsl_matrix *fm)
1556 {
1557   struct pivot_table *table = pivot_table_create (title);
1558
1559   const int n_factors = idata->n_extractions;
1560   create_numeric_dimension (
1561     table, PIVOT_AXIS_COLUMN,
1562     factor->extraction == EXTRACTION_PC ? N_("Component") : N_("Factor"),
1563     n_factors, true);
1564
1565   struct pivot_dimension *variables = pivot_dimension_create (
1566     table, PIVOT_AXIS_ROW, N_("Variables"));
1567
1568   /* Initialise to the identity permutation */
1569   gsl_permutation *perm = gsl_permutation_calloc (factor->n_vars);
1570
1571   if (factor->sort)
1572     sort_matrix_indirect (fm, perm);
1573
1574   for (size_t i = 0; i < factor->n_vars; ++i)
1575     {
1576       const int matrix_row = perm->data[i];
1577
1578       int var_idx = pivot_category_create_leaf (
1579         variables->root, pivot_value_new_variable (factor->vars[matrix_row]));
1580
1581       for (size_t j = 0; j < n_factors; ++j)
1582         {
1583           double x = gsl_matrix_get (fm, matrix_row, j);
1584           if (fabs (x) < factor->blank)
1585             continue;
1586
1587           pivot_table_put2 (table, j, var_idx, pivot_value_new_number (x));
1588         }
1589     }
1590
1591   gsl_permutation_free (perm);
1592
1593   pivot_table_submit (table);
1594 }
1595
1596 static void
1597 put_variance (struct pivot_table *table, int row, int phase_idx,
1598               double lambda, double percent, double cum)
1599 {
1600   double entries[] = { lambda, percent, cum };
1601   for (size_t i = 0; i < sizeof entries / sizeof *entries; i++)
1602     pivot_table_put3 (table, i, phase_idx, row,
1603                       pivot_value_new_number (entries[i]));
1604 }
1605
1606 static void
1607 show_explained_variance (const struct cmd_factor * factor,
1608                          const struct idata *idata,
1609                          const gsl_vector *initial_eigenvalues,
1610                          const gsl_vector *extracted_eigenvalues,
1611                          const gsl_vector *rotated_loadings)
1612 {
1613   if (!(factor->print & (PRINT_INITIAL | PRINT_EXTRACTION | PRINT_ROTATION)))
1614     return;
1615
1616   struct pivot_table *table = pivot_table_create (
1617     N_("Total Variance Explained"));
1618
1619   pivot_dimension_create (table, PIVOT_AXIS_COLUMN, N_("Statistics"),
1620                           N_("Total"), PIVOT_RC_OTHER,
1621                           /* xgettext:no-c-format */
1622                           N_("% of Variance"), PIVOT_RC_PERCENT,
1623                           /* xgettext:no-c-format */
1624                           N_("Cumulative %"), PIVOT_RC_PERCENT);
1625
1626   struct pivot_dimension *phase = pivot_dimension_create (
1627     table, PIVOT_AXIS_COLUMN, N_("Phase"));
1628   if (factor->print & PRINT_INITIAL)
1629     pivot_category_create_leaves (phase->root, N_("Initial Eigenvalues"));
1630
1631   if (factor->print & PRINT_EXTRACTION)
1632     pivot_category_create_leaves (phase->root,
1633                                   N_("Extraction Sums of Squared Loadings"));
1634
1635   if (factor->print & PRINT_ROTATION)
1636     pivot_category_create_leaves (phase->root,
1637                                   N_("Rotation Sums of Squared Loadings"));
1638
1639   struct pivot_dimension *components = pivot_dimension_create (
1640     table, PIVOT_AXIS_ROW,
1641     factor->extraction == EXTRACTION_PC ? N_("Component") : N_("Factor"));
1642
1643   double i_total = 0.0;
1644   for (size_t i = 0; i < initial_eigenvalues->size; ++i)
1645     i_total += gsl_vector_get (initial_eigenvalues, i);
1646
1647   double e_total = (factor->extraction == EXTRACTION_PAF
1648                     ? factor->n_vars
1649                     : i_total);
1650
1651   double i_cum = 0.0;
1652   double e_cum = 0.0;
1653   double r_cum = 0.0;
1654   for (size_t i = 0; i < factor->n_vars; ++i)
1655     {
1656       const double i_lambda = gsl_vector_get (initial_eigenvalues, i);
1657       double i_percent = 100.0 * i_lambda / i_total;
1658       i_cum += i_percent;
1659
1660       const double e_lambda = gsl_vector_get (extracted_eigenvalues, i);
1661       double e_percent = 100.0 * e_lambda / e_total;
1662       e_cum += e_percent;
1663
1664       int row = pivot_category_create_leaf (
1665         components->root, pivot_value_new_integer (i + 1));
1666
1667       int phase_idx = 0;
1668
1669       /* Initial Eigenvalues */
1670       if (factor->print & PRINT_INITIAL)
1671         put_variance (table, row, phase_idx++, i_lambda, i_percent, i_cum);
1672
1673       if (i < idata->n_extractions)
1674         {
1675           if (factor->print & PRINT_EXTRACTION)
1676             put_variance (table, row, phase_idx++, e_lambda, e_percent, e_cum);
1677
1678           if (rotated_loadings != NULL && factor->print & PRINT_ROTATION)
1679             {
1680               double r_lambda = gsl_vector_get (rotated_loadings, i);
1681               double r_percent = 100.0 * r_lambda / e_total;
1682               if (factor->rotation == ROT_PROMAX)
1683                 r_lambda = r_percent = SYSMIS;
1684
1685               r_cum += r_percent;
1686               put_variance (table, row, phase_idx++, r_lambda, r_percent,
1687                             r_cum);
1688             }
1689         }
1690     }
1691
1692   pivot_table_submit (table);
1693 }
1694
1695 static void
1696 show_factor_correlation (const struct cmd_factor * factor, const gsl_matrix *fcm)
1697 {
1698   struct pivot_table *table = pivot_table_create (
1699     N_("Factor Correlation Matrix"));
1700
1701   create_numeric_dimension (
1702     table, PIVOT_AXIS_ROW,
1703     factor->extraction == EXTRACTION_PC ? N_("Component") : N_("Factor"),
1704     fcm->size2, true);
1705
1706   create_numeric_dimension (table, PIVOT_AXIS_COLUMN, N_("Factor 2"),
1707                             fcm->size1, false);
1708
1709   for (size_t i = 0; i < fcm->size1; ++i)
1710     for (size_t j = 0; j < fcm->size2; ++j)
1711       pivot_table_put2 (table, j, i,
1712                         pivot_value_new_number (gsl_matrix_get (fcm, i, j)));
1713
1714   pivot_table_submit (table);
1715 }
1716
1717 static void
1718 add_var_dims (struct pivot_table *table, const struct cmd_factor *factor)
1719 {
1720   for (int i = 0; i < 2; i++)
1721     {
1722       struct pivot_dimension *d = pivot_dimension_create (
1723         table, i ? PIVOT_AXIS_ROW : PIVOT_AXIS_COLUMN,
1724         N_("Variables"));
1725
1726       for (size_t j = 0; j < factor->n_vars; j++)
1727         pivot_category_create_leaf (
1728           d->root, pivot_value_new_variable (factor->vars[j]));
1729     }
1730 }
1731
1732 static void
1733 show_aic (const struct cmd_factor *factor, const struct idata *idata)
1734 {
1735   if ((factor->print & PRINT_AIC) == 0)
1736     return;
1737
1738   struct pivot_table *table = pivot_table_create (N_("Anti-Image Matrices"));
1739
1740   add_var_dims (table, factor);
1741
1742   pivot_dimension_create (table, PIVOT_AXIS_ROW, N_("Statistics"),
1743                           N_("Anti-image Covariance"),
1744                           N_("Anti-image Correlation"));
1745
1746   for (size_t i = 0; i < factor->n_vars; ++i)
1747     for (size_t j = 0; j < factor->n_vars; ++j)
1748       {
1749         double cov = gsl_matrix_get (idata->ai_cov, i, j);
1750         pivot_table_put3 (table, i, j, 0, pivot_value_new_number (cov));
1751
1752         double corr = gsl_matrix_get (idata->ai_cor, i, j);
1753         pivot_table_put3 (table, i, j, 1, pivot_value_new_number (corr));
1754       }
1755
1756   pivot_table_submit (table);
1757 }
1758
1759 static void
1760 show_correlation_matrix (const struct cmd_factor *factor, const struct idata *idata)
1761 {
1762   if (!(factor->print & (PRINT_CORRELATION | PRINT_SIG | PRINT_DETERMINANT)))
1763     return;
1764
1765   struct pivot_table *table = pivot_table_create (N_("Correlation Matrix"));
1766
1767   if (factor->print & (PRINT_CORRELATION | PRINT_SIG))
1768     {
1769       add_var_dims (table, factor);
1770
1771       struct pivot_dimension *statistics = pivot_dimension_create (
1772         table, PIVOT_AXIS_ROW, N_("Statistics"));
1773       if (factor->print & PRINT_CORRELATION)
1774         pivot_category_create_leaves (statistics->root, N_("Correlation"),
1775                                       PIVOT_RC_CORRELATION);
1776       if (factor->print & PRINT_SIG)
1777         pivot_category_create_leaves (statistics->root, N_("Sig. (1-tailed)"),
1778                                       PIVOT_RC_SIGNIFICANCE);
1779
1780       int stat_idx = 0;
1781       if (factor->print & PRINT_CORRELATION)
1782         {
1783           for (int i = 0; i < factor->n_vars; ++i)
1784             for (int j = 0; j < factor->n_vars; ++j)
1785               {
1786                 double corr = gsl_matrix_get (idata->mm.corr, i, j);
1787                 pivot_table_put3 (table, j, i, stat_idx,
1788                                   pivot_value_new_number (corr));
1789               }
1790           stat_idx++;
1791         }
1792
1793       if (factor->print & PRINT_SIG)
1794         {
1795           for (int i = 0; i < factor->n_vars; ++i)
1796             for (int j = 0; j < factor->n_vars; ++j)
1797               if (i != j)
1798                 {
1799                   double rho = gsl_matrix_get (idata->mm.corr, i, j);
1800                   double w = gsl_matrix_get (idata->mm.n, i, j);
1801                   double sig = significance_of_correlation (rho, w);
1802                   pivot_table_put3 (table, j, i, stat_idx,
1803                                     pivot_value_new_number (sig));
1804                 }
1805           stat_idx++;
1806         }
1807     }
1808
1809   if (factor->print & PRINT_DETERMINANT)
1810     {
1811       struct pivot_value *caption = pivot_value_new_user_text_nocopy (
1812         xasprintf ("%s: %.2f", _("Determinant"), idata->detR));
1813       pivot_table_set_caption (table, caption);
1814     }
1815
1816   pivot_table_submit (table);
1817 }
1818
1819 static void
1820 show_covariance_matrix (const struct cmd_factor *factor, const struct idata *idata)
1821 {
1822   if (!(factor->print & PRINT_COVARIANCE))
1823     return;
1824
1825   struct pivot_table *table = pivot_table_create (N_("Covariance Matrix"));
1826   add_var_dims (table, factor);
1827
1828   for (int i = 0; i < factor->n_vars; ++i)
1829     for (int j = 0; j < factor->n_vars; ++j)
1830       {
1831         double cov = gsl_matrix_get (idata->mm.cov, i, j);
1832         pivot_table_put2 (table, j, i, pivot_value_new_number (cov));
1833       }
1834
1835   pivot_table_submit (table);
1836 }
1837
1838
1839 static void
1840 do_factor (const struct cmd_factor *factor, struct casereader *r)
1841 {
1842   struct ccase *c;
1843   struct idata *idata = idata_alloc (factor->n_vars);
1844
1845   idata->cvm = covariance_1pass_create (factor->n_vars, factor->vars,
1846                                         factor->wv, factor->exclude, true);
1847
1848   for (; (c = casereader_read (r)); case_unref (c))
1849     {
1850       covariance_accumulate (idata->cvm, c);
1851     }
1852
1853   idata->mm.cov = covariance_calculate (idata->cvm);
1854
1855   if (idata->mm.cov == NULL)
1856     {
1857       msg (MW, _("The dataset contains no complete observations. No analysis will be performed."));
1858       covariance_destroy (idata->cvm);
1859       goto finish;
1860     }
1861
1862   idata->mm.var_matrix = covariance_moments (idata->cvm, MOMENT_VARIANCE);
1863   idata->mm.mean_matrix = covariance_moments (idata->cvm, MOMENT_MEAN);
1864   idata->mm.n = covariance_moments (idata->cvm, MOMENT_NONE);
1865
1866   do_factor_by_matrix (factor, idata);
1867
1868  finish:
1869   gsl_matrix_free (idata->mm.corr);
1870   gsl_matrix_free (idata->mm.cov);
1871
1872   idata_free (idata);
1873   casereader_destroy (r);
1874 }
1875
1876 static void
1877 do_factor_by_matrix (const struct cmd_factor *factor, struct idata *idata)
1878 {
1879   if (!idata->mm.cov && !(idata->mm.corr && idata->mm.var_matrix))
1880     {
1881       msg (ME, _("The dataset has no covariance matrix or a "
1882                  "correlation matrix along with standard deviations."));
1883       return;
1884     }
1885
1886   if (idata->mm.cov && !idata->mm.corr)
1887     idata->mm.corr = correlation_from_covariance (idata->mm.cov, idata->mm.var_matrix);
1888   if (idata->mm.corr && !idata->mm.cov)
1889     idata->mm.cov = covariance_from_correlation (idata->mm.corr, idata->mm.var_matrix);
1890   if (factor->method == METHOD_CORR)
1891     idata->analysis_matrix = idata->mm.corr;
1892   else
1893     idata->analysis_matrix = idata->mm.cov;
1894
1895   gsl_matrix *r_inv;
1896   r_inv  = clone_matrix (idata->mm.corr);
1897   gsl_linalg_cholesky_decomp (r_inv);
1898   gsl_linalg_cholesky_invert (r_inv);
1899
1900   idata->ai_cov = anti_image_cov (r_inv);
1901   idata->ai_cor = anti_image_corr (r_inv, idata);
1902
1903   double sum_ssq_r = 0;
1904   double sum_ssq_a = 0;
1905   for (int i = 0; i < r_inv->size1; ++i)
1906     {
1907       sum_ssq_r += ssq_od_n (idata->mm.corr, i);
1908       sum_ssq_a += ssq_od_n (idata->ai_cor, i);
1909     }
1910
1911   gsl_matrix_free (r_inv);
1912
1913   if (factor->print & PRINT_DETERMINANT
1914       || factor->print & PRINT_KMO)
1915     {
1916       int sign = 0;
1917
1918       const int size = idata->mm.corr->size1;
1919       gsl_permutation *p = gsl_permutation_calloc (size);
1920       gsl_matrix *tmp = gsl_matrix_calloc (size, size);
1921       gsl_matrix_memcpy (tmp, idata->mm.corr);
1922
1923       gsl_linalg_LU_decomp (tmp, p, &sign);
1924       idata->detR = gsl_linalg_LU_det (tmp, sign);
1925       gsl_permutation_free (p);
1926       gsl_matrix_free (tmp);
1927     }
1928
1929   if (factor->print & PRINT_UNIVARIATE
1930       && idata->mm.n && idata->mm.mean_matrix && idata->mm.var_matrix)
1931     {
1932       struct pivot_table *table = pivot_table_create (
1933         N_("Descriptive Statistics"));
1934       pivot_table_set_weight_var (table, factor->wv);
1935
1936       pivot_dimension_create (table, PIVOT_AXIS_COLUMN, N_("Statistics"),
1937                               N_("Mean"), PIVOT_RC_OTHER,
1938                               N_("Std. Deviation"), PIVOT_RC_OTHER,
1939                               N_("Analysis N"), PIVOT_RC_COUNT);
1940
1941       struct pivot_dimension *variables = pivot_dimension_create (
1942         table, PIVOT_AXIS_ROW, N_("Variables"));
1943
1944       for (size_t i = 0; i < factor->n_vars; ++i)
1945         {
1946           const struct variable *v = factor->vars[i];
1947
1948           int row = pivot_category_create_leaf (
1949             variables->root, pivot_value_new_variable (v));
1950
1951           double entries[] = {
1952             gsl_matrix_get (idata->mm.mean_matrix, i, i),
1953             sqrt (gsl_matrix_get (idata->mm.var_matrix, i, i)),
1954             gsl_matrix_get (idata->mm.n, i, i),
1955           };
1956           for (size_t j = 0; j < sizeof entries / sizeof *entries; j++)
1957             pivot_table_put2 (table, j, row,
1958                               pivot_value_new_number (entries[j]));
1959         }
1960
1961       pivot_table_submit (table);
1962     }
1963
1964   if (factor->print & PRINT_KMO && idata->mm.n)
1965     {
1966       struct pivot_table *table = pivot_table_create (
1967         N_("KMO and Bartlett's Test"));
1968
1969       struct pivot_dimension *statistics = pivot_dimension_create (
1970         table, PIVOT_AXIS_ROW, N_("Statistics"),
1971         N_("Kaiser-Meyer-Olkin Measure of Sampling Adequacy"), PIVOT_RC_OTHER);
1972       pivot_category_create_group (
1973         statistics->root, N_("Bartlett's Test of Sphericity"),
1974         N_("Approx. Chi-Square"), PIVOT_RC_OTHER,
1975         N_("df"), PIVOT_RC_INTEGER,
1976         N_("Sig."), PIVOT_RC_SIGNIFICANCE);
1977
1978       /* The literature doesn't say what to do for the value of W when
1979          missing values are involved.  The best thing I can think of
1980          is to take the mean average. */
1981       double w = 0;
1982       for (int i = 0; i < idata->mm.n->size1; ++i)
1983         w += gsl_matrix_get (idata->mm.n, i, i);
1984       w /= idata->mm.n->size1;
1985
1986       double xsq = ((w - 1 - (2 * factor->n_vars + 5) / 6.0)
1987                     * -log (idata->detR));
1988       double df = factor->n_vars * (factor->n_vars - 1) / 2;
1989       double entries[] = {
1990         sum_ssq_r / (sum_ssq_r + sum_ssq_a),
1991         xsq,
1992         df,
1993         gsl_cdf_chisq_Q (xsq, df)
1994       };
1995       for (size_t i = 0; i < sizeof entries / sizeof *entries; i++)
1996         pivot_table_put1 (table, i, pivot_value_new_number (entries[i]));
1997
1998       pivot_table_submit (table);
1999     }
2000
2001   show_correlation_matrix (factor, idata);
2002   show_covariance_matrix (factor, idata);
2003   if (idata->cvm)
2004     covariance_destroy (idata->cvm);
2005
2006   {
2007     gsl_matrix *am = matrix_dup (idata->analysis_matrix);
2008     gsl_eigen_symmv_workspace *workspace = gsl_eigen_symmv_alloc (factor->n_vars);
2009
2010     gsl_eigen_symmv (am, idata->eval, idata->evec, workspace);
2011
2012     gsl_eigen_symmv_free (workspace);
2013     gsl_matrix_free (am);
2014   }
2015
2016   gsl_eigen_symmv_sort (idata->eval, idata->evec, GSL_EIGEN_SORT_ABS_DESC);
2017
2018   idata->n_extractions = n_extracted_factors (factor, idata);
2019
2020   if (idata->n_extractions == 0)
2021     {
2022       msg (MW, _("The %s criteria result in zero factors extracted. Therefore no analysis will be performed."), "FACTOR");
2023       return;
2024     }
2025
2026   if (idata->n_extractions > factor->n_vars)
2027     {
2028       msg (MW,
2029            _("The %s criteria result in more factors than variables, which is not meaningful. No analysis will be performed."),
2030            "FACTOR");
2031       return;
2032     }
2033
2034   {
2035     gsl_matrix *rotated_factors = NULL;
2036     gsl_matrix *pattern_matrix = NULL;
2037     gsl_matrix *fcm = NULL;
2038     gsl_vector *rotated_loadings = NULL;
2039
2040     const gsl_vector *extracted_eigenvalues = NULL;
2041     gsl_vector *initial_communalities = gsl_vector_alloc (factor->n_vars);
2042     gsl_vector *extracted_communalities = gsl_vector_alloc (factor->n_vars);
2043     struct factor_matrix_workspace *fmw = factor_matrix_workspace_alloc (idata->msr->size, idata->n_extractions);
2044     gsl_matrix *factor_matrix = gsl_matrix_calloc (factor->n_vars, fmw->n_factors);
2045
2046     if (factor->extraction == EXTRACTION_PAF)
2047       {
2048         gsl_vector *diff = gsl_vector_alloc (idata->msr->size);
2049         struct smr_workspace *ws = ws_create (idata->analysis_matrix);
2050
2051         for (size_t i = 0; i < factor->n_vars; ++i)
2052           {
2053             double r2 = squared_multiple_correlation (idata->analysis_matrix, i, ws);
2054
2055             gsl_vector_set (idata->msr, i, r2);
2056           }
2057         ws_destroy (ws);
2058
2059         gsl_vector_memcpy (initial_communalities, idata->msr);
2060
2061         for (size_t i = 0; i < factor->extraction_iterations; ++i)
2062           {
2063             double min, max;
2064             gsl_vector_memcpy (diff, idata->msr);
2065
2066             iterate_factor_matrix (idata->analysis_matrix, idata->msr, factor_matrix, fmw);
2067
2068             gsl_vector_sub (diff, idata->msr);
2069
2070             gsl_vector_minmax (diff, &min, &max);
2071
2072             if (fabs (min) < factor->econverge && fabs (max) < factor->econverge)
2073               break;
2074           }
2075         gsl_vector_free (diff);
2076
2077
2078
2079         gsl_vector_memcpy (extracted_communalities, idata->msr);
2080         extracted_eigenvalues = fmw->eval;
2081       }
2082     else if (factor->extraction == EXTRACTION_PC)
2083       {
2084         for (size_t i = 0; i < factor->n_vars; ++i)
2085           gsl_vector_set (initial_communalities, i, communality (idata, i, factor->n_vars));
2086
2087         gsl_vector_memcpy (extracted_communalities, initial_communalities);
2088
2089         iterate_factor_matrix (idata->analysis_matrix, extracted_communalities, factor_matrix, fmw);
2090
2091
2092         extracted_eigenvalues = idata->eval;
2093       }
2094
2095
2096     show_aic (factor, idata);
2097     show_communalities (factor, initial_communalities, extracted_communalities);
2098
2099     if (factor->rotation != ROT_NONE)
2100       {
2101         rotated_factors = gsl_matrix_calloc (factor_matrix->size1, factor_matrix->size2);
2102         rotated_loadings = gsl_vector_calloc (factor_matrix->size2);
2103         if (factor->rotation == ROT_PROMAX)
2104           {
2105             pattern_matrix = gsl_matrix_calloc (factor_matrix->size1, factor_matrix->size2);
2106             fcm = gsl_matrix_calloc (factor_matrix->size2, factor_matrix->size2);
2107           }
2108
2109
2110         rotate (factor, factor_matrix, extracted_communalities, rotated_factors, rotated_loadings, pattern_matrix, fcm);
2111       }
2112
2113     show_explained_variance (factor, idata, idata->eval, extracted_eigenvalues, rotated_loadings);
2114
2115     factor_matrix_workspace_free (fmw);
2116
2117     show_scree (factor, idata);
2118
2119     show_factor_matrix (factor, idata,
2120                         (factor->extraction == EXTRACTION_PC
2121                          ? N_("Component Matrix") : N_("Factor Matrix")),
2122                         factor_matrix);
2123
2124     if (factor->rotation == ROT_PROMAX)
2125       {
2126         show_factor_matrix (factor, idata, N_("Pattern Matrix"),
2127                             pattern_matrix);
2128         gsl_matrix_free (pattern_matrix);
2129       }
2130
2131     if (factor->rotation != ROT_NONE)
2132       {
2133         show_factor_matrix (factor, idata,
2134                             (factor->rotation == ROT_PROMAX
2135                              ? N_("Structure Matrix")
2136                              : factor->extraction == EXTRACTION_PC
2137                              ? N_("Rotated Component Matrix")
2138                              : N_("Rotated Factor Matrix")),
2139                             rotated_factors);
2140
2141         gsl_matrix_free (rotated_factors);
2142       }
2143
2144     if (factor->rotation == ROT_PROMAX)
2145       {
2146         show_factor_correlation (factor, fcm);
2147         gsl_matrix_free (fcm);
2148       }
2149
2150     gsl_matrix_free (factor_matrix);
2151     gsl_vector_free (rotated_loadings);
2152     gsl_vector_free (initial_communalities);
2153     gsl_vector_free (extracted_communalities);
2154   }
2155 }
2156
2157