1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 2009, 2010, 2011, 2012, 2014, 2015,
3 2016, 2017 Free Software Foundation, Inc.
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 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>
26 #include <gsl/gsl_cdf.h>
28 #include "data/any-reader.h"
29 #include "data/casegrouper.h"
30 #include "data/casereader.h"
31 #include "data/casewriter.h"
32 #include "data/dataset.h"
33 #include "data/dictionary.h"
34 #include "data/format.h"
35 #include "data/subcase.h"
36 #include "language/command.h"
37 #include "language/lexer/lexer.h"
38 #include "language/lexer/value-parser.h"
39 #include "language/lexer/variable-parser.h"
40 #include "language/commands/file-handle.h"
41 #include "language/commands/matrix-reader.h"
42 #include "libpspp/cast.h"
43 #include "libpspp/message.h"
44 #include "libpspp/misc.h"
45 #include "math/correlation.h"
46 #include "math/covariance.h"
47 #include "math/moments.h"
48 #include "output/charts/scree.h"
49 #include "output/pivot-table.h"
53 #define _(msgid) gettext (msgid)
54 #define N_(msgid) msgid
69 enum extraction_method
78 PLOT_ROTATION = 0x0002
83 PRINT_UNIVARIATE = 1 << 0,
84 PRINT_DETERMINANT = 1 << 1,
88 PRINT_COVARIANCE = 1 << 5,
89 PRINT_CORRELATION = 1 << 6,
90 PRINT_ROTATION = 1 << 7,
91 PRINT_EXTRACTION = 1 << 8,
92 PRINT_INITIAL = 1 << 9,
95 PRINT_FSCORE = 1 << 12
107 typedef void (*rotation_coefficients) (double *x, double *y,
108 double a, double b, double c, double d,
109 const gsl_matrix *loadings);
113 varimax_coefficients (double *x, double *y,
114 double a, double b, double c, double d,
115 const gsl_matrix *loadings)
117 *x = d - 2 * a * b / loadings->size1;
118 *y = c - (a * a - b * b) / loadings->size1;
122 equamax_coefficients (double *x, double *y,
123 double a, double b, double c, double d,
124 const gsl_matrix *loadings)
126 *x = d - loadings->size2 * a * b / loadings->size1;
127 *y = c - loadings->size2 * (a * a - b * b) / (2 * loadings->size1);
131 quartimax_coefficients (double *x, double *y,
132 double a UNUSED, double b UNUSED, double c, double d,
133 const gsl_matrix *loadings UNUSED)
139 static const rotation_coefficients rotation_coeff[] = {
140 varimax_coefficients,
141 equamax_coefficients,
142 quartimax_coefficients,
143 varimax_coefficients /* PROMAX is identical to VARIMAX */
147 /* return diag (C'C) ^ {-0.5} */
149 diag_rcp_sqrt (const gsl_matrix *C)
151 gsl_matrix *d = gsl_matrix_calloc (C->size1, C->size2);
152 gsl_matrix *r = gsl_matrix_calloc (C->size1, C->size2);
154 assert (C->size1 == C->size2);
156 gsl_linalg_matmult_mod (C, GSL_LINALG_MOD_TRANSPOSE,
157 C, GSL_LINALG_MOD_NONE,
160 for (int j = 0; j < d->size2; ++j)
162 double e = gsl_matrix_get (d, j, j);
164 gsl_matrix_set (r, j, j, e);
174 /* return diag ((C'C)^-1) ^ {-0.5} */
176 diag_rcp_inv_sqrt (const gsl_matrix *CCinv)
178 gsl_matrix *r = gsl_matrix_calloc (CCinv->size1, CCinv->size2);
180 assert (CCinv->size1 == CCinv->size2);
182 for (int j = 0; j < CCinv->size2; ++j)
184 double e = gsl_matrix_get (CCinv, j, j);
186 gsl_matrix_set (r, j, j, e);
199 const struct variable **vars;
201 const struct variable *wv;
204 enum missing_type missing_type;
205 enum mv_class exclude;
206 enum print_opts print;
207 enum extraction_method extraction;
209 enum rotation_type rotation;
210 int rotation_iterations;
213 /* Extraction Criteria */
217 int extraction_iterations;
229 /* Intermediate values used in calculation */
230 struct matrix_material mm;
232 gsl_matrix *analysis_matrix; /* A pointer to either mm.corr or mm.cov */
234 gsl_vector *eval; /* The eigenvalues */
235 gsl_matrix *evec; /* The eigenvectors */
239 gsl_vector *msr; /* Multiple Squared Regressions */
241 double detR; /* The determinant of the correlation matrix */
243 gsl_matrix *ai_cov; /* The anti-image covariance matrix */
244 gsl_matrix *ai_cor; /* The anti-image correlation matrix */
245 struct covariance *cvm;
248 static struct idata *
249 idata_alloc (size_t n_vars)
251 struct idata *id = XZALLOC (struct idata);
253 id->n_extractions = 0;
254 id->msr = gsl_vector_alloc (n_vars);
256 id->eval = gsl_vector_alloc (n_vars);
257 id->evec = gsl_matrix_alloc (n_vars, n_vars);
263 idata_free (struct idata *id)
265 gsl_vector_free (id->msr);
266 gsl_vector_free (id->eval);
267 gsl_matrix_free (id->evec);
268 gsl_matrix_free (id->ai_cov);
269 gsl_matrix_free (id->ai_cor);
274 /* Return the sum of squares of all the elements in row J excluding column J */
276 ssq_row_od_n (const gsl_matrix *m, int j)
278 assert (m->size1 == m->size2);
279 assert (j < m->size1);
282 for (int i = 0; i < m->size1; ++i)
284 ss += pow2 (gsl_matrix_get (m, i, j));
288 /* Return the sum of squares of all the elements excluding row N */
290 ssq_od_n (const gsl_matrix *m, int n)
292 assert (m->size1 == m->size2);
293 assert (n < m->size1);
296 for (int i = 0; i < m->size1; ++i)
297 for (int j = 0; j < m->size2; ++j)
299 ss += pow2 (gsl_matrix_get (m, i, j));
305 anti_image_corr (const gsl_matrix *m, const struct idata *idata)
307 assert (m->size1 == m->size2);
309 gsl_matrix *a = gsl_matrix_alloc (m->size1, m->size2);
310 for (int i = 0; i < m->size1; ++i)
311 for (int j = 0; j < m->size2; ++j)
313 double *p = gsl_matrix_ptr (a, i, j);
314 *p = gsl_matrix_get (m, i, j);
315 *p /= sqrt (gsl_matrix_get (m, i, i) *
316 gsl_matrix_get (m, j, j));
319 for (int i = 0; i < m->size1; ++i)
321 double r = ssq_row_od_n (idata->mm.corr, i);
322 double u = ssq_row_od_n (a, i);
323 gsl_matrix_set (a, i, i, r / (r + u));
330 anti_image_cov (const gsl_matrix *m)
332 assert (m->size1 == m->size2);
334 gsl_matrix *a = gsl_matrix_alloc (m->size1, m->size2);
335 for (int i = 0; i < m->size1; ++i)
336 for (int j = 0; j < m->size2; ++j)
338 double *p = gsl_matrix_ptr (a, i, j);
339 *p = gsl_matrix_get (m, i, j);
340 *p /= gsl_matrix_get (m, i, i);
341 *p /= gsl_matrix_get (m, j, j);
349 dump_matrix (const gsl_matrix *m)
351 for (int i = 0; i < m->size1; ++i)
353 for (int j = 0; j < m->size2; ++j)
354 printf ("%02f ", gsl_matrix_get (m, i, j));
360 dump_matrix_permute (const gsl_matrix *m, const gsl_permutation *p)
362 for (int i = 0; i < m->size1; ++i)
364 for (int j = 0; j < m->size2; ++j)
365 printf ("%02f ", gsl_matrix_get (m, gsl_permutation_get (p, i), j));
372 dump_vector (const gsl_vector *v)
374 for (size_t i = 0; i < v->size; ++i)
375 printf ("%02f\n", gsl_vector_get (v, i));
382 n_extracted_factors (const struct cmd_factor *factor, struct idata *idata)
384 /* If there is a cached value, then return that. */
385 if (idata->n_extractions != 0)
386 return idata->n_extractions;
388 /* Otherwise, if the number of factors has been explicitly requested,
390 if (factor->n_factors > 0)
392 idata->n_extractions = factor->n_factors;
396 /* Use the MIN_EIGEN setting. */
397 for (int i = 0; i < idata->eval->size; ++i)
399 double evali = fabs (gsl_vector_get (idata->eval, i));
401 idata->n_extractions = i;
403 if (evali < factor->min_eigen)
408 return idata->n_extractions;
412 /* Returns a newly allocated matrix identical to M.
413 It is the callers responsibility to free the returned value.
416 matrix_dup (const gsl_matrix *m)
418 gsl_matrix *n = gsl_matrix_alloc (m->size1, m->size2);
419 gsl_matrix_memcpy (n, m);
426 /* Copy of the subject */
431 gsl_permutation *perm;
438 static struct smr_workspace *ws_create (const gsl_matrix *input)
440 struct smr_workspace *ws = xmalloc (sizeof (*ws));
442 ws->m = gsl_matrix_alloc (input->size1, input->size2);
443 ws->inverse = gsl_matrix_calloc (input->size1 - 1, input->size2 - 1);
444 ws->perm = gsl_permutation_alloc (input->size1 - 1);
445 ws->result1 = gsl_matrix_calloc (input->size1 - 1, 1);
446 ws->result2 = gsl_matrix_calloc (1, 1);
452 ws_destroy (struct smr_workspace *ws)
454 gsl_matrix_free (ws->result2);
455 gsl_matrix_free (ws->result1);
456 gsl_permutation_free (ws->perm);
457 gsl_matrix_free (ws->inverse);
458 gsl_matrix_free (ws->m);
465 Return the square of the regression coefficient for VAR regressed against all other variables.
468 squared_multiple_correlation (const gsl_matrix *corr, int var, struct smr_workspace *ws)
470 /* For an explanation of what this is doing, see
471 http://www.visualstatistics.net/Visual%20Statistics%20Multimedia/multiple_regression_analysis.htm
474 gsl_matrix_memcpy (ws->m, corr);
476 gsl_matrix_swap_rows (ws->m, 0, var);
477 gsl_matrix_swap_columns (ws->m, 0, var);
479 gsl_matrix_view rxx = gsl_matrix_submatrix (ws->m, 1, 1, ws->m->size1 - 1, ws->m->size1 - 1);
482 gsl_linalg_LU_decomp (&rxx.matrix, ws->perm, &signum);
484 gsl_linalg_LU_invert (&rxx.matrix, ws->perm, ws->inverse);
486 gsl_matrix_const_view rxy = gsl_matrix_const_submatrix (ws->m, 1, 0, ws->m->size1 - 1, 1);
487 gsl_matrix_const_view ryx = gsl_matrix_const_submatrix (ws->m, 0, 1, 1, ws->m->size1 - 1);
489 gsl_blas_dgemm (CblasNoTrans, CblasNoTrans,
490 1.0, ws->inverse, &rxy.matrix, 0.0, ws->result1);
492 gsl_blas_dgemm (CblasNoTrans, CblasNoTrans,
493 1.0, &ryx.matrix, ws->result1, 0.0, ws->result2);
495 return gsl_matrix_get (ws->result2, 0, 0);
500 static double the_communality (const gsl_matrix *evec, const gsl_vector *eval, int n, int n_factors);
503 struct factor_matrix_workspace
506 gsl_eigen_symmv_workspace *eigen_ws;
516 static struct factor_matrix_workspace *
517 factor_matrix_workspace_alloc (size_t n, size_t nf)
519 struct factor_matrix_workspace *ws = xmalloc (sizeof (*ws));
522 ws->gamma = gsl_matrix_calloc (nf, nf);
523 ws->eigen_ws = gsl_eigen_symmv_alloc (n);
524 ws->eval = gsl_vector_alloc (n);
525 ws->evec = gsl_matrix_alloc (n, n);
526 ws->r = gsl_matrix_alloc (n, n);
532 factor_matrix_workspace_free (struct factor_matrix_workspace *ws)
534 gsl_eigen_symmv_free (ws->eigen_ws);
535 gsl_vector_free (ws->eval);
536 gsl_matrix_free (ws->evec);
537 gsl_matrix_free (ws->gamma);
538 gsl_matrix_free (ws->r);
543 Shift P left by OFFSET places, and overwrite TARGET
544 with the shifted result.
545 Positions in TARGET less than OFFSET are unchanged.
548 perm_shift_apply (gsl_permutation *target, const gsl_permutation *p,
551 assert (target->size == p->size);
552 assert (offset <= target->size);
554 for (size_t i = 0; i < target->size - offset; ++i)
555 target->data[i] = p->data [i + offset];
560 Indirectly sort the rows of matrix INPUT, storing the sort order in PERM.
561 The sort criteria are as follows:
563 Rows are sorted on the first column, until the absolute value of an
564 element in a subsequent column is greater than that of the first
565 column. Thereafter, rows will be sorted on the second column,
566 until the absolute value of an element in a subsequent column
567 exceeds that of the second column ...
570 sort_matrix_indirect (const gsl_matrix *input, gsl_permutation *perm)
572 assert (perm->size == input->size1);
574 const size_t n = perm->size;
575 const size_t m = input->size2;
576 gsl_permutation *p = gsl_permutation_alloc (n);
578 /* Copy INPUT into MAT, discarding the sign */
579 gsl_matrix *mat = gsl_matrix_alloc (n, m);
580 for (int i = 0; i < mat->size1; ++i)
581 for (int j = 0; j < mat->size2; ++j)
582 gsl_matrix_set (mat, i, j, fabs (gsl_matrix_get (input, i, j)));
586 while (column_n < m && row_n < n)
588 gsl_vector_const_view columni = gsl_matrix_const_column (mat, column_n);
589 gsl_sort_vector_index (p, &columni.vector);
592 for (i = 0; i < n; ++i)
594 gsl_vector_view row = gsl_matrix_row (mat, p->data[n - 1 - i]);
595 size_t maxindex = gsl_vector_max_index (&row.vector);
597 if (maxindex > column_n)
600 /* All subsequent elements of this row, are of no interest.
601 So set them all to a highly negative value */
602 for (int j = column_n + 1; j < row.vector.size; ++j)
603 gsl_vector_set (&row.vector, j, -DBL_MAX);
606 perm_shift_apply (perm, p, row_n);
612 gsl_permutation_free (p);
613 gsl_matrix_free (mat);
615 assert (0 == gsl_permutation_valid (perm));
617 /* We want the biggest value to be first */
618 gsl_permutation_reverse (perm);
623 drot_go (double phi, double *l0, double *l1)
625 double r0 = cos (phi) * *l0 + sin (phi) * *l1;
626 double r1 = - sin (phi) * *l0 + cos (phi) * *l1;
634 clone_matrix (const gsl_matrix *m)
636 gsl_matrix *c = gsl_matrix_calloc (m->size1, m->size2);
638 for (int j = 0; j < c->size1; ++j)
639 for (int k = 0; k < c->size2; ++k)
640 gsl_matrix_set (c, j, k, gsl_matrix_get (m, j, k));
647 initial_sv (const gsl_matrix *fm)
650 for (int j = 0; j < fm->size2; ++j)
655 for (int k = j + 1; k < fm->size2; ++k)
657 double lambda = gsl_matrix_get (fm, k, j);
658 double lambda_sq = lambda * lambda;
659 double lambda_4 = lambda_sq * lambda_sq;
664 sv += (fm->size1 * l4s - (l2s * l2s)) / (fm->size1 * fm->size1);
670 rotate (const struct cmd_factor *cf, const gsl_matrix *unrot,
671 const gsl_vector *communalities,
673 gsl_vector *rotated_loadings,
674 gsl_matrix *pattern_matrix,
675 gsl_matrix *factor_correlation_matrix)
677 /* First get a normalised version of UNROT */
678 gsl_matrix *normalised = gsl_matrix_calloc (unrot->size1, unrot->size2);
679 gsl_matrix *h_sqrt = gsl_matrix_calloc (communalities->size, communalities->size);
680 gsl_matrix *h_sqrt_inv;
682 /* H is the diagonal matrix containing the absolute values of the communalities */
683 for (int i = 0; i < communalities->size; ++i)
685 double *ptr = gsl_matrix_ptr (h_sqrt, i, i);
686 *ptr = fabs (gsl_vector_get (communalities, i));
689 /* Take the square root of the communalities */
690 gsl_linalg_cholesky_decomp (h_sqrt);
692 /* Save a copy of h_sqrt and invert it */
693 h_sqrt_inv = clone_matrix (h_sqrt);
694 gsl_linalg_cholesky_decomp (h_sqrt_inv);
695 gsl_linalg_cholesky_invert (h_sqrt_inv);
697 /* normalised vertion is H^{1/2} x UNROT */
698 gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, h_sqrt_inv, unrot, 0.0, normalised);
700 gsl_matrix_free (h_sqrt_inv);
702 /* Now perform the rotation iterations */
703 double prev_sv = initial_sv (normalised);
704 for (int i = 0; i < cf->rotation_iterations; ++i)
707 for (int j = 0; j < normalised->size2; ++j)
709 /* These variables relate to the convergence criterium */
713 for (int k = j + 1; k < normalised->size2; ++k)
719 for (int p = 0; p < normalised->size1; ++p)
721 double jv = gsl_matrix_get (normalised, p, j);
722 double kv = gsl_matrix_get (normalised, p, k);
724 double u = jv * jv - kv * kv;
725 double v = 2 * jv * kv;
733 rotation_coeff [cf->rotation] (&x, &y, a, b, c, d, normalised);
734 double phi = atan2 (x, y) / 4.0;
736 /* Don't bother rotating if the angle is small */
737 if (fabs (sin (phi)) <= pow (10.0, -15.0))
740 for (int p = 0; p < normalised->size1; ++p)
742 double *lambda0 = gsl_matrix_ptr (normalised, p, j);
743 double *lambda1 = gsl_matrix_ptr (normalised, p, k);
744 drot_go (phi, lambda0, lambda1);
747 /* Calculate the convergence criterium */
748 double lambda = gsl_matrix_get (normalised, k, j);
749 double lambda_sq = lambda * lambda;
750 double lambda_4 = lambda_sq * lambda_sq;
755 sv += (normalised->size1 * l4s - (l2s * l2s)) / (normalised->size1 * normalised->size1);
758 if (fabs (sv - prev_sv) <= cf->rconverge)
764 gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0,
765 h_sqrt, normalised, 0.0, result);
767 gsl_matrix_free (h_sqrt);
768 gsl_matrix_free (normalised);
770 if (cf->rotation == ROT_PROMAX)
772 /* general purpose m by m matrix, where m is the number of factors */
773 gsl_matrix *mm1 = gsl_matrix_calloc (unrot->size2, unrot->size2);
774 gsl_matrix *mm2 = gsl_matrix_calloc (unrot->size2, unrot->size2);
776 /* general purpose m by p matrix, where p is the number of variables */
777 gsl_matrix *mp1 = gsl_matrix_calloc (unrot->size2, unrot->size1);
779 gsl_matrix *pm1 = gsl_matrix_calloc (unrot->size1, unrot->size2);
781 gsl_permutation *perm = gsl_permutation_alloc (unrot->size2);
784 /* The following variables follow the notation by SPSS Statistical
785 Algorithms page 342. */
786 gsl_matrix *L = gsl_matrix_calloc (unrot->size2, unrot->size2);
787 gsl_matrix *P = clone_matrix (result);
789 /* Vector of length p containing (indexed by i)
790 \Sum^m_j {\lambda^2_{ij}} */
791 gsl_vector *rssq = gsl_vector_calloc (unrot->size1);
793 for (int i = 0; i < P->size1; ++i)
796 for (int j = 0; j < P->size2; ++j)
797 sum += gsl_matrix_get (result, i, j) * gsl_matrix_get (result, i, j);
798 gsl_vector_set (rssq, i, sqrt (sum));
801 for (int i = 0; i < P->size1; ++i)
803 for (int j = 0; j < P->size2; ++j)
805 double l = gsl_matrix_get (result, i, j);
806 double r = gsl_vector_get (rssq, i);
807 gsl_matrix_set (P, i, j, pow (fabs (l / r), cf->promax_power + 1) * r / l);
811 gsl_vector_free (rssq);
813 gsl_linalg_matmult_mod (result,
814 GSL_LINALG_MOD_TRANSPOSE,
820 gsl_linalg_LU_decomp (mm1, perm, &signum);
821 gsl_linalg_LU_invert (mm1, perm, mm2);
823 gsl_linalg_matmult_mod (mm2, GSL_LINALG_MOD_NONE,
824 result, GSL_LINALG_MOD_TRANSPOSE,
827 gsl_linalg_matmult_mod (mp1, GSL_LINALG_MOD_NONE,
828 P, GSL_LINALG_MOD_NONE,
831 gsl_matrix *D = diag_rcp_sqrt (L);
832 gsl_matrix *Q = gsl_matrix_calloc (unrot->size2, unrot->size2);
834 gsl_linalg_matmult_mod (L, GSL_LINALG_MOD_NONE,
835 D, GSL_LINALG_MOD_NONE,
838 gsl_matrix *QQinv = gsl_matrix_calloc (unrot->size2, unrot->size2);
840 gsl_linalg_matmult_mod (Q, GSL_LINALG_MOD_TRANSPOSE,
841 Q, GSL_LINALG_MOD_NONE,
844 gsl_linalg_cholesky_decomp (QQinv);
845 gsl_linalg_cholesky_invert (QQinv);
848 gsl_matrix *C = diag_rcp_inv_sqrt (QQinv);
849 gsl_matrix *Cinv = clone_matrix (C);
851 gsl_linalg_cholesky_decomp (Cinv);
852 gsl_linalg_cholesky_invert (Cinv);
855 gsl_linalg_matmult_mod (result, GSL_LINALG_MOD_NONE,
856 Q, GSL_LINALG_MOD_NONE,
859 gsl_linalg_matmult_mod (pm1, GSL_LINALG_MOD_NONE,
860 Cinv, GSL_LINALG_MOD_NONE,
864 gsl_linalg_matmult_mod (C, GSL_LINALG_MOD_NONE,
865 QQinv, GSL_LINALG_MOD_NONE,
868 gsl_linalg_matmult_mod (mm1, GSL_LINALG_MOD_NONE,
869 C, GSL_LINALG_MOD_TRANSPOSE,
870 factor_correlation_matrix);
872 gsl_linalg_matmult_mod (pattern_matrix, GSL_LINALG_MOD_NONE,
873 factor_correlation_matrix, GSL_LINALG_MOD_NONE,
876 gsl_matrix_memcpy (result, pm1);
879 gsl_matrix_free (QQinv);
881 gsl_matrix_free (Cinv);
888 gsl_permutation_free (perm);
890 gsl_matrix_free (mm1);
891 gsl_matrix_free (mm2);
892 gsl_matrix_free (mp1);
893 gsl_matrix_free (pm1);
897 /* reflect negative sums and populate the rotated loadings vector*/
898 for (int i = 0; i < result->size2; ++i)
902 for (int j = 0; j < result->size1; ++j)
904 double s = gsl_matrix_get (result, j, i);
909 gsl_vector_set (rotated_loadings, i, ssq);
912 for (int j = 0; j < result->size1; ++j)
914 double *lambda = gsl_matrix_ptr (result, j, i);
921 Get an approximation for the factor matrix into FACTORS, and the communalities into COMMUNALITIES.
922 R is the matrix to be analysed.
923 WS is a pointer to a structure which must have been initialised with factor_matrix_workspace_init.
926 iterate_factor_matrix (const gsl_matrix *r, gsl_vector *communalities, gsl_matrix *factors,
927 struct factor_matrix_workspace *ws)
929 assert (r->size1 == r->size2);
930 assert (r->size1 == communalities->size);
932 assert (factors->size1 == r->size1);
933 assert (factors->size2 == ws->n_factors);
935 gsl_matrix_memcpy (ws->r, r);
937 /* Apply Communalities to diagonal of correlation matrix */
938 for (size_t i = 0; i < communalities->size; ++i)
940 double *x = gsl_matrix_ptr (ws->r, i, i);
941 *x = gsl_vector_get (communalities, i);
944 gsl_eigen_symmv (ws->r, ws->eval, ws->evec, ws->eigen_ws);
946 gsl_matrix_view mv = gsl_matrix_submatrix (ws->evec, 0, 0, ws->evec->size1, ws->n_factors);
948 /* Gamma is the diagonal matrix containing the absolute values of the eigenvalues */
949 for (size_t i = 0; i < ws->n_factors; ++i)
951 double *ptr = gsl_matrix_ptr (ws->gamma, i, i);
952 *ptr = fabs (gsl_vector_get (ws->eval, i));
955 /* Take the square root of gamma */
956 gsl_linalg_cholesky_decomp (ws->gamma);
958 gsl_blas_dgemm (CblasNoTrans, CblasNoTrans, 1.0, &mv.matrix, ws->gamma, 0.0, factors);
960 for (size_t i = 0; i < r->size1; ++i)
962 double h = the_communality (ws->evec, ws->eval, i, ws->n_factors);
963 gsl_vector_set (communalities, i, h);
969 static bool run_factor (struct dataset *ds, const struct cmd_factor *factor);
971 static void do_factor_by_matrix (const struct cmd_factor *factor, struct idata *idata);
976 cmd_factor (struct lexer *lexer, struct dataset *ds)
978 int n_iterations = 25;
980 struct cmd_factor factor = {
983 .method = METHOD_CORR,
984 .missing_type = MISS_LISTWISE,
986 .print = PRINT_INITIAL | PRINT_EXTRACTION | PRINT_ROTATION,
987 .extraction = EXTRACTION_PC,
990 .extraction_iterations = 25,
991 .rotation_iterations = 25,
997 .rotation = ROT_VARIMAX,
1000 .rconverge = 0.0001,
1003 lex_match (lexer, T_SLASH);
1005 struct dictionary *dict = NULL;
1006 struct matrix_reader *mr = NULL;
1007 struct casereader *matrix_reader = NULL;
1009 int vars_start, vars_end;
1010 if (lex_match_id (lexer, "VARIABLES"))
1012 lex_match (lexer, T_EQUALS);
1013 dict = dataset_dict (ds);
1014 factor.wv = dict_get_weight (dict);
1016 vars_start = lex_ofs (lexer);
1017 if (!parse_variables_const (lexer, dict, &factor.vars, &factor.n_vars,
1018 PV_NO_DUPLICATE | PV_NUMERIC))
1020 vars_end = lex_ofs (lexer) - 1;
1022 else if (lex_match_id (lexer, "MATRIX"))
1024 lex_match (lexer, T_EQUALS);
1025 if (!lex_force_match_phrase (lexer, "IN("))
1027 if (!lex_match_id (lexer, "CORR") && !lex_match_id (lexer, "COV"))
1029 lex_error (lexer, _("Matrix input for %s must be either COV or CORR"),
1033 if (!lex_force_match (lexer, T_EQUALS))
1035 vars_start = lex_ofs (lexer);
1036 if (lex_match (lexer, T_ASTERISK))
1038 dict = dataset_dict (ds);
1039 matrix_reader = casereader_clone (dataset_source (ds));
1043 struct file_handle *fh = fh_parse (lexer, FH_REF_FILE, NULL);
1047 matrix_reader = any_reader_open_and_decode (fh, NULL, &dict, NULL);
1049 if (!(matrix_reader && dict))
1052 vars_end = lex_ofs (lexer) - 1;
1054 if (!lex_force_match (lexer, T_RPAREN))
1056 casereader_destroy (matrix_reader);
1060 mr = matrix_reader_create (dict, matrix_reader);
1061 factor.vars = xmemdup (mr->cvars, mr->n_cvars * sizeof *mr->cvars);
1062 factor.n_vars = mr->n_cvars;
1067 while (lex_token (lexer) != T_ENDCMD)
1069 lex_match (lexer, T_SLASH);
1071 if (lex_match_id (lexer, "ANALYSIS"))
1073 struct const_var_set *vs;
1074 const struct variable **vars;
1077 lex_match (lexer, T_EQUALS);
1079 vars_start = lex_ofs (lexer);
1080 vs = const_var_set_create_from_array (factor.vars, factor.n_vars);
1081 vars_end = lex_ofs (lexer) - 1;
1082 bool ok = parse_const_var_set_vars (lexer, vs, &vars, &n_vars,
1083 PV_NO_DUPLICATE | PV_NUMERIC);
1084 const_var_set_destroy (vs);
1091 factor.n_vars = n_vars;
1096 mr->cvars = xmemdup (vars, n_vars * sizeof *vars);
1097 mr->n_cvars = n_vars;
1100 else if (lex_match_id (lexer, "PLOT"))
1102 lex_match (lexer, T_EQUALS);
1103 while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
1105 if (lex_match_id (lexer, "EIGEN"))
1107 factor.plot |= PLOT_SCREE;
1109 #if FACTOR_FULLY_IMPLEMENTED
1110 else if (lex_match_id (lexer, "ROTATION"))
1116 lex_error_expecting (lexer, "EIGEN"
1117 #if FACTOR_FULLY_IMPLEMENTED
1125 else if (lex_match_id (lexer, "METHOD"))
1127 lex_match (lexer, T_EQUALS);
1128 while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
1130 if (lex_match_id (lexer, "COVARIANCE"))
1131 factor.method = METHOD_COV;
1132 else if (lex_match_id (lexer, "CORRELATION"))
1133 factor.method = METHOD_CORR;
1136 lex_error_expecting (lexer, "COVARIANCE", "CORRELATION");
1141 else if (lex_match_id (lexer, "ROTATION"))
1143 lex_match (lexer, T_EQUALS);
1144 while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
1146 /* VARIMAX and DEFAULT are defaults */
1147 if (lex_match_id (lexer, "VARIMAX") || lex_match_id (lexer, "DEFAULT"))
1148 factor.rotation = ROT_VARIMAX;
1149 else if (lex_match_id (lexer, "EQUAMAX"))
1150 factor.rotation = ROT_EQUAMAX;
1151 else if (lex_match_id (lexer, "QUARTIMAX"))
1152 factor.rotation = ROT_QUARTIMAX;
1153 else if (lex_match_id (lexer, "PROMAX"))
1155 factor.promax_power = 5;
1156 if (lex_match (lexer, T_LPAREN))
1158 if (!lex_force_int (lexer))
1160 factor.promax_power = lex_integer (lexer);
1162 if (!lex_force_match (lexer, T_RPAREN))
1165 factor.rotation = ROT_PROMAX;
1167 else if (lex_match_id (lexer, "NOROTATE"))
1168 factor.rotation = ROT_NONE;
1171 lex_error_expecting (lexer, "DEFAULT", "VARIMAX", "EQUAMAX",
1172 "QUARTIMAX", "PROMAX", "NOROTATE");
1176 factor.rotation_iterations = n_iterations;
1178 else if (lex_match_id (lexer, "CRITERIA"))
1180 lex_match (lexer, T_EQUALS);
1181 while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
1183 if (lex_match_id (lexer, "FACTORS"))
1185 if (!lex_force_match (lexer, T_LPAREN)
1186 || !lex_force_int (lexer))
1188 factor.n_factors = lex_integer (lexer);
1190 if (!lex_force_match (lexer, T_RPAREN))
1193 else if (lex_match_id (lexer, "MINEIGEN"))
1195 if (!lex_force_match (lexer, T_LPAREN)
1196 || !lex_force_num (lexer))
1198 factor.min_eigen = lex_number (lexer);
1200 if (!lex_force_match (lexer, T_RPAREN))
1203 else if (lex_match_id (lexer, "ECONVERGE"))
1205 if (!lex_force_match (lexer, T_LPAREN)
1206 || !lex_force_num (lexer))
1208 factor.econverge = lex_number (lexer);
1210 if (!lex_force_match (lexer, T_RPAREN))
1213 else if (lex_match_id (lexer, "RCONVERGE"))
1215 if (!lex_force_match (lexer, T_LPAREN)
1216 || !lex_force_num (lexer))
1218 factor.rconverge = lex_number (lexer);
1220 if (!lex_force_match (lexer, T_RPAREN))
1223 else if (lex_match_id (lexer, "ITERATE"))
1225 if (!lex_force_match (lexer, T_LPAREN)
1226 || !lex_force_int_range (lexer, "ITERATE", 0, INT_MAX))
1228 n_iterations = lex_integer (lexer);
1230 if (!lex_force_match (lexer, T_RPAREN))
1233 else if (lex_match_id (lexer, "DEFAULT"))
1235 factor.n_factors = 0;
1236 factor.min_eigen = 1;
1241 lex_error_expecting (lexer, "FACTORS", "MINEIGEN",
1242 "ECONVERGE", "RCONVERGE", "ITERATE",
1248 else if (lex_match_id (lexer, "EXTRACTION"))
1250 lex_match (lexer, T_EQUALS);
1251 while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
1253 if (lex_match_id (lexer, "PAF"))
1254 factor.extraction = EXTRACTION_PAF;
1255 else if (lex_match_id (lexer, "PC"))
1256 factor.extraction = EXTRACTION_PC;
1257 else if (lex_match_id (lexer, "PA1"))
1258 factor.extraction = EXTRACTION_PC;
1259 else if (lex_match_id (lexer, "DEFAULT"))
1260 factor.extraction = EXTRACTION_PC;
1263 lex_error_expecting (lexer, "PAF", "PC", "PA1", "DEFAULT");
1267 factor.extraction_iterations = n_iterations;
1269 else if (lex_match_id (lexer, "FORMAT"))
1271 lex_match (lexer, T_EQUALS);
1272 while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
1274 if (lex_match_id (lexer, "SORT"))
1276 else if (lex_match_id (lexer, "BLANK"))
1278 if (!lex_force_match (lexer, T_LPAREN)
1279 || !lex_force_num (lexer))
1281 factor.blank = lex_number (lexer);
1283 if (!lex_force_match (lexer, T_RPAREN))
1286 else if (lex_match_id (lexer, "DEFAULT"))
1289 factor.sort = false;
1293 lex_error_expecting (lexer, "SORT", "BLANK", "DEFAULT");
1298 else if (lex_match_id (lexer, "PRINT"))
1301 lex_match (lexer, T_EQUALS);
1302 while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
1304 if (lex_match_id (lexer, "UNIVARIATE"))
1305 factor.print |= PRINT_UNIVARIATE;
1306 else if (lex_match_id (lexer, "DET"))
1307 factor.print |= PRINT_DETERMINANT;
1308 #if FACTOR_FULLY_IMPLEMENTED
1309 else if (lex_match_id (lexer, "INV"))
1313 else if (lex_match_id (lexer, "AIC"))
1314 factor.print |= PRINT_AIC;
1315 else if (lex_match_id (lexer, "SIG"))
1316 factor.print |= PRINT_SIG;
1317 else if (lex_match_id (lexer, "CORRELATION"))
1318 factor.print |= PRINT_CORRELATION;
1319 else if (lex_match_id (lexer, "COVARIANCE"))
1320 factor.print |= PRINT_COVARIANCE;
1321 else if (lex_match_id (lexer, "ROTATION"))
1322 factor.print |= PRINT_ROTATION;
1323 else if (lex_match_id (lexer, "EXTRACTION"))
1324 factor.print |= PRINT_EXTRACTION;
1325 else if (lex_match_id (lexer, "INITIAL"))
1326 factor.print |= PRINT_INITIAL;
1327 else if (lex_match_id (lexer, "KMO"))
1328 factor.print |= PRINT_KMO;
1329 #if FACTOR_FULLY_IMPLEMENTED
1330 else if (lex_match_id (lexer, "REPR"))
1333 else if (lex_match_id (lexer, "FSCORE"))
1337 else if (lex_match (lexer, T_ALL))
1339 else if (lex_match_id (lexer, "DEFAULT"))
1341 factor.print |= PRINT_INITIAL;
1342 factor.print |= PRINT_EXTRACTION;
1343 factor.print |= PRINT_ROTATION;
1347 lex_error_expecting (lexer, "UNIVARIATE", "DET", "AIC", "SIG",
1348 "CORRELATION", "COVARIANCE", "ROTATION",
1349 "EXTRACTION", "INITIAL", "KMO", "ALL",
1355 else if (lex_match_id (lexer, "MISSING"))
1357 lex_match (lexer, T_EQUALS);
1358 while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
1360 if (lex_match_id (lexer, "INCLUDE"))
1361 factor.exclude = MV_SYSTEM;
1362 else if (lex_match_id (lexer, "EXCLUDE"))
1363 factor.exclude = MV_ANY;
1364 else if (lex_match_id (lexer, "LISTWISE"))
1365 factor.missing_type = MISS_LISTWISE;
1366 else if (lex_match_id (lexer, "PAIRWISE"))
1367 factor.missing_type = MISS_PAIRWISE;
1368 else if (lex_match_id (lexer, "MEANSUB"))
1369 factor.missing_type = MISS_MEANSUB;
1372 lex_error_expecting (lexer, "INCLUDE", "EXCLUDE", "LISTWISE",
1373 "PAIRRWISE", "MEANSUB");
1380 lex_error_expecting (lexer, "ANALYSIS", "PLOT", "METHOD", "ROTATION",
1381 "CRITERIA", "EXTRACTION", "FORMAT", "PRINT",
1387 if (factor.rotation == ROT_NONE)
1388 factor.print &= ~PRINT_ROTATION;
1390 assert (factor.n_vars > 0);
1391 if (factor.n_vars < 2)
1392 lex_ofs_msg (lexer, SW, vars_start, vars_end,
1393 _("Factor analysis on a single variable is not useful."));
1397 struct idata *id = idata_alloc (factor.n_vars);
1399 while (matrix_reader_next (&id->mm, mr, NULL))
1401 do_factor_by_matrix (&factor, id);
1403 gsl_matrix_free (id->ai_cov);
1405 gsl_matrix_free (id->ai_cor);
1408 matrix_material_uninit (&id->mm);
1414 if (!run_factor (ds, &factor))
1417 matrix_reader_destroy (mr);
1422 matrix_reader_destroy (mr);
1427 static void do_factor (const struct cmd_factor *factor, struct casereader *group);
1431 run_factor (struct dataset *ds, const struct cmd_factor *factor)
1433 struct dictionary *dict = dataset_dict (ds);
1435 struct casereader *group;
1437 struct casegrouper *grouper = casegrouper_create_splits (proc_open (ds), dict);
1439 while (casegrouper_get_next_group (grouper, &group))
1441 if (factor->missing_type == MISS_LISTWISE)
1442 group = casereader_create_filter_missing (group, factor->vars, factor->n_vars,
1445 do_factor (factor, group);
1448 ok = casegrouper_destroy (grouper);
1449 ok = proc_commit (ds) && ok;
1455 /* Return the communality of variable N, calculated to N_FACTORS */
1457 the_communality (const gsl_matrix *evec, const gsl_vector *eval, int n, int n_factors)
1460 assert (n < eval->size);
1461 assert (n < evec->size1);
1462 assert (n_factors <= eval->size);
1465 for (size_t i = 0; i < n_factors; ++i)
1467 double evali = fabs (gsl_vector_get (eval, i));
1469 double eveci = gsl_matrix_get (evec, n, i);
1471 comm += pow2 (eveci) * evali;
1477 /* Return the communality of variable N, calculated to N_FACTORS */
1479 communality (const struct idata *idata, int n, int n_factors)
1481 return the_communality (idata->evec, idata->eval, n, n_factors);
1486 show_scree (const struct cmd_factor *f, const struct idata *idata)
1491 if (!(f->plot & PLOT_SCREE))
1495 label = f->extraction == EXTRACTION_PC ? _("Component Number") : _("Factor Number");
1497 s = scree_create (idata->eval, label);
1503 show_communalities (const struct cmd_factor * factor,
1504 const gsl_vector *initial, const gsl_vector *extracted)
1506 if (!(factor->print & (PRINT_INITIAL | PRINT_EXTRACTION)))
1509 struct pivot_table *table = pivot_table_create (N_("Communalities"));
1511 struct pivot_dimension *communalities = pivot_dimension_create (
1512 table, PIVOT_AXIS_COLUMN, N_("Communalities"));
1513 if (factor->print & PRINT_INITIAL)
1514 pivot_category_create_leaves (communalities->root, N_("Initial"));
1515 if (factor->print & PRINT_EXTRACTION)
1516 pivot_category_create_leaves (communalities->root, N_("Extraction"));
1518 struct pivot_dimension *variables = pivot_dimension_create (
1519 table, PIVOT_AXIS_ROW, N_("Variables"));
1521 for (size_t i = 0; i < factor->n_vars; ++i)
1523 int row = pivot_category_create_leaf (
1524 variables->root, pivot_value_new_variable (factor->vars[i]));
1527 if (factor->print & PRINT_INITIAL)
1528 pivot_table_put2 (table, col++, row, pivot_value_new_number (
1529 gsl_vector_get (initial, i)));
1530 if (factor->print & PRINT_EXTRACTION)
1531 pivot_table_put2 (table, col++, row, pivot_value_new_number (
1532 gsl_vector_get (extracted, i)));
1535 pivot_table_submit (table);
1538 static struct pivot_dimension *
1539 create_numeric_dimension (struct pivot_table *table,
1540 enum pivot_axis_type axis_type, const char *name,
1541 size_t n, bool show_label)
1543 struct pivot_dimension *d = pivot_dimension_create (table, axis_type, name);
1544 d->root->show_label = show_label;
1545 for (int i = 0; i < n; ++i)
1546 pivot_category_create_leaf (d->root, pivot_value_new_integer (i + 1));
1551 show_factor_matrix (const struct cmd_factor *factor, const struct idata *idata, const char *title, const gsl_matrix *fm)
1553 struct pivot_table *table = pivot_table_create (title);
1555 const int n_factors = idata->n_extractions;
1556 create_numeric_dimension (
1557 table, PIVOT_AXIS_COLUMN,
1558 factor->extraction == EXTRACTION_PC ? N_("Component") : N_("Factor"),
1561 struct pivot_dimension *variables = pivot_dimension_create (
1562 table, PIVOT_AXIS_ROW, N_("Variables"));
1564 /* Initialise to the identity permutation */
1565 gsl_permutation *perm = gsl_permutation_calloc (factor->n_vars);
1568 sort_matrix_indirect (fm, perm);
1570 for (size_t i = 0; i < factor->n_vars; ++i)
1572 const int matrix_row = perm->data[i];
1574 int var_idx = pivot_category_create_leaf (
1575 variables->root, pivot_value_new_variable (factor->vars[matrix_row]));
1577 for (size_t j = 0; j < n_factors; ++j)
1579 double x = gsl_matrix_get (fm, matrix_row, j);
1580 if (fabs (x) < factor->blank)
1583 pivot_table_put2 (table, j, var_idx, pivot_value_new_number (x));
1587 gsl_permutation_free (perm);
1589 pivot_table_submit (table);
1593 put_variance (struct pivot_table *table, int row, int phase_idx,
1594 double lambda, double percent, double cum)
1596 double entries[] = { lambda, percent, cum };
1597 for (size_t i = 0; i < sizeof entries / sizeof *entries; i++)
1598 pivot_table_put3 (table, i, phase_idx, row,
1599 pivot_value_new_number (entries[i]));
1603 show_explained_variance (const struct cmd_factor * factor,
1604 const struct idata *idata,
1605 const gsl_vector *initial_eigenvalues,
1606 const gsl_vector *extracted_eigenvalues,
1607 const gsl_vector *rotated_loadings)
1609 if (!(factor->print & (PRINT_INITIAL | PRINT_EXTRACTION | PRINT_ROTATION)))
1612 struct pivot_table *table = pivot_table_create (
1613 N_("Total Variance Explained"));
1615 pivot_dimension_create (table, PIVOT_AXIS_COLUMN, N_("Statistics"),
1616 N_("Total"), PIVOT_RC_OTHER,
1617 /* xgettext:no-c-format */
1618 N_("% of Variance"), PIVOT_RC_PERCENT,
1619 /* xgettext:no-c-format */
1620 N_("Cumulative %"), PIVOT_RC_PERCENT);
1622 struct pivot_dimension *phase = pivot_dimension_create (
1623 table, PIVOT_AXIS_COLUMN, N_("Phase"));
1624 if (factor->print & PRINT_INITIAL)
1625 pivot_category_create_leaves (phase->root, N_("Initial Eigenvalues"));
1627 if (factor->print & PRINT_EXTRACTION)
1628 pivot_category_create_leaves (phase->root,
1629 N_("Extraction Sums of Squared Loadings"));
1631 if (factor->print & PRINT_ROTATION)
1632 pivot_category_create_leaves (phase->root,
1633 N_("Rotation Sums of Squared Loadings"));
1635 struct pivot_dimension *components = pivot_dimension_create (
1636 table, PIVOT_AXIS_ROW,
1637 factor->extraction == EXTRACTION_PC ? N_("Component") : N_("Factor"));
1639 double i_total = 0.0;
1640 for (size_t i = 0; i < initial_eigenvalues->size; ++i)
1641 i_total += gsl_vector_get (initial_eigenvalues, i);
1643 double e_total = (factor->extraction == EXTRACTION_PAF
1650 for (size_t i = 0; i < factor->n_vars; ++i)
1652 const double i_lambda = gsl_vector_get (initial_eigenvalues, i);
1653 double i_percent = 100.0 * i_lambda / i_total;
1656 const double e_lambda = gsl_vector_get (extracted_eigenvalues, i);
1657 double e_percent = 100.0 * e_lambda / e_total;
1660 int row = pivot_category_create_leaf (
1661 components->root, pivot_value_new_integer (i + 1));
1665 /* Initial Eigenvalues */
1666 if (factor->print & PRINT_INITIAL)
1667 put_variance (table, row, phase_idx++, i_lambda, i_percent, i_cum);
1669 if (i < idata->n_extractions)
1671 if (factor->print & PRINT_EXTRACTION)
1672 put_variance (table, row, phase_idx++, e_lambda, e_percent, e_cum);
1674 if (rotated_loadings != NULL && factor->print & PRINT_ROTATION)
1676 double r_lambda = gsl_vector_get (rotated_loadings, i);
1677 double r_percent = 100.0 * r_lambda / e_total;
1678 if (factor->rotation == ROT_PROMAX)
1679 r_lambda = r_percent = SYSMIS;
1682 put_variance (table, row, phase_idx++, r_lambda, r_percent,
1688 pivot_table_submit (table);
1692 show_factor_correlation (const struct cmd_factor * factor, const gsl_matrix *fcm)
1694 struct pivot_table *table = pivot_table_create (
1695 N_("Factor Correlation Matrix"));
1697 create_numeric_dimension (
1698 table, PIVOT_AXIS_ROW,
1699 factor->extraction == EXTRACTION_PC ? N_("Component") : N_("Factor"),
1702 create_numeric_dimension (table, PIVOT_AXIS_COLUMN, N_("Factor 2"),
1705 for (size_t i = 0; i < fcm->size1; ++i)
1706 for (size_t j = 0; j < fcm->size2; ++j)
1707 pivot_table_put2 (table, j, i,
1708 pivot_value_new_number (gsl_matrix_get (fcm, i, j)));
1710 pivot_table_submit (table);
1714 add_var_dims (struct pivot_table *table, const struct cmd_factor *factor)
1716 for (int i = 0; i < 2; i++)
1718 struct pivot_dimension *d = pivot_dimension_create (
1719 table, i ? PIVOT_AXIS_ROW : PIVOT_AXIS_COLUMN,
1722 for (size_t j = 0; j < factor->n_vars; j++)
1723 pivot_category_create_leaf (
1724 d->root, pivot_value_new_variable (factor->vars[j]));
1729 show_aic (const struct cmd_factor *factor, const struct idata *idata)
1731 if ((factor->print & PRINT_AIC) == 0)
1734 struct pivot_table *table = pivot_table_create (N_("Anti-Image Matrices"));
1736 add_var_dims (table, factor);
1738 pivot_dimension_create (table, PIVOT_AXIS_ROW, N_("Statistics"),
1739 N_("Anti-image Covariance"),
1740 N_("Anti-image Correlation"));
1742 for (size_t i = 0; i < factor->n_vars; ++i)
1743 for (size_t j = 0; j < factor->n_vars; ++j)
1745 double cov = gsl_matrix_get (idata->ai_cov, i, j);
1746 pivot_table_put3 (table, i, j, 0, pivot_value_new_number (cov));
1748 double corr = gsl_matrix_get (idata->ai_cor, i, j);
1749 pivot_table_put3 (table, i, j, 1, pivot_value_new_number (corr));
1752 pivot_table_submit (table);
1756 show_correlation_matrix (const struct cmd_factor *factor, const struct idata *idata)
1758 if (!(factor->print & (PRINT_CORRELATION | PRINT_SIG | PRINT_DETERMINANT)))
1761 struct pivot_table *table = pivot_table_create (N_("Correlation Matrix"));
1763 if (factor->print & (PRINT_CORRELATION | PRINT_SIG))
1765 add_var_dims (table, factor);
1767 struct pivot_dimension *statistics = pivot_dimension_create (
1768 table, PIVOT_AXIS_ROW, N_("Statistics"));
1769 if (factor->print & PRINT_CORRELATION)
1770 pivot_category_create_leaves (statistics->root, N_("Correlation"),
1771 PIVOT_RC_CORRELATION);
1772 if (factor->print & PRINT_SIG)
1773 pivot_category_create_leaves (statistics->root, N_("Sig. (1-tailed)"),
1774 PIVOT_RC_SIGNIFICANCE);
1777 if (factor->print & PRINT_CORRELATION)
1779 for (int i = 0; i < factor->n_vars; ++i)
1780 for (int j = 0; j < factor->n_vars; ++j)
1782 double corr = gsl_matrix_get (idata->mm.corr, i, j);
1783 pivot_table_put3 (table, j, i, stat_idx,
1784 pivot_value_new_number (corr));
1789 if (factor->print & PRINT_SIG)
1791 for (int i = 0; i < factor->n_vars; ++i)
1792 for (int j = 0; j < factor->n_vars; ++j)
1795 double rho = gsl_matrix_get (idata->mm.corr, i, j);
1796 double w = gsl_matrix_get (idata->mm.n, i, j);
1797 double sig = significance_of_correlation (rho, w);
1798 pivot_table_put3 (table, j, i, stat_idx,
1799 pivot_value_new_number (sig));
1805 if (factor->print & PRINT_DETERMINANT)
1807 struct pivot_value *caption = pivot_value_new_user_text_nocopy (
1808 xasprintf ("%s: %.2f", _("Determinant"), idata->detR));
1809 pivot_table_set_caption (table, caption);
1812 pivot_table_submit (table);
1816 show_covariance_matrix (const struct cmd_factor *factor, const struct idata *idata)
1818 if (!(factor->print & PRINT_COVARIANCE))
1821 struct pivot_table *table = pivot_table_create (N_("Covariance Matrix"));
1822 add_var_dims (table, factor);
1824 for (int i = 0; i < factor->n_vars; ++i)
1825 for (int j = 0; j < factor->n_vars; ++j)
1827 double cov = gsl_matrix_get (idata->mm.cov, i, j);
1828 pivot_table_put2 (table, j, i, pivot_value_new_number (cov));
1831 pivot_table_submit (table);
1836 do_factor (const struct cmd_factor *factor, struct casereader *r)
1839 struct idata *idata = idata_alloc (factor->n_vars);
1841 idata->cvm = covariance_1pass_create (factor->n_vars, factor->vars,
1842 factor->wv, factor->exclude, true);
1844 for (; (c = casereader_read (r)); case_unref (c))
1846 covariance_accumulate (idata->cvm, c);
1849 idata->mm.cov = covariance_calculate (idata->cvm);
1851 if (idata->mm.cov == NULL)
1853 msg (MW, _("The dataset contains no complete observations. No analysis will be performed."));
1854 covariance_destroy (idata->cvm);
1858 idata->mm.var_matrix = covariance_moments (idata->cvm, MOMENT_VARIANCE);
1859 idata->mm.mean_matrix = covariance_moments (idata->cvm, MOMENT_MEAN);
1860 idata->mm.n = covariance_moments (idata->cvm, MOMENT_NONE);
1862 do_factor_by_matrix (factor, idata);
1865 gsl_matrix_free (idata->mm.corr);
1866 gsl_matrix_free (idata->mm.cov);
1869 casereader_destroy (r);
1873 do_factor_by_matrix (const struct cmd_factor *factor, struct idata *idata)
1875 if (!idata->mm.cov && !(idata->mm.corr && idata->mm.var_matrix))
1877 msg (ME, _("The dataset has no covariance matrix or a "
1878 "correlation matrix along with standard deviations."));
1882 if (idata->mm.cov && !idata->mm.corr)
1883 idata->mm.corr = correlation_from_covariance (idata->mm.cov, idata->mm.var_matrix);
1884 if (idata->mm.corr && !idata->mm.cov)
1885 idata->mm.cov = covariance_from_correlation (idata->mm.corr, idata->mm.var_matrix);
1886 if (factor->method == METHOD_CORR)
1887 idata->analysis_matrix = idata->mm.corr;
1889 idata->analysis_matrix = idata->mm.cov;
1892 r_inv = clone_matrix (idata->mm.corr);
1893 gsl_linalg_cholesky_decomp (r_inv);
1894 gsl_linalg_cholesky_invert (r_inv);
1896 idata->ai_cov = anti_image_cov (r_inv);
1897 idata->ai_cor = anti_image_corr (r_inv, idata);
1899 double sum_ssq_r = 0;
1900 double sum_ssq_a = 0;
1901 for (int i = 0; i < r_inv->size1; ++i)
1903 sum_ssq_r += ssq_od_n (idata->mm.corr, i);
1904 sum_ssq_a += ssq_od_n (idata->ai_cor, i);
1907 gsl_matrix_free (r_inv);
1909 if (factor->print & PRINT_DETERMINANT
1910 || factor->print & PRINT_KMO)
1914 const int size = idata->mm.corr->size1;
1915 gsl_permutation *p = gsl_permutation_calloc (size);
1916 gsl_matrix *tmp = gsl_matrix_calloc (size, size);
1917 gsl_matrix_memcpy (tmp, idata->mm.corr);
1919 gsl_linalg_LU_decomp (tmp, p, &sign);
1920 idata->detR = gsl_linalg_LU_det (tmp, sign);
1921 gsl_permutation_free (p);
1922 gsl_matrix_free (tmp);
1925 if (factor->print & PRINT_UNIVARIATE
1926 && idata->mm.n && idata->mm.mean_matrix && idata->mm.var_matrix)
1928 struct pivot_table *table = pivot_table_create (
1929 N_("Descriptive Statistics"));
1930 pivot_table_set_weight_var (table, factor->wv);
1932 pivot_dimension_create (table, PIVOT_AXIS_COLUMN, N_("Statistics"),
1933 N_("Mean"), PIVOT_RC_OTHER,
1934 N_("Std. Deviation"), PIVOT_RC_OTHER,
1935 N_("Analysis N"), PIVOT_RC_COUNT);
1937 struct pivot_dimension *variables = pivot_dimension_create (
1938 table, PIVOT_AXIS_ROW, N_("Variables"));
1940 for (size_t i = 0; i < factor->n_vars; ++i)
1942 const struct variable *v = factor->vars[i];
1944 int row = pivot_category_create_leaf (
1945 variables->root, pivot_value_new_variable (v));
1947 double entries[] = {
1948 gsl_matrix_get (idata->mm.mean_matrix, i, i),
1949 sqrt (gsl_matrix_get (idata->mm.var_matrix, i, i)),
1950 gsl_matrix_get (idata->mm.n, i, i),
1952 for (size_t j = 0; j < sizeof entries / sizeof *entries; j++)
1953 pivot_table_put2 (table, j, row,
1954 pivot_value_new_number (entries[j]));
1957 pivot_table_submit (table);
1960 if (factor->print & PRINT_KMO && idata->mm.n)
1962 struct pivot_table *table = pivot_table_create (
1963 N_("KMO and Bartlett's Test"));
1965 struct pivot_dimension *statistics = pivot_dimension_create (
1966 table, PIVOT_AXIS_ROW, N_("Statistics"),
1967 N_("Kaiser-Meyer-Olkin Measure of Sampling Adequacy"), PIVOT_RC_OTHER);
1968 pivot_category_create_group (
1969 statistics->root, N_("Bartlett's Test of Sphericity"),
1970 N_("Approx. Chi-Square"), PIVOT_RC_OTHER,
1971 N_("df"), PIVOT_RC_INTEGER,
1972 N_("Sig."), PIVOT_RC_SIGNIFICANCE);
1974 /* The literature doesn't say what to do for the value of W when
1975 missing values are involved. The best thing I can think of
1976 is to take the mean average. */
1978 for (int i = 0; i < idata->mm.n->size1; ++i)
1979 w += gsl_matrix_get (idata->mm.n, i, i);
1980 w /= idata->mm.n->size1;
1982 double xsq = ((w - 1 - (2 * factor->n_vars + 5) / 6.0)
1983 * -log (idata->detR));
1984 double df = factor->n_vars * (factor->n_vars - 1) / 2;
1985 double entries[] = {
1986 sum_ssq_r / (sum_ssq_r + sum_ssq_a),
1989 gsl_cdf_chisq_Q (xsq, df)
1991 for (size_t i = 0; i < sizeof entries / sizeof *entries; i++)
1992 pivot_table_put1 (table, i, pivot_value_new_number (entries[i]));
1994 pivot_table_submit (table);
1997 show_correlation_matrix (factor, idata);
1998 show_covariance_matrix (factor, idata);
2000 covariance_destroy (idata->cvm);
2003 gsl_matrix *am = matrix_dup (idata->analysis_matrix);
2004 gsl_eigen_symmv_workspace *workspace = gsl_eigen_symmv_alloc (factor->n_vars);
2006 gsl_eigen_symmv (am, idata->eval, idata->evec, workspace);
2008 gsl_eigen_symmv_free (workspace);
2009 gsl_matrix_free (am);
2012 gsl_eigen_symmv_sort (idata->eval, idata->evec, GSL_EIGEN_SORT_ABS_DESC);
2014 idata->n_extractions = n_extracted_factors (factor, idata);
2016 if (idata->n_extractions == 0)
2018 msg (MW, _("The %s criteria result in zero factors extracted. Therefore no analysis will be performed."), "FACTOR");
2022 if (idata->n_extractions > factor->n_vars)
2025 _("The %s criteria result in more factors than variables, which is not meaningful. No analysis will be performed."),
2031 gsl_matrix *rotated_factors = NULL;
2032 gsl_matrix *pattern_matrix = NULL;
2033 gsl_matrix *fcm = NULL;
2034 gsl_vector *rotated_loadings = NULL;
2036 const gsl_vector *extracted_eigenvalues = NULL;
2037 gsl_vector *initial_communalities = gsl_vector_alloc (factor->n_vars);
2038 gsl_vector *extracted_communalities = gsl_vector_alloc (factor->n_vars);
2039 struct factor_matrix_workspace *fmw = factor_matrix_workspace_alloc (idata->msr->size, idata->n_extractions);
2040 gsl_matrix *factor_matrix = gsl_matrix_calloc (factor->n_vars, fmw->n_factors);
2042 if (factor->extraction == EXTRACTION_PAF)
2044 gsl_vector *diff = gsl_vector_alloc (idata->msr->size);
2045 struct smr_workspace *ws = ws_create (idata->analysis_matrix);
2047 for (size_t i = 0; i < factor->n_vars; ++i)
2049 double r2 = squared_multiple_correlation (idata->analysis_matrix, i, ws);
2051 gsl_vector_set (idata->msr, i, r2);
2055 gsl_vector_memcpy (initial_communalities, idata->msr);
2057 for (size_t i = 0; i < factor->extraction_iterations; ++i)
2060 gsl_vector_memcpy (diff, idata->msr);
2062 iterate_factor_matrix (idata->analysis_matrix, idata->msr, factor_matrix, fmw);
2064 gsl_vector_sub (diff, idata->msr);
2066 gsl_vector_minmax (diff, &min, &max);
2068 if (fabs (min) < factor->econverge && fabs (max) < factor->econverge)
2071 gsl_vector_free (diff);
2075 gsl_vector_memcpy (extracted_communalities, idata->msr);
2076 extracted_eigenvalues = fmw->eval;
2078 else if (factor->extraction == EXTRACTION_PC)
2080 for (size_t i = 0; i < factor->n_vars; ++i)
2081 gsl_vector_set (initial_communalities, i, communality (idata, i, factor->n_vars));
2083 gsl_vector_memcpy (extracted_communalities, initial_communalities);
2085 iterate_factor_matrix (idata->analysis_matrix, extracted_communalities, factor_matrix, fmw);
2088 extracted_eigenvalues = idata->eval;
2092 show_aic (factor, idata);
2093 show_communalities (factor, initial_communalities, extracted_communalities);
2095 if (factor->rotation != ROT_NONE)
2097 rotated_factors = gsl_matrix_calloc (factor_matrix->size1, factor_matrix->size2);
2098 rotated_loadings = gsl_vector_calloc (factor_matrix->size2);
2099 if (factor->rotation == ROT_PROMAX)
2101 pattern_matrix = gsl_matrix_calloc (factor_matrix->size1, factor_matrix->size2);
2102 fcm = gsl_matrix_calloc (factor_matrix->size2, factor_matrix->size2);
2106 rotate (factor, factor_matrix, extracted_communalities, rotated_factors, rotated_loadings, pattern_matrix, fcm);
2109 show_explained_variance (factor, idata, idata->eval, extracted_eigenvalues, rotated_loadings);
2111 factor_matrix_workspace_free (fmw);
2113 show_scree (factor, idata);
2115 show_factor_matrix (factor, idata,
2116 (factor->extraction == EXTRACTION_PC
2117 ? N_("Component Matrix") : N_("Factor Matrix")),
2120 if (factor->rotation == ROT_PROMAX)
2122 show_factor_matrix (factor, idata, N_("Pattern Matrix"),
2124 gsl_matrix_free (pattern_matrix);
2127 if (factor->rotation != ROT_NONE)
2129 show_factor_matrix (factor, idata,
2130 (factor->rotation == ROT_PROMAX
2131 ? N_("Structure Matrix")
2132 : factor->extraction == EXTRACTION_PC
2133 ? N_("Rotated Component Matrix")
2134 : N_("Rotated Factor Matrix")),
2137 gsl_matrix_free (rotated_factors);
2140 if (factor->rotation == ROT_PROMAX)
2142 show_factor_correlation (factor, fcm);
2143 gsl_matrix_free (fcm);
2146 gsl_matrix_free (factor_matrix);
2147 gsl_vector_free (rotated_loadings);
2148 gsl_vector_free (initial_communalities);
2149 gsl_vector_free (extracted_communalities);