def test_getelbow_smoke(): """A smoke test for the getelbow function.""" arr = np.random.random(100) idx = _utils.getelbow(arr) assert isinstance(idx, np.integer) val = _utils.getelbow(arr, return_val=True) assert isinstance(val, float) # Running an empty array should raise a ValueError arr = np.array([]) with pytest.raises(ValueError): _utils.getelbow(arr) # Running a 2D array should raise a ValueError arr = np.random.random((100, 100)) with pytest.raises(ValueError): _utils.getelbow(arr)
def kundu_tedpca(comptable, n_echos, kdaw=10., rdaw=1., stabilize=False): """ Select PCA components using Kundu's decision tree approach. Parameters ---------- comptable : :obj:`pandas.DataFrame` Component table with relevant metrics: kappa, rho, and normalized variance explained. Component number should be the index. n_echos : :obj:`int` Number of echoes in dataset. kdaw : :obj:`float`, optional Kappa dimensionality augmentation weight. Must be a non-negative float, or -1 (a special value). Default is 10. rdaw : :obj:`float`, optional Rho dimensionality augmentation weight. Must be a non-negative float, or -1 (a special value). Default is 1. stabilize : :obj:`bool`, optional Whether to stabilize convergence by reducing dimensionality, for low quality data. Default is False. Returns ------- comptable : :obj:`pandas.DataFrame` Component table with components classified as 'accepted', 'rejected', or 'ignored'. metric_metadata : :obj:`dict` Dictionary with metadata about calculated metrics. Each entry corresponds to a column in ``comptable``. """ LGR.info('Performing PCA component selection with Kundu decision tree') comptable['classification'] = 'accepted' comptable['rationale'] = '' eigenvalue_elbow = getelbow(comptable['normalized variance explained'], return_val=True) diff_varex_norm = np.abs( np.diff(comptable['normalized variance explained'])) lower_diff_varex_norm = diff_varex_norm[(len(diff_varex_norm) // 2):] varex_norm_thr = np.mean( [lower_diff_varex_norm.max(), diff_varex_norm.min()]) varex_norm_min = comptable['normalized variance explained'][ (len(diff_varex_norm) // 2) + np.arange(len(lower_diff_varex_norm))[ lower_diff_varex_norm >= varex_norm_thr][0] + 1] varex_norm_cum = np.cumsum(comptable['normalized variance explained']) fmin, fmid, fmax = getfbounds(n_echos) if int(kdaw) == -1: lim_idx = utils.andb( [comptable['kappa'] < fmid, comptable['kappa'] > fmin]) == 2 kappa_lim = comptable.loc[lim_idx, 'kappa'].values kappa_thr = kappa_lim[getelbow(kappa_lim)] lim_idx = utils.andb( [comptable['rho'] < fmid, comptable['rho'] > fmin]) == 2 rho_lim = comptable.loc[lim_idx, 'rho'].values rho_thr = rho_lim[getelbow(rho_lim)] stabilize = True LGR.info('kdaw set to -1. Switching TEDPCA algorithm to ' 'kundu-stabilize') elif int(rdaw) == -1: lim_idx = utils.andb( [comptable['rho'] < fmid, comptable['rho'] > fmin]) == 2 rho_lim = comptable.loc[lim_idx, 'rho'].values rho_thr = rho_lim[getelbow(rho_lim)] else: kappa_thr = np.average(sorted( [fmin, (getelbow(comptable['kappa'], return_val=True) / 2), fmid]), weights=[kdaw, 1, 1]) rho_thr = np.average(sorted([ fmin, (getelbow_cons(comptable['rho'], return_val=True) / 2), fmid ]), weights=[rdaw, 1, 1]) # Reject if low Kappa, Rho, and variance explained is_lowk = comptable['kappa'] <= kappa_thr is_lowr = comptable['rho'] <= rho_thr is_lowe = comptable['normalized variance explained'] <= eigenvalue_elbow is_lowkre = is_lowk & is_lowr & is_lowe comptable.loc[is_lowkre, 'classification'] = 'rejected' comptable.loc[is_lowkre, 'rationale'] += 'P001;' # Reject if low variance explained is_lows = comptable['normalized variance explained'] <= varex_norm_min comptable.loc[is_lows, 'classification'] = 'rejected' comptable.loc[is_lows, 'rationale'] += 'P002;' # Reject if Kappa over limit is_fmax1 = comptable['kappa'] == F_MAX comptable.loc[is_fmax1, 'classification'] = 'rejected' comptable.loc[is_fmax1, 'rationale'] += 'P003;' # Reject if Rho over limit is_fmax2 = comptable['rho'] == F_MAX comptable.loc[is_fmax2, 'classification'] = 'rejected' comptable.loc[is_fmax2, 'rationale'] += 'P004;' if stabilize: temp7 = varex_norm_cum >= 0.95 comptable.loc[temp7, 'classification'] = 'rejected' comptable.loc[temp7, 'rationale'] += 'P005;' under_fmin1 = comptable['kappa'] <= fmin comptable.loc[under_fmin1, 'classification'] = 'rejected' comptable.loc[under_fmin1, 'rationale'] += 'P006;' under_fmin2 = comptable['rho'] <= fmin comptable.loc[under_fmin2, 'classification'] = 'rejected' comptable.loc[under_fmin2, 'rationale'] += 'P007;' n_components = comptable.loc[comptable['classification'] == 'accepted'].shape[0] LGR.info('Selected {0} components with Kappa threshold: {1:.02f}, Rho ' 'threshold: {2:.02f}'.format(n_components, kappa_thr, rho_thr)) # Move decision columns to end comptable = clean_dataframe(comptable) metric_metadata = collect.get_metadata(comptable) return comptable, metric_metadata
def kundu_selection_v2(comptable, n_echos, n_vols): """ Classify components as "accepted," "rejected," or "ignored" based on relevant metrics. The selection process uses previously calculated parameters listed in comptable for each ICA component such as Kappa (a T2* weighting metric), Rho (an S0 weighting metric), and variance explained. See `Notes` for additional calculated metrics used to classify each component into one of the listed groups. Parameters ---------- comptable : (C x M) :obj:`pandas.DataFrame` Component metric table. One row for each component, with a column for each metric. The index should be the component number. n_echos : :obj:`int` Number of echos in original data n_vols : :obj:`int` Number of volumes in dataset Returns ------- comptable : :obj:`pandas.DataFrame` Updated component table with additional metrics and with classification (accepted, rejected, or ignored) Notes ----- The selection algorithm used in this function was originated in ME-ICA by Prantik Kundu, and his original implementation is available at: https://github.com/ME-ICA/me-ica/blob/b2781dd087ab9de99a2ec3925f04f02ce84f0adc/meica.libs/select_model.py This component selection process uses multiple, previously calculated metrics that include kappa, rho, variance explained, noise and spatial frequency metrics, and measures of spatial overlap across metrics. Prantik began to update these selection criteria to use SVMs to distinguish components, a hypercommented version of this attempt is available at: https://gist.github.com/emdupre/ca92d52d345d08ee85e104093b81482e References ---------- * Kundu, P., Brenowitz, N. D., Voon, V., Worbe, Y., Vértes, P. E., Inati, S. J., ... & Bullmore, E. T. (2013). Integrated strategy for improving functional connectivity mapping using multiecho fMRI. Proceedings of the National Academy of Sciences, 110(40), 16187-16192. """ LGR.info( 'Performing ICA component selection with Kundu decision tree v2.5') RepLGR.info("Next, component selection was performed to identify " "BOLD (TE-dependent), non-BOLD (TE-independent), and " "uncertain (low-variance) components using the Kundu " "decision tree (v2.5; Kundu et al., 2013).") RefLGR.info("Kundu, P., Brenowitz, N. D., Voon, V., Worbe, Y., " "Vértes, P. E., Inati, S. J., ... & Bullmore, E. T. " "(2013). Integrated strategy for improving functional " "connectivity mapping using multiecho fMRI. Proceedings " "of the National Academy of Sciences, 110(40), " "16187-16192.") comptable['classification'] = 'accepted' comptable['rationale'] = '' # Set knobs LOW_PERC = 25 HIGH_PERC = 90 if n_vols < 100: EXTEND_FACTOR = 3 else: EXTEND_FACTOR = 2 RESTRICT_FACTOR = 2 # Lists of components all_comps = np.arange(comptable.shape[0]) # unclf is a full list that is whittled down over criteria # since the default classification is "accepted", at the end of the tree # the remaining elements in unclf are classified as accepted unclf = all_comps.copy() """ Step 1: Reject anything that's obviously an artifact a. Estimate a null variance """ # Rho is higher than Kappa temp_rej0a = all_comps[(comptable['rho'] > comptable['kappa'])] comptable.loc[temp_rej0a, 'classification'] = 'rejected' comptable.loc[temp_rej0a, 'rationale'] += 'I002;' # Number of significant voxels for S0 model is higher than number for R2 # model *and* number for R2 model is greater than zero. temp_rej0b = all_comps[( (comptable['countsigFS0'] > comptable['countsigFR2']) & (comptable['countsigFR2'] > 0))] comptable.loc[temp_rej0b, 'classification'] = 'rejected' comptable.loc[temp_rej0b, 'rationale'] += 'I003;' rej = np.union1d(temp_rej0a, temp_rej0b) # Dice score for S0 maps is higher than Dice score for R2 maps and variance # explained is higher than the median across components. temp_rej1 = all_comps[(comptable['dice_FS0'] > comptable['dice_FR2']) & (comptable['variance explained'] > np.median( comptable['variance explained']))] comptable.loc[temp_rej1, 'classification'] = 'rejected' comptable.loc[temp_rej1, 'rationale'] += 'I004;' rej = np.union1d(temp_rej1, rej) # T-value is less than zero (noise has higher F-statistics than signal in # map) and variance explained is higher than the median across components. temp_rej2 = unclf[(comptable.loc[unclf, 'signal-noise_t'] < 0) & (comptable.loc[unclf, 'variance explained'] > np.median(comptable['variance explained']))] comptable.loc[temp_rej2, 'classification'] = 'rejected' comptable.loc[temp_rej2, 'rationale'] += 'I005;' rej = np.union1d(temp_rej2, rej) unclf = np.setdiff1d(unclf, rej) # Quit early if no potentially accepted components remain if len(unclf) == 0: LGR.warning('No BOLD-like components detected. Ignoring all remaining ' 'components.') ign = sorted(np.setdiff1d(all_comps, rej)) comptable.loc[ign, 'classification'] = 'ignored' comptable.loc[ign, 'rationale'] += 'I006;' # Move decision columns to end comptable = clean_dataframe(comptable) return comptable """ Step 2: Make a guess for what the good components are, in order to estimate good component properties a. Not outlier variance b. Kappa>kappa_elbow c. Rho<Rho_elbow d. High R2* dice compared to S0 dice e. Gain of F_R2 in clusters vs noise f. Estimate a low and high variance """ # Step 2a # Upper limit for variance explained is median across components with high # Kappa values. High Kappa is defined as Kappa above Kappa elbow. varex_upper_p = np.median(comptable.loc[ comptable['kappa'] > getelbow(comptable['kappa'], return_val=True), 'variance explained']) # Sort component table by variance explained and find outlier components by # change in variance explained from one component to the next. # Remove variance-explained outliers from list of components to consider # for acceptance. These components will have another chance to be accepted # later on. # NOTE: We're not sure why this is done this way, nor why it's specifically # done three times. ncls = unclf.copy() for i_loop in range(3): temp_comptable = comptable.loc[ncls].sort_values( by=['variance explained'], ascending=False) diff_vals = temp_comptable['variance explained'].diff(-1) diff_vals = diff_vals.fillna(0) ncls = temp_comptable.loc[diff_vals < varex_upper_p].index.values # Compute elbows from other elbows f05, _, f01 = getfbounds(n_echos) kappas_nonsig = comptable.loc[comptable['kappa'] < f01, 'kappa'] # NOTE: Would an elbow from all Kappa values *ever* be lower than one from # a subset of lower values? kappa_elbow = np.min((getelbow(kappas_nonsig, return_val=True), getelbow(comptable['kappa'], return_val=True))) rho_elbow = np.mean((getelbow(comptable.loc[ncls, 'rho'], return_val=True), getelbow(comptable['rho'], return_val=True), f05)) # Provisionally accept components based on Kappa and Rho elbows acc_prov = ncls[(comptable.loc[ncls, 'kappa'] >= kappa_elbow) & (comptable.loc[ncls, 'rho'] < rho_elbow)] # Quit early if no potentially accepted components remain if len(acc_prov) <= 1: LGR.warning('Too few BOLD-like components detected. ' 'Ignoring all remaining.') ign = sorted(np.setdiff1d(all_comps, rej)) comptable.loc[ign, 'classification'] = 'ignored' comptable.loc[ign, 'rationale'] += 'I006;' # Move decision columns to end comptable = clean_dataframe(comptable) return comptable # Calculate "rate" for kappa: kappa range divided by variance explained # range, for potentially accepted components # NOTE: What is the logic behind this? kappa_rate = ((np.max(comptable.loc[acc_prov, 'kappa']) - np.min(comptable.loc[acc_prov, 'kappa'])) / (np.max(comptable.loc[acc_prov, 'variance explained']) - np.min(comptable.loc[acc_prov, 'variance explained']))) comptable['kappa ratio'] = kappa_rate * comptable[ 'variance explained'] / comptable['kappa'] # Calculate bounds for variance explained varex_lower = stats.scoreatpercentile( comptable.loc[acc_prov, 'variance explained'], LOW_PERC) varex_upper = stats.scoreatpercentile( comptable.loc[acc_prov, 'variance explained'], HIGH_PERC) """ Step 3: Get rid of midk components; i.e., those with higher than max decision score and high variance """ max_good_d_score = EXTEND_FACTOR * len(acc_prov) midk = unclf[(comptable.loc[unclf, 'd_table_score'] > max_good_d_score) & ( comptable.loc[unclf, 'variance explained'] > EXTEND_FACTOR * varex_upper)] comptable.loc[midk, 'classification'] = 'rejected' comptable.loc[midk, 'rationale'] += 'I007;' unclf = np.setdiff1d(unclf, midk) acc_prov = np.setdiff1d(acc_prov, midk) """ Step 4: Find components to ignore """ # collect high variance unclassified components # and mix of high/low provisionally accepted high_varex = np.union1d( acc_prov, unclf[comptable.loc[unclf, 'variance explained'] > varex_lower]) # ignore low variance components ign = np.setdiff1d(unclf, high_varex) # but only if they have bad decision scores ign = np.setdiff1d( ign, ign[comptable.loc[ign, 'd_table_score'] < max_good_d_score]) # and low kappa ign = np.setdiff1d(ign, ign[comptable.loc[ign, 'kappa'] > kappa_elbow]) comptable.loc[ign, 'classification'] = 'ignored' comptable.loc[ign, 'rationale'] += 'I008;' unclf = np.setdiff1d(unclf, ign) """ Step 5: Scrub the set if there are components that haven't been rejected or ignored, but are still not listed in the provisionally accepted group. """ if len(unclf) > len(acc_prov): comptable['d_table_score_scrub'] = np.nan # Recompute the midk steps on the limited set to clean up the tail d_table_rank = np.vstack([ len(unclf) - stats.rankdata(comptable.loc[unclf, 'kappa']), len(unclf) - stats.rankdata(comptable.loc[unclf, 'dice_FR2']), len(unclf) - stats.rankdata(comptable.loc[unclf, 'signal-noise_t']), stats.rankdata(comptable.loc[unclf, 'countnoise']), len(unclf) - stats.rankdata(comptable.loc[unclf, 'countsigFR2']) ]).T comptable.loc[unclf, 'd_table_score_scrub'] = d_table_rank.mean(1) num_acc_guess = int( np.mean([ np.sum((comptable.loc[unclf, 'kappa'] > kappa_elbow) & (comptable.loc[unclf, 'rho'] < rho_elbow)), np.sum(comptable.loc[unclf, 'kappa'] > kappa_elbow) ])) # Rejection candidate based on artifact type A: candartA conservative_guess = num_acc_guess / RESTRICT_FACTOR candartA = np.intersect1d( unclf[comptable.loc[unclf, 'd_table_score_scrub'] > conservative_guess], unclf[comptable.loc[unclf, 'kappa ratio'] > EXTEND_FACTOR * 2]) candartA = (candartA[comptable.loc[candartA, 'variance explained'] > varex_upper * EXTEND_FACTOR]) comptable.loc[candartA, 'classification'] = 'rejected' comptable.loc[candartA, 'rationale'] += 'I009;' midk = np.union1d(midk, candartA) unclf = np.setdiff1d(unclf, midk) # Rejection candidate based on artifact type B: candartB conservative_guess2 = num_acc_guess * HIGH_PERC / 100. candartB = unclf[ comptable.loc[unclf, 'd_table_score_scrub'] > conservative_guess2] candartB = (candartB[comptable.loc[candartB, 'variance explained'] > varex_lower * EXTEND_FACTOR]) comptable.loc[candartB, 'classification'] = 'rejected' comptable.loc[candartB, 'rationale'] += 'I010;' midk = np.union1d(midk, candartB) unclf = np.setdiff1d(unclf, midk) # Find components to ignore # Ignore high variance explained, poor decision tree scored components new_varex_lower = stats.scoreatpercentile( comptable.loc[unclf[:num_acc_guess], 'variance explained'], LOW_PERC) candart = unclf[comptable.loc[unclf, 'd_table_score_scrub'] > num_acc_guess] ign_add0 = candart[ comptable.loc[candart, 'variance explained'] > new_varex_lower] ign_add0 = np.setdiff1d(ign_add0, midk) comptable.loc[ign_add0, 'classification'] = 'ignored' comptable.loc[ign_add0, 'rationale'] += 'I011;' ign = np.union1d(ign, ign_add0) unclf = np.setdiff1d(unclf, ign) # Ignore low Kappa, high variance explained components ign_add1 = np.intersect1d( unclf[comptable.loc[unclf, 'kappa'] <= kappa_elbow], unclf[comptable.loc[unclf, 'variance explained'] > new_varex_lower]) ign_add1 = np.setdiff1d(ign_add1, midk) comptable.loc[ign_add1, 'classification'] = 'ignored' comptable.loc[ign_add1, 'rationale'] += 'I012;' # at this point, unclf is equivalent to accepted # Move decision columns to end comptable = clean_dataframe(comptable) return comptable
def tedpca(catd, OCcatd, combmode, mask, t2s, t2sG, stabilize, ref_img, tes, kdaw, rdaw, ste=0, wvpca=False): """ Use principal components analysis (PCA) to identify and remove thermal noise from multi-echo data. Parameters ---------- catd : (S x E x T) array_like Input functional data OCcatd : (S x T) array_like Optimally-combined time series data combmode : {'t2s', 'ste'} str How optimal combination of echos should be made, where 't2s' indicates using the method of Posse 1999 and 'ste' indicates using the method of Poser 2006 mask : (S,) array_like Boolean mask array stabilize : :obj:`bool` Whether to attempt to stabilize convergence of ICA by returning dimensionally-reduced data from PCA and component selection. 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 `catd`, in milliseconds kdaw : :obj:`float` Dimensionality augmentation weight for Kappa calculations rdaw : :obj:`float` Dimensionality augmentation weight for Rho calculations ste : :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 all the echos and 0 will indicate using the optimal combination of the echos. A list can be provided to indicate a subset of echos. Default: 0 wvpca : :obj:`bool`, optional Whether to apply wavelet denoising to data. Default: False Returns ------- n_components : :obj:`int` Number of components retained from PCA decomposition dd : (S x T) :obj:`numpy.ndarray` Dimensionally reduced optimally combined functional data 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. ====================== ================================================= """ n_samp, n_echos, n_vols = catd.shape ste = np.array([int(ee) for ee in str(ste).split(',')]) if len(ste) == 1 and ste[0] == -1: LGR.info('Computing PCA of optimally combined multi-echo data') d = OCcatd[utils.make_min_mask(OCcatd[:, np.newaxis, :])][:, np.newaxis, :] elif len(ste) == 1 and ste[0] == 0: LGR.info('Computing PCA of spatially concatenated multi-echo data') d = catd[mask].astype('float64') else: LGR.info('Computing PCA of echo #%s' % ','.join([str(ee) for ee in ste])) d = np.stack([catd[mask, ee] for ee in ste - 1], axis=1).astype('float64') eim = np.squeeze(eimask(d)) d = np.squeeze(d[eim]) dz = ((d.T - d.T.mean(axis=0)) / d.T.std(axis=0)).T # var normalize ts dz = (dz - dz.mean()) / dz.std() # var normalize everything if wvpca: dz, cAl = dwtmat(dz) if not op.exists('pcastate.pkl'): voxel_comp_weights, varex, comp_ts = run_svd(dz) # actual variance explained (normalized) varex_norm = varex / varex.sum() eigenvalue_elbow = getelbow(varex_norm, return_val=True) diff_varex_norm = np.abs(np.diff(varex_norm)) lower_diff_varex_norm = diff_varex_norm[(len(diff_varex_norm) // 2):] varex_norm_thr = np.mean( [lower_diff_varex_norm.max(), diff_varex_norm.min()]) varex_norm_min = varex_norm[ (len(diff_varex_norm) // 2) + np.arange(len(lower_diff_varex_norm)) [lower_diff_varex_norm >= varex_norm_thr][0] + 1] varex_norm_cum = np.cumsum(varex_norm) # Compute K 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) vTmix = comp_ts.T vTmixN = ((vTmix.T - vTmix.T.mean(0)) / vTmix.T.std(0)).T LGR.info('Making initial component selection guess from PCA results') _, ct_df, betasv, v_T = model.fitmodels_direct(catd, comp_ts.T, eimum, t2s, t2sG, tes, combmode, ref_img, mmixN=vTmixN, full_sel=False) # varex_norm overrides normalized varex computed by fitmodels_direct ct_df['normalized variance explained'] = varex_norm # Save state fname = op.abspath('pcastate.pkl') LGR.info('Saving PCA results to: {}'.format(fname)) pcastate = { 'voxel_comp_weights': voxel_comp_weights, 'varex': varex, 'comp_ts': comp_ts, 'comptable': ct_df, 'eigenvalue_elbow': eigenvalue_elbow, 'varex_norm_min': varex_norm_min, 'varex_norm_cum': varex_norm_cum } try: with open(fname, 'wb') as handle: pickle.dump(pcastate, handle) except TypeError: LGR.warning('Could not save PCA solution') else: # if loading existing state LGR.info('Loading PCA from: pcastate.pkl') with open('pcastate.pkl', 'rb') as handle: pcastate = pickle.load(handle) voxel_comp_weights, varex = pcastate['voxel_comp_weights'], pcastate[ 'varex'] comp_ts = pcastate['comp_ts'] ct_df = pcastate['comptable'] eigenvalue_elbow = pcastate['eigenvalue_elbow'] varex_norm_min = pcastate['varex_norm_min'] varex_norm_cum = pcastate['varex_norm_cum'] np.savetxt('mepca_mix.1D', comp_ts.T) # write component maps to 4D image comp_maps = np.zeros((OCcatd.shape[0], comp_ts.shape[0])) for i_comp in range(comp_ts.shape[0]): temp_comp_ts = comp_ts[i_comp, :][:, None] comp_map = utils.unmask( model.computefeats2(OCcatd, temp_comp_ts, mask), mask) comp_maps[:, i_comp] = np.squeeze(comp_map) io.filewrite(comp_maps, 'mepca_OC_components.nii', ref_img) fmin, fmid, fmax = utils.getfbounds(n_echos) kappa_thr = np.average(sorted( [fmin, getelbow(ct_df['kappa'], return_val=True) / 2, fmid]), weights=[kdaw, 1, 1]) rho_thr = np.average(sorted( [fmin, getelbow_cons(ct_df['rho'], return_val=True) / 2, fmid]), weights=[rdaw, 1, 1]) if int(kdaw) == -1: lim_idx = utils.andb([ct_df['kappa'] < fmid, ct_df['kappa'] > fmin]) == 2 kappa_lim = ct_df.loc[lim_idx, 'kappa'].values kappa_thr = kappa_lim[getelbow(kappa_lim)] lim_idx = utils.andb([ct_df['rho'] < fmid, ct_df['rho'] > fmin]) == 2 rho_lim = ct_df.loc[lim_idx, 'rho'].values rho_thr = rho_lim[getelbow(rho_lim)] stabilize = True elif int(rdaw) == -1: lim_idx = utils.andb([ct_df['rho'] < fmid, ct_df['rho'] > fmin]) == 2 rho_lim = ct_df.loc[lim_idx, 'rho'].values rho_thr = rho_lim[getelbow(rho_lim)] # Add new columns to comptable for classification ct_df['classification'] = 'accepted' ct_df['rationale'] = '' # Reject if low Kappa, Rho, and variance explained is_lowk = ct_df['kappa'] <= kappa_thr is_lowr = ct_df['rho'] <= rho_thr is_lowe = ct_df['normalized variance explained'] <= eigenvalue_elbow is_lowkre = is_lowk & is_lowr & is_lowe ct_df.loc[is_lowkre, 'classification'] = 'rejected' ct_df.loc[is_lowkre, 'rationale'] += 'low rho, kappa, and varex;' # Reject if low variance explained is_lows = ct_df['normalized variance explained'] <= varex_norm_min ct_df.loc[is_lows, 'classification'] = 'rejected' ct_df.loc[is_lows, 'rationale'] += 'low variance explained;' # Reject if Kappa over limit is_fmax1 = ct_df['kappa'] == F_MAX ct_df.loc[is_fmax1, 'classification'] = 'rejected' ct_df.loc[is_fmax1, 'rationale'] += 'kappa equals fmax;' # Reject if Rho over limit is_fmax2 = ct_df['rho'] == F_MAX ct_df.loc[is_fmax2, 'classification'] = 'rejected' ct_df.loc[is_fmax2, 'rationale'] += 'rho equals fmax;' if stabilize: temp7 = varex_norm_cum >= 0.95 ct_df.loc[temp7, 'classification'] = 'rejected' ct_df.loc[temp7, 'rationale'] += 'cumulative var. explained above 95%;' under_fmin1 = ct_df['kappa'] <= fmin ct_df.loc[under_fmin1, 'classification'] = 'rejected' ct_df.loc[under_fmin1, 'rationale'] += 'kappa below fmin;' under_fmin2 = ct_df['rho'] <= fmin ct_df.loc[under_fmin2, 'classification'] = 'rejected' ct_df.loc[under_fmin2, 'rationale'] += 'rho below fmin;' ct_df.to_csv('comp_table_pca.txt', sep='\t', index=True, index_label='component', float_format='%.6f') sel_idx = ct_df['classification'] == 'accepted' n_components = np.sum(sel_idx) voxel_kept_comp_weighted = (voxel_comp_weights[:, sel_idx] * varex[None, sel_idx]) kept_data = np.dot(voxel_kept_comp_weighted, comp_ts[sel_idx, :]) if wvpca: kept_data = idwtmat(kept_data, cAl) LGR.info('Selected {0} components with Kappa threshold: {1:.02f}, ' 'Rho threshold: {2:.02f}'.format(n_components, kappa_thr, rho_thr)) kept_data = stats.zscore(kept_data, axis=1) # variance normalize timeseries kept_data = stats.zscore(kept_data, axis=None) # variance normalize everything return n_components, kept_data
def selcomps(seldict, comptable, mmix, manacc, n_echos): """ Classify components in seldict as "accepted," "rejected," "midk," or "ignored." The selection process uses previously calculated parameters listed in `seldict` for each ICA component such as Kappa (a T2* weighting metric), Rho (an S0 weighting metric), and variance explained. See `Notes` for additional calculated metrics used to classify each component into one of the four listed groups. Parameters ---------- seldict : :obj:`dict` A dictionary with component-specific features used for classification. As output from `fitmodels_direct` comptable : (C x 5) :obj:`pandas.DataFrame` Component metric table mmix : (T x C) array_like Mixing matrix for converting input data to component space, where `C` is components and `T` is the number of volumes in the original data manacc : :obj:`list` Comma-separated list of indices of manually accepted components n_echos : :obj:`int` Number of echos in original data Returns ------- comptable : :obj:`pandas.DataFrame` Updated component table with additional metrics and with classification (accepted, rejected, midk, or ignored) Notes ----- The selection algorithm used in this function was originated in ME-ICA by Prantik Kundu, and his original implementation is available at: https://github.com/ME-ICA/me-ica/blob/b2781dd087ab9de99a2ec3925f04f02ce84f0adc/meica.libs/select_model.py This component selection process uses multiple, previously calculated metrics that include: kappa, rho, variance explained, component spatial weighting maps, noise and spatial frequency metrics, and measures of spatial overlap across metrics. Prantik began to update these selection criteria to use SVMs to distinguish components, a hypercommented version of this attempt is available at: https://gist.github.com/emdupre/ca92d52d345d08ee85e104093b81482e """ cols_at_end = ['classification', 'rationale'] comptable['classification'] = 'accepted' comptable['rationale'] = '' Z_maps = seldict['Z_maps'] Z_clmaps = seldict['Z_clmaps'] F_R2_maps = seldict['F_R2_maps'] F_S0_clmaps = seldict['F_S0_clmaps'] F_R2_clmaps = seldict['F_R2_clmaps'] Br_S0_clmaps = seldict['Br_S0_clmaps'] Br_R2_clmaps = seldict['Br_R2_clmaps'] n_vols, n_comps = mmix.shape # Set knobs LOW_PERC = 25 HIGH_PERC = 90 if n_vols < 100: EXTEND_FACTOR = 3 else: EXTEND_FACTOR = 2 RESTRICT_FACTOR = 2 # List of components midk = [] ign = [] all_comps = np.arange(comptable.shape[0]) acc = np.arange(comptable.shape[0]) # If user has specified if manacc: acc = sorted([int(vv) for vv in manacc.split(',')]) rej = sorted(np.setdiff1d(all_comps, acc)) comptable.loc[acc, 'classification'] = 'accepted' comptable.loc[rej, 'classification'] = 'rejected' comptable.loc[rej, 'rationale'] += 'I001;' # Move decision columns to end comptable = comptable[[c for c in comptable if c not in cols_at_end] + [c for c in cols_at_end if c in comptable]] return comptable """ Do some tallies for no. of significant voxels """ countnoise = np.zeros(n_comps) comptable['countsigFR2'] = F_R2_clmaps.sum(axis=0) comptable['countsigFS0'] = F_S0_clmaps.sum(axis=0) """ Make table of dice values """ comptable['dice_FR2'] = np.zeros(all_comps.shape[0]) comptable['dice_FS0'] = np.zeros(all_comps.shape[0]) for i_comp in acc: comptable.loc[i_comp, 'dice_FR2'] = utils.dice(Br_R2_clmaps[:, i_comp], F_R2_clmaps[:, i_comp]) comptable.loc[i_comp, 'dice_FS0'] = utils.dice(Br_S0_clmaps[:, i_comp], F_S0_clmaps[:, i_comp]) comptable.loc[np.isnan(comptable['dice_FR2']), 'dice_FR2'] = 0 comptable.loc[np.isnan(comptable['dice_FS0']), 'dice_FS0'] = 0 """ Make table of noise gain """ comptable['countnoise'] = 0 comptable['signal-noise_t'] = 0 comptable['signal-noise_p'] = 0 for i_comp in all_comps: comp_noise_sel = ((np.abs(Z_maps[:, i_comp]) > 1.95) & (Z_clmaps[:, i_comp] == 0)) comptable.loc[i_comp, 'countnoise'] = np.array(comp_noise_sel, dtype=np.int).sum() noise_FR2_Z = np.log10(np.unique(F_R2_maps[comp_noise_sel, i_comp])) signal_FR2_Z = np.log10( np.unique(F_R2_maps[Z_clmaps[:, i_comp] == 1, i_comp])) (comptable.loc[i_comp, 'signal-noise_t'], comptable.loc[i_comp, 'signal-noise_p']) = stats.ttest_ind(signal_FR2_Z, noise_FR2_Z, equal_var=False) comptable.loc[np.isnan(comptable['signal-noise_t']), 'signal-noise_t'] = 0 comptable.loc[np.isnan(comptable['signal-noise_p']), 'signal-noise_p'] = 0 """ Assemble decision table """ d_table_rank = np.vstack([ n_comps - stats.rankdata(comptable['kappa'], method='ordinal'), n_comps - stats.rankdata(comptable['dice_FR2'], method='ordinal'), n_comps - stats.rankdata(comptable['signal-noise_t'], method='ordinal'), stats.rankdata(countnoise, method='ordinal'), n_comps - stats.rankdata(comptable['countsigFR2'], method='ordinal') ]).T n_decision_metrics = d_table_rank.shape[1] comptable['d_table_score'] = d_table_rank.sum(axis=1) """ Step 1: Reject anything that's obviously an artifact a. Estimate a null variance """ temp_rej0 = all_comps[(comptable['rho'] > comptable['kappa']) | ( (comptable['countsigFS0'] > comptable['countsigFR2']) & (comptable['countsigFR2'] > 0))] comptable.loc[temp_rej0, 'classification'] = 'rejected' comptable.loc[temp_rej0, 'rationale'] += 'I002;' temp_rej1 = all_comps[(comptable['dice_FS0'] > comptable['dice_FR2']) & (comptable['variance explained'] > np.median( comptable['variance explained']))] comptable.loc[temp_rej1, 'classification'] = 'rejected' comptable.loc[temp_rej1, 'rationale'] += 'I003;' rej = np.union1d(temp_rej0, temp_rej1) temp_rej2 = acc[(comptable.loc[acc, 'signal-noise_t'] < 0) & (comptable.loc[acc, 'variance explained'] > np.median( comptable['variance explained']))] comptable.loc[temp_rej2, 'classification'] = 'rejected' comptable.loc[temp_rej2, 'rationale'] += 'I004;' rej = np.union1d(temp_rej2, rej) acc = np.setdiff1d(acc, rej) """ Step 2: Make a guess for what the good components are, in order to estimate good component properties a. Not outlier variance b. Kappa>kappa_elbow c. Rho<Rho_elbow d. High R2* dice compared to S0 dice e. Gain of F_R2 in clusters vs noise f. Estimate a low and high variance """ # Step 2a varex_upper_p = np.median(comptable.loc[ comptable['kappa'] > getelbow(comptable['kappa'], return_val=True), 'variance explained']) ncls = acc.copy() # NOTE: We're not sure why this is done, nor why it's specifically done # three times. Need to look into this deeper, esp. to make sure the 3 # isn't a hard-coded reference to the number of echoes. for nn in range(3): ncls = comptable.loc[ncls].loc[comptable.loc[ ncls, 'variance explained'].diff() < varex_upper_p].index.values # Compute elbows kappas_lim = comptable.loc[ comptable['kappa'] < utils.getfbounds(n_echos)[-1], 'kappa'] kappa_elbow = np.min((getelbow(kappas_lim, return_val=True), getelbow(comptable['kappa'], return_val=True))) rho_elbow = np.mean( (getelbow(comptable.loc[ncls, 'rho'], return_val=True), getelbow(comptable['rho'], return_val=True), utils.getfbounds(n_echos)[0])) # Initial guess of good components based on Kappa and Rho elbows good_guess = ncls[(comptable.loc[ncls, 'kappa'] >= kappa_elbow) & (comptable.loc[ncls, 'rho'] < rho_elbow)] if len(good_guess) == 0: LGR.warning('No BOLD-like components detected') ign = sorted(np.setdiff1d(all_comps, rej)) comptable.loc[ign, 'classification'] = 'ignored' comptable.loc[ign, 'rationale'] += 'I005;' # Move decision columns to end comptable = comptable[[c for c in comptable if c not in cols_at_end] + [c for c in cols_at_end if c in comptable]] return comptable kappa_rate = ((np.max(comptable.loc[good_guess, 'kappa']) - np.min(comptable.loc[good_guess, 'kappa'])) / (np.max(comptable.loc[good_guess, 'variance explained']) - np.min(comptable.loc[good_guess, 'variance explained']))) kappa_ratios = kappa_rate * comptable['variance explained'] / comptable[ 'kappa'] varex_lower = stats.scoreatpercentile( comptable.loc[good_guess, 'variance explained'], LOW_PERC) varex_upper = stats.scoreatpercentile( comptable.loc[good_guess, 'variance explained'], HIGH_PERC) """ Step 3: Get rid of midk components; i.e., those with higher than max decision score and high variance """ max_good_d_score = EXTEND_FACTOR * len(good_guess) * n_decision_metrics midk = acc[(comptable.loc[acc, 'd_table_score'] > max_good_d_score) & (comptable.loc[acc, 'variance explained'] > EXTEND_FACTOR * varex_upper)] comptable.loc[midk, 'classification'] = 'rejected' comptable.loc[midk, 'rationale'] += 'I006;' acc = np.setdiff1d(acc, midk) """ Step 4: Find components to ignore """ good_guess = np.setdiff1d(good_guess, midk) loaded = np.union1d( good_guess, acc[comptable.loc[acc, 'variance explained'] > varex_lower]) ign = np.setdiff1d(acc, loaded) ign = np.setdiff1d( ign, ign[comptable.loc[ign, 'd_table_score'] < max_good_d_score]) ign = np.setdiff1d(ign, ign[comptable.loc[ign, 'kappa'] > kappa_elbow]) comptable.loc[ign, 'classification'] = 'ignored' comptable.loc[ign, 'rationale'] += 'I007;' acc = np.setdiff1d(acc, ign) """ Step 5: Scrub the set """ if len(acc) > len(good_guess): # Recompute the midk steps on the limited set to clean up the tail d_table_rank = np.vstack([ len(acc) - stats.rankdata(comptable.loc[acc, 'kappa'], method='ordinal'), len(acc) - stats.rankdata(comptable.loc[acc, 'dice_FR2'], method='ordinal'), len(acc) - stats.rankdata(comptable.loc[acc, 'signal-noise_t'], method='ordinal'), stats.rankdata(countnoise[acc], method='ordinal'), len(acc) - stats.rankdata(comptable.loc[acc, 'countsigFR2'], method='ordinal') ]).T comptable['d_table_score_scrub'] = np.nan comptable.loc[acc, 'd_table_score_scrub'] = d_table_rank.sum(1) num_acc_guess = int( np.mean([ np.sum((comptable.loc[acc, 'kappa'] > kappa_elbow) & (comptable.loc[acc, 'rho'] < rho_elbow)), np.sum(comptable.loc[acc, 'kappa'] > kappa_elbow) ])) conservative_guess = num_acc_guess * n_decision_metrics / RESTRICT_FACTOR # Rejection candidate based on artifact type A: candartA candartA = np.intersect1d( acc[comptable.loc[acc, 'd_table_score_scrub'] > conservative_guess], acc[kappa_ratios[acc] > EXTEND_FACTOR * 2]) candartA = np.intersect1d( candartA, candartA[comptable.loc[candartA, 'variance explained'] > varex_upper * EXTEND_FACTOR]) comptable.loc[candartA, 'classification'] = 'rejected' comptable.loc[candartA, 'rationale'] += 'I008;' midk = np.union1d(midk, candartA) # Rejection candidate based on artifact type B: candartB candartB = comptable.loc[acc].loc[ comptable.loc[acc, 'd_table_score_scrub'] > num_acc_guess * n_decision_metrics * HIGH_PERC / 100.].index.values candartB = np.intersect1d( candartB, candartB[comptable.loc[candartB, 'variance explained'] > varex_lower * EXTEND_FACTOR]) midk = np.union1d(midk, candartB) comptable.loc[candartB, 'classification'] = 'rejected' comptable.loc[candartB, 'rationale'] += 'I009;' # Find comps to ignore new_varex_lower = stats.scoreatpercentile( comptable.loc[acc[:num_acc_guess], 'variance explained'], LOW_PERC) candart = comptable.loc[acc].loc[ comptable.loc[acc, 'd_table_score'] > num_acc_guess * n_decision_metrics].index.values ign_add0 = np.intersect1d( candart[comptable.loc[candart, 'variance explained'] > new_varex_lower], candart) ign_add0 = np.setdiff1d(ign_add0, midk) comptable.loc[ign_add0, 'classification'] = 'ignored' comptable.loc[ign_add0, 'rationale'] += 'I010;' ign = np.union1d(ign, ign_add0) ign_add1 = np.intersect1d( acc[comptable.loc[acc, 'kappa'] <= kappa_elbow], acc[comptable.loc[acc, 'variance explained'] > new_varex_lower]) ign_add1 = np.setdiff1d(ign_add1, midk) comptable.loc[ign_add1, 'classification'] = 'ignored' comptable.loc[ign_add1, 'rationale'] += 'I011;' ign = np.union1d(ign, ign_add1) acc = np.setdiff1d(acc, np.union1d(midk, ign)) # Move decision columns to end comptable = comptable[[c for c in comptable if c not in cols_at_end] + [c for c in cols_at_end if c in comptable]] return comptable
def selcomps(seldict, comptable, mmix, manacc, n_echos): """ Classify components in seldict as "accepted," "rejected," or "ignored." The selection process uses previously calculated parameters listed in `seldict` for each ICA component such as Kappa (a T2* weighting metric), Rho (an S0 weighting metric), and variance explained. See `Notes` for additional calculated metrics used to classify each component into one of the four listed groups. Parameters ---------- seldict : :obj:`dict` A dictionary with component-specific features used for classification. As output from `fitmodels_direct` comptable : (C x X) :obj:`pandas.DataFrame` Component metric table. One row for each component, with a column for each metric. The index should be the component number. mmix : (T x C) array_like Mixing matrix for converting input data to component space, where `C` is components and `T` is the number of volumes in the original data manacc : :obj:`list` Comma-separated list of indices of manually accepted components n_echos : :obj:`int` Number of echos in original data Returns ------- comptable : :obj:`pandas.DataFrame` Updated component table with additional metrics and with classification (accepted, rejected, or ignored) Notes ----- The selection algorithm used in this function was originated in ME-ICA by Prantik Kundu, and his original implementation is available at: https://github.com/ME-ICA/me-ica/blob/b2781dd087ab9de99a2ec3925f04f02ce84f0adc/meica.libs/select_model.py This component selection process uses multiple, previously calculated metrics that include: kappa, rho, variance explained, component spatial weighting maps, noise and spatial frequency metrics, and measures of spatial overlap across metrics. Prantik began to update these selection criteria to use SVMs to distinguish components, a hypercommented version of this attempt is available at: https://gist.github.com/emdupre/ca92d52d345d08ee85e104093b81482e """ cols_at_end = ['classification', 'rationale'] # Lists of components all_comps = np.arange(comptable.shape[0]) # unclf is a full list that is whittled down over criteria # since the default classification is "accepted", at the end of the tree # the remaining elements in unclf are classified as accepted unclf = all_comps.copy() # If user has specified if manacc: LGR.info('Performing manual ICA component selection') if ('classification' in comptable.columns and 'original_classification' not in comptable.columns): comptable['original_classification'] = comptable['classification'] comptable['original_rationale'] = comptable['rationale'] comptable['classification'] = 'accepted' comptable['rationale'] = '' acc = [int(comp) for comp in manacc] rej = sorted(np.setdiff1d(all_comps, acc)) comptable.loc[acc, 'classification'] = 'accepted' comptable.loc[rej, 'classification'] = 'rejected' comptable.loc[rej, 'rationale'] += 'I001;' # Move decision columns to end comptable = comptable[[c for c in comptable if c not in cols_at_end] + [c for c in cols_at_end if c in comptable]] comptable['rationale'] = comptable['rationale'].str.rstrip(';') return comptable comptable['classification'] = 'accepted' comptable['rationale'] = '' Z_maps = seldict['Z_maps'] Z_clmaps = seldict['Z_clmaps'] F_R2_maps = seldict['F_R2_maps'] F_S0_clmaps = seldict['F_S0_clmaps'] F_R2_clmaps = seldict['F_R2_clmaps'] Br_S0_clmaps = seldict['Br_S0_clmaps'] Br_R2_clmaps = seldict['Br_R2_clmaps'] # Set knobs n_vols, n_comps = mmix.shape LOW_PERC = 25 HIGH_PERC = 90 if n_vols < 100: EXTEND_FACTOR = 3 else: EXTEND_FACTOR = 2 RESTRICT_FACTOR = 2 """ Tally number of significant voxels for cluster-extent thresholded R2 and S0 model F-statistic maps. """ comptable['countsigFR2'] = F_R2_clmaps.sum(axis=0) comptable['countsigFS0'] = F_S0_clmaps.sum(axis=0) """ Generate Dice values for R2 and S0 models - dice_FR2: Dice value of cluster-extent thresholded maps of R2-model betas and F-statistics. - dice_FS0: Dice value of cluster-extent thresholded maps of S0-model betas and F-statistics. """ comptable['dice_FR2'] = np.zeros(all_comps.shape[0]) comptable['dice_FS0'] = np.zeros(all_comps.shape[0]) for i_comp in all_comps: comptable.loc[i_comp, 'dice_FR2'] = utils.dice(Br_R2_clmaps[:, i_comp], F_R2_clmaps[:, i_comp]) comptable.loc[i_comp, 'dice_FS0'] = utils.dice(Br_S0_clmaps[:, i_comp], F_S0_clmaps[:, i_comp]) comptable.loc[np.isnan(comptable['dice_FR2']), 'dice_FR2'] = 0 comptable.loc[np.isnan(comptable['dice_FS0']), 'dice_FS0'] = 0 """ Generate three metrics of component noise: - countnoise: Number of "noise" voxels (voxels highly weighted for component, but not from clusters) - signal-noise_t: T-statistic for two-sample t-test of F-statistics from "signal" voxels (voxels in clusters) against "noise" voxels (voxels not in clusters) for R2 model. - signal-noise_p: P-value from t-test. """ comptable['countnoise'] = 0 comptable['signal-noise_t'] = 0 comptable['signal-noise_p'] = 0 for i_comp in all_comps: # index voxels significantly loading on component but not from clusters comp_noise_sel = ((np.abs(Z_maps[:, i_comp]) > 1.95) & (Z_clmaps[:, i_comp] == 0)) comptable.loc[i_comp, 'countnoise'] = np.array( comp_noise_sel, dtype=np.int).sum() # NOTE: Why only compare distributions of *unique* F-statistics? noise_FR2_Z = np.log10(np.unique(F_R2_maps[comp_noise_sel, i_comp])) signal_FR2_Z = np.log10(np.unique( F_R2_maps[Z_clmaps[:, i_comp] == 1, i_comp])) (comptable.loc[i_comp, 'signal-noise_t'], comptable.loc[i_comp, 'signal-noise_p']) = stats.ttest_ind( signal_FR2_Z, noise_FR2_Z, equal_var=False) comptable.loc[np.isnan(comptable['signal-noise_t']), 'signal-noise_t'] = 0 comptable.loc[np.isnan(comptable['signal-noise_p']), 'signal-noise_p'] = 0 """ Assemble decision table with five metrics: - Kappa values ranked from largest to smallest - R2-model F-score map/beta map Dice scores ranked from largest to smallest - Signal F > Noise F t-statistics ranked from largest to smallest - Number of "noise" voxels (voxels highly weighted for component, but not from clusters) ranked from smallest to largest - Number of voxels with significant R2-model F-scores within clusters ranked from largest to smallest Smaller values (i.e., higher ranks) across metrics indicate more BOLD dependence and less noise. """ d_table_rank = np.vstack([ n_comps - stats.rankdata(comptable['kappa']), n_comps - stats.rankdata(comptable['dice_FR2']), n_comps - stats.rankdata(comptable['signal-noise_t']), stats.rankdata(comptable['countnoise']), n_comps - stats.rankdata(comptable['countsigFR2'])]).T comptable['d_table_score'] = d_table_rank.mean(axis=1) """ Step 1: Reject anything that's obviously an artifact a. Estimate a null variance """ # Rho is higher than Kappa temp_rej0a = all_comps[(comptable['rho'] > comptable['kappa'])] comptable.loc[temp_rej0a, 'classification'] = 'rejected' comptable.loc[temp_rej0a, 'rationale'] += 'I002;' # Number of significant voxels for S0 model is higher than number for R2 # model *and* number for R2 model is greater than zero. temp_rej0b = all_comps[((comptable['countsigFS0'] > comptable['countsigFR2']) & (comptable['countsigFR2'] > 0))] comptable.loc[temp_rej0b, 'classification'] = 'rejected' comptable.loc[temp_rej0b, 'rationale'] += 'I003;' rej = np.union1d(temp_rej0a, temp_rej0b) # Dice score for S0 maps is higher than Dice score for R2 maps and variance # explained is higher than the median across components. temp_rej1 = all_comps[(comptable['dice_FS0'] > comptable['dice_FR2']) & (comptable['variance explained'] > np.median(comptable['variance explained']))] comptable.loc[temp_rej1, 'classification'] = 'rejected' comptable.loc[temp_rej1, 'rationale'] += 'I004;' rej = np.union1d(temp_rej1, rej) # T-value is less than zero (noise has higher F-statistics than signal in # map) and variance explained is higher than the median across components. temp_rej2 = unclf[(comptable.loc[unclf, 'signal-noise_t'] < 0) & (comptable.loc[unclf, 'variance explained'] > np.median(comptable['variance explained']))] comptable.loc[temp_rej2, 'classification'] = 'rejected' comptable.loc[temp_rej2, 'rationale'] += 'I005;' rej = np.union1d(temp_rej2, rej) unclf = np.setdiff1d(unclf, rej) """ Step 2: Make a guess for what the good components are, in order to estimate good component properties a. Not outlier variance b. Kappa>kappa_elbow c. Rho<Rho_elbow d. High R2* dice compared to S0 dice e. Gain of F_R2 in clusters vs noise f. Estimate a low and high variance """ # Step 2a # Upper limit for variance explained is median across components with high # Kappa values. High Kappa is defined as Kappa above Kappa elbow. varex_upper_p = np.median( comptable.loc[comptable['kappa'] > getelbow(comptable['kappa'], return_val=True), 'variance explained']) ncls = unclf.copy() # NOTE: We're not sure why this is done, nor why it's specifically done # three times. Need to look into this deeper, esp. to make sure the 3 # isn't a hard-coded reference to the number of echoes. # Reduce components to investigate as "good" to ones in which change in # variance explained is less than the limit defined above.... What? for i_loop in range(3): ncls = comptable.loc[ncls].loc[ comptable.loc[ ncls, 'variance explained'].diff() < varex_upper_p].index.values # Compute elbows from other elbows f05, _, f01 = utils.getfbounds(n_echos) kappas_nonsig = comptable.loc[comptable['kappa'] < f01, 'kappa'] # NOTE: Would an elbow from all Kappa values *ever* be lower than one from # a subset of lower values? kappa_elbow = np.min((getelbow(kappas_nonsig, return_val=True), getelbow(comptable['kappa'], return_val=True))) rho_elbow = np.mean((getelbow(comptable.loc[ncls, 'rho'], return_val=True), getelbow(comptable['rho'], return_val=True), f05)) # Provisionally accept components based on Kappa and Rho elbows acc_prov = ncls[(comptable.loc[ncls, 'kappa'] >= kappa_elbow) & (comptable.loc[ncls, 'rho'] < rho_elbow)] if len(acc_prov) == 0: LGR.warning('No BOLD-like components detected') ign = sorted(np.setdiff1d(all_comps, rej)) comptable.loc[ign, 'classification'] = 'ignored' comptable.loc[ign, 'rationale'] += 'I006;' # Move decision columns to end comptable = comptable[[c for c in comptable if c not in cols_at_end] + [c for c in cols_at_end if c in comptable]] comptable['rationale'] = comptable['rationale'].str.rstrip(';') return comptable # Calculate "rate" for kappa: kappa range divided by variance explained # range, for potentially accepted components # NOTE: What is the logic behind this? kappa_rate = ((np.max(comptable.loc[acc_prov, 'kappa']) - np.min(comptable.loc[acc_prov, 'kappa'])) / (np.max(comptable.loc[acc_prov, 'variance explained']) - np.min(comptable.loc[acc_prov, 'variance explained']))) comptable['kappa ratio'] = kappa_rate * comptable['variance explained'] / comptable['kappa'] varex_lower = stats.scoreatpercentile( comptable.loc[acc_prov, 'variance explained'], LOW_PERC) varex_upper = stats.scoreatpercentile( comptable.loc[acc_prov, 'variance explained'], HIGH_PERC) """ Step 3: Get rid of midk components; i.e., those with higher than max decision score and high variance """ max_good_d_score = EXTEND_FACTOR * len(acc_prov) midk = unclf[(comptable.loc[unclf, 'd_table_score'] > max_good_d_score) & (comptable.loc[unclf, 'variance explained'] > EXTEND_FACTOR * varex_upper)] comptable.loc[midk, 'classification'] = 'rejected' comptable.loc[midk, 'rationale'] += 'I007;' unclf = np.setdiff1d(unclf, midk) acc_prov = np.setdiff1d(acc_prov, midk) """ Step 4: Find components to ignore """ # collect high variance unclassified components # and mix of high/low provisionally accepted high_varex = np.union1d( acc_prov, unclf[comptable.loc[unclf, 'variance explained'] > varex_lower]) # ignore low variance components ign = np.setdiff1d(unclf, high_varex) # but only if they have bad decision scores ign = np.setdiff1d( ign, ign[comptable.loc[ign, 'd_table_score'] < max_good_d_score]) # and low kappa ign = np.setdiff1d(ign, ign[comptable.loc[ign, 'kappa'] > kappa_elbow]) comptable.loc[ign, 'classification'] = 'ignored' comptable.loc[ign, 'rationale'] += 'I008;' unclf = np.setdiff1d(unclf, ign) """ Step 5: Scrub the set if there are components that haven't been rejected or ignored, but are still not listed in the provisionally accepted group. """ if len(unclf) > len(acc_prov): comptable['d_table_score_scrub'] = np.nan # Recompute the midk steps on the limited set to clean up the tail d_table_rank = np.vstack([ len(unclf) - stats.rankdata(comptable.loc[unclf, 'kappa']), len(unclf) - stats.rankdata(comptable.loc[unclf, 'dice_FR2']), len(unclf) - stats.rankdata(comptable.loc[unclf, 'signal-noise_t']), stats.rankdata(comptable.loc[unclf, 'countnoise']), len(unclf) - stats.rankdata(comptable.loc[unclf, 'countsigFR2'])]).T comptable.loc[unclf, 'd_table_score_scrub'] = d_table_rank.mean(1) num_acc_guess = int(np.mean([ np.sum((comptable.loc[unclf, 'kappa'] > kappa_elbow) & (comptable.loc[unclf, 'rho'] < rho_elbow)), np.sum(comptable.loc[unclf, 'kappa'] > kappa_elbow)])) # Rejection candidate based on artifact type A: candartA conservative_guess = num_acc_guess / RESTRICT_FACTOR candartA = np.intersect1d( unclf[comptable.loc[unclf, 'd_table_score_scrub'] > conservative_guess], unclf[comptable.loc[unclf, 'kappa ratio'] > EXTEND_FACTOR * 2]) candartA = (candartA[comptable.loc[candartA, 'variance explained'] > varex_upper * EXTEND_FACTOR]) comptable.loc[candartA, 'classification'] = 'rejected' comptable.loc[candartA, 'rationale'] += 'I009;' midk = np.union1d(midk, candartA) unclf = np.setdiff1d(unclf, midk) # Rejection candidate based on artifact type B: candartB conservative_guess2 = num_acc_guess * HIGH_PERC / 100. candartB = unclf[comptable.loc[unclf, 'd_table_score_scrub'] > conservative_guess2] candartB = (candartB[comptable.loc[candartB, 'variance explained'] > varex_lower * EXTEND_FACTOR]) comptable.loc[candartB, 'classification'] = 'rejected' comptable.loc[candartB, 'rationale'] += 'I010;' midk = np.union1d(midk, candartB) unclf = np.setdiff1d(unclf, midk) # Find components to ignore # Ignore high variance explained, poor decision tree scored components new_varex_lower = stats.scoreatpercentile( comptable.loc[unclf[:num_acc_guess], 'variance explained'], LOW_PERC) candart = unclf[comptable.loc[unclf, 'd_table_score_scrub'] > num_acc_guess] ign_add0 = candart[comptable.loc[candart, 'variance explained'] > new_varex_lower] ign_add0 = np.setdiff1d(ign_add0, midk) comptable.loc[ign_add0, 'classification'] = 'ignored' comptable.loc[ign_add0, 'rationale'] += 'I011;' ign = np.union1d(ign, ign_add0) unclf = np.setdiff1d(unclf, ign) # Ignore low Kappa, high variance explained components ign_add1 = np.intersect1d( unclf[comptable.loc[unclf, 'kappa'] <= kappa_elbow], unclf[comptable.loc[unclf, 'variance explained'] > new_varex_lower]) ign_add1 = np.setdiff1d(ign_add1, midk) comptable.loc[ign_add1, 'classification'] = 'ignored' comptable.loc[ign_add1, 'rationale'] += 'I012;' # at this point, unclf is equivalent to accepted # Move decision columns to end comptable = comptable[[c for c in comptable if c not in cols_at_end] + [c for c in cols_at_end if c in comptable]] comptable['rationale'] = comptable['rationale'].str.rstrip(';') return comptable