eae6840f3b2f66716a61582e8863ee9746c673bb
[pspp-builds.git] / src / language / stats / factor.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2009, 2010 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16
17 #include <config.h>
18
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
27 #include <math/covariance.h>
28
29 #include <math/correlation.h>
30 #include <math/moments.h>
31 #include <data/procedure.h>
32 #include <language/lexer/variable-parser.h>
33 #include <language/lexer/value-parser.h>
34 #include <language/command.h>
35 #include <language/lexer/lexer.h>
36
37 #include <data/casegrouper.h>
38 #include <data/casereader.h>
39 #include <data/casewriter.h>
40 #include <data/dictionary.h>
41 #include <data/format.h>
42 #include <data/subcase.h>
43
44 #include <libpspp/misc.h>
45 #include <libpspp/message.h>
46
47 #include <output/tab.h>
48
49 #include <output/charts/scree.h>
50 #include <output/chart-item.h>
51
52 #include "gettext.h"
53 #define _(msgid) gettext (msgid)
54 #define N_(msgid) msgid
55
56 enum method
57   {
58     METHOD_CORR,
59     METHOD_COV
60   };
61
62 enum missing_type
63   {
64     MISS_LISTWISE,
65     MISS_PAIRWISE,
66     MISS_MEANSUB,
67   };
68
69 enum extraction_method
70   {
71     EXTRACTION_PC,
72     EXTRACTION_PAF,
73   };
74
75 enum plot_opts
76   {
77     PLOT_SCREE = 0x0001,
78     PLOT_ROTATION = 0x0002
79   };
80
81 enum print_opts
82   {
83     PRINT_UNIVARIATE  = 0x0001,
84     PRINT_DETERMINANT = 0x0002,
85     PRINT_INV         = 0x0004,
86     PRINT_AIC         = 0x0008,
87     PRINT_SIG         = 0x0010,
88     PRINT_COVARIANCE  = 0x0020,
89     PRINT_CORRELATION = 0x0040,
90     PRINT_ROTATION    = 0x0080,
91     PRINT_EXTRACTION  = 0x0100,
92     PRINT_INITIAL     = 0x0200,
93     PRINT_KMO         = 0x0400,
94     PRINT_REPR        = 0x0800, 
95     PRINT_FSCORE      = 0x1000
96   };
97
98 enum rotation_type
99   {
100     ROT_VARIMAX = 0,
101     ROT_EQUAMAX,
102     ROT_QUARTIMAX,
103     ROT_NONE
104   };
105
106 typedef void (*rotation_coefficients) (double *x, double *y,
107                                     double a, double b, double c, double d,
108                                     const gsl_matrix *loadings );
109
110
111 static void
112 varimax_coefficients (double *x, double *y,
113                       double a, double b, double c, double d,
114                       const gsl_matrix *loadings )
115 {
116   *x = d - 2 * a * b / loadings->size1;
117   *y = c - (a * a - b * b) / loadings->size1;
118 }
119
120 static void
121 equamax_coefficients (double *x, double *y,
122                       double a, double b, double c, double d,
123                       const gsl_matrix *loadings )
124 {
125   *x = d - loadings->size2 * a * b / loadings->size1;
126   *y = c - loadings->size2 * (a * a - b * b) / (2 * loadings->size1);
127 }
128
129 static void
130 quartimax_coefficients (double *x, double *y,
131                       double a UNUSED, double b UNUSED, double c, double d,
132                       const gsl_matrix *loadings UNUSED)
133 {
134   *x = d ;
135   *y = c ;
136 }
137
138 static const rotation_coefficients rotation_coeff[3] = {
139   varimax_coefficients,
140   equamax_coefficients,
141   quartimax_coefficients
142 };
143
144
145 struct cmd_factor 
146 {
147   size_t n_vars;
148   const struct variable **vars;
149
150   const struct variable *wv;
151
152   enum method method;
153   enum missing_type missing_type;
154   enum mv_class exclude;
155   enum print_opts print;
156   enum extraction_method extraction;
157   enum plot_opts plot;
158   enum rotation_type rotation;
159
160   /* Extraction Criteria */
161   int n_factors;
162   double min_eigen;
163   double econverge;
164   int iterations;
165
166   double rconverge;
167
168   /* Format */
169   double blank;
170   bool sort;
171 };
172
173 struct idata
174 {
175   /* Intermediate values used in calculation */
176
177   const gsl_matrix *corr ;  /* The correlation matrix */
178   gsl_matrix *cov ;         /* The covariance matrix */
179   const gsl_matrix *n ;     /* Matrix of number of samples */
180
181   gsl_vector *eval ;  /* The eigenvalues */
182   gsl_matrix *evec ;  /* The eigenvectors */
183
184   int n_extractions;
185
186   gsl_vector *msr ;  /* Multiple Squared Regressions */
187 };
188
189 static struct idata *
190 idata_alloc (size_t n_vars)
191 {
192   struct idata *id = xzalloc (sizeof (*id));
193
194   id->n_extractions = 0;
195   id->msr = gsl_vector_alloc (n_vars);
196
197   id->eval = gsl_vector_alloc (n_vars);
198   id->evec = gsl_matrix_alloc (n_vars, n_vars);
199
200   return id;
201 }
202
203 static void
204 idata_free (struct idata *id)
205 {
206   gsl_vector_free (id->msr);
207   gsl_vector_free (id->eval);
208   gsl_matrix_free (id->evec);
209   if (id->cov != NULL)
210     gsl_matrix_free (id->cov);
211
212   free (id);
213 }
214
215
216 #if 0
217 static void
218 dump_matrix (const gsl_matrix *m)
219 {
220   size_t i, j;
221
222   for (i = 0 ; i < m->size1; ++i)
223     {
224       for (j = 0 ; j < m->size2; ++j)
225         printf ("%02f ", gsl_matrix_get (m, i, j));
226       printf ("\n");
227     }
228 }
229
230
231 static void
232 dump_matrix_permute (const gsl_matrix *m, const gsl_permutation *p)
233 {
234   size_t i, j;
235
236   for (i = 0 ; i < m->size1; ++i)
237     {
238       for (j = 0 ; j < m->size2; ++j)
239         printf ("%02f ", gsl_matrix_get (m, gsl_permutation_get (p, i), j));
240       printf ("\n");
241     }
242 }
243
244
245 static void
246 dump_vector (const gsl_vector *v)
247 {
248   size_t i;
249   for (i = 0 ; i < v->size; ++i)
250     {
251       printf ("%02f\n", gsl_vector_get (v, i));
252     }
253   printf ("\n");
254 }
255 #endif
256
257
258 static int 
259 n_extracted_factors (const struct cmd_factor *factor, struct idata *idata)
260 {
261   int i;
262   
263   /* If there is a cached value, then return that. */
264   if ( idata->n_extractions != 0)
265     return idata->n_extractions;
266
267   /* Otherwise, if the number of factors has been explicitly requested,
268      use that. */
269   if (factor->n_factors > 0)
270     {
271       idata->n_extractions = factor->n_factors;
272       goto finish;
273     }
274   
275   /* Use the MIN_EIGEN setting. */
276   for (i = 0 ; i < idata->eval->size; ++i)
277     {
278       double evali = fabs (gsl_vector_get (idata->eval, i));
279
280       idata->n_extractions = i;
281
282       if (evali < factor->min_eigen)
283         goto finish;
284     }
285
286  finish:
287   return idata->n_extractions;
288 }
289
290
291 /* Returns a newly allocated matrix identical to M.
292    It it the callers responsibility to free the returned value.
293 */
294 static gsl_matrix *
295 matrix_dup (const gsl_matrix *m)
296 {
297   gsl_matrix *n =  gsl_matrix_alloc (m->size1, m->size2);
298
299   gsl_matrix_memcpy (n, m);
300
301   return n;
302 }
303
304
305 struct smr_workspace
306 {
307   /* Copy of the subject */
308   gsl_matrix *m;
309   
310   gsl_matrix *inverse;
311
312   gsl_permutation *perm;
313
314   gsl_matrix *result1;
315   gsl_matrix *result2;
316 };
317
318
319 static struct smr_workspace *ws_create (const gsl_matrix *input)
320 {
321   struct smr_workspace *ws = xmalloc (sizeof (*ws));
322   
323   ws->m = gsl_matrix_alloc (input->size1, input->size2);
324   ws->inverse = gsl_matrix_calloc (input->size1 - 1, input->size2 - 1);
325   ws->perm = gsl_permutation_alloc (input->size1 - 1);
326   ws->result1 = gsl_matrix_calloc (input->size1 - 1, 1);
327   ws->result2 = gsl_matrix_calloc (1, 1);
328
329   return ws;
330 }
331
332 static void
333 ws_destroy (struct smr_workspace *ws)
334 {
335   gsl_matrix_free (ws->result2);
336   gsl_matrix_free (ws->result1);
337   gsl_permutation_free (ws->perm);
338   gsl_matrix_free (ws->inverse);
339   gsl_matrix_free (ws->m);
340
341   free (ws);
342 }
343
344
345 /* 
346    Return the square of the regression coefficient for VAR regressed against all other variables.
347  */
348 static double
349 squared_multiple_correlation (const gsl_matrix *corr, int var, struct smr_workspace *ws)
350 {
351   /* For an explanation of what this is doing, see 
352      http://www.visualstatistics.net/Visual%20Statistics%20Multimedia/multiple_regression_analysis.htm
353   */
354
355   int signum = 0;
356   gsl_matrix_view rxx;
357
358   gsl_matrix_memcpy (ws->m, corr);
359
360   gsl_matrix_swap_rows (ws->m, 0, var);
361   gsl_matrix_swap_columns (ws->m, 0, var);
362
363   rxx = gsl_matrix_submatrix (ws->m, 1, 1, ws->m->size1 - 1, ws->m->size1 - 1); 
364
365   gsl_linalg_LU_decomp (&rxx.matrix, ws->perm, &signum);
366
367   gsl_linalg_LU_invert (&rxx.matrix, ws->perm, ws->inverse);
368
369   {
370     gsl_matrix_const_view rxy = gsl_matrix_const_submatrix (ws->m, 1, 0, ws->m->size1 - 1, 1);
371     gsl_matrix_const_view ryx = gsl_matrix_const_submatrix (ws->m, 0, 1, 1, ws->m->size1 - 1);
372
373     gsl_blas_dgemm (CblasNoTrans,  CblasNoTrans,
374                     1.0, ws->inverse, &rxy.matrix, 0.0, ws->result1);
375
376     gsl_blas_dgemm (CblasNoTrans,  CblasNoTrans,
377                     1.0, &ryx.matrix, ws->result1, 0.0, ws->result2);
378   }
379
380   return gsl_matrix_get (ws->result2, 0, 0);
381 }
382
383
384
385 static double the_communality (const gsl_matrix *evec, const gsl_vector *eval, int n, int n_factors);
386
387
388 struct factor_matrix_workspace
389 {
390   size_t n_factors;
391   gsl_eigen_symmv_workspace *eigen_ws;
392
393   gsl_vector *eval ;
394   gsl_matrix *evec ;
395
396   gsl_matrix *gamma ;
397
398   gsl_matrix *r;
399 };
400
401 static struct factor_matrix_workspace *
402 factor_matrix_workspace_alloc (size_t n, size_t nf)
403 {
404   struct factor_matrix_workspace *ws = xmalloc (sizeof (*ws));
405
406   ws->n_factors = nf;
407   ws->gamma = gsl_matrix_calloc (nf, nf);
408   ws->eigen_ws = gsl_eigen_symmv_alloc (n);
409   ws->eval = gsl_vector_alloc (n);
410   ws->evec = gsl_matrix_alloc (n, n);
411   ws->r  = gsl_matrix_alloc (n, n);
412   
413   return ws;
414 }
415
416 static void
417 factor_matrix_workspace_free (struct factor_matrix_workspace *ws)
418 {
419   gsl_eigen_symmv_free (ws->eigen_ws);
420   gsl_vector_free (ws->eval);
421   gsl_matrix_free (ws->evec);
422   gsl_matrix_free (ws->gamma);
423   gsl_matrix_free (ws->r);
424   free (ws);
425 }
426
427 /*
428   Shift P left by OFFSET places, and overwrite TARGET
429   with the shifted result.
430   Positions in TARGET less than OFFSET are unchanged.
431 */
432 static void
433 perm_shift_apply (gsl_permutation *target, const gsl_permutation *p,
434                   size_t offset)
435 {
436   size_t i;
437   assert (target->size == p->size);
438   assert (offset <= target->size);
439
440   for (i = 0; i < target->size - offset; ++i)
441     {
442       target->data[i] = p->data [i + offset];
443     }
444 }
445
446
447 /* 
448    Indirectly sort the rows of matrix INPUT, storing the sort order in PERM.
449    The sort criteria are as follows:
450    
451    Rows are sorted on the first column, until the absolute value of an
452    element in a subsequent column  is greater than that of the first
453    column.  Thereafter, rows will be sorted on the second column,
454    until the absolute value of an element in a subsequent column
455    exceeds that of the second column ...
456 */
457 static void
458 sort_matrix_indirect (const gsl_matrix *input, gsl_permutation *perm)
459 {
460   const size_t n = perm->size;
461   const size_t m = input->size2;
462   int i, j;
463   gsl_matrix *mat ;
464   int column_n = 0;
465   int row_n = 0;
466   gsl_permutation *p;
467
468   assert (perm->size == input->size1);
469
470   p = gsl_permutation_alloc (n);
471
472   /* Copy INPUT into MAT, discarding the sign */
473   mat = gsl_matrix_alloc (n, m);
474   for (i = 0 ; i < mat->size1; ++i)
475     {
476       for (j = 0 ; j < mat->size2; ++j)
477         {
478           double x = gsl_matrix_get (input, i, j);
479           gsl_matrix_set (mat, i, j, fabs (x));
480         }
481     }
482
483   while (column_n < m && row_n < n) 
484     {
485       gsl_vector_const_view columni = gsl_matrix_const_column (mat, column_n);
486       gsl_sort_vector_index (p, &columni.vector);
487
488       for (i = 0 ; i < n; ++i)
489         {
490           gsl_vector_view row = gsl_matrix_row (mat, p->data[n - 1 - i]);
491           size_t maxindex = gsl_vector_max_index (&row.vector);
492           
493           if ( maxindex > column_n )
494             break;
495
496           /* All subsequent elements of this row, are of no interest.
497              So set them all to a highly negative value */
498           for (j = column_n + 1; j < row.vector.size ; ++j)
499             gsl_vector_set (&row.vector, j, -DBL_MAX);
500         }
501
502       perm_shift_apply (perm, p, row_n);
503       row_n += i;
504
505       column_n++;
506     }
507
508   gsl_permutation_free (p);
509   gsl_matrix_free (mat);
510   
511   assert ( 0 == gsl_permutation_valid (perm));
512
513   /* We want the biggest value to be first */
514   gsl_permutation_reverse (perm);    
515 }
516
517
518 static void
519 drot_go (double phi, double *l0, double *l1)
520 {
521   double r0 = cos (phi) * *l0 + sin (phi) * *l1;
522   double r1 = - sin (phi) * *l0 + cos (phi) * *l1;
523
524   *l0 = r0;
525   *l1 = r1;
526 }
527
528
529 static gsl_matrix *
530 clone_matrix (const gsl_matrix *m)
531 {
532   int j, k;
533   gsl_matrix *c = gsl_matrix_calloc (m->size1, m->size2);
534
535   for (j = 0 ; j < c->size1; ++j)
536     {
537       for (k = 0 ; k < c->size2; ++k)
538         {
539           const double *v = gsl_matrix_const_ptr (m, j, k);
540           gsl_matrix_set (c, j, k, *v);
541         }
542     }
543
544   return c;
545 }
546
547
548 static double 
549 initial_sv (const gsl_matrix *fm)
550 {
551   int j, k;
552
553   double sv = 0.0;
554   for (j = 0 ; j < fm->size2; ++j)
555     {
556       double l4s = 0;
557       double l2s = 0;
558
559       for (k = j + 1 ; k < fm->size2; ++k)
560         {
561           double lambda = gsl_matrix_get (fm, k, j);
562           double lambda_sq = lambda * lambda;
563           double lambda_4 = lambda_sq * lambda_sq;
564
565           l4s += lambda_4;
566           l2s += lambda_sq;
567         }
568       sv += ( fm->size1 * l4s - (l2s * l2s) ) / (fm->size1 * fm->size1 );
569     }
570   return sv;
571 }
572
573 static void
574 rotate (const struct cmd_factor *cf, const gsl_matrix *unrot,
575         const gsl_vector *communalities,
576         gsl_matrix *result,
577         gsl_vector *rotated_loadings
578         )
579 {
580   int j, k;
581   int i;
582   double prev_sv;
583
584   /* First get a normalised version of UNROT */
585   gsl_matrix *normalised = gsl_matrix_calloc (unrot->size1, unrot->size2);
586   gsl_matrix *h_sqrt = gsl_matrix_calloc (communalities->size, communalities->size);
587   gsl_matrix *h_sqrt_inv ;
588
589   /* H is the diagonal matrix containing the absolute values of the communalities */
590   for (i = 0 ; i < communalities->size ; ++i)
591     {
592       double *ptr = gsl_matrix_ptr (h_sqrt, i, i);
593       *ptr = fabs (gsl_vector_get (communalities, i));
594     }
595
596   /* Take the square root of the communalities */
597   gsl_linalg_cholesky_decomp (h_sqrt);
598
599
600   /* Save a copy of h_sqrt and invert it */
601   h_sqrt_inv = clone_matrix (h_sqrt);
602   gsl_linalg_cholesky_decomp (h_sqrt_inv);
603   gsl_linalg_cholesky_invert (h_sqrt_inv);
604
605   /* normalised vertion is H^{1/2} x UNROT */
606   gsl_blas_dgemm (CblasNoTrans,  CblasNoTrans, 1.0, h_sqrt_inv, unrot, 0.0, normalised);
607
608   gsl_matrix_free (h_sqrt_inv);
609
610
611   /* Now perform the rotation iterations */
612
613   prev_sv = initial_sv (normalised);
614   for (i = 0 ; i < cf->iterations ; ++i)
615     {
616       double sv = 0.0;
617       for (j = 0 ; j < normalised->size2; ++j)
618         {
619           /* These variables relate to the convergence criterium */
620           double l4s = 0;
621           double l2s = 0;
622
623           for (k = j + 1 ; k < normalised->size2; ++k)
624             {
625               int p;
626               double a = 0.0;
627               double b = 0.0;
628               double c = 0.0;
629               double d = 0.0;
630               double x, y;
631               double phi;
632
633               for (p = 0; p < normalised->size1; ++p)
634                 {
635                   double jv = gsl_matrix_get (normalised, p, j);
636                   double kv = gsl_matrix_get (normalised, p, k);
637               
638                   double u = jv * jv - kv * kv;
639                   double v = 2 * jv * kv;
640                   a += u;
641                   b += v;
642                   c +=  u * u - v * v;
643                   d += 2 * u * v;
644                 }
645
646               rotation_coeff [cf->rotation] (&x, &y, a, b, c, d, normalised);
647
648               phi = atan2 (x,  y) / 4.0 ;
649
650               /* Don't bother rotating if the angle is small */
651               if ( fabs (sin (phi) ) <= pow (10.0, -15.0))
652                   continue;
653
654               for (p = 0; p < normalised->size1; ++p)
655                 {
656                   double *lambda0 = gsl_matrix_ptr (normalised, p, j);
657                   double *lambda1 = gsl_matrix_ptr (normalised, p, k);
658                   drot_go (phi, lambda0, lambda1);
659                 }
660
661               /* Calculate the convergence criterium */
662               {
663                 double lambda = gsl_matrix_get (normalised, k, j);
664                 double lambda_sq = lambda * lambda;
665                 double lambda_4 = lambda_sq * lambda_sq;
666
667                 l4s += lambda_4;
668                 l2s += lambda_sq;
669               }
670             }
671           sv += ( normalised->size1 * l4s - (l2s * l2s) ) / (normalised->size1 * normalised->size1 );
672         }
673
674       if ( fabs (sv - prev_sv) <= cf->rconverge)
675         break;
676
677       prev_sv = sv;
678     }
679
680   gsl_blas_dgemm (CblasNoTrans,  CblasNoTrans, 1.0,
681                   h_sqrt, normalised,  0.0,   result);
682
683   gsl_matrix_free (h_sqrt);
684
685
686   /* reflect negative sums and populate the rotated loadings vector*/
687   for (i = 0 ; i < result->size2; ++i)
688     {
689       double ssq = 0.0;
690       double sum = 0.0;
691       for (j = 0 ; j < result->size1; ++j)
692         {
693           double s = gsl_matrix_get (result, j, i);
694           ssq += s * s;
695           sum += gsl_matrix_get (result, j, i);
696         }
697
698       gsl_vector_set (rotated_loadings, i, ssq);
699
700       if ( sum < 0 )
701         for (j = 0 ; j < result->size1; ++j)
702           {
703             double *lambda = gsl_matrix_ptr (result, j, i);
704             *lambda = - *lambda;
705           }
706     }
707 }
708
709
710 /*
711   Get an approximation for the factor matrix into FACTORS, and the communalities into COMMUNALITIES.
712   R is the matrix to be analysed.
713   WS is a pointer to a structure which must have been initialised with factor_matrix_workspace_init.
714  */
715 static void
716 iterate_factor_matrix (const gsl_matrix *r, gsl_vector *communalities, gsl_matrix *factors, 
717                        struct factor_matrix_workspace *ws)
718 {
719   size_t i;
720   gsl_matrix_view mv ;
721
722   assert (r->size1 == r->size2);
723   assert (r->size1 == communalities->size);
724
725   assert (factors->size1 == r->size1);
726   assert (factors->size2 == ws->n_factors);
727
728   gsl_matrix_memcpy (ws->r, r);
729
730   /* Apply Communalities to diagonal of correlation matrix */
731   for (i = 0 ; i < communalities->size ; ++i)
732     {
733       double *x = gsl_matrix_ptr (ws->r, i, i);
734       *x = gsl_vector_get (communalities, i);
735     }
736
737   gsl_eigen_symmv (ws->r, ws->eval, ws->evec, ws->eigen_ws);
738
739   mv = gsl_matrix_submatrix (ws->evec, 0, 0, ws->evec->size1, ws->n_factors);
740
741   /* Gamma is the diagonal matrix containing the absolute values of the eigenvalues */
742   for (i = 0 ; i < ws->n_factors ; ++i)
743     {
744       double *ptr = gsl_matrix_ptr (ws->gamma, i, i);
745       *ptr = fabs (gsl_vector_get (ws->eval, i));
746     }
747
748   /* Take the square root of gamma */
749   gsl_linalg_cholesky_decomp (ws->gamma);
750
751   gsl_blas_dgemm (CblasNoTrans,  CblasNoTrans, 1.0, &mv.matrix, ws->gamma, 0.0, factors);
752
753   for (i = 0 ; i < r->size1 ; ++i)
754     {
755       double h = the_communality (ws->evec, ws->eval, i, ws->n_factors);
756       gsl_vector_set (communalities, i, h);
757     }
758 }
759
760
761
762 static bool run_factor (struct dataset *ds, const struct cmd_factor *factor);
763
764
765 int
766 cmd_factor (struct lexer *lexer, struct dataset *ds)
767 {
768   bool extraction_seen = false;
769   const struct dictionary *dict = dataset_dict (ds);
770
771   struct cmd_factor factor;
772   factor.n_vars = 0;
773   factor.vars = NULL;
774   factor.method = METHOD_CORR;
775   factor.missing_type = MISS_LISTWISE;
776   factor.exclude = MV_ANY;
777   factor.print = PRINT_INITIAL | PRINT_EXTRACTION | PRINT_ROTATION;
778   factor.extraction = EXTRACTION_PC;
779   factor.n_factors = 0;
780   factor.min_eigen = SYSMIS;
781   factor.iterations = 25;
782   factor.econverge = 0.001;
783
784   factor.blank = 0;
785   factor.sort = false;
786   factor.plot = 0;
787   factor.rotation = ROT_VARIMAX;
788
789   factor.rconverge = 0.0001;
790
791   factor.wv = dict_get_weight (dict);
792
793   lex_match (lexer, T_SLASH);
794
795   if (!lex_force_match_id (lexer, "VARIABLES"))
796     {
797       goto error;
798     }
799
800   lex_match (lexer, T_EQUALS);
801
802   if (!parse_variables_const (lexer, dict, &factor.vars, &factor.n_vars,
803                               PV_NO_DUPLICATE | PV_NUMERIC))
804     goto error;
805
806   if (factor.n_vars < 2)
807     msg (MW, _("Factor analysis on a single variable is not useful."));
808
809   while (lex_token (lexer) != T_ENDCMD)
810     {
811       lex_match (lexer, T_SLASH);
812
813       if (lex_match_id (lexer, "PLOT"))
814         {
815           lex_match (lexer, T_EQUALS);
816           while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
817             {
818               if (lex_match_id (lexer, "EIGEN"))
819                 {
820                   factor.plot |= PLOT_SCREE;
821                 }
822 #if FACTOR_FULLY_IMPLEMENTED
823               else if (lex_match_id (lexer, "ROTATION"))
824                 {
825                 }
826 #endif
827               else
828                 {
829                   lex_error (lexer, NULL);
830                   goto error;
831                 }
832             }
833         }
834       else if (lex_match_id (lexer, "METHOD"))
835         {
836           lex_match (lexer, T_EQUALS);
837           while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
838             {
839               if (lex_match_id (lexer, "COVARIANCE"))
840                 {
841                   factor.method = METHOD_COV;
842                 }
843               else if (lex_match_id (lexer, "CORRELATION"))
844                 {
845                   factor.method = METHOD_CORR;
846                 }
847               else
848                 {
849                   lex_error (lexer, NULL);
850                   goto error;
851                 }
852             }
853         }
854       else if (lex_match_id (lexer, "ROTATION"))
855         {
856           lex_match (lexer, T_EQUALS);
857           while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
858             {
859               /* VARIMAX and DEFAULT are defaults */
860               if (lex_match_id (lexer, "VARIMAX") || lex_match_id (lexer, "DEFAULT"))
861                 {
862                   factor.rotation = ROT_VARIMAX;
863                 }
864               else if (lex_match_id (lexer, "EQUAMAX"))
865                 {
866                   factor.rotation = ROT_EQUAMAX;
867                 }
868               else if (lex_match_id (lexer, "QUARTIMAX"))
869                 {
870                   factor.rotation = ROT_QUARTIMAX;
871                 }
872               else if (lex_match_id (lexer, "NOROTATE"))
873                 {
874                   factor.rotation = ROT_NONE;
875                 }
876               else
877                 {
878                   lex_error (lexer, NULL);
879                   goto error;
880                 }
881             }
882         }
883       else if (lex_match_id (lexer, "CRITERIA"))
884         {
885           lex_match (lexer, T_EQUALS);
886           while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
887             {
888               if (lex_match_id (lexer, "FACTORS"))
889                 {
890                   if ( lex_force_match (lexer, T_LPAREN))
891                     {
892                       lex_force_int (lexer);
893                       factor.n_factors = lex_integer (lexer);
894                       lex_get (lexer);
895                       lex_force_match (lexer, T_RPAREN);
896                     }
897                 }
898               else if (lex_match_id (lexer, "MINEIGEN"))
899                 {
900                   if ( lex_force_match (lexer, T_LPAREN))
901                     {
902                       lex_force_num (lexer);
903                       factor.min_eigen = lex_number (lexer);
904                       lex_get (lexer);
905                       lex_force_match (lexer, T_RPAREN);
906                     }
907                 }
908               else if (lex_match_id (lexer, "ECONVERGE"))
909                 {
910                   if ( lex_force_match (lexer, T_LPAREN))
911                     {
912                       lex_force_num (lexer);
913                       factor.econverge = lex_number (lexer);
914                       lex_get (lexer);
915                       lex_force_match (lexer, T_RPAREN);
916                     }
917                 }
918               else if (lex_match_id (lexer, "RCONVERGE"))
919                 {
920                   if ( lex_force_match (lexer, T_LPAREN))
921                     {
922                       lex_force_num (lexer);
923                       factor.rconverge = lex_number (lexer);
924                       lex_get (lexer);
925                       lex_force_match (lexer, T_RPAREN);
926                     }
927                 }
928               else if (lex_match_id (lexer, "ITERATE"))
929                 {
930                   if ( lex_force_match (lexer, T_LPAREN))
931                     {
932                       lex_force_int (lexer);
933                       factor.iterations = lex_integer (lexer);
934                       lex_get (lexer);
935                       lex_force_match (lexer, T_RPAREN);
936                     }
937                 }
938               else if (lex_match_id (lexer, "DEFAULT"))
939                 {
940                   factor.n_factors = 0;
941                   factor.min_eigen = 1;
942                   factor.iterations = 25;
943                 }
944               else
945                 {
946                   lex_error (lexer, NULL);
947                   goto error;
948                 }
949             }
950         }
951       else if (lex_match_id (lexer, "EXTRACTION"))
952         {
953           extraction_seen = true;
954           lex_match (lexer, T_EQUALS);
955           while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
956             {
957               if (lex_match_id (lexer, "PAF"))
958                 {
959                   factor.extraction = EXTRACTION_PAF;
960                 }
961               else if (lex_match_id (lexer, "PC"))
962                 {
963                   factor.extraction = EXTRACTION_PC;
964                 }
965               else if (lex_match_id (lexer, "PA1"))
966                 {
967                   factor.extraction = EXTRACTION_PC;
968                 }
969               else if (lex_match_id (lexer, "DEFAULT"))
970                 {
971                   factor.extraction = EXTRACTION_PC;
972                 }
973               else
974                 {
975                   lex_error (lexer, NULL);
976                   goto error;
977                 }
978             }
979         }
980       else if (lex_match_id (lexer, "FORMAT"))
981         {
982           lex_match (lexer, T_EQUALS);
983           while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
984             {
985               if (lex_match_id (lexer, "SORT"))
986                 {
987                   factor.sort = true;
988                 }
989               else if (lex_match_id (lexer, "BLANK"))
990                 {
991                   if ( lex_force_match (lexer, T_LPAREN))
992                     {
993                       lex_force_num (lexer);
994                       factor.blank = lex_number (lexer);
995                       lex_get (lexer);
996                       lex_force_match (lexer, T_RPAREN);
997                     }
998                 }
999               else if (lex_match_id (lexer, "DEFAULT"))
1000                 {
1001                   factor.blank = 0;
1002                   factor.sort = false;
1003                 }
1004               else
1005                 {
1006                   lex_error (lexer, NULL);
1007                   goto error;
1008                 }
1009             }
1010         }
1011       else if (lex_match_id (lexer, "PRINT"))
1012         {
1013           factor.print = 0;
1014           lex_match (lexer, T_EQUALS);
1015           while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
1016             {
1017               if (lex_match_id (lexer, "UNIVARIATE"))
1018                 {
1019                   factor.print |= PRINT_UNIVARIATE;
1020                 }
1021               else if (lex_match_id (lexer, "DET"))
1022                 {
1023                   factor.print |= PRINT_DETERMINANT;
1024                 }
1025 #if FACTOR_FULLY_IMPLEMENTED
1026               else if (lex_match_id (lexer, "INV"))
1027                 {
1028                 }
1029               else if (lex_match_id (lexer, "AIC"))
1030                 {
1031                 }
1032 #endif
1033               else if (lex_match_id (lexer, "SIG"))
1034                 {
1035                   factor.print |= PRINT_SIG;
1036                 }
1037               else if (lex_match_id (lexer, "CORRELATION"))
1038                 {
1039                   factor.print |= PRINT_CORRELATION;
1040                 }
1041 #if FACTOR_FULLY_IMPLEMENTED
1042               else if (lex_match_id (lexer, "COVARIANCE"))
1043                 {
1044                 }
1045 #endif
1046               else if (lex_match_id (lexer, "ROTATION"))
1047                 {
1048                   factor.print |= PRINT_ROTATION;
1049                 }
1050               else if (lex_match_id (lexer, "EXTRACTION"))
1051                 {
1052                   factor.print |= PRINT_EXTRACTION;
1053                 }
1054               else if (lex_match_id (lexer, "INITIAL"))
1055                 {
1056                   factor.print |= PRINT_INITIAL;
1057                 }
1058 #if FACTOR_FULLY_IMPLEMENTED
1059               else if (lex_match_id (lexer, "KMO"))
1060                 {
1061                 }
1062               else if (lex_match_id (lexer, "REPR"))
1063                 {
1064                 }
1065               else if (lex_match_id (lexer, "FSCORE"))
1066                 {
1067                 }
1068 #endif
1069               else if (lex_match (lexer, T_ALL))
1070                 {
1071                   factor.print = 0xFFFF;
1072                 }
1073               else if (lex_match_id (lexer, "DEFAULT"))
1074                 {
1075                   factor.print |= PRINT_INITIAL ;
1076                   factor.print |= PRINT_EXTRACTION ;
1077                   factor.print |= PRINT_ROTATION ;
1078                 }
1079               else
1080                 {
1081                   lex_error (lexer, NULL);
1082                   goto error;
1083                 }
1084             }
1085         }
1086       else if (lex_match_id (lexer, "MISSING"))
1087         {
1088           lex_match (lexer, T_EQUALS);
1089           while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
1090             {
1091               if (lex_match_id (lexer, "INCLUDE"))
1092                 {
1093                   factor.exclude = MV_SYSTEM;
1094                 }
1095               else if (lex_match_id (lexer, "EXCLUDE"))
1096                 {
1097                   factor.exclude = MV_ANY;
1098                 }
1099               else if (lex_match_id (lexer, "LISTWISE"))
1100                 {
1101                   factor.missing_type = MISS_LISTWISE;
1102                 }
1103               else if (lex_match_id (lexer, "PAIRWISE"))
1104                 {
1105                   factor.missing_type = MISS_PAIRWISE;
1106                 }
1107               else if (lex_match_id (lexer, "MEANSUB"))
1108                 {
1109                   factor.missing_type = MISS_MEANSUB;
1110                 }
1111               else
1112                 {
1113                   lex_error (lexer, NULL);
1114                   goto error;
1115                 }
1116             }
1117         }
1118       else
1119         {
1120           lex_error (lexer, NULL);
1121           goto error;
1122         }
1123     }
1124
1125   if ( factor.rotation == ROT_NONE )
1126     factor.print &= ~PRINT_ROTATION;
1127
1128   if ( ! run_factor (ds, &factor)) 
1129     goto error;
1130
1131   free (factor.vars);
1132   return CMD_SUCCESS;
1133
1134  error:
1135   free (factor.vars);
1136   return CMD_FAILURE;
1137 }
1138
1139 static void do_factor (const struct cmd_factor *factor, struct casereader *group);
1140
1141
1142 static bool
1143 run_factor (struct dataset *ds, const struct cmd_factor *factor)
1144 {
1145   struct dictionary *dict = dataset_dict (ds);
1146   bool ok;
1147   struct casereader *group;
1148
1149   struct casegrouper *grouper = casegrouper_create_splits (proc_open (ds), dict);
1150
1151   while (casegrouper_get_next_group (grouper, &group))
1152     {
1153       if ( factor->missing_type == MISS_LISTWISE )
1154         group  = casereader_create_filter_missing (group, factor->vars, factor->n_vars,
1155                                                    factor->exclude,
1156                                                    NULL,  NULL);
1157       do_factor (factor, group);
1158     }
1159
1160   ok = casegrouper_destroy (grouper);
1161   ok = proc_commit (ds) && ok;
1162
1163   return ok;
1164 }
1165
1166
1167 /* Return the communality of variable N, calculated to N_FACTORS */
1168 static double
1169 the_communality (const gsl_matrix *evec, const gsl_vector *eval, int n, int n_factors)
1170 {
1171   size_t i;
1172
1173   double comm = 0;
1174
1175   assert (n >= 0);
1176   assert (n < eval->size);
1177   assert (n < evec->size1);
1178   assert (n_factors <= eval->size);
1179
1180   for (i = 0 ; i < n_factors; ++i)
1181     {
1182       double evali = fabs (gsl_vector_get (eval, i));
1183
1184       double eveci = gsl_matrix_get (evec, n, i);
1185
1186       comm += pow2 (eveci) * evali;
1187     }
1188
1189   return comm;
1190 }
1191
1192 /* Return the communality of variable N, calculated to N_FACTORS */
1193 static double
1194 communality (struct idata *idata, int n, int n_factors)
1195 {
1196   return the_communality (idata->evec, idata->eval, n, n_factors);
1197 }
1198
1199
1200 static void
1201 show_scree (const struct cmd_factor *f, struct idata *idata)
1202 {
1203   struct scree *s;
1204   const char *label ;
1205
1206   if ( !(f->plot & PLOT_SCREE) )
1207     return;
1208
1209
1210   label = f->extraction == EXTRACTION_PC ? _("Component Number") : _("Factor Number");
1211
1212   s = scree_create (idata->eval, label);
1213
1214   scree_submit (s);
1215 }
1216
1217 static void
1218 show_communalities (const struct cmd_factor * factor,
1219                     const gsl_vector *initial, const gsl_vector *extracted)
1220 {
1221   int i;
1222   int c = 0;
1223   const int heading_columns = 1;
1224   int nc = heading_columns;
1225   const int heading_rows = 1;
1226   const int nr = heading_rows + factor->n_vars;
1227   struct tab_table *t;
1228
1229   if (factor->print & PRINT_EXTRACTION)
1230     nc++;
1231
1232   if (factor->print & PRINT_INITIAL)
1233     nc++;
1234
1235   /* No point having a table with only headings */
1236   if (nc <= 1)
1237     return;
1238
1239   t = tab_create (nc, nr);
1240
1241   tab_title (t, _("Communalities"));
1242
1243   tab_headers (t, heading_columns, 0, heading_rows, 0);
1244
1245   c = 1;
1246   if (factor->print & PRINT_INITIAL)
1247     tab_text (t, c++, 0, TAB_CENTER | TAT_TITLE, _("Initial"));
1248
1249   if (factor->print & PRINT_EXTRACTION)
1250     tab_text (t, c++, 0, TAB_CENTER | TAT_TITLE, _("Extraction"));
1251
1252   /* Outline the box */
1253   tab_box (t,
1254            TAL_2, TAL_2,
1255            -1, -1,
1256            0, 0,
1257            nc - 1, nr - 1);
1258
1259   /* Vertical lines */
1260   tab_box (t,
1261            -1, -1,
1262            -1, TAL_1,
1263            heading_columns, 0,
1264            nc - 1, nr - 1);
1265
1266   tab_hline (t, TAL_1, 0, nc - 1, heading_rows);
1267   tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
1268
1269   for (i = 0 ; i < factor->n_vars; ++i)
1270     {
1271       c = 0;
1272       tab_text (t, c++, i + heading_rows, TAT_TITLE, var_to_string (factor->vars[i]));
1273
1274       if (factor->print & PRINT_INITIAL)
1275         tab_double (t, c++, i + heading_rows, 0, gsl_vector_get (initial, i), NULL);
1276
1277       if (factor->print & PRINT_EXTRACTION)
1278         tab_double (t, c++, i + heading_rows, 0, gsl_vector_get (extracted, i), NULL);
1279     }
1280
1281   tab_submit (t);
1282 }
1283
1284
1285 static void
1286 show_factor_matrix (const struct cmd_factor *factor, struct idata *idata, const char *title, const gsl_matrix *fm)
1287 {
1288   int i;
1289   const int n_factors = idata->n_extractions;
1290
1291   const int heading_columns = 1;
1292   const int heading_rows = 2;
1293   const int nr = heading_rows + factor->n_vars;
1294   const int nc = heading_columns + n_factors;
1295   gsl_permutation *perm;
1296
1297   struct tab_table *t = tab_create (nc, nr);
1298
1299   /* 
1300   if ( factor->extraction == EXTRACTION_PC )
1301     tab_title (t, _("Component Matrix"));
1302   else 
1303     tab_title (t, _("Factor Matrix"));
1304   */
1305
1306   tab_title (t, title);
1307
1308   tab_headers (t, heading_columns, 0, heading_rows, 0);
1309
1310   if ( factor->extraction == EXTRACTION_PC )
1311     tab_joint_text (t,
1312                     1, 0,
1313                     nc - 1, 0,
1314                     TAB_CENTER | TAT_TITLE, _("Component"));
1315   else
1316     tab_joint_text (t,
1317                     1, 0,
1318                     nc - 1, 0,
1319                     TAB_CENTER | TAT_TITLE, _("Factor"));
1320
1321
1322   tab_hline (t, TAL_1, heading_columns, nc - 1, 1);
1323
1324
1325   /* Outline the box */
1326   tab_box (t,
1327            TAL_2, TAL_2,
1328            -1, -1,
1329            0, 0,
1330            nc - 1, nr - 1);
1331
1332   /* Vertical lines */
1333   tab_box (t,
1334            -1, -1,
1335            -1, TAL_1,
1336            heading_columns, 1,
1337            nc - 1, nr - 1);
1338
1339   tab_hline (t, TAL_1, 0, nc - 1, heading_rows);
1340   tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
1341
1342
1343   /* Initialise to the identity permutation */
1344   perm = gsl_permutation_calloc (factor->n_vars);
1345
1346   if ( factor->sort)
1347     sort_matrix_indirect (fm, perm);
1348
1349   for (i = 0 ; i < n_factors; ++i)
1350     {
1351       tab_text_format (t, heading_columns + i, 1, TAB_CENTER | TAT_TITLE, _("%d"), i + 1);
1352     }
1353
1354   for (i = 0 ; i < factor->n_vars; ++i)
1355     {
1356       int j;
1357       const int matrix_row = perm->data[i];
1358       tab_text (t, 0, i + heading_rows, TAT_TITLE, var_to_string (factor->vars[matrix_row]));
1359
1360       for (j = 0 ; j < n_factors; ++j)
1361         {
1362           double x = gsl_matrix_get (fm, matrix_row, j);
1363
1364           if ( fabs (x) < factor->blank)
1365             continue;
1366
1367           tab_double (t, heading_columns + j, heading_rows + i, 0, x, NULL);
1368         }
1369     }
1370
1371   gsl_permutation_free (perm);
1372
1373   tab_submit (t);
1374 }
1375
1376
1377 static void
1378 show_explained_variance (const struct cmd_factor * factor, struct idata *idata,
1379                          const gsl_vector *initial_eigenvalues,
1380                          const gsl_vector *extracted_eigenvalues,
1381                          const gsl_vector *rotated_loadings)
1382 {
1383   size_t i;
1384   int c = 0;
1385   const int heading_columns = 1;
1386   const int heading_rows = 2;
1387   const int nr = heading_rows + factor->n_vars;
1388
1389   struct tab_table *t ;
1390
1391   double i_total = 0.0;
1392   double i_cum = 0.0;
1393
1394   double e_total = 0.0;
1395   double e_cum = 0.0;
1396
1397   double r_cum = 0.0;
1398
1399   int nc = heading_columns;
1400
1401   if (factor->print & PRINT_EXTRACTION)
1402     nc += 3;
1403
1404   if (factor->print & PRINT_INITIAL)
1405     nc += 3;
1406
1407   if (factor->print & PRINT_ROTATION)
1408     nc += 3;
1409
1410   /* No point having a table with only headings */
1411   if ( nc <= heading_columns)
1412     return;
1413
1414   t = tab_create (nc, nr);
1415
1416   tab_title (t, _("Total Variance Explained"));
1417
1418   tab_headers (t, heading_columns, 0, heading_rows, 0);
1419
1420   /* Outline the box */
1421   tab_box (t,
1422            TAL_2, TAL_2,
1423            -1, -1,
1424            0, 0,
1425            nc - 1, nr - 1);
1426
1427   /* Vertical lines */
1428   tab_box (t,
1429            -1, -1,
1430            -1, TAL_1,
1431            heading_columns, 0,
1432            nc - 1, nr - 1);
1433
1434   tab_hline (t, TAL_1, 0, nc - 1, heading_rows);
1435   tab_hline (t, TAL_1, 1, nc - 1, 1);
1436
1437   tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
1438
1439
1440   if ( factor->extraction == EXTRACTION_PC)
1441     tab_text (t, 0, 1, TAB_LEFT | TAT_TITLE, _("Component"));
1442   else
1443     tab_text (t, 0, 1, TAB_LEFT | TAT_TITLE, _("Factor"));
1444
1445   c = 1;
1446   if (factor->print & PRINT_INITIAL)
1447     {
1448       tab_joint_text (t, c, 0, c + 2, 0, TAB_CENTER | TAT_TITLE, _("Initial Eigenvalues"));
1449       c += 3;
1450     }
1451
1452   if (factor->print & PRINT_EXTRACTION)
1453     {
1454       tab_joint_text (t, c, 0, c + 2, 0, TAB_CENTER | TAT_TITLE, _("Extraction Sums of Squared Loadings"));
1455       c += 3;
1456     }
1457
1458   if (factor->print & PRINT_ROTATION)
1459     {
1460       tab_joint_text (t, c, 0, c + 2, 0, TAB_CENTER | TAT_TITLE, _("Rotation Sums of Squared Loadings"));
1461       c += 3;
1462     }
1463
1464   for (i = 0; i < (nc - heading_columns) / 3 ; ++i)
1465     {
1466       tab_text (t, i * 3 + 1, 1, TAB_CENTER | TAT_TITLE, _("Total"));
1467       /* xgettext:no-c-format */
1468       tab_text (t, i * 3 + 2, 1, TAB_CENTER | TAT_TITLE, _("% of Variance"));
1469       tab_text (t, i * 3 + 3, 1, TAB_CENTER | TAT_TITLE, _("Cumulative %"));
1470
1471       tab_vline (t, TAL_2, heading_columns + i * 3, 0, nr - 1);
1472     }
1473
1474   for (i = 0 ; i < initial_eigenvalues->size; ++i)
1475     i_total += gsl_vector_get (initial_eigenvalues, i);
1476
1477   if ( factor->extraction == EXTRACTION_PAF)
1478     {
1479       e_total = factor->n_vars;
1480     }
1481   else
1482     {
1483       e_total = i_total;
1484     }
1485
1486   for (i = 0 ; i < factor->n_vars; ++i)
1487     {
1488       const double i_lambda = gsl_vector_get (initial_eigenvalues, i);
1489       double i_percent = 100.0 * i_lambda / i_total ;
1490
1491       const double e_lambda = gsl_vector_get (extracted_eigenvalues, i);
1492       double e_percent = 100.0 * e_lambda / e_total ;
1493
1494       const double r_lambda = gsl_vector_get (rotated_loadings, i);
1495       double r_percent = 100.0 * r_lambda / e_total ;
1496
1497       c = 0;
1498
1499       tab_text_format (t, c++, i + heading_rows, TAB_LEFT | TAT_TITLE, _("%d"), i + 1);
1500
1501       i_cum += i_percent;
1502       e_cum += e_percent;
1503       r_cum += r_percent;
1504
1505       /* Initial Eigenvalues */
1506       if (factor->print & PRINT_INITIAL)
1507       {
1508         tab_double (t, c++, i + heading_rows, 0, i_lambda, NULL);
1509         tab_double (t, c++, i + heading_rows, 0, i_percent, NULL);
1510         tab_double (t, c++, i + heading_rows, 0, i_cum, NULL);
1511       }
1512
1513
1514       if (factor->print & PRINT_EXTRACTION)
1515         {
1516           if (i < idata->n_extractions)
1517             {
1518               /* Sums of squared loadings */
1519               tab_double (t, c++, i + heading_rows, 0, e_lambda, NULL);
1520               tab_double (t, c++, i + heading_rows, 0, e_percent, NULL);
1521               tab_double (t, c++, i + heading_rows, 0, e_cum, NULL);
1522             }
1523         }
1524
1525       if (factor->print & PRINT_ROTATION)
1526         {
1527           if (i < idata->n_extractions)
1528             {
1529               tab_double (t, c++, i + heading_rows, 0, r_lambda, NULL);
1530               tab_double (t, c++, i + heading_rows, 0, r_percent, NULL);
1531               tab_double (t, c++, i + heading_rows, 0, r_cum, NULL);
1532             }
1533       }
1534
1535     }
1536
1537   tab_submit (t);
1538 }
1539
1540
1541 static void
1542 show_correlation_matrix (const struct cmd_factor *factor, const struct idata *idata)
1543 {
1544   struct tab_table *t ;
1545   size_t i, j;
1546   int y_pos_corr = -1;
1547   int y_pos_sig = -1;
1548   int suffix_rows = 0;
1549
1550   const int heading_rows = 1;
1551   const int heading_columns = 2;
1552
1553   int nc = heading_columns ;
1554   int nr = heading_rows ;
1555   int n_data_sets = 0;
1556
1557   if (factor->print & PRINT_CORRELATION)
1558     {
1559       y_pos_corr = n_data_sets;
1560       n_data_sets++;
1561       nc = heading_columns + factor->n_vars;
1562     }
1563
1564   if (factor->print & PRINT_SIG)
1565     {
1566       y_pos_sig = n_data_sets;
1567       n_data_sets++;
1568       nc = heading_columns + factor->n_vars;
1569     }
1570
1571   nr += n_data_sets * factor->n_vars;
1572
1573   if (factor->print & PRINT_DETERMINANT)
1574     suffix_rows = 1;
1575
1576   /* If the table would contain only headings, don't bother rendering it */
1577   if (nr <= heading_rows && suffix_rows == 0)
1578     return;
1579
1580   t = tab_create (nc, nr + suffix_rows);
1581
1582   tab_title (t, _("Correlation Matrix"));
1583
1584   tab_hline (t, TAL_1, 0, nc - 1, heading_rows);
1585
1586   if (nr > heading_rows)
1587     {
1588       tab_headers (t, heading_columns, 0, heading_rows, 0);
1589
1590       tab_vline (t, TAL_2, 2, 0, nr - 1);
1591
1592       /* Outline the box */
1593       tab_box (t,
1594                TAL_2, TAL_2,
1595                -1, -1,
1596                0, 0,
1597                nc - 1, nr - 1);
1598
1599       /* Vertical lines */
1600       tab_box (t,
1601                -1, -1,
1602                -1, TAL_1,
1603                heading_columns, 0,
1604                nc - 1, nr - 1);
1605
1606
1607       for (i = 0; i < factor->n_vars; ++i)
1608         tab_text (t, heading_columns + i, 0, TAT_TITLE, var_to_string (factor->vars[i]));
1609
1610
1611       for (i = 0 ; i < n_data_sets; ++i)
1612         {
1613           int y = heading_rows + i * factor->n_vars;
1614           size_t v;
1615           for (v = 0; v < factor->n_vars; ++v)
1616             tab_text (t, 1, y + v, TAT_TITLE, var_to_string (factor->vars[v]));
1617
1618           tab_hline (t, TAL_1, 0, nc - 1, y);
1619         }
1620
1621       if (factor->print & PRINT_CORRELATION)
1622         {
1623           const double y = heading_rows + y_pos_corr;
1624           tab_text (t, 0, y, TAT_TITLE, _("Correlations"));
1625
1626           for (i = 0; i < factor->n_vars; ++i)
1627             {
1628               for (j = 0; j < factor->n_vars; ++j)
1629                 tab_double (t, heading_columns + i,  y + j, 0, gsl_matrix_get (idata->corr, i, j), NULL);
1630             }
1631         }
1632
1633       if (factor->print & PRINT_SIG)
1634         {
1635           const double y = heading_rows + y_pos_sig * factor->n_vars;
1636           tab_text (t, 0, y, TAT_TITLE, _("Sig. (1-tailed)"));
1637
1638           for (i = 0; i < factor->n_vars; ++i)
1639             {
1640               for (j = 0; j < factor->n_vars; ++j)
1641                 {
1642                   double rho = gsl_matrix_get (idata->corr, i, j);
1643                   double w = gsl_matrix_get (idata->n, i, j);
1644
1645                   if (i == j)
1646                     continue;
1647
1648                   tab_double (t, heading_columns + i,  y + j, 0, significance_of_correlation (rho, w), NULL);
1649                 }
1650             }
1651         }
1652     }
1653
1654   if (factor->print & PRINT_DETERMINANT)
1655     {
1656       int sign = 0;
1657       double det = 0.0;
1658
1659       const int size = idata->corr->size1;
1660       gsl_permutation *p = gsl_permutation_calloc (size);
1661       gsl_matrix *tmp = gsl_matrix_calloc (size, size);
1662       gsl_matrix_memcpy (tmp, idata->corr);
1663
1664       gsl_linalg_LU_decomp (tmp, p, &sign);
1665       det = gsl_linalg_LU_det (tmp, sign);
1666       gsl_permutation_free (p);
1667       gsl_matrix_free (tmp);
1668
1669
1670       tab_text (t, 0, nr, TAB_LEFT | TAT_TITLE, _("Determinant"));
1671       tab_double (t, 1, nr, 0, det, NULL);
1672     }
1673
1674   tab_submit (t);
1675 }
1676
1677
1678
1679 static void
1680 do_factor (const struct cmd_factor *factor, struct casereader *r)
1681 {
1682   struct ccase *c;
1683   const gsl_matrix *var_matrix;
1684   const gsl_matrix *mean_matrix;
1685
1686   const gsl_matrix *analysis_matrix;
1687   struct idata *idata = idata_alloc (factor->n_vars);
1688
1689   struct covariance *cov = covariance_1pass_create (factor->n_vars, factor->vars,
1690                                               factor->wv, factor->exclude);
1691
1692   for ( ; (c = casereader_read (r) ); case_unref (c))
1693     {
1694       covariance_accumulate (cov, c);
1695     }
1696
1697   idata->cov = covariance_calculate (cov);
1698
1699   if (idata->cov == NULL)
1700     {
1701       msg (MW, _("The dataset contains no complete observations. No analysis will be performed."));
1702       goto finish;
1703     }
1704
1705   var_matrix = covariance_moments (cov, MOMENT_VARIANCE);
1706   mean_matrix = covariance_moments (cov, MOMENT_MEAN);
1707   idata->n = covariance_moments (cov, MOMENT_NONE);
1708
1709   if ( factor->method == METHOD_CORR)
1710     {
1711       idata->corr = correlation_from_covariance (idata->cov, var_matrix);
1712       analysis_matrix = idata->corr;
1713     }
1714   else
1715     analysis_matrix = idata->cov;
1716
1717   if ( factor->print & PRINT_UNIVARIATE)
1718     {
1719       const int nc = 4;
1720       int i;
1721       const struct fmt_spec *wfmt = factor->wv ? var_get_print_format (factor->wv) : & F_8_0;
1722
1723
1724       const int heading_columns = 1;
1725       const int heading_rows = 1;
1726
1727       const int nr = heading_rows + factor->n_vars;
1728
1729       struct tab_table *t = tab_create (nc, nr);
1730       tab_title (t, _("Descriptive Statistics"));
1731
1732       tab_headers (t, heading_columns, 0, heading_rows, 0);
1733
1734       /* Outline the box */
1735       tab_box (t,
1736                TAL_2, TAL_2,
1737                -1, -1,
1738                0, 0,
1739                nc - 1, nr - 1);
1740
1741       /* Vertical lines */
1742       tab_box (t,
1743                -1, -1,
1744                -1, TAL_1,
1745                heading_columns, 0,
1746                nc - 1, nr - 1);
1747
1748       tab_hline (t, TAL_1, 0, nc - 1, heading_rows);
1749       tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
1750
1751       tab_text (t, 1, 0, TAB_CENTER | TAT_TITLE, _("Mean"));
1752       tab_text (t, 2, 0, TAB_CENTER | TAT_TITLE, _("Std. Deviation"));
1753       tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("Analysis N"));
1754
1755       for (i = 0 ; i < factor->n_vars; ++i)
1756         {
1757           const struct variable *v = factor->vars[i];
1758           tab_text (t, 0, i + heading_rows, TAB_LEFT | TAT_TITLE, var_to_string (v));
1759
1760           tab_double (t, 1, i + heading_rows, 0, gsl_matrix_get (mean_matrix, i, i), NULL);
1761           tab_double (t, 2, i + heading_rows, 0, sqrt (gsl_matrix_get (var_matrix, i, i)), NULL);
1762           tab_double (t, 3, i + heading_rows, 0, gsl_matrix_get (idata->n, i, i), wfmt);
1763         }
1764
1765       tab_submit (t);
1766     }
1767
1768   show_correlation_matrix (factor, idata);
1769
1770 #if 1
1771   {
1772     gsl_eigen_symmv_workspace *workspace = gsl_eigen_symmv_alloc (factor->n_vars);
1773     
1774     gsl_eigen_symmv (matrix_dup (analysis_matrix), idata->eval, idata->evec, workspace);
1775
1776     gsl_eigen_symmv_free (workspace);
1777   }
1778
1779   gsl_eigen_symmv_sort (idata->eval, idata->evec, GSL_EIGEN_SORT_ABS_DESC);
1780 #endif
1781
1782   idata->n_extractions = n_extracted_factors (factor, idata);
1783
1784   if (idata->n_extractions == 0)
1785     {
1786       msg (MW, _("The FACTOR criteria result in zero factors extracted. Therefore no analysis will be performed."));
1787       goto finish;
1788     }
1789
1790   if (idata->n_extractions > factor->n_vars)
1791     {
1792       msg (MW, _("The FACTOR criteria result in more factors than variables, which is not meaningful. No analysis will be performed."));
1793       goto finish;
1794     }
1795     
1796   {
1797     gsl_matrix *rotated_factors = NULL;
1798     gsl_vector *rotated_loadings = NULL;
1799
1800     const gsl_vector *extracted_eigenvalues = NULL;
1801     gsl_vector *initial_communalities = gsl_vector_alloc (factor->n_vars);
1802     gsl_vector *extracted_communalities = gsl_vector_alloc (factor->n_vars);
1803     size_t i;
1804     struct factor_matrix_workspace *fmw = factor_matrix_workspace_alloc (idata->msr->size, idata->n_extractions);
1805     gsl_matrix *factor_matrix = gsl_matrix_calloc (factor->n_vars, fmw->n_factors);
1806
1807     if ( factor->extraction == EXTRACTION_PAF)
1808       {
1809         gsl_vector *diff = gsl_vector_alloc (idata->msr->size);
1810         struct smr_workspace *ws = ws_create (analysis_matrix);
1811
1812         for (i = 0 ; i < factor->n_vars ; ++i)
1813           {
1814             double r2 = squared_multiple_correlation (analysis_matrix, i, ws);
1815
1816             gsl_vector_set (idata->msr, i, r2);
1817           }
1818         ws_destroy (ws);
1819
1820         gsl_vector_memcpy (initial_communalities, idata->msr);
1821
1822         for (i = 0; i < factor->iterations; ++i)
1823           {
1824             double min, max;
1825             gsl_vector_memcpy (diff, idata->msr);
1826
1827             iterate_factor_matrix (analysis_matrix, idata->msr, factor_matrix, fmw);
1828       
1829             gsl_vector_sub (diff, idata->msr);
1830
1831             gsl_vector_minmax (diff, &min, &max);
1832       
1833             if ( fabs (min) < factor->econverge && fabs (max) < factor->econverge)
1834               break;
1835           }
1836         gsl_vector_free (diff);
1837
1838
1839
1840         gsl_vector_memcpy (extracted_communalities, idata->msr);
1841         extracted_eigenvalues = fmw->eval;
1842       }
1843     else if (factor->extraction == EXTRACTION_PC)
1844       {
1845         for (i = 0; i < factor->n_vars; ++i)
1846           gsl_vector_set (initial_communalities, i, communality (idata, i, factor->n_vars));
1847
1848         gsl_vector_memcpy (extracted_communalities, initial_communalities);
1849
1850         iterate_factor_matrix (analysis_matrix, extracted_communalities, factor_matrix, fmw);
1851
1852
1853         extracted_eigenvalues = idata->eval;
1854       }
1855
1856
1857     show_communalities (factor, initial_communalities, extracted_communalities);
1858
1859
1860     if ( factor->rotation != ROT_NONE)
1861       {
1862         rotated_factors = gsl_matrix_calloc (factor_matrix->size1, factor_matrix->size2);
1863         rotated_loadings = gsl_vector_calloc (factor_matrix->size2);
1864
1865         rotate (factor, factor_matrix, extracted_communalities, rotated_factors, rotated_loadings);
1866       }
1867
1868     show_explained_variance (factor, idata, idata->eval, extracted_eigenvalues, rotated_loadings);
1869
1870     factor_matrix_workspace_free (fmw);
1871
1872     show_scree (factor, idata);
1873
1874     show_factor_matrix (factor, idata,
1875                         factor->extraction == EXTRACTION_PC ? _("Component Matrix") : _("Factor Matrix"),
1876                         factor_matrix);
1877
1878     if ( factor->rotation != ROT_NONE)
1879       {
1880         show_factor_matrix (factor, idata,
1881                             factor->extraction == EXTRACTION_PC ? _("Rotated Component Matrix") : _("Rotated Factor Matrix"),
1882                             rotated_factors);
1883
1884         gsl_matrix_free (rotated_factors);
1885       }
1886
1887
1888
1889     gsl_vector_free (initial_communalities);
1890     gsl_vector_free (extracted_communalities);
1891   }
1892
1893  finish:
1894
1895   idata_free (idata);
1896
1897   casereader_destroy (r);
1898 }
1899
1900
1901