From 8952c746a72a980d09f90e4954d193065ecb6d6f Mon Sep 17 00:00:00 2001 From: Feilong Ma Date: Sat, 30 Jul 2022 07:53:04 -0400 Subject: [PATCH 01/14] Switch to modern package structure. --- pyproject.toml | 6 +++ setup.cfg | 44 +++++++++++++++++++ setup.py | 8 ---- src/hyperalignment/__init__.py | 0 .../hyperalignment}/ensemble.py | 0 .../hyperalignment}/linalg.py | 0 .../hyperalignment}/local_template.py | 0 .../hyperalignment}/procrustes.py | 0 .../hyperalignment}/ridge.py | 0 .../hyperalignment}/searchlight.py | 0 .../hyperalignment}/sparse.py | 0 11 files changed, 50 insertions(+), 8 deletions(-) create mode 100644 pyproject.toml create mode 100644 setup.cfg delete mode 100644 setup.py create mode 100644 src/hyperalignment/__init__.py rename {hyperalignment => src/hyperalignment}/ensemble.py (100%) rename {hyperalignment => src/hyperalignment}/linalg.py (100%) rename {hyperalignment => src/hyperalignment}/local_template.py (100%) rename {hyperalignment => src/hyperalignment}/procrustes.py (100%) rename {hyperalignment => src/hyperalignment}/ridge.py (100%) rename {hyperalignment => src/hyperalignment}/searchlight.py (100%) rename {hyperalignment => src/hyperalignment}/sparse.py (100%) diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..374b58c --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,6 @@ +[build-system] +requires = [ + "setuptools>=42", + "wheel" +] +build-backend = "setuptools.build_meta" diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..eac93d4 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,44 @@ +[metadata] +name = hyperalignment +version = 0.1.0 +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..e69de29 diff --git a/hyperalignment/ensemble.py b/src/hyperalignment/ensemble.py similarity index 100% rename from hyperalignment/ensemble.py rename to src/hyperalignment/ensemble.py 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 100% rename from hyperalignment/local_template.py rename to src/hyperalignment/local_template.py diff --git a/hyperalignment/procrustes.py b/src/hyperalignment/procrustes.py similarity index 100% rename from hyperalignment/procrustes.py rename to src/hyperalignment/procrustes.py diff --git a/hyperalignment/ridge.py b/src/hyperalignment/ridge.py similarity index 100% rename from hyperalignment/ridge.py rename to src/hyperalignment/ridge.py diff --git a/hyperalignment/searchlight.py b/src/hyperalignment/searchlight.py similarity index 100% rename from hyperalignment/searchlight.py rename to src/hyperalignment/searchlight.py diff --git a/hyperalignment/sparse.py b/src/hyperalignment/sparse.py similarity index 100% rename from hyperalignment/sparse.py rename to src/hyperalignment/sparse.py From 98437ddaeff9cbf47eb84f9137b3d653d6ad075b Mon Sep 17 00:00:00 2001 From: Feilong Ma Date: Sun, 31 Jul 2022 19:03:09 -0400 Subject: [PATCH 02/14] Add simple implementation of WHA. --- src/hyperalignment/ridge.py | 8 ++++++++ src/hyperalignment/searchlight.py | 22 +++++++++++++++++++--- 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/src/hyperalignment/ridge.py b/src/hyperalignment/ridge.py index 8c8a31d..9131425 100644 --- a/src/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 index fcc9f1e..2330443 100644 --- a/src/hyperalignment/searchlight.py +++ b/src/hyperalignment/searchlight.py @@ -1,7 +1,9 @@ import numpy as np +import functools from joblib import Parallel, delayed from hyperalignment.procrustes import procrustes +from hyperalignment.ridge import ridge from hyperalignment.local_template import compute_template @@ -23,20 +25,34 @@ def compute_searchlight_weights(sls, dists, radius): return weights -def searchlight_procrustes(X, Y, sls, dists, radius, T0=None, reflection=True, scaling=False, weighted=True): +def searchlight_hyperalignment(X, Y, sls, dists, radius, T0, sl_func, 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 = sl_func(X[:, sl], Y[:, sl]) 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 = sl_func(X[:, sl], Y[:, sl]) T[np.ix_(sl, sl)] += t return T +def searchlight_procrustes(X, Y, sls, dists, radius, T0=None, reflection=True, scaling=False, weighted=True): + sl_func = functools.partial(procrustes, reflection=reflection, scaling=scaling) + T = searchlight_hyperalignment( + X, Y, sls, dists, radius, T0=T0, sl_func=sl_func, weighted=weighted) + return T + + +def searchlight_ridge(X, Y, sls, dists, radius, T0=None, alpha=1e3, weighted=True): + sl_func = functools.partial(ridge, alpha=alpha) + T = searchlight_hyperalignment( + X, Y, sls, dists, radius, T0=T0, sl_func=sl_func, weighted=weighted) + 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: From 9beb34f74d3f4cd62ac35c6a585c5f8150ff286c Mon Sep 17 00:00:00 2001 From: Ma Feilong Date: Wed, 7 Sep 2022 14:46:21 -0400 Subject: [PATCH 03/14] Fix estimating the number of vertices. --- src/hyperalignment/searchlight.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/hyperalignment/searchlight.py b/src/hyperalignment/searchlight.py index 2330443..f943a21 100644 --- a/src/hyperalignment/searchlight.py +++ b/src/hyperalignment/searchlight.py @@ -11,7 +11,7 @@ def compute_searchlight_weights(sls, dists, radius): """ weights = compute_searchlight_weights(sls, dists, radius) """ - nv = len(sls) + nv = np.concatenate(sls).max() + 1 weights_sum = np.zeros((nv, )) for sl, d in zip(sls, dists): w = (radius - d) / radius From 5cb632b0ab7a2175e5b487f025bcfec32eb2be48 Mon Sep 17 00:00:00 2001 From: Ma Feilong Date: Wed, 7 Sep 2022 14:47:05 -0400 Subject: [PATCH 04/14] Allow caching sparse matrices. --- src/hyperalignment/sparse.py | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/hyperalignment/sparse.py b/src/hyperalignment/sparse.py index 12c7c3e..6fc3f8e 100644 --- a/src/hyperalignment/sparse.py +++ b/src/hyperalignment/sparse.py @@ -1,8 +1,9 @@ +import os import numpy as np from scipy import sparse -def initialize_sparse_matrix(sls, nv=None, dtype=np.float64): +def initialize_sparse_matrix(sls, nv=None, dtype=np.float64, cache_fn=None): """Initialize a sparse matrix based on the searchlights. Parameters @@ -13,12 +14,18 @@ def initialize_sparse_matrix(sls, nv=None, dtype=np.float64): 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 nv is None: nv = np.concatenate(sls).max() + 1 mat = sparse.lil_matrix((nv, nv), dtype=dtype) @@ -26,4 +33,7 @@ def initialize_sparse_matrix(sls, nv=None, dtype=np.float64): mat[np.ix_(sl, sl)] = 1. mat = mat.tocsc() mat.data = np.zeros_like(mat.data, dtype=mat.data.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 From f42a0e6dc59108b594e3ea4687bfabddc79d0d28 Mon Sep 17 00:00:00 2001 From: Ma Feilong Date: Wed, 7 Sep 2022 22:47:08 -0400 Subject: [PATCH 05/14] Ensemble searchlight hyperalignment algorithm. --- src/hyperalignment/ensemble.py | 38 ++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/src/hyperalignment/ensemble.py b/src/hyperalignment/ensemble.py index 3ab946d..78bfaae 100644 --- a/src/hyperalignment/ensemble.py +++ b/src/hyperalignment/ensemble.py @@ -1,4 +1,7 @@ import numpy as np +from joblib import Parallel, delayed + +from hyperalignment.searchlight import searchlight_hyperalignment def compute_ensemble_indices(nt, n_perms=10, n_folds=5, blocksize=4, buffersize=4, seed=0, mask=None): @@ -50,3 +53,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 From cddcd99cdd46435998ff0c21cdb04d932d4db4a6 Mon Sep 17 00:00:00 2001 From: Feilong Ma Date: Mon, 15 May 2023 17:11:45 -0400 Subject: [PATCH 06/14] Prepare for release. --- movie_datasets/__init__.py | 247 -------------------------- movie_datasets/fsaverage5_lh_mask.npy | Bin 10370 -> 0 bytes movie_datasets/fsaverage5_rh_mask.npy | Bin 10370 -> 0 bytes movie_datasets/fsaverage6_lh_mask.npy | Bin 41090 -> 0 bytes movie_datasets/fsaverage6_rh_mask.npy | Bin 41090 -> 0 bytes movie_datasets/fsaverage_lh_mask.npy | Bin 163970 -> 0 bytes movie_datasets/fsaverage_rh_mask.npy | Bin 163970 -> 0 bytes pyproject.toml | 5 +- setup.cfg | 2 +- src/hyperalignment/__init__.py | 7 + src/hyperalignment/ensemble.py | 2 - src/hyperalignment/procrustes.py | 9 - 12 files changed, 9 insertions(+), 263 deletions(-) delete mode 100644 movie_datasets/__init__.py delete mode 100644 movie_datasets/fsaverage5_lh_mask.npy delete mode 100644 movie_datasets/fsaverage5_rh_mask.npy delete mode 100644 movie_datasets/fsaverage6_lh_mask.npy delete mode 100644 movie_datasets/fsaverage6_rh_mask.npy delete mode 100644 movie_datasets/fsaverage_lh_mask.npy delete mode 100644 movie_datasets/fsaverage_rh_mask.npy 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 a232b605f6a77af9b6f7acb94f1116a2d13d5f6e..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 10370 zcmeHMJ5s|i5OrEk;m$CVf@G*T038es1r-yB8489l4nqT+f(s+9^;u~nTbAVy8JR+> z{X9KAZG;KGH+R>!_lxW^`zp5O{;4W1^Wyt)RV?%3c~^Z@o41EuwJo{-YV*1;nScMX zc`w=gbalSISTE0(`A;7BoGiqXN#nqnEt;aZAZt%-$;kMFAdLy~o2FluS<`ohc-o{5 zXr706WCS}-$Ucd~6A+R2tnf$!82}lqmI{&Gk_BPF^hu1FgBESv4$6zUd^;9qMH(!$ zG1`}H%pg1(vu7Lxarx1*pZd{cWemdcc8p+!sh8|&P1FrNS-ZJPHbU!JavM@EacpF$Md5b~x9afdJbV`vEPc}><>@vCd0eQ|kYj9G zSh@HnzmEbSZhf@ElvOffxn($fw1C+(9IHloOiUq3ipSI}D_1K!>Kw|&^ diff --git a/movie_datasets/fsaverage5_rh_mask.npy b/movie_datasets/fsaverage5_rh_mask.npy deleted file mode 100644 index 38076e71fcab32eedd9585bb8fb95a198e55f3ee..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 10370 zcmeHLy-ve05KdQ~B3nS}Kr1F5fDOdLz=R47Vn7tNhy{2GUKszL&(1m6PD35xEIxnt z_uXfcRD56ETwdSKs`u)nS+~1~ZF62XpZAMqUN?`M?b~+sa<|#8TaI6>o_8(7cTcO= zmhF!hr^~bD{A6B#)rrs1%>PuC_JN@Rxl(Xtvh3jQj)hh;q6UWuxLd$N;xnvtvEhtV z9mXuUq6|dI-O3?|Y2Fh(xJyrMv$gFg_@YAkwQL3>a%dBzRCswCeCzgs&GxAuu9JYY;4Jri9(yQ$! zQxIXVKRhG0le)lkR@tOdQ%^!tVADSqlPoXQI3M;9tR&7x5k_9D{R02y;j^lT&!z3K zRVtys-(fl9M@d$(vy9Ixxq}|atYj&58l-PrP;_=$7_#sK&xx4aR$QsbKare=L`OuO zAft{V4l@WN;50^*xaoNR*;b3e$CkE7fSjb#q@C5nyud|)Jt*K@wy^EMzT)L%cN$o+ zqf1r|4nfeDidgUNarLyT+mkQ1A5%qxzLbZGds40P*Gq61-dss7E#}o{cuywMX_nU mP4+YY)T)Rxa&8QKG4wFpFK>xPs1=SL42V*Qy@0nET7e(*{y=H~ diff --git a/movie_datasets/fsaverage6_lh_mask.npy b/movie_datasets/fsaverage6_lh_mask.npy deleted file mode 100644 index 2b9d84a2ff11d02983fbd2db6feddda29f7f6538..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 41090 zcmeI2y^dTb6vt=VJjHh7NLx6OWyyH}caGe+NEL1DjZ#=yYd1<0`zidw;p@NwE^uMs ze$9Vea5&%mV3<3z{{HKSckh3@IsJS3@BHcE`Qy|1m)rB#KYlvj-Jbt^eER3<{_o!( zpFTZE{oDJ`&ksWX{MY@L2Qh!~>gAi)Ki~a$cl+(O@%6)vd7Vg@7*97jD-Sr89Sa^O z`C=)(3Df)HJTE`y(i!VBY}!jL{rHMJW91}TXQY^!kTpLuVuqW-pfW3|5MjIvUdpU; z&T;JN!-{5?!~A-dFX!T2MF*_)V3f;VhlheIw^sbqFSl;8DRV^L`Bh3Rtr05|q}`8p z8WbP3T#Mh*OH&9fI*ZK^nzuEddnBaawmMhc7}lHYZ6q$UZQ-Cxs=Gys+Prula|??0 z=DK$Db2Sy7ROWS>6W#ExT(73hNRetE`bh!`uHITBk{ek9HJRJTAhDRX=ei_P^>Il8 z#HI<*CMP_|Y{rCFotkpiMZvp;fPBvqZ#A|giDE=1`8^=gL(!Fh**KN6-{y5~5y^H- zz?`mdpfC8rz2V#v3$_m0Zhs~S^uj7Mi5$CE+r`!h{a1ZB!V0I)$rAR}x!FXPoco?^ zZ8Y|@!iruGd%aXJSi;pFI(lRIig+8eJ^EzX#FJ#udo*1FXpb7E@gAv=W6K2C38glb ziY9Jko=kN1F%mBoUj<`oBI`&3(T@pYiwD(nhi6a$q#Z%PZJRh4?kk}9$~U4~Q_k&l z($qeJ)+4}9cUts+ZsmUJhYz8M7hqJ%*?$=3@!HIyr&2NVm533dDn%0{QK2cWS5R~k zc;eNX%XY;(gj`QR!PQ%9M9M*yKuzZMF-RXJ`Gi(oU^l zorT8A2NUdKYlM{<=vG&5;;`lEAS4z@W-}(d>eQ68E(+dl1c-KW2jzd1tGw_;uC`_n zRZRe-tC1mK4uRleps5O_Ni?PtN3IEl`jt7IX5W^?n)B*?FL^KByTA6S-PlXp=o17$ zU?hRW%a*Bo6=uF0=qH`Z6@ zW=8~L);mojK<2Xvf%;a=K%hjx9y<5N@>G7jXYwb$<2p0HqjA^DbFyh(%r?M{!T)@BmzpS6D96(%S+*1@p;(?k{%l-qU4B8G zD$>e3r9+y{5}=(HW2r~x>cmperFK`T*x#k45WhtN>;O1%bfZ*hbRFd1A_1}cTWkwG zfxylP&^?+O<#Noor`qpOQzXJNDt)Mo=EiF(A#_Os5yoakvIGo!BA`ArgF~>V{?RK4 zfB*(qm8;YAq2ta*Tw?t1pyEM0YQLWgIv~XLx}!}!+br_27>4|35ea=W@G3I1V8`; zKmY_Z0q?=0%fvmMMCm%0WKUC~sIA-n={xzU?XQAr7SE3#HfvVQDI9bnDa`SP4+tEa Sz^pgcMxErFS-+!e_UL~yU9L$0 diff --git a/movie_datasets/fsaverage6_rh_mask.npy b/movie_datasets/fsaverage6_rh_mask.npy deleted file mode 100644 index aaf7464bded36c23a8bf43917767b9060ba66b7c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 41090 zcmeHN%Wfq#5WU&*71>>ovH*mT-~(nih|Mfmp}+*OK+GsXY=EzrAI4?7?6Pm!?RLLA z=Pu%MJx`r-cjtEU>4$f3fBfn0^7rMR>-(pdU!Skv-(Uaz<*Vz%{q?sG&wo8X{`vEV z=l4&ffAjdq%ahT+{Qmgy$?QM>=F9KC{rcgHhx`BTJ3pV@l|PpY+k(Ifw`%H3j7ptv zcgFQ{r{o}&qP|U#XvRk*;dVoad>(_WIiqtF!MB-PG_iQadvcXZZf~+B1ekUrLhcY^ zgdhj&W`b#oPnPJf5sss!(Rq|x^FdRxI#fI2Siv|-#SO((54U#Rw5(Pu9KjlC+47y) zHPoG{#)k=dWH71aeu^9ug<@0E%@J#XnA=~3*7ID;kc94%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0uXo~f#P-c7AT6G1a^3z zt>kvkg-j}Cs{4moK7e^RrAE>+-dvYZ3BaMIiHO=MYdAr~>@1?O6ANySR>!+7 zU^X4+Y{EFAF@+YadW9%UN%SdfsU-_d-&@$3{^O$f&H@3gQFIW100bZa0SG_<0;dr8 EKkb%fyZ`_I diff --git a/pyproject.toml b/pyproject.toml index 374b58c..638dd9c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,3 @@ [build-system] -requires = [ - "setuptools>=42", - "wheel" -] +requires = ["setuptools>=61.0"] build-backend = "setuptools.build_meta" diff --git a/setup.cfg b/setup.cfg index eac93d4..9c88bca 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,6 +1,6 @@ [metadata] name = hyperalignment -version = 0.1.0 +version = 0.1.1 author = Ma Feilong author_email = mafeilong@gmail.com description = Hyperalignment algorithms for functional alignment of fMRI data. diff --git a/src/hyperalignment/__init__.py b/src/hyperalignment/__init__.py index e69de29..9c42247 100644 --- a/src/hyperalignment/__init__.py +++ 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/src/hyperalignment/ensemble.py b/src/hyperalignment/ensemble.py index 78bfaae..8c2d57e 100644 --- a/src/hyperalignment/ensemble.py +++ b/src/hyperalignment/ensemble.py @@ -1,8 +1,6 @@ import numpy as np from joblib import Parallel, delayed -from hyperalignment.searchlight import searchlight_hyperalignment - def compute_ensemble_indices(nt, n_perms=10, n_folds=5, blocksize=4, buffersize=4, seed=0, mask=None): rng = np.random.default_rng(seed=seed) diff --git a/src/hyperalignment/procrustes.py b/src/hyperalignment/procrustes.py index 0a18f98..0a61cbf 100644 --- a/src/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 From e600f070a80a0434dda6f273cb95c2e9f495fa5f Mon Sep 17 00:00:00 2001 From: Ma Feilong Date: Thu, 22 Aug 2024 10:38:20 -0400 Subject: [PATCH 07/14] Skip joblib when it's not necessary. --- src/hyperalignment/searchlight.py | 44 +++++++++++++++++++++---------- 1 file changed, 30 insertions(+), 14 deletions(-) diff --git a/src/hyperalignment/searchlight.py b/src/hyperalignment/searchlight.py index f943a21..81657a7 100644 --- a/src/hyperalignment/searchlight.py +++ b/src/hyperalignment/searchlight.py @@ -1,10 +1,11 @@ -import numpy as np import functools + +import numpy as np from joblib import Parallel, delayed +from hyperalignment.local_template import compute_template from hyperalignment.procrustes import procrustes from hyperalignment.ridge import ridge -from hyperalignment.local_template import compute_template def compute_searchlight_weights(sls, dists, radius): @@ -12,7 +13,7 @@ def compute_searchlight_weights(sls, dists, radius): weights = compute_searchlight_weights(sls, dists, radius) """ nv = np.concatenate(sls).max() + 1 - weights_sum = np.zeros((nv, )) + weights_sum = np.zeros((nv,)) for sl, d in zip(sls, dists): w = (radius - d) / radius weights_sum[sl] += w @@ -39,28 +40,43 @@ def searchlight_hyperalignment(X, Y, sls, dists, radius, T0, sl_func, weighted=T return T -def searchlight_procrustes(X, Y, sls, dists, radius, T0=None, reflection=True, scaling=False, weighted=True): +def searchlight_procrustes( + X, Y, sls, dists, radius, T0=None, reflection=True, scaling=False, weighted=True +): sl_func = functools.partial(procrustes, reflection=reflection, scaling=scaling) T = searchlight_hyperalignment( - X, Y, sls, dists, radius, T0=T0, sl_func=sl_func, weighted=weighted) + X, Y, sls, dists, radius, T0=T0, sl_func=sl_func, weighted=weighted + ) return T def searchlight_ridge(X, Y, sls, dists, radius, T0=None, alpha=1e3, weighted=True): sl_func = functools.partial(ridge, alpha=alpha) T = searchlight_hyperalignment( - X, Y, sls, dists, radius, T0=T0, sl_func=sl_func, weighted=weighted) + X, Y, sls, dists, radius, T0=T0, sl_func=sl_func, weighted=weighted + ) return T -def searchlight_template(dss, sls, dists, radius, n_jobs=1, tmpl_kind='pca'): +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] + + if n_jobs == 1: + for sl, w in zip(sls, weights): + local_template = compute_template( + dss, sl=sl, kind=tmpl_kind, max_npc=len(sl), common_topography=True + ) + tmpl[:, 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)( + dss, sl=sl, kind=tmpl_kind, max_npc=len(sl), common_topography=True + ) + for sl in sls + ) + + for local_template, w, sl in zip(local_templates, weights, sls): + tmpl[:, sl] += local_template * w[np.newaxis] return tmpl From 3cd78767cf379ae476fc5db48ff271b1fa6aabfe Mon Sep 17 00:00:00 2001 From: Ma Feilong Date: Thu, 22 Aug 2024 11:15:32 -0400 Subject: [PATCH 08/14] Generate template using the GPA algorithm. --- src/hyperalignment/local_template.py | 133 ++++++++++++++++++++++----- 1 file changed, 111 insertions(+), 22 deletions(-) diff --git a/src/hyperalignment/local_template.py b/src/hyperalignment/local_template.py index 52af7ff..232439f 100644 --- a/src/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) From 2c4478d81549432b9969433cf4ad38410c85463d Mon Sep 17 00:00:00 2001 From: Ma Feilong Date: Mon, 21 Jul 2025 13:49:19 -0400 Subject: [PATCH 09/14] Fix a bug of integer overflow. --- src/hyperalignment/searchlight.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/hyperalignment/searchlight.py b/src/hyperalignment/searchlight.py index 81657a7..699db04 100644 --- a/src/hyperalignment/searchlight.py +++ b/src/hyperalignment/searchlight.py @@ -12,7 +12,7 @@ def compute_searchlight_weights(sls, dists, radius): """ weights = compute_searchlight_weights(sls, dists, radius) """ - nv = np.concatenate(sls).max() + 1 + nv = int(np.concatenate(sls).max()) + 1 weights_sum = np.zeros((nv,)) for sl, d in zip(sls, dists): w = (radius - d) / radius From 017bb699318bf386f006e7ff6df1401d8fd9bcd8 Mon Sep 17 00:00:00 2001 From: Feilong Ma Date: Mon, 21 Jul 2025 14:06:02 -0400 Subject: [PATCH 10/14] Allow uniform weighting as an alternative to distance-based weighting. --- src/hyperalignment/searchlight.py | 19 +++++++++++--- tests/test_searchlight.py | 43 +++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 3 deletions(-) create mode 100644 tests/test_searchlight.py diff --git a/src/hyperalignment/searchlight.py b/src/hyperalignment/searchlight.py index 699db04..3cec457 100644 --- a/src/hyperalignment/searchlight.py +++ b/src/hyperalignment/searchlight.py @@ -8,21 +8,34 @@ from hyperalignment.ridge import ridge -def compute_searchlight_weights(sls, dists, radius): +def compute_searchlight_weights(sls, dists=None, radius=None): """ weights = compute_searchlight_weights(sls, dists, radius) """ 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) + + return weights + + # If dists is provided, use distance-based weighting 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 diff --git a/tests/test_searchlight.py b/tests/test_searchlight.py new file mode 100644 index 0000000..00fab59 --- /dev/null +++ b/tests/test_searchlight.py @@ -0,0 +1,43 @@ +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) From 67276ef6874213f6ab0a4ba391ca8c1d240fae59 Mon Sep 17 00:00:00 2001 From: Feilong Ma Date: Mon, 21 Jul 2025 14:26:47 -0400 Subject: [PATCH 11/14] Add docstring for compute_searchlight_weights. --- src/hyperalignment/searchlight.py | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/src/hyperalignment/searchlight.py b/src/hyperalignment/searchlight.py index 3cec457..b60445f 100644 --- a/src/hyperalignment/searchlight.py +++ b/src/hyperalignment/searchlight.py @@ -10,7 +10,33 @@ def compute_searchlight_weights(sls, dists=None, radius=None): """ - weights = compute_searchlight_weights(sls, dists, radius) + 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, scaled by the + radius. + + Typical usage: + >>> weights = compute_searchlight_weights(sls, dists, radius) + + 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 + Each ndarray contains the weights for the vertices in the corresponding + searchlight. The weights sum to 1 for each vertex. """ nv = int(np.concatenate(sls).max()) + 1 weights_sum = np.zeros((nv,)) @@ -27,6 +53,7 @@ def compute_searchlight_weights(sls, dists=None, radius=None): return weights # 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 From d1e4b8a485a23d8173c61a2af2531f119a3cfeb5 Mon Sep 17 00:00:00 2001 From: Feilong Ma Date: Mon, 21 Jul 2025 16:46:54 -0400 Subject: [PATCH 12/14] Optionally return the weights as a sparse matrix. --- src/hyperalignment/searchlight.py | 45 ++++++++++++++++++++----------- tests/test_searchlight.py | 17 ++++++++++++ 2 files changed, 46 insertions(+), 16 deletions(-) diff --git a/src/hyperalignment/searchlight.py b/src/hyperalignment/searchlight.py index b60445f..7767bcf 100644 --- a/src/hyperalignment/searchlight.py +++ b/src/hyperalignment/searchlight.py @@ -1,6 +1,7 @@ import functools import numpy as np +import scipy.sparse as sparse from joblib import Parallel, delayed from hyperalignment.local_template import compute_template @@ -8,17 +9,18 @@ from hyperalignment.ridge import ridge -def compute_searchlight_weights(sls, dists=None, radius=None): +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, scaled by the - radius. + 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 ---------- @@ -34,9 +36,14 @@ def compute_searchlight_weights(sls, dists=None, radius=None): Returns ------- - weights : list of ndarrays + 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. + 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,)) @@ -50,18 +57,24 @@ def compute_searchlight_weights(sls, dists=None, radius=None): w = 1.0 / weights_sum[sl] weights.append(w) - return weights - - # 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 + 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) - 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 diff --git a/tests/test_searchlight.py b/tests/test_searchlight.py index 00fab59..2a0241a 100644 --- a/tests/test_searchlight.py +++ b/tests/test_searchlight.py @@ -41,3 +41,20 @@ def test_sparse_searchlights(self): 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) From 0f7e24e6b388e7027b0304e3063f0edeea157a98 Mon Sep 17 00:00:00 2001 From: Ma Feilong Date: Thu, 9 Oct 2025 19:30:02 -0400 Subject: [PATCH 13/14] Add docstring and standardize variable names. --- src/hyperalignment/searchlight.py | 153 +++++++++++++++++++++++++----- 1 file changed, 127 insertions(+), 26 deletions(-) diff --git a/src/hyperalignment/searchlight.py b/src/hyperalignment/searchlight.py index 7767bcf..6ed43da 100644 --- a/src/hyperalignment/searchlight.py +++ b/src/hyperalignment/searchlight.py @@ -79,57 +79,158 @@ def compute_searchlight_weights(sls, dists=None, radius=None, return_sparse=Fals return weights -def searchlight_hyperalignment(X, Y, sls, dists, radius, T0, sl_func, 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 = sl_func(X[:, sl], Y[:, sl]) - T[np.ix_(sl, sl)] += t * w[np.newaxis] +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 in sls: - t = sl_func(X[:, sl], Y[:, sl]) - T[np.ix_(sl, sl)] += t - return T + 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, dists, radius, T0=None, reflection=True, scaling=False, weighted=True + 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) - T = searchlight_hyperalignment( - X, Y, sls, dists, radius, T0=T0, sl_func=sl_func, weighted=weighted + xfm = searchlight_hyperalignment( + X, Y, sls, sls_Y=sls_Y, sl_func=sl_func, mat0=mat0, weights=weights ) - return T + 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. -def searchlight_ridge(X, Y, sls, dists, radius, T0=None, alpha=1e3, weighted=True): + 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) - T = searchlight_hyperalignment( - X, Y, sls, dists, radius, T0=T0, sl_func=sl_func, weighted=weighted + xfm = searchlight_hyperalignment( + X, Y, sls, sls_Y=sls_Y, sl_func=sl_func, mat0=mat0, weights=weights ) - return T + return xfm -def searchlight_template(dss, sls, dists, radius, n_jobs=1, tmpl_kind="pca"): +def searchlight_template(dms, sls, dists, radius, n_jobs=1, tpl_kind="pca"): weights = compute_searchlight_weights(sls, dists, radius) - tmpl = np.zeros_like(dss[0]) + tpl = np.zeros_like(dms[0]) if n_jobs == 1: for sl, w in zip(sls, weights): local_template = compute_template( - dss, sl=sl, kind=tmpl_kind, max_npc=len(sl), common_topography=True + dms, sl=sl, kind=tpl_kind, max_npc=len(sl), common_topography=True ) - tmpl[:, sl] += local_template * w[np.newaxis] + 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)( - dss, sl=sl, kind=tmpl_kind, max_npc=len(sl), common_topography=True + 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): - tmpl[:, sl] += local_template * w[np.newaxis] - return tmpl + tpl[:, sl] += local_template * w[np.newaxis] + return tpl From ab50d1219c35e65fb3210da6bd75f7e69801d439 Mon Sep 17 00:00:00 2001 From: Feilong Ma Date: Mon, 2 Nov 2026 17:33:59 -0500 Subject: [PATCH 14/14] Fast initialization of the sparse matrix. --- src/hyperalignment/sparse.py | 28 ++++++++++--- tests/test_sparse.py | 76 ++++++++++++++++++++++++++++++++++++ 2 files changed, 98 insertions(+), 6 deletions(-) create mode 100644 tests/test_sparse.py diff --git a/src/hyperalignment/sparse.py b/src/hyperalignment/sparse.py index 6fc3f8e..0f3735d 100644 --- a/src/hyperalignment/sparse.py +++ b/src/hyperalignment/sparse.py @@ -26,13 +26,29 @@ def initialize_sparse_matrix(sls, nv=None, dtype=np.float64, cache_fn=None): """ 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: - 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) + 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) 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([])