INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Ensure that we re allowed to use this HTTP method.
def require_http_allowed_method(cls, request): """Ensure that we're allowed to use this HTTP method.""" allowed = cls.meta.http_allowed_methods if request.method not in allowed: # The specified method is not allowed for the resource # identified by the request URI. ...
Processes every request.
def route(self, request, response): """Processes every request. Directs control flow to the appropriate HTTP/1.1 method. """ # Ensure that we're allowed to use this HTTP method. self.require_http_allowed_method(request) # Retrieve the function corresponding to this HTTP...
Process an OPTIONS request.
def options(self, request, response): """Process an `OPTIONS` request. Used to initiate a cross-origin request. All handling specific to CORS requests is done on every request however this method also returns a list of available methods. """ # Gather a list available HTT...
Wraps the decorated function in a lightweight resource.
def resource(**kwargs): """Wraps the decorated function in a lightweight resource.""" def inner(function): name = kwargs.pop('name', None) if name is None: name = utils.dasherize(function.__name__) methods = kwargs.pop('methods', None) if isinstance(methods, six.stri...
s - > ( None s0 s1 ) ( s0 s1 s2 )... ( sn - 1 sn None ) example: for ( last cur next ) in threewise ( l ):
def threewise(iterable): """s -> (None, s0, s1), (s0, s1, s2), ... (sn-1, sn, None) example: for (last, cur, next) in threewise(l): """ a, b, c = itertools.tee(iterable,3) def prepend(val, l): yield val for i in l: yield i def postpend(val, l): for i in l: yield i ...
input: lines = list/ iterator of strings eg: lines = [ This is the first line This is the second line ]
def lines2less(lines): """ input: lines = list / iterator of strings eg: lines = ["This is the first line", "This is the second line"] output: print those lines to stdout if the output is short + narrow otherwise print the lines to less """ lines = iter(lines) #cast list to iterator...
Use for streaming writes to a less process Taken from pydoc. pipepager:/ usr/ lib/ python2. 7/ pydoc. py and/ usr/ lib/ python3. 5/ pydoc. py
def lesspager(lines): """ Use for streaming writes to a less process Taken from pydoc.pipepager: /usr/lib/python2.7/pydoc.py and /usr/lib/python3.5/pydoc.py """ cmd = "less -S" if sys.version_info[0] >= 3: """Page through text by feeding it to another program.""" impo...
http:// stackoverflow. com/ questions/ 5098580/ implementing - argmax - in - python
def argmax(l,f=None): """http://stackoverflow.com/questions/5098580/implementing-argmax-in-python""" if f: l = [f(i) for i in l] return max(enumerate(l), key=lambda x:x[1])[0]
Render to cookie strings.
def render_to_string(self): """Render to cookie strings. """ values = '' for key, value in self.items(): values += '{}={};'.format(key, value) return values
update self with cookie_string.
def from_cookie_string(self, cookie_string): """update self with cookie_string. """ for key_value in cookie_string.split(';'): if '=' in key_value: key, value = key_value.split('=', 1) else: key = key_value strip_key = key.strip...
Adds a method to the internal lists of allowed or denied methods. Each object in the internal list contains a resource ARN and a condition statement. The condition statement can be null.
def _add_method(self, effect, verb, resource, conditions): """ Adds a method to the internal lists of allowed or denied methods. Each object in the internal list contains a resource ARN and a condition statement. The condition statement can be null. """ if verb != '*' and...
This function loops over an array of objects containing a resourceArn and conditions statement and generates the array of statements for the policy.
def _get_effect_statement(self, effect, methods): """ This function loops over an array of objects containing a resourceArn and conditions statement and generates the array of statements for the policy. """ statements = [] if len(methods) > 0: stateme...
Adds an API Gateway method ( Http verb + Resource path ) to the list of allowed methods and includes a condition for the policy statement. More on AWS policy conditions here: http:// docs. aws. amazon. com/ IAM/ latest/ UserGuide/ reference_policies_elements. html#Condition
def allow_method_with_conditions(self, verb, resource, conditions): """ Adds an API Gateway method (Http verb + Resource path) to the list of allowed methods and includes a condition for the policy statement. More on AWS policy conditions here: http://docs.aws.amazon.com/IAM/late...
Adds an API Gateway method ( Http verb + Resource path ) to the list of denied methods and includes a condition for the policy statement. More on AWS policy conditions here: http:// docs. aws. amazon. com/ IAM/ latest/ UserGuide/ reference_policies_elements. html#Condition
def deny_method_with_conditions(self, verb, resource, conditions): """ Adds an API Gateway method (Http verb + Resource path) to the list of denied methods and includes a condition for the policy statement. More on AWS policy conditions here: http://docs.aws.amazon.com/IAM/latest...
Generates the policy document based on the internal lists of allowed and denied conditions. This will generate a policy with two main statements for the effect: one statement for Allow and one statement for Deny. Methods that includes conditions will have their own statement in the policy.
def build(self): """ Generates the policy document based on the internal lists of allowed and denied conditions. This will generate a policy with two main statements for the effect: one statement for Allow and one statement for Deny. Methods that includes conditions will ...
AWS doesn t quite have Swagger 2. 0 validation right and will fail on some refs. So we need to convert to deref before upload.
def deref(self, data): """AWS doesn't quite have Swagger 2.0 validation right and will fail on some refs. So, we need to convert to deref before upload.""" # We have to make a deepcopy here to create a proper JSON # compatible object, otherwise `json.dumps` fails when it ...
Check all necessary system requirements to exist.
def check_pre_requirements(pre_requirements): """Check all necessary system requirements to exist. :param pre_requirements: Sequence of pre-requirements to check by running ``where <pre_requirement>`` on Windows and ``which ...`` elsewhere. """ pre_requirements = set(pre_requirements or...
Convert config dict to arguments list.
def config_to_args(config): """Convert config dict to arguments list. :param config: Configuration dict. """ result = [] for key, value in iteritems(config): if value is False: continue key = '--{0}'.format(key.replace('_', '-')) if isinstance(value, (list, se...
Create virtual environment.
def create_env(env, args, recreate=False, ignore_activated=False, quiet=False): """Create virtual environment. :param env: Virtual environment name. :param args: Pass given arguments to ``virtualenv`` script. :param recerate: Recreate virtual environment? By default: False :param ignore_activated: ...
Decorator to error handling.
def error_handler(func): """Decorator to error handling.""" @wraps(func) def wrapper(*args, **kwargs): """ Run actual function and if exception catched and error handler enabled put traceback to log file """ try: return func(*args, **kwargs) except...
Install library or project into virtual environment.
def install(env, requirements, args, ignore_activated=False, install_dev_requirements=False, quiet=False): """Install library or project into virtual environment. :param env: Use given virtual environment name. :param requirements: Use given requirements file for pip. :param args: Pass give...
Iterate over dict items.
def iteritems(data, **kwargs): """Iterate over dict items.""" return iter(data.items(**kwargs)) if IS_PY3 else data.iteritems(**kwargs)
Iterate over dict keys.
def iterkeys(data, **kwargs): """Iterate over dict keys.""" return iter(data.keys(**kwargs)) if IS_PY3 else data.iterkeys(**kwargs)
r Bootstrap Python projects and libraries with virtualenv and pip.
def main(*args): r"""Bootstrap Python projects and libraries with virtualenv and pip. Also check system requirements before bootstrap and run post bootstrap hook if any. :param \*args: Command line arguments list. """ # Create parser, read arguments from direct input or command line with d...
Parse args from command line by creating argument parser instance and process it.
def parse_args(args): """ Parse args from command line by creating argument parser instance and process it. :param args: Command line arguments list. """ from argparse import ArgumentParser description = ('Bootstrap Python projects and libraries with virtualenv ' 'and pi...
r Run pip command in given or activated virtual environment.
def pip_cmd(env, cmd, ignore_activated=False, **kwargs): r"""Run pip command in given or activated virtual environment. :param env: Virtual environment name. :param cmd: Pip subcommand to run. :param ignore_activated: Ignore activated virtual environment and use given venv instead. By d...
Convert config dict to command line args line.
def prepare_args(config, bootstrap): """Convert config dict to command line args line. :param config: Configuration dict. :param bootstrap: Bootstrapper configuration dict. """ config = copy.deepcopy(config) environ = dict(copy.deepcopy(os.environ)) data = {'env': bootstrap['env'], ...
Print error message to stderr using ANSI - colors.
def print_error(message, wrap=True): """Print error message to stderr, using ANSI-colors. :param message: Message to print :param wrap: Wrap message into ``ERROR: <message>. Exit...`` template. By default: True """ if wrap: message = 'ERROR: {0}. Exit...'.format(message.rstr...
Print message via subprocess. call function.
def print_message(message=None): """Print message via ``subprocess.call`` function. This helps to ensure consistent output and avoid situations where print messages actually shown after messages from all inner threads. :param message: Text message to print. """ kwargs = {'stdout': sys.stdout, ...
Read and parse configuration file. By default filename is relative path to current work directory.
def read_config(filename, args): """ Read and parse configuration file. By default, ``filename`` is relative path to current work directory. If no config file found, default ``CONFIG`` would be used. :param filename: Read config from given filename. :param args: Parsed command line arguments. ...
r Call given command with subprocess. call function.
def run_cmd(cmd, echo=False, fail_silently=False, **kwargs): r"""Call given command with ``subprocess.call`` function. :param cmd: Command to run. :type cmd: tuple or str :param echo: If enabled show command to call and its output in STDOUT, otherwise hide all output. By default: False ...
Run post - bootstrap hook if any.
def run_hook(hook, config, quiet=False): """Run post-bootstrap hook if any. :param hook: Hook to run. :param config: Configuration dict. :param quiet: Do not output messages to STDOUT/STDERR. By default: False """ if not hook: return True if not quiet: print_message('== Ste...
Save error traceback to bootstrapper log file.
def save_traceback(err): """Save error traceback to bootstrapper log file. :param err: Catched exception. """ # Store logs to ~/.bootstrapper directory dirname = safe_path(os.path.expanduser( os.path.join('~', '.{0}'.format(__script__)) )) # But ensure that directory exists if ...
Convert Python object to string.
def smart_str(value, encoding='utf-8', errors='strict'): """Convert Python object to string. :param value: Python object to convert. :param encoding: Encoding to use if in Python 2 given object is unicode. :param errors: Errors mode to use if in Python 2 given object is unicode. """ if not IS_P...
Copy srcfile in destdir with name basename + get_extension ( srcfile ). Add pluses to the destination path basename if a file with the same name already exists in destdir.
def copy_w_ext(srcfile, destdir, basename): """ Copy `srcfile` in `destdir` with name `basename + get_extension(srcfile)`. Add pluses to the destination path basename if a file with the same name already exists in `destdir`. Parameters ---------- srcfile: str destdir: str basename:str...
Copy file from src path to dst path. If dst already exists will add + characters to the end of the basename without extension.
def copy_w_plus(src, dst): """Copy file from `src` path to `dst` path. If `dst` already exists, will add '+' characters to the end of the basename without extension. Parameters ---------- src: str dst: str Returns ------- dstpath: str """ dst_ext = get_extension(dst) d...
Returns the absolute path of folderpath. If the path does not exist will raise IOError.
def get_abspath(folderpath): """Returns the absolute path of folderpath. If the path does not exist, will raise IOError. """ if not op.exists(folderpath): raise FolderNotFound(folderpath) return op.abspath(folderpath)
Return the extension of fpath.
def get_extension(filepath, check_if_exists=False, allowed_exts=ALLOWED_EXTS): """Return the extension of fpath. Parameters ---------- fpath: string File name or path check_if_exists: bool allowed_exts: dict Dictionary of strings, where the key if the last part of a complex ('.' separ...
Add the extension ext to fpath if it doesn t have it.
def add_extension_if_needed(filepath, ext, check_if_exists=False): """Add the extension ext to fpath if it doesn't have it. Parameters ---------- filepath: str File name or path ext: str File extension check_if_exists: bool Returns ------- File name or path with extension...
Parses a file with a list of: <subject_file >: <subject_class_label >.
def parse_subjects_list(filepath, datadir='', split=':', labelsf=None): """Parses a file with a list of: <subject_file>:<subject_class_label>. Parameters ---------- filepath: str Path to file with a list of: <subject_file>:<subject_class_label>. Where ':' can be any split character datadir...
Creates a file where each line is <subject_file >: <subject_class_label >.
def create_subjects_file(filelist, labels, output_file, split=':'): """Creates a file where each line is <subject_file>:<subject_class_label>. Parameters ---------- filelist: list of str List of filepaths labels: list of int, str or labels that can be transformed with str() List of labels ...
Joins path to each line in filelist
def join_path_to_filelist(path, filelist): """Joins path to each line in filelist Parameters ---------- path: str filelist: list of str Returns ------- list of filepaths """ return [op.join(path, str(item)) for item in filelist]
Deletes all files in filelist
def remove_all(filelist, folder=''): """Deletes all files in filelist Parameters ---------- filelist: list of str List of the file paths to be removed folder: str Path to be used as common directory for all file paths in filelist """ if not folder: for f in filelist...
Returns a folder path of path with depth given by folder_dept:
def get_folder_subpath(path, folder_depth): """ Returns a folder path of path with depth given by folder_dept: Parameters ---------- path: str folder_depth: int > 0 Returns ------- A folder path Example ------- >>> get_folder_subpath('/home/user/mydoc/work/notes.txt',...
Uses tempfile to create a TemporaryDirectory using the default arguments. The folder is created using tempfile. mkdtemp () function.
def get_temp_dir(prefix=None, basepath=None): """ Uses tempfile to create a TemporaryDirectory using the default arguments. The folder is created using tempfile.mkdtemp() function. Parameters ---------- prefix: str Name prefix for the temporary folder. basepath: str Directory w...
Returns the length of the file using the wc GNU command
def ux_file_len(filepath): """Returns the length of the file using the 'wc' GNU command Parameters ---------- filepath: str Returns ------- float """ p = subprocess.Popen(['wc', '-l', filepath], stdout=subprocess.PIPE, stderr=subprocess.PIPE) result, er...
Merge two dictionaries.
def merge(dict_1, dict_2): """Merge two dictionaries. Values that evaluate to true take priority over falsy values. `dict_1` takes priority over `dict_2`. """ return dict((str(key), dict_1.get(key) or dict_2.get(key)) for key in set(dict_2) | set(dict_1))
Return a folder path if it exists.
def get_sys_path(rcpath, app_name, section_name=None): """Return a folder path if it exists. First will check if it is an existing system path, if it is, will return it expanded and absoluted. If this fails will look for the rcpath variable in the app_name rcfiles or exclusively within the given s...
Read environment variables and config files and return them merged with predefined list of arguments.
def rcfile(appname, section=None, args={}, strip_dashes=True): """Read environment variables and config files and return them merged with predefined list of arguments. Parameters ---------- appname: str Application name, used for config files and environment variable names. sec...
Return the dictionary containing the rcfile section configuration variables.
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...
Return the value of the variable in the section_name section of the app_name rc file.
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 ...
Return the section and the value of the variable where the first var_name is found in the app_name rcfiles.
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...
Filters the lst using pattern. If pattern starts with ( it will be considered a re regular expression otherwise it will use fnmatch filter.
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 ""...
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.
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...
Given a nested dictionary this returns all its leave elements in a list.
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...
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
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...
Will create dirpath folder. If dirpath already exists and overwrite is False will append a + suffix to dirpath until dirpath does not exist.
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...
Imports filetree and root_path variable values from the filepath.
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: {...
Remove the nodes that match the pattern.
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...
Return the number of nodes that match the pattern.
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): ...
Converts an array - like to an array of floats
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 ---------- ...
Return number of samples in array - like x.
def _num_samples(x): """Return number of samples in array-like x.""" if not hasattr(x, '__len__') and not hasattr(x, 'shape'): if hasattr(x, '__array__'): x = np.asarray(x) else: raise TypeError("Expected sequence or array-like, got %r" % x) return x.shape[0] if hasat...
Check that all arrays have consistent first dimensions.
def check_consistent_length(*arrays): """Check that all arrays have consistent first dimensions. Checks whether all objects in arrays have the same shape or length. Parameters ---------- arrays : list or tuple of input objects. Objects that will be checked for consistent length. """ ...
Make arrays indexable for cross - 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, ...
Input validation on an array list sparse matrix or similar.
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 --------...
Input validation for standard estimators.
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...
Ravel column or 1d numpy array else raises an error
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 ...
Warning utility function to check that data type is floating point.
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 ...
Convert an arbitrary array to numpy. ndarray.
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...
Call FSL tools to apply transformations to a given atlas to a functional image. Given the transformation matrices.
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, ...
Convert a FWHM value to sigma in a Gaussian kernel.
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(...
Convert a sigma in a Gaussian kernel to a FWHM value.
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)...
Smooth images with a a Gaussian filter.
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 ...
Smooth images using a Gaussian filter.
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 ...
Smooth images by applying a Gaussian filter. Apply a Gaussian filter along the three first dimensions of arr.
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/...
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.
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/...
Create requests session with any required auth headers applied.
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...
Create requests session with AAD auth headers
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: ...
Return a grid with coordinates in 3D physical space for img.
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...
Parameters ---------- cm: nipy. core. reference. coordinate_map. CoordinateMap
def voxcoord_to_mm(cm, i, j, k): ''' Parameters ---------- cm: nipy.core.reference.coordinate_map.CoordinateMap i, j, k: floats Voxel coordinates Returns ------- Triplet with real 3D world coordinates ''' try: mm = cm([i, j, k]) except Exception as exc: ...
Parameters ---------- cm: nipy. core. reference. coordinate_map. CoordinateMap
def mm_to_voxcoord(cm, x, y, z): ''' Parameters ---------- cm: nipy.core.reference.coordinate_map.CoordinateMap x, y, z: floats Physical coordinates Returns ------- Triplet with 3D voxel coordinates ''' try: vox = cm.inverse()([x, y, z]) except Exception as ...
Gets a 3D CoordinateMap from img.
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...
Return the header and affine matrix from a Nifti file.
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...
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.
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...
Read a Nifti file and return as nipy. Image
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(...
From the list of absolute paths to nifti files creates a Numpy array with the data.
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. ...
Crops image to a smaller size
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(...
Crops img as much as possible
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 ...
Create a new image of the same class as the reference image
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...
Parameters ---------- file_path: str
def save_variables_to_hdf5(file_path, variables, mode='w', h5path='/'): """ Parameters ---------- file_path: str variables: dict Dictionary with objects. Object name -> object mode: str HDF5 file access mode See h5py documentation for details. r Readonly, file...
Return the h5py. File given its file path.
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...
Return all dataset contents from h5path group in h5file in an OrderedDict.
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 ...
Return the node of type node_type names within h5path of h5file.
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 ...
self. mask setter
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...
Parameters ---------- one_img: str or img - like object. See NeuroImage constructor docstring.
def check_compatibility(self, one_img, another_img=None): """ Parameters ---------- one_img: str or img-like object. See NeuroImage constructor docstring. anoter_img: str or img-like object. See NeuroImage constructor docstring. If None will u...
Parameters ---------- labels: list of int or str This list will be checked to have the same size as
def set_labels(self, labels): """ Parameters ---------- labels: list of int or str This list will be checked to have the same size as Raises ------ ValueError if len(labels) != self.n_subjs """ if not isinstance(labels, str...
Read the images load them into self. items and set the labels.
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 ...
Return numpy. ndarray with the masked or flatten image data and the relevant information ( mask indices and volume shape ).
def to_matrix(self, smooth_fwhm=0, outdtype=None): """Return numpy.ndarray with the masked or flatten image data and the relevant information (mask indices and volume shape). Parameters ---------- smooth__fwhm: int Integer indicating the size of the FWHM Gaussian ...
Save the Numpy array created from to_matrix function to the output_file.
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) ...
Parameters ---------- subj_files: list or dict of str file_path - > int/ str
def _init_subj_data(self, subj_files): """ Parameters ---------- subj_files: list or dict of str file_path -> int/str """ try: if isinstance(subj_files, list): self.from_list(subj_files) elif isinstance(subj_files, dict...