_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q264300
get_rcfile_section
validation
def get_rcfile_section(app_name, section_name): """ Return the dictionary containing the rcfile section configuration variables. Parameters ---------- section_name: str Name of the section in the rcfiles. app_name: str Name of the application to look for its rcfiles. Retur...
python
{ "resource": "" }
q264301
get_rcfile_variable_value
validation
def get_rcfile_variable_value(var_name, app_name, section_name=None): """ Return the value of the variable in the section_name section of the app_name rc file. Parameters ---------- var_name: str Name of the variable to be searched for. section_name: str Name of the section in ...
python
{ "resource": "" }
q264302
find_in_sections
validation
def find_in_sections(var_name, app_name): """ Return the section and the value of the variable where the first var_name is found in the app_name rcfiles. Parameters ---------- var_name: str Name of the variable to be searched for. app_name: str Name of the application to look f...
python
{ "resource": "" }
q264303
filter_list
validation
def filter_list(lst, pattern): """ Filters the lst using pattern. If pattern starts with '(' it will be considered a re regular expression, otherwise it will use fnmatch filter. :param lst: list of strings :param pattern: string :return: list of strings Filtered list of strings ""...
python
{ "resource": "" }
q264304
get_subdict
validation
def get_subdict(adict, path, sep=os.sep): """ Given a nested dictionary adict. This returns its childen just below the path. The path is a string composed of adict keys separated by sep. :param adict: nested dict :param path: str :param sep: str :return: dict or list or leaf of treem...
python
{ "resource": "" }
q264305
get_dict_leaves
validation
def get_dict_leaves(data): """ Given a nested dictionary, this returns all its leave elements in a list. :param adict: :return: list """ result = [] if isinstance(data, dict): for item in data.values(): result.extend(get_dict_leaves(item)) elif isinstance(data, list...
python
{ "resource": "" }
q264306
get_possible_paths
validation
def get_possible_paths(base_path, path_regex): """ Looks for path_regex within base_path. Each match is append in the returned list. path_regex may contain subfolder structure. If any part of the folder structure is a :param base_path: str :param path_regex: str :return list of string...
python
{ "resource": "" }
q264307
FileTreeMap.create_folder
validation
def create_folder(dirpath, overwrite=False): """ Will create dirpath folder. If dirpath already exists and overwrite is False, will append a '+' suffix to dirpath until dirpath does not exist.""" if not overwrite: while op.exists(dirpath): dirpath += '+' os.m...
python
{ "resource": "" }
q264308
FileTreeMap._import_config
validation
def _import_config(filepath): """ Imports filetree and root_path variable values from the filepath. :param filepath: :return: root_path and filetree """ if not op.isfile(filepath): raise IOError('Data config file not found. ' 'Got: {...
python
{ "resource": "" }
q264309
FileTreeMap.remove_nodes
validation
def remove_nodes(self, pattern, adict): """ Remove the nodes that match the pattern. """ mydict = self._filetree if adict is None else adict if isinstance(mydict, dict): for nom in mydict.keys(): if isinstance(mydict[nom], dict): m...
python
{ "resource": "" }
q264310
FileTreeMap.count_node_match
validation
def count_node_match(self, pattern, adict=None): """ Return the number of nodes that match the pattern. :param pattern: :param adict: :return: int """ mydict = self._filetree if adict is None else adict k = 0 if isinstance(mydict, dict): ...
python
{ "resource": "" }
q264311
as_float_array
validation
def as_float_array(X, copy=True, force_all_finite=True): """Converts an array-like to an array of floats The new dtype will be np.float32 or np.float64, depending on the original type. The function can create a copy or modify the argument depending on the argument copy. Parameters ---------- ...
python
{ "resource": "" }
q264312
indexable
validation
def indexable(*iterables): """Make arrays indexable for cross-validation. Checks consistent length, passes through None, and ensures that everything can be indexed by converting sparse matrices to csr and converting non-interable objects to arrays. Parameters ---------- iterables : lists, ...
python
{ "resource": "" }
q264313
check_array
validation
def check_array(array, accept_sparse=None, dtype=None, order=None, copy=False, force_all_finite=True, ensure_2d=True, allow_nd=False): """Input validation on an array, list, sparse matrix or similar. By default, the input is converted to an at least 2nd numpy array. Parameters --------...
python
{ "resource": "" }
q264314
check_X_y
validation
def check_X_y(X, y, accept_sparse=None, dtype=None, order=None, copy=False, force_all_finite=True, ensure_2d=True, allow_nd=False, multi_output=False): """Input validation for standard estimators. Checks X and y for consistent length, enforces X 2d and y 1d. Standard input check...
python
{ "resource": "" }
q264315
column_or_1d
validation
def column_or_1d(y, warn=False): """ Ravel column or 1d numpy array, else raises an error Parameters ---------- y : array-like Returns ------- y : array """ shape = np.shape(y) if len(shape) == 1: return np.ravel(y) if len(shape) == 2 and shape[1] == 1: if ...
python
{ "resource": "" }
q264316
warn_if_not_float
validation
def warn_if_not_float(X, estimator='This algorithm'): """Warning utility function to check that data type is floating point. Returns True if a warning was raised (i.e. the input is not float) and False otherwise, for easier input validation. """ if not isinstance(estimator, str): estimator ...
python
{ "resource": "" }
q264317
as_ndarray
validation
def as_ndarray(arr, copy=False, dtype=None, order='K'): """Convert an arbitrary array to numpy.ndarray. In the case of a memmap array, a copy is automatically made to break the link with the underlying file (whatever the value of the "copy" keyword). The purpose of this function is mainly to get rid o...
python
{ "resource": "" }
q264318
xfm_atlas_to_functional
validation
def xfm_atlas_to_functional(atlas_filepath, anatbrain_filepath, meanfunc_filepath, atlas2anat_nonlin_xfm_filepath, is_atlas2anat_inverted, anat2func_lin_xfm_filepath, atlasinanat_out_filepath, atlasinfunc_out_filepath, ...
python
{ "resource": "" }
q264319
fwhm2sigma
validation
def fwhm2sigma(fwhm): """Convert a FWHM value to sigma in a Gaussian kernel. Parameters ---------- fwhm: float or numpy.array fwhm value or values Returns ------- fwhm: float or numpy.array sigma values """ fwhm = np.asarray(fwhm) return fwhm / np.sqrt(8 * np.log(...
python
{ "resource": "" }
q264320
sigma2fwhm
validation
def sigma2fwhm(sigma): """Convert a sigma in a Gaussian kernel to a FWHM value. Parameters ---------- sigma: float or numpy.array sigma value or values Returns ------- fwhm: float or numpy.array fwhm values corresponding to `sigma` values """ sigma = np.asarray(sigma)...
python
{ "resource": "" }
q264321
_smooth_data_array
validation
def _smooth_data_array(arr, affine, fwhm, copy=True): """Smooth images with a a Gaussian filter. Apply a Gaussian filter along the three first dimensions of arr. Parameters ---------- arr: numpy.ndarray 3D or 4D array, with image number as last dimension. affine: numpy.ndarray ...
python
{ "resource": "" }
q264322
smooth_imgs
validation
def smooth_imgs(images, fwhm): """Smooth images using a Gaussian filter. Apply a Gaussian filter along the three first dimensions of each image in images. In all cases, non-finite values in input are zeroed. Parameters ---------- imgs: str or img-like object or iterable of img-like objects ...
python
{ "resource": "" }
q264323
_smooth_array
validation
def _smooth_array(arr, affine, fwhm=None, ensure_finite=True, copy=True, **kwargs): """Smooth images by applying a Gaussian filter. Apply a Gaussian filter along the three first dimensions of arr. This is copied and slightly modified from nilearn: https://github.com/nilearn/nilearn/blob/master/nilearn/...
python
{ "resource": "" }
q264324
smooth_img
validation
def smooth_img(imgs, fwhm, **kwargs): """Smooth images by applying a Gaussian filter. Apply a Gaussian filter along the three first dimensions of arr. In all cases, non-finite values in input image are replaced by zeros. This is copied and slightly modified from nilearn: https://github.com/nilearn/...
python
{ "resource": "" }
q264325
ClientCertAuthentication.signed_session
validation
def signed_session(self, session=None): """Create requests session with any required auth headers applied. :rtype: requests.Session. """ if session: session = super(ClientCertAuthentication, self).signed_session(session) else: session = super(Cli...
python
{ "resource": "" }
q264326
AdalAuthentication.signed_session
validation
def signed_session(self, session=None): """Create requests session with AAD auth headers :rtype: requests.Session. """ from sfctl.config import (aad_metadata, aad_cache) if session: session = super(AdalAuthentication, self).signed_session(session) else: ...
python
{ "resource": "" }
q264327
voxspace_to_mmspace
validation
def voxspace_to_mmspace(img): """ Return a grid with coordinates in 3D physical space for `img`.""" shape, affine = img.shape[:3], img.affine coords = np.array(np.meshgrid(*(range(i) for i in shape), indexing='ij')) coords = np.rollaxis(coords, 0, len(shape) + 1) mm_coords = nib.affines.apply_affine...
python
{ "resource": "" }
q264328
get_3D_coordmap
validation
def get_3D_coordmap(img): ''' Gets a 3D CoordinateMap from img. Parameters ---------- img: nib.Nifti1Image or nipy Image Returns ------- nipy.core.reference.coordinate_map.CoordinateMap ''' if isinstance(img, nib.Nifti1Image): img = nifti2nipy(img) if img.ndim == 4...
python
{ "resource": "" }
q264329
get_img_info
validation
def get_img_info(image): """Return the header and affine matrix from a Nifti file. Parameters ---------- image: img-like object or str Can either be: - a file path to a Nifti image - any object with get_data() and get_affine() methods, e.g., nibabel.Nifti1Image. If niimg...
python
{ "resource": "" }
q264330
get_img_data
validation
def get_img_data(image, copy=True): """Return the voxel matrix of the Nifti file. If safe_mode will make a copy of the img before returning the data, so the input image is not modified. Parameters ---------- image: img-like object or str Can either be: - a file path to a Nifti image...
python
{ "resource": "" }
q264331
load_nipy_img
validation
def load_nipy_img(nii_file): """Read a Nifti file and return as nipy.Image Parameters ---------- param nii_file: str Nifti file path Returns ------- nipy.Image """ # delayed import because could not install nipy on Python 3 on OSX import nipy if not os.path.exists(...
python
{ "resource": "" }
q264332
niftilist_to_array
validation
def niftilist_to_array(img_filelist, outdtype=None): """ From the list of absolute paths to nifti files, creates a Numpy array with the data. Parameters ---------- img_filelist: list of str List of absolute file paths to nifti files. All nifti files must have the same shape. ...
python
{ "resource": "" }
q264333
_crop_img_to
validation
def _crop_img_to(image, slices, copy=True): """Crops image to a smaller size Crop img to size indicated by slices and modify the affine accordingly. Parameters ---------- image: img-like object or str Can either be: - a file path to a Nifti image - any object with get_data(...
python
{ "resource": "" }
q264334
crop_img
validation
def crop_img(image, rtol=1e-8, copy=True): """Crops img as much as possible Will crop img, removing as many zero entries as possible without touching non-zero entries. Will leave one voxel of zero padding around the obtained non-zero area in order to avoid sampling issues later on. Parameters ...
python
{ "resource": "" }
q264335
new_img_like
validation
def new_img_like(ref_niimg, data, affine=None, copy_header=False): """Create a new image of the same class as the reference image Parameters ---------- ref_niimg: image Reference image. The new image will be of the same type. data: numpy array Data to be stored in the image af...
python
{ "resource": "" }
q264336
get_h5file
validation
def get_h5file(file_path, mode='r'): """ Return the h5py.File given its file path. Parameters ---------- file_path: string HDF5 file path mode: string r Readonly, file must exist r+ Read/write, file must exist w Create file, truncate if exists w- Creat...
python
{ "resource": "" }
q264337
extract_datasets
validation
def extract_datasets(h5file, h5path='/'): """ Return all dataset contents from h5path group in h5file in an OrderedDict. Parameters ---------- h5file: h5py.File HDF5 file object h5path: str HDF5 group path to read datasets from Returns ------- datasets: OrderedDict ...
python
{ "resource": "" }
q264338
_get_node_names
validation
def _get_node_names(h5file, h5path='/', node_type=h5py.Dataset): """Return the node of type node_type names within h5path of h5file. Parameters ---------- h5file: h5py.File HDF5 file object h5path: str HDF5 group path to get the group names from node_type: h5py object type ...
python
{ "resource": "" }
q264339
NeuroImageSet.mask
validation
def mask(self, image): """ self.mask setter Parameters ---------- image: str or img-like object. See NeuroImage constructor docstring. """ if image is None: self._mask = None try: mask = load_mask(image) except Excepti...
python
{ "resource": "" }
q264340
NeuroImageSet._load_images_and_labels
validation
def _load_images_and_labels(self, images, labels=None): """Read the images, load them into self.items and set the labels.""" if not isinstance(images, (list, tuple)): raise ValueError('Expected an iterable (list or tuple) of strings or img-like objects. ' 'Got a ...
python
{ "resource": "" }
q264341
NeuroImageSet.to_file
validation
def to_file(self, output_file, smooth_fwhm=0, outdtype=None): """Save the Numpy array created from to_matrix function to the output_file. Will save into the file: outmat, mask_indices, vol_shape and self.others (put here whatever you want) data: Numpy array with shape N x prod(vol.shape) ...
python
{ "resource": "" }
q264342
die
validation
def die(msg, code=-1): """Writes msg to stderr and exits with return code""" sys.stderr.write(msg + "\n") sys.exit(code)
python
{ "resource": "" }
q264343
check_call
validation
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() ...
python
{ "resource": "" }
q264344
call_command
validation
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 ...
python
{ "resource": "" }
q264345
condor_call
validation
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 != ...
python
{ "resource": "" }
q264346
condor_submit
validation
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...
python
{ "resource": "" }
q264347
clean
validation
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))
python
{ "resource": "" }
q264348
upload
validation
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...
python
{ "resource": "" }
q264349
SFCommandLoader.load_command_table
validation
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: ...
python
{ "resource": "" }
q264350
open_volume_file
validation
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...
python
{ "resource": "" }
q264351
rename_file_group_to_serial_nums
validation
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...
python
{ "resource": "" }
q264352
DicomFileSet._store_dicom_paths
validation
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...
python
{ "resource": "" }
q264353
DicomFileSet.from_set
validation
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...
python
{ "resource": "" }
q264354
DicomFileSet.update
validation
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...
python
{ "resource": "" }
q264355
DicomFileSet.copy_files_to_other_folder
validation
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 ...
python
{ "resource": "" }
q264356
DicomGenericSet.get_dcm_reader
validation
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...
python
{ "resource": "" }
q264357
DicomGenericSet.scrape_all_files
validation
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...
python
{ "resource": "" }
q264358
get_unique_field_values
validation
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 ...
python
{ "resource": "" }
q264359
find_all_dicom_files
validation
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...
python
{ "resource": "" }
q264360
is_dicom_file
validation
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...
python
{ "resource": "" }
q264361
group_dicom_files
validation
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...
python
{ "resource": "" }
q264362
DicomFile.get_attributes
validation
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 --...
python
{ "resource": "" }
q264363
merge_images
validation
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...
python
{ "resource": "" }
q264364
nifti_out
validation
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]) ...
python
{ "resource": "" }
q264365
div_img
validation
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 ' ...
python
{ "resource": "" }
q264366
apply_mask
validation
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))
python
{ "resource": "" }
q264367
abs_img
validation
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)
python
{ "resource": "" }
q264368
icc_img_to_zscore
validation
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...
python
{ "resource": "" }
q264369
spatial_map
validation
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()
python
{ "resource": "" }
q264370
write_meta_header
validation
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...
python
{ "resource": "" }
q264371
dump_raw_data
validation
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...
python
{ "resource": "" }
q264372
write_mhd_file
validation
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...
python
{ "resource": "" }
q264373
copy_mhd_and_raw
validation
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...
python
{ "resource": "" }
q264374
sav_to_pandas_rpy2
validation
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)
python
{ "resource": "" }
q264375
sav_to_pandas_savreader
validation
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) ...
python
{ "resource": "" }
q264376
ExportData.save_varlist
validation
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 """ ...
python
{ "resource": "" }
q264377
cli
validation
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...
python
{ "resource": "" }
q264378
drain_rois
validation
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 - ...
python
{ "resource": "" }
q264379
largest_connected_component
validation
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...
python
{ "resource": "" }
q264380
large_clusters_mask
validation
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: ...
python
{ "resource": "" }
q264381
create_rois_mask
validation
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...
python
{ "resource": "" }
q264382
get_unique_nonzeros
validation
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...
python
{ "resource": "" }
q264383
get_rois_centers_of_mass
validation
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...
python
{ "resource": "" }
q264384
_partition_data
validation
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...
python
{ "resource": "" }
q264385
get_3D_from_4D
validation
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,...
python
{ "resource": "" }
q264386
HdfDataBuffer.get_dataset
validation
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: ...
python
{ "resource": "" }
q264387
HdfDataBuffer.create_empty_dataset
validation
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...
python
{ "resource": "" }
q264388
HdfDataBuffer.create_dataset
validation
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...
python
{ "resource": "" }
q264389
HdfDataBuffer.save
validation
def save(self, ds_name, data, dtype=None): """ See create_dataset. """ return self.create_dataset(ds_name, data, dtype)
python
{ "resource": "" }
q264390
NumpyHDFStore._fill_missing_values
validation
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 ...
python
{ "resource": "" }
q264391
NumpyHDFStore.get
validation
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:...
python
{ "resource": "" }
q264392
NumpyHDFStore.put
validation
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...
python
{ "resource": "" }
q264393
NumpyHDFStore.put_df_as_ndarray
validation
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...
python
{ "resource": "" }
q264394
MedicalImage.smooth_fwhm
validation
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
python
{ "resource": "" }
q264395
MedicalImage.apply_mask
validation
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 ...
python
{ "resource": "" }
q264396
MedicalImage.set_mask
validation
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: ...
python
{ "resource": "" }
q264397
MedicalImage._mask_data
validation
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...
python
{ "resource": "" }
q264398
MedicalImage.apply_smoothing
validation
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...
python
{ "resource": "" }
q264399
MedicalImage.mask_and_flatten
validation
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...
python
{ "resource": "" }