First attempt at FACTOR command
[pspp-builds.git] / src / language / stats / factor.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2009 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/table.h>
48
49
50 #include "gettext.h"
51 #define _(msgid) gettext (msgid)
52 #define N_(msgid) msgid
53
54 enum method
55   {
56     METHOD_CORR,
57     METHOD_COV
58   };
59
60 enum missing_type
61   {
62     MISS_LISTWISE,
63     MISS_PAIRWISE,
64     MISS_MEANSUB,
65   };
66
67 enum extraction_method
68   {
69     EXTRACTION_PC,
70     EXTRACTION_PAF,
71   };
72
73 enum print_opts
74   {
75     PRINT_UNIVARIATE  = 0x0001,
76     PRINT_DETERMINANT = 0x0002,
77     PRINT_INV         = 0x0004,
78     PRINT_AIC         = 0x0008,
79     PRINT_SIG         = 0x0010,
80     PRINT_COVARIANCE  = 0x0020,
81     PRINT_CORRELATION = 0x0040,
82     PRINT_ROTATION    = 0x0080,
83     PRINT_EXTRACTION  = 0x0100,
84     PRINT_INITIAL     = 0x0200,
85     PRINT_KMO         = 0x0400,
86     PRINT_REPR        = 0x0800, 
87     PRINT_FSCORE      = 0x1000
88   };
89
90
91 struct cmd_factor 
92 {
93   size_t n_vars;
94   const struct variable **vars;
95
96   const struct variable *wv;
97
98   enum method method;
99   enum missing_type missing_type;
100   enum mv_class exclude;
101   enum print_opts print;
102   enum extraction_method extraction;
103
104   /* Extraction Criteria */
105   int n_factors;
106   double min_eigen;
107   double econverge;
108   int iterations;
109
110   /* Format */
111   double blank;
112   bool sort;
113 };
114
115 struct idata
116 {
117   /* Intermediate values used in calculation */
118
119   gsl_vector *eval ;  /* The eigenvalues */
120   gsl_matrix *evec ;  /* The eigenvectors */
121
122   int n_extractions;
123
124   gsl_vector *msr ;  /* Multiple Squared Regressions */
125 };
126
127 static struct idata *
128 idata_alloc (size_t n_vars)
129 {
130   struct idata *id = xmalloc (sizeof (*id));
131
132   id->n_extractions = 0;
133   id->msr = gsl_vector_alloc (n_vars);
134
135   id->eval = gsl_vector_alloc (n_vars);
136   id->evec = gsl_matrix_alloc (n_vars, n_vars);
137
138   return id;
139 }
140
141 static void
142 idata_free (struct idata *id)
143 {
144   gsl_vector_free (id->msr);
145   gsl_vector_free (id->eval);
146   gsl_matrix_free (id->evec);
147
148   free (id);
149 }
150
151
152 static void
153 dump_matrix (const gsl_matrix *m)
154 {
155   size_t i, j;
156
157   for (i = 0 ; i < m->size1; ++i)
158     {
159       for (j = 0 ; j < m->size2; ++j)
160         printf ("%02f ", gsl_matrix_get (m, i, j));
161       printf ("\n");
162     }
163 }
164
165
166 static void
167 dump_matrix_permute (const gsl_matrix *m, const gsl_permutation *p)
168 {
169   size_t i, j;
170
171   for (i = 0 ; i < m->size1; ++i)
172     {
173       for (j = 0 ; j < m->size2; ++j)
174         printf ("%02f ", gsl_matrix_get (m, gsl_permutation_get (p, i), j));
175       printf ("\n");
176     }
177 }
178
179
180 static void
181 dump_vector (const gsl_vector *v)
182 {
183   size_t i;
184   for (i = 0 ; i < v->size; ++i)
185     {
186       printf ("%02f\n", gsl_vector_get (v, i));
187     }
188   printf ("\n");
189 }
190
191
192 static int 
193 n_extracted_factors (const struct cmd_factor *factor, struct idata *idata)
194 {
195   int i;
196   
197   /* If there is a cached value, then return that. */
198   if ( idata->n_extractions != 0)
199     return idata->n_extractions;
200
201   /* Otherwise, if the number of factors has been explicitly requested,
202      use that. */
203   if (factor->n_factors > 0)
204     {
205       idata->n_extractions = factor->n_factors;
206       goto finish;
207     }
208   
209   /* Use the MIN_EIGEN setting. */
210   for (i = 0 ; i < idata->eval->size; ++i)
211     {
212       double evali = fabs (gsl_vector_get (idata->eval, i));
213
214       idata->n_extractions = i;
215
216       if (evali < factor->min_eigen)
217         goto finish;
218     }
219
220  finish:
221   return idata->n_extractions;
222 }
223
224
225 /* Returns a newly allocated matrix identical to M.
226    It it the callers responsibility to free the returned value.
227 */
228 static gsl_matrix *
229 matrix_dup (const gsl_matrix *m)
230 {
231   gsl_matrix *n =  gsl_matrix_alloc (m->size1, m->size2);
232
233   gsl_matrix_memcpy (n, m);
234
235   return n;
236 }
237
238
239 struct smr_workspace
240 {
241   /* Copy of the subject */
242   gsl_matrix *m;
243   
244   gsl_matrix *inverse;
245
246   gsl_permutation *perm;
247
248   gsl_matrix *result1;
249   gsl_matrix *result2;
250 };
251
252
253 static struct smr_workspace *ws_create (const gsl_matrix *input)
254 {
255   struct smr_workspace *ws = xmalloc (sizeof (*ws));
256   
257   ws->m = gsl_matrix_alloc (input->size1, input->size2);
258   ws->inverse = gsl_matrix_calloc (input->size1 - 1, input->size2 - 1);
259   ws->perm = gsl_permutation_alloc (input->size1 - 1);
260   ws->result1 = gsl_matrix_calloc (input->size1 - 1, 1);
261   ws->result2 = gsl_matrix_calloc (1, 1);
262
263   return ws;
264 }
265
266 static void
267 ws_destroy (struct smr_workspace *ws)
268 {
269   gsl_matrix_free (ws->result2);
270   gsl_matrix_free (ws->result1);
271   gsl_permutation_free (ws->perm);
272   gsl_matrix_free (ws->inverse);
273   gsl_matrix_free (ws->m);
274
275   free (ws);
276 }
277
278
279 /* 
280    Return the square of the regression coefficient for VAR regressed against all other variables.
281  */
282 static double
283 squared_multiple_correlation (const gsl_matrix *analysis_matrix, int var, struct smr_workspace *ws)
284 {
285   /* For an explanation of what this is doing, see 
286      http://www.visualstatistics.net/Visual%20Statistics%20Multimedia/multiple_regression_analysis.htm
287   */
288
289   int signum = 0;
290   gsl_matrix_view rxx;
291
292   gsl_matrix_memcpy (ws->m, analysis_matrix);
293
294   gsl_matrix_swap_rows (ws->m, 0, var);
295   gsl_matrix_swap_columns (ws->m, 0, var);
296
297   rxx = gsl_matrix_submatrix (ws->m, 1, 1, ws->m->size1 - 1, ws->m->size1 - 1); 
298
299   gsl_linalg_LU_decomp (&rxx.matrix, ws->perm, &signum);
300
301   gsl_linalg_LU_invert (&rxx.matrix, ws->perm, ws->inverse);
302
303   {
304     gsl_matrix_const_view rxy = gsl_matrix_const_submatrix (ws->m, 1, 0, ws->m->size1 - 1, 1);
305     gsl_matrix_const_view ryx = gsl_matrix_const_submatrix (ws->m, 0, 1, 1, ws->m->size1 - 1);
306
307     gsl_blas_dgemm (CblasNoTrans,  CblasNoTrans,
308                     1.0, ws->inverse, &rxy.matrix, 0.0, ws->result1);
309
310     gsl_blas_dgemm (CblasNoTrans,  CblasNoTrans,
311                     1.0, &ryx.matrix, ws->result1, 0.0, ws->result2);
312   }
313
314   return gsl_matrix_get (ws->result2, 0, 0);
315 }
316
317
318
319 static double the_communality (const gsl_matrix *evec, const gsl_vector *eval, int n, int n_factors);
320
321
322 struct factor_matrix_workspace
323 {
324   size_t n_factors;
325   gsl_eigen_symmv_workspace *eigen_ws;
326
327   gsl_vector *eval ;
328   gsl_matrix *evec ;
329
330   gsl_matrix *gamma ;
331
332   gsl_matrix *r;
333 };
334
335 static struct factor_matrix_workspace *
336 factor_matrix_workspace_alloc (size_t n, size_t nf)
337 {
338   struct factor_matrix_workspace *ws = xmalloc (sizeof (*ws));
339
340   ws->n_factors = nf;
341   ws->gamma = gsl_matrix_calloc (nf, nf);
342   ws->eigen_ws = gsl_eigen_symmv_alloc (n);
343   ws->eval = gsl_vector_alloc (n);
344   ws->evec = gsl_matrix_alloc (n, n);
345   ws->r  = gsl_matrix_alloc (n, n);
346   
347   return ws;
348 }
349
350 static void
351 factor_matrix_workspace_free (struct factor_matrix_workspace *ws)
352 {
353   gsl_eigen_symmv_free (ws->eigen_ws);
354   gsl_vector_free (ws->eval);
355   gsl_matrix_free (ws->evec);
356   gsl_matrix_free (ws->gamma);
357   gsl_matrix_free (ws->r);
358   free (ws);
359 }
360
361 /*
362   Shift P left by OFFSET places, and overwrite TARGET
363   with the shifted result.
364   Positions in TARGET less than OFFSET are unchanged.
365 */
366 static void
367 perm_shift_apply (gsl_permutation *target, const gsl_permutation *p,
368                   size_t offset)
369 {
370   size_t i;
371   assert (target->size == p->size);
372   assert (offset <= target->size);
373
374   for (i = 0; i < target->size - offset; ++i)
375     {
376       target->data[i] = p->data [i + offset];
377     }
378 }
379
380
381 /* 
382    Indirectly sort the rows of matrix INPUT, storing the sort order in PERM.
383    The sort criteria are as follows:
384    
385    Rows are sorted on the first column, until the absolute value of an
386    element in a subsequent column  is greater than that of the first
387    column.  Thereafter, rows will be sorted on the second column,
388    until the absolute value of an element in a subsequent column
389    exceeds that of the second column ...
390 */
391 static void
392 sort_matrix_indirect (const gsl_matrix *input, gsl_permutation *perm)
393 {
394   const size_t n = perm->size;
395   const size_t m = input->size2;
396   int i, j;
397   gsl_matrix *mat ;
398   int column_n = 0;
399   int row_n = 0;
400   gsl_permutation *p;
401
402   assert (perm->size == input->size1);
403
404   p = gsl_permutation_alloc (n);
405
406   /* Copy INPUT into MAT, discarding the sign */
407   mat = gsl_matrix_alloc (n, m);
408   for (i = 0 ; i < mat->size1; ++i)
409     {
410       for (j = 0 ; j < mat->size2; ++j)
411         {
412           double x = gsl_matrix_get (input, i, j);
413           gsl_matrix_set (mat, i, j, fabs (x));
414         }
415     }
416
417   while (column_n < m && row_n < n) 
418     {
419       gsl_vector_const_view columni = gsl_matrix_const_column (mat, column_n);
420       gsl_sort_vector_index (p, &columni.vector);
421
422       for (i = 0 ; i < n; ++i)
423         {
424           gsl_vector_view row = gsl_matrix_row (mat, p->data[n - 1 - i]);
425           size_t maxindex = gsl_vector_max_index (&row.vector);
426           
427           if ( maxindex > column_n )
428             break;
429
430           /* All subsequent elements of this row, are of no interest.
431              So set them all to a highly negative value */
432           for (j = column_n + 1; j < row.vector.size ; ++j)
433             gsl_vector_set (&row.vector, j, -DBL_MAX);
434         }
435
436       perm_shift_apply (perm, p, row_n);
437       row_n += i;
438
439       column_n++;
440     }
441
442   gsl_permutation_free (p);
443   gsl_matrix_free (mat);
444   
445   assert ( 0 == gsl_permutation_valid (perm));
446
447   /* We want the biggest value to be first */
448   gsl_permutation_reverse (perm);    
449 }
450
451
452 /*
453   Get an approximation for the factor matrix into FACTORS, and the communalities into COMMUNALITIES.
454   R is the matrix to be analysed.
455   WS is a pointer to a structure which must have been initialised with factor_matrix_workspace_init.
456  */
457 static void
458 iterate_factor_matrix (const gsl_matrix *r, gsl_vector *communalities, gsl_matrix *factors, struct factor_matrix_workspace *ws)
459 {
460   size_t i;
461   gsl_matrix_view mv ;
462
463   assert (r->size1 == r->size2);
464   assert (r->size1 == communalities->size);
465
466   assert (factors->size1 == r->size1);
467   assert (factors->size2 == ws->n_factors);
468
469   gsl_matrix_memcpy (ws->r, r);
470
471   /* Apply Communalities to diagonal of correlation matrix */
472   for (i = 0 ; i < communalities->size ; ++i)
473     {
474       double *x = gsl_matrix_ptr (ws->r, i, i);
475       *x = gsl_vector_get (communalities, i);
476     }
477
478   gsl_eigen_symmv (ws->r, ws->eval, ws->evec, ws->eigen_ws);
479
480   mv = gsl_matrix_submatrix (ws->evec, 0, 0, ws->evec->size1, ws->n_factors);
481
482   /* Gamma is the diagonal matrix containing the absolute values of the eigenvalues */
483   for (i = 0 ; i < ws->n_factors ; ++i)
484     {
485       double *ptr = gsl_matrix_ptr (ws->gamma, i, i);
486       *ptr = fabs (gsl_vector_get (ws->eval, i));
487     }
488
489   /* Take the square root of gamma */
490   gsl_linalg_cholesky_decomp (ws->gamma);
491
492   gsl_blas_dgemm (CblasNoTrans,  CblasNoTrans,
493                   1.0, &mv.matrix, ws->gamma, 0.0, factors);
494
495   for (i = 0 ; i < r->size1 ; ++i)
496     {
497       double h = the_communality (ws->evec, ws->eval, i, ws->n_factors);
498       gsl_vector_set (communalities, i, h);
499     }
500 }
501
502
503
504 static bool run_factor (struct dataset *ds, const struct cmd_factor *factor);
505
506
507 int
508 cmd_factor (struct lexer *lexer, struct dataset *ds)
509 {
510   bool extraction_seen = false;
511   const struct dictionary *dict = dataset_dict (ds);
512
513   struct cmd_factor factor;
514   factor.method = METHOD_CORR;
515   factor.missing_type = MISS_LISTWISE;
516   factor.exclude = MV_ANY;
517   factor.print = PRINT_INITIAL | PRINT_EXTRACTION | PRINT_ROTATION;
518   factor.extraction = EXTRACTION_PC;
519   factor.n_factors = 0;
520   factor.min_eigen = SYSMIS;
521   factor.iterations = 25;
522   factor.econverge = 0.001;
523   factor.blank = 0;
524   factor.sort = false;
525
526   factor.wv = dict_get_weight (dict);
527
528   lex_match (lexer, '/');
529
530   if (!lex_force_match_id (lexer, "VARIABLES"))
531     {
532       goto error;
533     }
534
535   lex_match (lexer, '=');
536
537   if (!parse_variables_const (lexer, dict, &factor.vars, &factor.n_vars,
538                               PV_NO_DUPLICATE | PV_NUMERIC))
539     goto error;
540
541   while (lex_token (lexer) != '.')
542     {
543       lex_match (lexer, '/');
544
545 #if FACTOR_FULLY_IMPLEMENTED
546       if (lex_match_id (lexer, "PLOT"))
547         {
548           lex_match (lexer, '=');
549           while (lex_token (lexer) != '.' && lex_token (lexer) != '/')
550             {
551               if (lex_match_id (lexer, "EIGEN"))
552                 {
553                 }
554               else if (lex_match_id (lexer, "ROTATION"))
555                 {
556                 }
557               else
558                 {
559                   lex_error (lexer, NULL);
560                   goto error;
561                 }
562             }
563         }
564       else
565 #endif
566       if (lex_match_id (lexer, "METHOD"))
567         {
568           lex_match (lexer, '=');
569           while (lex_token (lexer) != '.' && lex_token (lexer) != '/')
570             {
571               if (lex_match_id (lexer, "COVARIANCE"))
572                 {
573                   factor.method = METHOD_COV;
574                 }
575               else if (lex_match_id (lexer, "CORRELATION"))
576                 {
577                   factor.method = METHOD_CORR;
578                 }
579               else
580                 {
581                   lex_error (lexer, NULL);
582                   goto error;
583                 }
584             }
585         }
586 #if FACTOR_FULLY_IMPLEMENTED
587       else if (lex_match_id (lexer, "ROTATION"))
588         {
589           lex_match (lexer, '=');
590           while (lex_token (lexer) != '.' && lex_token (lexer) != '/')
591             {
592               if (lex_match_id (lexer, "VARIMAX"))
593                 {
594                 }
595               else if (lex_match_id (lexer, "DEFAULT"))
596                 {
597                 }
598               else
599                 {
600                   lex_error (lexer, NULL);
601                   goto error;
602                 }
603             }
604         }
605 #endif
606       else if (lex_match_id (lexer, "CRITERIA"))
607         {
608           lex_match (lexer, '=');
609           while (lex_token (lexer) != '.' && lex_token (lexer) != '/')
610             {
611               if (lex_match_id (lexer, "FACTORS"))
612                 {
613                   if ( lex_force_match (lexer, '('))
614                     {
615                       lex_force_int (lexer);
616                       factor.n_factors = lex_integer (lexer);
617                       lex_get (lexer);
618                       lex_force_match (lexer, ')');
619                     }
620                 }
621               else if (lex_match_id (lexer, "MINEIGEN"))
622                 {
623                   if ( lex_force_match (lexer, '('))
624                     {
625                       lex_force_num (lexer);
626                       factor.min_eigen = lex_number (lexer);
627                       lex_get (lexer);
628                       lex_force_match (lexer, ')');
629                     }
630                 }
631               else if (lex_match_id (lexer, "ECONVERGE"))
632                 {
633                   if ( lex_force_match (lexer, '('))
634                     {
635                       lex_force_num (lexer);
636                       factor.econverge = lex_number (lexer);
637                       lex_get (lexer);
638                       lex_force_match (lexer, ')');
639                     }
640                 }
641               else if (lex_match_id (lexer, "ITERATE"))
642                 {
643                   if ( lex_force_match (lexer, '('))
644                     {
645                       lex_force_int (lexer);
646                       factor.iterations = lex_integer (lexer);
647                       lex_get (lexer);
648                       lex_force_match (lexer, ')');
649                     }
650                 }
651               else if (lex_match_id (lexer, "DEFAULT"))
652                 {
653                   factor.n_factors = 0;
654                   factor.min_eigen = 1;
655                   factor.iterations = 25;
656                 }
657               else
658                 {
659                   lex_error (lexer, NULL);
660                   goto error;
661                 }
662             }
663         }
664       else if (lex_match_id (lexer, "EXTRACTION"))
665         {
666           extraction_seen = true;
667           lex_match (lexer, '=');
668           while (lex_token (lexer) != '.' && lex_token (lexer) != '/')
669             {
670               if (lex_match_id (lexer, "PAF"))
671                 {
672                   factor.extraction = EXTRACTION_PAF;
673                 }
674               else if (lex_match_id (lexer, "PC"))
675                 {
676                   factor.extraction = EXTRACTION_PC;
677                 }
678               else if (lex_match_id (lexer, "PA1"))
679                 {
680                   factor.extraction = EXTRACTION_PC;
681                 }
682               else if (lex_match_id (lexer, "DEFAULT"))
683                 {
684                   factor.extraction = EXTRACTION_PC;
685                 }
686               else
687                 {
688                   lex_error (lexer, NULL);
689                   goto error;
690                 }
691             }
692         }
693       else if (lex_match_id (lexer, "FORMAT"))
694         {
695           lex_match (lexer, '=');
696           while (lex_token (lexer) != '.' && lex_token (lexer) != '/')
697             {
698               if (lex_match_id (lexer, "SORT"))
699                 {
700                   factor.sort = true;
701                 }
702               else if (lex_match_id (lexer, "BLANK"))
703                 {
704                   if ( lex_force_match (lexer, '('))
705                     {
706                       lex_force_num (lexer);
707                       factor.blank = lex_number (lexer);
708                       lex_get (lexer);
709                       lex_force_match (lexer, ')');
710                     }
711                 }
712               else if (lex_match_id (lexer, "DEFAULT"))
713                 {
714                   factor.blank = 0;
715                   factor.sort = false;
716                 }
717               else
718                 {
719                   lex_error (lexer, NULL);
720                   goto error;
721                 }
722             }
723         }
724       else if (lex_match_id (lexer, "PRINT"))
725         {
726           factor.print = 0;
727           lex_match (lexer, '=');
728           while (lex_token (lexer) != '.' && lex_token (lexer) != '/')
729             {
730               if (lex_match_id (lexer, "UNIVARIATE"))
731                 {
732                   factor.print |= PRINT_UNIVARIATE;
733                 }
734               else if (lex_match_id (lexer, "DET"))
735                 {
736                   factor.print |= PRINT_DETERMINANT;
737                 }
738 #if FACTOR_FULLY_IMPLEMENTED
739               else if (lex_match_id (lexer, "INV"))
740                 {
741                 }
742               else if (lex_match_id (lexer, "AIC"))
743                 {
744                 }
745               else if (lex_match_id (lexer, "SIG"))
746                 {
747                 }
748               else if (lex_match_id (lexer, "COVARIANCE"))
749                 {
750                 }
751               else if (lex_match_id (lexer, "CORRELATION"))
752                 {
753                 }
754 #endif
755               else if (lex_match_id (lexer, "ROTATION"))
756                 {
757                   factor.print |= PRINT_ROTATION;
758                 }
759               else if (lex_match_id (lexer, "EXTRACTION"))
760                 {
761                   factor.print |= PRINT_EXTRACTION;
762                 }
763               else if (lex_match_id (lexer, "INITIAL"))
764                 {
765                   factor.print |= PRINT_INITIAL;
766                 }
767 #if FACTOR_FULLY_IMPLEMENTED
768               else if (lex_match_id (lexer, "KMO"))
769                 {
770                 }
771               else if (lex_match_id (lexer, "REPR"))
772                 {
773                 }
774               else if (lex_match_id (lexer, "FSCORE"))
775                 {
776                 }
777 #endif
778               else if (lex_match (lexer, T_ALL))
779                 {
780                   factor.print = 0xFFFF;
781                 }
782               else if (lex_match_id (lexer, "DEFAULT"))
783                 {
784                   factor.print |= PRINT_INITIAL ;
785                   factor.print |= PRINT_EXTRACTION ;
786                   factor.print |= PRINT_ROTATION ;
787                 }
788               else
789                 {
790                   lex_error (lexer, NULL);
791                   goto error;
792                 }
793             }
794         }
795       else if (lex_match_id (lexer, "MISSING"))
796         {
797           lex_match (lexer, '=');
798           while (lex_token (lexer) != '.' && lex_token (lexer) != '/')
799             {
800               if (lex_match_id (lexer, "INCLUDE"))
801                 {
802                   factor.exclude = MV_SYSTEM;
803                 }
804               else if (lex_match_id (lexer, "EXCLUDE"))
805                 {
806                   factor.exclude = MV_ANY;
807                 }
808               else if (lex_match_id (lexer, "LISTWISE"))
809                 {
810                   factor.missing_type = MISS_LISTWISE;
811                 }
812               else if (lex_match_id (lexer, "PAIRWISE"))
813                 {
814                   factor.missing_type = MISS_PAIRWISE;
815                 }
816               else if (lex_match_id (lexer, "MEANSUB"))
817                 {
818                   factor.missing_type = MISS_MEANSUB;
819                 }
820               else
821                 {
822                   lex_error (lexer, NULL);
823                   goto error;
824                 }
825             }
826         }
827       else
828         {
829           lex_error (lexer, NULL);
830           goto error;
831         }
832     }
833
834   if ( ! run_factor (ds, &factor)) 
835     goto error;
836
837   free (factor.vars);
838   return CMD_SUCCESS;
839
840  error:
841   free (factor.vars);
842   return CMD_FAILURE;
843 }
844
845 static void do_factor (const struct cmd_factor *factor, struct casereader *group);
846
847
848 static bool
849 run_factor (struct dataset *ds, const struct cmd_factor *factor)
850 {
851   struct dictionary *dict = dataset_dict (ds);
852   bool ok;
853   struct casereader *group;
854
855   struct casegrouper *grouper = casegrouper_create_splits (proc_open (ds), dict);
856
857   while (casegrouper_get_next_group (grouper, &group))
858     {
859       if ( factor->missing_type == MISS_LISTWISE )
860         group  = casereader_create_filter_missing (group, factor->vars, factor->n_vars,
861                                                    factor->exclude,
862                                                    NULL,  NULL);
863       do_factor (factor, group);
864     }
865
866   ok = casegrouper_destroy (grouper);
867   ok = proc_commit (ds) && ok;
868
869   return ok;
870 }
871
872
873 /* Return the communality of variable N, calculated to N_FACTORS */
874 static double
875 the_communality (const gsl_matrix *evec, const gsl_vector *eval, int n, int n_factors)
876 {
877   size_t i;
878
879   double comm = 0;
880
881   assert (n >= 0);
882   assert (n < eval->size);
883   assert (n < evec->size1);
884   assert (n_factors <= eval->size);
885
886   for (i = 0 ; i < n_factors; ++i)
887     {
888       double evali = fabs (gsl_vector_get (eval, i));
889
890       double eveci = gsl_matrix_get (evec, n, i);
891
892       comm += pow2 (eveci) * evali;
893     }
894
895   return comm;
896 }
897
898 /* Return the communality of variable N, calculated to N_FACTORS */
899 static double
900 communality (struct idata *idata, int n, int n_factors)
901 {
902   return the_communality (idata->evec, idata->eval, n, n_factors);
903 }
904
905
906
907 static void
908 show_communalities (const struct cmd_factor * factor,
909                     const gsl_vector *initial, const gsl_vector *extracted)
910 {
911   int i;
912   int c = 0;
913   const int heading_columns = 1;
914   int nc = heading_columns;
915   const int heading_rows = 1;
916   const int nr = heading_rows + factor->n_vars;
917   struct tab_table *t;
918
919   if (factor->print & PRINT_EXTRACTION)
920     nc++;
921
922   if (factor->print & PRINT_INITIAL)
923     nc++;
924
925   /* No point having a table with only headings */
926   if (nc <= 1)
927     return;
928
929   t = tab_create (nc, nr, 0);
930
931   tab_title (t, _("Communalities"));
932
933   tab_dim (t, tab_natural_dimensions, NULL);
934
935   tab_headers (t, heading_columns, 0, heading_rows, 0);
936
937   c = 1;
938   if (factor->print & PRINT_INITIAL)
939     tab_text (t, c++, 0, TAB_CENTER | TAT_TITLE, _("Initial"));
940
941   if (factor->print & PRINT_EXTRACTION)
942     tab_text (t, c++, 0, TAB_CENTER | TAT_TITLE, _("Extraction"));
943
944   /* Outline the box */
945   tab_box (t,
946            TAL_2, TAL_2,
947            -1, -1,
948            0, 0,
949            nc - 1, nr - 1);
950
951   /* Vertical lines */
952   tab_box (t,
953            -1, -1,
954            -1, TAL_1,
955            heading_columns, 0,
956            nc - 1, nr - 1);
957
958   tab_hline (t, TAL_1, 0, nc - 1, heading_rows);
959   tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
960
961   for (i = 0 ; i < factor->n_vars; ++i)
962     {
963       c = 0;
964       tab_text (t, c++, i + heading_rows, TAT_TITLE, var_to_string (factor->vars[i]));
965
966       if (factor->print & PRINT_INITIAL)
967         tab_double (t, c++, i + heading_rows, 0, gsl_vector_get (initial, i), NULL);
968
969       if (factor->print & PRINT_EXTRACTION)
970         tab_double (t, c++, i + heading_rows, 0, gsl_vector_get (extracted, i), NULL);
971     }
972
973   tab_submit (t);
974 }
975
976
977 static void
978 show_factor_matrix (const struct cmd_factor *factor, struct idata *idata, const gsl_matrix *fm)
979 {
980   int i;
981   const int n_factors = n_extracted_factors (factor, idata);
982
983   const int heading_columns = 1;
984   const int heading_rows = 2;
985   const int nr = heading_rows + factor->n_vars;
986   const int nc = heading_columns + n_factors;
987   gsl_permutation *perm;
988
989   struct tab_table *t = tab_create (nc, nr, 0);
990
991   if ( factor->extraction == EXTRACTION_PC )
992     tab_title (t, _("Component Matrix"));
993   else 
994     tab_title (t, _("Factor Matrix"));
995
996   tab_dim (t, tab_natural_dimensions, NULL);
997
998   tab_headers (t, heading_columns, 0, heading_rows, 0);
999
1000   if ( factor->extraction == EXTRACTION_PC )
1001     tab_joint_text (t,
1002                     1, 0,
1003                     nc - 1, 0,
1004                     TAB_CENTER | TAT_TITLE, _("Component"));
1005   else
1006     tab_joint_text (t,
1007                     1, 0,
1008                     nc - 1, 0,
1009                     TAB_CENTER | TAT_TITLE, _("Factor"));
1010
1011
1012   tab_hline (t, TAL_1, heading_columns, nc - 1, 1);
1013
1014
1015   /* Outline the box */
1016   tab_box (t,
1017            TAL_2, TAL_2,
1018            -1, -1,
1019            0, 0,
1020            nc - 1, nr - 1);
1021
1022   /* Vertical lines */
1023   tab_box (t,
1024            -1, -1,
1025            -1, TAL_1,
1026            heading_columns, 1,
1027            nc - 1, nr - 1);
1028
1029   tab_hline (t, TAL_1, 0, nc - 1, heading_rows);
1030   tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
1031
1032
1033   {
1034     gsl_vector_const_view r1 = gsl_matrix_const_row (fm, 0);
1035     gsl_vector_const_view r2 = gsl_matrix_const_row (fm, 1);
1036
1037     dump_vector (&r1.vector);
1038     dump_vector (&r2.vector);
1039   }
1040
1041   /* Initialise to the identity permutation */
1042   perm = gsl_permutation_calloc (factor->n_vars);
1043
1044   if ( factor->sort)
1045     sort_matrix_indirect (fm, perm);
1046
1047   for (i = 0 ; i < n_factors; ++i)
1048     {
1049       tab_text_format (t, heading_columns + i, 1, TAB_CENTER | TAT_TITLE, _("%d"), i + 1);
1050     }
1051
1052   for (i = 0 ; i < factor->n_vars; ++i)
1053     {
1054       int j;
1055       const int matrix_row = perm->data[i];
1056       tab_text (t, 0, i + heading_rows, TAT_TITLE, var_to_string (factor->vars[matrix_row]));
1057
1058       for (j = 0 ; j < n_factors; ++j)
1059         {
1060           double x = gsl_matrix_get (fm, matrix_row, j);
1061
1062           if ( fabs (x) < factor->blank)
1063             continue;
1064
1065           tab_double (t, heading_columns + j, heading_rows + i, 0, x, NULL);
1066         }
1067     }
1068
1069   gsl_permutation_free (perm);
1070
1071   tab_submit (t);
1072 }
1073
1074
1075 static void
1076 show_explained_variance (const struct cmd_factor * factor, struct idata *idata,
1077                          const gsl_vector *initial_eigenvalues,
1078                          const gsl_vector *extracted_eigenvalues)
1079 {
1080   size_t i;
1081   int c = 0;
1082   const int heading_columns = 1;
1083   const int heading_rows = 2;
1084   const int nr = heading_rows + factor->n_vars;
1085
1086   struct tab_table *t ;
1087
1088   double i_total = 0.0;
1089   double i_cum = 0.0;
1090
1091   double e_total = 0.0;
1092   double e_cum = 0.0;
1093
1094   int nc = heading_columns;
1095
1096   if (factor->print & PRINT_EXTRACTION)
1097     nc += 3;
1098
1099   if (factor->print & PRINT_INITIAL)
1100     nc += 3;
1101
1102   if (factor->print & PRINT_ROTATION)
1103     nc += 3;
1104
1105   /* No point having a table with only headings */
1106   if ( nc <= heading_columns)
1107     return;
1108
1109   t = tab_create (nc, nr, 0);
1110
1111   tab_title (t, _("Total Variance Explained"));
1112
1113   tab_dim (t, tab_natural_dimensions, NULL);
1114
1115   tab_headers (t, heading_columns, 0, heading_rows, 0);
1116
1117   /* Outline the box */
1118   tab_box (t,
1119            TAL_2, TAL_2,
1120            -1, -1,
1121            0, 0,
1122            nc - 1, nr - 1);
1123
1124   /* Vertical lines */
1125   tab_box (t,
1126            -1, -1,
1127            -1, TAL_1,
1128            heading_columns, 0,
1129            nc - 1, nr - 1);
1130
1131   tab_hline (t, TAL_1, 0, nc - 1, heading_rows);
1132   tab_hline (t, TAL_1, 1, nc - 1, 1);
1133
1134   tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
1135
1136
1137   if ( factor->extraction == EXTRACTION_PC)
1138     tab_text (t, 0, 1, TAB_LEFT | TAT_TITLE, _("Component"));
1139   else
1140     tab_text (t, 0, 1, TAB_LEFT | TAT_TITLE, _("Factor"));
1141
1142   c = 1;
1143   if (factor->print & PRINT_INITIAL)
1144     {
1145       tab_joint_text (t, c, 0, c + 2, 0, TAB_CENTER | TAT_TITLE, _("Initial Eigenvalues"));
1146       c += 3;
1147     }
1148
1149   if (factor->print & PRINT_EXTRACTION)
1150     {
1151       tab_joint_text (t, c, 0, c + 2, 0, TAB_CENTER | TAT_TITLE, _("Extraction Sums of Squared Loadings"));
1152       c += 3;
1153     }
1154
1155   if (factor->print & PRINT_ROTATION)
1156     {
1157       printf ("C is %d\n", c);
1158       tab_joint_text (t, c, 0, c + 2, 0, TAB_CENTER | TAT_TITLE, _("Rotation Sums of Squared Loadings"));
1159       c += 3;
1160     }
1161
1162   for (i = 0; i < (nc - heading_columns) / 3 ; ++i)
1163     {
1164       tab_text (t, i * 3 + 1, 1, TAB_CENTER | TAT_TITLE, _("Total"));
1165       tab_text (t, i * 3 + 2, 1, TAB_CENTER | TAT_TITLE, _("% of Variance"));
1166       tab_text (t, i * 3 + 3, 1, TAB_CENTER | TAT_TITLE, _("Cumulative %"));
1167
1168       tab_vline (t, TAL_2, heading_columns + i * 3, 0, nr - 1);
1169     }
1170
1171   for (i = 0 ; i < initial_eigenvalues->size; ++i)
1172     i_total += gsl_vector_get (initial_eigenvalues, i);
1173
1174   if ( factor->extraction == EXTRACTION_PAF)
1175     {
1176       e_total = factor->n_vars;
1177     }
1178   else
1179     {
1180       e_total = i_total;
1181     }
1182
1183
1184   for (i = 0 ; i < factor->n_vars; ++i)
1185     {
1186       const double i_lambda = gsl_vector_get (initial_eigenvalues, i);
1187       double i_percent = 100.0 * i_lambda / i_total ;
1188
1189       const double e_lambda = gsl_vector_get (extracted_eigenvalues, i);
1190       double e_percent = 100.0 * e_lambda / e_total ;
1191
1192       c = 0;
1193
1194       tab_text_format (t, c++, i + heading_rows, TAB_LEFT | TAT_TITLE, _("%d"), i + 1);
1195
1196       i_cum += i_percent;
1197       e_cum += e_percent;
1198
1199       /* Initial Eigenvalues */
1200       if (factor->print & PRINT_INITIAL)
1201       {
1202         tab_double (t, c++, i + heading_rows, 0, i_lambda, NULL);
1203         tab_double (t, c++, i + heading_rows, 0, i_percent, NULL);
1204         tab_double (t, c++, i + heading_rows, 0, i_cum, NULL);
1205       }
1206
1207       if (factor->print & PRINT_EXTRACTION)
1208         {
1209           if ( i < n_extracted_factors (factor, idata))
1210             {
1211               /* Sums of squared loadings */
1212               tab_double (t, c++, i + heading_rows, 0, e_lambda, NULL);
1213               tab_double (t, c++, i + heading_rows, 0, e_percent, NULL);
1214               tab_double (t, c++, i + heading_rows, 0, e_cum, NULL);
1215             }
1216         }
1217     }
1218
1219   tab_submit (t);
1220 }
1221
1222
1223
1224 static void
1225 do_factor (const struct cmd_factor *factor, struct casereader *r)
1226 {
1227   struct ccase *c;
1228   const gsl_matrix *cov_matrix;
1229   const gsl_matrix *var_matrix;
1230   const gsl_matrix *mean_matrix;
1231   const gsl_matrix *n_matrix;
1232
1233   const gsl_matrix *analysis_matrix;
1234   struct idata *idata;
1235
1236   struct covariance *cov = covariance_create (factor->n_vars, factor->vars,
1237                                               factor->wv, factor->exclude);
1238
1239   for ( ; (c = casereader_read (r) ); case_unref (c))
1240     {
1241       covariance_accumulate (cov, c);
1242     }
1243
1244   cov_matrix = covariance_calculate (cov);
1245
1246   var_matrix = covariance_moments (cov, MOMENT_VARIANCE);
1247   mean_matrix = covariance_moments (cov, MOMENT_MEAN);
1248   n_matrix = covariance_moments (cov, MOMENT_NONE);
1249
1250   if ( factor->method == METHOD_CORR)
1251     {
1252       analysis_matrix = correlation_from_covariance (cov_matrix, var_matrix);
1253     }
1254   else
1255     analysis_matrix = cov_matrix;
1256
1257   if ( factor->print & PRINT_UNIVARIATE)
1258     {
1259       const int nc = 4;
1260       int i;
1261       const struct fmt_spec *wfmt = factor->wv ? var_get_print_format (factor->wv) : & F_8_0;
1262
1263
1264       const int heading_columns = 1;
1265       const int heading_rows = 1;
1266
1267       const int nr = heading_rows + factor->n_vars;
1268
1269       struct tab_table *t = tab_create (nc, nr, 0);
1270       tab_title (t, _("Descriptive Statistics"));
1271       tab_dim (t, tab_natural_dimensions, NULL);
1272
1273       tab_headers (t, heading_columns, 0, heading_rows, 0);
1274
1275       /* Outline the box */
1276       tab_box (t,
1277                TAL_2, TAL_2,
1278                -1, -1,
1279                0, 0,
1280                nc - 1, nr - 1);
1281
1282       /* Vertical lines */
1283       tab_box (t,
1284                -1, -1,
1285                -1, TAL_1,
1286                heading_columns, 0,
1287                nc - 1, nr - 1);
1288
1289       tab_hline (t, TAL_1, 0, nc - 1, heading_rows);
1290       tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
1291
1292       tab_text (t, 1, 0, TAB_CENTER | TAT_TITLE, _("Mean"));
1293       tab_text (t, 2, 0, TAB_CENTER | TAT_TITLE, _("Std. Deviation"));
1294       tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("Analysis N"));
1295
1296       for (i = 0 ; i < factor->n_vars; ++i)
1297         {
1298           const struct variable *v = factor->vars[i];
1299           tab_text (t, 0, i + heading_rows, TAB_LEFT | TAT_TITLE, var_to_string (v));
1300
1301           tab_double (t, 1, i + heading_rows, 0, gsl_matrix_get (mean_matrix, i, i), NULL);
1302           tab_double (t, 2, i + heading_rows, 0, sqrt (gsl_matrix_get (var_matrix, i, i)), NULL);
1303           tab_double (t, 3, i + heading_rows, 0, gsl_matrix_get (n_matrix, i, i), wfmt);
1304         }
1305
1306       tab_submit (t);
1307     }
1308
1309   if ( factor->print & PRINT_DETERMINANT)
1310     {
1311       const int nc = 2;
1312       const int heading_columns = 0;
1313       const int heading_rows = 0;
1314       const int nr = 1;
1315       struct tab_table *t ;
1316
1317       int sign = 0;
1318       double det = 0.0;
1319       const int size = analysis_matrix->size1;
1320       gsl_permutation *p = gsl_permutation_calloc (size);
1321       gsl_matrix *tmp = gsl_matrix_calloc (size, size);
1322
1323       gsl_matrix_memcpy (tmp, analysis_matrix);
1324       gsl_linalg_LU_decomp (tmp, p, &sign);
1325       det = gsl_linalg_LU_det (tmp, sign);
1326       gsl_permutation_free (p);
1327       gsl_matrix_free (tmp);
1328
1329       t = tab_create (nc, nr, 0);
1330
1331       if ( factor->method == METHOD_CORR)
1332         tab_title (t, _("Correlation Matrix"));
1333       else 
1334         tab_title (t, _("Covariance Matrix"));
1335
1336       tab_dim (t, tab_natural_dimensions, NULL);
1337
1338       tab_headers (t, heading_columns, 0, heading_rows, 0);
1339
1340       tab_hline (t, TAL_1, 0, nc - 1, heading_rows);
1341
1342       tab_text (t, 0, 0, TAB_LEFT | TAT_TITLE, _("Determinant"));
1343       tab_double (t, 1, 0, 0, det, NULL);
1344
1345       tab_submit (t);
1346     }
1347
1348
1349   idata = idata_alloc (factor->n_vars);
1350
1351
1352 #if 1
1353   {
1354     gsl_eigen_symmv_workspace *workspace = gsl_eigen_symmv_alloc (factor->n_vars);
1355     
1356     gsl_eigen_symmv (matrix_dup (analysis_matrix), idata->eval, idata->evec, workspace);
1357
1358     gsl_eigen_symmv_free (workspace);
1359   }
1360
1361   gsl_eigen_symmv_sort (idata->eval, idata->evec, GSL_EIGEN_SORT_ABS_DESC);
1362 #endif
1363
1364   {
1365     const gsl_vector *extracted_eigenvalues = NULL;
1366     gsl_vector *initial_communalities = gsl_vector_alloc (factor->n_vars);
1367     gsl_vector *extracted_communalities = gsl_vector_alloc (factor->n_vars);
1368     size_t i;
1369     struct factor_matrix_workspace *fmw = factor_matrix_workspace_alloc (idata->msr->size, n_extracted_factors (factor, idata));
1370     gsl_matrix *factor_matrix = gsl_matrix_calloc (factor->n_vars, fmw->n_factors);
1371
1372     if ( factor->extraction == EXTRACTION_PAF)
1373       {
1374         gsl_vector *diff = gsl_vector_alloc (idata->msr->size);
1375         struct smr_workspace *ws = ws_create (analysis_matrix);
1376
1377         for (i = 0 ; i < factor->n_vars ; ++i)
1378           {
1379             double r2 = squared_multiple_correlation (analysis_matrix, i, ws);
1380
1381             gsl_vector_set (idata->msr, i, r2);
1382           }
1383         ws_destroy (ws);
1384
1385         gsl_vector_memcpy (initial_communalities, idata->msr);
1386
1387         for (i = 0; i < factor->iterations; ++i)
1388           {
1389             double min, max;
1390             gsl_vector_memcpy (diff, idata->msr);
1391
1392             iterate_factor_matrix (analysis_matrix, idata->msr, factor_matrix, fmw);
1393       
1394             gsl_vector_sub (diff, idata->msr);
1395
1396             gsl_vector_minmax (diff, &min, &max);
1397       
1398             if ( fabs (min) < factor->econverge && fabs (max) < factor->econverge)
1399               break;
1400           }
1401         gsl_vector_free (diff);
1402
1403         gsl_vector_memcpy (extracted_communalities, idata->msr);
1404         extracted_eigenvalues = fmw->eval;
1405       }
1406     else if (factor->extraction == EXTRACTION_PC)
1407       {
1408         for (i = 0 ; i < factor->n_vars; ++i)
1409           {
1410             gsl_vector_set (initial_communalities, i, communality (idata, i, factor->n_vars));
1411           }
1412         gsl_vector_memcpy (extracted_communalities, initial_communalities);
1413
1414         iterate_factor_matrix (analysis_matrix, extracted_communalities, factor_matrix, fmw);
1415         extracted_eigenvalues = idata->eval;
1416       }
1417
1418     show_communalities (factor, initial_communalities, extracted_communalities);
1419
1420     show_explained_variance (factor, idata, idata->eval, extracted_eigenvalues);
1421
1422     factor_matrix_workspace_free (fmw);
1423
1424     show_factor_matrix (factor, idata, factor_matrix);
1425
1426     gsl_vector_free (initial_communalities);
1427     gsl_vector_free (extracted_communalities);
1428   }
1429
1430   idata_free (idata);
1431
1432   casereader_destroy (r);
1433 }