def compute_powerspectrum(ieeg_file, method, taper, duration, output_dir): """ compute psd Parameters ---------- method : str "spectrogram" or "dh2012" taper : str "dpss", "boxcar", "hann" (only if method=='spectrogram') duration : float duration of the trials """ with ieeg_file.open('rb') as f: dat = load(f) if method == 'spectrogram': freq = compute_frequency(dat, taper, duration) elif method == 'dh2012': freq = compute_welch_dh2012(dat, duration) else: raise ValueError(f'Unknown method "{method}"') output_file = output_dir / replace_extension(ieeg_file.name, 'psd.pkl') with output_file.open('wb') as f: dump(freq, f) return output_file
def compute_prf(input_file, dat, indices, stimuli, method): tsv_file = replace_extension(input_file, 'prf.tsv') x = [] y = [] sigma = [] beta = [] with tsv_file.open('w') as f: f.write(f'channel\tx\ty\tsigma\tbeta\n') for i, index in enumerate(indices): if method == 'analyzePRF': output = fit_analyzePRF(stimuli, dat[i, :]) f.write( f'{index}\t{output.x[0]}\t{output.x[1]}\t{output.x[2]}\t{output.x[3]}\n' ) results = output.x elif method == 'popeye': output = fit_popeye(stimuli, dat[i, :]) f.write( f'{index}\t{output.estimate[0]}\t{output.estimate[1]}\t{output.estimate[2]}\t{output.estimate[3]}\n' ) results = output.estimate x.append(results[0]) y.append(results[1]) sigma.append(results[2]) beta.append(results[3]) f.flush() return array(x), array(y), array(sigma), array(beta)
def estimate_bold_prf(bold_file, method): prf_task = Task(bold_file) stimuli = read_prf_stimuli(prf_task) region_idx = 11143 aparc = nload(str(data_aparc)) img = nload(str(prf_task.filename)) mri = img.get_data() roi = select_region(aparc, lambda x: x == region_idx) roi_idx = apply_affine(img.affine, array(where(roi.get_data() > 0)).T) roi_str = [f'{xyz[0]:.2f},{xyz[1]:.2f},{xyz[2]:.2f}' for xyz in roi_idx] dat = mri[roi.get_data() > 0, :] output = compute_prf(bold_file, dat, roi_str, stimuli, method) images = ['X', 'Y', 'SIGMA', 'BETA'] for i in range(len(output)): nii_file = replace_extension(bold_file, 'prf' + images[i] + '.nii.gz') out = zeros(mri.shape[:3]) out[roi.get_data() > 0] = output[i] x_img = Nifti1Image(out, img.affine) x_img.to_filename(str(nii_file))
def create_bold(bold_file, taskname, region_idx, timeseries): aparc = nload(str(data_aparc)) brain = select_region(aparc, lambda x: x > 0) act = select_region(aparc, lambda x: x == region_idx) t = timeseries.shape[0] random.seed(100) idx = where(brain.get_data() == 1) r = random.randn(idx[0].shape[0], t) bold = ones(brain.get_data().shape + (t, )) bold[act.get_data() == 1, :] = timeseries bold[idx] += r nifti = Nifti1Image(bold.astype('float32'), brain.affine) nifti.header['pixdim'][4] = TR nifti.header.set_xyzt_units('mm', 'sec') nifti.to_filename(str(bold_file)) d = { 'RepetitionTime': TR, 'TaskName': taskname, } json_bold = replace_extension(bold_file, '.json') with json_bold.open('w') as f: dump(d, f, ensure_ascii=False, indent=' ')
def preprocess_ecog(ieeg_file, reref, duration, offset, output_dir): """ Parameters ---------- reref : str 'average' or 'regression' duration : int length of the segments offset : bool remove one sample for whole duration TODO ---- labels_in_roi = find_labels_in_regions(electrodes, regions) clean_roi_labels = [label for label in clean_labels if label in labels_in_roi] data = select(data, chan=clean_roi_labels) """ with ieeg_file.open('rb') as f: data = load(f) data = montage(data, ref_to_avg=True, method=reref) data = make_segments(data, duration, offset) output_file = output_dir / replace_extension(ieeg_file.name, 'proc.pkl') with output_file.open('wb') as f: dump(data, f) return output_file
def write_bids(data, filename, markers=[]): write_brainvision(data, filename, markers) _write_ieeg_json( replace_extension(filename, '.json')) _write_ieeg_channels( replace_underscore(filename, 'channels.tsv'), data) _write_ieeg_events( replace_underscore(filename, 'events.tsv'), markers)
def run_fslmaths_threshold(gm_file, threshold): gm_bin_file = replace_extension(gm_file, '_bin.nii.gz') p = run(['fslmaths', gm_file, '-thr', str(threshold), '-bin', gm_bin_file], stdout=PIPE, stderr=PIPE) check_subprocess(p) return gm_bin_file
def save_frequency(ieeg_file, bands, method): with ieeg_file.open('rb') as f: data = load(f) data = butterpass_eeglabdata(data, bands) data = extract_broadband(data, method) output_file = replace_extension(ieeg_file, 'broadband.pkl') with output_file.open('wb') as f: dump(data, f)
def read_physio(physio_tsv): physio_json = replace_extension(physio_tsv, '.json') with physio_json.open() as r: hdr = load(r) tsv = genfromtxt(physio_tsv, delimiter='\t', names=hdr['Columns']) # normalize values between 0 and 1 cols = [x.split('_')[-1] for x in tsv.dtype.names] tsv.dtype.names = cols for col in tsv.dtype.names[1:]: tsv[col] = normalize(tsv[col]) return tsv
def simulate_ieeg(root, ieeg_task, elec): bids_mkdir(root, ieeg_task) chan_names = [x['name'] for x in elec] ieeg_file = ieeg_task.get_filename(root) create_ieeg_data(ieeg_file, chan_names) create_ieeg_info(replace_extension(ieeg_file, '.json')) create_channels(replace_underscore(ieeg_file, 'channels.tsv'), elec) create_events(replace_underscore(ieeg_file, 'events.tsv')) return iEEG(ieeg_file)
def compare_fmri(feat_path, measure, normalize_to_mean, output_dir): # measure='percent', normalize_to_mean=False): if measure == 'percent': fmri_stat = compute_percent(feat_path, normalize_to_mean) elif measure == 'zstat': fmri_stat = compute_zstat(feat_path) else: raise ValueError(f'Unknown measure: {measure}') task_path = output_dir / replace_extension(feat_path.name, '_compare.nii.gz') nsave(fmri_stat, str(task_path)) return task_path
def estimate_ieeg_prf(ieeg_file, method, freq=(60, 80)): with ieeg_file.open('rb') as f: data = load(f) stimuli = data.attr['stimuli'] data = select(data, freq=freq) data = math(data, operator_name='mean', axis='time') data = math(data, operator_name='mean', axis='freq') data = concatenate(data, 'trial') compute_prf(ieeg_file, data.data[0], data.chan[0], stimuli, method) return replace_extension(ieeg_file, 'prf.tsv')
def run_flirt_feat(task_fmri, gm_file): gm_feat_file = replace_extension( gm_file, '_feat.nii.gz') # TEST: same affine as bold compare p = run([ 'flirt', '-in', str(gm_file), '-ref', str(task_fmri.filename), '-usesqform', '-applyxfm', '-out', str(gm_feat_file), ], stdout=PIPE, stderr=PIPE, env=ENVIRON) check_subprocess(p) return gm_feat_file
def prepare_design(func, anat, output_dir): """You should set remove_unnecessary_outputs to False, otherwise it removes the events.tsv file """ task = Task(func) events_fsl = output_dir / task.events.filename.name _write_events(task.events.filename, events_fsl) # collect info img = niload(str(task.filename)) n_vols = img.header.get_data_shape()[3] tr = img.header['pixdim'][4] # Not sure it it's reliable with DESIGN_TEMPLATE.open('r') as f: design = f.read() feat_dir = output_dir / replace_extension( Path(task.filename).name, '.feat') design_values = { 'XXX_OUTPUTDIR': str(feat_dir), 'XXX_NPTS': str(n_vols), 'XXX_TR': str(tr), 'XXX_FEAT_FILE': str(task.filename), 'XXX_HIGHRES_FILE': str(anat), 'XXX_EV1': 'active', 'XXX_TSVFILE': str(events_fsl), } for pattern, value in design_values.items(): design = design.replace(pattern, value) subj_design = output_dir / replace_underscore( Path(task.filename).name, 'design.fsf') with subj_design.open('w') as f: f.write(design) return subj_design
def test_replace_extension(): assert replace_extension('file.txt', '.bin') == 'file.bin'