/
pca.py
285 lines (245 loc) · 10.8 KB
/
pca.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
"""
PCA and related signal decomposition methods for tedana
"""
import logging
import numpy as np
from scipy import stats
from sklearn.decomposition import PCA
from tedana import metrics, utils, io
from tedana.decomposition._utils import eimask
from tedana.stats import computefeats2
from tedana.selection import kundu_tedpca
from tedana.due import due, BibTeX
LGR = logging.getLogger(__name__)
@due.dcite(BibTeX(
"""
@inproceedings{minka2001automatic,
title={Automatic choice of dimensionality for PCA},
author={Minka, Thomas P},
booktitle={Advances in neural information processing systems},
pages={598--604},
year={2001}
}
"""),
description='Introduces method for choosing PCA dimensionality '
'automatically')
def run_mlepca(data):
"""
Run Singular Value Decomposition (SVD) on input data,
automatically select components on MLE variance cut-off.
Parameters
----------
data : (S [*E] x T) array_like
Optimally combined (S x T) or full multi-echo (S*E x T) data.
Returns
-------
u : (S [*E] x C) array_like
Component weight map for each component.
s : (C,) array_like
Variance explained for each component.
v : (T x C) array_like
Component timeseries.
"""
# do PC dimension selection and get eigenvalue cutoff
ppca = PCA(n_components='mle', svd_solver='full', copy=False)
ppca.fit(data)
v = ppca.components_.T
s = ppca.explained_variance_
u = np.dot(np.dot(data, v), np.diag(1. / s))
varex_norm = ppca.explained_variance_ratio_
return u, s, varex_norm, v
def low_mem_pca(data):
"""
Run Singular Value Decomposition (SVD) on input data.
Parameters
----------
data : (S [*E] x T) array_like
Optimally combined (S x T) or full multi-echo (S*E x T) data.
Returns
-------
u : (S [*E] x C) array_like
Component weight map for each component.
s : (C,) array_like
Variance explained for each component.
v : (C x T) array_like
Component timeseries.
"""
from sklearn.decomposition import IncrementalPCA
ppca = IncrementalPCA(n_components=(data.shape[-1] - 1))
ppca.fit(data)
v = ppca.components_.T
s = ppca.explained_variance_
u = np.dot(np.dot(data, v), np.diag(1. / s))
return u, s, v
def tedpca(data_cat, data_oc, combmode, mask, t2s, t2sG,
ref_img, tes, algorithm='mle', source_tes=-1, kdaw=10., rdaw=1.,
out_dir='.', verbose=False, low_mem=False):
"""
Use principal components analysis (PCA) to identify and remove thermal
noise from multi-echo data.
Parameters
----------
data_cat : (S x E x T) array_like
Input functional data
data_oc : (S x T) array_like
Optimally combined time series data
combmode : {'t2s', 'paid'} str
How optimal combination of echos should be made, where 't2s' indicates
using the method of Posse 1999 and 'paid' indicates using the method of
Poser 2006
mask : (S,) array_like
Boolean mask array
t2s : (S,) array_like
Map of voxel-wise T2* estimates.
t2sG : (S,) array_like
Map of voxel-wise T2* estimates.
ref_img : :obj:`str` or img_like
Reference image to dictate how outputs are saved to disk
tes : :obj:`list`
List of echo times associated with `data_cat`, in milliseconds
algorithm : {'mle', 'kundu', 'kundu-stabilize'}, optional
Method with which to select components in TEDPCA. Default is 'mle'.
source_tes : :obj:`int` or :obj:`list` of :obj:`int`, optional
Which echos to use in PCA. Values -1 and 0 are special, where a value
of -1 will indicate using the optimal combination of the echos
and 0 will indicate using all the echos. A list can be provided
to indicate a subset of echos.
Default: -1
kdaw : :obj:`float`, optional
Dimensionality augmentation weight for Kappa calculations. Must be a
non-negative float, or -1 (a special value). Default is 10.
rdaw : :obj:`float`, optional
Dimensionality augmentation weight for Rho calculations. Must be a
non-negative float, or -1 (a special value). Default is 1.
out_dir : :obj:`str`, optional
Output directory.
verbose : :obj:`bool`, optional
Whether to output files from fitmodels_direct or not. Default: False
low_mem : :obj:`bool`, optional
Whether to use incremental PCA (for low-memory systems) or not.
Default: False
Returns
-------
kept_data : (S x T) :obj:`numpy.ndarray`
Dimensionally reduced optimally combined functional data
n_components : :obj:`int`
Number of components retained from PCA decomposition
Notes
-----
====================== =================================================
Notation Meaning
====================== =================================================
:math:`\\kappa` Component pseudo-F statistic for TE-dependent
(BOLD) model.
:math:`\\rho` Component pseudo-F statistic for TE-independent
(artifact) model.
:math:`v` Voxel
:math:`V` Total number of voxels in mask
:math:`\\zeta` Something
:math:`c` Component
:math:`p` Something else
====================== =================================================
Steps:
1. Variance normalize either multi-echo or optimally combined data,
depending on settings.
2. Decompose normalized data using PCA or SVD.
3. Compute :math:`{\\kappa}` and :math:`{\\rho}`:
.. math::
{\\kappa}_c = \\frac{\\sum_{v}^V {\\zeta}_{c,v}^p * \
F_{c,v,R_2^*}}{\\sum {\\zeta}_{c,v}^p}
{\\rho}_c = \\frac{\\sum_{v}^V {\\zeta}_{c,v}^p * \
F_{c,v,S_0}}{\\sum {\\zeta}_{c,v}^p}
4. Some other stuff. Something about elbows.
5. Classify components as thermal noise if they meet both of the
following criteria:
- Nonsignificant :math:`{\\kappa}` and :math:`{\\rho}`.
- Nonsignificant variance explained.
Outputs:
This function writes out several files:
====================== =================================================
Filename Content
====================== =================================================
pcastate.pkl Values from PCA results.
comp_table_pca.txt PCA component table.
mepca_mix.1D PCA mixing matrix.
====================== =================================================
"""
if low_mem and algorithm == 'mle':
LGR.warning('Low memory option is not compatible with MLE '
'dimensionality estimation. Switching to Kundu decision '
'tree.')
algorithm = 'kundu'
n_samp, n_echos, n_vols = data_cat.shape
source_tes = np.array([int(ee) for ee in str(source_tes).split(',')])
if len(source_tes) == 1 and source_tes[0] == -1:
LGR.info('Computing PCA of optimally combined multi-echo data')
data = data_oc[mask, :][:, np.newaxis, :]
elif len(source_tes) == 1 and source_tes[0] == 0:
LGR.info('Computing PCA of spatially concatenated multi-echo data')
data = data_cat[mask, ...]
else:
LGR.info('Computing PCA of echo #{0}'.format(','.join([str(ee) for ee in source_tes])))
data = np.stack([data_cat[mask, ee, :] for ee in source_tes - 1], axis=1)
eim = np.squeeze(eimask(data))
data = np.squeeze(data[eim])
data_z = ((data.T - data.T.mean(axis=0)) / data.T.std(axis=0)).T # var normalize ts
data_z = (data_z - data_z.mean()) / data_z.std() # var normalize everything
if algorithm == 'mle':
voxel_comp_weights, varex, varex_norm, comp_ts = run_mlepca(data_z)
elif low_mem:
voxel_comp_weights, varex, comp_ts = low_mem_pca(data_z)
varex_norm = varex / varex.sum()
else:
ppca = PCA(copy=False, n_components=(n_vols - 1))
ppca.fit(data_z)
comp_ts = ppca.components_.T
varex = ppca.explained_variance_
voxel_comp_weights = np.dot(np.dot(data_z, comp_ts),
np.diag(1. / varex))
varex_norm = varex / varex.sum()
# Compute Kappa and Rho for PCA comps
eimum = np.atleast_2d(eim)
eimum = np.transpose(eimum, np.argsort(eimum.shape)[::-1])
eimum = eimum.prod(axis=1)
o = np.zeros((mask.shape[0], *eimum.shape[1:]))
o[mask, ...] = eimum
eimum = np.squeeze(o).astype(bool)
# Normalize each component's time series
vTmixN = stats.zscore(comp_ts, axis=0)
comptable, _, _, _ = metrics.dependence_metrics(
data_cat, data_oc, comp_ts, t2s, tes, ref_img,
reindex=False, mmixN=vTmixN, algorithm=None,
label='mepca_', out_dir=out_dir, verbose=verbose)
# varex_norm from PCA overrides varex_norm from dependence_metrics,
# but we retain the original
comptable['estimated normalized variance explained'] = \
comptable['normalized variance explained']
comptable['normalized variance explained'] = varex_norm
np.savetxt('mepca_mix.1D', comp_ts)
# write component maps to 4D image
comp_maps = np.zeros((data_oc.shape[0], comp_ts.shape[1]))
for i_comp in range(comp_ts.shape[1]):
temp_comp_ts = comp_ts[:, i_comp][:, None]
comp_map = utils.unmask(computefeats2(data_oc, temp_comp_ts, mask), mask)
comp_maps[:, i_comp] = np.squeeze(comp_map)
io.filewrite(comp_maps, 'mepca_OC_components.nii', ref_img)
# Select components using decision tree
if algorithm == 'kundu':
comptable = kundu_tedpca(comptable, n_echos, kdaw, rdaw, stabilize=False)
elif algorithm == 'kundu-stabilize':
comptable = kundu_tedpca(comptable, n_echos, kdaw, rdaw, stabilize=True)
elif algorithm == 'mle':
LGR.info('Selected {0} components with MLE dimensionality '
'detection'.format(comptable.shape[0]))
comptable['classification'] = 'accepted'
comptable['rationale'] = ''
comptable.to_csv('comp_table_pca.txt', sep='\t', index=True,
index_label='component', float_format='%.6f')
acc = comptable[comptable.classification == 'accepted'].index.values
n_components = acc.size
voxel_kept_comp_weighted = (voxel_comp_weights[:, acc] *
varex[None, acc])
kept_data = np.dot(voxel_kept_comp_weighted, comp_ts[:, acc].T)
kept_data = stats.zscore(kept_data, axis=1) # variance normalize time series
kept_data = stats.zscore(kept_data, axis=None) # variance normalize everything
return kept_data, n_components