import datasets import torch import numpy as np import json import os import tarfile _DESCRIPTION = """ MindEye is a groundbreaking fMRI-to-image dataset that enables state-of-the-art reconstruction and retrieval of viewed natural scene images from human brain activity. Built on the Natural Scenes Dataset (NSD), this dataset contains brain responses from 4 human participants who passively viewed MS-COCO natural scenes during 7-Tesla fMRI scanning. This repository also includes supplementary data from the Human Connectome Project (HCP). """ _HOMEPAGE = "https://medarc.ai/mindeye/" _LICENSE = "MIT" _CITATION = """ @article{scotti2023reconstructing, title={Reconstructing the Mind's Eye: fMRI-to-Image with Contrastive Learning and Diffusion Priors}, author={Paul S. Scotti and Atmadeep Banerjee and Jimmie Goode and Stepan Shabalin and Alex Nguyen and Ethan Cohen and Aidan J. Dempster and Nathalie Verlinde and Elad Yundler and David Weisberg and Kenneth A. Norman and Tanishq Mathew Abraham}, journal={arXiv preprint arXiv:2305.18274}, year={2023}, url={https://arxiv.org/abs/2305.18274v2} } """ class MindEyeFmri(datasets.GeneratorBasedBuilder): """The MindEye fMRI and HCP Foundation Model Dataset.""" VERSION = datasets.Version("1.0.0") BUILDER_CONFIGS = [ datasets.BuilderConfig(name="nsd-brain-trials", version=VERSION, description="fMRI trial data from the Natural Scenes Dataset (NSD)."), datasets.BuilderConfig(name="hcp-brain-trials", version=VERSION, description="fMRI trial data from the Human Connectome Project (HCP)."), datasets.BuilderConfig(name="hcp-flat-archives", version=VERSION, description="Raw .tar archives of preprocessed HCP fMRI data."), datasets.BuilderConfig(name="clip-image-embeddings", version=VERSION, description="CLIP ViT-L/14 embeddings for NSD stimulus images."), datasets.BuilderConfig(name="semantic-clusters", version=VERSION, description="Semantic cluster assignments for COCO/NSD images."), datasets.BuilderConfig(name="brain-parcellations", version=VERSION, description="Brain atlas files (Schaefer 2018, Yeo 2011) for feature engineering."), datasets.BuilderConfig(name="hcp-task-mapping", version=VERSION, description="Mapping from HCP task trial types to numerical target IDs."), datasets.BuilderConfig(name="hcp-session-metadata", version=VERSION, description="Session-level metadata for the HCP dataset portion."), ] DEFAULT_CONFIG_NAME = "nsd-brain-trials" def _info(self): if self.config.name == "nsd-brain-trials": features = datasets.Features({ "subject_id": datasets.Value("string"), "session": datasets.Value("int32"), "run": datasets.Value("int32"), "n_frames": datasets.Value("int32"), "fmri_data": datasets.Sequence(datasets.Sequence(datasets.Value("float16"))), "start_frame": datasets.Value("int32"), "onset_time": datasets.Value("float32"), "duration": datasets.Value("float32"), "trial_type": datasets.Value("string"), "nsd_image_id": datasets.Value("int32"), "target_class": datasets.Value("int32"), }) elif self.config.name == "hcp-brain-trials": features = datasets.Features({ "subject_id": datasets.Value("string"), "modality": datasets.Value("string"), "task": datasets.Value("string"), "field_strength": datasets.Value("string"), "phase_encoding": datasets.Value("string"), "n_frames": datasets.Value("int32"), "fmri_data": datasets.Sequence(datasets.Sequence(datasets.Value("float16"))), "start_frame": datasets.Value("int32"), "onset_time": datasets.Value("float32"), "duration": datasets.Value("float32"), "trial_type": datasets.Value("string"), "target_class": datasets.Value("int32"), }) elif self.config.name == "hcp-flat-archives": features = datasets.Features({"file_path": datasets.Value("string")}) elif self.config.name == "clip-image-embeddings": features = datasets.Features({"image_embeddings": datasets.Sequence(datasets.Sequence(datasets.Value("float32")))}) elif self.config.name == "semantic-clusters": features = datasets.Features({"cluster_ids": datasets.Sequence(datasets.Value("int64"))}) elif self.config.name == "brain-parcellations": features = datasets.Features({ "parcellation_type": datasets.Value("string"), "parcellation_map": datasets.Sequence(datasets.Sequence(datasets.Value("int64"))), "max_regions": datasets.Value("int32"), }) elif self.config.name == "hcp-task-mapping": features = datasets.Features({"trial_type": datasets.Value("string"), "target_id": datasets.Value("int32")}) elif self.config.name == "hcp-session-metadata": features = datasets.Features({ "session_key": datasets.Value("string"), "subject_id": datasets.Value("string"), "task": datasets.Value("string"), "modality": datasets.Value("string"), "magnet_strength_t": datasets.Value("string"), "phase_encoding_dir": datasets.Value("string"), "n_frames": datasets.Value("int32"), "n_voxels": datasets.Value("int32"), }) else: raise ValueError(f"Unknown config name: {self.config.name}") return datasets.DatasetInfo( description=_DESCRIPTION, features=features, homepage=_HOMEPAGE, license=_LICENSE, citation=_CITATION, ) def _split_generators(self, dl_manager): data_dir = dl_manager.manual_dir if dl_manager.manual_dir else "." return [datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"data_dir": data_dir})] def _generate_examples(self, data_dir): config_name = self.config.name if config_name == "nsd-brain-trials": pt_dir = os.path.join(data_dir, "datasets/flat-clips/nsd-train-task-clips-16t") if not os.path.exists(pt_dir): return for i, pt_file in enumerate(sorted(os.listdir(pt_dir))): if pt_file.endswith(".pt"): file_path = os.path.join(pt_dir, pt_file) try: data = torch.load(file_path) yield i, { "subject_id": str(data.get("subject_id", "")), "session": int(data.get("session", -1)), "run": int(data.get("run", -1)), "n_frames": int(data.get("n_frames", -1)), "fmri_data": data.get("fmri_data").tolist() if data.get("fmri_data") is not None else [], "start_frame": int(data.get("start_frame", -1)), "onset_time": float(data.get("onset_time", -1.0)), "duration": float(data.get("duration", -1.0)), "trial_type": str(data.get("trial_type", "")), "nsd_image_id": int(data.get("nsd_image_id", -1)), "target_class": int(data.get("target_class", -1)), } except Exception as e: print(f"Error loading {file_path}: {e}") elif config_name == "hcp-brain-trials": pt_dir = os.path.join(data_dir, "datasets/flat-clips/hcp-train-task-clips-16t") if not os.path.exists(pt_dir): return for i, pt_file in enumerate(sorted(os.listdir(pt_dir))): if pt_file.endswith(".pt"): file_path = os.path.join(pt_dir, pt_file) try: data = torch.load(file_path) yield i, { "subject_id": str(data.get("subject_id", "")), "modality": str(data.get("modality", "")), "task": str(data.get("task", "")), "field_strength": str(data.get("field_strength", "")), "phase_encoding": str(data.get("phase_encoding", "")), "n_frames": int(data.get("n_frames", -1)), "fmri_data": data.get("fmri_data").tolist() if data.get("fmri_data") is not None else [], "start_frame": int(data.get("start_frame", -1)), "onset_time": float(data.get("onset_time", -1.0)), "duration": float(data.get("duration", -1.0)), "trial_type": str(data.get("trial_type", "")), "target_class": int(data.get("target_class", -1)), } except Exception as e: print(f"Error loading {file_path}: {e}") elif config_name == "hcp-flat-archives": archive_dir = os.path.join(data_dir, "datasets/hcp-flat") if not os.path.exists(archive_dir): return for i, archive_file in enumerate(sorted(os.listdir(archive_dir))): if archive_file.endswith(".tar"): yield i, {"file_path": os.path.join(archive_dir, archive_file)} elif config_name == "clip-image-embeddings": file_path = os.path.join(data_dir, "datasets/nsd_clip_embeds.npy") if not os.path.exists(file_path): return embeddings = np.load(file_path, allow_pickle=True) yield 0, {"image_embeddings": embeddings.tolist()} elif config_name == "semantic-clusters": file_path = os.path.join(data_dir, "datasets/nsd_coco_73k_semantic_cluster_ids.npy") if not os.path.exists(file_path): return clusters = np.load(file_path) yield 0, {"cluster_ids": clusters.tolist()} elif config_name == "brain-parcellations": schaefer_path = os.path.join(data_dir, "datasets/Schaefer2018_400Parcels_7Networks_order.flat.npy") if os.path.exists(schaefer_path): schaefer_map = np.load(schaefer_path) yield 0, {"parcellation_type": "Schaefer2018_400Parcels_7Networks", "parcellation_map": schaefer_map.tolist(), "max_regions": 400} yeo_path = os.path.join(data_dir, "datasets/Yeo2011_RSFC_7Networks.flat.npy") if os.path.exists(yeo_path): yeo_map = np.load(yeo_path) yield 1, {"parcellation_type": "Yeo2011_RSFC_7Networks", "parcellation_map": yeo_map.tolist(), "max_regions": 7} elif config_name == "hcp-task-mapping": file_path = os.path.join(data_dir, "datasets/hcp_trial_type_target_id_map.json") if not os.path.exists(file_path): return with open(file_path, 'r') as f: mapping = json.load(f) for i, (key, value) in enumerate(mapping.items()): yield i, {"trial_type": key, "target_id": value} elif config_name == "hcp-session-metadata": file_path = os.path.join(data_dir, "datasets/session_metadata.json") if not os.path.exists(file_path): return with open(file_path, 'r') as f: metadata = json.load(f) for i, item in enumerate(metadata): yield i, item