1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 2009, 2010, 2011 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/>. */
19 #include <gsl/gsl_vector.h>
20 #include <gsl/gsl_linalg.h>
21 #include <gsl/gsl_matrix.h>
22 #include <gsl/gsl_eigen.h>
23 #include <gsl/gsl_blas.h>
24 #include <gsl/gsl_sort_vector.h>
26 #include "data/casegrouper.h"
27 #include "data/casereader.h"
28 #include "data/casewriter.h"
29 #include "data/dataset.h"
30 #include "data/dictionary.h"
31 #include "data/format.h"
32 #include "data/subcase.h"
33 #include "language/command.h"
34 #include "language/lexer/lexer.h"
35 #include "language/lexer/value-parser.h"
36 #include "language/lexer/variable-parser.h"
37 #include "libpspp/message.h"
38 #include "libpspp/misc.h"
39 #include "math/correlation.h"
40 #include "math/covariance.h"
41 #include "math/moments.h"
42 #include "output/chart-item.h"
43 #include "output/charts/scree.h"
44 #include "output/tab.h"
47 #define _(msgid) gettext (msgid)
48 #define N_(msgid) msgid
63 enum extraction_method
72 PLOT_ROTATION = 0x0002
77 PRINT_UNIVARIATE = 0x0001,
78 PRINT_DETERMINANT = 0x0002,
82 PRINT_COVARIANCE = 0x0020,
83 PRINT_CORRELATION = 0x0040,
84 PRINT_ROTATION = 0x0080,
85 PRINT_EXTRACTION = 0x0100,
86 PRINT_INITIAL = 0x0200,
100 typedef void (*rotation_coefficients) (double *x, double *y,
101 double a, double b, double c, double d,
102 const gsl_matrix *loadings );
106 varimax_coefficients (double *x, double *y,
107 double a, double b, double c, double d,
108 const gsl_matrix *loadings )
110 *x = d - 2 * a * b / loadings->size1;
111 *y = c - (a * a - b * b) / loadings->size1;
115 equamax_coefficients (double *x, double *y,
116 double a, double b, double c, double d,
117 const gsl_matrix *loadings )
119 *x = d - loadings->size2 * a * b / loadings->size1;
120 *y = c - loadings->size2 * (a * a - b * b) / (2 * loadings->size1);
124 quartimax_coefficients (double *x, double *y,
125 double a UNUSED, double b UNUSED, double c, double d,
126 const gsl_matrix *loadings UNUSED)
132 static const rotation_coefficients rotation_coeff[3] = {
133 varimax_coefficients,
134 equamax_coefficients,
135 quartimax_coefficients
142 const struct variable **vars;
144 const struct variable *wv;
147 enum missing_type missing_type;
148 enum mv_class exclude;
149 enum print_opts print;
150 enum extraction_method extraction;
152 enum rotation_type rotation;
154 /* Extraction Criteria */
169 /* Intermediate values used in calculation */
171 const gsl_matrix *corr ; /* The correlation matrix */
172 gsl_matrix *cov ; /* The covariance matrix */
173 const gsl_matrix *n ; /* Matrix of number of samples */
175 gsl_vector *eval ; /* The eigenvalues */
176 gsl_matrix *evec ; /* The eigenvectors */
180 gsl_vector *msr ; /* Multiple Squared Regressions */
183 static struct idata *
184 idata_alloc (size_t n_vars)
186 struct idata *id = xzalloc (sizeof (*id));
188 id->n_extractions = 0;
189 id->msr = gsl_vector_alloc (n_vars);
191 id->eval = gsl_vector_alloc (n_vars);
192 id->evec = gsl_matrix_alloc (n_vars, n_vars);
198 idata_free (struct idata *id)
200 gsl_vector_free (id->msr);
201 gsl_vector_free (id->eval);
202 gsl_matrix_free (id->evec);
204 gsl_matrix_free (id->cov);
212 dump_matrix (const gsl_matrix *m)
216 for (i = 0 ; i < m->size1; ++i)
218 for (j = 0 ; j < m->size2; ++j)
219 printf ("%02f ", gsl_matrix_get (m, i, j));
226 dump_matrix_permute (const gsl_matrix *m, const gsl_permutation *p)
230 for (i = 0 ; i < m->size1; ++i)
232 for (j = 0 ; j < m->size2; ++j)
233 printf ("%02f ", gsl_matrix_get (m, gsl_permutation_get (p, i), j));
240 dump_vector (const gsl_vector *v)
243 for (i = 0 ; i < v->size; ++i)
245 printf ("%02f\n", gsl_vector_get (v, i));
253 n_extracted_factors (const struct cmd_factor *factor, struct idata *idata)
257 /* If there is a cached value, then return that. */
258 if ( idata->n_extractions != 0)
259 return idata->n_extractions;
261 /* Otherwise, if the number of factors has been explicitly requested,
263 if (factor->n_factors > 0)
265 idata->n_extractions = factor->n_factors;
269 /* Use the MIN_EIGEN setting. */
270 for (i = 0 ; i < idata->eval->size; ++i)
272 double evali = fabs (gsl_vector_get (idata->eval, i));
274 idata->n_extractions = i;
276 if (evali < factor->min_eigen)
281 return idata->n_extractions;
285 /* Returns a newly allocated matrix identical to M.
286 It it the callers responsibility to free the returned value.
289 matrix_dup (const gsl_matrix *m)
291 gsl_matrix *n = gsl_matrix_alloc (m->size1, m->size2);
293 gsl_matrix_memcpy (n, m);
301 /* Copy of the subject */
306 gsl_permutation *perm;
313 static struct smr_workspace *ws_create (const gsl_matrix *input)
315 struct smr_workspace *ws = xmalloc (sizeof (*ws));
317 ws->m = gsl_matrix_alloc (input->size1, input->size2);
318 ws->inverse = gsl_matrix_calloc (input->size1 - 1, input->size2 - 1);
319 ws->perm = gsl_permutation_alloc (input->size1 - 1);
320 ws->result1 = gsl_matrix_calloc (input->size1 - 1, 1);
321 ws->result2 = gsl_matrix_calloc (1, 1);
327 ws_destroy (struct smr_workspace *ws)
329 gsl_matrix_free (ws->result2);
330 gsl_matrix_free (ws->result1);
331 gsl_permutation_free (ws->perm);
332 gsl_matrix_free (ws->inverse);
333 gsl_matrix_free (ws->m);
340 Return the square of the regression coefficient for VAR regressed against all other variables.
343 squared_multiple_correlation (const gsl_matrix *corr, int var, struct smr_workspace *ws)
345 /* For an explanation of what this is doing, see
346 http://www.visualstatistics.net/Visual%20Statistics%20Multimedia/multiple_regression_analysis.htm
352 gsl_matrix_memcpy (ws->m, corr);
354 gsl_matrix_swap_rows (ws->m, 0, var);
355 gsl_matrix_swap_columns (ws->m, 0, var);
357 rxx = gsl_matrix_submatrix (ws->m, 1, 1, ws->m->size1 - 1, ws->m->size1 - 1);
359 gsl_linalg_LU_decomp (&rxx.matrix, ws->perm, &signum);
361 gsl_linalg_LU_invert (&rxx.matrix, ws->perm, ws->inverse);
364 gsl_matrix_const_view rxy = gsl_matrix_const_submatrix (ws->m, 1, 0, ws->m->size1 - 1, 1);
365 gsl_matrix_const_view ryx = gsl_matrix_const_submatrix (ws->m, 0, 1, 1, ws->m->size1 - 1);
367 gsl_blas_dgemm (CblasNoTrans, CblasNoTrans,
368 1.0, ws->inverse, &rxy.matrix, 0.0, ws->result1);
370 gsl_blas_dgemm (CblasNoTrans, CblasNoTrans,
371 1.0, &ryx.matrix, ws->result1, 0.0, ws->result2);
374 return gsl_matrix_get (ws->result2, 0, 0);
379 static double the_communality (const gsl_matrix *evec, const gsl_vector *eval, int n, int n_factors);
382 struct factor_matrix_workspace
385 gsl_eigen_symmv_workspace *eigen_ws;
395 static struct factor_matrix_workspace *
396 factor_matrix_workspace_alloc (size_t n, size_t nf)
398 struct factor_matrix_workspace *ws = xmalloc (sizeof (*ws));
401 ws->gamma = gsl_matrix_calloc (nf, nf);
402 ws->eigen_ws = gsl_eigen_symmv_alloc (n);
403 ws->eval = gsl_vector_alloc (n);
404 ws->evec = gsl_matrix_alloc (n, n);
405 ws->r = gsl_matrix_alloc (n, n);
411 factor_matrix_workspace_free (struct factor_matrix_workspace *ws)
413 gsl_eigen_symmv_free (ws->eigen_ws);
414 gsl_vector_free (ws->eval);
415 gsl_matrix_free (ws->evec);
416 gsl_matrix_free (ws->gamma);
417 gsl_matrix_free (ws->r);
422 Shift P left by OFFSET places, and overwrite TARGET
423 with the shifted result.
424 Positions in TARGET less than OFFSET are unchanged.
427 perm_shift_apply (gsl_permutation *target, const gsl_permutation *p,
431 assert (target->size == p->size);
432 assert (offset <= target->size);
434 for (i = 0; i < target->size - offset; ++i)
436 target->data[i] = p->data [i + offset];
442 Indirectly sort the rows of matrix INPUT, storing the sort order in PERM.
443 The sort criteria are as follows:
445 Rows are sorted on the first column, until the absolute value of an
446 element in a subsequent column is greater than that of the first
447 column. Thereafter, rows will be sorted on the second column,
448 until the absolute value of an element in a subsequent column
449 exceeds that of the second column ...
452 sort_matrix_indirect (const gsl_matrix *input, gsl_permutation *perm)
454 const size_t n = perm->size;
455 const size_t m = input->size2;
462 assert (perm->size == input->size1);
464 p = gsl_permutation_alloc (n);
466 /* Copy INPUT into MAT, discarding the sign */
467 mat = gsl_matrix_alloc (n, m);
468 for (i = 0 ; i < mat->size1; ++i)
470 for (j = 0 ; j < mat->size2; ++j)
472 double x = gsl_matrix_get (input, i, j);
473 gsl_matrix_set (mat, i, j, fabs (x));
477 while (column_n < m && row_n < n)
479 gsl_vector_const_view columni = gsl_matrix_const_column (mat, column_n);
480 gsl_sort_vector_index (p, &columni.vector);
482 for (i = 0 ; i < n; ++i)
484 gsl_vector_view row = gsl_matrix_row (mat, p->data[n - 1 - i]);
485 size_t maxindex = gsl_vector_max_index (&row.vector);
487 if ( maxindex > column_n )
490 /* All subsequent elements of this row, are of no interest.
491 So set them all to a highly negative value */
492 for (j = column_n + 1; j < row.vector.size ; ++j)
493 gsl_vector_set (&row.vector, j, -DBL_MAX);
496 perm_shift_apply (perm, p, row_n);
502 gsl_permutation_free (p);
503 gsl_matrix_free (mat);
505 assert ( 0 == gsl_permutation_valid (perm));
507 /* We want the biggest value to be first */
508 gsl_permutation_reverse (perm);
513 drot_go (double phi, double *l0, double *l1)
515 double r0 = cos (phi) * *l0 + sin (phi) * *l1;
516 double r1 = - sin (phi) * *l0 + cos (phi) * *l1;
524 clone_matrix (const gsl_matrix *m)
527 gsl_matrix *c = gsl_matrix_calloc (m->size1, m->size2);
529 for (j = 0 ; j < c->size1; ++j)
531 for (k = 0 ; k < c->size2; ++k)
533 const double *v = gsl_matrix_const_ptr (m, j, k);
534 gsl_matrix_set (c, j, k, *v);
543 initial_sv (const gsl_matrix *fm)
548 for (j = 0 ; j < fm->size2; ++j)
553 for (k = j + 1 ; k < fm->size2; ++k)
555 double lambda = gsl_matrix_get (fm, k, j);
556 double lambda_sq = lambda * lambda;
557 double lambda_4 = lambda_sq * lambda_sq;
562 sv += ( fm->size1 * l4s - (l2s * l2s) ) / (fm->size1 * fm->size1 );
568 rotate (const struct cmd_factor *cf, const gsl_matrix *unrot,
569 const gsl_vector *communalities,
571 gsl_vector *rotated_loadings
578 /* First get a normalised version of UNROT */
579 gsl_matrix *normalised = gsl_matrix_calloc (unrot->size1, unrot->size2);
580 gsl_matrix *h_sqrt = gsl_matrix_calloc (communalities->size, communalities->size);
581 gsl_matrix *h_sqrt_inv ;
583 /* H is the diagonal matrix containing the absolute values of the communalities */
584 for (i = 0 ; i < communalities->size ; ++i)
586 double *ptr = gsl_matrix_ptr (h_sqrt, i, i);
587 *ptr = fabs (gsl_vector_get (communalities, i));
590 /* Take the square root of the communalities */
591 gsl_linalg_cholesky_decomp (h_sqrt);
594 /* Save a copy of h_sqrt and invert it */
595 h_sqrt_inv = clone_matrix (h_sqrt);
596 gsl_linalg_cholesky_decomp (h_sqrt_inv);
597 gsl_linalg_cholesky_invert (h_sqrt_inv);
599 /* normalised vertion is H^{1/2} x UNROT */
600 gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, h_sqrt_inv, unrot, 0.0, normalised);
602 gsl_matrix_free (h_sqrt_inv);
605 /* Now perform the rotation iterations */
607 prev_sv = initial_sv (normalised);
608 for (i = 0 ; i < cf->iterations ; ++i)
611 for (j = 0 ; j < normalised->size2; ++j)
613 /* These variables relate to the convergence criterium */
617 for (k = j + 1 ; k < normalised->size2; ++k)
627 for (p = 0; p < normalised->size1; ++p)
629 double jv = gsl_matrix_get (normalised, p, j);
630 double kv = gsl_matrix_get (normalised, p, k);
632 double u = jv * jv - kv * kv;
633 double v = 2 * jv * kv;
640 rotation_coeff [cf->rotation] (&x, &y, a, b, c, d, normalised);
642 phi = atan2 (x, y) / 4.0 ;
644 /* Don't bother rotating if the angle is small */
645 if ( fabs (sin (phi) ) <= pow (10.0, -15.0))
648 for (p = 0; p < normalised->size1; ++p)
650 double *lambda0 = gsl_matrix_ptr (normalised, p, j);
651 double *lambda1 = gsl_matrix_ptr (normalised, p, k);
652 drot_go (phi, lambda0, lambda1);
655 /* Calculate the convergence criterium */
657 double lambda = gsl_matrix_get (normalised, k, j);
658 double lambda_sq = lambda * lambda;
659 double lambda_4 = lambda_sq * lambda_sq;
665 sv += ( normalised->size1 * l4s - (l2s * l2s) ) / (normalised->size1 * normalised->size1 );
668 if ( fabs (sv - prev_sv) <= cf->rconverge)
674 gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0,
675 h_sqrt, normalised, 0.0, result);
677 gsl_matrix_free (h_sqrt);
680 /* reflect negative sums and populate the rotated loadings vector*/
681 for (i = 0 ; i < result->size2; ++i)
685 for (j = 0 ; j < result->size1; ++j)
687 double s = gsl_matrix_get (result, j, i);
689 sum += gsl_matrix_get (result, j, i);
692 gsl_vector_set (rotated_loadings, i, ssq);
695 for (j = 0 ; j < result->size1; ++j)
697 double *lambda = gsl_matrix_ptr (result, j, i);
705 Get an approximation for the factor matrix into FACTORS, and the communalities into COMMUNALITIES.
706 R is the matrix to be analysed.
707 WS is a pointer to a structure which must have been initialised with factor_matrix_workspace_init.
710 iterate_factor_matrix (const gsl_matrix *r, gsl_vector *communalities, gsl_matrix *factors,
711 struct factor_matrix_workspace *ws)
716 assert (r->size1 == r->size2);
717 assert (r->size1 == communalities->size);
719 assert (factors->size1 == r->size1);
720 assert (factors->size2 == ws->n_factors);
722 gsl_matrix_memcpy (ws->r, r);
724 /* Apply Communalities to diagonal of correlation matrix */
725 for (i = 0 ; i < communalities->size ; ++i)
727 double *x = gsl_matrix_ptr (ws->r, i, i);
728 *x = gsl_vector_get (communalities, i);
731 gsl_eigen_symmv (ws->r, ws->eval, ws->evec, ws->eigen_ws);
733 mv = gsl_matrix_submatrix (ws->evec, 0, 0, ws->evec->size1, ws->n_factors);
735 /* Gamma is the diagonal matrix containing the absolute values of the eigenvalues */
736 for (i = 0 ; i < ws->n_factors ; ++i)
738 double *ptr = gsl_matrix_ptr (ws->gamma, i, i);
739 *ptr = fabs (gsl_vector_get (ws->eval, i));
742 /* Take the square root of gamma */
743 gsl_linalg_cholesky_decomp (ws->gamma);
745 gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, &mv.matrix, ws->gamma, 0.0, factors);
747 for (i = 0 ; i < r->size1 ; ++i)
749 double h = the_communality (ws->evec, ws->eval, i, ws->n_factors);
750 gsl_vector_set (communalities, i, h);
756 static bool run_factor (struct dataset *ds, const struct cmd_factor *factor);
760 cmd_factor (struct lexer *lexer, struct dataset *ds)
762 bool extraction_seen = false;
763 const struct dictionary *dict = dataset_dict (ds);
765 struct cmd_factor factor;
768 factor.method = METHOD_CORR;
769 factor.missing_type = MISS_LISTWISE;
770 factor.exclude = MV_ANY;
771 factor.print = PRINT_INITIAL | PRINT_EXTRACTION | PRINT_ROTATION;
772 factor.extraction = EXTRACTION_PC;
773 factor.n_factors = 0;
774 factor.min_eigen = SYSMIS;
775 factor.iterations = 25;
776 factor.econverge = 0.001;
781 factor.rotation = ROT_VARIMAX;
783 factor.rconverge = 0.0001;
785 factor.wv = dict_get_weight (dict);
787 lex_match (lexer, T_SLASH);
789 if (!lex_force_match_id (lexer, "VARIABLES"))
794 lex_match (lexer, T_EQUALS);
796 if (!parse_variables_const (lexer, dict, &factor.vars, &factor.n_vars,
797 PV_NO_DUPLICATE | PV_NUMERIC))
800 if (factor.n_vars < 2)
801 msg (MW, _("Factor analysis on a single variable is not useful."));
803 while (lex_token (lexer) != T_ENDCMD)
805 lex_match (lexer, T_SLASH);
807 if (lex_match_id (lexer, "PLOT"))
809 lex_match (lexer, T_EQUALS);
810 while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
812 if (lex_match_id (lexer, "EIGEN"))
814 factor.plot |= PLOT_SCREE;
816 #if FACTOR_FULLY_IMPLEMENTED
817 else if (lex_match_id (lexer, "ROTATION"))
823 lex_error (lexer, NULL);
828 else if (lex_match_id (lexer, "METHOD"))
830 lex_match (lexer, T_EQUALS);
831 while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
833 if (lex_match_id (lexer, "COVARIANCE"))
835 factor.method = METHOD_COV;
837 else if (lex_match_id (lexer, "CORRELATION"))
839 factor.method = METHOD_CORR;
843 lex_error (lexer, NULL);
848 else if (lex_match_id (lexer, "ROTATION"))
850 lex_match (lexer, T_EQUALS);
851 while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
853 /* VARIMAX and DEFAULT are defaults */
854 if (lex_match_id (lexer, "VARIMAX") || lex_match_id (lexer, "DEFAULT"))
856 factor.rotation = ROT_VARIMAX;
858 else if (lex_match_id (lexer, "EQUAMAX"))
860 factor.rotation = ROT_EQUAMAX;
862 else if (lex_match_id (lexer, "QUARTIMAX"))
864 factor.rotation = ROT_QUARTIMAX;
866 else if (lex_match_id (lexer, "NOROTATE"))
868 factor.rotation = ROT_NONE;
872 lex_error (lexer, NULL);
877 else if (lex_match_id (lexer, "CRITERIA"))
879 lex_match (lexer, T_EQUALS);
880 while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
882 if (lex_match_id (lexer, "FACTORS"))
884 if ( lex_force_match (lexer, T_LPAREN))
886 lex_force_int (lexer);
887 factor.n_factors = lex_integer (lexer);
889 lex_force_match (lexer, T_RPAREN);
892 else if (lex_match_id (lexer, "MINEIGEN"))
894 if ( lex_force_match (lexer, T_LPAREN))
896 lex_force_num (lexer);
897 factor.min_eigen = lex_number (lexer);
899 lex_force_match (lexer, T_RPAREN);
902 else if (lex_match_id (lexer, "ECONVERGE"))
904 if ( lex_force_match (lexer, T_LPAREN))
906 lex_force_num (lexer);
907 factor.econverge = lex_number (lexer);
909 lex_force_match (lexer, T_RPAREN);
912 else if (lex_match_id (lexer, "RCONVERGE"))
914 if ( lex_force_match (lexer, T_LPAREN))
916 lex_force_num (lexer);
917 factor.rconverge = lex_number (lexer);
919 lex_force_match (lexer, T_RPAREN);
922 else if (lex_match_id (lexer, "ITERATE"))
924 if ( lex_force_match (lexer, T_LPAREN))
926 lex_force_int (lexer);
927 factor.iterations = lex_integer (lexer);
929 lex_force_match (lexer, T_RPAREN);
932 else if (lex_match_id (lexer, "DEFAULT"))
934 factor.n_factors = 0;
935 factor.min_eigen = 1;
936 factor.iterations = 25;
940 lex_error (lexer, NULL);
945 else if (lex_match_id (lexer, "EXTRACTION"))
947 extraction_seen = true;
948 lex_match (lexer, T_EQUALS);
949 while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
951 if (lex_match_id (lexer, "PAF"))
953 factor.extraction = EXTRACTION_PAF;
955 else if (lex_match_id (lexer, "PC"))
957 factor.extraction = EXTRACTION_PC;
959 else if (lex_match_id (lexer, "PA1"))
961 factor.extraction = EXTRACTION_PC;
963 else if (lex_match_id (lexer, "DEFAULT"))
965 factor.extraction = EXTRACTION_PC;
969 lex_error (lexer, NULL);
974 else if (lex_match_id (lexer, "FORMAT"))
976 lex_match (lexer, T_EQUALS);
977 while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
979 if (lex_match_id (lexer, "SORT"))
983 else if (lex_match_id (lexer, "BLANK"))
985 if ( lex_force_match (lexer, T_LPAREN))
987 lex_force_num (lexer);
988 factor.blank = lex_number (lexer);
990 lex_force_match (lexer, T_RPAREN);
993 else if (lex_match_id (lexer, "DEFAULT"))
1000 lex_error (lexer, NULL);
1005 else if (lex_match_id (lexer, "PRINT"))
1008 lex_match (lexer, T_EQUALS);
1009 while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
1011 if (lex_match_id (lexer, "UNIVARIATE"))
1013 factor.print |= PRINT_UNIVARIATE;
1015 else if (lex_match_id (lexer, "DET"))
1017 factor.print |= PRINT_DETERMINANT;
1019 #if FACTOR_FULLY_IMPLEMENTED
1020 else if (lex_match_id (lexer, "INV"))
1023 else if (lex_match_id (lexer, "AIC"))
1027 else if (lex_match_id (lexer, "SIG"))
1029 factor.print |= PRINT_SIG;
1031 else if (lex_match_id (lexer, "CORRELATION"))
1033 factor.print |= PRINT_CORRELATION;
1035 #if FACTOR_FULLY_IMPLEMENTED
1036 else if (lex_match_id (lexer, "COVARIANCE"))
1040 else if (lex_match_id (lexer, "ROTATION"))
1042 factor.print |= PRINT_ROTATION;
1044 else if (lex_match_id (lexer, "EXTRACTION"))
1046 factor.print |= PRINT_EXTRACTION;
1048 else if (lex_match_id (lexer, "INITIAL"))
1050 factor.print |= PRINT_INITIAL;
1052 #if FACTOR_FULLY_IMPLEMENTED
1053 else if (lex_match_id (lexer, "KMO"))
1056 else if (lex_match_id (lexer, "REPR"))
1059 else if (lex_match_id (lexer, "FSCORE"))
1063 else if (lex_match (lexer, T_ALL))
1065 factor.print = 0xFFFF;
1067 else if (lex_match_id (lexer, "DEFAULT"))
1069 factor.print |= PRINT_INITIAL ;
1070 factor.print |= PRINT_EXTRACTION ;
1071 factor.print |= PRINT_ROTATION ;
1075 lex_error (lexer, NULL);
1080 else if (lex_match_id (lexer, "MISSING"))
1082 lex_match (lexer, T_EQUALS);
1083 while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
1085 if (lex_match_id (lexer, "INCLUDE"))
1087 factor.exclude = MV_SYSTEM;
1089 else if (lex_match_id (lexer, "EXCLUDE"))
1091 factor.exclude = MV_ANY;
1093 else if (lex_match_id (lexer, "LISTWISE"))
1095 factor.missing_type = MISS_LISTWISE;
1097 else if (lex_match_id (lexer, "PAIRWISE"))
1099 factor.missing_type = MISS_PAIRWISE;
1101 else if (lex_match_id (lexer, "MEANSUB"))
1103 factor.missing_type = MISS_MEANSUB;
1107 lex_error (lexer, NULL);
1114 lex_error (lexer, NULL);
1119 if ( factor.rotation == ROT_NONE )
1120 factor.print &= ~PRINT_ROTATION;
1122 if ( ! run_factor (ds, &factor))
1133 static void do_factor (const struct cmd_factor *factor, struct casereader *group);
1137 run_factor (struct dataset *ds, const struct cmd_factor *factor)
1139 struct dictionary *dict = dataset_dict (ds);
1141 struct casereader *group;
1143 struct casegrouper *grouper = casegrouper_create_splits (proc_open (ds), dict);
1145 while (casegrouper_get_next_group (grouper, &group))
1147 if ( factor->missing_type == MISS_LISTWISE )
1148 group = casereader_create_filter_missing (group, factor->vars, factor->n_vars,
1151 do_factor (factor, group);
1154 ok = casegrouper_destroy (grouper);
1155 ok = proc_commit (ds) && ok;
1161 /* Return the communality of variable N, calculated to N_FACTORS */
1163 the_communality (const gsl_matrix *evec, const gsl_vector *eval, int n, int n_factors)
1170 assert (n < eval->size);
1171 assert (n < evec->size1);
1172 assert (n_factors <= eval->size);
1174 for (i = 0 ; i < n_factors; ++i)
1176 double evali = fabs (gsl_vector_get (eval, i));
1178 double eveci = gsl_matrix_get (evec, n, i);
1180 comm += pow2 (eveci) * evali;
1186 /* Return the communality of variable N, calculated to N_FACTORS */
1188 communality (struct idata *idata, int n, int n_factors)
1190 return the_communality (idata->evec, idata->eval, n, n_factors);
1195 show_scree (const struct cmd_factor *f, struct idata *idata)
1200 if ( !(f->plot & PLOT_SCREE) )
1204 label = f->extraction == EXTRACTION_PC ? _("Component Number") : _("Factor Number");
1206 s = scree_create (idata->eval, label);
1212 show_communalities (const struct cmd_factor * factor,
1213 const gsl_vector *initial, const gsl_vector *extracted)
1217 const int heading_columns = 1;
1218 int nc = heading_columns;
1219 const int heading_rows = 1;
1220 const int nr = heading_rows + factor->n_vars;
1221 struct tab_table *t;
1223 if (factor->print & PRINT_EXTRACTION)
1226 if (factor->print & PRINT_INITIAL)
1229 /* No point having a table with only headings */
1233 t = tab_create (nc, nr);
1235 tab_title (t, _("Communalities"));
1237 tab_headers (t, heading_columns, 0, heading_rows, 0);
1240 if (factor->print & PRINT_INITIAL)
1241 tab_text (t, c++, 0, TAB_CENTER | TAT_TITLE, _("Initial"));
1243 if (factor->print & PRINT_EXTRACTION)
1244 tab_text (t, c++, 0, TAB_CENTER | TAT_TITLE, _("Extraction"));
1246 /* Outline the box */
1253 /* Vertical lines */
1260 tab_hline (t, TAL_1, 0, nc - 1, heading_rows);
1261 tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
1263 for (i = 0 ; i < factor->n_vars; ++i)
1266 tab_text (t, c++, i + heading_rows, TAT_TITLE, var_to_string (factor->vars[i]));
1268 if (factor->print & PRINT_INITIAL)
1269 tab_double (t, c++, i + heading_rows, 0, gsl_vector_get (initial, i), NULL);
1271 if (factor->print & PRINT_EXTRACTION)
1272 tab_double (t, c++, i + heading_rows, 0, gsl_vector_get (extracted, i), NULL);
1280 show_factor_matrix (const struct cmd_factor *factor, struct idata *idata, const char *title, const gsl_matrix *fm)
1283 const int n_factors = idata->n_extractions;
1285 const int heading_columns = 1;
1286 const int heading_rows = 2;
1287 const int nr = heading_rows + factor->n_vars;
1288 const int nc = heading_columns + n_factors;
1289 gsl_permutation *perm;
1291 struct tab_table *t = tab_create (nc, nr);
1294 if ( factor->extraction == EXTRACTION_PC )
1295 tab_title (t, _("Component Matrix"));
1297 tab_title (t, _("Factor Matrix"));
1300 tab_title (t, title);
1302 tab_headers (t, heading_columns, 0, heading_rows, 0);
1304 if ( factor->extraction == EXTRACTION_PC )
1308 TAB_CENTER | TAT_TITLE, _("Component"));
1313 TAB_CENTER | TAT_TITLE, _("Factor"));
1316 tab_hline (t, TAL_1, heading_columns, nc - 1, 1);
1319 /* Outline the box */
1326 /* Vertical lines */
1333 tab_hline (t, TAL_1, 0, nc - 1, heading_rows);
1334 tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
1337 /* Initialise to the identity permutation */
1338 perm = gsl_permutation_calloc (factor->n_vars);
1341 sort_matrix_indirect (fm, perm);
1343 for (i = 0 ; i < n_factors; ++i)
1345 tab_text_format (t, heading_columns + i, 1, TAB_CENTER | TAT_TITLE, _("%d"), i + 1);
1348 for (i = 0 ; i < factor->n_vars; ++i)
1351 const int matrix_row = perm->data[i];
1352 tab_text (t, 0, i + heading_rows, TAT_TITLE, var_to_string (factor->vars[matrix_row]));
1354 for (j = 0 ; j < n_factors; ++j)
1356 double x = gsl_matrix_get (fm, matrix_row, j);
1358 if ( fabs (x) < factor->blank)
1361 tab_double (t, heading_columns + j, heading_rows + i, 0, x, NULL);
1365 gsl_permutation_free (perm);
1372 show_explained_variance (const struct cmd_factor * factor, struct idata *idata,
1373 const gsl_vector *initial_eigenvalues,
1374 const gsl_vector *extracted_eigenvalues,
1375 const gsl_vector *rotated_loadings)
1379 const int heading_columns = 1;
1380 const int heading_rows = 2;
1381 const int nr = heading_rows + factor->n_vars;
1383 struct tab_table *t ;
1385 double i_total = 0.0;
1388 double e_total = 0.0;
1393 int nc = heading_columns;
1395 if (factor->print & PRINT_EXTRACTION)
1398 if (factor->print & PRINT_INITIAL)
1401 if (factor->print & PRINT_ROTATION)
1404 /* No point having a table with only headings */
1405 if ( nc <= heading_columns)
1408 t = tab_create (nc, nr);
1410 tab_title (t, _("Total Variance Explained"));
1412 tab_headers (t, heading_columns, 0, heading_rows, 0);
1414 /* Outline the box */
1421 /* Vertical lines */
1428 tab_hline (t, TAL_1, 0, nc - 1, heading_rows);
1429 tab_hline (t, TAL_1, 1, nc - 1, 1);
1431 tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
1434 if ( factor->extraction == EXTRACTION_PC)
1435 tab_text (t, 0, 1, TAB_LEFT | TAT_TITLE, _("Component"));
1437 tab_text (t, 0, 1, TAB_LEFT | TAT_TITLE, _("Factor"));
1440 if (factor->print & PRINT_INITIAL)
1442 tab_joint_text (t, c, 0, c + 2, 0, TAB_CENTER | TAT_TITLE, _("Initial Eigenvalues"));
1446 if (factor->print & PRINT_EXTRACTION)
1448 tab_joint_text (t, c, 0, c + 2, 0, TAB_CENTER | TAT_TITLE, _("Extraction Sums of Squared Loadings"));
1452 if (factor->print & PRINT_ROTATION)
1454 tab_joint_text (t, c, 0, c + 2, 0, TAB_CENTER | TAT_TITLE, _("Rotation Sums of Squared Loadings"));
1458 for (i = 0; i < (nc - heading_columns) / 3 ; ++i)
1460 tab_text (t, i * 3 + 1, 1, TAB_CENTER | TAT_TITLE, _("Total"));
1461 /* xgettext:no-c-format */
1462 tab_text (t, i * 3 + 2, 1, TAB_CENTER | TAT_TITLE, _("% of Variance"));
1463 tab_text (t, i * 3 + 3, 1, TAB_CENTER | TAT_TITLE, _("Cumulative %"));
1465 tab_vline (t, TAL_2, heading_columns + i * 3, 0, nr - 1);
1468 for (i = 0 ; i < initial_eigenvalues->size; ++i)
1469 i_total += gsl_vector_get (initial_eigenvalues, i);
1471 if ( factor->extraction == EXTRACTION_PAF)
1473 e_total = factor->n_vars;
1480 for (i = 0 ; i < factor->n_vars; ++i)
1482 const double i_lambda = gsl_vector_get (initial_eigenvalues, i);
1483 double i_percent = 100.0 * i_lambda / i_total ;
1485 const double e_lambda = gsl_vector_get (extracted_eigenvalues, i);
1486 double e_percent = 100.0 * e_lambda / e_total ;
1488 const double r_lambda = gsl_vector_get (rotated_loadings, i);
1489 double r_percent = 100.0 * r_lambda / e_total ;
1493 tab_text_format (t, c++, i + heading_rows, TAB_LEFT | TAT_TITLE, _("%d"), i + 1);
1499 /* Initial Eigenvalues */
1500 if (factor->print & PRINT_INITIAL)
1502 tab_double (t, c++, i + heading_rows, 0, i_lambda, NULL);
1503 tab_double (t, c++, i + heading_rows, 0, i_percent, NULL);
1504 tab_double (t, c++, i + heading_rows, 0, i_cum, NULL);
1508 if (factor->print & PRINT_EXTRACTION)
1510 if (i < idata->n_extractions)
1512 /* Sums of squared loadings */
1513 tab_double (t, c++, i + heading_rows, 0, e_lambda, NULL);
1514 tab_double (t, c++, i + heading_rows, 0, e_percent, NULL);
1515 tab_double (t, c++, i + heading_rows, 0, e_cum, NULL);
1519 if (factor->print & PRINT_ROTATION)
1521 if (i < idata->n_extractions)
1523 tab_double (t, c++, i + heading_rows, 0, r_lambda, NULL);
1524 tab_double (t, c++, i + heading_rows, 0, r_percent, NULL);
1525 tab_double (t, c++, i + heading_rows, 0, r_cum, NULL);
1536 show_correlation_matrix (const struct cmd_factor *factor, const struct idata *idata)
1538 struct tab_table *t ;
1540 int y_pos_corr = -1;
1542 int suffix_rows = 0;
1544 const int heading_rows = 1;
1545 const int heading_columns = 2;
1547 int nc = heading_columns ;
1548 int nr = heading_rows ;
1549 int n_data_sets = 0;
1551 if (factor->print & PRINT_CORRELATION)
1553 y_pos_corr = n_data_sets;
1555 nc = heading_columns + factor->n_vars;
1558 if (factor->print & PRINT_SIG)
1560 y_pos_sig = n_data_sets;
1562 nc = heading_columns + factor->n_vars;
1565 nr += n_data_sets * factor->n_vars;
1567 if (factor->print & PRINT_DETERMINANT)
1570 /* If the table would contain only headings, don't bother rendering it */
1571 if (nr <= heading_rows && suffix_rows == 0)
1574 t = tab_create (nc, nr + suffix_rows);
1576 tab_title (t, _("Correlation Matrix"));
1578 tab_hline (t, TAL_1, 0, nc - 1, heading_rows);
1580 if (nr > heading_rows)
1582 tab_headers (t, heading_columns, 0, heading_rows, 0);
1584 tab_vline (t, TAL_2, 2, 0, nr - 1);
1586 /* Outline the box */
1593 /* Vertical lines */
1601 for (i = 0; i < factor->n_vars; ++i)
1602 tab_text (t, heading_columns + i, 0, TAT_TITLE, var_to_string (factor->vars[i]));
1605 for (i = 0 ; i < n_data_sets; ++i)
1607 int y = heading_rows + i * factor->n_vars;
1609 for (v = 0; v < factor->n_vars; ++v)
1610 tab_text (t, 1, y + v, TAT_TITLE, var_to_string (factor->vars[v]));
1612 tab_hline (t, TAL_1, 0, nc - 1, y);
1615 if (factor->print & PRINT_CORRELATION)
1617 const double y = heading_rows + y_pos_corr;
1618 tab_text (t, 0, y, TAT_TITLE, _("Correlations"));
1620 for (i = 0; i < factor->n_vars; ++i)
1622 for (j = 0; j < factor->n_vars; ++j)
1623 tab_double (t, heading_columns + i, y + j, 0, gsl_matrix_get (idata->corr, i, j), NULL);
1627 if (factor->print & PRINT_SIG)
1629 const double y = heading_rows + y_pos_sig * factor->n_vars;
1630 tab_text (t, 0, y, TAT_TITLE, _("Sig. (1-tailed)"));
1632 for (i = 0; i < factor->n_vars; ++i)
1634 for (j = 0; j < factor->n_vars; ++j)
1636 double rho = gsl_matrix_get (idata->corr, i, j);
1637 double w = gsl_matrix_get (idata->n, i, j);
1642 tab_double (t, heading_columns + i, y + j, 0, significance_of_correlation (rho, w), NULL);
1648 if (factor->print & PRINT_DETERMINANT)
1653 const int size = idata->corr->size1;
1654 gsl_permutation *p = gsl_permutation_calloc (size);
1655 gsl_matrix *tmp = gsl_matrix_calloc (size, size);
1656 gsl_matrix_memcpy (tmp, idata->corr);
1658 gsl_linalg_LU_decomp (tmp, p, &sign);
1659 det = gsl_linalg_LU_det (tmp, sign);
1660 gsl_permutation_free (p);
1661 gsl_matrix_free (tmp);
1664 tab_text (t, 0, nr, TAB_LEFT | TAT_TITLE, _("Determinant"));
1665 tab_double (t, 1, nr, 0, det, NULL);
1674 do_factor (const struct cmd_factor *factor, struct casereader *r)
1677 const gsl_matrix *var_matrix;
1678 const gsl_matrix *mean_matrix;
1680 const gsl_matrix *analysis_matrix;
1681 struct idata *idata = idata_alloc (factor->n_vars);
1683 struct covariance *cov = covariance_1pass_create (factor->n_vars, factor->vars,
1684 factor->wv, factor->exclude);
1686 for ( ; (c = casereader_read (r) ); case_unref (c))
1688 covariance_accumulate (cov, c);
1691 idata->cov = covariance_calculate (cov);
1693 if (idata->cov == NULL)
1695 msg (MW, _("The dataset contains no complete observations. No analysis will be performed."));
1699 var_matrix = covariance_moments (cov, MOMENT_VARIANCE);
1700 mean_matrix = covariance_moments (cov, MOMENT_MEAN);
1701 idata->n = covariance_moments (cov, MOMENT_NONE);
1703 if ( factor->method == METHOD_CORR)
1705 idata->corr = correlation_from_covariance (idata->cov, var_matrix);
1706 analysis_matrix = idata->corr;
1709 analysis_matrix = idata->cov;
1711 if ( factor->print & PRINT_UNIVARIATE)
1715 const struct fmt_spec *wfmt = factor->wv ? var_get_print_format (factor->wv) : & F_8_0;
1718 const int heading_columns = 1;
1719 const int heading_rows = 1;
1721 const int nr = heading_rows + factor->n_vars;
1723 struct tab_table *t = tab_create (nc, nr);
1724 tab_title (t, _("Descriptive Statistics"));
1726 tab_headers (t, heading_columns, 0, heading_rows, 0);
1728 /* Outline the box */
1735 /* Vertical lines */
1742 tab_hline (t, TAL_1, 0, nc - 1, heading_rows);
1743 tab_vline (t, TAL_2, heading_columns, 0, nr - 1);
1745 tab_text (t, 1, 0, TAB_CENTER | TAT_TITLE, _("Mean"));
1746 tab_text (t, 2, 0, TAB_CENTER | TAT_TITLE, _("Std. Deviation"));
1747 tab_text (t, 3, 0, TAB_CENTER | TAT_TITLE, _("Analysis N"));
1749 for (i = 0 ; i < factor->n_vars; ++i)
1751 const struct variable *v = factor->vars[i];
1752 tab_text (t, 0, i + heading_rows, TAB_LEFT | TAT_TITLE, var_to_string (v));
1754 tab_double (t, 1, i + heading_rows, 0, gsl_matrix_get (mean_matrix, i, i), NULL);
1755 tab_double (t, 2, i + heading_rows, 0, sqrt (gsl_matrix_get (var_matrix, i, i)), NULL);
1756 tab_double (t, 3, i + heading_rows, 0, gsl_matrix_get (idata->n, i, i), wfmt);
1762 show_correlation_matrix (factor, idata);
1766 gsl_eigen_symmv_workspace *workspace = gsl_eigen_symmv_alloc (factor->n_vars);
1768 gsl_eigen_symmv (matrix_dup (analysis_matrix), idata->eval, idata->evec, workspace);
1770 gsl_eigen_symmv_free (workspace);
1773 gsl_eigen_symmv_sort (idata->eval, idata->evec, GSL_EIGEN_SORT_ABS_DESC);
1776 idata->n_extractions = n_extracted_factors (factor, idata);
1778 if (idata->n_extractions == 0)
1780 msg (MW, _("The FACTOR criteria result in zero factors extracted. Therefore no analysis will be performed."));
1784 if (idata->n_extractions > factor->n_vars)
1786 msg (MW, _("The FACTOR criteria result in more factors than variables, which is not meaningful. No analysis will be performed."));
1791 gsl_matrix *rotated_factors = NULL;
1792 gsl_vector *rotated_loadings = NULL;
1794 const gsl_vector *extracted_eigenvalues = NULL;
1795 gsl_vector *initial_communalities = gsl_vector_alloc (factor->n_vars);
1796 gsl_vector *extracted_communalities = gsl_vector_alloc (factor->n_vars);
1798 struct factor_matrix_workspace *fmw = factor_matrix_workspace_alloc (idata->msr->size, idata->n_extractions);
1799 gsl_matrix *factor_matrix = gsl_matrix_calloc (factor->n_vars, fmw->n_factors);
1801 if ( factor->extraction == EXTRACTION_PAF)
1803 gsl_vector *diff = gsl_vector_alloc (idata->msr->size);
1804 struct smr_workspace *ws = ws_create (analysis_matrix);
1806 for (i = 0 ; i < factor->n_vars ; ++i)
1808 double r2 = squared_multiple_correlation (analysis_matrix, i, ws);
1810 gsl_vector_set (idata->msr, i, r2);
1814 gsl_vector_memcpy (initial_communalities, idata->msr);
1816 for (i = 0; i < factor->iterations; ++i)
1819 gsl_vector_memcpy (diff, idata->msr);
1821 iterate_factor_matrix (analysis_matrix, idata->msr, factor_matrix, fmw);
1823 gsl_vector_sub (diff, idata->msr);
1825 gsl_vector_minmax (diff, &min, &max);
1827 if ( fabs (min) < factor->econverge && fabs (max) < factor->econverge)
1830 gsl_vector_free (diff);
1834 gsl_vector_memcpy (extracted_communalities, idata->msr);
1835 extracted_eigenvalues = fmw->eval;
1837 else if (factor->extraction == EXTRACTION_PC)
1839 for (i = 0; i < factor->n_vars; ++i)
1840 gsl_vector_set (initial_communalities, i, communality (idata, i, factor->n_vars));
1842 gsl_vector_memcpy (extracted_communalities, initial_communalities);
1844 iterate_factor_matrix (analysis_matrix, extracted_communalities, factor_matrix, fmw);
1847 extracted_eigenvalues = idata->eval;
1851 show_communalities (factor, initial_communalities, extracted_communalities);
1854 if ( factor->rotation != ROT_NONE)
1856 rotated_factors = gsl_matrix_calloc (factor_matrix->size1, factor_matrix->size2);
1857 rotated_loadings = gsl_vector_calloc (factor_matrix->size2);
1859 rotate (factor, factor_matrix, extracted_communalities, rotated_factors, rotated_loadings);
1862 show_explained_variance (factor, idata, idata->eval, extracted_eigenvalues, rotated_loadings);
1864 factor_matrix_workspace_free (fmw);
1866 show_scree (factor, idata);
1868 show_factor_matrix (factor, idata,
1869 factor->extraction == EXTRACTION_PC ? _("Component Matrix") : _("Factor Matrix"),
1872 if ( factor->rotation != ROT_NONE)
1874 show_factor_matrix (factor, idata,
1875 factor->extraction == EXTRACTION_PC ? _("Rotated Component Matrix") : _("Rotated Factor Matrix"),
1878 gsl_matrix_free (rotated_factors);
1883 gsl_vector_free (initial_communalities);
1884 gsl_vector_free (extracted_communalities);
1891 casereader_destroy (r);