diff --git a/hyperalignment/searchlight.py b/hyperalignment/searchlight.py deleted file mode 100644 index fcc9f1e..0000000 --- a/hyperalignment/searchlight.py +++ /dev/null @@ -1,50 +0,0 @@ -import numpy as np -from joblib import Parallel, delayed - -from hyperalignment.procrustes import procrustes -from hyperalignment.local_template import compute_template - - -def compute_searchlight_weights(sls, dists, radius): - """ - weights = compute_searchlight_weights(sls, dists, radius) - """ - nv = len(sls) - weights_sum = np.zeros((nv, )) - for sl, d in zip(sls, dists): - w = (radius - d) / radius - weights_sum[sl] += w - # print(np.percentile(weights_sum, np.linspace(0, 100, 11))) - weights = [] - for sl, d in zip(sls, dists): - w = (radius - d) / radius - w /= weights_sum[sl] - weights.append(w) - return weights - - -def searchlight_procrustes(X, Y, sls, dists, radius, T0=None, reflection=True, scaling=False, weighted=True): - T = np.zeros((X.shape[1], Y.shape[1])) if T0 is None else T0.copy() - if weighted: - weights = compute_searchlight_weights(sls, dists, radius) - for sl, w in zip(sls, weights): - t = procrustes(X[:, sl], Y[:, sl], reflection=reflection, scaling=scaling) - T[np.ix_(sl, sl)] += t * w[np.newaxis] - else: - for sl in sls: - t = procrustes(X[:, sl], Y[:, sl], reflection=reflection, scaling=scaling) - T[np.ix_(sl, sl)] += t - return T - - -def searchlight_template(dss, sls, dists, radius, n_jobs=1, tmpl_kind='pca'): - weights = compute_searchlight_weights(sls, dists, radius) - with Parallel(n_jobs=n_jobs, batch_size=1, verbose=1) as parallel: - local_templates = parallel( - delayed(compute_template)(dss, sl=sl, kind=tmpl_kind, max_npc=len(sl), common_topography=True) - for sl in sls) - - tmpl = np.zeros_like(dss[0]) - for local_template, w, sl in zip(local_templates, weights, sls): - tmpl[:, sl] += local_template * w[np.newaxis] - return tmpl diff --git a/hyperalignment/sparse.py b/hyperalignment/sparse.py deleted file mode 100644 index 12c7c3e..0000000 --- a/hyperalignment/sparse.py +++ /dev/null @@ -1,29 +0,0 @@ -import numpy as np -from scipy import sparse - - -def initialize_sparse_matrix(sls, nv=None, dtype=np.float64): - """Initialize a sparse matrix based on the searchlights. - - Parameters - ---------- - sls : list - A list of searchlights. Each entry is an integer array comprising the indices of a searchlight. - nv : int, optional - Number of vertices, by default None. The sparse matrix has a shape of (nv, nv). - dtype : dtype, optional - The dtype of the generated sparse matrix, by default np.float64 - - Returns - ------- - mat : csc_matrix - The initialized sparse matrix which allows fast computations for searchlight algorithms. All of its elements are 0's. - """ - if nv is None: - nv = np.concatenate(sls).max() + 1 - mat = sparse.lil_matrix((nv, nv), dtype=dtype) - for sl in sls: - mat[np.ix_(sl, sl)] = 1. - mat = mat.tocsc() - mat.data = np.zeros_like(mat.data, dtype=mat.data.dtype) - return mat diff --git a/movie_datasets/__init__.py b/movie_datasets/__init__.py deleted file mode 100644 index 95b80d3..0000000 --- a/movie_datasets/__init__.py +++ /dev/null @@ -1,247 +0,0 @@ -import os -from glob import glob -import numpy as np -import pandas as pd -from scipy.stats import zscore - -DIR = os.path.dirname(os.path.realpath(__file__)) -DATA_ROOT = os.path.join(DIR, 'data') - - -class MovieDataset(object): - def __init__(self, dset_name, flavor, version, surf_type='fsaverage', masked=False): - self.name = dset_name - self.flavor = flavor - self.version = version - self.surf_type = surf_type - self.masked = masked - - self.data_dir = f'{DATA_ROOT}/{dset_name}_{version}/preprocessed_correct/{flavor}' - self.sid_tasks = {} - for fn in glob(f'{self.data_dir}/*.npy'): - parts = os.path.basename(fn)[:-4].split('_') - if len(parts) == 4: - sid, lr, task, run = parts - elif len(parts) == 5: - sid, lr, task, ses, run = parts - if sid not in self.sid_tasks: - self.sid_tasks[sid] = set() - self.sid_tasks[sid].add(task) - self.all_subjects = sorted(self.sid_tasks.keys()) - self.subject_sets = { - 'all': self.all_subjects, - } - if not self.masked: - if self.surf_type == 'fsaverage': - self.masks = [np.load(os.path.join(DIR, 'fsaverage_lh_mask.npy')), - np.load(os.path.join(DIR, 'fsaverage_rh_mask.npy'))] - elif self.surf_type == 'fsaverage5': - self.masks = [np.load(os.path.join(DIR, 'fsaverage5_lh_mask.npy')), - np.load(os.path.join(DIR, 'fsaverage5_rh_mask.npy'))] - - def load_data(self, sid, lr, task, run, chop=True, z=True, mask=True): - fn = f'{self.data_dir}/{sid}_{lr}h_{task}_{run:02d}.npy' - data = np.load(fn) - if mask: - if not self.masked: - m = self.masks['lr'.index(lr)][:data.shape[1]] - data = data[:, m] - else: - if self.masked: - raise ValueError - if z: - data = np.nan_to_num(zscore(data, axis=0)) - return data - - def load_subj_movie_data(self, sid, lr, runs=None, chop=True, z=True, mask=True, return_lengths=False): - ds = [] - if runs is None: - for task_name, task_runs in self.task_info: - if task_name == self.movie_task: - runs = task_runs - break - for run in runs: - d = self.load_data(sid, lr, self.movie_task, run, chop=chop, z=z, mask=mask) - ds.append(d) - lengths = [d.shape[0] for d in ds] - ds = np.concatenate(ds, axis=0) - if return_lengths: - return ds, lengths - return ds - - def load_movie_data(self, lr, runs, chop=True, z=True, mask=True, group='all'): - dss = [] - for sid in self.subject_sets[group]: - dss.append(self.load_subj_movie_data(sid, lr, runs, chop=chop, z=z, mask=mask)) - dss = np.stack(dss, axis=0) - return dss - - # def load_subj_all_data(self, sid, lr, chop=True, z=True, mask=True): - # ds = [] - # lengths = [] - # for task, runs in self.task_info: - # for run in runs: - # d = self.load_data(sid, lr, task, run, chop=chop, z=z, mask=mask) - # lengths.append(d.shape[0]) - # ds.append(d) - # ds = np.concatenate(ds, axis=0) - # lengths = np.array(lengths) - # return ds, lengths - - -# To use the old 1.4.1 version of the dataset: -# HyperfaceDataset(version='1-4-1', masked=True) -class HyperfaceDataset(MovieDataset): - def __init__(self, flavor='fmriprep_global-mc-reg_renamed', version='20-1-1', surf_type='fsaverage', masked=False): - super().__init__(dset_name='hyperface', flavor=flavor, version=version, surf_type=surf_type, masked=masked) - self.movie_task = 'budapest' - self.task_info = [ - ['budapest', (1, 2, 3, 4, 5)], - ['localizer', (1, 2, 3, 4)], - ] - - -class SiemensRaidersDataset(MovieDataset): - def __init__(self, flavor='fmriprep_global-mc-reg', version='20-2-0', surf_type='fsaverage', masked=True): - super().__init__(dset_name='siemens-raiders', flavor=flavor, version=version, surf_type=surf_type, masked=masked) - self.movie_task = 'movie' - self.task_info = [ - ['movie', (1, 2, 3, 4)], - ['actions', (1, 2, 3, 4, 5, 6, 7, 8)], - ] - # 8 + 8 + 7 subjects, 7 + 7 + 6 with localizers - self.subject_sets['fold1_1'] = ['sid000005', 'sid000007', 'sid000009', 'sid000010', 'sid000012', 'sid000013', 'sid000020', 'sid000021'] - self.subject_sets['fold1_2'] = ['sid000024', 'sid000029', 'sid000034', 'sid000052', 'sid000102', 'sid000114', 'sid000120', 'sid000134', 'sid000142', 'sid000278', 'sid000416', 'sid000433', 'sid000499', 'sid000522', 'sid000535'] - self.subject_sets['fold2_1'] = ['sid000024', 'sid000029', 'sid000034', 'sid000052', 'sid000102', 'sid000114', 'sid000120', 'sid000134'] - self.subject_sets['fold2_2'] = ['sid000005', 'sid000007', 'sid000009', 'sid000010', 'sid000012', 'sid000013', 'sid000020', 'sid000021', 'sid000142', 'sid000278', 'sid000416', 'sid000433', 'sid000499', 'sid000522', 'sid000535'] - self.subject_sets['fold3_1'] = ['sid000142', 'sid000278', 'sid000416', 'sid000433', 'sid000499', 'sid000522', 'sid000535'] - self.subject_sets['fold3_2'] = ['sid000005', 'sid000007', 'sid000009', 'sid000010', 'sid000012', 'sid000013', 'sid000020', 'sid000021', 'sid000024', 'sid000029', 'sid000034', 'sid000052', 'sid000102', 'sid000114', 'sid000120', 'sid000134'] - - def load_data(self, sid, lr, task, run, chop=True, z=True, mask=True): - fn = f'{self.data_dir}/{sid}_{lr}h_{task}_{run:02d}.npy' - data = np.load(fn) - if mask: - if not self.masked: - m = self.masks['lr'.index(lr)][:data.shape[1]] - data = data[:, m] - else: - if self.masked: - raise ValueError - if chop: - if task == 'movie': - if run == 1: - data = data[:-10] - elif run == 4: - data = data[10:] - else: - data = data[10:-10] - if z: - data = np.nan_to_num(zscore(data, axis=0)) - return data - - -class ForrestDataset(MovieDataset): - def __init__(self, flavor='fmriprep_global-mc-reg', version='20-1-1', surf_type='fsaverage'): - super().__init__(dset_name='forrest', flavor=flavor, version=version, surf_type=surf_type) - self.movie_task = 'movie' - self.task_info = [ - ['movie', (1, 2, 3, 4, 5, 6, 7, 8)], - ['objectcategories', (1, 2, 3, 4)], - ['retmapccw', (1, )], - ['retmapclw', (1, )], - ['retmapcon', (1, )], - ['retmapexp', (1, )], - ] - self.subject_sets['fold1_1'] = ['01', '02', '03', '04', '05'] - self.subject_sets['fold1_2'] = ['06', '09', '10', '14', '15', '16', '17', '18', '19', '20'] - self.subject_sets['fold2_1'] = ['06', '09', '10', '14', '15'] - self.subject_sets['fold2_2'] = ['01', '02', '03', '04', '05', '16', '17', '18', '19', '20'] - self.subject_sets['fold3_1'] = ['16', '17', '18', '19', '20'] - self.subject_sets['fold3_2'] = ['01', '02', '03', '04', '05', '06', '09', '10', '14', '15'] - - -class ID1000Dataset(MovieDataset): - def __init__(self, flavor='fmriprep_global-mc-reg', version='1-4-1', surf_type='fsaverage5', masked=True): - super().__init__(dset_name='id1000', flavor=flavor, version=version, surf_type=surf_type, masked=masked) - self.movie_task = 'movie' - self.task_info = [ - ['movie', (1, )], - ] - - def get_df(self, sids=None): - df_fn = f'{DIR}/id1000.tsv' # originally `ds003097/participants.tsv` - df = pd.read_csv(df_fn, index_col='participant_id', sep='\t') - if sids is not None: - df = df.loc[[f'sub-{_}' for _ in sids]] - return df - - -class CamCANDataset(MovieDataset): - def __init__(self, flavor='fmriprep_global-mc-reg', version='20-2-0', surf_type='fsaverage', masked=True): - super().__init__(dset_name='camcan', flavor=flavor, version=version, surf_type=surf_type, masked=masked) - self.movie_task = 'movie' - self.task_info = [ - ['movie', (1, )], - ] - for name in ['half1', 'half2']: - with open(f'{DIR}/camcan_{name}.txt', 'r') as f: - sids = f.read().splitlines() - self.subject_sets[name] = sids - - def get_df(self, sids=None): - df_fn = f'{DIR}/camcan.pkl' - df = pd.read_pickle(df_fn) - if sids is not None: - df = df.loc[sids] - # df['Sex'], uniques = pd.factorize(df['Sex'], sort=True) - # print(uniques) - df['Sex'] = df['Sex'].map({'FEMALE': -1, 'MALE': 1}) - return df - - -class RaidersDataset(MovieDataset): - def __init__(self, flavor='fmriprep_global-mc-reg', version='20-1-1', surf_type='fsaverage'): - super().__init__(dset_name='raiders', flavor=flavor, version=version, surf_type=surf_type) - self.movie_task = 'raiders' - self.task_info = [ - ['raiders', (1, 2, 3, 4, 5, 6, 7, 8)], - ['localizer', (1, 2, 3, 4)], - ] - self.subject_sets['all'] = [sid for sid in self.all_subjects if 'raiders' in self.sid_tasks[sid]] - self.subject_sets['8ch'] = [ - 'rid000005', 'rid000011', 'rid000014', 'rid000015', 'rid000020', - 'rid000028', 'rid000029', 'rid000033', 'rid000038', 'rid000042', - 'rid000043'] - self.subject_sets['32ch'] = [ - 'rid000001', 'rid000008', 'rid000009', 'rid000012', 'rid000013', - 'rid000016', 'rid000017', 'rid000018', 'rid000019', 'rid000021', - 'rid000022', 'rid000024', 'rid000025', 'rid000026', 'rid000027', - 'rid000031', 'rid000032', 'rid000036', 'rid000037', 'rid000041'] - - def load_data(self, sid, lr, task, run, chop=True, z=True, mask=True): - fn = f'{self.data_dir}/{sid}_{lr}h_{task}_{run:02d}.npy' - data = np.load(fn) - if mask: - m = self.masks['lr'.index(lr)][:data.shape[1]] - data = data[:, m] - if chop: - if task == 'raiders' and run != 1: - data = data[8:] - elif task == 'retmapping': - data = data[10:90] - if z: - data = np.nan_to_num(zscore(data, axis=0)) - return data - - def load_subj_all_data(self): - raise NotImplementedError - - -class WhiplashDataset(MovieDataset): - def __init__(self, flavor='fmriprep_global-mc-reg', version='20-0-3', surf_type='fsaverage'): - super().__init__(dset_name='whiplash', flavor=flavor, version=version, surf_type=surf_type) - self.movie_task = 'whiplash' - self.task_info = [ - ['whiplash', (1, 2)], - ] - self.subject_sets['all'] = [sid for sid in self.all_subjects if 'whiplash' in self.sid_tasks[sid]] diff --git a/movie_datasets/fsaverage5_lh_mask.npy b/movie_datasets/fsaverage5_lh_mask.npy deleted file mode 100644 index a232b60..0000000 Binary files a/movie_datasets/fsaverage5_lh_mask.npy and /dev/null differ diff --git a/movie_datasets/fsaverage5_rh_mask.npy b/movie_datasets/fsaverage5_rh_mask.npy deleted file mode 100644 index 38076e7..0000000 Binary files a/movie_datasets/fsaverage5_rh_mask.npy and /dev/null differ diff --git a/movie_datasets/fsaverage6_lh_mask.npy b/movie_datasets/fsaverage6_lh_mask.npy deleted file mode 100644 index 2b9d84a..0000000 Binary files a/movie_datasets/fsaverage6_lh_mask.npy and /dev/null differ diff --git a/movie_datasets/fsaverage6_rh_mask.npy b/movie_datasets/fsaverage6_rh_mask.npy deleted file mode 100644 index aaf7464..0000000 Binary files a/movie_datasets/fsaverage6_rh_mask.npy and /dev/null differ diff --git a/movie_datasets/fsaverage_lh_mask.npy b/movie_datasets/fsaverage_lh_mask.npy deleted file mode 100644 index 92ae30c..0000000 Binary files a/movie_datasets/fsaverage_lh_mask.npy and /dev/null differ diff --git a/movie_datasets/fsaverage_rh_mask.npy b/movie_datasets/fsaverage_rh_mask.npy deleted file mode 100644 index 543546a..0000000 Binary files a/movie_datasets/fsaverage_rh_mask.npy and /dev/null differ diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..638dd9c --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,3 @@ +[build-system] +requires = ["setuptools>=61.0"] +build-backend = "setuptools.build_meta" diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..9c88bca --- /dev/null +++ b/setup.cfg @@ -0,0 +1,44 @@ +[metadata] +name = hyperalignment +version = 0.1.1 +author = Ma Feilong +author_email = mafeilong@gmail.com +description = Hyperalignment algorithms for functional alignment of fMRI data. +long_description = file: README.md +long_description_content_type = text/markdown +keywords = hyperalignment, mvpa, brain, fmri, neuroscience, neuroimaging +url = https://feilong.github.io/hyperalignment/ +project_urls = + Bug Tracker = https://github.com/feilong/hyperalignment/issues + Source Code = https://github.com/feilong/hyperalignment +classifiers = + Programming Language :: Python :: 3 :: Only + Programming Language :: Python :: 3.6 + Programming Language :: Python :: 3.7 + Programming Language :: Python :: 3.8 + Programming Language :: Python :: 3.9 + Programming Language :: Python :: 3.10 + +[options] +package_dir = + = src +packages = find: +python_requires = >=3.6 +include_package_data = True +scripts = + bin/npls + bin/rmdirs + +install_requires = + numpy + scipy + scikit-learn + +[options.package_data] + +[options.packages.find] +where = src + +[options.extras_require] +tests = + pytest diff --git a/setup.py b/setup.py deleted file mode 100644 index ea70d9d..0000000 --- a/setup.py +++ /dev/null @@ -1,8 +0,0 @@ -from setuptools import setup, find_packages - -setup( - name='hyperalignment', - version='0.1', - packages=find_packages(), - scripts=['bin/npls', 'bin/rmdirs'], -) diff --git a/src/hyperalignment/__init__.py b/src/hyperalignment/__init__.py new file mode 100644 index 0000000..9c42247 --- /dev/null +++ b/src/hyperalignment/__init__.py @@ -0,0 +1,7 @@ +from .procrustes import procrustes +from .searchlight import compute_searchlight_weights as searchlight_weights +from .searchlight import searchlight_hyperalignment, searchlight_procrustes, searchlight_ridge, searchlight_template +from .ridge import ridge, ridge_grid, ensemble_ridge +from .local_template import compute_template +from .ensemble import compute_ensemble_indices +from .sparse import initialize_sparse_matrix diff --git a/hyperalignment/ensemble.py b/src/hyperalignment/ensemble.py similarity index 65% rename from hyperalignment/ensemble.py rename to src/hyperalignment/ensemble.py index 3ab946d..8c2d57e 100644 --- a/hyperalignment/ensemble.py +++ b/src/hyperalignment/ensemble.py @@ -1,4 +1,5 @@ import numpy as np +from joblib import Parallel, delayed def compute_ensemble_indices(nt, n_perms=10, n_folds=5, blocksize=4, buffersize=4, seed=0, mask=None): @@ -50,3 +51,38 @@ def compute_ensemble_indices(nt, n_perms=10, n_folds=5, blocksize=4, buffersize= test_idx_li.append(test_idx) return train_idx_li, test_idx_li + + +def searchlight_hyperalignment_for_ensemble(X, Y, train_idx, sls, sl_weights, mat0, sl_func): + X = X[train_idx] + Y = Y[train_idx] + xmat = mat0.copy() + for sl, w in zip(sls, sl_weights): + t = sl_func(X[:, sl], Y[:, sl]) + xmat[np.ix_(sl, sl)] += t * w[np.newaxis] + return xmat.data + + +def ensemble_searchlight_hyperalignment( + X, Y, sls, sl_weights, mat0, train_idx_li, test_idx_li, sl_func, n_jobs=1): + + with Parallel(n_jobs=n_jobs, verbose=1) as parallel: + results = parallel( + delayed(searchlight_hyperalignment_for_ensemble)( + X, Y, train_idx, sls, sl_weights, mat0, sl_func) + for train_idx in train_idx_li) + + nt, nv = Y.shape + counts = np.zeros((nt, ), dtype=int) + Yhat = np.zeros_like(y) + for d, test_idx in zip(results, test_idx_li): + xmat = mat0.copy() + xmat.data = d + Yhat[test_idx] += X[test_idx] @ T + counts[test_idx] += 1 + Yhat /= counts[:, np.newaxis] + + xmat = mat0.copy() + xmat.data = np.mean(results, axis=0) + + return xmat, Yhat diff --git a/hyperalignment/linalg.py b/src/hyperalignment/linalg.py similarity index 100% rename from hyperalignment/linalg.py rename to src/hyperalignment/linalg.py diff --git a/hyperalignment/local_template.py b/src/hyperalignment/local_template.py similarity index 58% rename from hyperalignment/local_template.py rename to src/hyperalignment/local_template.py index 52af7ff..232439f 100644 --- a/hyperalignment/local_template.py +++ b/src/hyperalignment/local_template.py @@ -1,6 +1,6 @@ import numpy as np -from scipy.stats import zscore from scipy.linalg import LinAlgError +from scipy.stats import zscore from sklearn.decomposition import PCA from sklearn.utils.extmath import randomized_svd @@ -8,7 +8,9 @@ from hyperalignment.procrustes import procrustes -def PCA_decomposition(dss, max_npc=None, flavor='sklearn', adjust_ns=False, demean=True): +def PCA_decomposition( + dss, max_npc=None, flavor="sklearn", adjust_ns=False, demean=True +): """Decompose concatenated data matrices using PCA/SVD. Parameters @@ -30,7 +32,7 @@ def PCA_decomposition(dss, max_npc=None, flavor='sklearn', adjust_ns=False, deme X = dss.transpose(1, 0, 2).reshape(nt, ns * nv) if max_npc is not None: max_npc = min(max_npc, min(X.shape[0], X.shape[1])) - if flavor == 'sklearn': + if flavor == "sklearn": try: if demean: pca = PCA(n_components=max_npc, random_state=0) @@ -40,7 +42,11 @@ def PCA_decomposition(dss, max_npc=None, flavor='sklearn', adjust_ns=False, deme XX /= np.sqrt(ns) return XX, cc else: - U, s, Vt = randomized_svd(X, (max_npc if max_npc is not None else min(X.shape)), random_state=0) + U, s, Vt = randomized_svd( + X, + (max_npc if max_npc is not None else min(X.shape)), + random_state=0, + ) if adjust_ns: XX = U[:, :max_npc] * (s[np.newaxis, :max_npc] / np.sqrt(ns)) else: @@ -48,8 +54,10 @@ def PCA_decomposition(dss, max_npc=None, flavor='sklearn', adjust_ns=False, deme cc = Vt[:max_npc].reshape(-1, ns, nv) return XX, cc except LinAlgError as e: - return PCA_decomposition(dss, max_npc=max_npc, flavor='svd', adjust_ns=adjust_ns, demean=demean) - elif flavor == 'svd': + return PCA_decomposition( + dss, max_npc=max_npc, flavor="svd", adjust_ns=adjust_ns, demean=demean + ) + elif flavor == "svd": U, s, Vt = safe_svd(X, demean=demean) if adjust_ns: XX = U[:, :max_npc] * (s[np.newaxis, :max_npc] / np.sqrt(ns)) @@ -61,34 +69,109 @@ def PCA_decomposition(dss, max_npc=None, flavor='sklearn', adjust_ns=False, deme raise NotImplementedError -def compute_PCA_template(dss, sl=None, max_npc=None, flavor='sklearn', demean=True): +def compute_PCA_template(dss, sl=None, max_npc=None, flavor="sklearn", demean=True): if sl is not None: dss = dss[:, :, sl] - XX, cc = PCA_decomposition(dss, max_npc=max_npc, flavor=flavor, adjust_ns=True, demean=demean) + XX, cc = PCA_decomposition( + dss, max_npc=max_npc, flavor=flavor, adjust_ns=True, demean=demean + ) return XX -def compute_PCA_var1_template(dss, sl=None, max_npc=None, flavor='sklearn', demean=True): +def compute_PCA_var1_template( + dss, sl=None, max_npc=None, flavor="sklearn", demean=True +): if sl is not None: dss = dss[:, :, sl] - XX, cc = PCA_decomposition(dss, max_npc=max_npc, flavor=flavor, adjust_ns=False, demean=demean) + XX, cc = PCA_decomposition( + dss, max_npc=max_npc, flavor=flavor, adjust_ns=False, demean=demean + ) w = np.sqrt(np.sum(cc**2, axis=2)).mean(axis=1) XX *= w[np.newaxis] return XX -def compute_PCA_var2_template(dss, sl=None, max_npc=None, flavor='sklearn', demean=True): +def compute_PCA_var2_template( + dss, sl=None, max_npc=None, flavor="sklearn", demean=True +): if sl is not None: dss = dss[:, :, sl] - XX, cc = PCA_decomposition(dss, max_npc=max_npc, flavor=flavor, adjust_ns=False, demean=demean) + XX, cc = PCA_decomposition( + dss, max_npc=max_npc, flavor=flavor, adjust_ns=False, demean=demean + ) # w = np.sqrt(np.sum(cc**2, axis=2)).mean(axis=1) w = np.exp(0.5 * np.log(np.sum(cc**2, axis=2)).mean(axis=1)) XX *= w[np.newaxis] return XX +def compute_GPA_template( + dss, + sl=None, + reflection=True, + scaling=False, + zscore_common=True, + level2_iter=1, + dss2=None, + **kwargs +): + if sl is not None: + dss = dss[:, :, sl] + + common_space = np.mean(dss, axis=0) + if zscore_common: + common_space = np.nan_to_num(zscore(common_space, axis=0)) + + aligned_dss = [] + for ds in dss: + T = procrustes(ds, common_space, reflection=reflection, scaling=scaling) + aligned_ds = ds.dot(T) + if zscore_common: + aligned_ds = np.nan_to_num(zscore(aligned_ds, axis=0)) + aligned_dss.append(aligned_ds) + + aligned_dss2 = [] + for level2 in range(level2_iter): + common_space = np.zeros_like(dss[0]) + for ds in aligned_dss: + common_space += ds + for i, ds in enumerate(dss): + reference = (common_space - aligned_dss[i]) / float(len(dss) - 1) + if zscore_common: + reference = np.nan_to_num(zscore(reference, axis=0)) + T = procrustes(ds, reference, reflection=reflection, scaling=scaling) + if level2 == level2_iter - 1 and dss2 is not None: + aligned_dss2.append(dss2[i].dot(T)) + aligned_dss[i] = ds.dot(T) + + common_space = np.sum(aligned_dss, axis=0) + if zscore_common: + common_space = np.nan_to_num(zscore(common_space, axis=0)) + else: + common_space /= float(len(dss)) + if dss2 is not None: + common_space2 = np.zeros_like(dss2[0]) + for ds in aligned_dss2: + common_space2 += ds + if zscore_common: + common_space2 = np.nan_to_num(zscore(common_space2, axis=0)) + else: + common_space2 /= float(len(dss)) + return common_space, common_space2 + + return common_space + + def compute_procrustes_template( - dss, sl=None, reflection=True, scaling=False, zscore_common=True, level2_iter=1, dss2=None, **kwargs): + dss, + sl=None, + reflection=True, + scaling=False, + zscore_common=True, + level2_iter=1, + dss2=None, + **kwargs +): if sl is not None: dss = dss[:, :, sl] common_space = np.copy(dss[0]) @@ -138,15 +221,19 @@ def compute_procrustes_template( return common_space -def compute_template(dss, sl=None, kind='procrustes', max_npc=None, common_topography=False, demean=False): +def compute_template( + dss, sl=None, kind="procrustes", max_npc=None, common_topography=False, demean=False +): mapping = { - 'pca': compute_PCA_template, - 'pcav1': compute_PCA_var1_template, - 'pcav2': compute_PCA_var2_template, - 'cls': compute_procrustes_template, + "pca": compute_PCA_template, + "pcav1": compute_PCA_var1_template, + "pcav2": compute_PCA_var2_template, + "cls": compute_procrustes_template, } - if kind == 'procrustes': - tmpl = compute_procrustes_template(dss=dss, sl=sl, reflection=True, scaling=False, zscore_common=True) + if kind == "procrustes": + tmpl = compute_procrustes_template( + dss=dss, sl=sl, reflection=True, scaling=False, zscore_common=True + ) elif kind in mapping: tmpl = mapping[kind](dss=dss, sl=sl, max_npc=max_npc, demean=demean) else: @@ -156,14 +243,16 @@ def compute_template(dss, sl=None, kind='procrustes', max_npc=None, common_topog if sl is not None: dss = dss[:, :, sl] ns, nt, nv = dss.shape - T = procrustes(np.tile(tmpl, (ns, 1)), dss.reshape(ns*nt, nv)) + T = procrustes(np.tile(tmpl, (ns, 1)), dss.reshape(ns * nt, nv)) tmpl = tmpl @ T return tmpl -if __name__ == '__main__': +if __name__ == "__main__": from scipy.stats import zscore + from hyperalignment.linalg import svd_pca + rng = np.random.default_rng(0) dss = rng.standard_normal((1, 200, 100)) dss = zscore(dss, axis=1) diff --git a/hyperalignment/procrustes.py b/src/hyperalignment/procrustes.py similarity index 89% rename from hyperalignment/procrustes.py rename to src/hyperalignment/procrustes.py index 0a18f98..0a61cbf 100644 --- a/hyperalignment/procrustes.py +++ b/src/hyperalignment/procrustes.py @@ -73,12 +73,3 @@ def procrustes(X, Y, reflection=True, scaling=False): T *= scale return T - - -def searchlight_procrustes(X, Y, sls, reflection=True, scaling=False): - counts = np.zeros((X.shape[1], )) - T = np.zeros((X.shape[1], Y.shape[1])) - for sl in sls: - T[np.ix_(sl, sl)] += procrustes(X[:, sl], Y[:, sl], reflection=reflection, scaling=scaling) - counts[sl] += 1 - return T, counts diff --git a/hyperalignment/ridge.py b/src/hyperalignment/ridge.py similarity index 91% rename from hyperalignment/ridge.py rename to src/hyperalignment/ridge.py index 8c8a31d..9131425 100644 --- a/hyperalignment/ridge.py +++ b/src/hyperalignment/ridge.py @@ -4,6 +4,14 @@ from hyperalignment.linalg import safe_svd +def ridge(X, Y, alpha): + U, s, Vt = safe_svd(X, remove_mean=False) + d = s / (alpha + s**2) + d_UT_Y = d[:, np.newaxis] * (U.T @ Y) + betas = Vt.T @ d_UT_Y + return betas + + def ridge_grid(X, y, alphas, npcs, train_idx=None): if train_idx is not None: X = X[train_idx] diff --git a/src/hyperalignment/searchlight.py b/src/hyperalignment/searchlight.py new file mode 100644 index 0000000..6ed43da --- /dev/null +++ b/src/hyperalignment/searchlight.py @@ -0,0 +1,236 @@ +import functools + +import numpy as np +import scipy.sparse as sparse +from joblib import Parallel, delayed + +from hyperalignment.local_template import compute_template +from hyperalignment.procrustes import procrustes +from hyperalignment.ridge import ridge + + +def compute_searchlight_weights(sls, dists=None, radius=None, return_sparse=False): + """ + Compute the weights used for combining searchlight models. + If `dists` is None, uniform weights are used. + If `dists` is provided, distance-based weights are computed, where the + weight for each vertex is highest at the center of the searchlight and + decreases linearly to zero at the edge of the searchlight. + + Typical usage: + >>> weights = compute_searchlight_weights(sls, dists, radius) + >>> mat = compute_searchlight_weights( + ... sls, dists, radius, return_sparse=True) + + Parameters + ---------- + sls : list of ndarrays + Searchlight indices, where each ndarray contains the indices of the + vertices in the searchlight. + dists : list of ndarrays or None, default=None + Each array contains the distances of the vertices in the searchlight + to the center of the searchlight, used for distance-based weighting. + If None, uniform weights are used. + radius : float or None, default=None + The radius of the searchlight, used for distance-based weighting. + + Returns + ------- + weights : list of ndarrays, optional + Each ndarray contains the weights for the vertices in the corresponding + searchlight. The weights sum to 1 for each vertex. Returned only if + `return_sparse` is False. + mat : sparse matrix, optional + A sparse matrix where each row corresponds to a searchlight and each + column corresponds to a vertex. Returned only if `return_sparse` is + True. + """ + nv = int(np.concatenate(sls).max()) + 1 + weights_sum = np.zeros((nv,)) + weights = [] + + if dists is None: + for sl in sls: + weights_sum[sl] += 1 + + for sl in sls: + w = 1.0 / weights_sum[sl] + weights.append(w) + + else: + # If dists is provided, use distance-based weighting + assert radius is not None, "Radius must be provided if distances are given." + for sl, d in zip(sls, dists): + w = (radius - d) / radius + weights_sum[sl] += w + + for sl, d in zip(sls, dists): + w = (radius - d) / radius + w /= weights_sum[sl] + weights.append(w) + + if return_sparse: + mat = sparse.lil_array((len(sls), nv)) + for i, w in enumerate(weights): + mat[i, sls[i]] = w + mat = mat.tocsr() + return mat + + return weights + + +def searchlight_hyperalignment( + X, Y, sls, sls_Y=None, sl_func=None, mat0=None, weights=None +): + """ + Searchlight hyperalignment. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features_X) + The first data matrix, to be aligned to ``Y``. + Y : ndarray of shape (n_samples, n_features_Y) + The second data matrix, the target for alignment. + sls : list of ndarrays + Each ndarray contains the indices of the vertices in the searchlight + for the first data matrix. + sls_Y : list of ndarrays or None, default=None + Searchlight indices for the second data matrix, if different from + ``sls``. + sl_func : callable + A function that takes two arrays and computes the transformation + between them. + mat0 : sparse matrix or None, default=None + The sparse matrix to initialize the transformation, because changing + sparse matrix sparsity is very slow. If None, initialize using a dense + array of zeros. + weights : list of ndarrays or None, default=None + Weights for combining searchlight transformations. If None, simply add + the transformations without weighting. + + Returns + ------- + mat : sparse matrix or ndarray + The resulting transformation matrix, where each row corresponds to a + vertex in ``X`` and each column corresponds to a vertex in ``Y``. + """ + if sls_Y is None: + sls_Y = sls + + mat = np.zeros((X.shape[1], Y.shape[1])) if mat0 is None else mat0.copy() + + if weights is not None: + for sl_X, sl_Y, w in zip(sls, sls_Y, weights): + t = sl_func(X[:, sl_X], Y[:, sl_Y]) + mat[np.ix_(sl_X, sl_Y)] += t * w[np.newaxis] + else: + for sl_X, sl_Y in zip(sls, sls_Y): + t = sl_func(X[:, sl_X], Y[:, sl_Y]) + mat[np.ix_(sl_X, sl_Y)] += t + return mat + + +def searchlight_procrustes( + X, Y, sls, sls_Y=None, mat0=None, reflection=True, scaling=False, weights=None +): + """ + Searchlight hyperalignment using orthogonal Procrustes. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features_X) + The first data matrix, to be aligned to ``Y``. + Y : ndarray of shape (n_samples, n_features_Y) + The second data matrix, the target for alignment. + sls : list of ndarrays + Each ndarray contains the indices of the vertices in the searchlight + for the first data matrix. + sls_Y : list of ndarrays or None, default=None + Searchlight indices for the second data matrix, if different from + ``sls``. + mat0 : sparse matrix or None, default=None + The sparse matrix to initialize the transformation, because changing + sparse matrix sparsity is very slow. If None, initialize using a dense + array of zeros. + reflection : bool, default=True + Whether allows reflection in the transformation (True) or not (False). + scaling : bool, default=False + Whether allows global scaling (True) or not (False). + weights : list of ndarrays or None, default=None + Weights for combining searchlight transformations. If None, simply add + the transformations without weighting. + + Returns + ------- + mat : sparse matrix or ndarray + The resulting transformation matrix, where each row corresponds to a + vertex in ``X`` and each column corresponds to a vertex in ``Y``. + """ + sl_func = functools.partial(procrustes, reflection=reflection, scaling=scaling) + xfm = searchlight_hyperalignment( + X, Y, sls, sls_Y=sls_Y, sl_func=sl_func, mat0=mat0, weights=weights + ) + return xfm + + +def searchlight_ridge(X, Y, sls, sls_Y=None, mat0=None, alpha=1e3, weights=None): + """ + Searchlight hyperalignment using ridge regression. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features_X) + The first data matrix, to be aligned to ``Y``. + Y : ndarray of shape (n_samples, n_features_Y) + The second data matrix, the target for alignment. + sls : list of ndarrays + Each ndarray contains the indices of the vertices in the searchlight + for the first data matrix. + sls_Y : list of ndarrays or None, default=None + Searchlight indices for the second data matrix, if different from + ``sls``. + mat0 : sparse matrix or None, default=None + The sparse matrix to initialize the transformation, because changing + sparse matrix sparsity is very slow. If None, initialize using a dense + array of zeros. + alpha : float, default=1e3 + The regularization parameter for ridge regression. + weights : list of ndarrays or None, default=None + Weights for combining searchlight transformations. If None, simply add + the transformations without weighting. + + Returns + ------- + mat : sparse matrix or ndarray + The resulting transformation matrix, where each row corresponds to a + vertex in ``X`` and each column corresponds to a vertex in ``Y``. + """ + sl_func = functools.partial(ridge, alpha=alpha) + xfm = searchlight_hyperalignment( + X, Y, sls, sls_Y=sls_Y, sl_func=sl_func, mat0=mat0, weights=weights + ) + return xfm + + +def searchlight_template(dms, sls, dists, radius, n_jobs=1, tpl_kind="pca"): + weights = compute_searchlight_weights(sls, dists, radius) + tpl = np.zeros_like(dms[0]) + + if n_jobs == 1: + for sl, w in zip(sls, weights): + local_template = compute_template( + dms, sl=sl, kind=tpl_kind, max_npc=len(sl), common_topography=True + ) + tpl[:, sl] += local_template * w[np.newaxis] + else: + with Parallel(n_jobs=n_jobs, batch_size=1, verbose=1) as parallel: + local_templates = parallel( + delayed(compute_template)( + dms, sl=sl, kind=tpl_kind, max_npc=len(sl), common_topography=True + ) + for sl in sls + ) + + for local_template, w, sl in zip(local_templates, weights, sls): + tpl[:, sl] += local_template * w[np.newaxis] + return tpl diff --git a/src/hyperalignment/sparse.py b/src/hyperalignment/sparse.py new file mode 100644 index 0000000..0f3735d --- /dev/null +++ b/src/hyperalignment/sparse.py @@ -0,0 +1,55 @@ +import os +import numpy as np +from scipy import sparse + + +def initialize_sparse_matrix(sls, nv=None, dtype=np.float64, cache_fn=None): + """Initialize a sparse matrix based on the searchlights. + + Parameters + ---------- + sls : list + A list of searchlights. Each entry is an integer array comprising the indices of a searchlight. + nv : int, optional + Number of vertices, by default None. The sparse matrix has a shape of (nv, nv). + dtype : dtype, optional + The dtype of the generated sparse matrix, by default np.float64 + cache_fn : {None, str} + The file name of the cached sparse matrix. If the file exists, it will + be loaded to avoid repeated computations. If it is `None`, no cached + file will be used and the matrix will be computed. + + Returns + ------- + mat : csc_matrix + The initialized sparse matrix which allows fast computations for searchlight algorithms. All of its elements are 0's. + """ + if cache_fn is not None and os.path.exists(cache_fn): + return sparse.load_npz(cache_fn) + if len(sls): + indices = np.concatenate(sls).astype(np.int64) + else: + indices = np.zeros(0, dtype=np.int64) + if nv is None: + if not len(indices): + raise ValueError("`nv` must be specified when `sls` is empty.") + nv = int(indices.max()) + 1 + # The CSR constructor below does not check bounds, so validate them here. + if len(indices) and (indices.min() < 0 or indices.max() >= nv): + raise IndexError(f"Searchlight indices must be in [0, {nv}) for nv={nv}.") + + # Membership matrix: row i is the indicator of searchlight i. The product + # B.T @ B is nonzero exactly where two vertices share a searchlight, which + # is the sparsity pattern of a searchlight model. + indptr = np.zeros(len(sls) + 1, dtype=np.int64) + np.cumsum([len(sl) for sl in sls], out=indptr[1:]) + data = np.ones(len(indices), dtype=np.float32) + B = sparse.csr_matrix((data, indices, indptr), shape=(len(sls), nv)) + + mat = (B.T @ B).tocsc() + mat.sum_duplicates() + mat.data = np.zeros(mat.nnz, dtype=dtype) + if cache_fn is not None: + os.makedirs(os.path.dirname(cache_fn), exist_ok=True) + sparse.save_npz(cache_fn, mat) + return mat diff --git a/tests/test_searchlight.py b/tests/test_searchlight.py new file mode 100644 index 0000000..2a0241a --- /dev/null +++ b/tests/test_searchlight.py @@ -0,0 +1,60 @@ +import neuroboros as nb +import numpy as np + +from hyperalignment.searchlight import compute_searchlight_weights + + +class TestSearchlightWeights: + def test_uniform_weights(self): + sls = nb.sls("l", 20) + weights = compute_searchlight_weights(sls) + + nv = int(np.concatenate(sls).max()) + 1 + weights_sum = np.zeros((nv,)) + + for sl, w in zip(sls, weights): + weights_sum[sl] += w + + np.testing.assert_allclose(weights_sum, 1.0) + + def test_distance_weights(self): + radius = 20 + sls, dists = nb.sls("l", radius, return_dists=True) + weights = compute_searchlight_weights(sls, dists, radius) + + nv = int(np.concatenate(sls).max()) + 1 + weights_sum = np.zeros((nv,)) + + for sl, w in zip(sls, weights): + weights_sum[sl] += w + + np.testing.assert_allclose(weights_sum, 1.0) + + def test_sparse_searchlights(self): + sls = nb.sls("l", 20, "onavg-ico64", center_space="onavg-ico32") + weights = compute_searchlight_weights(sls) + + nv = int(np.concatenate(sls).max()) + 1 + weights_sum = np.zeros((nv,)) + + for sl, w in zip(sls, weights): + weights_sum[sl] += w + + np.testing.assert_allclose(weights_sum, 1.0) + + def test_sparse_output(self): + radius = 20 + sls, dists = nb.sls("l", radius, return_dists=True) + weights = compute_searchlight_weights(sls, dists, radius, return_sparse=True) + + assert weights.shape[0] == len(sls) + assert weights.shape[1] == int(np.concatenate(sls).max()) + 1 + + np.testing.assert_allclose(weights.sum(axis=0), 1.0) + + weights = compute_searchlight_weights(sls, return_sparse=True) + + assert weights.shape[0] == len(sls) + assert weights.shape[1] == int(np.concatenate(sls).max()) + 1 + + np.testing.assert_allclose(weights.sum(axis=0), 1.0) diff --git a/tests/test_sparse.py b/tests/test_sparse.py new file mode 100644 index 0000000..df9606e --- /dev/null +++ b/tests/test_sparse.py @@ -0,0 +1,76 @@ +import warnings + +import neuroboros as nb +import numpy as np +import pytest +from scipy import sparse + +from hyperalignment.sparse import initialize_sparse_matrix + + +def reference(sls, nv): + """The original lil_matrix-based construction.""" + mat = sparse.lil_matrix((nv, nv)) + for sl in sls: + mat[np.ix_(sl, sl)] = 1.0 + mat = mat.tocsc() + mat.data = np.zeros_like(mat.data) + return mat + + +class TestInitializeSparseMatrix: + def test_same_structure_as_reference(self): + sls = nb.sls("l", 10) + nv = int(np.concatenate(sls).max()) + 1 + mat = initialize_sparse_matrix(sls) + ref = reference(sls, nv) + + assert mat.format == "csc" + assert mat.shape == ref.shape == (nv, nv) + assert mat.nnz == ref.nnz + np.testing.assert_array_equal(mat.indptr, ref.indptr) + np.testing.assert_array_equal(mat.indices, ref.indices) + assert mat.has_canonical_format + assert mat.dtype == np.float64 + assert not mat.data.any() + + def test_nv_and_dtype(self): + sls = nb.sls("l", 10) + nv = int(np.concatenate(sls).max()) + 100 + mat = initialize_sparse_matrix(sls, nv=nv, dtype=np.float32) + assert mat.shape == (nv, nv) + assert mat.dtype == np.float32 + + def test_block_assignment_keeps_sparsity(self): + sls = nb.sls("l", 10) + mat = initialize_sparse_matrix(sls) + nnz = mat.nnz + with warnings.catch_warnings(): + warnings.simplefilter("error", sparse.SparseEfficiencyWarning) + for sl in sls[:10]: + mat[np.ix_(sl, sl)] += np.ones((len(sl), len(sl))) + assert mat.nnz == nnz + + def test_cache(self, tmp_path): + sls = nb.sls("l", 10) + cache_fn = str(tmp_path / "sub" / "mat0.npz") + mat = initialize_sparse_matrix(sls, cache_fn=cache_fn) + cached = initialize_sparse_matrix(sls, cache_fn=cache_fn) + assert cached.format == "csc" + assert cached.shape == mat.shape + np.testing.assert_array_equal(cached.indptr, mat.indptr) + np.testing.assert_array_equal(cached.indices, mat.indices) + + def test_out_of_range_indices(self): + with pytest.raises(IndexError): + initialize_sparse_matrix([np.array([0, 3])], nv=3) + with pytest.raises(IndexError): + initialize_sparse_matrix([np.array([-1, 0])], nv=3) + + def test_empty_searchlights(self): + mat = initialize_sparse_matrix([], nv=3) + assert mat.format == "csc" + assert mat.shape == (3, 3) + assert mat.nnz == 0 + with pytest.raises(ValueError): + initialize_sparse_matrix([])