本文整理汇总了Python中nilearn.input_data.NiftiMasker方法的典型用法代码示例。如果您正苦于以下问题:Python input_data.NiftiMasker方法的具体用法?Python input_data.NiftiMasker怎么用?Python input_data.NiftiMasker使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类nilearn.input_data
的用法示例。
在下文中一共展示了input_data.NiftiMasker方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _check_dict_init
# 需要导入模块: from nilearn import input_data [as 别名]
# 或者: from nilearn.input_data import NiftiMasker [as 别名]
def _check_dict_init(dict_init, mask_img, n_components=None):
if dict_init is not None:
if isinstance(dict_init, np.ndarray):
assert (dict_init.shape[1] == mask_img.get_data().sum())
components = dict_init
else:
masker = NiftiMasker(smoothing_fwhm=None,
mask_img=mask_img).fit()
components = masker.transform(dict_init)
if n_components is not None:
return components[:n_components]
else:
return components
else:
return None
示例2: extract_data
# 需要导入模块: from nilearn import input_data [as 别名]
# 或者: from nilearn.input_data import NiftiMasker [as 别名]
def extract_data(nifti_file, mask_file, out_file, zscore, detrend, smoothing_fwmw):
if mask_file is None:
#whole brain, get coordinate info from nifti_file itself
mask = nib.load(nifti_file.name)
else:
mask = nib.load(mask_file.name)
affine = mask.get_affine()
if mask_file is None:
mask_data = mask.get_data()
if mask_data.ndim == 4:
#get mask in 3D
img_data_type = mask.header.get_data_dtype()
n_tr = mask_data.shape[3]
mask_data = mask_data[:,:,:,n_tr//2].astype(bool)
mask = nib.Nifti1Image(mask_data.astype(img_data_type), affine)
else:
mask_data = mask_data.astype(bool)
else:
mask_data = mask.get_data().astype(bool)
#get voxel coordinates
R = np.float64(np.argwhere(mask_data))
#get scanner RAS coordinates based on voxel coordinates
if affine is not []:
R = (np.dot(affine[:3,:3], R.T) + affine[:3,3:4]).T
#get ROI data, and run preprocessing
nifti_masker = NiftiMasker(mask_img=mask, standardize=zscore, detrend=detrend, smoothing_fwhm=smoothing_fwmw)
img = nib.load(nifti_file.name)
all_images = np.float64(nifti_masker.fit_transform(img))
data = all_images.T.copy()
#save data
subj_data = {'data': data, 'R': R}
scipy.io.savemat(out_file.name, subj_data)
示例3: responders
# 需要导入模块: from nilearn import input_data [as 别名]
# 或者: from nilearn.input_data import NiftiMasker [as 别名]
def responders(l2_dir,
roi="dsurqec_200micron_roi-dr",
data_root="~/ni_data/ofM.dr",
roi_root='/usr/share/mouse-brain-atlases',
save_inplace=True,
save_as='',
):
data_regex = "(?P<subject>.+)/.*?_tstat\.nii\.gz"
data_path = "{data_root}/l2/{l2_dir}/".format(data_root=data_root, l2_dir=l2_dir)
data_path = path.expanduser(data_path)
roi_path = "{roi_root}/{roi}.nii".format(roi_root=roi_root, roi=roi)
roi_path = path.expanduser(roi_path)
data_find = DataFinder()
data_find.inputs.root_paths = data_path
data_find.inputs.match_regex = path.join(data_path,data_regex)
found_data = data_find.run().outputs
print(found_data)
masker = NiftiMasker(mask_img=roi_path)
voxeldf = pd.DataFrame({})
for subject, data_file in zip(found_data.subject, found_data.out_paths):
subject_data = {}
print(subject, data_file)
img = nib.load(data_file)
img = masker.fit_transform(img)
img = img.flatten()
subject_data["subject"]=subject
for i in img:
voxel_data = deepcopy(subject_data)
voxel_data["t"]=i
df_ = pd.DataFrame(voxel_data, index=[None])
voxeldf = pd.concat([voxeldf,df_])
if save_inplace:
voxeldf.to_csv('{}/ctx_responders.csv'.format(data_path))
else:
voxeldf.to_csv(path.abspath(path.expanduser(save_as)))
示例4: per_session
# 需要导入模块: from nilearn import input_data [as 别名]
# 或者: from nilearn.input_data import NiftiMasker [as 别名]
def per_session(substitutions, roi_mask,
filename_template="~/ni_data/ofM.dr/l1/{l1_dir}/sub-{subject}/ses-{session}/sub-{subject}_ses-{session}_task-{scan}_tstat.nii.gz",
feature=[],
atlas='',
mapping='',
):
"""
roi_mask : str
Path to the ROI mask for which to select the t-values.
roi_mask_normalize : str
Path to a ROI mask by the mean of whose t-values to normalite the t-values in roi_mask.
"""
if isinstance(roi_mask,str):
roi_mask = path.abspath(path.expanduser(roi_mask))
roi_mask = nib.load(roi_mask)
masker = NiftiMasker(mask_img=roi_mask)
n_jobs = mp.cpu_count()-2
dfs = Parallel(n_jobs=n_jobs, verbose=0, backend="threading")(map(delayed(roi_df),
[filename_template]*len(substitutions),
[masker]*len(substitutions),
substitutions,
feature*len(substitutions),
[atlas]*len(substitutions),
[mapping]*len(substitutions),
))
df = pd.concat(dfs)
return df
示例5: mean
# 需要导入模块: from nilearn import input_data [as 别名]
# 或者: from nilearn.input_data import NiftiMasker [as 别名]
def mean(img_path, mask_path):
"""Return the mean of the masked region of an image.
"""
mask = path.abspath(path.expanduser(mask_path))
if mask_path.endswith("roi"):
mask = loadmat(mask)["ROI"]
while mask.ndim != 3:
mask=mask[0]
img_path = path.abspath(path.expanduser(img_path))
img = nib.load(img_path)
else:
masker = NiftiMasker(mask_img=mask)
roi_df(img_path,masker)
示例6: roi_data
# 需要导入模块: from nilearn import input_data [as 别名]
# 或者: from nilearn.input_data import NiftiMasker [as 别名]
def roi_data(img_path, masker,
substitution={},
exclude_zero=False,
zero_threshold=0.1,
):
"""
Return the mean of a Region of Interest (ROI) score.
Parameters
----------
img_path : str
Path to NIfTI file from which the ROI is to be extracted.
makser : nilearn.NiftiMasker
Nilearn `nifti1.Nifti1Image` object to use for masking the desired ROI.
exclude_zero : bool, optional
Whether to filter out zero values.
substitution : dict, optional
A dictionary with keys which include 'subject' and 'session'.
zero_threshold : float, optional
Absolute value below which values are to be considered zero.
"""
if substitution:
img_path = img_path.format(**substitution)
img_path = path.abspath(path.expanduser(img_path))
img = nib.load(img_path)
try:
masked_data = masker.fit_transform(img)
except:
masker = path.abspath(path.expanduser(masker))
masker = NiftiMasker(mask_img=masker)
masked_data = masker.fit_transform(img)
masked_data = masked_data.flatten()
masked_data = masked_data[~np.isnan(masked_data)]
if exclude_zero:
masked_data = masked_data[np.abs(masked_data)>=zero_threshold]
masked_mean = np.mean(masked_data)
masked_median = np.median(masked_data)
return masked_mean, masked_median
示例7: pattern_df
# 需要导入模块: from nilearn import input_data [as 别名]
# 或者: from nilearn.input_data import NiftiMasker [as 别名]
def pattern_df(img_path, pattern,
substitution=False,
):
"""
Return a dataframe containing the `patern` score of `img_path` (i.e. the mean of the multiplication product).
Parameters
----------
img_path : str
Path to NIfTI file from which the ROI is to be extracted.
pattern : nilearn.NiftiMasker
Nilearn `nifti1.Nifti1Image` object to use for masking the desired ROI.
substitution : dict, optional
A dictionary with keys which include 'subject' and 'session'.
"""
subject_data={}
if substitution:
img_path = img_path.format(**substitution)
img_path = path.abspath(path.expanduser(img_path))
try:
img = nib.load(img_path)
except (FileNotFoundError, nib.py3k.FileNotFoundError):
return pd.DataFrame({}), pd.DataFrame({})
else:
img_data = img.get_data()
pattern_data = pattern.get_data()
pattern_evaluation = img_data*pattern_data
pattern_evaluation = pattern_evaluation.flatten()
pattern_score = np.nanmean(pattern_evaluation)
subject_data["session"]=substitution["session"]
subject_data["subject"]=substitution["subject"]
subject_data["t"]=pattern_score
subject_data['feature'] = pattern.get_filename()
df = pd.DataFrame(subject_data, index=[None])
return df
示例8: get_signal
# 需要导入模块: from nilearn import input_data [as 别名]
# 或者: from nilearn.input_data import NiftiMasker [as 别名]
def get_signal(substitutions_a, substitutions_b,
functional_file_template="~/ni_data/ofM.dr/preprocessing/{preprocessing_dir}/sub-{subject}/ses-{session}/func/sub-{subject}_ses-{session}_task-{scan}.nii.gz",
mask="~/ni_data/templates/DSURQEc_200micron_bin.nii.gz",
):
mask = path.abspath(path.expanduser(mask))
out_t_names = []
out_cope_names = []
out_varcb_names = []
for substitution in substitutions_a+substitutions_b:
ts_name = path.abspath(path.expanduser("{subject}_{session}.mat".format(**substitution)))
out_t_name = path.abspath(path.expanduser("{subject}_{session}_tstat.nii.gz".format(**substitution)))
out_cope_name = path.abspath(path.expanduser("{subject}_{session}_cope.nii.gz".format(**substitution)))
out_varcb_name = path.abspath(path.expanduser("{subject}_{session}_varcb.nii.gz".format(**substitution)))
out_t_names.append(out_t_name)
out_cope_names.append(out_cope_name)
out_varcb_names.append(out_varcb_name)
functional_file = path.abspath(path.expanduser(functional_file_template.format(**substitution)))
if not path.isfile(ts_name):
masker = NiftiMasker(mask_img=mask)
ts = masker.fit_transform(functional_file).T
ts = np.mean(ts, axis=0)
header = "/NumWaves 1\n/NumPoints 1490\n/PPheights 1.308540e+01 4.579890e+00\n\n/Matrix"
np.savetxt(ts_name, ts, delimiter="\n", header=header, comments="")
glm = fsl.GLM(in_file=functional_file, design=ts_name, output_type='NIFTI_GZ')
glm.inputs.contrasts = path.abspath(path.expanduser("run0.con"))
glm.inputs.out_t_name = out_t_name
glm.inputs.out_cope = out_cope_name
glm.inputs.out_varcb_name = out_varcb_name
print(glm.cmdline)
glm_run=glm.run()
copemerge = fsl.Merge(dimension='t')
varcopemerge = fsl.Merge(dimension='t')
示例9: apply_mask
# 需要导入模块: from nilearn import input_data [as 别名]
# 或者: from nilearn.input_data import NiftiMasker [as 别名]
def apply_mask(self, mask, resample_mask_to_brain=False):
""" Mask Brain_Data instance
Note target data will be resampled into the same space as the mask. If you would like the mask
resampled into the Brain_Data space, then set resample_mask_to_brain=True.
Args:
mask: (Brain_Data or nifti object) mask to apply to Brain_Data object.
resample_mask_to_brain: (bool) Will resample mask to brain space before applying mask (default=False).
Returns:
masked: (Brain_Data) masked Brain_Data object
"""
masked = deepcopy(self)
mask = check_brain_data(mask)
if not check_brain_data_is_single(mask):
raise ValueError('Mask must be a single image')
n_vox = len(self) if check_brain_data_is_single(self) else self.shape()[1]
if resample_mask_to_brain:
mask = resample_to_img(mask.to_nifti(), masked.to_nifti())
mask = check_brain_data(mask, masked.mask)
nifti_masker = NiftiMasker(mask_img=mask.to_nifti()).fit()
if n_vox == len(mask):
if check_brain_data_is_single(masked):
masked.data = masked.data[mask.data.astype(bool)]
else:
masked.data = masked.data[:, mask.data.astype(bool)]
else:
masked.data = nifti_masker.fit_transform(masked.to_nifti())
masked.nifti_masker = nifti_masker
if (len(masked.shape()) > 1) & (masked.shape()[0] == 1):
masked.data = masked.data.flatten()
return masked
示例10: __init__
# 需要导入模块: from nilearn import input_data [as 别名]
# 或者: from nilearn.input_data import NiftiMasker [as 别名]
def __init__(self, brain_mask=None, output_dir=None): # no scoring param
# self.resource_folder = os.path.join(os.getcwd(),'resources')
if output_dir is None:
self.output_dir = os.path.join(os.getcwd())
else:
self.output_dir = output_dir
if isinstance(brain_mask, str):
brain_mask = nib.load(brain_mask)
elif brain_mask is None:
brain_mask = nib.load(resolve_mni_path(MNI_Template)['mask'])
elif ~isinstance(brain_mask, nib.nifti1.Nifti1Image):
raise ValueError("brain_mask is not a string or a nibabel instance")
self.brain_mask = brain_mask
self.nifti_masker = NiftiMasker(mask_img=self.brain_mask)
示例11: get_masker
# 需要导入模块: from nilearn import input_data [as 别名]
# 或者: from nilearn.input_data import NiftiMasker [as 别名]
def get_masker(mask):
"""
Get an initialized, fitted nilearn Masker instance from passed argument.
Parameters
----------
mask : str, :class:`nibabel.nifti1.Nifti1Image`, or any nilearn Masker
Returns
-------
masker : an initialized, fitted instance of a subclass of
`nilearn.input_data.base_masker.BaseMasker`
"""
if isinstance(mask, str):
mask = nib.load(mask)
if isinstance(mask, nib.nifti1.Nifti1Image):
mask = NiftiMasker(mask)
if not (hasattr(mask, 'transform') and hasattr(mask, 'inverse_transform')):
raise ValueError("mask argument must be a string, a nibabel image,"
" or a Nilearn Masker instance.")
# Fit the masker if needed
if not hasattr(mask, 'mask_img_'):
mask.fit()
return mask
示例12: compute_fixed_effects
# 需要导入模块: from nilearn import input_data [as 别名]
# 或者: from nilearn.input_data import NiftiMasker [as 别名]
def compute_fixed_effects(contrast_imgs, variance_imgs, mask=None,
precision_weighted=False):
"""Compute the fixed effects, given images of effects and variance
Parameters
----------
contrast_imgs: list of Nifti1Images or strings
the input contrast images
variance_imgs: list of Nifti1Images or strings
the input variance images
mask: Nifti1Image or NiftiMasker instance or None, optional,
mask image. If None, it is recomputed from contrast_imgs
precision_weighted: Bool, optional,
Whether fixed effects estimates should be weighted by inverse
variance or not. Defaults to False.
Returns
-------
fixed_fx_contrast_img: Nifti1Image,
the fixed effects contrast computed within the mask
fixed_fx_variance_img: Nifti1Image,
the fixed effects variance computed within the mask
fixed_fx_t_img: Nifti1Image,
the fixed effects t-test computed within the mask
"""
if len(contrast_imgs) != len(variance_imgs):
raise ValueError(
'The number of contrast images (%d) '
'differs from the number of variance images (%d). '
% (len(contrast_imgs), len(variance_imgs))
)
if isinstance(mask, NiftiMasker):
masker = mask.fit()
elif mask is None:
masker = NiftiMasker().fit(contrast_imgs)
else:
masker = NiftiMasker(mask_img=mask).fit()
variances = masker.transform(variance_imgs)
contrasts = masker.transform(contrast_imgs)
(fixed_fx_contrast,
fixed_fx_variance, fixed_fx_t) = _compute_fixed_effects_params(
contrasts, variances, precision_weighted)
fixed_fx_contrast_img = masker.inverse_transform(fixed_fx_contrast)
fixed_fx_variance_img = masker.inverse_transform(fixed_fx_variance)
fixed_fx_t_img = masker.inverse_transform(fixed_fx_t)
return fixed_fx_contrast_img, fixed_fx_variance_img, fixed_fx_t_img
示例13: iter_threshold_volume
# 需要导入模块: from nilearn import input_data [as 别名]
# 或者: from nilearn.input_data import NiftiMasker [as 别名]
def iter_threshold_volume(file_template, substitutions,
mask_path='',
threshold=60,
threshold_is_percentile=True,
invert_data=False,
save_as='',
):
"""
Return a `pandas.DataFrame` (optionally savable as `.csv`), containing the total volume of brain space exceeding a value.
This function is an iteration wrapper of `samri.report.snr.threshold_volume()` using the SAMRI file_template/substitution model.
Parameters
----------
file_template : str
A formattable string containing as format fields keys present in the dictionaries passed to the `substitutions` variable.
substitutions : list of dicts
A list of dictionaries countaining formatting strings as keys and strings as values.
masker : str or nilearn.NiftiMasker, optional
Path to a NIfTI file containing a mask (1 and 0 values) or a `nilearn.NiftiMasker` object.
NOT YET SUPPORTED!
threshold : float, optional
A float giving the voxel value threshold.
threshold_is_percentile : bool, optional
Whether `threshold` is to be interpreted not literally, but as a percentile of the data matrix.
This is useful for making sure that the volume estimation is not susceptible to the absolute value range, but only the value distribution.
save_as : str, optional
Path to which to save the Pandas DataFrame.
Returns
-------
pandas.DataFrame
Pandas DataFrame object containing a row for each analyzed file and columns named 'Mean', 'Median', and (provided the respective key is present in the `sustitutions` variable) 'subject', 'session', 'task', and 'acquisition'.
"""
n_jobs = mp.cpu_count()-2
iter_data = Parallel(n_jobs=n_jobs, verbose=0, backend="threading")(map(delayed(threshold_volume),
[file_template]*len(substitutions),
substitutions,
[mask_path]*len(substitutions),
[threshold]*len(substitutions),
[threshold_is_percentile]*len(substitutions),
))
df_items = [
('Volume', [i[1] for i in iter_data]),
]
df = pd.DataFrame.from_items(df_items)
for field in ['subject','session','task','acquisition']:
try:
df[field] = [i[field] for i in substitutions]
except KeyError:
pass
if save_as:
save_as = path.abspath(path.expanduser(save_as))
if save_as.lower().endswith('.csv'):
df.to_csv(save_as)
else:
raise ValueError("Please specify an output path ending in any one of "+",".join((".csv",))+".")
return df
示例14: significant_signal
# 需要导入模块: from nilearn import input_data [as 别名]
# 或者: from nilearn.input_data import NiftiMasker [as 别名]
def significant_signal(data_path,
substitution={},
mask_path='',
exclude_ones=False,
):
"""Return the mean and median inverse logarithm of a p-value map.
Parameters
----------
data_path : str
Path to a p-value map in NIfTI format.
mask_path : str
Path to a region of interest map in NIfTI format.
THIS IS ALMOST ALWAYS REQUIRED, as NIfTI statistic images populate the whole 3D circumscribed space around your structure of interest,
and commonly assign null values to the background.
In an inverse logarithm computation, null corresponds to infinity, which can considerably bias the evaluation.
substitution : dict
Dictionary whose keys are format identifiers present in `data_path` and whose values are strings.
Returns
-------
mean : float
median : float
"""
if substitution:
data_path = data_path.format(**substitution)
data_path = path.abspath(path.expanduser(data_path))
try:
img = nib.load(data_path)
except FileNotFoundError:
return float('NaN'), float('NaN')
if mask_path:
if isinstance(mask_path, str):
mask_path = path.abspath(path.expanduser(mask_path))
masker = NiftiMasker(mask_img=mask_path)
masked_data = masker.fit_transform(img).T
data = masked_data[~np.isnan(masked_data)]
else:
data = img.get_data()
data = data[~np.isnan(data)]
# We interpret zero as the lowest p-value, and conservatively estimate it to be equal to just under half of the smallest value in the defined range
if 0 in data:
full_data = img.get_data()
nonzero = full_data[np.nonzero(full_data)]
data_min = np.min(nonzero)
data_min = data_min*0.49
if data_min <= 6.8663624751916035e-46:
data_min *=2
data[data == 0] = data_min
if exclude_ones:
data = data[data!=1]
data = -np.log10(data)
# We use np.ma.median() because life is complicated:
# https://github.com/numpy/numpy/issues/7330
median = np.ma.median(data, axis=None)
mean = np.mean(data)
return mean, median
示例15: seed_based
# 需要导入模块: from nilearn import input_data [as 别名]
# 或者: from nilearn.input_data import NiftiMasker [as 别名]
def seed_based(substitutions, seed, roi,
ts_file_template="~/ni_data/ofM.dr/preprocessing/{preprocessing_dir}/sub-{subject}/ses-{session}/func/sub-{subject}_ses-{session}_task-{task}.nii.gz",
smoothing_fwhm=.3,
detrend=True,
standardize=True,
low_pass=0.25,
high_pass=0.004,
tr=1.,
save_results="",
n_procs=2,
cachedir='',
):
"""Plot a ROI t-values over the session timecourse
roi_mask : str
Path to the ROI mask for which to select the t-values.
figure : {"per-participant", "per-voxel", "both"}
At what level to resolve the t-values. Per-participant compares participant means, per-voxel compares all voxel values, both creates two plots covering the aforementioned cases.
roi_mask_normalize : str
Path to a ROI mask by the mean of whose t-values to normalite the t-values in roi_mask.
"""
if isinstance(roi,str):
roi_mask = path.abspath(path.expanduser(roi))
if isinstance(seed,str):
seed_mask = path.abspath(path.expanduser(seed))
seed_masker = NiftiMasker(
mask_img=seed_mask,
smoothing_fwhm=smoothing_fwhm,
detrend=detrend,
standardize=standardize,
low_pass=low_pass,
high_pass=high_pass,
t_r=tr,
memory=cachedir, memory_level=1, verbose=0
)
brain_masker = NiftiMasker(
mask_img=roi_mask,
smoothing_fwhm=smoothing_fwhm,
detrend=detrend,
standardize=standardize,
low_pass=low_pass,
high_pass=high_pass,
t_r=tr,
memory=cachedir, memory_level=1, verbose=0
)
fc_maps = Parallel(n_jobs=n_procs, verbose=0, backend="threading")(map(delayed(add_fc_roi_data),
[ts_file_template]*len(substitutions),
[seed_masker]*len(substitutions),
[brain_masker]*len(substitutions),
[True]*len(substitutions),
[save_results]*len(substitutions),
substitutions,
))
return fc_maps