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