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/data-io/file-handle.h"
41 #include "language/data-io/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_id (lexer, "IN"))
1027 if (!lex_force_match (lexer, T_LPAREN))
1029 if (!lex_match_id (lexer, "CORR") && !lex_match_id (lexer, "COV"))
1031 lex_error (lexer, _("Matrix input for %s must be either COV or CORR"),
1035 if (!lex_force_match (lexer, T_EQUALS))
1037 vars_start = lex_ofs (lexer);
1038 if (lex_match (lexer, T_ASTERISK))
1040 dict = dataset_dict (ds);
1041 matrix_reader = casereader_clone (dataset_source (ds));
1045 struct file_handle *fh = fh_parse (lexer, FH_REF_FILE, NULL);
1049 matrix_reader = any_reader_open_and_decode (fh, NULL, &dict, NULL);
1051 if (!(matrix_reader && dict))
1054 vars_end = lex_ofs (lexer) - 1;
1056 if (!lex_force_match (lexer, T_RPAREN))
1059 mr = matrix_reader_create (dict, matrix_reader);
1060 factor.vars = xmemdup (mr->cvars, mr->n_cvars * sizeof *mr->cvars);
1061 factor.n_vars = mr->n_cvars;
1066 while (lex_token (lexer) != T_ENDCMD)
1068 lex_match (lexer, T_SLASH);
1070 if (lex_match_id (lexer, "ANALYSIS"))
1072 struct const_var_set *vs;
1073 const struct variable **vars;
1076 lex_match (lexer, T_EQUALS);
1078 vars_start = lex_ofs (lexer);
1079 vs = const_var_set_create_from_array (factor.vars, factor.n_vars);
1080 vars_end = lex_ofs (lexer) - 1;
1081 bool ok = parse_const_var_set_vars (lexer, vs, &vars, &n_vars,
1082 PV_NO_DUPLICATE | PV_NUMERIC);
1083 const_var_set_destroy (vs);
1090 factor.n_vars = n_vars;
1095 mr->cvars = xmemdup (vars, n_vars * sizeof *vars);
1096 mr->n_cvars = n_vars;
1099 else if (lex_match_id (lexer, "PLOT"))
1101 lex_match (lexer, T_EQUALS);
1102 while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
1104 if (lex_match_id (lexer, "EIGEN"))
1106 factor.plot |= PLOT_SCREE;
1108 #if FACTOR_FULLY_IMPLEMENTED
1109 else if (lex_match_id (lexer, "ROTATION"))
1115 lex_error (lexer, NULL);
1120 else if (lex_match_id (lexer, "METHOD"))
1122 lex_match (lexer, T_EQUALS);
1123 while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
1125 if (lex_match_id (lexer, "COVARIANCE"))
1126 factor.method = METHOD_COV;
1127 else if (lex_match_id (lexer, "CORRELATION"))
1128 factor.method = METHOD_CORR;
1131 lex_error_expecting (lexer, "COVARIANCE", "CORRELATION");
1136 else if (lex_match_id (lexer, "ROTATION"))
1138 lex_match (lexer, T_EQUALS);
1139 while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
1141 /* VARIMAX and DEFAULT are defaults */
1142 if (lex_match_id (lexer, "VARIMAX") || lex_match_id (lexer, "DEFAULT"))
1143 factor.rotation = ROT_VARIMAX;
1144 else if (lex_match_id (lexer, "EQUAMAX"))
1145 factor.rotation = ROT_EQUAMAX;
1146 else if (lex_match_id (lexer, "QUARTIMAX"))
1147 factor.rotation = ROT_QUARTIMAX;
1148 else if (lex_match_id (lexer, "PROMAX"))
1150 factor.promax_power = 5;
1151 if (lex_match (lexer, T_LPAREN)
1152 && lex_force_int (lexer))
1154 factor.promax_power = lex_integer (lexer);
1156 if (!lex_force_match (lexer, T_RPAREN))
1159 factor.rotation = ROT_PROMAX;
1161 else if (lex_match_id (lexer, "NOROTATE"))
1162 factor.rotation = ROT_NONE;
1165 lex_error_expecting (lexer, "DEFAULT", "VARIMAX", "EQUAMAX",
1166 "QUARTIMAX", "PROMAX", "NOROTATE");
1170 factor.rotation_iterations = n_iterations;
1172 else if (lex_match_id (lexer, "CRITERIA"))
1174 lex_match (lexer, T_EQUALS);
1175 while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
1177 if (lex_match_id (lexer, "FACTORS"))
1179 if (lex_force_match (lexer, T_LPAREN)
1180 && lex_force_int (lexer))
1182 factor.n_factors = lex_integer (lexer);
1184 if (!lex_force_match (lexer, T_RPAREN))
1188 else if (lex_match_id (lexer, "MINEIGEN"))
1190 if (lex_force_match (lexer, T_LPAREN)
1191 && lex_force_num (lexer))
1193 factor.min_eigen = lex_number (lexer);
1195 if (!lex_force_match (lexer, T_RPAREN))
1199 else if (lex_match_id (lexer, "ECONVERGE"))
1201 if (lex_force_match (lexer, T_LPAREN)
1202 && lex_force_num (lexer))
1204 factor.econverge = lex_number (lexer);
1206 if (!lex_force_match (lexer, T_RPAREN))
1210 else if (lex_match_id (lexer, "RCONVERGE"))
1212 if (lex_force_match (lexer, T_LPAREN)
1213 && lex_force_num (lexer))
1215 factor.rconverge = lex_number (lexer);
1217 if (!lex_force_match (lexer, T_RPAREN))
1221 else if (lex_match_id (lexer, "ITERATE"))
1223 if (lex_force_match (lexer, T_LPAREN)
1224 && lex_force_int_range (lexer, "ITERATE", 0, INT_MAX))
1226 n_iterations = lex_integer (lexer);
1228 if (!lex_force_match (lexer, T_RPAREN))
1232 else if (lex_match_id (lexer, "DEFAULT"))
1234 factor.n_factors = 0;
1235 factor.min_eigen = 1;
1240 lex_error_expecting (lexer, "FACTORS", "MINEIGEN",
1241 "ECONVERGE", "RCONVERGE", "ITERATE",
1247 else if (lex_match_id (lexer, "EXTRACTION"))
1249 lex_match (lexer, T_EQUALS);
1250 while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
1252 if (lex_match_id (lexer, "PAF"))
1253 factor.extraction = EXTRACTION_PAF;
1254 else if (lex_match_id (lexer, "PC"))
1255 factor.extraction = EXTRACTION_PC;
1256 else if (lex_match_id (lexer, "PA1"))
1257 factor.extraction = EXTRACTION_PC;
1258 else if (lex_match_id (lexer, "DEFAULT"))
1259 factor.extraction = EXTRACTION_PC;
1262 lex_error_expecting (lexer, "PAF", "PC", "PA1", "DEFAULT");
1266 factor.extraction_iterations = n_iterations;
1268 else if (lex_match_id (lexer, "FORMAT"))
1270 lex_match (lexer, T_EQUALS);
1271 while (lex_token (lexer) != T_ENDCMD && lex_token (lexer) != T_SLASH)
1273 if (lex_match_id (lexer, "SORT"))
1275 else if (lex_match_id (lexer, "BLANK"))
1277 if (lex_force_match (lexer, T_LPAREN)
1278 && lex_force_num (lexer))
1280 factor.blank = lex_number (lexer);
1282 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 (lexer, NULL);
1385 if (factor.rotation == ROT_NONE)
1386 factor.print &= ~PRINT_ROTATION;
1388 if (factor.n_vars < 2)
1389 lex_ofs_msg (lexer, SW, vars_start, vars_end,
1390 _("Factor analysis on a single variable is not useful."));
1392 if (factor.n_vars < 1)
1394 lex_ofs_error (lexer, vars_start, vars_end,
1395 _("Factor analysis without variables is not possible."));
1401 struct idata *id = idata_alloc (factor.n_vars);
1403 while (matrix_reader_next (&id->mm, mr, NULL))
1405 do_factor_by_matrix (&factor, id);
1407 gsl_matrix_free (id->ai_cov);
1409 gsl_matrix_free (id->ai_cor);
1412 matrix_material_uninit (&id->mm);
1418 if (!run_factor (ds, &factor))
1421 matrix_reader_destroy (mr);
1426 matrix_reader_destroy (mr);
1431 static void do_factor (const struct cmd_factor *factor, struct casereader *group);
1435 run_factor (struct dataset *ds, const struct cmd_factor *factor)
1437 struct dictionary *dict = dataset_dict (ds);
1439 struct casereader *group;
1441 struct casegrouper *grouper = casegrouper_create_splits (proc_open (ds), dict);
1443 while (casegrouper_get_next_group (grouper, &group))
1445 if (factor->missing_type == MISS_LISTWISE)
1446 group = casereader_create_filter_missing (group, factor->vars, factor->n_vars,
1449 do_factor (factor, group);
1452 ok = casegrouper_destroy (grouper);
1453 ok = proc_commit (ds) && ok;
1459 /* Return the communality of variable N, calculated to N_FACTORS */
1461 the_communality (const gsl_matrix *evec, const gsl_vector *eval, int n, int n_factors)
1464 assert (n < eval->size);
1465 assert (n < evec->size1);
1466 assert (n_factors <= eval->size);
1469 for (size_t i = 0; i < n_factors; ++i)
1471 double evali = fabs (gsl_vector_get (eval, i));
1473 double eveci = gsl_matrix_get (evec, n, i);
1475 comm += pow2 (eveci) * evali;
1481 /* Return the communality of variable N, calculated to N_FACTORS */
1483 communality (const struct idata *idata, int n, int n_factors)
1485 return the_communality (idata->evec, idata->eval, n, n_factors);
1490 show_scree (const struct cmd_factor *f, const struct idata *idata)
1495 if (!(f->plot & PLOT_SCREE))
1499 label = f->extraction == EXTRACTION_PC ? _("Component Number") : _("Factor Number");
1501 s = scree_create (idata->eval, label);
1507 show_communalities (const struct cmd_factor * factor,
1508 const gsl_vector *initial, const gsl_vector *extracted)
1510 if (!(factor->print & (PRINT_INITIAL | PRINT_EXTRACTION)))
1513 struct pivot_table *table = pivot_table_create (N_("Communalities"));
1515 struct pivot_dimension *communalities = pivot_dimension_create (
1516 table, PIVOT_AXIS_COLUMN, N_("Communalities"));
1517 if (factor->print & PRINT_INITIAL)
1518 pivot_category_create_leaves (communalities->root, N_("Initial"));
1519 if (factor->print & PRINT_EXTRACTION)
1520 pivot_category_create_leaves (communalities->root, N_("Extraction"));
1522 struct pivot_dimension *variables = pivot_dimension_create (
1523 table, PIVOT_AXIS_ROW, N_("Variables"));
1525 for (size_t i = 0; i < factor->n_vars; ++i)
1527 int row = pivot_category_create_leaf (
1528 variables->root, pivot_value_new_variable (factor->vars[i]));
1531 if (factor->print & PRINT_INITIAL)
1532 pivot_table_put2 (table, col++, row, pivot_value_new_number (
1533 gsl_vector_get (initial, i)));
1534 if (factor->print & PRINT_EXTRACTION)
1535 pivot_table_put2 (table, col++, row, pivot_value_new_number (
1536 gsl_vector_get (extracted, i)));
1539 pivot_table_submit (table);
1542 static struct pivot_dimension *
1543 create_numeric_dimension (struct pivot_table *table,
1544 enum pivot_axis_type axis_type, const char *name,
1545 size_t n, bool show_label)
1547 struct pivot_dimension *d = pivot_dimension_create (table, axis_type, name);
1548 d->root->show_label = show_label;
1549 for (int i = 0; i < n; ++i)
1550 pivot_category_create_leaf (d->root, pivot_value_new_integer (i + 1));
1555 show_factor_matrix (const struct cmd_factor *factor, const struct idata *idata, const char *title, const gsl_matrix *fm)
1557 struct pivot_table *table = pivot_table_create (title);
1559 const int n_factors = idata->n_extractions;
1560 create_numeric_dimension (
1561 table, PIVOT_AXIS_COLUMN,
1562 factor->extraction == EXTRACTION_PC ? N_("Component") : N_("Factor"),
1565 struct pivot_dimension *variables = pivot_dimension_create (
1566 table, PIVOT_AXIS_ROW, N_("Variables"));
1568 /* Initialise to the identity permutation */
1569 gsl_permutation *perm = gsl_permutation_calloc (factor->n_vars);
1572 sort_matrix_indirect (fm, perm);
1574 for (size_t i = 0; i < factor->n_vars; ++i)
1576 const int matrix_row = perm->data[i];
1578 int var_idx = pivot_category_create_leaf (
1579 variables->root, pivot_value_new_variable (factor->vars[matrix_row]));
1581 for (size_t j = 0; j < n_factors; ++j)
1583 double x = gsl_matrix_get (fm, matrix_row, j);
1584 if (fabs (x) < factor->blank)
1587 pivot_table_put2 (table, j, var_idx, pivot_value_new_number (x));
1591 gsl_permutation_free (perm);
1593 pivot_table_submit (table);
1597 put_variance (struct pivot_table *table, int row, int phase_idx,
1598 double lambda, double percent, double cum)
1600 double entries[] = { lambda, percent, cum };
1601 for (size_t i = 0; i < sizeof entries / sizeof *entries; i++)
1602 pivot_table_put3 (table, i, phase_idx, row,
1603 pivot_value_new_number (entries[i]));
1607 show_explained_variance (const struct cmd_factor * factor,
1608 const struct idata *idata,
1609 const gsl_vector *initial_eigenvalues,
1610 const gsl_vector *extracted_eigenvalues,
1611 const gsl_vector *rotated_loadings)
1613 if (!(factor->print & (PRINT_INITIAL | PRINT_EXTRACTION | PRINT_ROTATION)))
1616 struct pivot_table *table = pivot_table_create (
1617 N_("Total Variance Explained"));
1619 pivot_dimension_create (table, PIVOT_AXIS_COLUMN, N_("Statistics"),
1620 N_("Total"), PIVOT_RC_OTHER,
1621 /* xgettext:no-c-format */
1622 N_("% of Variance"), PIVOT_RC_PERCENT,
1623 /* xgettext:no-c-format */
1624 N_("Cumulative %"), PIVOT_RC_PERCENT);
1626 struct pivot_dimension *phase = pivot_dimension_create (
1627 table, PIVOT_AXIS_COLUMN, N_("Phase"));
1628 if (factor->print & PRINT_INITIAL)
1629 pivot_category_create_leaves (phase->root, N_("Initial Eigenvalues"));
1631 if (factor->print & PRINT_EXTRACTION)
1632 pivot_category_create_leaves (phase->root,
1633 N_("Extraction Sums of Squared Loadings"));
1635 if (factor->print & PRINT_ROTATION)
1636 pivot_category_create_leaves (phase->root,
1637 N_("Rotation Sums of Squared Loadings"));
1639 struct pivot_dimension *components = pivot_dimension_create (
1640 table, PIVOT_AXIS_ROW,
1641 factor->extraction == EXTRACTION_PC ? N_("Component") : N_("Factor"));
1643 double i_total = 0.0;
1644 for (size_t i = 0; i < initial_eigenvalues->size; ++i)
1645 i_total += gsl_vector_get (initial_eigenvalues, i);
1647 double e_total = (factor->extraction == EXTRACTION_PAF
1654 for (size_t i = 0; i < factor->n_vars; ++i)
1656 const double i_lambda = gsl_vector_get (initial_eigenvalues, i);
1657 double i_percent = 100.0 * i_lambda / i_total;
1660 const double e_lambda = gsl_vector_get (extracted_eigenvalues, i);
1661 double e_percent = 100.0 * e_lambda / e_total;
1664 int row = pivot_category_create_leaf (
1665 components->root, pivot_value_new_integer (i + 1));
1669 /* Initial Eigenvalues */
1670 if (factor->print & PRINT_INITIAL)
1671 put_variance (table, row, phase_idx++, i_lambda, i_percent, i_cum);
1673 if (i < idata->n_extractions)
1675 if (factor->print & PRINT_EXTRACTION)
1676 put_variance (table, row, phase_idx++, e_lambda, e_percent, e_cum);
1678 if (rotated_loadings != NULL && factor->print & PRINT_ROTATION)
1680 double r_lambda = gsl_vector_get (rotated_loadings, i);
1681 double r_percent = 100.0 * r_lambda / e_total;
1682 if (factor->rotation == ROT_PROMAX)
1683 r_lambda = r_percent = SYSMIS;
1686 put_variance (table, row, phase_idx++, r_lambda, r_percent,
1692 pivot_table_submit (table);
1696 show_factor_correlation (const struct cmd_factor * factor, const gsl_matrix *fcm)
1698 struct pivot_table *table = pivot_table_create (
1699 N_("Factor Correlation Matrix"));
1701 create_numeric_dimension (
1702 table, PIVOT_AXIS_ROW,
1703 factor->extraction == EXTRACTION_PC ? N_("Component") : N_("Factor"),
1706 create_numeric_dimension (table, PIVOT_AXIS_COLUMN, N_("Factor 2"),
1709 for (size_t i = 0; i < fcm->size1; ++i)
1710 for (size_t j = 0; j < fcm->size2; ++j)
1711 pivot_table_put2 (table, j, i,
1712 pivot_value_new_number (gsl_matrix_get (fcm, i, j)));
1714 pivot_table_submit (table);
1718 add_var_dims (struct pivot_table *table, const struct cmd_factor *factor)
1720 for (int i = 0; i < 2; i++)
1722 struct pivot_dimension *d = pivot_dimension_create (
1723 table, i ? PIVOT_AXIS_ROW : PIVOT_AXIS_COLUMN,
1726 for (size_t j = 0; j < factor->n_vars; j++)
1727 pivot_category_create_leaf (
1728 d->root, pivot_value_new_variable (factor->vars[j]));
1733 show_aic (const struct cmd_factor *factor, const struct idata *idata)
1735 if ((factor->print & PRINT_AIC) == 0)
1738 struct pivot_table *table = pivot_table_create (N_("Anti-Image Matrices"));
1740 add_var_dims (table, factor);
1742 pivot_dimension_create (table, PIVOT_AXIS_ROW, N_("Statistics"),
1743 N_("Anti-image Covariance"),
1744 N_("Anti-image Correlation"));
1746 for (size_t i = 0; i < factor->n_vars; ++i)
1747 for (size_t j = 0; j < factor->n_vars; ++j)
1749 double cov = gsl_matrix_get (idata->ai_cov, i, j);
1750 pivot_table_put3 (table, i, j, 0, pivot_value_new_number (cov));
1752 double corr = gsl_matrix_get (idata->ai_cor, i, j);
1753 pivot_table_put3 (table, i, j, 1, pivot_value_new_number (corr));
1756 pivot_table_submit (table);
1760 show_correlation_matrix (const struct cmd_factor *factor, const struct idata *idata)
1762 if (!(factor->print & (PRINT_CORRELATION | PRINT_SIG | PRINT_DETERMINANT)))
1765 struct pivot_table *table = pivot_table_create (N_("Correlation Matrix"));
1767 if (factor->print & (PRINT_CORRELATION | PRINT_SIG))
1769 add_var_dims (table, factor);
1771 struct pivot_dimension *statistics = pivot_dimension_create (
1772 table, PIVOT_AXIS_ROW, N_("Statistics"));
1773 if (factor->print & PRINT_CORRELATION)
1774 pivot_category_create_leaves (statistics->root, N_("Correlation"),
1775 PIVOT_RC_CORRELATION);
1776 if (factor->print & PRINT_SIG)
1777 pivot_category_create_leaves (statistics->root, N_("Sig. (1-tailed)"),
1778 PIVOT_RC_SIGNIFICANCE);
1781 if (factor->print & PRINT_CORRELATION)
1783 for (int i = 0; i < factor->n_vars; ++i)
1784 for (int j = 0; j < factor->n_vars; ++j)
1786 double corr = gsl_matrix_get (idata->mm.corr, i, j);
1787 pivot_table_put3 (table, j, i, stat_idx,
1788 pivot_value_new_number (corr));
1793 if (factor->print & PRINT_SIG)
1795 for (int i = 0; i < factor->n_vars; ++i)
1796 for (int j = 0; j < factor->n_vars; ++j)
1799 double rho = gsl_matrix_get (idata->mm.corr, i, j);
1800 double w = gsl_matrix_get (idata->mm.n, i, j);
1801 double sig = significance_of_correlation (rho, w);
1802 pivot_table_put3 (table, j, i, stat_idx,
1803 pivot_value_new_number (sig));
1809 if (factor->print & PRINT_DETERMINANT)
1811 struct pivot_value *caption = pivot_value_new_user_text_nocopy (
1812 xasprintf ("%s: %.2f", _("Determinant"), idata->detR));
1813 pivot_table_set_caption (table, caption);
1816 pivot_table_submit (table);
1820 show_covariance_matrix (const struct cmd_factor *factor, const struct idata *idata)
1822 if (!(factor->print & PRINT_COVARIANCE))
1825 struct pivot_table *table = pivot_table_create (N_("Covariance Matrix"));
1826 add_var_dims (table, factor);
1828 for (int i = 0; i < factor->n_vars; ++i)
1829 for (int j = 0; j < factor->n_vars; ++j)
1831 double cov = gsl_matrix_get (idata->mm.cov, i, j);
1832 pivot_table_put2 (table, j, i, pivot_value_new_number (cov));
1835 pivot_table_submit (table);
1840 do_factor (const struct cmd_factor *factor, struct casereader *r)
1843 struct idata *idata = idata_alloc (factor->n_vars);
1845 idata->cvm = covariance_1pass_create (factor->n_vars, factor->vars,
1846 factor->wv, factor->exclude, true);
1848 for (; (c = casereader_read (r)); case_unref (c))
1850 covariance_accumulate (idata->cvm, c);
1853 idata->mm.cov = covariance_calculate (idata->cvm);
1855 if (idata->mm.cov == NULL)
1857 msg (MW, _("The dataset contains no complete observations. No analysis will be performed."));
1858 covariance_destroy (idata->cvm);
1862 idata->mm.var_matrix = covariance_moments (idata->cvm, MOMENT_VARIANCE);
1863 idata->mm.mean_matrix = covariance_moments (idata->cvm, MOMENT_MEAN);
1864 idata->mm.n = covariance_moments (idata->cvm, MOMENT_NONE);
1866 do_factor_by_matrix (factor, idata);
1869 gsl_matrix_free (idata->mm.corr);
1870 gsl_matrix_free (idata->mm.cov);
1873 casereader_destroy (r);
1877 do_factor_by_matrix (const struct cmd_factor *factor, struct idata *idata)
1879 if (!idata->mm.cov && !(idata->mm.corr && idata->mm.var_matrix))
1881 msg (ME, _("The dataset has no covariance matrix or a "
1882 "correlation matrix along with standard deviations."));
1886 if (idata->mm.cov && !idata->mm.corr)
1887 idata->mm.corr = correlation_from_covariance (idata->mm.cov, idata->mm.var_matrix);
1888 if (idata->mm.corr && !idata->mm.cov)
1889 idata->mm.cov = covariance_from_correlation (idata->mm.corr, idata->mm.var_matrix);
1890 if (factor->method == METHOD_CORR)
1891 idata->analysis_matrix = idata->mm.corr;
1893 idata->analysis_matrix = idata->mm.cov;
1896 r_inv = clone_matrix (idata->mm.corr);
1897 gsl_linalg_cholesky_decomp (r_inv);
1898 gsl_linalg_cholesky_invert (r_inv);
1900 idata->ai_cov = anti_image_cov (r_inv);
1901 idata->ai_cor = anti_image_corr (r_inv, idata);
1903 double sum_ssq_r = 0;
1904 double sum_ssq_a = 0;
1905 for (int i = 0; i < r_inv->size1; ++i)
1907 sum_ssq_r += ssq_od_n (idata->mm.corr, i);
1908 sum_ssq_a += ssq_od_n (idata->ai_cor, i);
1911 gsl_matrix_free (r_inv);
1913 if (factor->print & PRINT_DETERMINANT
1914 || factor->print & PRINT_KMO)
1918 const int size = idata->mm.corr->size1;
1919 gsl_permutation *p = gsl_permutation_calloc (size);
1920 gsl_matrix *tmp = gsl_matrix_calloc (size, size);
1921 gsl_matrix_memcpy (tmp, idata->mm.corr);
1923 gsl_linalg_LU_decomp (tmp, p, &sign);
1924 idata->detR = gsl_linalg_LU_det (tmp, sign);
1925 gsl_permutation_free (p);
1926 gsl_matrix_free (tmp);
1929 if (factor->print & PRINT_UNIVARIATE
1930 && idata->mm.n && idata->mm.mean_matrix && idata->mm.var_matrix)
1932 struct pivot_table *table = pivot_table_create (
1933 N_("Descriptive Statistics"));
1934 pivot_table_set_weight_var (table, factor->wv);
1936 pivot_dimension_create (table, PIVOT_AXIS_COLUMN, N_("Statistics"),
1937 N_("Mean"), PIVOT_RC_OTHER,
1938 N_("Std. Deviation"), PIVOT_RC_OTHER,
1939 N_("Analysis N"), PIVOT_RC_COUNT);
1941 struct pivot_dimension *variables = pivot_dimension_create (
1942 table, PIVOT_AXIS_ROW, N_("Variables"));
1944 for (size_t i = 0; i < factor->n_vars; ++i)
1946 const struct variable *v = factor->vars[i];
1948 int row = pivot_category_create_leaf (
1949 variables->root, pivot_value_new_variable (v));
1951 double entries[] = {
1952 gsl_matrix_get (idata->mm.mean_matrix, i, i),
1953 sqrt (gsl_matrix_get (idata->mm.var_matrix, i, i)),
1954 gsl_matrix_get (idata->mm.n, i, i),
1956 for (size_t j = 0; j < sizeof entries / sizeof *entries; j++)
1957 pivot_table_put2 (table, j, row,
1958 pivot_value_new_number (entries[j]));
1961 pivot_table_submit (table);
1964 if (factor->print & PRINT_KMO && idata->mm.n)
1966 struct pivot_table *table = pivot_table_create (
1967 N_("KMO and Bartlett's Test"));
1969 struct pivot_dimension *statistics = pivot_dimension_create (
1970 table, PIVOT_AXIS_ROW, N_("Statistics"),
1971 N_("Kaiser-Meyer-Olkin Measure of Sampling Adequacy"), PIVOT_RC_OTHER);
1972 pivot_category_create_group (
1973 statistics->root, N_("Bartlett's Test of Sphericity"),
1974 N_("Approx. Chi-Square"), PIVOT_RC_OTHER,
1975 N_("df"), PIVOT_RC_INTEGER,
1976 N_("Sig."), PIVOT_RC_SIGNIFICANCE);
1978 /* The literature doesn't say what to do for the value of W when
1979 missing values are involved. The best thing I can think of
1980 is to take the mean average. */
1982 for (int i = 0; i < idata->mm.n->size1; ++i)
1983 w += gsl_matrix_get (idata->mm.n, i, i);
1984 w /= idata->mm.n->size1;
1986 double xsq = ((w - 1 - (2 * factor->n_vars + 5) / 6.0)
1987 * -log (idata->detR));
1988 double df = factor->n_vars * (factor->n_vars - 1) / 2;
1989 double entries[] = {
1990 sum_ssq_r / (sum_ssq_r + sum_ssq_a),
1993 gsl_cdf_chisq_Q (xsq, df)
1995 for (size_t i = 0; i < sizeof entries / sizeof *entries; i++)
1996 pivot_table_put1 (table, i, pivot_value_new_number (entries[i]));
1998 pivot_table_submit (table);
2001 show_correlation_matrix (factor, idata);
2002 show_covariance_matrix (factor, idata);
2004 covariance_destroy (idata->cvm);
2007 gsl_matrix *am = matrix_dup (idata->analysis_matrix);
2008 gsl_eigen_symmv_workspace *workspace = gsl_eigen_symmv_alloc (factor->n_vars);
2010 gsl_eigen_symmv (am, idata->eval, idata->evec, workspace);
2012 gsl_eigen_symmv_free (workspace);
2013 gsl_matrix_free (am);
2016 gsl_eigen_symmv_sort (idata->eval, idata->evec, GSL_EIGEN_SORT_ABS_DESC);
2018 idata->n_extractions = n_extracted_factors (factor, idata);
2020 if (idata->n_extractions == 0)
2022 msg (MW, _("The %s criteria result in zero factors extracted. Therefore no analysis will be performed."), "FACTOR");
2026 if (idata->n_extractions > factor->n_vars)
2029 _("The %s criteria result in more factors than variables, which is not meaningful. No analysis will be performed."),
2035 gsl_matrix *rotated_factors = NULL;
2036 gsl_matrix *pattern_matrix = NULL;
2037 gsl_matrix *fcm = NULL;
2038 gsl_vector *rotated_loadings = NULL;
2040 const gsl_vector *extracted_eigenvalues = NULL;
2041 gsl_vector *initial_communalities = gsl_vector_alloc (factor->n_vars);
2042 gsl_vector *extracted_communalities = gsl_vector_alloc (factor->n_vars);
2043 struct factor_matrix_workspace *fmw = factor_matrix_workspace_alloc (idata->msr->size, idata->n_extractions);
2044 gsl_matrix *factor_matrix = gsl_matrix_calloc (factor->n_vars, fmw->n_factors);
2046 if (factor->extraction == EXTRACTION_PAF)
2048 gsl_vector *diff = gsl_vector_alloc (idata->msr->size);
2049 struct smr_workspace *ws = ws_create (idata->analysis_matrix);
2051 for (size_t i = 0; i < factor->n_vars; ++i)
2053 double r2 = squared_multiple_correlation (idata->analysis_matrix, i, ws);
2055 gsl_vector_set (idata->msr, i, r2);
2059 gsl_vector_memcpy (initial_communalities, idata->msr);
2061 for (size_t i = 0; i < factor->extraction_iterations; ++i)
2064 gsl_vector_memcpy (diff, idata->msr);
2066 iterate_factor_matrix (idata->analysis_matrix, idata->msr, factor_matrix, fmw);
2068 gsl_vector_sub (diff, idata->msr);
2070 gsl_vector_minmax (diff, &min, &max);
2072 if (fabs (min) < factor->econverge && fabs (max) < factor->econverge)
2075 gsl_vector_free (diff);
2079 gsl_vector_memcpy (extracted_communalities, idata->msr);
2080 extracted_eigenvalues = fmw->eval;
2082 else if (factor->extraction == EXTRACTION_PC)
2084 for (size_t i = 0; i < factor->n_vars; ++i)
2085 gsl_vector_set (initial_communalities, i, communality (idata, i, factor->n_vars));
2087 gsl_vector_memcpy (extracted_communalities, initial_communalities);
2089 iterate_factor_matrix (idata->analysis_matrix, extracted_communalities, factor_matrix, fmw);
2092 extracted_eigenvalues = idata->eval;
2096 show_aic (factor, idata);
2097 show_communalities (factor, initial_communalities, extracted_communalities);
2099 if (factor->rotation != ROT_NONE)
2101 rotated_factors = gsl_matrix_calloc (factor_matrix->size1, factor_matrix->size2);
2102 rotated_loadings = gsl_vector_calloc (factor_matrix->size2);
2103 if (factor->rotation == ROT_PROMAX)
2105 pattern_matrix = gsl_matrix_calloc (factor_matrix->size1, factor_matrix->size2);
2106 fcm = gsl_matrix_calloc (factor_matrix->size2, factor_matrix->size2);
2110 rotate (factor, factor_matrix, extracted_communalities, rotated_factors, rotated_loadings, pattern_matrix, fcm);
2113 show_explained_variance (factor, idata, idata->eval, extracted_eigenvalues, rotated_loadings);
2115 factor_matrix_workspace_free (fmw);
2117 show_scree (factor, idata);
2119 show_factor_matrix (factor, idata,
2120 (factor->extraction == EXTRACTION_PC
2121 ? N_("Component Matrix") : N_("Factor Matrix")),
2124 if (factor->rotation == ROT_PROMAX)
2126 show_factor_matrix (factor, idata, N_("Pattern Matrix"),
2128 gsl_matrix_free (pattern_matrix);
2131 if (factor->rotation != ROT_NONE)
2133 show_factor_matrix (factor, idata,
2134 (factor->rotation == ROT_PROMAX
2135 ? N_("Structure Matrix")
2136 : factor->extraction == EXTRACTION_PC
2137 ? N_("Rotated Component Matrix")
2138 : N_("Rotated Factor Matrix")),
2141 gsl_matrix_free (rotated_factors);
2144 if (factor->rotation == ROT_PROMAX)
2146 show_factor_correlation (factor, fcm);
2147 gsl_matrix_free (fcm);
2150 gsl_matrix_free (factor_matrix);
2151 gsl_vector_free (rotated_loadings);
2152 gsl_vector_free (initial_communalities);
2153 gsl_vector_free (extracted_communalities);