1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 2009, 2010 Free Software Foundation, Inc.
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.
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.
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/>. */
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>
27 #include <math/covariance.h>
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>
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>
44 #include <libpspp/misc.h>
45 #include <libpspp/message.h>
47 #include <output/tab.h>
49 #include <output/charts/scree.h>
50 #include <output/chart-item.h>
53 #define _(msgid) gettext (msgid)
54 #define N_(msgid) msgid
69 enum extraction_method
78 PLOT_ROTATION = 0x0002
83 PRINT_UNIVARIATE = 0x0001,
84 PRINT_DETERMINANT = 0x0002,
88 PRINT_COVARIANCE = 0x0020,
89 PRINT_CORRELATION = 0x0040,
90 PRINT_ROTATION = 0x0080,
91 PRINT_EXTRACTION = 0x0100,
92 PRINT_INITIAL = 0x0200,
106 typedef void (*rotation_coefficients) (double *x, double *y,
107 double a, double b, double c, double d,
108 const gsl_matrix *loadings );
112 varimax_coefficients (double *x, double *y,
113 double a, double b, double c, double d,
114 const gsl_matrix *loadings )
116 *x = d - 2 * a * b / loadings->size1;
117 *y = c - (a * a - b * b) / loadings->size1;
121 equamax_coefficients (double *x, double *y,
122 double a, double b, double c, double d,
123 const gsl_matrix *loadings )
125 *x = d - loadings->size2 * a * b / loadings->size1;
126 *y = c - loadings->size2 * (a * a - b * b) / (2 * loadings->size1);
130 quartimax_coefficients (double *x, double *y,
131 double a UNUSED, double b UNUSED, double c, double d,
132 const gsl_matrix *loadings UNUSED)
138 static const rotation_coefficients rotation_coeff[3] = {
139 varimax_coefficients,
140 equamax_coefficients,
141 quartimax_coefficients
148 const struct variable **vars;
150 const struct variable *wv;
153 enum missing_type missing_type;
154 enum mv_class exclude;
155 enum print_opts print;
156 enum extraction_method extraction;
158 enum rotation_type rotation;
160 /* Extraction Criteria */
175 /* Intermediate values used in calculation */
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 */
181 gsl_vector *eval ; /* The eigenvalues */
182 gsl_matrix *evec ; /* The eigenvectors */
186 gsl_vector *msr ; /* Multiple Squared Regressions */
189 static struct idata *
190 idata_alloc (size_t n_vars)
192 struct idata *id = xzalloc (sizeof (*id));
194 id->n_extractions = 0;
195 id->msr = gsl_vector_alloc (n_vars);
197 id->eval = gsl_vector_alloc (n_vars);
198 id->evec = gsl_matrix_alloc (n_vars, n_vars);
204 idata_free (struct idata *id)
206 gsl_vector_free (id->msr);
207 gsl_vector_free (id->eval);
208 gsl_matrix_free (id->evec);
216 dump_matrix (const gsl_matrix *m)
220 for (i = 0 ; i < m->size1; ++i)
222 for (j = 0 ; j < m->size2; ++j)
223 printf ("%02f ", gsl_matrix_get (m, i, j));
230 dump_matrix_permute (const gsl_matrix *m, const gsl_permutation *p)
234 for (i = 0 ; i < m->size1; ++i)
236 for (j = 0 ; j < m->size2; ++j)
237 printf ("%02f ", gsl_matrix_get (m, gsl_permutation_get (p, i), j));
244 dump_vector (const gsl_vector *v)
247 for (i = 0 ; i < v->size; ++i)
249 printf ("%02f\n", gsl_vector_get (v, i));
257 n_extracted_factors (const struct cmd_factor *factor, struct idata *idata)
261 /* If there is a cached value, then return that. */
262 if ( idata->n_extractions != 0)
263 return idata->n_extractions;
265 /* Otherwise, if the number of factors has been explicitly requested,
267 if (factor->n_factors > 0)
269 idata->n_extractions = factor->n_factors;
273 /* Use the MIN_EIGEN setting. */
274 for (i = 0 ; i < idata->eval->size; ++i)
276 double evali = fabs (gsl_vector_get (idata->eval, i));
278 idata->n_extractions = i;
280 if (evali < factor->min_eigen)
285 return idata->n_extractions;
289 /* Returns a newly allocated matrix identical to M.
290 It it the callers responsibility to free the returned value.
293 matrix_dup (const gsl_matrix *m)
295 gsl_matrix *n = gsl_matrix_alloc (m->size1, m->size2);
297 gsl_matrix_memcpy (n, m);
305 /* Copy of the subject */
310 gsl_permutation *perm;
317 static struct smr_workspace *ws_create (const gsl_matrix *input)
319 struct smr_workspace *ws = xmalloc (sizeof (*ws));
321 ws->m = gsl_matrix_alloc (input->size1, input->size2);
322 ws->inverse = gsl_matrix_calloc (input->size1 - 1, input->size2 - 1);
323 ws->perm = gsl_permutation_alloc (input->size1 - 1);
324 ws->result1 = gsl_matrix_calloc (input->size1 - 1, 1);
325 ws->result2 = gsl_matrix_calloc (1, 1);
331 ws_destroy (struct smr_workspace *ws)
333 gsl_matrix_free (ws->result2);
334 gsl_matrix_free (ws->result1);
335 gsl_permutation_free (ws->perm);
336 gsl_matrix_free (ws->inverse);
337 gsl_matrix_free (ws->m);
344 Return the square of the regression coefficient for VAR regressed against all other variables.
347 squared_multiple_correlation (const gsl_matrix *corr, int var, struct smr_workspace *ws)
349 /* For an explanation of what this is doing, see
350 http://www.visualstatistics.net/Visual%20Statistics%20Multimedia/multiple_regression_analysis.htm
356 gsl_matrix_memcpy (ws->m, corr);
358 gsl_matrix_swap_rows (ws->m, 0, var);
359 gsl_matrix_swap_columns (ws->m, 0, var);
361 rxx = gsl_matrix_submatrix (ws->m, 1, 1, ws->m->size1 - 1, ws->m->size1 - 1);
363 gsl_linalg_LU_decomp (&rxx.matrix, ws->perm, &signum);
365 gsl_linalg_LU_invert (&rxx.matrix, ws->perm, ws->inverse);
368 gsl_matrix_const_view rxy = gsl_matrix_const_submatrix (ws->m, 1, 0, ws->m->size1 - 1, 1);
369 gsl_matrix_const_view ryx = gsl_matrix_const_submatrix (ws->m, 0, 1, 1, ws->m->size1 - 1);
371 gsl_blas_dgemm (CblasNoTrans, CblasNoTrans,
372 1.0, ws->inverse, &rxy.matrix, 0.0, ws->result1);
374 gsl_blas_dgemm (CblasNoTrans, CblasNoTrans,
375 1.0, &ryx.matrix, ws->result1, 0.0, ws->result2);
378 return gsl_matrix_get (ws->result2, 0, 0);
383 static double the_communality (const gsl_matrix *evec, const gsl_vector *eval, int n, int n_factors);
386 struct factor_matrix_workspace
389 gsl_eigen_symmv_workspace *eigen_ws;
399 static struct factor_matrix_workspace *
400 factor_matrix_workspace_alloc (size_t n, size_t nf)
402 struct factor_matrix_workspace *ws = xmalloc (sizeof (*ws));
405 ws->gamma = gsl_matrix_calloc (nf, nf);
406 ws->eigen_ws = gsl_eigen_symmv_alloc (n);
407 ws->eval = gsl_vector_alloc (n);
408 ws->evec = gsl_matrix_alloc (n, n);
409 ws->r = gsl_matrix_alloc (n, n);
415 factor_matrix_workspace_free (struct factor_matrix_workspace *ws)
417 gsl_eigen_symmv_free (ws->eigen_ws);
418 gsl_vector_free (ws->eval);
419 gsl_matrix_free (ws->evec);
420 gsl_matrix_free (ws->gamma);
421 gsl_matrix_free (ws->r);
426 Shift P left by OFFSET places, and overwrite TARGET
427 with the shifted result.
428 Positions in TARGET less than OFFSET are unchanged.
431 perm_shift_apply (gsl_permutation *target, const gsl_permutation *p,
435 assert (target->size == p->size);
436 assert (offset <= target->size);
438 for (i = 0; i < target->size - offset; ++i)
440 target->data[i] = p->data [i + offset];
446 Indirectly sort the rows of matrix INPUT, storing the sort order in PERM.
447 The sort criteria are as follows:
449 Rows are sorted on the first column, until the absolute value of an
450 element in a subsequent column is greater than that of the first
451 column. Thereafter, rows will be sorted on the second column,
452 until the absolute value of an element in a subsequent column
453 exceeds that of the second column ...
456 sort_matrix_indirect (const gsl_matrix *input, gsl_permutation *perm)
458 const size_t n = perm->size;
459 const size_t m = input->size2;
466 assert (perm->size == input->size1);
468 p = gsl_permutation_alloc (n);
470 /* Copy INPUT into MAT, discarding the sign */
471 mat = gsl_matrix_alloc (n, m);
472 for (i = 0 ; i < mat->size1; ++i)
474 for (j = 0 ; j < mat->size2; ++j)
476 double x = gsl_matrix_get (input, i, j);
477 gsl_matrix_set (mat, i, j, fabs (x));
481 while (column_n < m && row_n < n)
483 gsl_vector_const_view columni = gsl_matrix_const_column (mat, column_n);
484 gsl_sort_vector_index (p, &columni.vector);
486 for (i = 0 ; i < n; ++i)
488 gsl_vector_view row = gsl_matrix_row (mat, p->data[n - 1 - i]);
489 size_t maxindex = gsl_vector_max_index (&row.vector);
491 if ( maxindex > column_n )
494 /* All subsequent elements of this row, are of no interest.
495 So set them all to a highly negative value */
496 for (j = column_n + 1; j < row.vector.size ; ++j)
497 gsl_vector_set (&row.vector, j, -DBL_MAX);
500 perm_shift_apply (perm, p, row_n);
506 gsl_permutation_free (p);
507 gsl_matrix_free (mat);
509 assert ( 0 == gsl_permutation_valid (perm));
511 /* We want the biggest value to be first */
512 gsl_permutation_reverse (perm);
517 drot_go (double phi, double *l0, double *l1)
519 double r0 = cos (phi) * *l0 + sin (phi) * *l1;
520 double r1 = - sin (phi) * *l0 + cos (phi) * *l1;
528 clone_matrix (const gsl_matrix *m)
531 gsl_matrix *c = gsl_matrix_calloc (m->size1, m->size2);
533 for (j = 0 ; j < c->size1; ++j)
535 for (k = 0 ; k < c->size2; ++k)
537 const double *v = gsl_matrix_const_ptr (m, j, k);
538 gsl_matrix_set (c, j, k, *v);
547 initial_sv (const gsl_matrix *fm)
552 for (j = 0 ; j < fm->size2; ++j)
557 for (k = j + 1 ; k < fm->size2; ++k)
559 double lambda = gsl_matrix_get (fm, k, j);
560 double lambda_sq = lambda * lambda;
561 double lambda_4 = lambda_sq * lambda_sq;
566 sv += ( fm->size1 * l4s - (l2s * l2s) ) / (fm->size1 * fm->size1 );
572 rotate (const struct cmd_factor *cf, const gsl_matrix *unrot,
573 const gsl_vector *communalities,
575 gsl_vector *rotated_loadings
582 /* First get a normalised version of UNROT */
583 gsl_matrix *normalised = gsl_matrix_calloc (unrot->size1, unrot->size2);
584 gsl_matrix *h_sqrt = gsl_matrix_calloc (communalities->size, communalities->size);
585 gsl_matrix *h_sqrt_inv ;
587 /* H is the diagonal matrix containing the absolute values of the communalities */
588 for (i = 0 ; i < communalities->size ; ++i)
590 double *ptr = gsl_matrix_ptr (h_sqrt, i, i);
591 *ptr = fabs (gsl_vector_get (communalities, i));
594 /* Take the square root of the communalities */
595 gsl_linalg_cholesky_decomp (h_sqrt);
598 /* Save a copy of h_sqrt and invert it */
599 h_sqrt_inv = clone_matrix (h_sqrt);
600 gsl_linalg_cholesky_decomp (h_sqrt_inv);
601 gsl_linalg_cholesky_invert (h_sqrt_inv);
603 /* normalised vertion is H^{1/2} x UNROT */
604 gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, h_sqrt_inv, unrot, 0.0, normalised);
606 gsl_matrix_free (h_sqrt_inv);
609 /* Now perform the rotation iterations */
611 prev_sv = initial_sv (normalised);
612 for (i = 0 ; i < cf->iterations ; ++i)
615 for (j = 0 ; j < normalised->size2; ++j)
617 /* These variables relate to the convergence criterium */
621 for (k = j + 1 ; k < normalised->size2; ++k)
631 for (p = 0; p < normalised->size1; ++p)
633 double jv = gsl_matrix_get (normalised, p, j);
634 double kv = gsl_matrix_get (normalised, p, k);
636 double u = jv * jv - kv * kv;
637 double v = 2 * jv * kv;
644 rotation_coeff [cf->rotation] (&x, &y, a, b, c, d, normalised);
646 phi = atan2 (x, y) / 4.0 ;
648 /* Don't bother rotating if the angle is small */
649 if ( fabs (sin (phi) ) <= pow (10.0, -15.0))
652 for (p = 0; p < normalised->size1; ++p)
654 double *lambda0 = gsl_matrix_ptr (normalised, p, j);
655 double *lambda1 = gsl_matrix_ptr (normalised, p, k);
656 drot_go (phi, lambda0, lambda1);
659 /* Calculate the convergence criterium */
661 double lambda = gsl_matrix_get (normalised, k, j);
662 double lambda_sq = lambda * lambda;
663 double lambda_4 = lambda_sq * lambda_sq;
669 sv += ( normalised->size1 * l4s - (l2s * l2s) ) / (normalised->size1 * normalised->size1 );
672 if ( fabs (sv - prev_sv) <= cf->rconverge)
678 gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0,
679 h_sqrt, normalised, 0.0, result);
681 gsl_matrix_free (h_sqrt);
684 /* reflect negative sums and populate the rotated loadings vector*/
685 for (i = 0 ; i < result->size2; ++i)
689 for (j = 0 ; j < result->size1; ++j)
691 double s = gsl_matrix_get (result, j, i);
693 sum += gsl_matrix_get (result, j, i);
696 gsl_vector_set (rotated_loadings, i, ssq);
699 for (j = 0 ; j < result->size1; ++j)
701 double *lambda = gsl_matrix_ptr (result, j, i);
709 Get an approximation for the factor matrix into FACTORS, and the communalities into COMMUNALITIES.
710 R is the matrix to be analysed.
711 WS is a pointer to a structure which must have been initialised with factor_matrix_workspace_init.
714 iterate_factor_matrix (const gsl_matrix *r, gsl_vector *communalities, gsl_matrix *factors,
715 struct factor_matrix_workspace *ws)
720 assert (r->size1 == r->size2);
721 assert (r->size1 == communalities->size);
723 assert (factors->size1 == r->size1);
724 assert (factors->size2 == ws->n_factors);
726 gsl_matrix_memcpy (ws->r, r);
728 /* Apply Communalities to diagonal of correlation matrix */
729 for (i = 0 ; i < communalities->size ; ++i)
731 double *x = gsl_matrix_ptr (ws->r, i, i);
732 *x = gsl_vector_get (communalities, i);
735 gsl_eigen_symmv (ws->r, ws->eval, ws->evec, ws->eigen_ws);
737 mv = gsl_matrix_submatrix (ws->evec, 0, 0, ws->evec->size1, ws->n_factors);
739 /* Gamma is the diagonal matrix containing the absolute values of the eigenvalues */
740 for (i = 0 ; i < ws->n_factors ; ++i)
742 double *ptr = gsl_matrix_ptr (ws->gamma, i, i);
743 *ptr = fabs (gsl_vector_get (ws->eval, i));
746 /* Take the square root of gamma */
747 gsl_linalg_cholesky_decomp (ws->gamma);
749 gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, &mv.matrix, ws->gamma, 0.0, factors);
751 for (i = 0 ; i < r->size1 ; ++i)
753 double h = the_communality (ws->evec, ws->eval, i, ws->n_factors);
754 gsl_vector_set (communalities, i, h);
760 static bool run_factor (struct dataset *ds, const struct cmd_factor *factor);
764 cmd_factor (struct lexer *lexer, struct dataset *ds)
766 bool extraction_seen = false;
767 const struct dictionary *dict = dataset_dict (ds);
769 struct cmd_factor factor;
772 factor.method = METHOD_CORR;
773 factor.missing_type = MISS_LISTWISE;
774 factor.exclude = MV_ANY;
775 factor.print = PRINT_INITIAL | PRINT_EXTRACTION | PRINT_ROTATION;
776 factor.extraction = EXTRACTION_PC;
777 factor.n_factors = 0;
778 factor.min_eigen = SYSMIS;
779 factor.iterations = 25;
780 factor.econverge = 0.001;
785 factor.rotation = ROT_VARIMAX;
787 factor.rconverge = 0.0001;
789 factor.wv = dict_get_weight (dict);
791 lex_match (lexer, '/');
793 if (!lex_force_match_id (lexer, "VARIABLES"))
798 lex_match (lexer, '=');
800 if (!parse_variables_const (lexer, dict, &factor.vars, &factor.n_vars,
801 PV_NO_DUPLICATE | PV_NUMERIC))
804 if (factor.n_vars < 2)
805 msg (MW, _("Factor analysis on a single variable is not useful."));
807 while (lex_token (lexer) != '.')
809 lex_match (lexer, '/');
811 if (lex_match_id (lexer, "PLOT"))
813 lex_match (lexer, '=');
814 while (lex_token (lexer) != '.' && lex_token (lexer) != '/')
816 if (lex_match_id (lexer, "EIGEN"))
818 factor.plot |= PLOT_SCREE;
820 #if FACTOR_FULLY_IMPLEMENTED
821 else if (lex_match_id (lexer, "ROTATION"))
827 lex_error (lexer, NULL);
832 else if (lex_match_id (lexer, "METHOD"))
834 lex_match (lexer, '=');
835 while (lex_token (lexer) != '.' && lex_token (lexer) != '/')
837 if (lex_match_id (lexer, "COVARIANCE"))
839 factor.method = METHOD_COV;
841 else if (lex_match_id (lexer, "CORRELATION"))
843 factor.method = METHOD_CORR;
847 lex_error (lexer, NULL);
852 else if (lex_match_id (lexer, "ROTATION"))
854 lex_match (lexer, '=');
855 while (lex_token (lexer) != '.' && lex_token (lexer) != '/')
857 /* VARIMAX and DEFAULT are defaults */
858 if (lex_match_id (lexer, "VARIMAX") || lex_match_id (lexer, "DEFAULT"))
860 factor.rotation = ROT_VARIMAX;
862 else if (lex_match_id (lexer, "EQUAMAX"))
864 factor.rotation = ROT_EQUAMAX;
866 else if (lex_match_id (lexer, "QUARTIMAX"))
868 factor.rotation = ROT_QUARTIMAX;
870 else if (lex_match_id (lexer, "NOROTATE"))
872 factor.rotation = ROT_NONE;
876 lex_error (lexer, NULL);
881 else if (lex_match_id (lexer, "CRITERIA"))
883 lex_match (lexer, '=');
884 while (lex_token (lexer) != '.' && lex_token (lexer) != '/')
886 if (lex_match_id (lexer, "FACTORS"))
888 if ( lex_force_match (lexer, '('))
890 lex_force_int (lexer);
891 factor.n_factors = lex_integer (lexer);
893 lex_force_match (lexer, ')');
896 else if (lex_match_id (lexer, "MINEIGEN"))
898 if ( lex_force_match (lexer, '('))
900 lex_force_num (lexer);
901 factor.min_eigen = lex_number (lexer);
903 lex_force_match (lexer, ')');
906 else if (lex_match_id (lexer, "ECONVERGE"))
908 if ( lex_force_match (lexer, '('))
910 lex_force_num (lexer);
911 factor.econverge = lex_number (lexer);
913 lex_force_match (lexer, ')');
916 else if (lex_match_id (lexer, "RCONVERGE"))
918 if ( lex_force_match (lexer, '('))
920 lex_force_num (lexer);
921 factor.rconverge = lex_number (lexer);
923 lex_force_match (lexer, ')');
926 else if (lex_match_id (lexer, "ITERATE"))
928 if ( lex_force_match (lexer, '('))
930 lex_force_int (lexer);
931 factor.iterations = lex_integer (lexer);
933 lex_force_match (lexer, ')');
936 else if (lex_match_id (lexer, "DEFAULT"))
938 factor.n_factors = 0;
939 factor.min_eigen = 1;
940 factor.iterations = 25;
944 lex_error (lexer, NULL);
949 else if (lex_match_id (lexer, "EXTRACTION"))
951 extraction_seen = true;
952 lex_match (lexer, '=');
953 while (lex_token (lexer) != '.' && lex_token (lexer) != '/')
955 if (lex_match_id (lexer, "PAF"))
957 factor.extraction = EXTRACTION_PAF;
959 else if (lex_match_id (lexer, "PC"))
961 factor.extraction = EXTRACTION_PC;
963 else if (lex_match_id (lexer, "PA1"))
965 factor.extraction = EXTRACTION_PC;
967 else if (lex_match_id (lexer, "DEFAULT"))
969 factor.extraction = EXTRACTION_PC;
973 lex_error (lexer, NULL);
978 else if (lex_match_id (lexer, "FORMAT"))
980 lex_match (lexer, '=');
981 while (lex_token (lexer) != '.' && lex_token (lexer) != '/')
983 if (lex_match_id (lexer, "SORT"))
987 else if (lex_match_id (lexer, "BLANK"))
989 if ( lex_force_match (lexer, '('))
991 lex_force_num (lexer);
992 factor.blank = lex_number (lexer);
994 lex_force_match (lexer, ')');
997 else if (lex_match_id (lexer, "DEFAULT"))
1000 factor.sort = false;
1004 lex_error (lexer, NULL);
1009 else if (lex_match_id (lexer, "PRINT"))
1012 lex_match (lexer, '=');
1013 while (lex_token (lexer) != '.' && lex_token (lexer) != '/')
1015 if (lex_match_id (lexer, "UNIVARIATE"))
1017 factor.print |= PRINT_UNIVARIATE;
1019 else if (lex_match_id (lexer, "DET"))
1021 factor.print |= PRINT_DETERMINANT;
1023 #if FACTOR_FULLY_IMPLEMENTED
1024 else if (lex_match_id (lexer, "INV"))
1027 else if (lex_match_id (lexer, "AIC"))
1031 else if (lex_match_id (lexer, "SIG"))
1033 factor.print |= PRINT_SIG;
1035 else if (lex_match_id (lexer, "CORRELATION"))
1037 factor.print |= PRINT_CORRELATION;
1039 #if FACTOR_FULLY_IMPLEMENTED
1040 else if (lex_match_id (lexer, "COVARIANCE"))
1044 else if (lex_match_id (lexer, "ROTATION"))
1046 factor.print |= PRINT_ROTATION;
1048 else if (lex_match_id (lexer, "EXTRACTION"))
1050 factor.print |= PRINT_EXTRACTION;
1052 else if (lex_match_id (lexer, "INITIAL"))
1054 factor.print |= PRINT_INITIAL;
1056 #if FACTOR_FULLY_IMPLEMENTED
1057 else if (lex_match_id (lexer, "KMO"))
1060 else if (lex_match_id (lexer, "REPR"))
1063 else if (lex_match_id (lexer, "FSCORE"))
1067 else if (lex_match (lexer, T_ALL))
1069 factor.print = 0xFFFF;
1071 else if (lex_match_id (lexer, "DEFAULT"))
1073 factor.print |= PRINT_INITIAL ;
1074 factor.print |= PRINT_EXTRACTION ;
1075 factor.print |= PRINT_ROTATION ;
1079 lex_error (lexer, NULL);
1084 else if (lex_match_id (lexer, "MISSING"))
1086 lex_match (lexer, '=');
1087 while (lex_token (lexer) != '.' && lex_token (lexer) != '/')
1089 if (lex_match_id (lexer, "INCLUDE"))
1091 factor.exclude = MV_SYSTEM;
1093 else if (lex_match_id (lexer, "EXCLUDE"))
1095 factor.exclude = MV_ANY;
1097 else if (lex_match_id (lexer, "LISTWISE"))
1099 factor.missing_type = MISS_LISTWISE;
1101 else if (lex_match_id (lexer, "PAIRWISE"))
1103 factor.missing_type = MISS_PAIRWISE;
1105 else if (lex_match_id (lexer, "MEANSUB"))
1107 factor.missing_type = MISS_MEANSUB;
1111 lex_error (lexer, NULL);
1118 lex_error (lexer, NULL);
1123 if ( factor.rotation == ROT_NONE )
1124 factor.print &= ~PRINT_ROTATION;
1126 if ( ! run_factor (ds, &factor))
1137 static void do_factor (const struct cmd_factor *factor, struct casereader *group);
1141 run_factor (struct dataset *ds, const struct cmd_factor *factor)
1143 struct dictionary *dict = dataset_dict (ds);
1145 struct casereader *group;
1147 struct casegrouper *grouper = casegrouper_create_splits (proc_open (ds), dict);
1149 while (casegrouper_get_next_group (grouper, &group))
1151 if ( factor->missing_type == MISS_LISTWISE )
1152 group = casereader_create_filter_missing (group, factor->vars, factor->n_vars,
1155 do_factor (factor, group);
1158 ok = casegrouper_destroy (grouper);
1159 ok = proc_commit (ds) && ok;
1165 /* Return the communality of variable N, calculated to N_FACTORS */
1167 the_communality (const gsl_matrix *evec, const gsl_vector *eval, int n, int n_factors)
1174 assert (n < eval->size);
1175 assert (n < evec->size1);
1176 assert (n_factors <= eval->size);
1178 for (i = 0 ; i < n_factors; ++i)
1180 double evali = fabs (gsl_vector_get (eval, i));
1182 double eveci = gsl_matrix_get (evec, n, i);
1184 comm += pow2 (eveci) * evali;
1190 /* Return the communality of variable N, calculated to N_FACTORS */
1192 communality (struct idata *idata, int n, int n_factors)
1194 return the_communality (idata->evec, idata->eval, n, n_factors);
1199 show_scree (const struct cmd_factor *f, struct idata *idata)
1204 if ( !(f->plot & PLOT_SCREE) )
1208 label = f->extraction == EXTRACTION_PC ? _("Component Number") : _("Factor Number");
1210 s = scree_create (idata->eval, label);
1216 show_communalities (const struct cmd_factor * factor,
1217 const gsl_vector *initial, const gsl_vector *extracted)
1221 const int heading_columns = 1;
1222 int nc = heading_columns;
1223 const int heading_rows = 1;
1224 const int nr = heading_rows + factor->n_vars;
1225 struct tab_table *t;
1227 if (factor->print & PRINT_EXTRACTION)
1230 if (factor->print & PRINT_INITIAL)
1233 /* No point having a table with only headings */
1237 t = tab_create (nc, nr);
1239 tab_title (t, _("Communalities"));
1241 tab_headers (t, heading_columns, 0, heading_rows, 0);
1244 if (factor->print & PRINT_INITIAL)
1245 tab_text (t, c++, 0, TAB_CENTER | TAT_TITLE, _("Initial"));
1247 if (factor->print & PRINT_EXTRACTION)
1248 tab_text (t, c++, 0, TAB_CENTER | TAT_TITLE, _("Extraction"));
1250 /* Outline the box */
1257 /* Vertical lines */
1264 tab_hline (t, TAL_1, 0, nc - 1, heading_rows);
1265 tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
1267 for (i = 0 ; i < factor->n_vars; ++i)
1270 tab_text (t, c++, i + heading_rows, TAT_TITLE, var_to_string (factor->vars[i]));
1272 if (factor->print & PRINT_INITIAL)
1273 tab_double (t, c++, i + heading_rows, 0, gsl_vector_get (initial, i), NULL);
1275 if (factor->print & PRINT_EXTRACTION)
1276 tab_double (t, c++, i + heading_rows, 0, gsl_vector_get (extracted, i), NULL);
1284 show_factor_matrix (const struct cmd_factor *factor, struct idata *idata, const char *title, const gsl_matrix *fm)
1287 const int n_factors = idata->n_extractions;
1289 const int heading_columns = 1;
1290 const int heading_rows = 2;
1291 const int nr = heading_rows + factor->n_vars;
1292 const int nc = heading_columns + n_factors;
1293 gsl_permutation *perm;
1295 struct tab_table *t = tab_create (nc, nr);
1298 if ( factor->extraction == EXTRACTION_PC )
1299 tab_title (t, _("Component Matrix"));
1301 tab_title (t, _("Factor Matrix"));
1304 tab_title (t, title);
1306 tab_headers (t, heading_columns, 0, heading_rows, 0);
1308 if ( factor->extraction == EXTRACTION_PC )
1312 TAB_CENTER | TAT_TITLE, _("Component"));
1317 TAB_CENTER | TAT_TITLE, _("Factor"));
1320 tab_hline (t, TAL_1, heading_columns, nc - 1, 1);
1323 /* Outline the box */
1330 /* Vertical lines */
1337 tab_hline (t, TAL_1, 0, nc - 1, heading_rows);
1338 tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
1341 /* Initialise to the identity permutation */
1342 perm = gsl_permutation_calloc (factor->n_vars);
1345 sort_matrix_indirect (fm, perm);
1347 for (i = 0 ; i < n_factors; ++i)
1349 tab_text_format (t, heading_columns + i, 1, TAB_CENTER | TAT_TITLE, _("%d"), i + 1);
1352 for (i = 0 ; i < factor->n_vars; ++i)
1355 const int matrix_row = perm->data[i];
1356 tab_text (t, 0, i + heading_rows, TAT_TITLE, var_to_string (factor->vars[matrix_row]));
1358 for (j = 0 ; j < n_factors; ++j)
1360 double x = gsl_matrix_get (fm, matrix_row, j);
1362 if ( fabs (x) < factor->blank)
1365 tab_double (t, heading_columns + j, heading_rows + i, 0, x, NULL);
1369 gsl_permutation_free (perm);
1376 show_explained_variance (const struct cmd_factor * factor, struct idata *idata,
1377 const gsl_vector *initial_eigenvalues,
1378 const gsl_vector *extracted_eigenvalues,
1379 const gsl_vector *rotated_loadings)
1383 const int heading_columns = 1;
1384 const int heading_rows = 2;
1385 const int nr = heading_rows + factor->n_vars;
1387 struct tab_table *t ;
1389 double i_total = 0.0;
1392 double e_total = 0.0;
1397 int nc = heading_columns;
1399 if (factor->print & PRINT_EXTRACTION)
1402 if (factor->print & PRINT_INITIAL)
1405 if (factor->print & PRINT_ROTATION)
1408 /* No point having a table with only headings */
1409 if ( nc <= heading_columns)
1412 t = tab_create (nc, nr);
1414 tab_title (t, _("Total Variance Explained"));
1416 tab_headers (t, heading_columns, 0, heading_rows, 0);
1418 /* Outline the box */
1425 /* Vertical lines */
1432 tab_hline (t, TAL_1, 0, nc - 1, heading_rows);
1433 tab_hline (t, TAL_1, 1, nc - 1, 1);
1435 tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
1438 if ( factor->extraction == EXTRACTION_PC)
1439 tab_text (t, 0, 1, TAB_LEFT | TAT_TITLE, _("Component"));
1441 tab_text (t, 0, 1, TAB_LEFT | TAT_TITLE, _("Factor"));
1444 if (factor->print & PRINT_INITIAL)
1446 tab_joint_text (t, c, 0, c + 2, 0, TAB_CENTER | TAT_TITLE, _("Initial Eigenvalues"));
1450 if (factor->print & PRINT_EXTRACTION)
1452 tab_joint_text (t, c, 0, c + 2, 0, TAB_CENTER | TAT_TITLE, _("Extraction Sums of Squared Loadings"));
1456 if (factor->print & PRINT_ROTATION)
1458 tab_joint_text (t, c, 0, c + 2, 0, TAB_CENTER | TAT_TITLE, _("Rotation Sums of Squared Loadings"));
1462 for (i = 0; i < (nc - heading_columns) / 3 ; ++i)
1464 tab_text (t, i * 3 + 1, 1, TAB_CENTER | TAT_TITLE, _("Total"));
1465 /* xgettext:no-c-format */
1466 tab_text (t, i * 3 + 2, 1, TAB_CENTER | TAT_TITLE, _("% of Variance"));
1467 tab_text (t, i * 3 + 3, 1, TAB_CENTER | TAT_TITLE, _("Cumulative %"));
1469 tab_vline (t, TAL_2, heading_columns + i * 3, 0, nr - 1);
1472 for (i = 0 ; i < initial_eigenvalues->size; ++i)
1473 i_total += gsl_vector_get (initial_eigenvalues, i);
1475 if ( factor->extraction == EXTRACTION_PAF)
1477 e_total = factor->n_vars;
1484 for (i = 0 ; i < factor->n_vars; ++i)
1486 const double i_lambda = gsl_vector_get (initial_eigenvalues, i);
1487 double i_percent = 100.0 * i_lambda / i_total ;
1489 const double e_lambda = gsl_vector_get (extracted_eigenvalues, i);
1490 double e_percent = 100.0 * e_lambda / e_total ;
1492 const double r_lambda = gsl_vector_get (rotated_loadings, i);
1493 double r_percent = 100.0 * r_lambda / e_total ;
1497 tab_text_format (t, c++, i + heading_rows, TAB_LEFT | TAT_TITLE, _("%d"), i + 1);
1503 /* Initial Eigenvalues */
1504 if (factor->print & PRINT_INITIAL)
1506 tab_double (t, c++, i + heading_rows, 0, i_lambda, NULL);
1507 tab_double (t, c++, i + heading_rows, 0, i_percent, NULL);
1508 tab_double (t, c++, i + heading_rows, 0, i_cum, NULL);
1512 if (factor->print & PRINT_EXTRACTION)
1514 if (i < idata->n_extractions)
1516 /* Sums of squared loadings */
1517 tab_double (t, c++, i + heading_rows, 0, e_lambda, NULL);
1518 tab_double (t, c++, i + heading_rows, 0, e_percent, NULL);
1519 tab_double (t, c++, i + heading_rows, 0, e_cum, NULL);
1523 if (factor->print & PRINT_ROTATION)
1525 if (i < idata->n_extractions)
1527 tab_double (t, c++, i + heading_rows, 0, r_lambda, NULL);
1528 tab_double (t, c++, i + heading_rows, 0, r_percent, NULL);
1529 tab_double (t, c++, i + heading_rows, 0, r_cum, NULL);
1540 show_correlation_matrix (const struct cmd_factor *factor, const struct idata *idata)
1542 struct tab_table *t ;
1544 int y_pos_corr = -1;
1546 int suffix_rows = 0;
1548 const int heading_rows = 1;
1549 const int heading_columns = 2;
1551 int nc = heading_columns ;
1552 int nr = heading_rows ;
1553 int n_data_sets = 0;
1555 if (factor->print & PRINT_CORRELATION)
1557 y_pos_corr = n_data_sets;
1559 nc = heading_columns + factor->n_vars;
1562 if (factor->print & PRINT_SIG)
1564 y_pos_sig = n_data_sets;
1566 nc = heading_columns + factor->n_vars;
1569 nr += n_data_sets * factor->n_vars;
1571 if (factor->print & PRINT_DETERMINANT)
1574 /* If the table would contain only headings, don't bother rendering it */
1575 if (nr <= heading_rows && suffix_rows == 0)
1578 t = tab_create (nc, nr + suffix_rows);
1580 tab_title (t, _("Correlation Matrix"));
1582 tab_hline (t, TAL_1, 0, nc - 1, heading_rows);
1584 if (nr > heading_rows)
1586 tab_headers (t, heading_columns, 0, heading_rows, 0);
1588 tab_vline (t, TAL_2, 2, 0, nr - 1);
1590 /* Outline the box */
1597 /* Vertical lines */
1605 for (i = 0; i < factor->n_vars; ++i)
1606 tab_text (t, heading_columns + i, 0, TAT_TITLE, var_to_string (factor->vars[i]));
1609 for (i = 0 ; i < n_data_sets; ++i)
1611 int y = heading_rows + i * factor->n_vars;
1613 for (v = 0; v < factor->n_vars; ++v)
1614 tab_text (t, 1, y + v, TAT_TITLE, var_to_string (factor->vars[v]));
1616 tab_hline (t, TAL_1, 0, nc - 1, y);
1619 if (factor->print & PRINT_CORRELATION)
1621 const double y = heading_rows + y_pos_corr;
1622 tab_text (t, 0, y, TAT_TITLE, _("Correlations"));
1624 for (i = 0; i < factor->n_vars; ++i)
1626 for (j = 0; j < factor->n_vars; ++j)
1627 tab_double (t, heading_columns + i, y + j, 0, gsl_matrix_get (idata->corr, i, j), NULL);
1631 if (factor->print & PRINT_SIG)
1633 const double y = heading_rows + y_pos_sig * factor->n_vars;
1634 tab_text (t, 0, y, TAT_TITLE, _("Sig. 1-tailed"));
1636 for (i = 0; i < factor->n_vars; ++i)
1638 for (j = 0; j < factor->n_vars; ++j)
1640 double rho = gsl_matrix_get (idata->corr, i, j);
1641 double w = gsl_matrix_get (idata->n, i, j);
1646 tab_double (t, heading_columns + i, y + j, 0, significance_of_correlation (rho, w), NULL);
1652 if (factor->print & PRINT_DETERMINANT)
1657 const int size = idata->corr->size1;
1658 gsl_permutation *p = gsl_permutation_calloc (size);
1659 gsl_matrix *tmp = gsl_matrix_calloc (size, size);
1660 gsl_matrix_memcpy (tmp, idata->corr);
1662 gsl_linalg_LU_decomp (tmp, p, &sign);
1663 det = gsl_linalg_LU_det (tmp, sign);
1664 gsl_permutation_free (p);
1665 gsl_matrix_free (tmp);
1668 tab_text (t, 0, nr, TAB_LEFT | TAT_TITLE, _("Determinant"));
1669 tab_double (t, 1, nr, 0, det, NULL);
1678 do_factor (const struct cmd_factor *factor, struct casereader *r)
1681 const gsl_matrix *var_matrix;
1682 const gsl_matrix *mean_matrix;
1684 const gsl_matrix *analysis_matrix;
1685 struct idata *idata = idata_alloc (factor->n_vars);
1687 struct covariance *cov = covariance_1pass_create (factor->n_vars, factor->vars,
1688 factor->wv, factor->exclude);
1690 for ( ; (c = casereader_read (r) ); case_unref (c))
1692 covariance_accumulate (cov, c);
1695 idata->cov = covariance_calculate (cov);
1697 var_matrix = covariance_moments (cov, MOMENT_VARIANCE);
1698 mean_matrix = covariance_moments (cov, MOMENT_MEAN);
1699 idata->n = covariance_moments (cov, MOMENT_NONE);
1701 if ( factor->method == METHOD_CORR)
1703 idata->corr = correlation_from_covariance (idata->cov, var_matrix);
1704 analysis_matrix = idata->corr;
1707 analysis_matrix = idata->cov;
1709 if ( factor->print & PRINT_UNIVARIATE)
1713 const struct fmt_spec *wfmt = factor->wv ? var_get_print_format (factor->wv) : & F_8_0;
1716 const int heading_columns = 1;
1717 const int heading_rows = 1;
1719 const int nr = heading_rows + factor->n_vars;
1721 struct tab_table *t = tab_create (nc, nr);
1722 tab_title (t, _("Descriptive Statistics"));
1724 tab_headers (t, heading_columns, 0, heading_rows, 0);
1726 /* Outline the box */
1733 /* Vertical lines */
1740 tab_hline (t, TAL_1, 0, nc - 1, heading_rows);
1741 tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
1743 tab_text (t, 1, 0, TAB_CENTER | TAT_TITLE, _("Mean"));
1744 tab_text (t, 2, 0, TAB_CENTER | TAT_TITLE, _("Std. Deviation"));
1745 tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("Analysis N"));
1747 for (i = 0 ; i < factor->n_vars; ++i)
1749 const struct variable *v = factor->vars[i];
1750 tab_text (t, 0, i + heading_rows, TAB_LEFT | TAT_TITLE, var_to_string (v));
1752 tab_double (t, 1, i + heading_rows, 0, gsl_matrix_get (mean_matrix, i, i), NULL);
1753 tab_double (t, 2, i + heading_rows, 0, sqrt (gsl_matrix_get (var_matrix, i, i)), NULL);
1754 tab_double (t, 3, i + heading_rows, 0, gsl_matrix_get (idata->n, i, i), wfmt);
1760 show_correlation_matrix (factor, idata);
1764 gsl_eigen_symmv_workspace *workspace = gsl_eigen_symmv_alloc (factor->n_vars);
1766 gsl_eigen_symmv (matrix_dup (analysis_matrix), idata->eval, idata->evec, workspace);
1768 gsl_eigen_symmv_free (workspace);
1771 gsl_eigen_symmv_sort (idata->eval, idata->evec, GSL_EIGEN_SORT_ABS_DESC);
1774 idata->n_extractions = n_extracted_factors (factor, idata);
1776 if (idata->n_extractions == 0)
1778 msg (MW, _("The FACTOR criteria result in zero factors extracted. Therefore no analysis will be performed."));
1782 if (idata->n_extractions > factor->n_vars)
1784 msg (MW, _("The FACTOR criteria result in more factors than variables, which is not meaningful. No analysis will be performed."));
1789 gsl_matrix *rotated_factors = NULL;
1790 gsl_vector *rotated_loadings = NULL;
1792 const gsl_vector *extracted_eigenvalues = NULL;
1793 gsl_vector *initial_communalities = gsl_vector_alloc (factor->n_vars);
1794 gsl_vector *extracted_communalities = gsl_vector_alloc (factor->n_vars);
1796 struct factor_matrix_workspace *fmw = factor_matrix_workspace_alloc (idata->msr->size, idata->n_extractions);
1797 gsl_matrix *factor_matrix = gsl_matrix_calloc (factor->n_vars, fmw->n_factors);
1799 if ( factor->extraction == EXTRACTION_PAF)
1801 gsl_vector *diff = gsl_vector_alloc (idata->msr->size);
1802 struct smr_workspace *ws = ws_create (analysis_matrix);
1804 for (i = 0 ; i < factor->n_vars ; ++i)
1806 double r2 = squared_multiple_correlation (analysis_matrix, i, ws);
1808 gsl_vector_set (idata->msr, i, r2);
1812 gsl_vector_memcpy (initial_communalities, idata->msr);
1814 for (i = 0; i < factor->iterations; ++i)
1817 gsl_vector_memcpy (diff, idata->msr);
1819 iterate_factor_matrix (analysis_matrix, idata->msr, factor_matrix, fmw);
1821 gsl_vector_sub (diff, idata->msr);
1823 gsl_vector_minmax (diff, &min, &max);
1825 if ( fabs (min) < factor->econverge && fabs (max) < factor->econverge)
1828 gsl_vector_free (diff);
1832 gsl_vector_memcpy (extracted_communalities, idata->msr);
1833 extracted_eigenvalues = fmw->eval;
1835 else if (factor->extraction == EXTRACTION_PC)
1837 for (i = 0; i < factor->n_vars; ++i)
1838 gsl_vector_set (initial_communalities, i, communality (idata, i, factor->n_vars));
1840 gsl_vector_memcpy (extracted_communalities, initial_communalities);
1842 iterate_factor_matrix (analysis_matrix, extracted_communalities, factor_matrix, fmw);
1845 extracted_eigenvalues = idata->eval;
1849 show_communalities (factor, initial_communalities, extracted_communalities);
1852 if ( factor->rotation != ROT_NONE)
1854 rotated_factors = gsl_matrix_calloc (factor_matrix->size1, factor_matrix->size2);
1855 rotated_loadings = gsl_vector_calloc (factor_matrix->size2);
1857 rotate (factor, factor_matrix, extracted_communalities, rotated_factors, rotated_loadings);
1860 show_explained_variance (factor, idata, idata->eval, extracted_eigenvalues, rotated_loadings);
1862 factor_matrix_workspace_free (fmw);
1864 show_scree (factor, idata);
1866 show_factor_matrix (factor, idata,
1867 factor->extraction == EXTRACTION_PC ? _("Component Matrix") : _("Factor Matrix"),
1870 if ( factor->rotation != ROT_NONE)
1872 show_factor_matrix (factor, idata,
1873 factor->extraction == EXTRACTION_PC ? _("Rotated Component Matrix") : _("Rotated Factor Matrix"),
1876 gsl_matrix_free (rotated_factors);
1881 gsl_vector_free (initial_communalities);
1882 gsl_vector_free (extracted_communalities);
1889 casereader_destroy (r);