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