| 1 | /* ICA.cpp |
| 2 | * |
| 3 | * Copyright (C) 2010-2023, 2026 David Weenink |
| 4 | * |
| 5 | * This code 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 2 of the License, or (at |
| 8 | * your option) any later version. |
| 9 | * |
| 10 | * This code is distributed in the hope that it will be useful, but |
| 11 | * WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 13 | * General Public License for more details. |
| 14 | * |
| 15 | * You should have received a copy of the GNU General Public License |
| 16 | * along with this work. If not, see <http://www.gnu.org/licenses/>. |
| 17 | */ |
| 18 | |
| 19 | /* |
| 20 | djmw 20101202 Initial version |
| 21 | djmw 20110304 Thing_new |
| 22 | */ |
| 23 | |
| 24 | #include "ICA.h" |
| 25 | #include "Interpreter.h" |
| 26 | #include "NUM2.h" |
| 27 | #include "Sound_and_PCA.h" |
| 28 | #include "SVD.h" |
| 29 | |
| 30 | //TODO 20181013 massive cleanups only at pointers removed rest follows |
| 31 | // matrix multiply R = V*C*V', V is nrv x ncv, C is ncv x ncv, R is nrv x nrv |
| 32 | static void MATmul_VCVt_preallocated (MAT r, constMAT v, constMAT c, bool csym) { |
| 33 | Melder_assert (r.nrow == r.ncol); |
| 34 | Melder_assert (v.nrow == r.ncol); |
| 35 | Melder_assert (c.nrow == c.ncol); |
| 36 | Melder_assert (v.ncol == c.ncol); |
| 37 | for (integer i = 1; i <= r.nrow; i ++) { |
| 38 | const integer jstart = ( csym ? i : 1 ); |
| 39 | for (integer j = jstart; j <= r.nrow; j ++) { |
| 40 | // V_ik C_kl V'_lj = V_ik C_kl V_jl |
| 41 | longdouble vcv = 0.0; |
| 42 | for (integer k = 1; k <= c.nrow; k ++) { |
| 43 | for (integer l = 1; l <= c.nrow; l ++) { |
| 44 | vcv += v [i] [k] * c [k] [l] * v [j] [l]; |
| 45 | } |
| 46 | } |
| 47 | r [i] [j] = vcv; |
| 48 | if (csym) |
| 49 | r [j] [i] = vcv; |
| 50 | } |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | // D += scalef * M * M', M = nrm x ncm, D is nrm x nrm |
| 55 | static void multiplyScaleAdd_preallocated (MAT r, constMAT m, double scalef) { |
| 56 | Melder_assert (r.nrow == r.ncol && r.nrow == m.nrow); |
| 57 | for (integer i = 1; i <= r.nrow; i ++) { |
| 58 | for (integer j = 1; j <= r.nrow; j ++) |
| 59 | r [i] [j] += scalef * NUMinner (m.row (i), m.row (j)); // M_ik M'_kj = M_ik M_jk |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | /* |
| 64 | d = diag(diag(W'*C0*W)); |
| 65 | W = W*d^(-1/2); |
| 66 | |
| 67 | D_ij = W'_ik C_kl W_lj => D_ii = W_ki C_kl W_li |
| 68 | */ |
| 69 | static void normalizeColumnVectors (MAT w, MAT c) { // TODO |
| 70 | Melder_assert (w.nrow == c.ncol && w.ncol == c.nrow); |
| 71 | for (integer i = 1; i <= w.ncol; i ++) { |
| 72 | longdouble di = 0.0; |
| 73 | for (integer k = 1; k <= w.ncol; k ++) |
| 74 | for (integer l = 1; l <= w.nrow; l ++) { |
| 75 | di += w [k] [i] * c [k] [l] * w [l] [i]; |
| 76 | } |
| 77 | di = 1.0 / sqrt (di); |
| 78 | for (integer j = 1; j <= w.nrow; j ++) { |
| 79 | w [j] [i] *= di; |
| 80 | } |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | static double diagonalityMeasure (MAT v) { |
| 85 | Melder_assert (v.nrow == v.ncol); |
| 86 | longdouble dmsq = 0.0; |
| 87 | if (v.nrow < 2) |
| 88 | return 0.0; |
| 89 | for (integer i = 1; i <= v.nrow; i ++) { |
| 90 | for (integer j = 1; j <= v.nrow; j ++) |
| 91 | if (i != j) |
| 92 | dmsq += v [i] [j] * v [i] [j]; |
| 93 | } |
| 94 | return (double) dmsq / (v.nrow * (v.nrow - 1)); |
| 95 | } |
| 96 | |
| 97 | /* |
| 98 | This routine is modelled after qdiag.m from Andreas Ziehe, Pavel Laskov, Guido Nolte, Klaus-Robert Müller, |
| 99 | A Fast Algorithm for Joint Diagonalization with Non-orthogonal Transformations and its Application to |
| 100 | Blind Source Separation, Journal of Machine Learning Research 5 (2004), 777–800. |
| 101 | */ |
| 102 | static void Diagonalizer_CrossCorrelationTableList_ffdiag (Diagonalizer me, CrossCorrelationTableList thee, integer maxNumberOfIterations, double delta) { |
| 103 | try { |
| 104 | const integer dimension = my numberOfRows; |
| 105 | |
| 106 | autoCrossCorrelationTableList ccts = CrossCorrelationTableList_Diagonalizer_diagonalize (thee, me); |
| 107 | autoMAT w = zero_MAT (dimension, dimension); |
| 108 | autoMAT vnew = zero_MAT (dimension, dimension); |
| 109 | autoMAT cc = zero_MAT (dimension, dimension); |
| 110 | |
| 111 | for (integer i = 1; i <= dimension; i ++) |
| 112 | w [i] [i] = 1.0; |
| 113 | |
| 114 | autoMelderProgress progress (U"Simultaneous diagonalization of many CrossCorrelationTables..."); |
| 115 | double dm_new = CrossCorrelationTableList_getDiagonalityMeasure (ccts.get(), nullptr, 0, 0); |
| 116 | integer iter = 0; |
| 117 | try { |
| 118 | const double theta = 1.0; |
| 119 | double dm_old, dm_start = dm_new; |
| 120 | do { |
| 121 | dm_old = dm_new; |
| 122 | for (integer i = 1; i <= dimension; i ++) { |
| 123 | for (integer j = i + 1; j <= dimension; j ++) { |
| 124 | longdouble zii = 0.0, zij = 0.0, zjj = 0.0, yij = 0.0, yji = 0.0; // zij == zji |
| 125 | for (integer k = 1; k <= ccts->size; k ++) { |
| 126 | CrossCorrelationTable ct = ccts -> at [k]; |
| 127 | zii += ct -> data [i] [i] * ct -> data [i] [i]; |
| 128 | zij += ct -> data [i] [i] * ct -> data [j] [j]; |
| 129 | zjj += ct -> data [j] [j] * ct -> data [j] [j]; |
| 130 | yij += ct -> data [j] [j] * ct -> data [i] [j]; |
| 131 | yji += ct -> data [i] [i] * ct -> data [i] [j]; |
| 132 | } |
| 133 | const longdouble denom = zjj * zii - zij * zij; |
| 134 | if (denom != 0.0) { |
| 135 | w [i] [j] = double ((zij * yji - zii * yij) / denom); |
| 136 | w [j] [i] = double ((zij * yij - zjj * yji) / denom); |
| 137 | } else { |
| 138 | // ppgb: prove that the result is valid |
| 139 | } |
| 140 | } |
| 141 | } |
| 142 | longdouble norma = 0.0; |
| 143 | for (integer i = 1; i <= dimension; i ++) { |
| 144 | longdouble normai = 0.0; |
| 145 | for (integer j = 1; j <= dimension; j ++) { |
| 146 | if (i != j) |
| 147 | normai += fabs (w [i] [j]); |
| 148 | } |
| 149 | if (normai > norma) |
| 150 | norma = normai; |
| 151 | } |
| 152 | // evaluate the norm |
| 153 | if (norma > theta) { |
| 154 | longdouble normf = 0.0; |
| 155 | for (integer i = 1; i <= dimension; i ++) |
| 156 | for (integer j = 1; j <= dimension; j ++) |
| 157 | if (i != j) |
| 158 | normf += w [i] [j] * w [i] [j]; |
| 159 | const longdouble scalef = theta / sqrt (normf); |
| 160 | for (integer i = 1; i <= dimension; i ++) |
| 161 | for (integer j = 1; j <= dimension; j ++) |
| 162 | if (i != j) |
| 163 | w [i] [j] *= scalef; |
| 164 | } |
| 165 | // update V |
| 166 | vnew.all() <<= my data.all(); |
| 167 | mul_MAT_out (my data.get(), w.get(), vnew.get()); |
| 168 | for (integer k = 1; k <= ccts->size; k ++) { |
| 169 | const CrossCorrelationTable ct = ccts->at [k]; |
| 170 | Melder_assert (ct -> data.nrow == dimension && ct -> data.ncol == dimension); // ppgb 20180913 |
| 171 | cc.all() <<= ct -> data.all(); |
| 172 | MATmul_VCVt_preallocated (ct -> data.get(), w.get(), cc.get(), true); |
| 173 | } |
| 174 | dm_new = CrossCorrelationTableList_getDiagonalityMeasure (ccts.get(), nullptr, 0, 0); |
| 175 | iter ++; |
| 176 | Melder_progress ((double) iter / (double) maxNumberOfIterations, U"Iteration: ", iter, U", measure: ", |
| 177 | (double) dm_new, U"\n fractional measure: ", (double)(dm_new / dm_start)); |
| 178 | } while (fabs (dm_old - dm_new) > std::max (fabs (delta * dm_new), NUMeps) && iter < maxNumberOfIterations); |
| 179 | } catch (MelderError) { |
| 180 | Melder_clearError (); |
| 181 | } |
| 182 | } catch (MelderError) { |
| 183 | Melder_throw (me, U" & ", thee, U": no joint diagonalization (ffdiag)."); |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | /* |
| 188 | The following two routines are modelled after qdiag.m from |
| 189 | R. Vollgraf and K. Obermayer, Quadratic Optimization for Simultaneous |
| 190 | Matrix Diagonalization, IEEE Transaction on Signal Processing, 2006, |
| 191 | */ |
| 192 | static void update_one_column (CrossCorrelationTableList me, MAT d, constVEC wp, constVEC wvec, double scalef, VEC work) { |
| 193 | integer dimension = my at [1] -> numberOfColumns; |
| 194 | |
| 195 | for (integer ic = 2; ic <= my size; ic ++) { // exclude C0 |
| 196 | const SSCP cov = my at [ic]; |
| 197 | // m1 = C * wvec |
| 198 | mul_VEC_out (work, cov -> data.get(), wvec); |
| 199 | // D = D +/- 2*p(t)*(m1*m1'); |
| 200 | for (integer i = 1; i <= dimension; i ++) { |
| 201 | for (integer j = 1; j <= dimension; j ++) { |
| 202 | d [i] [j] += 2.0 * scalef * wp [ic] * work [i] * work [j]; |
| 203 | } |
| 204 | } |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | static void Diagonalizer_CrossCorrelationTable_qdiag (Diagonalizer me, CrossCorrelationTableList thee, VEC cweights, integer maxNumberOfIterations, double delta) { |
| 209 | try { |
| 210 | const CrossCorrelationTable c0 = thy at [1]; |
| 211 | const integer dimension = c0 -> numberOfColumns; |
| 212 | |
| 213 | autoEigen eigen = Eigen_createFromSquareMAT (c0 -> data.get(), kMAT_TYPE::SYMMETRIC, dimension, false); |
| 214 | autoCrossCorrelationTableList ccts = Data_copy (thee); |
| 215 | autoMAT d = zero_MAT (dimension, dimension); |
| 216 | autoMAT pinv = raw_MAT (dimension, dimension); |
| 217 | autoMAT p = zero_MAT (dimension, dimension); |
| 218 | autoMAT m1 = zero_MAT (dimension, dimension); |
| 219 | autoVEC wvec = raw_VEC (dimension); |
| 220 | autoVEC wnew = raw_VEC (dimension); |
| 221 | autoVEC mvec = zero_VEC (dimension); |
| 222 | |
| 223 | autoMAT wc = transpose_MAT (my data.get()); |
| 224 | |
| 225 | // d = diag(diag(W'*C0*W)); |
| 226 | // W = W*d^(-1/2); |
| 227 | |
| 228 | normalizeColumnVectors (wc.get(), c0 -> data.get()); |
| 229 | |
| 230 | // scale eigenvectors for sphering |
| 231 | // [vb,db] = eig(C0); |
| 232 | // P = db^(-1/2)*vb'; |
| 233 | |
| 234 | for (integer i = 1; i <= dimension; i ++) { |
| 235 | Melder_require (eigen -> eigenvalues [i] >= 0.0, |
| 236 | U"Covariance matrix should be positive definite. Eigenvalue [", i, U"] is negative."); |
| 237 | const double scalef = 1.0 / sqrt (eigen -> eigenvalues [i]); |
| 238 | p.row (dimension - i + 1) <<= eigen -> eigenvectors.row (i) * scalef; |
| 239 | } |
| 240 | |
| 241 | // P*C [i]*P' |
| 242 | |
| 243 | for (integer ic = 1; ic <= thy size; ic ++) { |
| 244 | const CrossCorrelationTable cov1 = thy at [ic]; |
| 245 | const CrossCorrelationTable cov2 = ccts -> at [ic]; |
| 246 | MATmul_VCVt_preallocated (cov2 -> data.get(), p.get(), cov1 -> data.get(), true); |
| 247 | } |
| 248 | |
| 249 | // W = P'\W == inv(P') * W |
| 250 | |
| 251 | MATpseudoInverse (pinv.get (), p.get(), 0.0); |
| 252 | mul_MAT_out (my data.get(), pinv.transpose(), wc.get()); |
| 253 | |
| 254 | // initialisation for order KN^3 |
| 255 | |
| 256 | for (integer ic = 2; ic <= thy size; ic ++) { |
| 257 | const CrossCorrelationTable cov = ccts -> at [ic]; |
| 258 | // C * W |
| 259 | mul_MAT_out (m1.get(), cov -> data.get(), my data.get()); |
| 260 | // D += scalef * M1*M1' |
| 261 | multiplyScaleAdd_preallocated (d.get(), m1.get(), 2.0 * cweights [ic]); |
| 262 | } |
| 263 | |
| 264 | integer iter = 0; |
| 265 | double delta_w; |
| 266 | |
| 267 | autoMelderProgress progress (U"Simultaneous diagonalization of many CrossCorrelationTables..."); |
| 268 | try { |
| 269 | do { |
| 270 | // the standard diagonality measure is rather expensive to calculate so we compare the norms of |
| 271 | // differences of eigenvectors. |
| 272 | |
| 273 | delta_w = 0.0; |
| 274 | for (integer kol = 1; kol <= dimension; kol ++) { |
| 275 | wvec.all() <<= my data.column (kol); |
| 276 | |
| 277 | update_one_column (ccts.get(), d.get(), cweights, wvec.get(), -1.0, mvec.get()); |
| 278 | |
| 279 | MAT_into_Eigen (d.get(), kMAT_TYPE::SYMMETRIC, eigen.get(), false); |
| 280 | |
| 281 | // Eigenvalues sorted from high to low; get eigenvector of smallest ! |
| 282 | wnew.all() <<= eigen -> eigenvectors.row (dimension); |
| 283 | |
| 284 | update_one_column (ccts.get(), d.get(), cweights, wnew.get(), 1.0, mvec.get()); |
| 285 | my data.column (kol) <<= wnew.all(); |
| 286 | |
| 287 | // compare norms of eigenvectors. We have to compare ||wvec +/- w_new|| because eigenvectors |
| 288 | // may change sign. |
| 289 | |
| 290 | double normp = 0.0, normm = 0.0; |
| 291 | for (integer j = 1; j <= dimension; j ++) { |
| 292 | const double dm = wvec [j] - wnew [j], dp = wvec [j] + wnew [j]; |
| 293 | normp += dm * dm; |
| 294 | normm += dp * dp; |
| 295 | } |
| 296 | |
| 297 | normp = std::min (normp, normm); |
| 298 | normp = sqrt (normp); |
| 299 | delta_w = std::max (normp, delta_w ); |
| 300 | } |
| 301 | iter ++; |
| 302 | |
| 303 | Melder_progress ((double) iter / (double) (maxNumberOfIterations + 1), U"Iteration: ", iter, U", norm: ", delta_w); |
| 304 | } while (delta_w > delta && iter < maxNumberOfIterations); |
| 305 | } catch (MelderError) { |
| 306 | Melder_clearError (); |
| 307 | } |
| 308 | |
| 309 | // Revert the sphering W = P'*W; |
| 310 | // Take transpose to make W*C [i]W' diagonal instead of W'*C [i]*W => (P'*W)'=W'*P |
| 311 | wc.all() <<= my data.all(); |
| 312 | mul_MAT_out (my data.get(), wc.transpose(), p.get()); // W = W'*P: final result |
| 313 | |
| 314 | // Calculate the "real" diagonality measure |
| 315 | // double dm = CrossCorrelationTableList_Diagonalizer_getDiagonalityMeasure (thee, me, cweights, 1, thy size); |
| 316 | |
| 317 | } catch (MelderError) { |
| 318 | Melder_throw (me, U" & ", thee, U": no joint diagonalization (qdiag)."); |
| 319 | } |
| 320 | } |
| 321 | |
| 322 | void MixingMatrix_CrossCorrelationTableList_improveUnmixing (MixingMatrix me, CrossCorrelationTableList thee, integer maxNumberOfIterations, double tol, int method) { |
| 323 | autoDiagonalizer him = MixingMatrix_to_Diagonalizer (me); |
| 324 | Diagonalizer_CrossCorrelationTableList_improveDiagonality (him.get(), thee, maxNumberOfIterations, tol, method); |
| 325 | MATpseudoInverse (my data.get(), his data.get(), 0); |
| 326 | } |
| 327 | |
| 328 | |
| 329 | /* Preconditions: |
| 330 | * x [1..nrows] [1..ncols], cc [1..nrows] [1..nrows], centroid [1..nrows] |
| 331 | * if (lag>0) {i2 + lag <= ncols} else {i1-lag >= 1} |
| 332 | * no array boundary checks! |
| 333 | * lag >= 0 |
| 334 | */ |
| 335 | static void NUMcrossCorrelate_rows (constMAT x, integer icol1, integer icol2, integer lag, MAT inout_cc, VEC inout_centroid, double scale) { |
| 336 | Melder_assert (inout_cc.nrow == inout_cc.ncol && inout_cc.nrow == x.nrow); |
| 337 | lag = integer_abs (lag); |
| 338 | const integer nsamples = icol2 - icol1 + 1 + lag; |
| 339 | Melder_require (nsamples > 0, |
| 340 | U"Not enough samples to perform cross-correlations."); |
| 341 | for (integer i = 1; i <= x.nrow; i ++) |
| 342 | inout_centroid [i] = NUMmean (x.row (i).part (icol1, icol2 + lag)); |
| 343 | |
| 344 | for (integer irow = 1; irow <= x.nrow; irow ++) { |
| 345 | for (integer icol = irow; icol <= x.nrow; icol ++) { |
| 346 | longdouble ccor = 0.0; |
| 347 | for (integer k = icol1; k <= icol2; k ++) |
| 348 | ccor += (x [irow] [k] - inout_centroid [irow]) * (x [icol] [k + lag] - inout_centroid [icol]); |
| 349 | inout_cc [icol] [irow] = inout_cc [irow] [icol] = ccor * scale; |
| 350 | } |
| 351 | } |
| 352 | } |
| 353 | |
| 354 | /* |
| 355 | This is for multi-channel "sounds" like EEG signals. |
| 356 | The cross-correlation between channel i and channel j is defined as |
| 357 | sum(k=1..nsamples, (z [i] [k] - mean [i])(z [j] [k + tau] - mean [j]))*samplingTime |
| 358 | */ |
| 359 | autoCrossCorrelationTable Sound_to_CrossCorrelationTable (Sound me, double startTime, double endTime, double lagStep) |
| 360 | { |
| 361 | try { |
| 362 | if (endTime <= startTime) { |
| 363 | startTime = my xmin; |
| 364 | endTime = my xmax; |
| 365 | } |
| 366 | const integer lag = Melder_iround (lagStep / my dx); |
| 367 | integer i1 = Sampled_xToNearestIndex (me, startTime); |
| 368 | Melder_clipLeft (1_integer, & i1); |
| 369 | |
| 370 | integer i2 = Sampled_xToNearestIndex (me, endTime); |
| 371 | Melder_clipRight (& i2, my nx); |
| 372 | |
| 373 | i2 -= lag; |
| 374 | const integer nsamples = i2 - i1 + 1; |
| 375 | |
| 376 | Melder_require (nsamples > my ny, |
| 377 | U"Not enough samples, choose a longer interval."); |
| 378 | |
| 379 | autoCrossCorrelationTable thee = CrossCorrelationTable_create (my ny); |
| 380 | |
| 381 | NUMcrossCorrelate_rows (my z.get(), i1, i2, lag, thy data.get(), thy centroid.get(), my dx); |
| 382 | |
| 383 | thy numberOfObservations = nsamples; |
| 384 | |
| 385 | return thee; |
| 386 | } catch (MelderError) { |
| 387 | Melder_throw (me, U": CrossCorrelationTable not created."); |
| 388 | } |
| 389 | } |
| 390 | |
| 391 | /* Calculate the CrossCorrelationTable between the channels of two multichannel sounds irrespective of the domains. |
| 392 | * Both sounds are treated as if their domain runs from 0 to duration. |
| 393 | * Outside the chosen interval the sounds are assumed to be zero |
| 394 | */ |
| 395 | autoCrossCorrelationTable Sounds_to_CrossCorrelationTable_combined (Sound me, Sound thee, |
| 396 | double relativeStartTime, double relativeEndTime, double lagStep) |
| 397 | { |
| 398 | try { |
| 399 | Melder_require (my dx == thy dx, |
| 400 | U"Sampling frequencies should be equal."); |
| 401 | if (relativeEndTime <= relativeStartTime) { |
| 402 | relativeStartTime = my xmin; |
| 403 | relativeEndTime = my xmax; |
| 404 | } |
| 405 | const integer lag = Melder_iround (lagStep / my dx), nchannels = my ny + thy ny; |
| 406 | integer i1 = Sampled_xToNearestIndex (me, relativeStartTime); |
| 407 | Melder_clipLeft (1_integer, & i1); |
| 408 | |
| 409 | integer i2 = Sampled_xToNearestIndex (me, relativeEndTime); |
| 410 | Melder_clipRight (& i2, my nx); |
| 411 | |
| 412 | i2 -= lag; |
| 413 | integer nsamples = i2 - i1 + 1; |
| 414 | Melder_require (nsamples > nchannels, U"Not enough samples"); |
| 415 | |
| 416 | autoCrossCorrelationTable him = CrossCorrelationTable_create (nchannels); |
| 417 | |
| 418 | autoVEC centroid1 = raw_VEC (my ny); |
| 419 | autoMAT x1x1 = raw_MAT (my ny, my ny); |
| 420 | NUMcrossCorrelate_rows (my z.get(), i1, i2, lag, x1x1.get(), centroid1.get(), my dx); |
| 421 | his centroid.part (1, my ny) <<= centroid1.all(); |
| 422 | for (integer irow = 1; irow <= my ny; irow ++) |
| 423 | his data.row (irow).part (1, my ny) <<= x1x1.row (irow); |
| 424 | |
| 425 | autoVEC centroid2 = raw_VEC (thy ny); |
| 426 | autoMAT x2x2 = raw_MAT (thy ny, thy ny); |
| 427 | NUMcrossCorrelate_rows (thy z.get(), i1, i2, lag, x2x2.get(), centroid2.get(), my dx); |
| 428 | his centroid.part (my ny + 1, nchannels) <<= centroid2.all(); |
| 429 | for (integer irow = 1; irow <= thy ny; irow ++) |
| 430 | his data.row (my ny + irow).part (my ny + 1, nchannels) <<= x2x2.row (irow); |
| 431 | |
| 432 | for (integer irow = 1; irow <= my ny; irow ++) { |
| 433 | for (integer icol = 1; icol <= thy ny; icol ++) { |
| 434 | longdouble ccor = 0.0; |
| 435 | for (integer k = i1; k <= i2; k ++) |
| 436 | ccor += (my z [irow] [k] - centroid1 [irow]) * (thy z [icol] [k + lag] - centroid2 [icol]); |
| 437 | his data [irow] [my ny + icol] = his data [my ny + icol] [irow] = ccor * my dx; |
| 438 | } |
| 439 | } |
| 440 | |
| 441 | his numberOfObservations = nsamples; |
| 442 | |
| 443 | return him; |
| 444 | } catch (MelderError) { |
| 445 | Melder_throw (me, U": CrossCorrelationTable not created."); |
| 446 | } |
| 447 | } |
| 448 | |
| 449 | autoCovariance Sound_to_Covariance_channels (Sound me, double startTime, double endTime) { |
| 450 | try { |
| 451 | const double lagStep = 0.0; |
| 452 | autoCrossCorrelationTable thee = Sound_to_CrossCorrelationTable (me, startTime, endTime, lagStep); |
| 453 | autoCovariance him = Thing_new (Covariance); |
| 454 | thy structCrossCorrelationTable :: v1_copy (him.get()); |
| 455 | return him; |
| 456 | } catch (MelderError) { |
| 457 | Melder_throw (me, U": no Covariance created."); |
| 458 | } |
| 459 | } |
| 460 | |
| 461 | autoCrossCorrelationTableList Sound_to_CrossCorrelationTableList (Sound me, |
| 462 | double startTime, double endTime, integer numberOfCrossCorrelations, double lagStep) |
| 463 | { |
| 464 | try { |
| 465 | Melder_clipLeft (my dx, & lagStep); |
| 466 | if (endTime <= startTime) { |
| 467 | startTime = my xmin; |
| 468 | endTime = my xmax; |
| 469 | } |
| 470 | Melder_require (startTime + numberOfCrossCorrelations * lagStep <= endTime, |
| 471 | U"Lag time is too large."); |
| 472 | |
| 473 | autoCrossCorrelationTableList thee = CrossCorrelationTableList_create (); |
| 474 | for (integer i = 1; i <= numberOfCrossCorrelations; i ++) { |
| 475 | const double lag = (i - 1) * lagStep; |
| 476 | autoCrossCorrelationTable ct = Sound_to_CrossCorrelationTable (me, startTime, endTime, lag); |
| 477 | thy addItem_move (ct.move()); |
| 478 | } |
| 479 | return thee; |
| 480 | } catch (MelderError) { |
| 481 | Melder_throw (me, U": no CrossCorrelationTableList created."); |
| 482 | } |
| 483 | } |
| 484 | |
| 485 | autoSound Sound_to_Sound_BSS (Sound me, |
| 486 | double startTime, double endTime, integer numberOfCrossCorrelations, double lagStep, |
| 487 | integer maxNumberOfIterations, double tol, int method) |
| 488 | { |
| 489 | try { |
| 490 | autoMixingMatrix him = Sound_to_MixingMatrix (me, |
| 491 | startTime, endTime, numberOfCrossCorrelations, lagStep, |
| 492 | maxNumberOfIterations, tol, method); |
| 493 | autoSound thee = Sound_MixingMatrix_unmix (me, him.get()); |
| 494 | return thee; |
| 495 | } catch (MelderError) { |
| 496 | Melder_throw (me, U": not separated."); |
| 497 | } |
| 498 | } |
| 499 | |
| 500 | /************************ Diagonalizer **********************************/ |
| 501 | |
| 502 | Thing_implement (Diagonalizer, TableOfReal, 0); |
| 503 | |
| 504 | autoDiagonalizer Diagonalizer_create (integer dimension) { |
| 505 | try { |
| 506 | autoDiagonalizer me = Thing_new (Diagonalizer); |
| 507 | TableOfReal_init (me.get(), dimension, dimension); |
| 508 | for (integer i = 1; i <= dimension; i ++) |
| 509 | my data [i] [i] = 1.0; |
| 510 | |
| 511 | return me; |
| 512 | } catch (MelderError) { |
| 513 | Melder_throw (U"Diagonalizer not created."); |
| 514 | } |
| 515 | } |
| 516 | |
| 517 | /***************** Diagonalizer & MixingMatrix *************************/ |
| 518 | |
| 519 | |
| 520 | autoDiagonalizer MixingMatrix_to_Diagonalizer (MixingMatrix me) { |
| 521 | try { |
| 522 | Melder_require (my numberOfRows == my numberOfColumns, |
| 523 | U"The number of channels and the number of components should be equal."); |
| 524 | |
| 525 | autoDiagonalizer thee = Diagonalizer_create (my numberOfRows); |
| 526 | MATpseudoInverse (thy data.get(), my data.get(), 0.0); |
| 527 | return thee; |
| 528 | } catch (MelderError) { |
| 529 | Melder_throw (me, U": no Diagonalizer created."); |
| 530 | } |
| 531 | } |
| 532 | |
| 533 | autoMixingMatrix Diagonalizer_to_MixingMatrix (Diagonalizer me) { |
| 534 | try { |
| 535 | autoMixingMatrix thee = MixingMatrix_create (my numberOfRows, my numberOfColumns); |
| 536 | MixingMatrix_setRandomGauss (thee.get(), 0.0, 1.0); |
| 537 | MATpseudoInverse (thy data.get(), my data.get(), 0.0); |
| 538 | |
| 539 | return thee; |
| 540 | } catch (MelderError) { |
| 541 | Melder_throw (me, U": no MixingMatrix created."); |
| 542 | } |
| 543 | } |
| 544 | |
| 545 | void MixingMatrix_Sound_improveUnmixing (MixingMatrix me, Sound thee, double startTime, double endTime, integer numberOfCrossCorrelations, double lagStep, integer maxNumberOfIterations, double tol, int method) { |
| 546 | autoCrossCorrelationTableList ccs = Sound_to_CrossCorrelationTableList (thee, startTime, endTime, numberOfCrossCorrelations, lagStep); |
| 547 | MixingMatrix_CrossCorrelationTableList_improveUnmixing (me, ccs.get(), maxNumberOfIterations, tol, method); |
| 548 | } |
| 549 | |
| 550 | autoMixingMatrix Sound_to_MixingMatrix (Sound me, |
| 551 | double startTime, double endTime, integer numberOfCrossCorrelations, double lagStep, |
| 552 | integer maxNumberOfIterations, double tol, int method) |
| 553 | { |
| 554 | try { |
| 555 | autoCrossCorrelationTableList ccs = Sound_to_CrossCorrelationTableList (me, startTime, endTime, numberOfCrossCorrelations, lagStep); |
| 556 | autoMixingMatrix thee = MixingMatrix_create (my ny, my ny); |
| 557 | MixingMatrix_setRandomGauss (thee.get(), 0.0, 1.0); |
| 558 | MixingMatrix_CrossCorrelationTableList_improveUnmixing (thee.get(), ccs.get(), maxNumberOfIterations, tol, method); |
| 559 | return thee; |
| 560 | } catch (MelderError) { |
| 561 | Melder_throw (me, U": no MixingMatrix created."); |
| 562 | } |
| 563 | } |
| 564 | |
| 565 | autoMixingMatrix TableOfReal_to_MixingMatrix (TableOfReal me) { |
| 566 | try { |
| 567 | Melder_require (my numberOfColumns == my numberOfRows, |
| 568 | U"Number of rows and columns should be equal."); |
| 569 | autoMixingMatrix thee = Thing_new (MixingMatrix); |
| 570 | my structTableOfReal :: v1_copy (thee.get()); |
| 571 | return thee; |
| 572 | } catch (MelderError) { |
| 573 | Melder_throw (me, U": not converted to MixingMatrix."); |
| 574 | } |
| 575 | } |
| 576 | |
| 577 | /************* CrossCorrelationTable *****************************/ |
| 578 | |
| 579 | Thing_implement (CrossCorrelationTable, SSCP, 0); |
| 580 | |
| 581 | void structCrossCorrelationTable :: v1_info () { |
| 582 | CrossCorrelationTable_Parent :: v1_info (); |
| 583 | const double dm = CrossCorrelationTable_getDiagonalityMeasure (this); |
| 584 | MelderInfo_writeLine (U"Diagonality measure: ", dm); |
| 585 | } |
| 586 | |
| 587 | autoCrossCorrelationTable CrossCorrelationTable_create (integer dimension) { |
| 588 | try { |
| 589 | autoCrossCorrelationTable me = Thing_new (CrossCorrelationTable); |
| 590 | SSCP_init (me.get(), dimension, kSSCPstorage::COMPLETE); |
| 591 | return me; |
| 592 | } catch (MelderError) { |
| 593 | Melder_throw (U"CrossCorrelationTable not created."); |
| 594 | } |
| 595 | } |
| 596 | |
| 597 | autoCrossCorrelationTable CrossCorrelationTable_createSimple (conststring32 covars_string, conststring32 centroid_string, integer numberOfSamples) { |
| 598 | try { |
| 599 | autoSTRVEC covars = splitByWhitespace_STRVEC (covars_string); |
| 600 | autoSTRVEC centroid = splitByWhitespace_STRVEC (centroid_string); |
| 601 | const integer dimension = centroid.size; |
| 602 | const integer ncovars = covars.size; |
| 603 | const integer ncovars_wanted = dimension * (dimension + 1) / 2; |
| 604 | |
| 605 | Melder_require (ncovars == ncovars_wanted, |
| 606 | U"The number of matrix elements and the number of " |
| 607 | U"centroid elements should agree. There should be \"d(d+1)/2\" matrix values and \"d\" centroid values."); |
| 608 | |
| 609 | autoCrossCorrelationTable me = CrossCorrelationTable_create (dimension); |
| 610 | |
| 611 | /* |
| 612 | Construct the full matrix from the upper-diagonal elements |
| 613 | */ |
| 614 | integer irow = 1; |
| 615 | for (integer inum = 1; inum <= ncovars; inum ++) { |
| 616 | const integer nmissing = (irow - 1) * irow / 2; |
| 617 | const integer inumc = inum + nmissing; |
| 618 | irow = (inumc - 1) / dimension + 1; |
| 619 | const integer icol = (inumc - 1) % dimension + 1; |
| 620 | double number; |
| 621 | Interpreter_numericExpression (nullptr, covars [inum].get(), & number); |
| 622 | my data [irow] [icol] = my data [icol] [irow] = number; |
| 623 | if (icol == dimension) |
| 624 | irow ++; |
| 625 | } |
| 626 | for (integer inum = 1; inum <= dimension; inum ++) { |
| 627 | double number; |
| 628 | Interpreter_numericExpression (nullptr, centroid [inum].get(), & number); |
| 629 | my centroid [inum] = number; |
| 630 | } |
| 631 | my numberOfObservations = numberOfSamples; |
| 632 | return me; |
| 633 | } catch (MelderError) { |
| 634 | Melder_throw (U"CrossCorrelationTable not created."); |
| 635 | } |
| 636 | } |
| 637 | |
| 638 | double CrossCorrelationTable_getDiagonalityMeasure (CrossCorrelationTable me) { |
| 639 | return diagonalityMeasure (my data.get()); |
| 640 | } |
| 641 | |
| 642 | /************* CrossCorrelationTables *****************************/ |
| 643 | |
| 644 | void structCrossCorrelationTableList :: v1_info () { |
| 645 | our structThing :: v1_info (); |
| 646 | MelderInfo_writeLine (U"Contains ", our size, U" CrossCorrelationTable objects"); |
| 647 | CrossCorrelationTable thee = our at [1]; |
| 648 | MelderInfo_writeLine (U"Number of rows and columns: ", thy numberOfRows, U" in each CrossCorrelationTable"); |
| 649 | for (integer itable = 1; itable <= our size; itable ++) { |
| 650 | const double dm = CrossCorrelationTable_getDiagonalityMeasure (our at [itable]); |
| 651 | MelderInfo_writeLine (U" Diagonality measure for item ", itable, U": ", dm); |
| 652 | } |
| 653 | } |
| 654 | |
| 655 | autoCrossCorrelationTableList CrossCorrelationTables_to_CrossCorrelationTableList (OrderedOf<structCrossCorrelationTable> *me) { |
| 656 | try { |
| 657 | autoCrossCorrelationTableList thee = CrossCorrelationTableList_create (); |
| 658 | integer numberOfRows = 0, numberOfColumns = 0; |
| 659 | for (integer itable = 1; itable <= my size; itable ++) { |
| 660 | CrossCorrelationTable item = my at [itable]; |
| 661 | if (itable == 1) { |
| 662 | numberOfRows = item -> numberOfRows; |
| 663 | numberOfColumns = item -> numberOfColumns; |
| 664 | } |
| 665 | Melder_require (item -> numberOfRows == numberOfRows && item -> numberOfColumns == numberOfColumns, |
| 666 | U"Dimensions of table ", itable, U" differs from the rest."); |
| 667 | |
| 668 | autoCrossCorrelationTable myc = Data_copy (item); |
| 669 | thy addItem_move (myc.move()); |
| 670 | } |
| 671 | return thee; |
| 672 | } catch (MelderError) { |
| 673 | Melder_throw (U"No CrossCorrelationTableList created from CrossCorrelationTable(s)"); |
| 674 | } |
| 675 | } |
| 676 | |
| 677 | Thing_implement (CrossCorrelationTableList, SSCPList, 0); |
| 678 | |
| 679 | double CrossCorrelationTableList_getDiagonalityMeasure (CrossCorrelationTableList me, double *w, integer start, integer end) { |
| 680 | if (start >= end) { |
| 681 | start = 1; |
| 682 | end = my size; |
| 683 | } |
| 684 | Melder_clipLeft (1_integer, & start); |
| 685 | Melder_clipRight (& end, my size); |
| 686 | |
| 687 | const integer ntables = end - start + 1; |
| 688 | double dmsq = 0; |
| 689 | for (integer itable = start; itable <= end; itable ++) { |
| 690 | const CrossCorrelationTable thee = my at [itable]; |
| 691 | const double dmksq = diagonalityMeasure (thy data.get()); |
| 692 | dmsq += ( w ? dmksq * w [itable] : dmksq / ntables ); |
| 693 | } |
| 694 | return dmsq; |
| 695 | } |
| 696 | |
| 697 | /************************** CrossCorrelationTables & Diagonalizer *******************************/ |
| 698 | |
| 699 | double CrossCorrelationTableList_Diagonalizer_getDiagonalityMeasure (CrossCorrelationTableList me, Diagonalizer thee, double *w, integer start, integer end) { |
| 700 | autoCrossCorrelationTableList him = CrossCorrelationTableList_Diagonalizer_diagonalize (me, thee); |
| 701 | const double dm = CrossCorrelationTableList_getDiagonalityMeasure (him.get(), w, start, end); |
| 702 | return dm; |
| 703 | } |
| 704 | |
| 705 | autoCrossCorrelationTable CrossCorrelationTable_Diagonalizer_diagonalize (CrossCorrelationTable me, Diagonalizer thee) { |
| 706 | try { |
| 707 | Melder_require (my numberOfRows == thy numberOfRows, |
| 708 | U"The CrossCorrelationTable and the Diagonalizer matrix dimensions should be equal."); |
| 709 | |
| 710 | autoCrossCorrelationTable him = CrossCorrelationTable_create (my numberOfColumns); |
| 711 | MATmul_VCVt_preallocated (his data.get(), thy data.get(), my data.get(), true); |
| 712 | return him; |
| 713 | } catch (MelderError) { |
| 714 | Melder_throw (U"CrossCorrelationTable not diagonalized."); |
| 715 | } |
| 716 | } |
| 717 | |
| 718 | autoCrossCorrelationTableList CrossCorrelationTableList_Diagonalizer_diagonalize (CrossCorrelationTableList me, Diagonalizer thee) { |
| 719 | try { |
| 720 | autoCrossCorrelationTableList him = CrossCorrelationTableList_create (); |
| 721 | for (integer itable = 1; itable <= my size; itable ++) { |
| 722 | const CrossCorrelationTable item = my at [itable]; |
| 723 | autoCrossCorrelationTable ct = CrossCorrelationTable_Diagonalizer_diagonalize (item, thee); |
| 724 | his addItem_move (ct.move()); |
| 725 | } |
| 726 | return him; |
| 727 | } catch (MelderError) { |
| 728 | Melder_throw (U"CrossCorrelationTableList not diagonalized."); |
| 729 | } |
| 730 | } |
| 731 | |
| 732 | autoDiagonalizer CrossCorrelationTableList_to_Diagonalizer (CrossCorrelationTableList me, integer maxNumberOfIterations, double tol, int method) { |
| 733 | try { |
| 734 | Melder_assert (my size > 0); |
| 735 | CrossCorrelationTable him = my at [1]; |
| 736 | autoDiagonalizer thee = Diagonalizer_create (his numberOfColumns); |
| 737 | Diagonalizer_CrossCorrelationTableList_improveDiagonality (thee.get(), me, maxNumberOfIterations, tol, method); |
| 738 | return thee; |
| 739 | } catch (MelderError) { |
| 740 | Melder_throw (U"Diagonalizer not created from CrossCorrelationTableList."); |
| 741 | }; |
| 742 | } |
| 743 | |
| 744 | void Diagonalizer_CrossCorrelationTableList_improveDiagonality (Diagonalizer me, CrossCorrelationTableList thee, integer maxNumberOfIterations, double tol, int method) { |
| 745 | if (method == 1) { |
| 746 | autoVEC cweights = raw_VEC (thy size); |
| 747 | cweights.all() <<= 1.0 / thy size; |
| 748 | Diagonalizer_CrossCorrelationTable_qdiag (me, thee, cweights.get(), maxNumberOfIterations, tol); |
| 749 | } else { |
| 750 | Diagonalizer_CrossCorrelationTableList_ffdiag (me, thee, maxNumberOfIterations, tol); |
| 751 | } |
| 752 | } |
| 753 | |
| 754 | autoSound Sound_whitenChannels (Sound me, double varianceFraction) { |
| 755 | try { |
| 756 | autoCovariance cov = Sound_to_Covariance_channels (me, 0.0, 0.0); |
| 757 | autoSound thee = Sound_Covariance_whitenChannels (me, cov.get(), varianceFraction); |
| 758 | return thee; |
| 759 | } catch (MelderError) { |
| 760 | Melder_throw (me, U": not whitened."); |
| 761 | } |
| 762 | } |
| 763 | |
| 764 | autoSound Sound_Covariance_whitenChannels (Sound me, Covariance thee, double varianceFraction) { |
| 765 | try { |
| 766 | autoPCA pca = SSCP_to_PCA (thee); |
| 767 | const integer numberOfComponents = Eigen_getDimensionOfFraction (pca.get(), varianceFraction); |
| 768 | autoSound him = Sound_PCA_whitenChannels (me, pca.get(), numberOfComponents); |
| 769 | return him; |
| 770 | } catch (MelderError) { |
| 771 | Melder_throw (me, U": not whitened from ", thee); |
| 772 | } |
| 773 | } |
| 774 | |
| 775 | /* |
| 776 | * Generate n different cct's that have a common diagonalizer. |
| 777 | */ |
| 778 | autoCrossCorrelationTableList CrossCorrelationTableList_createTestSet (integer dimension, integer n, int firstPositiveDefinite, double sigma) { |
| 779 | try { |
| 780 | /* |
| 781 | Start with a square matrix with random gaussian elements and make its singular value decomposition UDV' |
| 782 | The V matrix will be the common diagonalizer matrix that we use. |
| 783 | */ |
| 784 | |
| 785 | autoMAT d = randomGauss_MAT (dimension, dimension, 0.0, 1.0); |
| 786 | autoMAT v = raw_MAT (dimension, dimension); |
| 787 | autoSVD svd = SVD_createFromGeneralMatrix (d.get()); |
| 788 | autoCrossCorrelationTableList me = CrossCorrelationTableList_create (); |
| 789 | |
| 790 | d.all() <<= 0.0; |
| 791 | |
| 792 | // Start with a diagonal matrix D and calculate V'DV |
| 793 | |
| 794 | for (integer k = 1; k <= n; k ++) { |
| 795 | autoCrossCorrelationTable ct = CrossCorrelationTable_create (dimension); |
| 796 | const double low = ( k == 1 && firstPositiveDefinite ? 0.1 : -1.0 ); |
| 797 | for (integer i = 1; i <= dimension; i ++) |
| 798 | d [i] [i] = NUMrandomUniform (low, 1.0); |
| 799 | for (integer i = 1; i <= dimension; i ++) |
| 800 | for (integer j = 1; j <= dimension; j ++) |
| 801 | v [i] [j] = NUMrandomGauss (svd -> v [i] [j], sigma); |
| 802 | // we need V'DV, however our V has eigenvectors row-wise -> VDV' |
| 803 | MATmul_VCVt_preallocated (ct -> data.get(), v.get(), d.get(), true); |
| 804 | my addItem_move (ct.move()); |
| 805 | } |
| 806 | return me; |
| 807 | } catch (MelderError) { |
| 808 | Melder_throw (U"CrossCorrelationTableList test set not created."); |
| 809 | } |
| 810 | } |
| 811 | |
| 812 | #if 0 |
| 813 | static void Sound_MixingMatrix_improveUnmixing_fica (Sound me, MixingMatrix thee, integer maxNumberOfIterations, double /* tol */, int /* method */) { |
| 814 | try { |
| 815 | integer iter = 0; |
| 816 | Melder_require (my ny == thy numberOfColumns, U"Dimensions should agree."); |
| 817 | |
| 818 | autoMAT x = newmatrixcopy (my z.get()); |
| 819 | do { |
| 820 | iter ++; |
| 821 | } while (/*fabs((dm_old - dm_new) / dm_new) > tol &&*/ iter < maxNumberOfIterations); |
| 822 | } catch (MelderError) { |
| 823 | Melder_throw (me, U" & ", thee, U" ."); |
| 824 | } |
| 825 | } |
| 826 | #endif |
| 827 | |
| 828 | /* End of file ICA.cpp */ |