FACTOR: Make idata parameters const where they can be.
[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 (matrix_reader)
1471     {
1472       struct idata *id = idata_alloc (factor.n_vars);
1473
1474       while (next_matrix_from_reader (&id->mm, mr,
1475                                       factor.vars, factor.n_vars))
1476         {
1477           do_factor_by_matrix (&factor, id);
1478
1479           gsl_matrix_free (id->mm.corr);
1480           id->mm.corr = NULL;
1481           gsl_matrix_free (id->mm.cov);
1482           id->mm.cov = NULL;
1483         }
1484
1485       idata_free (id);
1486     }
1487   else
1488     if ( ! run_factor (ds, &factor))
1489       goto error;
1490
1491
1492   destroy_matrix_reader (mr);
1493   free (factor.vars);
1494   return CMD_SUCCESS;
1495
1496  error:
1497   destroy_matrix_reader (mr);
1498   free (factor.vars);
1499   return CMD_FAILURE;
1500 }
1501
1502 static void do_factor (const struct cmd_factor *factor, struct casereader *group);
1503
1504
1505 static bool
1506 run_factor (struct dataset *ds, const struct cmd_factor *factor)
1507 {
1508   struct dictionary *dict = dataset_dict (ds);
1509   bool ok;
1510   struct casereader *group;
1511
1512   struct casegrouper *grouper = casegrouper_create_splits (proc_open (ds), dict);
1513
1514   while (casegrouper_get_next_group (grouper, &group))
1515     {
1516       if ( factor->missing_type == MISS_LISTWISE )
1517         group  = casereader_create_filter_missing (group, factor->vars, factor->n_vars,
1518                                                    factor->exclude,
1519                                                    NULL,  NULL);
1520       do_factor (factor, group);
1521     }
1522
1523   ok = casegrouper_destroy (grouper);
1524   ok = proc_commit (ds) && ok;
1525
1526   return ok;
1527 }
1528
1529
1530 /* Return the communality of variable N, calculated to N_FACTORS */
1531 static double
1532 the_communality (const gsl_matrix *evec, const gsl_vector *eval, int n, int n_factors)
1533 {
1534   size_t i;
1535
1536   double comm = 0;
1537
1538   assert (n >= 0);
1539   assert (n < eval->size);
1540   assert (n < evec->size1);
1541   assert (n_factors <= eval->size);
1542
1543   for (i = 0 ; i < n_factors; ++i)
1544     {
1545       double evali = fabs (gsl_vector_get (eval, i));
1546
1547       double eveci = gsl_matrix_get (evec, n, i);
1548
1549       comm += pow2 (eveci) * evali;
1550     }
1551
1552   return comm;
1553 }
1554
1555 /* Return the communality of variable N, calculated to N_FACTORS */
1556 static double
1557 communality (const struct idata *idata, int n, int n_factors)
1558 {
1559   return the_communality (idata->evec, idata->eval, n, n_factors);
1560 }
1561
1562
1563 static void
1564 show_scree (const struct cmd_factor *f, const struct idata *idata)
1565 {
1566   struct scree *s;
1567   const char *label ;
1568
1569   if ( !(f->plot & PLOT_SCREE) )
1570     return;
1571
1572
1573   label = f->extraction == EXTRACTION_PC ? _("Component Number") : _("Factor Number");
1574
1575   s = scree_create (idata->eval, label);
1576
1577   scree_submit (s);
1578 }
1579
1580 static void
1581 show_communalities (const struct cmd_factor * factor,
1582                     const gsl_vector *initial, const gsl_vector *extracted)
1583 {
1584   int i;
1585   int c = 0;
1586   const int heading_columns = 1;
1587   int nc = heading_columns;
1588   const int heading_rows = 1;
1589   const int nr = heading_rows + factor->n_vars;
1590   struct tab_table *t;
1591
1592   if (factor->print & PRINT_EXTRACTION)
1593     nc++;
1594
1595   if (factor->print & PRINT_INITIAL)
1596     nc++;
1597
1598   /* No point having a table with only headings */
1599   if (nc <= 1)
1600     return;
1601
1602   t = tab_create (nc, nr);
1603
1604   tab_title (t, _("Communalities"));
1605
1606   tab_headers (t, heading_columns, 0, heading_rows, 0);
1607
1608   c = 1;
1609   if (factor->print & PRINT_INITIAL)
1610     tab_text (t, c++, 0, TAB_CENTER | TAT_TITLE, _("Initial"));
1611
1612   if (factor->print & PRINT_EXTRACTION)
1613     tab_text (t, c++, 0, TAB_CENTER | TAT_TITLE, _("Extraction"));
1614
1615   /* Outline the box */
1616   tab_box (t,
1617            TAL_2, TAL_2,
1618            -1, -1,
1619            0, 0,
1620            nc - 1, nr - 1);
1621
1622   /* Vertical lines */
1623   tab_box (t,
1624            -1, -1,
1625            -1, TAL_1,
1626            heading_columns, 0,
1627            nc - 1, nr - 1);
1628
1629   tab_hline (t, TAL_1, 0, nc - 1, heading_rows);
1630   tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
1631
1632   for (i = 0 ; i < factor->n_vars; ++i)
1633     {
1634       c = 0;
1635       tab_text (t, c++, i + heading_rows, TAT_TITLE, var_to_string (factor->vars[i]));
1636
1637       if (factor->print & PRINT_INITIAL)
1638         tab_double (t, c++, i + heading_rows, 0, gsl_vector_get (initial, i), NULL, RC_OTHER);
1639
1640       if (factor->print & PRINT_EXTRACTION)
1641         tab_double (t, c++, i + heading_rows, 0, gsl_vector_get (extracted, i), NULL, RC_OTHER);
1642     }
1643
1644   tab_submit (t);
1645 }
1646
1647
1648 static void
1649 show_factor_matrix (const struct cmd_factor *factor, const struct idata *idata, const char *title, const gsl_matrix *fm)
1650 {
1651   int i;
1652
1653   const int n_factors = idata->n_extractions;
1654
1655   const int heading_columns = 1;
1656   const int heading_rows = 2;
1657   const int nr = heading_rows + factor->n_vars;
1658   const int nc = heading_columns + n_factors;
1659   gsl_permutation *perm;
1660
1661   struct tab_table *t = tab_create (nc, nr);
1662
1663   /*
1664   if ( factor->extraction == EXTRACTION_PC )
1665     tab_title (t, _("Component Matrix"));
1666   else
1667     tab_title (t, _("Factor Matrix"));
1668   */
1669
1670   tab_title (t, "%s", title);
1671
1672   tab_headers (t, heading_columns, 0, heading_rows, 0);
1673
1674   if ( factor->extraction == EXTRACTION_PC )
1675     tab_joint_text (t,
1676                     1, 0,
1677                     nc - 1, 0,
1678                     TAB_CENTER | TAT_TITLE, _("Component"));
1679   else
1680     tab_joint_text (t,
1681                     1, 0,
1682                     nc - 1, 0,
1683                     TAB_CENTER | TAT_TITLE, _("Factor"));
1684
1685
1686   tab_hline (t, TAL_1, heading_columns, nc - 1, 1);
1687
1688
1689   /* Outline the box */
1690   tab_box (t,
1691            TAL_2, TAL_2,
1692            -1, -1,
1693            0, 0,
1694            nc - 1, nr - 1);
1695
1696   /* Vertical lines */
1697   tab_box (t,
1698            -1, -1,
1699            -1, TAL_1,
1700            heading_columns, 1,
1701            nc - 1, nr - 1);
1702
1703   tab_hline (t, TAL_1, 0, nc - 1, heading_rows);
1704   tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
1705
1706
1707   /* Initialise to the identity permutation */
1708   perm = gsl_permutation_calloc (factor->n_vars);
1709
1710   if ( factor->sort)
1711     sort_matrix_indirect (fm, perm);
1712
1713   for (i = 0 ; i < n_factors; ++i)
1714     {
1715       tab_text_format (t, heading_columns + i, 1, TAB_CENTER | TAT_TITLE, _("%d"), i + 1);
1716     }
1717
1718   for (i = 0 ; i < factor->n_vars; ++i)
1719     {
1720       int j;
1721       const int matrix_row = perm->data[i];
1722       tab_text (t, 0, i + heading_rows, TAT_TITLE, var_to_string (factor->vars[matrix_row]));
1723
1724       for (j = 0 ; j < n_factors; ++j)
1725         {
1726           double x = gsl_matrix_get (fm, matrix_row, j);
1727
1728           if ( fabs (x) < factor->blank)
1729             continue;
1730
1731           tab_double (t, heading_columns + j, heading_rows + i, 0, x, NULL, RC_OTHER);
1732         }
1733     }
1734
1735   gsl_permutation_free (perm);
1736
1737   tab_submit (t);
1738 }
1739
1740
1741 static void
1742 show_explained_variance (const struct cmd_factor * factor,
1743                          const struct idata *idata,
1744                          const gsl_vector *initial_eigenvalues,
1745                          const gsl_vector *extracted_eigenvalues,
1746                          const gsl_vector *rotated_loadings)
1747 {
1748   size_t i;
1749   int c = 0;
1750   const int heading_columns = 1;
1751   const int heading_rows = 2;
1752   const int nr = heading_rows + factor->n_vars;
1753
1754   struct tab_table *t ;
1755
1756   double i_total = 0.0;
1757   double i_cum = 0.0;
1758
1759   double e_total = 0.0;
1760   double e_cum = 0.0;
1761
1762   double r_cum = 0.0;
1763
1764   int nc = heading_columns;
1765
1766   if (factor->print & PRINT_EXTRACTION)
1767     nc += 3;
1768
1769   if (factor->print & PRINT_INITIAL)
1770     nc += 3;
1771
1772   if (factor->print & PRINT_ROTATION)
1773     {
1774       nc += factor->rotation == ROT_PROMAX ? 1 : 3;
1775     }
1776
1777   /* No point having a table with only headings */
1778   if ( nc <= heading_columns)
1779     return;
1780
1781   t = tab_create (nc, nr);
1782
1783   tab_title (t, _("Total Variance Explained"));
1784
1785   tab_headers (t, heading_columns, 0, heading_rows, 0);
1786
1787   /* Outline the box */
1788   tab_box (t,
1789            TAL_2, TAL_2,
1790            -1, -1,
1791            0, 0,
1792            nc - 1, nr - 1);
1793
1794   /* Vertical lines */
1795   tab_box (t,
1796            -1, -1,
1797            -1, TAL_1,
1798            heading_columns, 0,
1799            nc - 1, nr - 1);
1800
1801   tab_hline (t, TAL_1, 0, nc - 1, heading_rows);
1802   tab_hline (t, TAL_1, 1, nc - 1, 1);
1803
1804   tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
1805
1806
1807   if ( factor->extraction == EXTRACTION_PC)
1808     tab_text (t, 0, 1, TAB_LEFT | TAT_TITLE, _("Component"));
1809   else
1810     tab_text (t, 0, 1, TAB_LEFT | TAT_TITLE, _("Factor"));
1811
1812   c = 1;
1813   if (factor->print & PRINT_INITIAL)
1814     {
1815       tab_joint_text (t, c, 0, c + 2, 0, TAB_CENTER | TAT_TITLE, _("Initial Eigenvalues"));
1816       c += 3;
1817     }
1818
1819   if (factor->print & PRINT_EXTRACTION)
1820     {
1821       tab_joint_text (t, c, 0, c + 2, 0, TAB_CENTER | TAT_TITLE, _("Extraction Sums of Squared Loadings"));
1822       c += 3;
1823     }
1824
1825   if (factor->print & PRINT_ROTATION)
1826     {
1827       const int width = factor->rotation == ROT_PROMAX ? 0 : 2;
1828       tab_joint_text (t, c, 0, c + width, 0, TAB_CENTER | TAT_TITLE, _("Rotation Sums of Squared Loadings"));
1829       c += width + 1;
1830     }
1831
1832   for (i = 0; i < (nc - heading_columns + 2) / 3 ; ++i)
1833     {
1834       tab_text (t, i * 3 + 1, 1, TAB_CENTER | TAT_TITLE, _("Total"));
1835
1836       tab_vline (t, TAL_2, heading_columns + i * 3, 0, nr - 1);
1837
1838       if (i == 2 && factor->rotation == ROT_PROMAX)
1839         continue;
1840
1841       /* xgettext:no-c-format */
1842       tab_text (t, i * 3 + 2, 1, TAB_CENTER | TAT_TITLE, _("% of Variance"));
1843       tab_text (t, i * 3 + 3, 1, TAB_CENTER | TAT_TITLE, _("Cumulative %"));
1844     }
1845
1846   for (i = 0 ; i < initial_eigenvalues->size; ++i)
1847     i_total += gsl_vector_get (initial_eigenvalues, i);
1848
1849   if ( factor->extraction == EXTRACTION_PAF)
1850     {
1851       e_total = factor->n_vars;
1852     }
1853   else
1854     {
1855       e_total = i_total;
1856     }
1857
1858   for (i = 0 ; i < factor->n_vars; ++i)
1859     {
1860       const double i_lambda = gsl_vector_get (initial_eigenvalues, i);
1861       double i_percent = 100.0 * i_lambda / i_total ;
1862
1863       const double e_lambda = gsl_vector_get (extracted_eigenvalues, i);
1864       double e_percent = 100.0 * e_lambda / e_total ;
1865
1866       c = 0;
1867
1868       tab_text_format (t, c++, i + heading_rows, TAB_LEFT | TAT_TITLE, _("%zu"), i + 1);
1869
1870       i_cum += i_percent;
1871       e_cum += e_percent;
1872
1873       /* Initial Eigenvalues */
1874       if (factor->print & PRINT_INITIAL)
1875       {
1876         tab_double (t, c++, i + heading_rows, 0, i_lambda, NULL, RC_OTHER);
1877         tab_double (t, c++, i + heading_rows, 0, i_percent, NULL, RC_OTHER);
1878         tab_double (t, c++, i + heading_rows, 0, i_cum, NULL, RC_OTHER);
1879       }
1880
1881
1882       if (factor->print & PRINT_EXTRACTION)
1883         {
1884           if (i < idata->n_extractions)
1885             {
1886               /* Sums of squared loadings */
1887               tab_double (t, c++, i + heading_rows, 0, e_lambda, NULL, RC_OTHER);
1888               tab_double (t, c++, i + heading_rows, 0, e_percent, NULL, RC_OTHER);
1889               tab_double (t, c++, i + heading_rows, 0, e_cum, NULL, RC_OTHER);
1890             }
1891         }
1892
1893       if (rotated_loadings != NULL)
1894         {
1895           const double r_lambda = gsl_vector_get (rotated_loadings, i);
1896           double r_percent = 100.0 * r_lambda / e_total ;
1897
1898           if (factor->print & PRINT_ROTATION)
1899             {
1900               if (i < idata->n_extractions)
1901                 {
1902                   r_cum += r_percent;
1903                   tab_double (t, c++, i + heading_rows, 0, r_lambda, NULL, RC_OTHER);
1904                   if (factor->rotation != ROT_PROMAX)
1905                     {
1906                       tab_double (t, c++, i + heading_rows, 0, r_percent, NULL, RC_OTHER);
1907                       tab_double (t, c++, i + heading_rows, 0, r_cum, NULL, RC_OTHER);
1908                     }
1909                 }
1910             }
1911         }
1912     }
1913
1914   tab_submit (t);
1915 }
1916
1917
1918 static void
1919 show_factor_correlation (const struct cmd_factor * factor, const gsl_matrix *fcm)
1920 {
1921   size_t i, j;
1922   const int heading_columns = 1;
1923   const int heading_rows = 1;
1924   const int nr = heading_rows + fcm->size2;
1925   const int nc = heading_columns + fcm->size1;
1926   struct tab_table *t = tab_create (nc, nr);
1927
1928   tab_title (t, _("Factor Correlation Matrix"));
1929
1930   tab_headers (t, heading_columns, 0, heading_rows, 0);
1931
1932   /* Outline the box */
1933   tab_box (t,
1934            TAL_2, TAL_2,
1935            -1, -1,
1936            0, 0,
1937            nc - 1, nr - 1);
1938
1939   /* Vertical lines */
1940   tab_box (t,
1941            -1, -1,
1942            -1, TAL_1,
1943            heading_columns, 0,
1944            nc - 1, nr - 1);
1945
1946   tab_hline (t, TAL_1, 0, nc - 1, heading_rows);
1947   tab_hline (t, TAL_1, 1, nc - 1, 1);
1948
1949   tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
1950
1951
1952   if ( factor->extraction == EXTRACTION_PC)
1953     tab_text (t, 0, 0, TAB_LEFT | TAT_TITLE, _("Component"));
1954   else
1955     tab_text (t, 0, 0, TAB_LEFT | TAT_TITLE, _("Factor"));
1956
1957   for (i = 0 ; i < fcm->size1; ++i)
1958     {
1959       tab_text_format (t, heading_columns + i, 0, TAB_CENTER | TAT_TITLE, _("%zu"), i + 1);
1960     }
1961
1962   for (i = 0 ; i < fcm->size2; ++i)
1963     {
1964       tab_text_format (t, 0, heading_rows + i, TAB_CENTER | TAT_TITLE, _("%zu"), i + 1);
1965     }
1966
1967
1968   for (i = 0 ; i < fcm->size1; ++i)
1969     {
1970       for (j = 0 ; j < fcm->size2; ++j)
1971         tab_double (t, heading_columns + j,  heading_rows + i, 0,
1972                     gsl_matrix_get (fcm, i, j), NULL, RC_OTHER);
1973     }
1974
1975   tab_submit (t);
1976 }
1977
1978
1979 static void
1980 show_correlation_matrix (const struct cmd_factor *factor, const struct idata *idata)
1981 {
1982   struct tab_table *t ;
1983   size_t i, j;
1984   int y_pos_corr = -1;
1985   int y_pos_sig = -1;
1986   int suffix_rows = 0;
1987
1988   const int heading_rows = 1;
1989   const int heading_columns = 2;
1990
1991   int nc = heading_columns ;
1992   int nr = heading_rows ;
1993   int n_data_sets = 0;
1994
1995   if (factor->print & PRINT_CORRELATION)
1996     {
1997       y_pos_corr = n_data_sets;
1998       n_data_sets++;
1999       nc = heading_columns + factor->n_vars;
2000     }
2001
2002   if (factor->print & PRINT_SIG)
2003     {
2004       y_pos_sig = n_data_sets;
2005       n_data_sets++;
2006       nc = heading_columns + factor->n_vars;
2007     }
2008
2009   nr += n_data_sets * factor->n_vars;
2010
2011   if (factor->print & PRINT_DETERMINANT)
2012     suffix_rows = 1;
2013
2014   /* If the table would contain only headings, don't bother rendering it */
2015   if (nr <= heading_rows && suffix_rows == 0)
2016     return;
2017
2018   t = tab_create (nc, nr + suffix_rows);
2019
2020   tab_title (t, _("Correlation Matrix"));
2021
2022   tab_hline (t, TAL_1, 0, nc - 1, heading_rows);
2023
2024   if (nr > heading_rows)
2025     {
2026       tab_headers (t, heading_columns, 0, heading_rows, 0);
2027
2028       tab_vline (t, TAL_2, 2, 0, nr - 1);
2029
2030       /* Outline the box */
2031       tab_box (t,
2032                TAL_2, TAL_2,
2033                -1, -1,
2034                0, 0,
2035                nc - 1, nr - 1);
2036
2037       /* Vertical lines */
2038       tab_box (t,
2039                -1, -1,
2040                -1, TAL_1,
2041                heading_columns, 0,
2042                nc - 1, nr - 1);
2043
2044
2045       for (i = 0; i < factor->n_vars; ++i)
2046         tab_text (t, heading_columns + i, 0, TAT_TITLE, var_to_string (factor->vars[i]));
2047
2048
2049       for (i = 0 ; i < n_data_sets; ++i)
2050         {
2051           int y = heading_rows + i * factor->n_vars;
2052           size_t v;
2053           for (v = 0; v < factor->n_vars; ++v)
2054             tab_text (t, 1, y + v, TAT_TITLE, var_to_string (factor->vars[v]));
2055
2056           tab_hline (t, TAL_1, 0, nc - 1, y);
2057         }
2058
2059       if (factor->print & PRINT_CORRELATION)
2060         {
2061           const double y = heading_rows + y_pos_corr;
2062           tab_text (t, 0, y, TAT_TITLE, _("Correlations"));
2063
2064           for (i = 0; i < factor->n_vars; ++i)
2065             {
2066               for (j = 0; j < factor->n_vars; ++j)
2067                 tab_double (t, heading_columns + j,  y + i, 0, gsl_matrix_get (idata->mm.corr, i, j), NULL, RC_OTHER);
2068             }
2069         }
2070
2071       if (factor->print & PRINT_SIG)
2072         {
2073           const double y = heading_rows + y_pos_sig * factor->n_vars;
2074           tab_text (t, 0, y, TAT_TITLE, _("Sig. (1-tailed)"));
2075
2076           for (i = 0; i < factor->n_vars; ++i)
2077             {
2078               for (j = 0; j < factor->n_vars; ++j)
2079                 {
2080                   double rho = gsl_matrix_get (idata->mm.corr, i, j);
2081                   double w = gsl_matrix_get (idata->mm.n, i, j);
2082
2083                   if (i == j)
2084                     continue;
2085
2086                   tab_double (t, heading_columns + j,  y + i, 0, significance_of_correlation (rho, w), NULL, RC_PVALUE);
2087                 }
2088             }
2089         }
2090     }
2091
2092   if (factor->print & PRINT_DETERMINANT)
2093     {
2094       tab_text (t, 0, nr, TAB_LEFT | TAT_TITLE, _("Determinant"));
2095
2096       tab_double (t, 1, nr, 0, idata->detR, NULL, RC_OTHER);
2097     }
2098
2099   tab_submit (t);
2100 }
2101
2102 static void
2103 show_covariance_matrix (const struct cmd_factor *factor, const struct idata *idata)
2104 {
2105   struct tab_table *t ;
2106   size_t i, j;
2107   int y_pos_corr = -1;
2108   int suffix_rows = 0;
2109
2110   const int heading_rows = 1;
2111   const int heading_columns = 1;
2112
2113   int nc = heading_columns ;
2114   int nr = heading_rows ;
2115   int n_data_sets = 0;
2116
2117   if (factor->print & PRINT_COVARIANCE)
2118     {
2119       y_pos_corr = n_data_sets;
2120       n_data_sets++;
2121       nc = heading_columns + factor->n_vars;
2122     }
2123
2124   nr += n_data_sets * factor->n_vars;
2125
2126   /* If the table would contain only headings, don't bother rendering it */
2127   if (nr <= heading_rows && suffix_rows == 0)
2128     return;
2129
2130   t = tab_create (nc, nr + suffix_rows);
2131
2132   tab_title (t, _("Covariance Matrix"));
2133
2134   tab_hline (t, TAL_1, 0, nc - 1, heading_rows);
2135
2136   if (nr > heading_rows)
2137     {
2138       tab_headers (t, heading_columns, 0, heading_rows, 0);
2139
2140       tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
2141
2142       /* Outline the box */
2143       tab_box (t,
2144                TAL_2, TAL_2,
2145                -1, -1,
2146                0, 0,
2147                nc - 1, nr - 1);
2148
2149       /* Vertical lines */
2150       tab_box (t,
2151                -1, -1,
2152                -1, TAL_1,
2153                heading_columns, 0,
2154                nc - 1, nr - 1);
2155
2156
2157       for (i = 0; i < factor->n_vars; ++i)
2158         tab_text (t, heading_columns + i, 0, TAT_TITLE, var_to_string (factor->vars[i]));
2159
2160
2161       for (i = 0 ; i < n_data_sets; ++i)
2162         {
2163           int y = heading_rows + i * factor->n_vars;
2164           size_t v;
2165           for (v = 0; v < factor->n_vars; ++v)
2166             tab_text (t, heading_columns -1, y + v, TAT_TITLE, var_to_string (factor->vars[v]));
2167
2168           tab_hline (t, TAL_1, 0, nc - 1, y);
2169         }
2170
2171       if (factor->print & PRINT_COVARIANCE)
2172         {
2173           const double y = heading_rows + y_pos_corr;
2174
2175           for (i = 0; i < factor->n_vars; ++i)
2176             {
2177               for (j = 0; j < factor->n_vars; ++j)
2178                 tab_double (t, heading_columns + j,  y + i, 0, gsl_matrix_get (idata->mm.cov, i, j), NULL, RC_OTHER);
2179             }
2180         }
2181     }
2182
2183   tab_submit (t);
2184 }
2185
2186
2187 static void
2188 do_factor (const struct cmd_factor *factor, struct casereader *r)
2189 {
2190   struct ccase *c;
2191   struct idata *idata = idata_alloc (factor->n_vars);
2192
2193   idata->cvm = covariance_1pass_create (factor->n_vars, factor->vars,
2194                                               factor->wv, factor->exclude);
2195
2196   for ( ; (c = casereader_read (r) ); case_unref (c))
2197     {
2198       covariance_accumulate (idata->cvm, c);
2199     }
2200
2201   idata->mm.cov = covariance_calculate (idata->cvm);
2202
2203   if (idata->mm.cov == NULL)
2204     {
2205       msg (MW, _("The dataset contains no complete observations. No analysis will be performed."));
2206       covariance_destroy (idata->cvm);
2207       goto finish;
2208     }
2209
2210   idata->mm.var_matrix = covariance_moments (idata->cvm, MOMENT_VARIANCE);
2211   idata->mm.mean_matrix = covariance_moments (idata->cvm, MOMENT_MEAN);
2212   idata->mm.n = covariance_moments (idata->cvm, MOMENT_NONE);
2213
2214   do_factor_by_matrix (factor, idata);
2215
2216  finish:
2217   gsl_matrix_free (idata->mm.corr);
2218   gsl_matrix_free (idata->mm.cov);
2219
2220   idata_free (idata);
2221   casereader_destroy (r);
2222 }
2223
2224 static void
2225 do_factor_by_matrix (const struct cmd_factor *factor, struct idata *idata)
2226 {
2227   if (idata->mm.cov && !idata->mm.corr)
2228     idata->mm.corr = correlation_from_covariance (idata->mm.cov, idata->mm.var_matrix);
2229   if (idata->mm.corr && !idata->mm.cov)
2230     idata->mm.cov = covariance_from_correlation (idata->mm.corr, idata->mm.var_matrix);
2231   if (factor->method == METHOD_CORR)
2232     idata->analysis_matrix = idata->mm.corr;
2233   else
2234     idata->analysis_matrix = idata->mm.cov;
2235
2236   if (factor->print & PRINT_DETERMINANT
2237       || factor->print & PRINT_KMO)
2238     {
2239       int sign = 0;
2240
2241       const int size = idata->mm.corr->size1;
2242       gsl_permutation *p = gsl_permutation_calloc (size);
2243       gsl_matrix *tmp = gsl_matrix_calloc (size, size);
2244       gsl_matrix_memcpy (tmp, idata->mm.corr);
2245
2246       gsl_linalg_LU_decomp (tmp, p, &sign);
2247       idata->detR = gsl_linalg_LU_det (tmp, sign);
2248       gsl_permutation_free (p);
2249       gsl_matrix_free (tmp);
2250     }
2251
2252   if ( factor->print & PRINT_UNIVARIATE)
2253     {
2254       const struct fmt_spec *wfmt = factor->wv ? var_get_print_format (factor->wv) : & F_8_0;
2255       const int nc = 4;
2256       int i;
2257
2258       const int heading_columns = 1;
2259       const int heading_rows = 1;
2260
2261       const int nr = heading_rows + factor->n_vars;
2262
2263       struct tab_table *t = tab_create (nc, nr);
2264       tab_set_format (t, RC_WEIGHT, wfmt);
2265       tab_title (t, _("Descriptive Statistics"));
2266
2267       tab_headers (t, heading_columns, 0, heading_rows, 0);
2268
2269       /* Outline the box */
2270       tab_box (t,
2271                TAL_2, TAL_2,
2272                -1, -1,
2273                0, 0,
2274                nc - 1, nr - 1);
2275
2276       /* Vertical lines */
2277       tab_box (t,
2278                -1, -1,
2279                -1, TAL_1,
2280                heading_columns, 0,
2281                nc - 1, nr - 1);
2282
2283       tab_hline (t, TAL_1, 0, nc - 1, heading_rows);
2284       tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
2285
2286       tab_text (t, 1, 0, TAB_CENTER | TAT_TITLE, _("Mean"));
2287       tab_text (t, 2, 0, TAB_CENTER | TAT_TITLE, _("Std. Deviation"));
2288       tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("Analysis N"));
2289
2290       for (i = 0 ; i < factor->n_vars; ++i)
2291         {
2292           const struct variable *v = factor->vars[i];
2293           tab_text (t, 0, i + heading_rows, TAB_LEFT | TAT_TITLE, var_to_string (v));
2294
2295           tab_double (t, 1, i + heading_rows, 0, gsl_matrix_get (idata->mm.mean_matrix, i, i), NULL, RC_OTHER);
2296           tab_double (t, 2, i + heading_rows, 0, sqrt (gsl_matrix_get (idata->mm.var_matrix, i, i)), NULL, RC_OTHER);
2297           tab_double (t, 3, i + heading_rows, 0, gsl_matrix_get (idata->mm.n, i, i), NULL, RC_WEIGHT);
2298         }
2299
2300       tab_submit (t);
2301     }
2302
2303   if (factor->print & PRINT_KMO)
2304     {
2305       int i;
2306       double sum_ssq_r = 0;
2307       double sum_ssq_a = 0;
2308
2309       double df = factor->n_vars * (factor->n_vars - 1) / 2;
2310
2311       double w = 0;
2312
2313
2314       double xsq;
2315
2316       const int heading_columns = 2;
2317       const int heading_rows = 0;
2318
2319       const int nr = heading_rows + 4;
2320       const int nc = heading_columns + 1;
2321
2322       gsl_matrix *a, *x;
2323
2324       struct tab_table *t = tab_create (nc, nr);
2325       tab_title (t, _("KMO and Bartlett's Test"));
2326
2327       x  = clone_matrix (idata->mm.corr);
2328       gsl_linalg_cholesky_decomp (x);
2329       gsl_linalg_cholesky_invert (x);
2330
2331       a = anti_image (x);
2332
2333       for (i = 0; i < x->size1; ++i)
2334         {
2335           sum_ssq_r += ssq_od_n (x, i);
2336           sum_ssq_a += ssq_od_n (a, i);
2337         }
2338
2339       gsl_matrix_free (a);
2340       gsl_matrix_free (x);
2341
2342       tab_headers (t, heading_columns, 0, heading_rows, 0);
2343
2344       /* Outline the box */
2345       tab_box (t,
2346                TAL_2, TAL_2,
2347                -1, -1,
2348                0, 0,
2349                nc - 1, nr - 1);
2350
2351       tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
2352
2353       tab_text (t, 0, 0, TAT_TITLE | TAB_LEFT, _("Kaiser-Meyer-Olkin Measure of Sampling Adequacy"));
2354
2355       tab_double (t, 2, 0, 0, sum_ssq_r /  (sum_ssq_r + sum_ssq_a), NULL, RC_OTHER);
2356
2357       tab_text (t, 0, 1, TAT_TITLE | TAB_LEFT, _("Bartlett's Test of Sphericity"));
2358
2359       tab_text (t, 1, 1, TAT_TITLE, _("Approx. Chi-Square"));
2360       tab_text (t, 1, 2, TAT_TITLE, _("df"));
2361       tab_text (t, 1, 3, TAT_TITLE, _("Sig."));
2362
2363
2364       /* The literature doesn't say what to do for the value of W when
2365          missing values are involved.  The best thing I can think of
2366          is to take the mean average. */
2367       w = 0;
2368       for (i = 0; i < idata->mm.n->size1; ++i)
2369         w += gsl_matrix_get (idata->mm.n, i, i);
2370       w /= idata->mm.n->size1;
2371
2372       xsq = w - 1 - (2 * factor->n_vars + 5) / 6.0;
2373       xsq *= -log (idata->detR);
2374
2375       tab_double (t, 2, 1, 0, xsq, NULL, RC_OTHER);
2376       tab_double (t, 2, 2, 0, df, NULL, RC_INTEGER);
2377       tab_double (t, 2, 3, 0, gsl_cdf_chisq_Q (xsq, df), NULL, RC_PVALUE);
2378
2379
2380       tab_submit (t);
2381     }
2382
2383   show_correlation_matrix (factor, idata);
2384   show_covariance_matrix (factor, idata);
2385   if (idata->cvm)
2386     covariance_destroy (idata->cvm);
2387
2388   {
2389     gsl_matrix *am = matrix_dup (idata->analysis_matrix);
2390     gsl_eigen_symmv_workspace *workspace = gsl_eigen_symmv_alloc (factor->n_vars);
2391
2392     gsl_eigen_symmv (am, idata->eval, idata->evec, workspace);
2393
2394     gsl_eigen_symmv_free (workspace);
2395     gsl_matrix_free (am);
2396   }
2397
2398   gsl_eigen_symmv_sort (idata->eval, idata->evec, GSL_EIGEN_SORT_ABS_DESC);
2399
2400   idata->n_extractions = n_extracted_factors (factor, idata);
2401
2402   if (idata->n_extractions == 0)
2403     {
2404       msg (MW, _("The %s criteria result in zero factors extracted. Therefore no analysis will be performed."), "FACTOR");
2405       goto finish;
2406     }
2407
2408   if (idata->n_extractions > factor->n_vars)
2409     {
2410       msg (MW,
2411            _("The %s criteria result in more factors than variables, which is not meaningful. No analysis will be performed."),
2412            "FACTOR");
2413       goto finish;
2414     }
2415
2416   {
2417     gsl_matrix *rotated_factors = NULL;
2418     gsl_matrix *pattern_matrix = NULL;
2419     gsl_matrix *fcm = NULL;
2420     gsl_vector *rotated_loadings = NULL;
2421
2422     const gsl_vector *extracted_eigenvalues = NULL;
2423     gsl_vector *initial_communalities = gsl_vector_alloc (factor->n_vars);
2424     gsl_vector *extracted_communalities = gsl_vector_alloc (factor->n_vars);
2425     size_t i;
2426     struct factor_matrix_workspace *fmw = factor_matrix_workspace_alloc (idata->msr->size, idata->n_extractions);
2427     gsl_matrix *factor_matrix = gsl_matrix_calloc (factor->n_vars, fmw->n_factors);
2428
2429     if ( factor->extraction == EXTRACTION_PAF)
2430       {
2431         gsl_vector *diff = gsl_vector_alloc (idata->msr->size);
2432         struct smr_workspace *ws = ws_create (idata->analysis_matrix);
2433
2434         for (i = 0 ; i < factor->n_vars ; ++i)
2435           {
2436             double r2 = squared_multiple_correlation (idata->analysis_matrix, i, ws);
2437
2438             gsl_vector_set (idata->msr, i, r2);
2439           }
2440         ws_destroy (ws);
2441
2442         gsl_vector_memcpy (initial_communalities, idata->msr);
2443
2444         for (i = 0; i < factor->extraction_iterations; ++i)
2445           {
2446             double min, max;
2447             gsl_vector_memcpy (diff, idata->msr);
2448
2449             iterate_factor_matrix (idata->analysis_matrix, idata->msr, factor_matrix, fmw);
2450
2451             gsl_vector_sub (diff, idata->msr);
2452
2453             gsl_vector_minmax (diff, &min, &max);
2454
2455             if ( fabs (min) < factor->econverge && fabs (max) < factor->econverge)
2456               break;
2457           }
2458         gsl_vector_free (diff);
2459
2460
2461
2462         gsl_vector_memcpy (extracted_communalities, idata->msr);
2463         extracted_eigenvalues = fmw->eval;
2464       }
2465     else if (factor->extraction == EXTRACTION_PC)
2466       {
2467         for (i = 0; i < factor->n_vars; ++i)
2468           gsl_vector_set (initial_communalities, i, communality (idata, i, factor->n_vars));
2469
2470         gsl_vector_memcpy (extracted_communalities, initial_communalities);
2471
2472         iterate_factor_matrix (idata->analysis_matrix, extracted_communalities, factor_matrix, fmw);
2473
2474
2475         extracted_eigenvalues = idata->eval;
2476       }
2477
2478
2479     show_communalities (factor, initial_communalities, extracted_communalities);
2480
2481
2482     if ( factor->rotation != ROT_NONE)
2483       {
2484         rotated_factors = gsl_matrix_calloc (factor_matrix->size1, factor_matrix->size2);
2485         rotated_loadings = gsl_vector_calloc (factor_matrix->size2);
2486         if (factor->rotation == ROT_PROMAX)
2487           {
2488             pattern_matrix = gsl_matrix_calloc (factor_matrix->size1, factor_matrix->size2);
2489             fcm = gsl_matrix_calloc (factor_matrix->size2, factor_matrix->size2);
2490           }
2491
2492
2493         rotate (factor, factor_matrix, extracted_communalities, rotated_factors, rotated_loadings, pattern_matrix, fcm);
2494       }
2495
2496     show_explained_variance (factor, idata, idata->eval, extracted_eigenvalues, rotated_loadings);
2497
2498     factor_matrix_workspace_free (fmw);
2499
2500     show_scree (factor, idata);
2501
2502     show_factor_matrix (factor, idata,
2503                         factor->extraction == EXTRACTION_PC ? _("Component Matrix") : _("Factor Matrix"),
2504                         factor_matrix);
2505
2506     if ( factor->rotation == ROT_PROMAX)
2507       {
2508         show_factor_matrix (factor, idata, _("Pattern Matrix"),  pattern_matrix);
2509         gsl_matrix_free (pattern_matrix);
2510       }
2511
2512     if ( factor->rotation != ROT_NONE)
2513       {
2514         show_factor_matrix (factor, idata,
2515                             (factor->rotation == ROT_PROMAX) ? _("Structure Matrix") :
2516                             (factor->extraction == EXTRACTION_PC ? _("Rotated Component Matrix") :
2517                              _("Rotated Factor Matrix")),
2518                             rotated_factors);
2519
2520         gsl_matrix_free (rotated_factors);
2521       }
2522
2523     if ( factor->rotation == ROT_PROMAX)
2524       {
2525         show_factor_correlation (factor, fcm);
2526         gsl_matrix_free (fcm);
2527       }
2528
2529     gsl_matrix_free (factor_matrix);
2530     gsl_vector_free (rotated_loadings);
2531     gsl_vector_free (initial_communalities);
2532     gsl_vector_free (extracted_communalities);
2533   }
2534
2535  finish:
2536   return;
2537 }
2538
2539