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 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);
210 gsl_matrix_free (id->cov);
218 dump_matrix (const gsl_matrix *m)
222 for (i = 0 ; i < m->size1; ++i)
224 for (j = 0 ; j < m->size2; ++j)
225 printf ("%02f ", gsl_matrix_get (m, i, j));
232 dump_matrix_permute (const gsl_matrix *m, const gsl_permutation *p)
236 for (i = 0 ; i < m->size1; ++i)
238 for (j = 0 ; j < m->size2; ++j)
239 printf ("%02f ", gsl_matrix_get (m, gsl_permutation_get (p, i), j));
246 dump_vector (const gsl_vector *v)
249 for (i = 0 ; i < v->size; ++i)
251 printf ("%02f\n", gsl_vector_get (v, i));
259 n_extracted_factors (const struct cmd_factor *factor, struct idata *idata)
263 /* If there is a cached value, then return that. */
264 if ( idata->n_extractions != 0)
265 return idata->n_extractions;
267 /* Otherwise, if the number of factors has been explicitly requested,
269 if (factor->n_factors > 0)
271 idata->n_extractions = factor->n_factors;
275 /* Use the MIN_EIGEN setting. */
276 for (i = 0 ; i < idata->eval->size; ++i)
278 double evali = fabs (gsl_vector_get (idata->eval, i));
280 idata->n_extractions = i;
282 if (evali < factor->min_eigen)
287 return idata->n_extractions;
291 /* Returns a newly allocated matrix identical to M.
292 It it the callers responsibility to free the returned value.
295 matrix_dup (const gsl_matrix *m)
297 gsl_matrix *n = gsl_matrix_alloc (m->size1, m->size2);
299 gsl_matrix_memcpy (n, m);
307 /* Copy of the subject */
312 gsl_permutation *perm;
319 static struct smr_workspace *ws_create (const gsl_matrix *input)
321 struct smr_workspace *ws = xmalloc (sizeof (*ws));
323 ws->m = gsl_matrix_alloc (input->size1, input->size2);
324 ws->inverse = gsl_matrix_calloc (input->size1 - 1, input->size2 - 1);
325 ws->perm = gsl_permutation_alloc (input->size1 - 1);
326 ws->result1 = gsl_matrix_calloc (input->size1 - 1, 1);
327 ws->result2 = gsl_matrix_calloc (1, 1);
333 ws_destroy (struct smr_workspace *ws)
335 gsl_matrix_free (ws->result2);
336 gsl_matrix_free (ws->result1);
337 gsl_permutation_free (ws->perm);
338 gsl_matrix_free (ws->inverse);
339 gsl_matrix_free (ws->m);
346 Return the square of the regression coefficient for VAR regressed against all other variables.
349 squared_multiple_correlation (const gsl_matrix *corr, int var, struct smr_workspace *ws)
351 /* For an explanation of what this is doing, see
352 http://www.visualstatistics.net/Visual%20Statistics%20Multimedia/multiple_regression_analysis.htm
358 gsl_matrix_memcpy (ws->m, corr);
360 gsl_matrix_swap_rows (ws->m, 0, var);
361 gsl_matrix_swap_columns (ws->m, 0, var);
363 rxx = gsl_matrix_submatrix (ws->m, 1, 1, ws->m->size1 - 1, ws->m->size1 - 1);
365 gsl_linalg_LU_decomp (&rxx.matrix, ws->perm, &signum);
367 gsl_linalg_LU_invert (&rxx.matrix, ws->perm, ws->inverse);
370 gsl_matrix_const_view rxy = gsl_matrix_const_submatrix (ws->m, 1, 0, ws->m->size1 - 1, 1);
371 gsl_matrix_const_view ryx = gsl_matrix_const_submatrix (ws->m, 0, 1, 1, ws->m->size1 - 1);
373 gsl_blas_dgemm (CblasNoTrans, CblasNoTrans,
374 1.0, ws->inverse, &rxy.matrix, 0.0, ws->result1);
376 gsl_blas_dgemm (CblasNoTrans, CblasNoTrans,
377 1.0, &ryx.matrix, ws->result1, 0.0, ws->result2);
380 return gsl_matrix_get (ws->result2, 0, 0);
385 static double the_communality (const gsl_matrix *evec, const gsl_vector *eval, int n, int n_factors);
388 struct factor_matrix_workspace
391 gsl_eigen_symmv_workspace *eigen_ws;
401 static struct factor_matrix_workspace *
402 factor_matrix_workspace_alloc (size_t n, size_t nf)
404 struct factor_matrix_workspace *ws = xmalloc (sizeof (*ws));
407 ws->gamma = gsl_matrix_calloc (nf, nf);
408 ws->eigen_ws = gsl_eigen_symmv_alloc (n);
409 ws->eval = gsl_vector_alloc (n);
410 ws->evec = gsl_matrix_alloc (n, n);
411 ws->r = gsl_matrix_alloc (n, n);
417 factor_matrix_workspace_free (struct factor_matrix_workspace *ws)
419 gsl_eigen_symmv_free (ws->eigen_ws);
420 gsl_vector_free (ws->eval);
421 gsl_matrix_free (ws->evec);
422 gsl_matrix_free (ws->gamma);
423 gsl_matrix_free (ws->r);
428 Shift P left by OFFSET places, and overwrite TARGET
429 with the shifted result.
430 Positions in TARGET less than OFFSET are unchanged.
433 perm_shift_apply (gsl_permutation *target, const gsl_permutation *p,
437 assert (target->size == p->size);
438 assert (offset <= target->size);
440 for (i = 0; i < target->size - offset; ++i)
442 target->data[i] = p->data [i + offset];
448 Indirectly sort the rows of matrix INPUT, storing the sort order in PERM.
449 The sort criteria are as follows:
451 Rows are sorted on the first column, until the absolute value of an
452 element in a subsequent column is greater than that of the first
453 column. Thereafter, rows will be sorted on the second column,
454 until the absolute value of an element in a subsequent column
455 exceeds that of the second column ...
458 sort_matrix_indirect (const gsl_matrix *input, gsl_permutation *perm)
460 const size_t n = perm->size;
461 const size_t m = input->size2;
468 assert (perm->size == input->size1);
470 p = gsl_permutation_alloc (n);
472 /* Copy INPUT into MAT, discarding the sign */
473 mat = gsl_matrix_alloc (n, m);
474 for (i = 0 ; i < mat->size1; ++i)
476 for (j = 0 ; j < mat->size2; ++j)
478 double x = gsl_matrix_get (input, i, j);
479 gsl_matrix_set (mat, i, j, fabs (x));
483 while (column_n < m && row_n < n)
485 gsl_vector_const_view columni = gsl_matrix_const_column (mat, column_n);
486 gsl_sort_vector_index (p, &columni.vector);
488 for (i = 0 ; i < n; ++i)
490 gsl_vector_view row = gsl_matrix_row (mat, p->data[n - 1 - i]);
491 size_t maxindex = gsl_vector_max_index (&row.vector);
493 if ( maxindex > column_n )
496 /* All subsequent elements of this row, are of no interest.
497 So set them all to a highly negative value */
498 for (j = column_n + 1; j < row.vector.size ; ++j)
499 gsl_vector_set (&row.vector, j, -DBL_MAX);
502 perm_shift_apply (perm, p, row_n);
508 gsl_permutation_free (p);
509 gsl_matrix_free (mat);
511 assert ( 0 == gsl_permutation_valid (perm));
513 /* We want the biggest value to be first */
514 gsl_permutation_reverse (perm);
519 drot_go (double phi, double *l0, double *l1)
521 double r0 = cos (phi) * *l0 + sin (phi) * *l1;
522 double r1 = - sin (phi) * *l0 + cos (phi) * *l1;
530 clone_matrix (const gsl_matrix *m)
533 gsl_matrix *c = gsl_matrix_calloc (m->size1, m->size2);
535 for (j = 0 ; j < c->size1; ++j)
537 for (k = 0 ; k < c->size2; ++k)
539 const double *v = gsl_matrix_const_ptr (m, j, k);
540 gsl_matrix_set (c, j, k, *v);
549 initial_sv (const gsl_matrix *fm)
554 for (j = 0 ; j < fm->size2; ++j)
559 for (k = j + 1 ; k < fm->size2; ++k)
561 double lambda = gsl_matrix_get (fm, k, j);
562 double lambda_sq = lambda * lambda;
563 double lambda_4 = lambda_sq * lambda_sq;
568 sv += ( fm->size1 * l4s - (l2s * l2s) ) / (fm->size1 * fm->size1 );
574 rotate (const struct cmd_factor *cf, const gsl_matrix *unrot,
575 const gsl_vector *communalities,
577 gsl_vector *rotated_loadings
584 /* First get a normalised version of UNROT */
585 gsl_matrix *normalised = gsl_matrix_calloc (unrot->size1, unrot->size2);
586 gsl_matrix *h_sqrt = gsl_matrix_calloc (communalities->size, communalities->size);
587 gsl_matrix *h_sqrt_inv ;
589 /* H is the diagonal matrix containing the absolute values of the communalities */
590 for (i = 0 ; i < communalities->size ; ++i)
592 double *ptr = gsl_matrix_ptr (h_sqrt, i, i);
593 *ptr = fabs (gsl_vector_get (communalities, i));
596 /* Take the square root of the communalities */
597 gsl_linalg_cholesky_decomp (h_sqrt);
600 /* Save a copy of h_sqrt and invert it */
601 h_sqrt_inv = clone_matrix (h_sqrt);
602 gsl_linalg_cholesky_decomp (h_sqrt_inv);
603 gsl_linalg_cholesky_invert (h_sqrt_inv);
605 /* normalised vertion is H^{1/2} x UNROT */
606 gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, h_sqrt_inv, unrot, 0.0, normalised);
608 gsl_matrix_free (h_sqrt_inv);
611 /* Now perform the rotation iterations */
613 prev_sv = initial_sv (normalised);
614 for (i = 0 ; i < cf->iterations ; ++i)
617 for (j = 0 ; j < normalised->size2; ++j)
619 /* These variables relate to the convergence criterium */
623 for (k = j + 1 ; k < normalised->size2; ++k)
633 for (p = 0; p < normalised->size1; ++p)
635 double jv = gsl_matrix_get (normalised, p, j);
636 double kv = gsl_matrix_get (normalised, p, k);
638 double u = jv * jv - kv * kv;
639 double v = 2 * jv * kv;
646 rotation_coeff [cf->rotation] (&x, &y, a, b, c, d, normalised);
648 phi = atan2 (x, y) / 4.0 ;
650 /* Don't bother rotating if the angle is small */
651 if ( fabs (sin (phi) ) <= pow (10.0, -15.0))
654 for (p = 0; p < normalised->size1; ++p)
656 double *lambda0 = gsl_matrix_ptr (normalised, p, j);
657 double *lambda1 = gsl_matrix_ptr (normalised, p, k);
658 drot_go (phi, lambda0, lambda1);
661 /* Calculate the convergence criterium */
663 double lambda = gsl_matrix_get (normalised, k, j);
664 double lambda_sq = lambda * lambda;
665 double lambda_4 = lambda_sq * lambda_sq;
671 sv += ( normalised->size1 * l4s - (l2s * l2s) ) / (normalised->size1 * normalised->size1 );
674 if ( fabs (sv - prev_sv) <= cf->rconverge)
680 gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0,
681 h_sqrt, normalised, 0.0, result);
683 gsl_matrix_free (h_sqrt);
686 /* reflect negative sums and populate the rotated loadings vector*/
687 for (i = 0 ; i < result->size2; ++i)
691 for (j = 0 ; j < result->size1; ++j)
693 double s = gsl_matrix_get (result, j, i);
695 sum += gsl_matrix_get (result, j, i);
698 gsl_vector_set (rotated_loadings, i, ssq);
701 for (j = 0 ; j < result->size1; ++j)
703 double *lambda = gsl_matrix_ptr (result, j, i);
711 Get an approximation for the factor matrix into FACTORS, and the communalities into COMMUNALITIES.
712 R is the matrix to be analysed.
713 WS is a pointer to a structure which must have been initialised with factor_matrix_workspace_init.
716 iterate_factor_matrix (const gsl_matrix *r, gsl_vector *communalities, gsl_matrix *factors,
717 struct factor_matrix_workspace *ws)
722 assert (r->size1 == r->size2);
723 assert (r->size1 == communalities->size);
725 assert (factors->size1 == r->size1);
726 assert (factors->size2 == ws->n_factors);
728 gsl_matrix_memcpy (ws->r, r);
730 /* Apply Communalities to diagonal of correlation matrix */
731 for (i = 0 ; i < communalities->size ; ++i)
733 double *x = gsl_matrix_ptr (ws->r, i, i);
734 *x = gsl_vector_get (communalities, i);
737 gsl_eigen_symmv (ws->r, ws->eval, ws->evec, ws->eigen_ws);
739 mv = gsl_matrix_submatrix (ws->evec, 0, 0, ws->evec->size1, ws->n_factors);
741 /* Gamma is the diagonal matrix containing the absolute values of the eigenvalues */
742 for (i = 0 ; i < ws->n_factors ; ++i)
744 double *ptr = gsl_matrix_ptr (ws->gamma, i, i);
745 *ptr = fabs (gsl_vector_get (ws->eval, i));
748 /* Take the square root of gamma */
749 gsl_linalg_cholesky_decomp (ws->gamma);
751 gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, &mv.matrix, ws->gamma, 0.0, factors);
753 for (i = 0 ; i < r->size1 ; ++i)
755 double h = the_communality (ws->evec, ws->eval, i, ws->n_factors);
756 gsl_vector_set (communalities, i, h);
762 static bool run_factor (struct dataset *ds, const struct cmd_factor *factor);
766 cmd_factor (struct lexer *lexer, struct dataset *ds)
768 bool extraction_seen = false;
769 const struct dictionary *dict = dataset_dict (ds);
771 struct cmd_factor factor;
774 factor.method = METHOD_CORR;
775 factor.missing_type = MISS_LISTWISE;
776 factor.exclude = MV_ANY;
777 factor.print = PRINT_INITIAL | PRINT_EXTRACTION | PRINT_ROTATION;
778 factor.extraction = EXTRACTION_PC;
779 factor.n_factors = 0;
780 factor.min_eigen = SYSMIS;
781 factor.iterations = 25;
782 factor.econverge = 0.001;
787 factor.rotation = ROT_VARIMAX;
789 factor.rconverge = 0.0001;
791 factor.wv = dict_get_weight (dict);
793 lex_match (lexer, T_SLASH);
795 if (!lex_force_match_id (lexer, "VARIABLES"))
800 lex_match (lexer, T_EQUALS);
802 if (!parse_variables_const (lexer, dict, &factor.vars, &factor.n_vars,
803 PV_NO_DUPLICATE | PV_NUMERIC))
806 if (factor.n_vars < 2)
807 msg (MW, _("Factor analysis on a single variable is not useful."));
809 while (lex_token (lexer) != T_ENDCMD)
811 lex_match (lexer, T_SLASH);
813 if (lex_match_id (lexer, "PLOT"))
815 lex_match (lexer, T_EQUALS);
816 while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
818 if (lex_match_id (lexer, "EIGEN"))
820 factor.plot |= PLOT_SCREE;
822 #if FACTOR_FULLY_IMPLEMENTED
823 else if (lex_match_id (lexer, "ROTATION"))
829 lex_error (lexer, NULL);
834 else if (lex_match_id (lexer, "METHOD"))
836 lex_match (lexer, T_EQUALS);
837 while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
839 if (lex_match_id (lexer, "COVARIANCE"))
841 factor.method = METHOD_COV;
843 else if (lex_match_id (lexer, "CORRELATION"))
845 factor.method = METHOD_CORR;
849 lex_error (lexer, NULL);
854 else if (lex_match_id (lexer, "ROTATION"))
856 lex_match (lexer, T_EQUALS);
857 while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
859 /* VARIMAX and DEFAULT are defaults */
860 if (lex_match_id (lexer, "VARIMAX") || lex_match_id (lexer, "DEFAULT"))
862 factor.rotation = ROT_VARIMAX;
864 else if (lex_match_id (lexer, "EQUAMAX"))
866 factor.rotation = ROT_EQUAMAX;
868 else if (lex_match_id (lexer, "QUARTIMAX"))
870 factor.rotation = ROT_QUARTIMAX;
872 else if (lex_match_id (lexer, "NOROTATE"))
874 factor.rotation = ROT_NONE;
878 lex_error (lexer, NULL);
883 else if (lex_match_id (lexer, "CRITERIA"))
885 lex_match (lexer, T_EQUALS);
886 while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
888 if (lex_match_id (lexer, "FACTORS"))
890 if ( lex_force_match (lexer, T_LPAREN))
892 lex_force_int (lexer);
893 factor.n_factors = lex_integer (lexer);
895 lex_force_match (lexer, T_RPAREN);
898 else if (lex_match_id (lexer, "MINEIGEN"))
900 if ( lex_force_match (lexer, T_LPAREN))
902 lex_force_num (lexer);
903 factor.min_eigen = lex_number (lexer);
905 lex_force_match (lexer, T_RPAREN);
908 else if (lex_match_id (lexer, "ECONVERGE"))
910 if ( lex_force_match (lexer, T_LPAREN))
912 lex_force_num (lexer);
913 factor.econverge = lex_number (lexer);
915 lex_force_match (lexer, T_RPAREN);
918 else if (lex_match_id (lexer, "RCONVERGE"))
920 if ( lex_force_match (lexer, T_LPAREN))
922 lex_force_num (lexer);
923 factor.rconverge = lex_number (lexer);
925 lex_force_match (lexer, T_RPAREN);
928 else if (lex_match_id (lexer, "ITERATE"))
930 if ( lex_force_match (lexer, T_LPAREN))
932 lex_force_int (lexer);
933 factor.iterations = lex_integer (lexer);
935 lex_force_match (lexer, T_RPAREN);
938 else if (lex_match_id (lexer, "DEFAULT"))
940 factor.n_factors = 0;
941 factor.min_eigen = 1;
942 factor.iterations = 25;
946 lex_error (lexer, NULL);
951 else if (lex_match_id (lexer, "EXTRACTION"))
953 extraction_seen = true;
954 lex_match (lexer, T_EQUALS);
955 while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
957 if (lex_match_id (lexer, "PAF"))
959 factor.extraction = EXTRACTION_PAF;
961 else if (lex_match_id (lexer, "PC"))
963 factor.extraction = EXTRACTION_PC;
965 else if (lex_match_id (lexer, "PA1"))
967 factor.extraction = EXTRACTION_PC;
969 else if (lex_match_id (lexer, "DEFAULT"))
971 factor.extraction = EXTRACTION_PC;
975 lex_error (lexer, NULL);
980 else if (lex_match_id (lexer, "FORMAT"))
982 lex_match (lexer, T_EQUALS);
983 while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
985 if (lex_match_id (lexer, "SORT"))
989 else if (lex_match_id (lexer, "BLANK"))
991 if ( lex_force_match (lexer, T_LPAREN))
993 lex_force_num (lexer);
994 factor.blank = lex_number (lexer);
996 lex_force_match (lexer, T_RPAREN);
999 else if (lex_match_id (lexer, "DEFAULT"))
1002 factor.sort = false;
1006 lex_error (lexer, NULL);
1011 else if (lex_match_id (lexer, "PRINT"))
1014 lex_match (lexer, T_EQUALS);
1015 while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
1017 if (lex_match_id (lexer, "UNIVARIATE"))
1019 factor.print |= PRINT_UNIVARIATE;
1021 else if (lex_match_id (lexer, "DET"))
1023 factor.print |= PRINT_DETERMINANT;
1025 #if FACTOR_FULLY_IMPLEMENTED
1026 else if (lex_match_id (lexer, "INV"))
1029 else if (lex_match_id (lexer, "AIC"))
1033 else if (lex_match_id (lexer, "SIG"))
1035 factor.print |= PRINT_SIG;
1037 else if (lex_match_id (lexer, "CORRELATION"))
1039 factor.print |= PRINT_CORRELATION;
1041 #if FACTOR_FULLY_IMPLEMENTED
1042 else if (lex_match_id (lexer, "COVARIANCE"))
1046 else if (lex_match_id (lexer, "ROTATION"))
1048 factor.print |= PRINT_ROTATION;
1050 else if (lex_match_id (lexer, "EXTRACTION"))
1052 factor.print |= PRINT_EXTRACTION;
1054 else if (lex_match_id (lexer, "INITIAL"))
1056 factor.print |= PRINT_INITIAL;
1058 #if FACTOR_FULLY_IMPLEMENTED
1059 else if (lex_match_id (lexer, "KMO"))
1062 else if (lex_match_id (lexer, "REPR"))
1065 else if (lex_match_id (lexer, "FSCORE"))
1069 else if (lex_match (lexer, T_ALL))
1071 factor.print = 0xFFFF;
1073 else if (lex_match_id (lexer, "DEFAULT"))
1075 factor.print |= PRINT_INITIAL ;
1076 factor.print |= PRINT_EXTRACTION ;
1077 factor.print |= PRINT_ROTATION ;
1081 lex_error (lexer, NULL);
1086 else if (lex_match_id (lexer, "MISSING"))
1088 lex_match (lexer, T_EQUALS);
1089 while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
1091 if (lex_match_id (lexer, "INCLUDE"))
1093 factor.exclude = MV_SYSTEM;
1095 else if (lex_match_id (lexer, "EXCLUDE"))
1097 factor.exclude = MV_ANY;
1099 else if (lex_match_id (lexer, "LISTWISE"))
1101 factor.missing_type = MISS_LISTWISE;
1103 else if (lex_match_id (lexer, "PAIRWISE"))
1105 factor.missing_type = MISS_PAIRWISE;
1107 else if (lex_match_id (lexer, "MEANSUB"))
1109 factor.missing_type = MISS_MEANSUB;
1113 lex_error (lexer, NULL);
1120 lex_error (lexer, NULL);
1125 if ( factor.rotation == ROT_NONE )
1126 factor.print &= ~PRINT_ROTATION;
1128 if ( ! run_factor (ds, &factor))
1139 static void do_factor (const struct cmd_factor *factor, struct casereader *group);
1143 run_factor (struct dataset *ds, const struct cmd_factor *factor)
1145 struct dictionary *dict = dataset_dict (ds);
1147 struct casereader *group;
1149 struct casegrouper *grouper = casegrouper_create_splits (proc_open (ds), dict);
1151 while (casegrouper_get_next_group (grouper, &group))
1153 if ( factor->missing_type == MISS_LISTWISE )
1154 group = casereader_create_filter_missing (group, factor->vars, factor->n_vars,
1157 do_factor (factor, group);
1160 ok = casegrouper_destroy (grouper);
1161 ok = proc_commit (ds) && ok;
1167 /* Return the communality of variable N, calculated to N_FACTORS */
1169 the_communality (const gsl_matrix *evec, const gsl_vector *eval, int n, int n_factors)
1176 assert (n < eval->size);
1177 assert (n < evec->size1);
1178 assert (n_factors <= eval->size);
1180 for (i = 0 ; i < n_factors; ++i)
1182 double evali = fabs (gsl_vector_get (eval, i));
1184 double eveci = gsl_matrix_get (evec, n, i);
1186 comm += pow2 (eveci) * evali;
1192 /* Return the communality of variable N, calculated to N_FACTORS */
1194 communality (struct idata *idata, int n, int n_factors)
1196 return the_communality (idata->evec, idata->eval, n, n_factors);
1201 show_scree (const struct cmd_factor *f, struct idata *idata)
1206 if ( !(f->plot & PLOT_SCREE) )
1210 label = f->extraction == EXTRACTION_PC ? _("Component Number") : _("Factor Number");
1212 s = scree_create (idata->eval, label);
1218 show_communalities (const struct cmd_factor * factor,
1219 const gsl_vector *initial, const gsl_vector *extracted)
1223 const int heading_columns = 1;
1224 int nc = heading_columns;
1225 const int heading_rows = 1;
1226 const int nr = heading_rows + factor->n_vars;
1227 struct tab_table *t;
1229 if (factor->print & PRINT_EXTRACTION)
1232 if (factor->print & PRINT_INITIAL)
1235 /* No point having a table with only headings */
1239 t = tab_create (nc, nr);
1241 tab_title (t, _("Communalities"));
1243 tab_headers (t, heading_columns, 0, heading_rows, 0);
1246 if (factor->print & PRINT_INITIAL)
1247 tab_text (t, c++, 0, TAB_CENTER | TAT_TITLE, _("Initial"));
1249 if (factor->print & PRINT_EXTRACTION)
1250 tab_text (t, c++, 0, TAB_CENTER | TAT_TITLE, _("Extraction"));
1252 /* Outline the box */
1259 /* Vertical lines */
1266 tab_hline (t, TAL_1, 0, nc - 1, heading_rows);
1267 tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
1269 for (i = 0 ; i < factor->n_vars; ++i)
1272 tab_text (t, c++, i + heading_rows, TAT_TITLE, var_to_string (factor->vars[i]));
1274 if (factor->print & PRINT_INITIAL)
1275 tab_double (t, c++, i + heading_rows, 0, gsl_vector_get (initial, i), NULL);
1277 if (factor->print & PRINT_EXTRACTION)
1278 tab_double (t, c++, i + heading_rows, 0, gsl_vector_get (extracted, i), NULL);
1286 show_factor_matrix (const struct cmd_factor *factor, struct idata *idata, const char *title, const gsl_matrix *fm)
1289 const int n_factors = idata->n_extractions;
1291 const int heading_columns = 1;
1292 const int heading_rows = 2;
1293 const int nr = heading_rows + factor->n_vars;
1294 const int nc = heading_columns + n_factors;
1295 gsl_permutation *perm;
1297 struct tab_table *t = tab_create (nc, nr);
1300 if ( factor->extraction == EXTRACTION_PC )
1301 tab_title (t, _("Component Matrix"));
1303 tab_title (t, _("Factor Matrix"));
1306 tab_title (t, title);
1308 tab_headers (t, heading_columns, 0, heading_rows, 0);
1310 if ( factor->extraction == EXTRACTION_PC )
1314 TAB_CENTER | TAT_TITLE, _("Component"));
1319 TAB_CENTER | TAT_TITLE, _("Factor"));
1322 tab_hline (t, TAL_1, heading_columns, nc - 1, 1);
1325 /* Outline the box */
1332 /* Vertical lines */
1339 tab_hline (t, TAL_1, 0, nc - 1, heading_rows);
1340 tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
1343 /* Initialise to the identity permutation */
1344 perm = gsl_permutation_calloc (factor->n_vars);
1347 sort_matrix_indirect (fm, perm);
1349 for (i = 0 ; i < n_factors; ++i)
1351 tab_text_format (t, heading_columns + i, 1, TAB_CENTER | TAT_TITLE, _("%d"), i + 1);
1354 for (i = 0 ; i < factor->n_vars; ++i)
1357 const int matrix_row = perm->data[i];
1358 tab_text (t, 0, i + heading_rows, TAT_TITLE, var_to_string (factor->vars[matrix_row]));
1360 for (j = 0 ; j < n_factors; ++j)
1362 double x = gsl_matrix_get (fm, matrix_row, j);
1364 if ( fabs (x) < factor->blank)
1367 tab_double (t, heading_columns + j, heading_rows + i, 0, x, NULL);
1371 gsl_permutation_free (perm);
1378 show_explained_variance (const struct cmd_factor * factor, struct idata *idata,
1379 const gsl_vector *initial_eigenvalues,
1380 const gsl_vector *extracted_eigenvalues,
1381 const gsl_vector *rotated_loadings)
1385 const int heading_columns = 1;
1386 const int heading_rows = 2;
1387 const int nr = heading_rows + factor->n_vars;
1389 struct tab_table *t ;
1391 double i_total = 0.0;
1394 double e_total = 0.0;
1399 int nc = heading_columns;
1401 if (factor->print & PRINT_EXTRACTION)
1404 if (factor->print & PRINT_INITIAL)
1407 if (factor->print & PRINT_ROTATION)
1410 /* No point having a table with only headings */
1411 if ( nc <= heading_columns)
1414 t = tab_create (nc, nr);
1416 tab_title (t, _("Total Variance Explained"));
1418 tab_headers (t, heading_columns, 0, heading_rows, 0);
1420 /* Outline the box */
1427 /* Vertical lines */
1434 tab_hline (t, TAL_1, 0, nc - 1, heading_rows);
1435 tab_hline (t, TAL_1, 1, nc - 1, 1);
1437 tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
1440 if ( factor->extraction == EXTRACTION_PC)
1441 tab_text (t, 0, 1, TAB_LEFT | TAT_TITLE, _("Component"));
1443 tab_text (t, 0, 1, TAB_LEFT | TAT_TITLE, _("Factor"));
1446 if (factor->print & PRINT_INITIAL)
1448 tab_joint_text (t, c, 0, c + 2, 0, TAB_CENTER | TAT_TITLE, _("Initial Eigenvalues"));
1452 if (factor->print & PRINT_EXTRACTION)
1454 tab_joint_text (t, c, 0, c + 2, 0, TAB_CENTER | TAT_TITLE, _("Extraction Sums of Squared Loadings"));
1458 if (factor->print & PRINT_ROTATION)
1460 tab_joint_text (t, c, 0, c + 2, 0, TAB_CENTER | TAT_TITLE, _("Rotation Sums of Squared Loadings"));
1464 for (i = 0; i < (nc - heading_columns) / 3 ; ++i)
1466 tab_text (t, i * 3 + 1, 1, TAB_CENTER | TAT_TITLE, _("Total"));
1467 /* xgettext:no-c-format */
1468 tab_text (t, i * 3 + 2, 1, TAB_CENTER | TAT_TITLE, _("% of Variance"));
1469 tab_text (t, i * 3 + 3, 1, TAB_CENTER | TAT_TITLE, _("Cumulative %"));
1471 tab_vline (t, TAL_2, heading_columns + i * 3, 0, nr - 1);
1474 for (i = 0 ; i < initial_eigenvalues->size; ++i)
1475 i_total += gsl_vector_get (initial_eigenvalues, i);
1477 if ( factor->extraction == EXTRACTION_PAF)
1479 e_total = factor->n_vars;
1486 for (i = 0 ; i < factor->n_vars; ++i)
1488 const double i_lambda = gsl_vector_get (initial_eigenvalues, i);
1489 double i_percent = 100.0 * i_lambda / i_total ;
1491 const double e_lambda = gsl_vector_get (extracted_eigenvalues, i);
1492 double e_percent = 100.0 * e_lambda / e_total ;
1494 const double r_lambda = gsl_vector_get (rotated_loadings, i);
1495 double r_percent = 100.0 * r_lambda / e_total ;
1499 tab_text_format (t, c++, i + heading_rows, TAB_LEFT | TAT_TITLE, _("%d"), i + 1);
1505 /* Initial Eigenvalues */
1506 if (factor->print & PRINT_INITIAL)
1508 tab_double (t, c++, i + heading_rows, 0, i_lambda, NULL);
1509 tab_double (t, c++, i + heading_rows, 0, i_percent, NULL);
1510 tab_double (t, c++, i + heading_rows, 0, i_cum, NULL);
1514 if (factor->print & PRINT_EXTRACTION)
1516 if (i < idata->n_extractions)
1518 /* Sums of squared loadings */
1519 tab_double (t, c++, i + heading_rows, 0, e_lambda, NULL);
1520 tab_double (t, c++, i + heading_rows, 0, e_percent, NULL);
1521 tab_double (t, c++, i + heading_rows, 0, e_cum, NULL);
1525 if (factor->print & PRINT_ROTATION)
1527 if (i < idata->n_extractions)
1529 tab_double (t, c++, i + heading_rows, 0, r_lambda, NULL);
1530 tab_double (t, c++, i + heading_rows, 0, r_percent, NULL);
1531 tab_double (t, c++, i + heading_rows, 0, r_cum, NULL);
1542 show_correlation_matrix (const struct cmd_factor *factor, const struct idata *idata)
1544 struct tab_table *t ;
1546 int y_pos_corr = -1;
1548 int suffix_rows = 0;
1550 const int heading_rows = 1;
1551 const int heading_columns = 2;
1553 int nc = heading_columns ;
1554 int nr = heading_rows ;
1555 int n_data_sets = 0;
1557 if (factor->print & PRINT_CORRELATION)
1559 y_pos_corr = n_data_sets;
1561 nc = heading_columns + factor->n_vars;
1564 if (factor->print & PRINT_SIG)
1566 y_pos_sig = n_data_sets;
1568 nc = heading_columns + factor->n_vars;
1571 nr += n_data_sets * factor->n_vars;
1573 if (factor->print & PRINT_DETERMINANT)
1576 /* If the table would contain only headings, don't bother rendering it */
1577 if (nr <= heading_rows && suffix_rows == 0)
1580 t = tab_create (nc, nr + suffix_rows);
1582 tab_title (t, _("Correlation Matrix"));
1584 tab_hline (t, TAL_1, 0, nc - 1, heading_rows);
1586 if (nr > heading_rows)
1588 tab_headers (t, heading_columns, 0, heading_rows, 0);
1590 tab_vline (t, TAL_2, 2, 0, nr - 1);
1592 /* Outline the box */
1599 /* Vertical lines */
1607 for (i = 0; i < factor->n_vars; ++i)
1608 tab_text (t, heading_columns + i, 0, TAT_TITLE, var_to_string (factor->vars[i]));
1611 for (i = 0 ; i < n_data_sets; ++i)
1613 int y = heading_rows + i * factor->n_vars;
1615 for (v = 0; v < factor->n_vars; ++v)
1616 tab_text (t, 1, y + v, TAT_TITLE, var_to_string (factor->vars[v]));
1618 tab_hline (t, TAL_1, 0, nc - 1, y);
1621 if (factor->print & PRINT_CORRELATION)
1623 const double y = heading_rows + y_pos_corr;
1624 tab_text (t, 0, y, TAT_TITLE, _("Correlations"));
1626 for (i = 0; i < factor->n_vars; ++i)
1628 for (j = 0; j < factor->n_vars; ++j)
1629 tab_double (t, heading_columns + i, y + j, 0, gsl_matrix_get (idata->corr, i, j), NULL);
1633 if (factor->print & PRINT_SIG)
1635 const double y = heading_rows + y_pos_sig * factor->n_vars;
1636 tab_text (t, 0, y, TAT_TITLE, _("Sig. (1-tailed)"));
1638 for (i = 0; i < factor->n_vars; ++i)
1640 for (j = 0; j < factor->n_vars; ++j)
1642 double rho = gsl_matrix_get (idata->corr, i, j);
1643 double w = gsl_matrix_get (idata->n, i, j);
1648 tab_double (t, heading_columns + i, y + j, 0, significance_of_correlation (rho, w), NULL);
1654 if (factor->print & PRINT_DETERMINANT)
1659 const int size = idata->corr->size1;
1660 gsl_permutation *p = gsl_permutation_calloc (size);
1661 gsl_matrix *tmp = gsl_matrix_calloc (size, size);
1662 gsl_matrix_memcpy (tmp, idata->corr);
1664 gsl_linalg_LU_decomp (tmp, p, &sign);
1665 det = gsl_linalg_LU_det (tmp, sign);
1666 gsl_permutation_free (p);
1667 gsl_matrix_free (tmp);
1670 tab_text (t, 0, nr, TAB_LEFT | TAT_TITLE, _("Determinant"));
1671 tab_double (t, 1, nr, 0, det, NULL);
1680 do_factor (const struct cmd_factor *factor, struct casereader *r)
1683 const gsl_matrix *var_matrix;
1684 const gsl_matrix *mean_matrix;
1686 const gsl_matrix *analysis_matrix;
1687 struct idata *idata = idata_alloc (factor->n_vars);
1689 struct covariance *cov = covariance_1pass_create (factor->n_vars, factor->vars,
1690 factor->wv, factor->exclude);
1692 for ( ; (c = casereader_read (r) ); case_unref (c))
1694 covariance_accumulate (cov, c);
1697 idata->cov = covariance_calculate (cov);
1699 if (idata->cov == NULL)
1701 msg (MW, _("The dataset contains no complete observations. No analysis will be performed."));
1705 var_matrix = covariance_moments (cov, MOMENT_VARIANCE);
1706 mean_matrix = covariance_moments (cov, MOMENT_MEAN);
1707 idata->n = covariance_moments (cov, MOMENT_NONE);
1709 if ( factor->method == METHOD_CORR)
1711 idata->corr = correlation_from_covariance (idata->cov, var_matrix);
1712 analysis_matrix = idata->corr;
1715 analysis_matrix = idata->cov;
1717 if ( factor->print & PRINT_UNIVARIATE)
1721 const struct fmt_spec *wfmt = factor->wv ? var_get_print_format (factor->wv) : & F_8_0;
1724 const int heading_columns = 1;
1725 const int heading_rows = 1;
1727 const int nr = heading_rows + factor->n_vars;
1729 struct tab_table *t = tab_create (nc, nr);
1730 tab_title (t, _("Descriptive Statistics"));
1732 tab_headers (t, heading_columns, 0, heading_rows, 0);
1734 /* Outline the box */
1741 /* Vertical lines */
1748 tab_hline (t, TAL_1, 0, nc - 1, heading_rows);
1749 tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
1751 tab_text (t, 1, 0, TAB_CENTER | TAT_TITLE, _("Mean"));
1752 tab_text (t, 2, 0, TAB_CENTER | TAT_TITLE, _("Std. Deviation"));
1753 tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("Analysis N"));
1755 for (i = 0 ; i < factor->n_vars; ++i)
1757 const struct variable *v = factor->vars[i];
1758 tab_text (t, 0, i + heading_rows, TAB_LEFT | TAT_TITLE, var_to_string (v));
1760 tab_double (t, 1, i + heading_rows, 0, gsl_matrix_get (mean_matrix, i, i), NULL);
1761 tab_double (t, 2, i + heading_rows, 0, sqrt (gsl_matrix_get (var_matrix, i, i)), NULL);
1762 tab_double (t, 3, i + heading_rows, 0, gsl_matrix_get (idata->n, i, i), wfmt);
1768 show_correlation_matrix (factor, idata);
1772 gsl_eigen_symmv_workspace *workspace = gsl_eigen_symmv_alloc (factor->n_vars);
1774 gsl_eigen_symmv (matrix_dup (analysis_matrix), idata->eval, idata->evec, workspace);
1776 gsl_eigen_symmv_free (workspace);
1779 gsl_eigen_symmv_sort (idata->eval, idata->evec, GSL_EIGEN_SORT_ABS_DESC);
1782 idata->n_extractions = n_extracted_factors (factor, idata);
1784 if (idata->n_extractions == 0)
1786 msg (MW, _("The FACTOR criteria result in zero factors extracted. Therefore no analysis will be performed."));
1790 if (idata->n_extractions > factor->n_vars)
1792 msg (MW, _("The FACTOR criteria result in more factors than variables, which is not meaningful. No analysis will be performed."));
1797 gsl_matrix *rotated_factors = NULL;
1798 gsl_vector *rotated_loadings = NULL;
1800 const gsl_vector *extracted_eigenvalues = NULL;
1801 gsl_vector *initial_communalities = gsl_vector_alloc (factor->n_vars);
1802 gsl_vector *extracted_communalities = gsl_vector_alloc (factor->n_vars);
1804 struct factor_matrix_workspace *fmw = factor_matrix_workspace_alloc (idata->msr->size, idata->n_extractions);
1805 gsl_matrix *factor_matrix = gsl_matrix_calloc (factor->n_vars, fmw->n_factors);
1807 if ( factor->extraction == EXTRACTION_PAF)
1809 gsl_vector *diff = gsl_vector_alloc (idata->msr->size);
1810 struct smr_workspace *ws = ws_create (analysis_matrix);
1812 for (i = 0 ; i < factor->n_vars ; ++i)
1814 double r2 = squared_multiple_correlation (analysis_matrix, i, ws);
1816 gsl_vector_set (idata->msr, i, r2);
1820 gsl_vector_memcpy (initial_communalities, idata->msr);
1822 for (i = 0; i < factor->iterations; ++i)
1825 gsl_vector_memcpy (diff, idata->msr);
1827 iterate_factor_matrix (analysis_matrix, idata->msr, factor_matrix, fmw);
1829 gsl_vector_sub (diff, idata->msr);
1831 gsl_vector_minmax (diff, &min, &max);
1833 if ( fabs (min) < factor->econverge && fabs (max) < factor->econverge)
1836 gsl_vector_free (diff);
1840 gsl_vector_memcpy (extracted_communalities, idata->msr);
1841 extracted_eigenvalues = fmw->eval;
1843 else if (factor->extraction == EXTRACTION_PC)
1845 for (i = 0; i < factor->n_vars; ++i)
1846 gsl_vector_set (initial_communalities, i, communality (idata, i, factor->n_vars));
1848 gsl_vector_memcpy (extracted_communalities, initial_communalities);
1850 iterate_factor_matrix (analysis_matrix, extracted_communalities, factor_matrix, fmw);
1853 extracted_eigenvalues = idata->eval;
1857 show_communalities (factor, initial_communalities, extracted_communalities);
1860 if ( factor->rotation != ROT_NONE)
1862 rotated_factors = gsl_matrix_calloc (factor_matrix->size1, factor_matrix->size2);
1863 rotated_loadings = gsl_vector_calloc (factor_matrix->size2);
1865 rotate (factor, factor_matrix, extracted_communalities, rotated_factors, rotated_loadings);
1868 show_explained_variance (factor, idata, idata->eval, extracted_eigenvalues, rotated_loadings);
1870 factor_matrix_workspace_free (fmw);
1872 show_scree (factor, idata);
1874 show_factor_matrix (factor, idata,
1875 factor->extraction == EXTRACTION_PC ? _("Component Matrix") : _("Factor Matrix"),
1878 if ( factor->rotation != ROT_NONE)
1880 show_factor_matrix (factor, idata,
1881 factor->extraction == EXTRACTION_PC ? _("Rotated Component Matrix") : _("Rotated Factor Matrix"),
1884 gsl_matrix_free (rotated_factors);
1889 gsl_vector_free (initial_communalities);
1890 gsl_vector_free (extracted_communalities);
1897 casereader_destroy (r);