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