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