INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Parameters ---------- file_path: str Path to the nifti file | def _load_image(file_path):
"""
Parameters
----------
file_path: str
Path to the nifti file
Returns
-------
nipy.Image with a file_path member
"""
if not os.path.exists(file_path):
raise FileNotFound(file_path)
try... |
Parameters ---------- nii_img: nipy. Image | def _smooth_img(nii_img, smooth_fwhm):
"""
Parameters
----------
nii_img: nipy.Image
smooth_fwhm: float
Returns
-------
smoothed nipy.Image
"""
# delayed import because could not install nipy on Python 3 on OSX
from nipy.algorit... |
Parameters ---------- subj_files: dict of str file_path - > int/ str | def from_dict(self, subj_files):
"""
Parameters
----------
subj_files: dict of str
file_path -> int/str
"""
for group_label in subj_files:
try:
group_files = subj_files[group_label]
self.items.extend([self._load_imag... |
Parameters ---------- subj_files: list of str file_paths | def from_list(self, subj_files):
"""
Parameters
----------
subj_files: list of str
file_paths
"""
for sf in subj_files:
try:
nii_img = self._load_image(get_abspath(sf))
self.items.append(nii_img)
except E... |
Parameters ---------- subj_labels: list of int or str This list will be checked to have the same size as files list ( self. items ) | def set_labels(self, subj_labels):
"""
Parameters
----------
subj_labels: list of int or str
This list will be checked to have the same size as files list
(self.items)
"""
if len(subj_labels) != self.n_subjs:
raise ValueError('The numbe... |
Create a Numpy array with the data and return the relevant information ( mask indices and volume shape ). | def to_matrix(self, smooth_fwhm=0, outdtype=None):
"""Create a Numpy array with the data and return the relevant information (mask indices and volume shape).
Parameters
----------
smooth_fwhm: int
Integer indicating the size of the FWHM Gaussian smoothing kernel
... |
Writes msg to stderr and exits with return code | def die(msg, code=-1):
"""Writes msg to stderr and exits with return code"""
sys.stderr.write(msg + "\n")
sys.exit(code) |
Calls the command | def check_call(cmd_args):
"""
Calls the command
Parameters
----------
cmd_args: list of str
Command name to call and its arguments in a list.
Returns
-------
Command output
"""
p = subprocess.Popen(cmd_args, stdout=subprocess.PIPE)
(output, err) = p.communicate()
... |
Call CLI command with arguments and returns its return value. | def call_command(cmd_name, args_strings):
"""Call CLI command with arguments and returns its return value.
Parameters
----------
cmd_name: str
Command name or full path to the binary file.
arg_strings: list of str
Argument strings list.
Returns
-------
return_value
... |
Tries to submit cmd to HTCondor if it does not succeed it will be called with subprocess. call. | def condor_call(cmd, shell=True):
"""
Tries to submit cmd to HTCondor, if it does not succeed, it will
be called with subprocess.call.
Parameters
----------
cmd: string
Command to be submitted
Returns
-------
"""
log.info(cmd)
ret = condor_submit(cmd)
if ret != ... |
Submits cmd to HTCondor queue | def condor_submit(cmd):
"""
Submits cmd to HTCondor queue
Parameters
----------
cmd: string
Command to be submitted
Returns
-------
int
returncode value from calling the submission command.
"""
is_running = subprocess.call('condor_status', shell=True) == 0
i... |
Clean previously built package artifacts. | def clean(ctx):
"""Clean previously built package artifacts.
"""
ctx.run(f'python setup.py clean')
dist = ROOT.joinpath('dist')
print(f'removing {dist}')
shutil.rmtree(str(dist)) |
Upload the package to an index server. | def upload(ctx, repo):
"""Upload the package to an index server.
This implies cleaning and re-building the package.
:param repo: Required. Name of the index server to upload to, as specifies
in your .pypirc configuration file.
"""
artifacts = ' '.join(
shlex.quote(str(n))
f... |
Load all Service Fabric commands | def load_command_table(self, args): #pylint: disable=too-many-statements
"""Load all Service Fabric commands"""
# Need an empty client for the select and upload operations
with CommandSuperGroup(__name__, self,
'rcctl.custom_cluster#{}') as super_group:
... |
Open a volumetric file using the tools following the file extension. | def open_volume_file(filepath):
"""Open a volumetric file using the tools following the file extension.
Parameters
----------
filepath: str
Path to a volume file
Returns
-------
volume_data: np.ndarray
Volume data
pixdim: 1xN np.ndarray
Vector with the descript... |
Check that image is a proper img. Turn filenames into objects. | def _check_medimg(image, make_it_3d=True):
"""Check that image is a proper img. Turn filenames into objects.
Parameters
----------
image: img-like object or str
Can either be:
- a file path to a medical image file, e.g. NifTI, .mhd/raw, .mha
- any object with get_data() method a... |
Will rename all files in file_lst to a padded serial number plus its extension | def rename_file_group_to_serial_nums(file_lst):
"""Will rename all files in file_lst to a padded serial
number plus its extension
:param file_lst: list of path.py paths
"""
file_lst.sort()
c = 1
for f in file_lst:
dirname = get_abspath(f.dirname())
fdest = f.joinpath(dirname... |
Search for dicoms in folders and save file paths into self. dicom_paths set. | def _store_dicom_paths(self, folders):
"""Search for dicoms in folders and save file paths into
self.dicom_paths set.
:param folders: str or list of str
"""
if isinstance(folders, str):
folders = [folders]
for folder in folders:
if not os.path.e... |
Overwrites self. items with the given set of files. Will filter the fileset and keep only Dicom files. | def from_set(self, fileset, check_if_dicoms=True):
"""Overwrites self.items with the given set of files.
Will filter the fileset and keep only Dicom files.
Parameters
----------
fileset: iterable of str
Paths to files
check_if_dicoms: bool
Whether to che... |
Update this set with the union of itself and dicomset. | def update(self, dicomset):
"""Update this set with the union of itself and dicomset.
Parameters
----------
dicomset: DicomFileSet
"""
if not isinstance(dicomset, DicomFileSet):
raise ValueError('Given dicomset is not a DicomFileSet.')
self.items = l... |
Copies all files within this set to the output_folder | def copy_files_to_other_folder(self, output_folder, rename_files=True,
mkdir=True, verbose=False):
"""
Copies all files within this set to the output_folder
Parameters
----------
output_folder: str
Path of the destination folder of the ... |
Creates a lambda function to read DICOM files. If store_store_metadata is False will only return the file path. Else if you give header_fields will return only the set of of header_fields within a DicomFile object or the whole DICOM file if None. | def get_dcm_reader(store_metadata=True, header_fields=None):
"""
Creates a lambda function to read DICOM files.
If store_store_metadata is False, will only return the file path.
Else if you give header_fields, will return only the set of of
header_fields within a DicomFile object... |
Generator that yields one by one the return value for self. read_dcm for each file within this set | def scrape_all_files(self):
"""
Generator that yields one by one the return value for self.read_dcm
for each file within this set
"""
try:
for dcmf in self.items:
yield self.read_dcm(dcmf)
except IOError as ioe:
raise IOError('Error... |
Return a set of unique field values from a list of DICOM files | def get_unique_field_values(dcm_file_list, field_name):
"""Return a set of unique field values from a list of DICOM files
Parameters
----------
dcm_file_list: iterable of DICOM file paths
field_name: str
Name of the field from where to get each value
Returns
-------
Set of field ... |
Returns a list of the dicom files within root_path | def find_all_dicom_files(root_path):
"""
Returns a list of the dicom files within root_path
Parameters
----------
root_path: str
Path to the directory to be recursively searched for DICOM files.
Returns
-------
dicoms: set
Set of DICOM absolute file paths
"""
dicoms = s... |
Tries to read the file using dicom. read_file if the file exists and dicom. read_file does not raise and Exception returns True. False otherwise. | def is_dicom_file(filepath):
"""
Tries to read the file using dicom.read_file,
if the file exists and dicom.read_file does not raise
and Exception returns True. False otherwise.
:param filepath: str
Path to DICOM file
:return: bool
"""
if not os.path.exists(filepath):
rais... |
Group in a dictionary all the DICOM files in dicom_paths separated by the given hdr_field tag value. | def group_dicom_files(dicom_paths, hdr_field='PatientID'):
"""Group in a dictionary all the DICOM files in dicom_paths
separated by the given `hdr_field` tag value.
Parameters
----------
dicom_paths: str
Iterable of DICOM file paths.
hdr_field: str
Name of the DICOM tag whose v... |
Decompress all *. dcm files recursively found in DICOM_DIR. This uses gdcmconv -- raw. It works when dcm2nii shows the Unsupported Transfer Syntax error. This error is usually caused by lack of JPEG2000 support in dcm2nii compilation. | def decompress(input_dir, dcm_pattern='*.dcm'):
""" Decompress all *.dcm files recursively found in DICOM_DIR.
This uses 'gdcmconv --raw'.
It works when 'dcm2nii' shows the `Unsupported Transfer Syntax` error. This error is
usually caused by lack of JPEG2000 support in dcm2nii compilation.
Read mor... |
Return the attributes values from this DicomFile | def get_attributes(self, attributes, default=''):
"""Return the attributes values from this DicomFile
Parameters
----------
attributes: str or list of str
DICOM field names
default: str
Default value if the attribute does not exist.
Returns
--... |
Concatenate images in the direction determined in axis. | def merge_images(images, axis='t'):
""" Concatenate `images` in the direction determined in `axis`.
Parameters
----------
images: list of str or img-like object.
See NeuroImage constructor docstring.
axis: str
't' : concatenate images in time
'x' : concatenate images in the x d... |
Picks a function whose first argument is an img processes its data and returns a numpy array. This decorator wraps this numpy array into a nibabel. Nifti1Image. | def nifti_out(f):
""" Picks a function whose first argument is an `img`, processes its
data and returns a numpy array. This decorator wraps this numpy array
into a nibabel.Nifti1Image."""
@wraps(f)
def wrapped(*args, **kwargs):
r = f(*args, **kwargs)
img = read_img(args[0])
... |
Use the given magic function name func to threshold with value thr the data of img and return a new nibabel. Nifti1Image. Parameters ---------- img: img - like | def thr_img(img, thr=2., mode='+'):
""" Use the given magic function name `func` to threshold with value `thr`
the data of `img` and return a new nibabel.Nifti1Image.
Parameters
----------
img: img-like
thr: float or int
The threshold value.
mode: str
Choices: '+' for posit... |
Pixelwise division or divide by a number | def div_img(img1, div2):
""" Pixelwise division or divide by a number """
if is_img(div2):
return img1.get_data()/div2.get_data()
elif isinstance(div2, (float, int)):
return img1.get_data()/div2
else:
raise NotImplementedError('Cannot divide {}({}) by '
... |
Return the image with the given mask applied. | def apply_mask(img, mask):
"""Return the image with the given `mask` applied."""
from .mask import apply_mask
vol, _ = apply_mask(img, mask)
return vector_to_volume(vol, read_img(mask).get_data().astype(bool)) |
Return an image with the binarised version of the data of img. | def abs_img(img):
""" Return an image with the binarised version of the data of `img`."""
bool_img = np.abs(read_img(img).get_data())
return bool_img.astype(int) |
Return a z - scored version of icc. This function is based on GIFT icatb_convertImageToZScores function. | def icc_img_to_zscore(icc, center_image=False):
""" Return a z-scored version of `icc`.
This function is based on GIFT `icatb_convertImageToZScores` function.
"""
vol = read_img(icc).get_data()
v2 = vol[vol != 0]
if center_image:
v2 = detrend(v2, axis=0)
vstd = np.linalg.norm(v2, o... |
Return the thresholded z - scored icc. | def spatial_map(icc, thr, mode='+'):
""" Return the thresholded z-scored `icc`. """
return thr_img(icc_img_to_zscore(icc), thr=thr, mode=mode).get_data() |
Threshold then mask an IC correlation map. Parameters ---------- icc: img - like The raw ICC map. | def filter_icc(icc, mask=None, thr=2, zscore=True, mode="+"):
""" Threshold then mask an IC correlation map.
Parameters
----------
icc: img-like
The 'raw' ICC map.
mask: img-like
If not None. Will apply this masks in the end of the process.
thr: float
The threshold valu... |
Check that image is a proper img. Turn filenames into objects. | def check_mhd_img(image, make_it_3d=False):
"""Check that image is a proper img. Turn filenames into objects.
Parameters
----------
image: img-like object or str
Can either be:
- a file path to a .mhd file. (if it is a .raw file, this won't work).
- any object with get_data() an... |
Enforce that img is a 3D img - like object if it is not raise a TypeError. i. e. remove dimensions of size 1. | def _make_it_3d(img):
"""Enforce that img is a 3D img-like object, if it is not, raise a TypeError.
i.e., remove dimensions of size 1.
Parameters
----------
img: numpy.ndarray
Image data array
Returns
-------
3D numpy ndarray object
"""
shape = img.shape
if len(sha... |
Write the content of the meta_dict into filename. | def write_meta_header(filename, meta_dict):
""" Write the content of the `meta_dict` into `filename`.
Parameters
----------
filename: str
Path to the output file
meta_dict: dict
Dictionary with the fields of the metadata .mhd file
"""
header = ''
# do not use tags = met... |
Write the data into a raw format file. Big endian is always used. | def dump_raw_data(filename, data):
""" Write the data into a raw format file. Big endian is always used.
Parameters
----------
filename: str
Path to the output file
data: numpy.ndarray
n-dimensional image data array.
"""
if data.ndim == 3:
# Begin 3D fix
dat... |
Write the data and meta_dict in two files with names that use filename as a prefix. | def write_mhd_file(filename, data, shape=None, meta_dict=None):
""" Write the `data` and `meta_dict` in two files with names
that use `filename` as a prefix.
Parameters
----------
filename: str
Path to the output file.
This is going to be used as a preffix.
Two files will be... |
Copy. mhd and. raw files to dst. | def copy_mhd_and_raw(src, dst):
"""Copy .mhd and .raw files to dst.
If dst is a folder, won't change the file, but if dst is another filepath,
will modify the ElementDataFile field in the .mhd to point to the
new renamed .raw file.
Parameters
----------
src: str
Path to the .mhd fi... |
SPSS. sav files to Pandas DataFrame through Rpy2 | def sav_to_pandas_rpy2(input_file):
"""
SPSS .sav files to Pandas DataFrame through Rpy2
:param input_file: string
:return:
"""
import pandas.rpy.common as com
w = com.robj.r('foreign::read.spss("%s", to.data.frame=TRUE)' % input_file)
return com.convert_robj(w) |
SPSS. sav files to Pandas DataFrame through savreader module | def sav_to_pandas_savreader(input_file):
"""
SPSS .sav files to Pandas DataFrame through savreader module
:param input_file: string
:return:
"""
from savReaderWriter import SavReader
lines = []
with SavReader(input_file, returnHeader=True) as reader:
header = next(reader)
... |
Save given variables in a file. Valid extensions:. pyshelf or. shelf ( Python shelve ). mat ( Matlab archive ). hdf5 or. h5 ( HDF5 file ) | def save_variables(filename, variables):
"""Save given variables in a file.
Valid extensions: '.pyshelf' or '.shelf' (Python shelve)
'.mat' (Matlab archive),
'.hdf5' or '.h5' (HDF5 file)
Parameters
----------
filename: str
... |
Valid extensions. pyshelf. mat. hdf5 or. h5 | def save_varlist(filename, varnames, varlist):
"""
Valid extensions '.pyshelf', '.mat', '.hdf5' or '.h5'
@param filename: string
@param varnames: list of strings
Names of the variables
@param varlist: list of objects
The objects to be saved
"""
... |
Create CLI environment | def cli():
"""Create CLI environment"""
return VersionedCLI(cli_name=SF_CLI_NAME,
config_dir=SF_CLI_CONFIG_DIR,
config_env_var_prefix=SF_CLI_ENV_VAR_PREFIX,
commands_loader_cls=SFCommandLoader,
help_cls=SFCommandHelp... |
Find all the ROIs in img and returns a similar volume with the ROIs emptied keeping only their border voxels. | def drain_rois(img):
"""Find all the ROIs in img and returns a similar volume with the ROIs
emptied, keeping only their border voxels.
This is useful for DTI tractography.
Parameters
----------
img: img-like object or str
Can either be:
- a file path to a Nifti image
- ... |
Return the rois_img only with the ROI values from roi_values. Parameters ---------- rois_img: niimg - like | def pick_rois(rois_img, roi_values, bg_val=0):
""" Return the `rois_img` only with the ROI values from `roi_values`.
Parameters
----------
rois_img: niimg-like
roi_values: list of int or float
The list of values from rois_img.
bg_val: int or float
The background value of `rois_... |
Return the largest connected component of a 3D array. | def largest_connected_component(volume):
"""Return the largest connected component of a 3D array.
Parameters
-----------
volume: numpy.array
3D boolean array.
Returns
--------
volume: numpy.array
3D boolean array with only one connected component.
"""
# We use asarr... |
Return as mask for volume that includes only areas where the connected components have a size bigger than min_cluster_size in number of voxels. | def large_clusters_mask(volume, min_cluster_size):
""" Return as mask for `volume` that includes only areas where
the connected components have a size bigger than `min_cluster_size`
in number of voxels.
Parameters
-----------
volume: numpy.array
3D boolean array.
min_cluster_size: ... |
Look for the files in filelist containing the names in roislist these files will be opened binarised and merged in one mask. | def create_rois_mask(roislist, filelist):
"""Look for the files in filelist containing the names in roislist, these files will be opened, binarised
and merged in one mask.
Parameters
----------
roislist: list of strings
Names of the ROIs, which will have to be in the names of the files in f... |
Return a sorted list of the non - zero unique values of arr. | def get_unique_nonzeros(arr):
""" Return a sorted list of the non-zero unique values of arr.
Parameters
----------
arr: numpy.ndarray
The data array
Returns
-------
list of items of arr.
"""
rois = np.unique(arr)
rois = rois[np.nonzero(rois)]
rois.sort()
return... |
Get the center of mass for each ROI in the given volume. | def get_rois_centers_of_mass(vol):
"""Get the center of mass for each ROI in the given volume.
Parameters
----------
vol: numpy ndarray
Volume with different values for each ROI.
Returns
-------
OrderedDict
Each entry in the dict has the ROI value as key and the center_of_m... |
Partition the timeseries in tsvol according to the ROIs in roivol. If a mask is given will use it to exclude any voxel outside of it. | def partition_timeseries(image, roi_img, mask_img=None, zeroe=True, roi_values=None, outdict=False):
"""Partition the timeseries in tsvol according to the ROIs in roivol.
If a mask is given, will use it to exclude any voxel outside of it.
The outdict indicates whether you want a dictionary for each set of ... |
Extracts the values in datavol that are in the ROI with value roivalue in roivol. The ROI can be masked by maskvol. | def _partition_data(datavol, roivol, roivalue, maskvol=None, zeroe=True):
""" Extracts the values in `datavol` that are in the ROI with value `roivalue` in `roivol`.
The ROI can be masked by `maskvol`.
Parameters
----------
datavol: numpy.ndarray
4D timeseries volume or a 3D volume to be pa... |
Partition the timeseries in tsvol according to the ROIs in roivol. If a mask is given will use it to exclude any voxel outside of it. | def _extract_timeseries_dict(tsvol, roivol, maskvol=None, roi_values=None, zeroe=True):
"""Partition the timeseries in tsvol according to the ROIs in roivol.
If a mask is given, will use it to exclude any voxel outside of it.
Parameters
----------
tsvol: numpy.ndarray
4D timeseries volume o... |
Partition the timeseries in tsvol according to the ROIs in roivol. If a mask is given will use it to exclude any voxel outside of it. | def _extract_timeseries_list(tsvol, roivol, maskvol=None, roi_values=None, zeroe=True):
"""Partition the timeseries in tsvol according to the ROIs in roivol.
If a mask is given, will use it to exclude any voxel outside of it.
Parameters
----------
tsvol: numpy.ndarray
4D timeseries volume o... |
Pick one 3D volume from a 4D nifti image file | def get_3D_from_4D(image, vol_idx=0):
"""Pick one 3D volume from a 4D nifti image file
Parameters
----------
image: img-like object or str
Volume defining different ROIs.
Can either be:
- a file path to a Nifti image
- any object with get_data() and get_affine() methods,... |
: return: h5py DataSet | def create_hdf_file(self):
"""
:return: h5py DataSet
"""
mode = 'w'
if not self._overwrite and os.path.exists(self._fname):
mode = 'a'
self._hdf_file = h5py.File(self._fname, mode)
if self._hdf_basepath == '/':
self._group = self._hdf_fil... |
Returns a h5py dataset given its registered name. | def get_dataset(self, ds_name, mode='r'):
"""
Returns a h5py dataset given its registered name.
:param ds_name: string
Name of the dataset to be returned.
:return:
"""
if ds_name in self._datasets:
return self._datasets[ds_name]
else:
... |
Creates a Dataset with unknown size. Resize it before using. | def create_empty_dataset(self, ds_name, dtype=np.float32):
"""
Creates a Dataset with unknown size.
Resize it before using.
:param ds_name: string
:param dtype: dtype
Datatype of the dataset
:return: h5py DataSet
"""
if ds_name in self._datasets... |
Saves a Numpy array in a dataset in the HDF file registers it as ds_name and returns the h5py dataset. | def create_dataset(self, ds_name, data, attrs=None, dtype=None):
"""
Saves a Numpy array in a dataset in the HDF file, registers it as
ds_name and returns the h5py dataset.
:param ds_name: string
Registration name of the dataset to be registered.
:param data: Numpy ndar... |
See create_dataset. | def save(self, ds_name, data, dtype=None):
"""
See create_dataset.
"""
return self.create_dataset(ds_name, data, dtype) |
Will get the names of the index colums of df obtain their ranges from range_values dict and return a reindexed version of df with the given range values. | def _fill_missing_values(df, range_values, fill_value=0, fill_method=None):
"""
Will get the names of the index colums of df, obtain their ranges from
range_values dict and return a reindexed version of df with the given
range values.
:param df: pandas DataFrame
:param ... |
Retrieve pandas object or group of Numpy ndarrays stored in file | def get(self, key):
"""
Retrieve pandas object or group of Numpy ndarrays
stored in file
Parameters
----------
key : object
Returns
-------
obj : type of object stored in file
"""
node = self.get_node(key)
if node is None:... |
Store object in HDFStore | def put(self, key, value, attrs=None, format=None, append=False, **kwargs):
"""
Store object in HDFStore
Parameters
----------
key : str
value : {Series, DataFrame, Panel, Numpy ndarray}
format : 'fixed(f)|table(t)', default is 'fixed'
fixed(f) : Fi... |
: param key: string: param df: pandas Dataframe: param ds_name: string | def _push_dfblock(self, key, df, ds_name, range_values):
"""
:param key: string
:param df: pandas Dataframe
:param ds_name: string
"""
#create numpy array and put into hdf_file
vals_colranges = [range_values[x] for x in df.index.names]
nu_shape = [len(x) f... |
Returns a PyTables HDF Array from df in the shape given by its index columns range values. | def put_df_as_ndarray(self, key, df, range_values, loop_multiindex=False,
unstack=False, fill_value=0, fill_method=None):
"""Returns a PyTables HDF Array from df in the shape given by its index columns range values.
:param key: string object
:param df: pandas DataFram... |
Get the data in the image. If save_copy is True will perform a deep copy of the data and return it. | def get_data(self, safe_copy=False):
"""Get the data in the image.
If save_copy is True, will perform a deep copy of the data and return it.
Parameters
----------
smoothed: (optional) bool
If True and self._smooth_fwhm > 0 will smooth the data before masking.
... |
Set a smoothing Gaussian kernel given its FWHM in mm. | def smooth_fwhm(self, fwhm):
""" Set a smoothing Gaussian kernel given its FWHM in mm. """
if fwhm != self._smooth_fwhm:
self._is_data_smooth = False
self._smooth_fwhm = fwhm |
Get the data in the image. If save_copy is True will perform a deep copy of the data and return it. | def get_data(self, smoothed=True, masked=True, safe_copy=False):
"""Get the data in the image.
If save_copy is True, will perform a deep copy of the data and return it.
Parameters
----------
smoothed: (optional) bool
If True and self._smooth_fwhm > 0 will smooth the... |
First set_mask and the get_masked_data. | def apply_mask(self, mask_img):
"""First set_mask and the get_masked_data.
Parameters
----------
mask_img: nifti-like image, NeuroImage or str
3D mask array: True where a voxel should be used.
Can either be:
- a file path to a Nifti image
... |
Sets a mask img to this. So every operation to self this mask will be taken into account. | def set_mask(self, mask_img):
"""Sets a mask img to this. So every operation to self, this mask will be taken into account.
Parameters
----------
mask_img: nifti-like image, NeuroImage or str
3D mask array: True where a voxel should be used.
Can either be:
... |
Return the data masked with self. mask | def _mask_data(self, data):
"""Return the data masked with self.mask
Parameters
----------
data: np.ndarray
Returns
-------
masked np.ndarray
Raises
------
ValueError if the data and mask dimensions are not compatible.
Other exce... |
Set self. _smooth_fwhm and then smooths the data. See boyle. nifti. smooth. smooth_imgs. | def apply_smoothing(self, smooth_fwhm):
"""Set self._smooth_fwhm and then smooths the data.
See boyle.nifti.smooth.smooth_imgs.
Returns
-------
the smoothed data deepcopied.
"""
if smooth_fwhm <= 0:
return
old_smooth_fwhm = self._smooth_fw... |
Return a vector of the masked data. | def mask_and_flatten(self):
"""Return a vector of the masked data.
Returns
-------
np.ndarray, tuple of indices (np.ndarray), tuple of the mask shape
"""
self._check_for_mask()
return self.get_data(smoothed=True, masked=True, safe_copy=False)[self.get_mask_indic... |
Use self. mask to reshape arr and self. img to get an affine and header to create a new self. img using the data in arr. If self. has_mask () is False will return the same arr. | def unmask(self, arr):
"""Use self.mask to reshape arr and self.img to get an affine and header to create
a new self.img using the data in arr.
If self.has_mask() is False, will return the same arr.
"""
self._check_for_mask()
if 1 > arr.ndim > 2:
raise ValueE... |
Save this object instance in outpath. | def to_file(self, outpath):
"""Save this object instance in outpath.
Parameters
----------
outpath: str
Output file path
"""
if not self.has_mask() and not self.is_smoothed():
save_niigz(outpath, self.img)
else:
save_niigz(outp... |
Setup logging configuration. | def setup_logging(log_config_file=op.join(op.dirname(__file__), 'logger.yml'),
log_default_level=LOG_LEVEL,
env_key=MODULE_NAME.upper() + '_LOG_CFG'):
"""Setup logging configuration."""
path = log_config_file
value = os.getenv(env_key, None)
if value:
path = v... |
Return a dictionary of meta data from meta header file. | def _read_meta_header(filename):
"""Return a dictionary of meta data from meta header file.
Parameters
----------
filename: str
Path to a .mhd file
Returns
-------
meta_dict: dict
A dictionary with the .mhd header content.
"""
fileIN = open(filename, 'r')
line ... |
Return a dictionary of meta data from meta header file. | def load_raw_data_with_mhd(filename):
"""Return a dictionary of meta data from meta header file.
Parameters
----------
filename: str
Path to a .mhd file
Returns
-------
data: numpy.ndarray
n-dimensional image data array.
meta_dict: dict
A dictionary with the .m... |
Return a 3D volume from a 4D nifti image file | def get_3D_from_4D(filename, vol_idx=0):
"""Return a 3D volume from a 4D nifti image file
Parameters
----------
filename: str
Path to the 4D .mhd file
vol_idx: int
Index of the 3D volume to be extracted from the 4D volume.
Returns
-------
vol, hdr
The data arra... |
A wrapper for mem. cache that flushes the cache if the version number of nibabel has changed. | def _safe_cache(memory, func, **kwargs):
""" A wrapper for mem.cache that flushes the cache if the version
number of nibabel has changed.
"""
cachedir = memory.cachedir
if cachedir is None or cachedir in __CACHE_CHECKED:
return memory.cache(func, **kwargs)
version_file = os.path.jo... |
Return a joblib. Memory object. | def cache(func, memory, func_memory_level=None, memory_level=None,
**kwargs):
""" Return a joblib.Memory object.
The memory_level determines the level above which the wrapped
function output is cached. By specifying a numeric value for
this level, the user can to control the amount of cache m... |
Return a joblib. Memory object. | def _cache(self, func, func_memory_level=1, **kwargs):
""" Return a joblib.Memory object.
The memory_level determines the level above which the wrapped
function output is cached. By specifying a numeric value for
this level, the user can to control the amount of cache memory
use... |
Saves a volume into a Nifti (. nii. gz ) file. | def save_niigz(filepath, vol, header=None, affine=None):
"""Saves a volume into a Nifti (.nii.gz) file.
Parameters
----------
vol: Numpy 3D or 4D array
Volume with the data to be saved.
file_path: string
Output file name path
affine: (optional) 4x4 Numpy array
Array wi... |
Saves a Nifti1Image into an HDF5 group. | def spatialimg_to_hdfgroup(h5group, spatial_img):
"""Saves a Nifti1Image into an HDF5 group.
Parameters
----------
h5group: h5py Group
Output HDF5 file path
spatial_img: nibabel SpatialImage
Image to be saved
h5path: str
HDF5 group path where the image data will be sav... |
Saves a Nifti1Image into an HDF5 file. | def spatialimg_to_hdfpath(file_path, spatial_img, h5path=None, append=True):
"""Saves a Nifti1Image into an HDF5 file.
Parameters
----------
file_path: string
Output HDF5 file path
spatial_img: nibabel SpatialImage
Image to be saved
h5path: string
HDF5 group path where... |
Returns a nibabel Nifti1Image from a HDF5 group datasets | def hdfpath_to_nifti1image(file_path, h5path):
"""Returns a nibabel Nifti1Image from a HDF5 group datasets
Parameters
----------
file_path: string
HDF5 file path
h5path:
HDF5 group path in file_path
Returns
-------
nibabel Nifti1Image
"""
with h5py.File(fil... |
Returns a nibabel Nifti1Image from a HDF5 group datasets | def hdfgroup_to_nifti1image(h5group):
"""Returns a nibabel Nifti1Image from a HDF5 group datasets
Parameters
----------
h5group: h5py.Group
HDF5 group
Returns
-------
nibabel Nifti1Image
"""
try:
data = h5group['data'][:]
affine = h5group['affine'][:]
... |
Transforms an H5py Attributes set to a dict. Converts unicode string keys into standard strings and each value into a numpy array. | def get_nifti1hdr_from_h5attrs(h5attrs):
"""Transforms an H5py Attributes set to a dict.
Converts unicode string keys into standard strings
and each value into a numpy array.
Parameters
----------
h5attrs: H5py Attributes
Returns
--------
dict
"""
hdr = nib.Nifti1Header()
... |
Returns in a list all images found under h5group. | def all_childnodes_to_nifti1img(h5group):
"""Returns in a list all images found under h5group.
Parameters
----------
h5group: h5py.Group
HDF group
Returns
-------
list of nifti1Image
"""
child_nodes = []
def append_parent_if_dataset(name, obj):
if isinstance(obj... |
Inserts all given nifti files from file_list into one dataset in fname. This will not check if the dimensionality of all files match. | def insert_volumes_in_one_dataset(file_path, h5path, file_list, newshape=None,
concat_axis=0, dtype=None, append=True):
"""Inserts all given nifti files from file_list into one dataset in fname.
This will not check if the dimensionality of all files match.
Parameters
-... |
Generate all combinations of the elements of iterable and its subsets. | def treefall(iterable):
"""
Generate all combinations of the elements of iterable and its subsets.
Parameters
----------
iterable: list, set or dict or any iterable object
Returns
-------
A generator of all possible combinations of the iterable.
Example:
-------
>>> for i ... |
List existing reliable dictionaries. | def get_reliabledictionary_list(client, application_name, service_name):
"""List existing reliable dictionaries.
List existing reliable dictionaries and respective schema for given application and service.
:param application_name: Name of the application.
:type application_name: str
:param service... |
Query Schema information for existing reliable dictionaries. | def get_reliabledictionary_schema(client, application_name, service_name, dictionary_name, output_file=None):
"""Query Schema information for existing reliable dictionaries.
Query Schema information existing reliable dictionaries for given application and service.
:param application_name: Name of the appl... |
Query existing reliable dictionary. | def query_reliabledictionary(client, application_name, service_name, dictionary_name, query_string, partition_key=None, partition_id=None, output_file=None):
"""Query existing reliable dictionary.
Query existing reliable dictionaries for given application and service.
:param application_name: Name of the ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.