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