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