"""Bounded parsing of MindEye2 subject-1 arrays; no object/pickle inputs.""" import io import hashlib import zipfile import numpy as np VOXELS=15724 MAX_BYTES=2_000_000 def parse(raw,suffix): if len(raw)>MAX_BYTES:raise ValueError('Use an fMRI array under 2 MB.') if suffix=='.npz': try: with zipfile.ZipFile(io.BytesIO(raw)) as z: entry=z.getinfo('voxels.npy') if entry.file_size>MAX_BYTES:raise ValueError('The voxels array is too large.') raw=z.read(entry) except (zipfile.BadZipFile,KeyError) as e: raise ValueError('The NPZ file needs a numeric array named voxels.') from e elif suffix!='.npy':raise ValueError('Choose a .npy file or a .npz file containing voxels.') stream=io.BytesIO(raw) try: version=np.lib.format.read_magic(stream) if version==(1,0):shape,_,dtype=np.lib.format.read_array_header_1_0(stream) elif version==(2,0):shape,_,dtype=np.lib.format.read_array_header_2_0(stream) else:raise ValueError('Use a standard NumPy v1/v2 array.') if dtype.kind!='f' or dtype.itemsize not in [4,8]:raise ValueError('Use float32 or float64 fMRI values.') if shape not in [(VOXELS,),(1,VOXELS),(2,VOXELS),(3,VOXELS)]: raise ValueError('This decoder needs 15,724 values from NSD participant 1, with one to three repeated recordings.') array=np.load(io.BytesIO(raw),allow_pickle=False) except (OSError,EOFError) as e:raise ValueError('The NumPy array is incomplete or unreadable.') from e array=np.asarray(array,dtype='float32').reshape(-1,VOXELS) if not np.isfinite(array).all():raise ValueError('The array contains missing or infinite values.') if float(array.std())<1e-8:raise ValueError('This array has no signal variation.') if float(np.abs(array).max())>10000:raise ValueError('Values are outside the expected preprocessed fMRI range.') return array def repetitions(array): """Use the repetition convention in the authors' inference notebook.""" if len(array)==1:return array[[0,0,0]] if len(array)==2:return array[[0,0,1]] return array def recorded_match(values,manifest): """Tie a recorded-data claim to the authorized sample-preparation receipt.""" if not manifest.get('access_confirmed_by_human') or manifest.get('subject')!=1: return None if manifest.get('source_repository')!='pscotti/mindeyev2':return None digest=hashlib.sha256(np.ascontiguousarray(values,dtype='float32').tobytes()).hexdigest() return next((sample for sample in manifest.get('samples',[]) if sample.get('values_sha256')==digest),None)