id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
237,200
ANTsX/ANTsPy
ants/core/ants_image.py
ANTsImage.to_file
def to_file(self, filename): """ Write the ANTsImage to file Args ---- filename : string filepath to which the image will be written """ filename = os.path.expanduser(filename) libfn = utils.get_lib_fn('toFile%s'%self._libsuffix) libfn(self.pointer, filename)
python
def to_file(self, filename): """ Write the ANTsImage to file Args ---- filename : string filepath to which the image will be written """ filename = os.path.expanduser(filename) libfn = utils.get_lib_fn('toFile%s'%self._libsuffix) libfn(self.pointer, filename)
[ "def", "to_file", "(", "self", ",", "filename", ")", ":", "filename", "=", "os", ".", "path", ".", "expanduser", "(", "filename", ")", "libfn", "=", "utils", ".", "get_lib_fn", "(", "'toFile%s'", "%", "self", ".", "_libsuffix", ")", "libfn", "(", "self", ".", "pointer", ",", "filename", ")" ]
Write the ANTsImage to file Args ---- filename : string filepath to which the image will be written
[ "Write", "the", "ANTsImage", "to", "file" ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image.py#L347-L358
237,201
ANTsX/ANTsPy
ants/core/ants_image.py
ANTsImage.apply
def apply(self, fn): """ Apply an arbitrary function to ANTsImage. Args ---- fn : python function or lambda function to apply to ENTIRE image at once Returns ------- ANTsImage image with function applied to it """ this_array = self.numpy() new_array = fn(this_array) return self.new_image_like(new_array)
python
def apply(self, fn): """ Apply an arbitrary function to ANTsImage. Args ---- fn : python function or lambda function to apply to ENTIRE image at once Returns ------- ANTsImage image with function applied to it """ this_array = self.numpy() new_array = fn(this_array) return self.new_image_like(new_array)
[ "def", "apply", "(", "self", ",", "fn", ")", ":", "this_array", "=", "self", ".", "numpy", "(", ")", "new_array", "=", "fn", "(", "this_array", ")", "return", "self", ".", "new_image_like", "(", "new_array", ")" ]
Apply an arbitrary function to ANTsImage. Args ---- fn : python function or lambda function to apply to ENTIRE image at once Returns ------- ANTsImage image with function applied to it
[ "Apply", "an", "arbitrary", "function", "to", "ANTsImage", "." ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image.py#L361-L377
237,202
ANTsX/ANTsPy
ants/core/ants_image.py
ANTsImage.sum
def sum(self, axis=None, keepdims=False): """ Return sum along specified axis """ return self.numpy().sum(axis=axis, keepdims=keepdims)
python
def sum(self, axis=None, keepdims=False): """ Return sum along specified axis """ return self.numpy().sum(axis=axis, keepdims=keepdims)
[ "def", "sum", "(", "self", ",", "axis", "=", "None", ",", "keepdims", "=", "False", ")", ":", "return", "self", ".", "numpy", "(", ")", ".", "sum", "(", "axis", "=", "axis", ",", "keepdims", "=", "keepdims", ")" ]
Return sum along specified axis
[ "Return", "sum", "along", "specified", "axis" ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image.py#L395-L397
237,203
ANTsX/ANTsPy
ants/core/ants_image.py
ANTsImage.range
def range(self, axis=None): """ Return range tuple along specified axis """ return (self.min(axis=axis), self.max(axis=axis))
python
def range(self, axis=None): """ Return range tuple along specified axis """ return (self.min(axis=axis), self.max(axis=axis))
[ "def", "range", "(", "self", ",", "axis", "=", "None", ")", ":", "return", "(", "self", ".", "min", "(", "axis", "=", "axis", ")", ",", "self", ".", "max", "(", "axis", "=", "axis", ")", ")" ]
Return range tuple along specified axis
[ "Return", "range", "tuple", "along", "specified", "axis" ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image.py#L404-L406
237,204
ANTsX/ANTsPy
ants/core/ants_image.py
ANTsImage.argrange
def argrange(self, axis=None): """ Return argrange along specified axis """ amin = self.argmin(axis=axis) amax = self.argmax(axis=axis) if axis is None: return (amin, amax) else: return np.stack([amin, amax]).T
python
def argrange(self, axis=None): """ Return argrange along specified axis """ amin = self.argmin(axis=axis) amax = self.argmax(axis=axis) if axis is None: return (amin, amax) else: return np.stack([amin, amax]).T
[ "def", "argrange", "(", "self", ",", "axis", "=", "None", ")", ":", "amin", "=", "self", ".", "argmin", "(", "axis", "=", "axis", ")", "amax", "=", "self", ".", "argmax", "(", "axis", "=", "axis", ")", "if", "axis", "is", "None", ":", "return", "(", "amin", ",", "amax", ")", "else", ":", "return", "np", ".", "stack", "(", "[", "amin", ",", "amax", "]", ")", ".", "T" ]
Return argrange along specified axis
[ "Return", "argrange", "along", "specified", "axis" ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image.py#L413-L420
237,205
ANTsX/ANTsPy
ants/core/ants_image.py
ANTsImage.unique
def unique(self, sort=False): """ Return unique set of values in image """ unique_vals = np.unique(self.numpy()) if sort: unique_vals = np.sort(unique_vals) return unique_vals
python
def unique(self, sort=False): """ Return unique set of values in image """ unique_vals = np.unique(self.numpy()) if sort: unique_vals = np.sort(unique_vals) return unique_vals
[ "def", "unique", "(", "self", ",", "sort", "=", "False", ")", ":", "unique_vals", "=", "np", ".", "unique", "(", "self", ".", "numpy", "(", ")", ")", "if", "sort", ":", "unique_vals", "=", "np", ".", "sort", "(", "unique_vals", ")", "return", "unique_vals" ]
Return unique set of values in image
[ "Return", "unique", "set", "of", "values", "in", "image" ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image.py#L427-L432
237,206
ANTsX/ANTsPy
ants/core/ants_image.py
LabelImage.uniquekeys
def uniquekeys(self, metakey=None): """ Get keys for a given metakey """ if metakey is None: return self._uniquekeys else: if metakey not in self.metakeys(): raise ValueError('metakey %s does not exist' % metakey) return self._uniquekeys[metakey]
python
def uniquekeys(self, metakey=None): """ Get keys for a given metakey """ if metakey is None: return self._uniquekeys else: if metakey not in self.metakeys(): raise ValueError('metakey %s does not exist' % metakey) return self._uniquekeys[metakey]
[ "def", "uniquekeys", "(", "self", ",", "metakey", "=", "None", ")", ":", "if", "metakey", "is", "None", ":", "return", "self", ".", "_uniquekeys", "else", ":", "if", "metakey", "not", "in", "self", ".", "metakeys", "(", ")", ":", "raise", "ValueError", "(", "'metakey %s does not exist'", "%", "metakey", ")", "return", "self", ".", "_uniquekeys", "[", "metakey", "]" ]
Get keys for a given metakey
[ "Get", "keys", "for", "a", "given", "metakey" ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image.py#L731-L740
237,207
ANTsX/ANTsPy
ants/utils/label_clusters.py
label_clusters
def label_clusters(image, min_cluster_size=50, min_thresh=1e-6, max_thresh=1, fully_connected=False): """ This will give a unique ID to each connected component 1 through N of size > min_cluster_size ANTsR function: `labelClusters` Arguments --------- image : ANTsImage input image e.g. a statistical map min_cluster_size : integer throw away clusters smaller than this value min_thresh : scalar threshold to a statistical map max_thresh : scalar threshold to a statistical map fully_connected : boolean boolean sets neighborhood connectivity pattern Returns ------- ANTsImage Example ------- >>> import ants >>> image = ants.image_read( ants.get_ants_data('r16') ) >>> timageFully = ants.label_clusters( image, 10, 128, 150, True ) >>> timageFace = ants.label_clusters( image, 10, 128, 150, False ) """ dim = image.dimension clust = threshold_image(image, min_thresh, max_thresh) temp = int(fully_connected) args = [dim, clust, clust, min_cluster_size, temp] processed_args = _int_antsProcessArguments(args) libfn = utils.get_lib_fn('LabelClustersUniquely') libfn(processed_args) return clust
python
def label_clusters(image, min_cluster_size=50, min_thresh=1e-6, max_thresh=1, fully_connected=False): """ This will give a unique ID to each connected component 1 through N of size > min_cluster_size ANTsR function: `labelClusters` Arguments --------- image : ANTsImage input image e.g. a statistical map min_cluster_size : integer throw away clusters smaller than this value min_thresh : scalar threshold to a statistical map max_thresh : scalar threshold to a statistical map fully_connected : boolean boolean sets neighborhood connectivity pattern Returns ------- ANTsImage Example ------- >>> import ants >>> image = ants.image_read( ants.get_ants_data('r16') ) >>> timageFully = ants.label_clusters( image, 10, 128, 150, True ) >>> timageFace = ants.label_clusters( image, 10, 128, 150, False ) """ dim = image.dimension clust = threshold_image(image, min_thresh, max_thresh) temp = int(fully_connected) args = [dim, clust, clust, min_cluster_size, temp] processed_args = _int_antsProcessArguments(args) libfn = utils.get_lib_fn('LabelClustersUniquely') libfn(processed_args) return clust
[ "def", "label_clusters", "(", "image", ",", "min_cluster_size", "=", "50", ",", "min_thresh", "=", "1e-6", ",", "max_thresh", "=", "1", ",", "fully_connected", "=", "False", ")", ":", "dim", "=", "image", ".", "dimension", "clust", "=", "threshold_image", "(", "image", ",", "min_thresh", ",", "max_thresh", ")", "temp", "=", "int", "(", "fully_connected", ")", "args", "=", "[", "dim", ",", "clust", ",", "clust", ",", "min_cluster_size", ",", "temp", "]", "processed_args", "=", "_int_antsProcessArguments", "(", "args", ")", "libfn", "=", "utils", ".", "get_lib_fn", "(", "'LabelClustersUniquely'", ")", "libfn", "(", "processed_args", ")", "return", "clust" ]
This will give a unique ID to each connected component 1 through N of size > min_cluster_size ANTsR function: `labelClusters` Arguments --------- image : ANTsImage input image e.g. a statistical map min_cluster_size : integer throw away clusters smaller than this value min_thresh : scalar threshold to a statistical map max_thresh : scalar threshold to a statistical map fully_connected : boolean boolean sets neighborhood connectivity pattern Returns ------- ANTsImage Example ------- >>> import ants >>> image = ants.image_read( ants.get_ants_data('r16') ) >>> timageFully = ants.label_clusters( image, 10, 128, 150, True ) >>> timageFace = ants.label_clusters( image, 10, 128, 150, False )
[ "This", "will", "give", "a", "unique", "ID", "to", "each", "connected", "component", "1", "through", "N", "of", "size", ">", "min_cluster_size" ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/label_clusters.py#L11-L53
237,208
ANTsX/ANTsPy
ants/registration/make_points_image.py
make_points_image
def make_points_image(pts, mask, radius=5): """ Create label image from physical space points Creates spherical points in the coordinate space of the target image based on the n-dimensional matrix of points that the user supplies. The image defines the dimensionality of the data so if the input image is 3D then the input points should be 2D or 3D. ANTsR function: `makePointsImage` Arguments --------- pts : numpy.ndarray input powers points mask : ANTsImage mask defining target space radius : integer radius for the points Returns ------- ANTsImage Example ------- >>> import ants >>> import pandas as pd >>> mni = ants.image_read(ants.get_data('mni')).get_mask() >>> powers_pts = pd.read_csv(ants.get_data('powers_mni_itk')) >>> powers_labels = ants.make_points_image(powers_pts.iloc[:,:3].values, mni, radius=3) """ powers_lblimg = mask * 0 npts = len(pts) dim = mask.dimension if pts.shape[1] != dim: raise ValueError('points dimensionality should match that of images') for r in range(npts): pt = pts[r,:] idx = tio.transform_physical_point_to_index(mask, pt.tolist() ).astype(int) in_image = (np.prod(idx <= mask.shape)==1) and (len(np.where(idx<0)[0])==0) if ( in_image == True ): if (dim == 3): powers_lblimg[idx[0],idx[1],idx[2]] = r + 1 elif (dim == 2): powers_lblimg[idx[0],idx[1]] = r + 1 return utils.morphology( powers_lblimg, 'dilate', radius, 'grayscale' )
python
def make_points_image(pts, mask, radius=5): """ Create label image from physical space points Creates spherical points in the coordinate space of the target image based on the n-dimensional matrix of points that the user supplies. The image defines the dimensionality of the data so if the input image is 3D then the input points should be 2D or 3D. ANTsR function: `makePointsImage` Arguments --------- pts : numpy.ndarray input powers points mask : ANTsImage mask defining target space radius : integer radius for the points Returns ------- ANTsImage Example ------- >>> import ants >>> import pandas as pd >>> mni = ants.image_read(ants.get_data('mni')).get_mask() >>> powers_pts = pd.read_csv(ants.get_data('powers_mni_itk')) >>> powers_labels = ants.make_points_image(powers_pts.iloc[:,:3].values, mni, radius=3) """ powers_lblimg = mask * 0 npts = len(pts) dim = mask.dimension if pts.shape[1] != dim: raise ValueError('points dimensionality should match that of images') for r in range(npts): pt = pts[r,:] idx = tio.transform_physical_point_to_index(mask, pt.tolist() ).astype(int) in_image = (np.prod(idx <= mask.shape)==1) and (len(np.where(idx<0)[0])==0) if ( in_image == True ): if (dim == 3): powers_lblimg[idx[0],idx[1],idx[2]] = r + 1 elif (dim == 2): powers_lblimg[idx[0],idx[1]] = r + 1 return utils.morphology( powers_lblimg, 'dilate', radius, 'grayscale' )
[ "def", "make_points_image", "(", "pts", ",", "mask", ",", "radius", "=", "5", ")", ":", "powers_lblimg", "=", "mask", "*", "0", "npts", "=", "len", "(", "pts", ")", "dim", "=", "mask", ".", "dimension", "if", "pts", ".", "shape", "[", "1", "]", "!=", "dim", ":", "raise", "ValueError", "(", "'points dimensionality should match that of images'", ")", "for", "r", "in", "range", "(", "npts", ")", ":", "pt", "=", "pts", "[", "r", ",", ":", "]", "idx", "=", "tio", ".", "transform_physical_point_to_index", "(", "mask", ",", "pt", ".", "tolist", "(", ")", ")", ".", "astype", "(", "int", ")", "in_image", "=", "(", "np", ".", "prod", "(", "idx", "<=", "mask", ".", "shape", ")", "==", "1", ")", "and", "(", "len", "(", "np", ".", "where", "(", "idx", "<", "0", ")", "[", "0", "]", ")", "==", "0", ")", "if", "(", "in_image", "==", "True", ")", ":", "if", "(", "dim", "==", "3", ")", ":", "powers_lblimg", "[", "idx", "[", "0", "]", ",", "idx", "[", "1", "]", ",", "idx", "[", "2", "]", "]", "=", "r", "+", "1", "elif", "(", "dim", "==", "2", ")", ":", "powers_lblimg", "[", "idx", "[", "0", "]", ",", "idx", "[", "1", "]", "]", "=", "r", "+", "1", "return", "utils", ".", "morphology", "(", "powers_lblimg", ",", "'dilate'", ",", "radius", ",", "'grayscale'", ")" ]
Create label image from physical space points Creates spherical points in the coordinate space of the target image based on the n-dimensional matrix of points that the user supplies. The image defines the dimensionality of the data so if the input image is 3D then the input points should be 2D or 3D. ANTsR function: `makePointsImage` Arguments --------- pts : numpy.ndarray input powers points mask : ANTsImage mask defining target space radius : integer radius for the points Returns ------- ANTsImage Example ------- >>> import ants >>> import pandas as pd >>> mni = ants.image_read(ants.get_data('mni')).get_mask() >>> powers_pts = pd.read_csv(ants.get_data('powers_mni_itk')) >>> powers_labels = ants.make_points_image(powers_pts.iloc[:,:3].values, mni, radius=3)
[ "Create", "label", "image", "from", "physical", "space", "points" ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/registration/make_points_image.py#L11-L60
237,209
ANTsX/ANTsPy
ants/utils/weingarten_image_curvature.py
weingarten_image_curvature
def weingarten_image_curvature(image, sigma=1.0, opt='mean'): """ Uses the weingarten map to estimate image mean or gaussian curvature ANTsR function: `weingartenImageCurvature` Arguments --------- image : ANTsImage image from which curvature is calculated sigma : scalar smoothing parameter opt : string mean by default, otherwise `gaussian` or `characterize` Returns ------- ANTsImage Example ------- >>> import ants >>> image = ants.image_read(ants.get_ants_data('mni')).resample_image((3,3,3)) >>> imagecurv = ants.weingarten_image_curvature(image) """ if image.dimension not in {2,3}: raise ValueError('image must be 2D or 3D') if image.dimension == 2: d = image.shape temp = np.zeros(list(d)+[10]) for k in range(1,7): voxvals = image[:d[0],:d[1]] temp[:d[0],:d[1],k] = voxvals temp = core.from_numpy(temp) myspc = image.spacing myspc = list(myspc) + [min(myspc)] temp.set_spacing(myspc) temp = temp.clone('float') else: temp = image.clone('float') optnum = 0 if opt == 'gaussian': optnum = 6 if opt == 'characterize': optnum = 5 libfn = utils.get_lib_fn('weingartenImageCurvature') mykout = libfn(temp.pointer, sigma, optnum) mykout = iio.ANTsImage(pixeltype=image.pixeltype, dimension=3, components=image.components, pointer=mykout) if image.dimension == 3: return mykout elif image.dimension == 2: subarr = core.from_numpy(mykout.numpy()[:,:,4]) return core.copy_image_info(image, subarr)
python
def weingarten_image_curvature(image, sigma=1.0, opt='mean'): """ Uses the weingarten map to estimate image mean or gaussian curvature ANTsR function: `weingartenImageCurvature` Arguments --------- image : ANTsImage image from which curvature is calculated sigma : scalar smoothing parameter opt : string mean by default, otherwise `gaussian` or `characterize` Returns ------- ANTsImage Example ------- >>> import ants >>> image = ants.image_read(ants.get_ants_data('mni')).resample_image((3,3,3)) >>> imagecurv = ants.weingarten_image_curvature(image) """ if image.dimension not in {2,3}: raise ValueError('image must be 2D or 3D') if image.dimension == 2: d = image.shape temp = np.zeros(list(d)+[10]) for k in range(1,7): voxvals = image[:d[0],:d[1]] temp[:d[0],:d[1],k] = voxvals temp = core.from_numpy(temp) myspc = image.spacing myspc = list(myspc) + [min(myspc)] temp.set_spacing(myspc) temp = temp.clone('float') else: temp = image.clone('float') optnum = 0 if opt == 'gaussian': optnum = 6 if opt == 'characterize': optnum = 5 libfn = utils.get_lib_fn('weingartenImageCurvature') mykout = libfn(temp.pointer, sigma, optnum) mykout = iio.ANTsImage(pixeltype=image.pixeltype, dimension=3, components=image.components, pointer=mykout) if image.dimension == 3: return mykout elif image.dimension == 2: subarr = core.from_numpy(mykout.numpy()[:,:,4]) return core.copy_image_info(image, subarr)
[ "def", "weingarten_image_curvature", "(", "image", ",", "sigma", "=", "1.0", ",", "opt", "=", "'mean'", ")", ":", "if", "image", ".", "dimension", "not", "in", "{", "2", ",", "3", "}", ":", "raise", "ValueError", "(", "'image must be 2D or 3D'", ")", "if", "image", ".", "dimension", "==", "2", ":", "d", "=", "image", ".", "shape", "temp", "=", "np", ".", "zeros", "(", "list", "(", "d", ")", "+", "[", "10", "]", ")", "for", "k", "in", "range", "(", "1", ",", "7", ")", ":", "voxvals", "=", "image", "[", ":", "d", "[", "0", "]", ",", ":", "d", "[", "1", "]", "]", "temp", "[", ":", "d", "[", "0", "]", ",", ":", "d", "[", "1", "]", ",", "k", "]", "=", "voxvals", "temp", "=", "core", ".", "from_numpy", "(", "temp", ")", "myspc", "=", "image", ".", "spacing", "myspc", "=", "list", "(", "myspc", ")", "+", "[", "min", "(", "myspc", ")", "]", "temp", ".", "set_spacing", "(", "myspc", ")", "temp", "=", "temp", ".", "clone", "(", "'float'", ")", "else", ":", "temp", "=", "image", ".", "clone", "(", "'float'", ")", "optnum", "=", "0", "if", "opt", "==", "'gaussian'", ":", "optnum", "=", "6", "if", "opt", "==", "'characterize'", ":", "optnum", "=", "5", "libfn", "=", "utils", ".", "get_lib_fn", "(", "'weingartenImageCurvature'", ")", "mykout", "=", "libfn", "(", "temp", ".", "pointer", ",", "sigma", ",", "optnum", ")", "mykout", "=", "iio", ".", "ANTsImage", "(", "pixeltype", "=", "image", ".", "pixeltype", ",", "dimension", "=", "3", ",", "components", "=", "image", ".", "components", ",", "pointer", "=", "mykout", ")", "if", "image", ".", "dimension", "==", "3", ":", "return", "mykout", "elif", "image", ".", "dimension", "==", "2", ":", "subarr", "=", "core", ".", "from_numpy", "(", "mykout", ".", "numpy", "(", ")", "[", ":", ",", ":", ",", "4", "]", ")", "return", "core", ".", "copy_image_info", "(", "image", ",", "subarr", ")" ]
Uses the weingarten map to estimate image mean or gaussian curvature ANTsR function: `weingartenImageCurvature` Arguments --------- image : ANTsImage image from which curvature is calculated sigma : scalar smoothing parameter opt : string mean by default, otherwise `gaussian` or `characterize` Returns ------- ANTsImage Example ------- >>> import ants >>> image = ants.image_read(ants.get_ants_data('mni')).resample_image((3,3,3)) >>> imagecurv = ants.weingarten_image_curvature(image)
[ "Uses", "the", "weingarten", "map", "to", "estimate", "image", "mean", "or", "gaussian", "curvature" ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/weingarten_image_curvature.py#L11-L69
237,210
ANTsX/ANTsPy
ants/core/ants_image_io.py
from_numpy
def from_numpy(data, origin=None, spacing=None, direction=None, has_components=False, is_rgb=False): """ Create an ANTsImage object from a numpy array ANTsR function: `as.antsImage` Arguments --------- data : ndarray image data array origin : tuple/list image origin spacing : tuple/list image spacing direction : list/ndarray image direction has_components : boolean whether the image has components Returns ------- ANTsImage image with given data and any given information """ data = data.astype('float32') if data.dtype.name == 'float64' else data img = _from_numpy(data.T.copy(), origin, spacing, direction, has_components, is_rgb) return img
python
def from_numpy(data, origin=None, spacing=None, direction=None, has_components=False, is_rgb=False): """ Create an ANTsImage object from a numpy array ANTsR function: `as.antsImage` Arguments --------- data : ndarray image data array origin : tuple/list image origin spacing : tuple/list image spacing direction : list/ndarray image direction has_components : boolean whether the image has components Returns ------- ANTsImage image with given data and any given information """ data = data.astype('float32') if data.dtype.name == 'float64' else data img = _from_numpy(data.T.copy(), origin, spacing, direction, has_components, is_rgb) return img
[ "def", "from_numpy", "(", "data", ",", "origin", "=", "None", ",", "spacing", "=", "None", ",", "direction", "=", "None", ",", "has_components", "=", "False", ",", "is_rgb", "=", "False", ")", ":", "data", "=", "data", ".", "astype", "(", "'float32'", ")", "if", "data", ".", "dtype", ".", "name", "==", "'float64'", "else", "data", "img", "=", "_from_numpy", "(", "data", ".", "T", ".", "copy", "(", ")", ",", "origin", ",", "spacing", ",", "direction", ",", "has_components", ",", "is_rgb", ")", "return", "img" ]
Create an ANTsImage object from a numpy array ANTsR function: `as.antsImage` Arguments --------- data : ndarray image data array origin : tuple/list image origin spacing : tuple/list image spacing direction : list/ndarray image direction has_components : boolean whether the image has components Returns ------- ANTsImage image with given data and any given information
[ "Create", "an", "ANTsImage", "object", "from", "a", "numpy", "array" ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image_io.py#L76-L106
237,211
ANTsX/ANTsPy
ants/core/ants_image_io.py
_from_numpy
def _from_numpy(data, origin=None, spacing=None, direction=None, has_components=False, is_rgb=False): """ Internal function for creating an ANTsImage """ if is_rgb: has_components = True ndim = data.ndim if has_components: ndim -= 1 dtype = data.dtype.name ptype = _npy_to_itk_map[dtype] data = np.array(data) if origin is None: origin = tuple([0.]*ndim) if spacing is None: spacing = tuple([1.]*ndim) if direction is None: direction = np.eye(ndim) libfn = utils.get_lib_fn('fromNumpy%s%i' % (_ntype_type_map[dtype], ndim)) if not has_components: itk_image = libfn(data, data.shape[::-1]) ants_image = iio.ANTsImage(pixeltype=ptype, dimension=ndim, components=1, pointer=itk_image) ants_image.set_origin(origin) ants_image.set_spacing(spacing) ants_image.set_direction(direction) ants_image._ndarr = data else: arrays = [data[i,...].copy() for i in range(data.shape[0])] data_shape = arrays[0].shape ants_images = [] for i in range(len(arrays)): tmp_ptr = libfn(arrays[i], data_shape[::-1]) tmp_img = iio.ANTsImage(pixeltype=ptype, dimension=ndim, components=1, pointer=tmp_ptr) tmp_img.set_origin(origin) tmp_img.set_spacing(spacing) tmp_img.set_direction(direction) tmp_img._ndarr = arrays[i] ants_images.append(tmp_img) ants_image = utils.merge_channels(ants_images) if is_rgb: ants_image = ants_image.vector_to_rgb() return ants_image
python
def _from_numpy(data, origin=None, spacing=None, direction=None, has_components=False, is_rgb=False): """ Internal function for creating an ANTsImage """ if is_rgb: has_components = True ndim = data.ndim if has_components: ndim -= 1 dtype = data.dtype.name ptype = _npy_to_itk_map[dtype] data = np.array(data) if origin is None: origin = tuple([0.]*ndim) if spacing is None: spacing = tuple([1.]*ndim) if direction is None: direction = np.eye(ndim) libfn = utils.get_lib_fn('fromNumpy%s%i' % (_ntype_type_map[dtype], ndim)) if not has_components: itk_image = libfn(data, data.shape[::-1]) ants_image = iio.ANTsImage(pixeltype=ptype, dimension=ndim, components=1, pointer=itk_image) ants_image.set_origin(origin) ants_image.set_spacing(spacing) ants_image.set_direction(direction) ants_image._ndarr = data else: arrays = [data[i,...].copy() for i in range(data.shape[0])] data_shape = arrays[0].shape ants_images = [] for i in range(len(arrays)): tmp_ptr = libfn(arrays[i], data_shape[::-1]) tmp_img = iio.ANTsImage(pixeltype=ptype, dimension=ndim, components=1, pointer=tmp_ptr) tmp_img.set_origin(origin) tmp_img.set_spacing(spacing) tmp_img.set_direction(direction) tmp_img._ndarr = arrays[i] ants_images.append(tmp_img) ants_image = utils.merge_channels(ants_images) if is_rgb: ants_image = ants_image.vector_to_rgb() return ants_image
[ "def", "_from_numpy", "(", "data", ",", "origin", "=", "None", ",", "spacing", "=", "None", ",", "direction", "=", "None", ",", "has_components", "=", "False", ",", "is_rgb", "=", "False", ")", ":", "if", "is_rgb", ":", "has_components", "=", "True", "ndim", "=", "data", ".", "ndim", "if", "has_components", ":", "ndim", "-=", "1", "dtype", "=", "data", ".", "dtype", ".", "name", "ptype", "=", "_npy_to_itk_map", "[", "dtype", "]", "data", "=", "np", ".", "array", "(", "data", ")", "if", "origin", "is", "None", ":", "origin", "=", "tuple", "(", "[", "0.", "]", "*", "ndim", ")", "if", "spacing", "is", "None", ":", "spacing", "=", "tuple", "(", "[", "1.", "]", "*", "ndim", ")", "if", "direction", "is", "None", ":", "direction", "=", "np", ".", "eye", "(", "ndim", ")", "libfn", "=", "utils", ".", "get_lib_fn", "(", "'fromNumpy%s%i'", "%", "(", "_ntype_type_map", "[", "dtype", "]", ",", "ndim", ")", ")", "if", "not", "has_components", ":", "itk_image", "=", "libfn", "(", "data", ",", "data", ".", "shape", "[", ":", ":", "-", "1", "]", ")", "ants_image", "=", "iio", ".", "ANTsImage", "(", "pixeltype", "=", "ptype", ",", "dimension", "=", "ndim", ",", "components", "=", "1", ",", "pointer", "=", "itk_image", ")", "ants_image", ".", "set_origin", "(", "origin", ")", "ants_image", ".", "set_spacing", "(", "spacing", ")", "ants_image", ".", "set_direction", "(", "direction", ")", "ants_image", ".", "_ndarr", "=", "data", "else", ":", "arrays", "=", "[", "data", "[", "i", ",", "...", "]", ".", "copy", "(", ")", "for", "i", "in", "range", "(", "data", ".", "shape", "[", "0", "]", ")", "]", "data_shape", "=", "arrays", "[", "0", "]", ".", "shape", "ants_images", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "arrays", ")", ")", ":", "tmp_ptr", "=", "libfn", "(", "arrays", "[", "i", "]", ",", "data_shape", "[", ":", ":", "-", "1", "]", ")", "tmp_img", "=", "iio", ".", "ANTsImage", "(", "pixeltype", "=", "ptype", ",", "dimension", "=", "ndim", ",", "components", "=", "1", ",", "pointer", "=", "tmp_ptr", ")", "tmp_img", ".", "set_origin", "(", "origin", ")", "tmp_img", ".", "set_spacing", "(", "spacing", ")", "tmp_img", ".", "set_direction", "(", "direction", ")", "tmp_img", ".", "_ndarr", "=", "arrays", "[", "i", "]", "ants_images", ".", "append", "(", "tmp_img", ")", "ants_image", "=", "utils", ".", "merge_channels", "(", "ants_images", ")", "if", "is_rgb", ":", "ants_image", "=", "ants_image", ".", "vector_to_rgb", "(", ")", "return", "ants_image" ]
Internal function for creating an ANTsImage
[ "Internal", "function", "for", "creating", "an", "ANTsImage" ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image_io.py#L109-L152
237,212
ANTsX/ANTsPy
ants/core/ants_image_io.py
make_image
def make_image(imagesize, voxval=0, spacing=None, origin=None, direction=None, has_components=False, pixeltype='float'): """ Make an image with given size and voxel value or given a mask and vector ANTsR function: `makeImage` Arguments --------- shape : tuple/ANTsImage input image size or mask voxval : scalar input image value or vector, size of mask spacing : tuple/list image spatial resolution origin : tuple/list image spatial origin direction : list/ndarray direction matrix to convert from index to physical space components : boolean whether there are components per pixel or not pixeltype : float data type of image values Returns ------- ANTsImage """ if isinstance(imagesize, iio.ANTsImage): img = imagesize.clone() sel = imagesize > 0 if voxval.ndim > 1: voxval = voxval.flatten() if (len(voxval) == int((sel>0).sum())) or (len(voxval) == 0): img[sel] = voxval else: raise ValueError('Num given voxels %i not same as num positive values %i in `imagesize`' % (len(voxval), int((sel>0).sum()))) return img else: if isinstance(voxval, (tuple,list,np.ndarray)): array = np.asarray(voxval).astype('float32').reshape(imagesize) else: array = np.full(imagesize,voxval,dtype='float32') image = from_numpy(array, origin=origin, spacing=spacing, direction=direction, has_components=has_components) return image.clone(pixeltype)
python
def make_image(imagesize, voxval=0, spacing=None, origin=None, direction=None, has_components=False, pixeltype='float'): """ Make an image with given size and voxel value or given a mask and vector ANTsR function: `makeImage` Arguments --------- shape : tuple/ANTsImage input image size or mask voxval : scalar input image value or vector, size of mask spacing : tuple/list image spatial resolution origin : tuple/list image spatial origin direction : list/ndarray direction matrix to convert from index to physical space components : boolean whether there are components per pixel or not pixeltype : float data type of image values Returns ------- ANTsImage """ if isinstance(imagesize, iio.ANTsImage): img = imagesize.clone() sel = imagesize > 0 if voxval.ndim > 1: voxval = voxval.flatten() if (len(voxval) == int((sel>0).sum())) or (len(voxval) == 0): img[sel] = voxval else: raise ValueError('Num given voxels %i not same as num positive values %i in `imagesize`' % (len(voxval), int((sel>0).sum()))) return img else: if isinstance(voxval, (tuple,list,np.ndarray)): array = np.asarray(voxval).astype('float32').reshape(imagesize) else: array = np.full(imagesize,voxval,dtype='float32') image = from_numpy(array, origin=origin, spacing=spacing, direction=direction, has_components=has_components) return image.clone(pixeltype)
[ "def", "make_image", "(", "imagesize", ",", "voxval", "=", "0", ",", "spacing", "=", "None", ",", "origin", "=", "None", ",", "direction", "=", "None", ",", "has_components", "=", "False", ",", "pixeltype", "=", "'float'", ")", ":", "if", "isinstance", "(", "imagesize", ",", "iio", ".", "ANTsImage", ")", ":", "img", "=", "imagesize", ".", "clone", "(", ")", "sel", "=", "imagesize", ">", "0", "if", "voxval", ".", "ndim", ">", "1", ":", "voxval", "=", "voxval", ".", "flatten", "(", ")", "if", "(", "len", "(", "voxval", ")", "==", "int", "(", "(", "sel", ">", "0", ")", ".", "sum", "(", ")", ")", ")", "or", "(", "len", "(", "voxval", ")", "==", "0", ")", ":", "img", "[", "sel", "]", "=", "voxval", "else", ":", "raise", "ValueError", "(", "'Num given voxels %i not same as num positive values %i in `imagesize`'", "%", "(", "len", "(", "voxval", ")", ",", "int", "(", "(", "sel", ">", "0", ")", ".", "sum", "(", ")", ")", ")", ")", "return", "img", "else", ":", "if", "isinstance", "(", "voxval", ",", "(", "tuple", ",", "list", ",", "np", ".", "ndarray", ")", ")", ":", "array", "=", "np", ".", "asarray", "(", "voxval", ")", ".", "astype", "(", "'float32'", ")", ".", "reshape", "(", "imagesize", ")", "else", ":", "array", "=", "np", ".", "full", "(", "imagesize", ",", "voxval", ",", "dtype", "=", "'float32'", ")", "image", "=", "from_numpy", "(", "array", ",", "origin", "=", "origin", ",", "spacing", "=", "spacing", ",", "direction", "=", "direction", ",", "has_components", "=", "has_components", ")", "return", "image", ".", "clone", "(", "pixeltype", ")" ]
Make an image with given size and voxel value or given a mask and vector ANTsR function: `makeImage` Arguments --------- shape : tuple/ANTsImage input image size or mask voxval : scalar input image value or vector, size of mask spacing : tuple/list image spatial resolution origin : tuple/list image spatial origin direction : list/ndarray direction matrix to convert from index to physical space components : boolean whether there are components per pixel or not pixeltype : float data type of image values Returns ------- ANTsImage
[ "Make", "an", "image", "with", "given", "size", "and", "voxel", "value", "or", "given", "a", "mask", "and", "vector" ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image_io.py#L155-L205
237,213
ANTsX/ANTsPy
ants/core/ants_image_io.py
matrix_to_images
def matrix_to_images(data_matrix, mask): """ Unmasks rows of a matrix and writes as images ANTsR function: `matrixToImages` Arguments --------- data_matrix : numpy.ndarray each row corresponds to an image array should have number of columns equal to non-zero voxels in the mask mask : ANTsImage image containing a binary mask. Rows of the matrix are unmasked and written as images. The mask defines the output image space Returns ------- list of ANTsImage types """ if data_matrix.ndim > 2: data_matrix = data_matrix.reshape(data_matrix.shape[0], -1) numimages = len(data_matrix) numVoxelsInMatrix = data_matrix.shape[1] numVoxelsInMask = (mask >= 0.5).sum() if numVoxelsInMask != numVoxelsInMatrix: raise ValueError('Num masked voxels %i must match data matrix %i' % (numVoxelsInMask, numVoxelsInMatrix)) imagelist = [] for i in range(numimages): img = mask.clone() img[mask >= 0.5] = data_matrix[i,:] imagelist.append(img) return imagelist
python
def matrix_to_images(data_matrix, mask): """ Unmasks rows of a matrix and writes as images ANTsR function: `matrixToImages` Arguments --------- data_matrix : numpy.ndarray each row corresponds to an image array should have number of columns equal to non-zero voxels in the mask mask : ANTsImage image containing a binary mask. Rows of the matrix are unmasked and written as images. The mask defines the output image space Returns ------- list of ANTsImage types """ if data_matrix.ndim > 2: data_matrix = data_matrix.reshape(data_matrix.shape[0], -1) numimages = len(data_matrix) numVoxelsInMatrix = data_matrix.shape[1] numVoxelsInMask = (mask >= 0.5).sum() if numVoxelsInMask != numVoxelsInMatrix: raise ValueError('Num masked voxels %i must match data matrix %i' % (numVoxelsInMask, numVoxelsInMatrix)) imagelist = [] for i in range(numimages): img = mask.clone() img[mask >= 0.5] = data_matrix[i,:] imagelist.append(img) return imagelist
[ "def", "matrix_to_images", "(", "data_matrix", ",", "mask", ")", ":", "if", "data_matrix", ".", "ndim", ">", "2", ":", "data_matrix", "=", "data_matrix", ".", "reshape", "(", "data_matrix", ".", "shape", "[", "0", "]", ",", "-", "1", ")", "numimages", "=", "len", "(", "data_matrix", ")", "numVoxelsInMatrix", "=", "data_matrix", ".", "shape", "[", "1", "]", "numVoxelsInMask", "=", "(", "mask", ">=", "0.5", ")", ".", "sum", "(", ")", "if", "numVoxelsInMask", "!=", "numVoxelsInMatrix", ":", "raise", "ValueError", "(", "'Num masked voxels %i must match data matrix %i'", "%", "(", "numVoxelsInMask", ",", "numVoxelsInMatrix", ")", ")", "imagelist", "=", "[", "]", "for", "i", "in", "range", "(", "numimages", ")", ":", "img", "=", "mask", ".", "clone", "(", ")", "img", "[", "mask", ">=", "0.5", "]", "=", "data_matrix", "[", "i", ",", ":", "]", "imagelist", ".", "append", "(", "img", ")", "return", "imagelist" ]
Unmasks rows of a matrix and writes as images ANTsR function: `matrixToImages` Arguments --------- data_matrix : numpy.ndarray each row corresponds to an image array should have number of columns equal to non-zero voxels in the mask mask : ANTsImage image containing a binary mask. Rows of the matrix are unmasked and written as images. The mask defines the output image space Returns ------- list of ANTsImage types
[ "Unmasks", "rows", "of", "a", "matrix", "and", "writes", "as", "images" ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image_io.py#L208-L243
237,214
ANTsX/ANTsPy
ants/core/ants_image_io.py
images_to_matrix
def images_to_matrix(image_list, mask=None, sigma=None, epsilon=0.5 ): """ Read images into rows of a matrix, given a mask - much faster for large datasets as it is based on C++ implementations. ANTsR function: `imagesToMatrix` Arguments --------- image_list : list of ANTsImage types images to convert to ndarray mask : ANTsImage (optional) image containing binary mask. voxels in the mask are placed in the matrix sigma : scaler (optional) smoothing factor epsilon : scalar threshold for mask Returns ------- ndarray array with a row for each image shape = (N_IMAGES, N_VOXELS) Example ------- >>> import ants >>> img = ants.image_read(ants.get_ants_data('r16')) >>> img2 = ants.image_read(ants.get_ants_data('r16')) >>> img3 = ants.image_read(ants.get_ants_data('r16')) >>> mat = ants.image_list_to_matrix([img,img2,img3]) """ def listfunc(x): if np.sum(np.array(x.shape) - np.array(mask.shape)) != 0: x = reg.resample_image_to_target(x, mask, 2) return x[mask] if mask is None: mask = utils.get_mask(image_list[0]) num_images = len(image_list) mask_arr = mask.numpy() >= epsilon num_voxels = np.sum(mask_arr) data_matrix = np.empty((num_images, num_voxels)) do_smooth = sigma is not None for i,img in enumerate(image_list): if do_smooth: data_matrix[i, :] = listfunc(utils.smooth_image(img, sigma, sigma_in_physical_coordinates=True)) else: data_matrix[i,:] = listfunc(img) return data_matrix
python
def images_to_matrix(image_list, mask=None, sigma=None, epsilon=0.5 ): """ Read images into rows of a matrix, given a mask - much faster for large datasets as it is based on C++ implementations. ANTsR function: `imagesToMatrix` Arguments --------- image_list : list of ANTsImage types images to convert to ndarray mask : ANTsImage (optional) image containing binary mask. voxels in the mask are placed in the matrix sigma : scaler (optional) smoothing factor epsilon : scalar threshold for mask Returns ------- ndarray array with a row for each image shape = (N_IMAGES, N_VOXELS) Example ------- >>> import ants >>> img = ants.image_read(ants.get_ants_data('r16')) >>> img2 = ants.image_read(ants.get_ants_data('r16')) >>> img3 = ants.image_read(ants.get_ants_data('r16')) >>> mat = ants.image_list_to_matrix([img,img2,img3]) """ def listfunc(x): if np.sum(np.array(x.shape) - np.array(mask.shape)) != 0: x = reg.resample_image_to_target(x, mask, 2) return x[mask] if mask is None: mask = utils.get_mask(image_list[0]) num_images = len(image_list) mask_arr = mask.numpy() >= epsilon num_voxels = np.sum(mask_arr) data_matrix = np.empty((num_images, num_voxels)) do_smooth = sigma is not None for i,img in enumerate(image_list): if do_smooth: data_matrix[i, :] = listfunc(utils.smooth_image(img, sigma, sigma_in_physical_coordinates=True)) else: data_matrix[i,:] = listfunc(img) return data_matrix
[ "def", "images_to_matrix", "(", "image_list", ",", "mask", "=", "None", ",", "sigma", "=", "None", ",", "epsilon", "=", "0.5", ")", ":", "def", "listfunc", "(", "x", ")", ":", "if", "np", ".", "sum", "(", "np", ".", "array", "(", "x", ".", "shape", ")", "-", "np", ".", "array", "(", "mask", ".", "shape", ")", ")", "!=", "0", ":", "x", "=", "reg", ".", "resample_image_to_target", "(", "x", ",", "mask", ",", "2", ")", "return", "x", "[", "mask", "]", "if", "mask", "is", "None", ":", "mask", "=", "utils", ".", "get_mask", "(", "image_list", "[", "0", "]", ")", "num_images", "=", "len", "(", "image_list", ")", "mask_arr", "=", "mask", ".", "numpy", "(", ")", ">=", "epsilon", "num_voxels", "=", "np", ".", "sum", "(", "mask_arr", ")", "data_matrix", "=", "np", ".", "empty", "(", "(", "num_images", ",", "num_voxels", ")", ")", "do_smooth", "=", "sigma", "is", "not", "None", "for", "i", ",", "img", "in", "enumerate", "(", "image_list", ")", ":", "if", "do_smooth", ":", "data_matrix", "[", "i", ",", ":", "]", "=", "listfunc", "(", "utils", ".", "smooth_image", "(", "img", ",", "sigma", ",", "sigma_in_physical_coordinates", "=", "True", ")", ")", "else", ":", "data_matrix", "[", "i", ",", ":", "]", "=", "listfunc", "(", "img", ")", "return", "data_matrix" ]
Read images into rows of a matrix, given a mask - much faster for large datasets as it is based on C++ implementations. ANTsR function: `imagesToMatrix` Arguments --------- image_list : list of ANTsImage types images to convert to ndarray mask : ANTsImage (optional) image containing binary mask. voxels in the mask are placed in the matrix sigma : scaler (optional) smoothing factor epsilon : scalar threshold for mask Returns ------- ndarray array with a row for each image shape = (N_IMAGES, N_VOXELS) Example ------- >>> import ants >>> img = ants.image_read(ants.get_ants_data('r16')) >>> img2 = ants.image_read(ants.get_ants_data('r16')) >>> img3 = ants.image_read(ants.get_ants_data('r16')) >>> mat = ants.image_list_to_matrix([img,img2,img3])
[ "Read", "images", "into", "rows", "of", "a", "matrix", "given", "a", "mask", "-", "much", "faster", "for", "large", "datasets", "as", "it", "is", "based", "on", "C", "++", "implementations", "." ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image_io.py#L247-L301
237,215
ANTsX/ANTsPy
ants/core/ants_image_io.py
timeseries_to_matrix
def timeseries_to_matrix( image, mask=None ): """ Convert a timeseries image into a matrix. ANTsR function: `timeseries2matrix` Arguments --------- image : image whose slices we convert to a matrix. E.g. a 3D image of size x by y by z will convert to a z by x*y sized matrix mask : ANTsImage (optional) image containing binary mask. voxels in the mask are placed in the matrix Returns ------- ndarray array with a row for each image shape = (N_IMAGES, N_VOXELS) Example ------- >>> import ants >>> img = ants.make_image( (10,10,10,5 ) ) >>> mat = ants.timeseries_to_matrix( img ) """ temp = utils.ndimage_to_list( image ) if mask is None: mask = temp[0]*0 + 1 return image_list_to_matrix( temp, mask )
python
def timeseries_to_matrix( image, mask=None ): """ Convert a timeseries image into a matrix. ANTsR function: `timeseries2matrix` Arguments --------- image : image whose slices we convert to a matrix. E.g. a 3D image of size x by y by z will convert to a z by x*y sized matrix mask : ANTsImage (optional) image containing binary mask. voxels in the mask are placed in the matrix Returns ------- ndarray array with a row for each image shape = (N_IMAGES, N_VOXELS) Example ------- >>> import ants >>> img = ants.make_image( (10,10,10,5 ) ) >>> mat = ants.timeseries_to_matrix( img ) """ temp = utils.ndimage_to_list( image ) if mask is None: mask = temp[0]*0 + 1 return image_list_to_matrix( temp, mask )
[ "def", "timeseries_to_matrix", "(", "image", ",", "mask", "=", "None", ")", ":", "temp", "=", "utils", ".", "ndimage_to_list", "(", "image", ")", "if", "mask", "is", "None", ":", "mask", "=", "temp", "[", "0", "]", "*", "0", "+", "1", "return", "image_list_to_matrix", "(", "temp", ",", "mask", ")" ]
Convert a timeseries image into a matrix. ANTsR function: `timeseries2matrix` Arguments --------- image : image whose slices we convert to a matrix. E.g. a 3D image of size x by y by z will convert to a z by x*y sized matrix mask : ANTsImage (optional) image containing binary mask. voxels in the mask are placed in the matrix Returns ------- ndarray array with a row for each image shape = (N_IMAGES, N_VOXELS) Example ------- >>> import ants >>> img = ants.make_image( (10,10,10,5 ) ) >>> mat = ants.timeseries_to_matrix( img )
[ "Convert", "a", "timeseries", "image", "into", "a", "matrix", "." ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image_io.py#L307-L336
237,216
ANTsX/ANTsPy
ants/core/ants_image_io.py
matrix_to_timeseries
def matrix_to_timeseries( image, matrix, mask=None ): """ converts a matrix to a ND image. ANTsR function: `matrix2timeseries` Arguments --------- image: reference ND image matrix: matrix to convert to image mask: mask image defining voxels of interest Returns ------- ANTsImage Example ------- >>> import ants >>> img = ants.make_image( (10,10,10,5 ) ) >>> mask = ants.ndimage_to_list( img )[0] * 0 >>> mask[ 4:8, 4:8, 4:8 ] = 1 >>> mat = ants.timeseries_to_matrix( img, mask = mask ) >>> img2 = ants.matrix_to_timeseries( img, mat, mask) """ if mask is None: mask = temp[0]*0 + 1 temp = matrix_to_images( matrix, mask ) newImage = utils.list_to_ndimage( image, temp) iio.copy_image_info( image, newImage) return(newImage)
python
def matrix_to_timeseries( image, matrix, mask=None ): """ converts a matrix to a ND image. ANTsR function: `matrix2timeseries` Arguments --------- image: reference ND image matrix: matrix to convert to image mask: mask image defining voxels of interest Returns ------- ANTsImage Example ------- >>> import ants >>> img = ants.make_image( (10,10,10,5 ) ) >>> mask = ants.ndimage_to_list( img )[0] * 0 >>> mask[ 4:8, 4:8, 4:8 ] = 1 >>> mat = ants.timeseries_to_matrix( img, mask = mask ) >>> img2 = ants.matrix_to_timeseries( img, mat, mask) """ if mask is None: mask = temp[0]*0 + 1 temp = matrix_to_images( matrix, mask ) newImage = utils.list_to_ndimage( image, temp) iio.copy_image_info( image, newImage) return(newImage)
[ "def", "matrix_to_timeseries", "(", "image", ",", "matrix", ",", "mask", "=", "None", ")", ":", "if", "mask", "is", "None", ":", "mask", "=", "temp", "[", "0", "]", "*", "0", "+", "1", "temp", "=", "matrix_to_images", "(", "matrix", ",", "mask", ")", "newImage", "=", "utils", ".", "list_to_ndimage", "(", "image", ",", "temp", ")", "iio", ".", "copy_image_info", "(", "image", ",", "newImage", ")", "return", "(", "newImage", ")" ]
converts a matrix to a ND image. ANTsR function: `matrix2timeseries` Arguments --------- image: reference ND image matrix: matrix to convert to image mask: mask image defining voxels of interest Returns ------- ANTsImage Example ------- >>> import ants >>> img = ants.make_image( (10,10,10,5 ) ) >>> mask = ants.ndimage_to_list( img )[0] * 0 >>> mask[ 4:8, 4:8, 4:8 ] = 1 >>> mat = ants.timeseries_to_matrix( img, mask = mask ) >>> img2 = ants.matrix_to_timeseries( img, mat, mask)
[ "converts", "a", "matrix", "to", "a", "ND", "image", "." ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image_io.py#L339-L374
237,217
ANTsX/ANTsPy
ants/core/ants_image_io.py
image_header_info
def image_header_info(filename): """ Read file info from image header ANTsR function: `antsImageHeaderInfo` Arguments --------- filename : string name of image file from which info will be read Returns ------- dict """ if not os.path.exists(filename): raise Exception('filename does not exist') libfn = utils.get_lib_fn('antsImageHeaderInfo') retval = libfn(filename) retval['dimensions'] = tuple(retval['dimensions']) retval['origin'] = tuple([round(o,4) for o in retval['origin']]) retval['spacing'] = tuple([round(s,4) for s in retval['spacing']]) retval['direction'] = np.round(retval['direction'],4) return retval
python
def image_header_info(filename): """ Read file info from image header ANTsR function: `antsImageHeaderInfo` Arguments --------- filename : string name of image file from which info will be read Returns ------- dict """ if not os.path.exists(filename): raise Exception('filename does not exist') libfn = utils.get_lib_fn('antsImageHeaderInfo') retval = libfn(filename) retval['dimensions'] = tuple(retval['dimensions']) retval['origin'] = tuple([round(o,4) for o in retval['origin']]) retval['spacing'] = tuple([round(s,4) for s in retval['spacing']]) retval['direction'] = np.round(retval['direction'],4) return retval
[ "def", "image_header_info", "(", "filename", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "raise", "Exception", "(", "'filename does not exist'", ")", "libfn", "=", "utils", ".", "get_lib_fn", "(", "'antsImageHeaderInfo'", ")", "retval", "=", "libfn", "(", "filename", ")", "retval", "[", "'dimensions'", "]", "=", "tuple", "(", "retval", "[", "'dimensions'", "]", ")", "retval", "[", "'origin'", "]", "=", "tuple", "(", "[", "round", "(", "o", ",", "4", ")", "for", "o", "in", "retval", "[", "'origin'", "]", "]", ")", "retval", "[", "'spacing'", "]", "=", "tuple", "(", "[", "round", "(", "s", ",", "4", ")", "for", "s", "in", "retval", "[", "'spacing'", "]", "]", ")", "retval", "[", "'direction'", "]", "=", "np", ".", "round", "(", "retval", "[", "'direction'", "]", ",", "4", ")", "return", "retval" ]
Read file info from image header ANTsR function: `antsImageHeaderInfo` Arguments --------- filename : string name of image file from which info will be read Returns ------- dict
[ "Read", "file", "info", "from", "image", "header" ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image_io.py#L377-L401
237,218
ANTsX/ANTsPy
ants/core/ants_image_io.py
image_read
def image_read(filename, dimension=None, pixeltype='float', reorient=False): """ Read an ANTsImage from file ANTsR function: `antsImageRead` Arguments --------- filename : string Name of the file to read the image from. dimension : int Number of dimensions of the image read. This need not be the same as the dimensions of the image in the file. Allowed values: 2, 3, 4. If not provided, the dimension is obtained from the image file pixeltype : string C++ datatype to be used to represent the pixels read. This datatype need not be the same as the datatype used in the file. Options: unsigned char, unsigned int, float, double reorient : boolean | string if True, the image will be reoriented to RPI if it is 3D if False, nothing will happen if string, this should be the 3-letter orientation to which the input image will reoriented if 3D. if the image is 2D, this argument is ignored Returns ------- ANTsImage """ if filename.endswith('.npy'): filename = os.path.expanduser(filename) img_array = np.load(filename) if os.path.exists(filename.replace('.npy', '.json')): with open(filename.replace('.npy', '.json')) as json_data: img_header = json.load(json_data) ants_image = from_numpy(img_array, origin=img_header.get('origin', None), spacing=img_header.get('spacing', None), direction=np.asarray(img_header.get('direction',None)), has_components=img_header.get('components',1)>1) else: img_header = {} ants_image = from_numpy(img_array) else: filename = os.path.expanduser(filename) if not os.path.exists(filename): raise ValueError('File %s does not exist!' % filename) hinfo = image_header_info(filename) ptype = hinfo['pixeltype'] pclass = hinfo['pixelclass'] ndim = hinfo['nDimensions'] ncomp = hinfo['nComponents'] is_rgb = True if pclass == 'rgb' else False if dimension is not None: ndim = dimension # error handling on pixelclass if pclass not in _supported_pclasses: raise ValueError('Pixel class %s not supported!' % pclass) # error handling on pixeltype if ptype in _unsupported_ptypes: ptype = _unsupported_ptype_map.get(ptype, 'unsupported') if ptype == 'unsupported': raise ValueError('Pixeltype %s not supported' % ptype) # error handling on dimension if (ndim < 2) or (ndim > 4): raise ValueError('Found %i-dimensional image - not supported!' % ndim) libfn = utils.get_lib_fn(_image_read_dict[pclass][ptype][ndim]) itk_pointer = libfn(filename) ants_image = iio.ANTsImage(pixeltype=ptype, dimension=ndim, components=ncomp, pointer=itk_pointer, is_rgb=is_rgb) if pixeltype is not None: ants_image = ants_image.clone(pixeltype) if (reorient != False) and (ants_image.dimension == 3): if reorient == True: ants_image = ants_image.reorient_image2('RPI') elif isinstance(reorient, str): ants_image = ants_image.reorient_image2(reorient) return ants_image
python
def image_read(filename, dimension=None, pixeltype='float', reorient=False): """ Read an ANTsImage from file ANTsR function: `antsImageRead` Arguments --------- filename : string Name of the file to read the image from. dimension : int Number of dimensions of the image read. This need not be the same as the dimensions of the image in the file. Allowed values: 2, 3, 4. If not provided, the dimension is obtained from the image file pixeltype : string C++ datatype to be used to represent the pixels read. This datatype need not be the same as the datatype used in the file. Options: unsigned char, unsigned int, float, double reorient : boolean | string if True, the image will be reoriented to RPI if it is 3D if False, nothing will happen if string, this should be the 3-letter orientation to which the input image will reoriented if 3D. if the image is 2D, this argument is ignored Returns ------- ANTsImage """ if filename.endswith('.npy'): filename = os.path.expanduser(filename) img_array = np.load(filename) if os.path.exists(filename.replace('.npy', '.json')): with open(filename.replace('.npy', '.json')) as json_data: img_header = json.load(json_data) ants_image = from_numpy(img_array, origin=img_header.get('origin', None), spacing=img_header.get('spacing', None), direction=np.asarray(img_header.get('direction',None)), has_components=img_header.get('components',1)>1) else: img_header = {} ants_image = from_numpy(img_array) else: filename = os.path.expanduser(filename) if not os.path.exists(filename): raise ValueError('File %s does not exist!' % filename) hinfo = image_header_info(filename) ptype = hinfo['pixeltype'] pclass = hinfo['pixelclass'] ndim = hinfo['nDimensions'] ncomp = hinfo['nComponents'] is_rgb = True if pclass == 'rgb' else False if dimension is not None: ndim = dimension # error handling on pixelclass if pclass not in _supported_pclasses: raise ValueError('Pixel class %s not supported!' % pclass) # error handling on pixeltype if ptype in _unsupported_ptypes: ptype = _unsupported_ptype_map.get(ptype, 'unsupported') if ptype == 'unsupported': raise ValueError('Pixeltype %s not supported' % ptype) # error handling on dimension if (ndim < 2) or (ndim > 4): raise ValueError('Found %i-dimensional image - not supported!' % ndim) libfn = utils.get_lib_fn(_image_read_dict[pclass][ptype][ndim]) itk_pointer = libfn(filename) ants_image = iio.ANTsImage(pixeltype=ptype, dimension=ndim, components=ncomp, pointer=itk_pointer, is_rgb=is_rgb) if pixeltype is not None: ants_image = ants_image.clone(pixeltype) if (reorient != False) and (ants_image.dimension == 3): if reorient == True: ants_image = ants_image.reorient_image2('RPI') elif isinstance(reorient, str): ants_image = ants_image.reorient_image2(reorient) return ants_image
[ "def", "image_read", "(", "filename", ",", "dimension", "=", "None", ",", "pixeltype", "=", "'float'", ",", "reorient", "=", "False", ")", ":", "if", "filename", ".", "endswith", "(", "'.npy'", ")", ":", "filename", "=", "os", ".", "path", ".", "expanduser", "(", "filename", ")", "img_array", "=", "np", ".", "load", "(", "filename", ")", "if", "os", ".", "path", ".", "exists", "(", "filename", ".", "replace", "(", "'.npy'", ",", "'.json'", ")", ")", ":", "with", "open", "(", "filename", ".", "replace", "(", "'.npy'", ",", "'.json'", ")", ")", "as", "json_data", ":", "img_header", "=", "json", ".", "load", "(", "json_data", ")", "ants_image", "=", "from_numpy", "(", "img_array", ",", "origin", "=", "img_header", ".", "get", "(", "'origin'", ",", "None", ")", ",", "spacing", "=", "img_header", ".", "get", "(", "'spacing'", ",", "None", ")", ",", "direction", "=", "np", ".", "asarray", "(", "img_header", ".", "get", "(", "'direction'", ",", "None", ")", ")", ",", "has_components", "=", "img_header", ".", "get", "(", "'components'", ",", "1", ")", ">", "1", ")", "else", ":", "img_header", "=", "{", "}", "ants_image", "=", "from_numpy", "(", "img_array", ")", "else", ":", "filename", "=", "os", ".", "path", ".", "expanduser", "(", "filename", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "raise", "ValueError", "(", "'File %s does not exist!'", "%", "filename", ")", "hinfo", "=", "image_header_info", "(", "filename", ")", "ptype", "=", "hinfo", "[", "'pixeltype'", "]", "pclass", "=", "hinfo", "[", "'pixelclass'", "]", "ndim", "=", "hinfo", "[", "'nDimensions'", "]", "ncomp", "=", "hinfo", "[", "'nComponents'", "]", "is_rgb", "=", "True", "if", "pclass", "==", "'rgb'", "else", "False", "if", "dimension", "is", "not", "None", ":", "ndim", "=", "dimension", "# error handling on pixelclass", "if", "pclass", "not", "in", "_supported_pclasses", ":", "raise", "ValueError", "(", "'Pixel class %s not supported!'", "%", "pclass", ")", "# error handling on pixeltype", "if", "ptype", "in", "_unsupported_ptypes", ":", "ptype", "=", "_unsupported_ptype_map", ".", "get", "(", "ptype", ",", "'unsupported'", ")", "if", "ptype", "==", "'unsupported'", ":", "raise", "ValueError", "(", "'Pixeltype %s not supported'", "%", "ptype", ")", "# error handling on dimension", "if", "(", "ndim", "<", "2", ")", "or", "(", "ndim", ">", "4", ")", ":", "raise", "ValueError", "(", "'Found %i-dimensional image - not supported!'", "%", "ndim", ")", "libfn", "=", "utils", ".", "get_lib_fn", "(", "_image_read_dict", "[", "pclass", "]", "[", "ptype", "]", "[", "ndim", "]", ")", "itk_pointer", "=", "libfn", "(", "filename", ")", "ants_image", "=", "iio", ".", "ANTsImage", "(", "pixeltype", "=", "ptype", ",", "dimension", "=", "ndim", ",", "components", "=", "ncomp", ",", "pointer", "=", "itk_pointer", ",", "is_rgb", "=", "is_rgb", ")", "if", "pixeltype", "is", "not", "None", ":", "ants_image", "=", "ants_image", ".", "clone", "(", "pixeltype", ")", "if", "(", "reorient", "!=", "False", ")", "and", "(", "ants_image", ".", "dimension", "==", "3", ")", ":", "if", "reorient", "==", "True", ":", "ants_image", "=", "ants_image", ".", "reorient_image2", "(", "'RPI'", ")", "elif", "isinstance", "(", "reorient", ",", "str", ")", ":", "ants_image", "=", "ants_image", ".", "reorient_image2", "(", "reorient", ")", "return", "ants_image" ]
Read an ANTsImage from file ANTsR function: `antsImageRead` Arguments --------- filename : string Name of the file to read the image from. dimension : int Number of dimensions of the image read. This need not be the same as the dimensions of the image in the file. Allowed values: 2, 3, 4. If not provided, the dimension is obtained from the image file pixeltype : string C++ datatype to be used to represent the pixels read. This datatype need not be the same as the datatype used in the file. Options: unsigned char, unsigned int, float, double reorient : boolean | string if True, the image will be reoriented to RPI if it is 3D if False, nothing will happen if string, this should be the 3-letter orientation to which the input image will reoriented if 3D. if the image is 2D, this argument is ignored Returns ------- ANTsImage
[ "Read", "an", "ANTsImage", "from", "file" ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image_io.py#L425-L515
237,219
ANTsX/ANTsPy
ants/core/ants_image_io.py
dicom_read
def dicom_read(directory, pixeltype='float'): """ Read a set of dicom files in a directory into a single ANTsImage. The origin of the resulting 3D image will be the origin of the first dicom image read. Arguments --------- directory : string folder in which all the dicom images exist Returns ------- ANTsImage Example ------- >>> import ants >>> img = ants.dicom_read('~/desktop/dicom-subject/') """ slices = [] imgidx = 0 for imgpath in os.listdir(directory): if imgpath.endswith('.dcm'): if imgidx == 0: tmp = image_read(os.path.join(directory,imgpath), dimension=3, pixeltype=pixeltype) origin = tmp.origin spacing = tmp.spacing direction = tmp.direction tmp = tmp.numpy()[:,:,0] else: tmp = image_read(os.path.join(directory,imgpath), dimension=2, pixeltype=pixeltype).numpy() slices.append(tmp) imgidx += 1 slices = np.stack(slices, axis=-1) return from_numpy(slices, origin=origin, spacing=spacing, direction=direction)
python
def dicom_read(directory, pixeltype='float'): """ Read a set of dicom files in a directory into a single ANTsImage. The origin of the resulting 3D image will be the origin of the first dicom image read. Arguments --------- directory : string folder in which all the dicom images exist Returns ------- ANTsImage Example ------- >>> import ants >>> img = ants.dicom_read('~/desktop/dicom-subject/') """ slices = [] imgidx = 0 for imgpath in os.listdir(directory): if imgpath.endswith('.dcm'): if imgidx == 0: tmp = image_read(os.path.join(directory,imgpath), dimension=3, pixeltype=pixeltype) origin = tmp.origin spacing = tmp.spacing direction = tmp.direction tmp = tmp.numpy()[:,:,0] else: tmp = image_read(os.path.join(directory,imgpath), dimension=2, pixeltype=pixeltype).numpy() slices.append(tmp) imgidx += 1 slices = np.stack(slices, axis=-1) return from_numpy(slices, origin=origin, spacing=spacing, direction=direction)
[ "def", "dicom_read", "(", "directory", ",", "pixeltype", "=", "'float'", ")", ":", "slices", "=", "[", "]", "imgidx", "=", "0", "for", "imgpath", "in", "os", ".", "listdir", "(", "directory", ")", ":", "if", "imgpath", ".", "endswith", "(", "'.dcm'", ")", ":", "if", "imgidx", "==", "0", ":", "tmp", "=", "image_read", "(", "os", ".", "path", ".", "join", "(", "directory", ",", "imgpath", ")", ",", "dimension", "=", "3", ",", "pixeltype", "=", "pixeltype", ")", "origin", "=", "tmp", ".", "origin", "spacing", "=", "tmp", ".", "spacing", "direction", "=", "tmp", ".", "direction", "tmp", "=", "tmp", ".", "numpy", "(", ")", "[", ":", ",", ":", ",", "0", "]", "else", ":", "tmp", "=", "image_read", "(", "os", ".", "path", ".", "join", "(", "directory", ",", "imgpath", ")", ",", "dimension", "=", "2", ",", "pixeltype", "=", "pixeltype", ")", ".", "numpy", "(", ")", "slices", ".", "append", "(", "tmp", ")", "imgidx", "+=", "1", "slices", "=", "np", ".", "stack", "(", "slices", ",", "axis", "=", "-", "1", ")", "return", "from_numpy", "(", "slices", ",", "origin", "=", "origin", ",", "spacing", "=", "spacing", ",", "direction", "=", "direction", ")" ]
Read a set of dicom files in a directory into a single ANTsImage. The origin of the resulting 3D image will be the origin of the first dicom image read. Arguments --------- directory : string folder in which all the dicom images exist Returns ------- ANTsImage Example ------- >>> import ants >>> img = ants.dicom_read('~/desktop/dicom-subject/')
[ "Read", "a", "set", "of", "dicom", "files", "in", "a", "directory", "into", "a", "single", "ANTsImage", ".", "The", "origin", "of", "the", "resulting", "3D", "image", "will", "be", "the", "origin", "of", "the", "first", "dicom", "image", "read", "." ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image_io.py#L518-L555
237,220
ANTsX/ANTsPy
ants/core/ants_image_io.py
image_write
def image_write(image, filename, ri=False): """ Write an ANTsImage to file ANTsR function: `antsImageWrite` Arguments --------- image : ANTsImage image to save to file filename : string name of file to which image will be saved ri : boolean if True, return image. This allows for using this function in a pipeline: >>> img2 = img.smooth_image(2.).image_write(file1, ri=True).threshold_image(0,20).image_write(file2, ri=True) if False, do not return image """ if filename.endswith('.npy'): img_array = image.numpy() img_header = {'origin': image.origin,'spacing': image.spacing, 'direction': image.direction.tolist(), 'components': image.components} np.save(filename, img_array) with open(filename.replace('.npy','.json'), 'w') as outfile: json.dump(img_header, outfile) else: image.to_file(filename) if ri: return image
python
def image_write(image, filename, ri=False): """ Write an ANTsImage to file ANTsR function: `antsImageWrite` Arguments --------- image : ANTsImage image to save to file filename : string name of file to which image will be saved ri : boolean if True, return image. This allows for using this function in a pipeline: >>> img2 = img.smooth_image(2.).image_write(file1, ri=True).threshold_image(0,20).image_write(file2, ri=True) if False, do not return image """ if filename.endswith('.npy'): img_array = image.numpy() img_header = {'origin': image.origin,'spacing': image.spacing, 'direction': image.direction.tolist(), 'components': image.components} np.save(filename, img_array) with open(filename.replace('.npy','.json'), 'w') as outfile: json.dump(img_header, outfile) else: image.to_file(filename) if ri: return image
[ "def", "image_write", "(", "image", ",", "filename", ",", "ri", "=", "False", ")", ":", "if", "filename", ".", "endswith", "(", "'.npy'", ")", ":", "img_array", "=", "image", ".", "numpy", "(", ")", "img_header", "=", "{", "'origin'", ":", "image", ".", "origin", ",", "'spacing'", ":", "image", ".", "spacing", ",", "'direction'", ":", "image", ".", "direction", ".", "tolist", "(", ")", ",", "'components'", ":", "image", ".", "components", "}", "np", ".", "save", "(", "filename", ",", "img_array", ")", "with", "open", "(", "filename", ".", "replace", "(", "'.npy'", ",", "'.json'", ")", ",", "'w'", ")", "as", "outfile", ":", "json", ".", "dump", "(", "img_header", ",", "outfile", ")", "else", ":", "image", ".", "to_file", "(", "filename", ")", "if", "ri", ":", "return", "image" ]
Write an ANTsImage to file ANTsR function: `antsImageWrite` Arguments --------- image : ANTsImage image to save to file filename : string name of file to which image will be saved ri : boolean if True, return image. This allows for using this function in a pipeline: >>> img2 = img.smooth_image(2.).image_write(file1, ri=True).threshold_image(0,20).image_write(file2, ri=True) if False, do not return image
[ "Write", "an", "ANTsImage", "to", "file" ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_image_io.py#L558-L589
237,221
ANTsX/ANTsPy
ants/segmentation/otsu.py
otsu_segmentation
def otsu_segmentation(image, k, mask=None): """ Otsu image segmentation This is a very fast segmentation algorithm good for quick explortation, but does not return probability maps. ANTsR function: `thresholdImage(image, 'Otsu', k)` Arguments --------- image : ANTsImage input image k : integer integer number of classes. Note that a background class will be added to this, so the resulting segmentation will have k+1 unique values. mask : ANTsImage segment inside this mask Returns ------- ANTsImage Example ------- >>> import ants >>> mni = ants.image_read(ants.get_data('mni')) >>> seg = mni.otsu_segmentation(k=3) #0=bg,1=csf,2=gm,3=wm """ if mask is not None: image = image.mask_image(mask) seg = image.threshold_image('Otsu', k) return seg
python
def otsu_segmentation(image, k, mask=None): """ Otsu image segmentation This is a very fast segmentation algorithm good for quick explortation, but does not return probability maps. ANTsR function: `thresholdImage(image, 'Otsu', k)` Arguments --------- image : ANTsImage input image k : integer integer number of classes. Note that a background class will be added to this, so the resulting segmentation will have k+1 unique values. mask : ANTsImage segment inside this mask Returns ------- ANTsImage Example ------- >>> import ants >>> mni = ants.image_read(ants.get_data('mni')) >>> seg = mni.otsu_segmentation(k=3) #0=bg,1=csf,2=gm,3=wm """ if mask is not None: image = image.mask_image(mask) seg = image.threshold_image('Otsu', k) return seg
[ "def", "otsu_segmentation", "(", "image", ",", "k", ",", "mask", "=", "None", ")", ":", "if", "mask", "is", "not", "None", ":", "image", "=", "image", ".", "mask_image", "(", "mask", ")", "seg", "=", "image", ".", "threshold_image", "(", "'Otsu'", ",", "k", ")", "return", "seg" ]
Otsu image segmentation This is a very fast segmentation algorithm good for quick explortation, but does not return probability maps. ANTsR function: `thresholdImage(image, 'Otsu', k)` Arguments --------- image : ANTsImage input image k : integer integer number of classes. Note that a background class will be added to this, so the resulting segmentation will have k+1 unique values. mask : ANTsImage segment inside this mask Returns ------- ANTsImage Example ------- >>> import ants >>> mni = ants.image_read(ants.get_data('mni')) >>> seg = mni.otsu_segmentation(k=3) #0=bg,1=csf,2=gm,3=wm
[ "Otsu", "image", "segmentation" ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/segmentation/otsu.py#L7-L43
237,222
ANTsX/ANTsPy
ants/utils/crop_image.py
crop_image
def crop_image(image, label_image=None, label=1): """ Use a label image to crop a smaller ANTsImage from within a larger ANTsImage ANTsR function: `cropImage` Arguments --------- image : ANTsImage image to crop label_image : ANTsImage image with label values. If not supplied, estimated from data. label : integer the label value to use Returns ------- ANTsImage Example ------- >>> import ants >>> fi = ants.image_read( ants.get_ants_data('r16') ) >>> cropped = ants.crop_image(fi) >>> cropped = ants.crop_image(fi, fi, 100 ) """ inpixeltype = image.pixeltype ndim = image.dimension if image.pixeltype != 'float': image = image.clone('float') if label_image is None: label_image = get_mask(image) if label_image.pixeltype != 'float': label_image = label_image.clone('float') libfn = utils.get_lib_fn('cropImageF%i' % ndim) itkimage = libfn(image.pointer, label_image.pointer, label, 0, [], []) return iio.ANTsImage(pixeltype='float', dimension=ndim, components=image.components, pointer=itkimage).clone(inpixeltype)
python
def crop_image(image, label_image=None, label=1): """ Use a label image to crop a smaller ANTsImage from within a larger ANTsImage ANTsR function: `cropImage` Arguments --------- image : ANTsImage image to crop label_image : ANTsImage image with label values. If not supplied, estimated from data. label : integer the label value to use Returns ------- ANTsImage Example ------- >>> import ants >>> fi = ants.image_read( ants.get_ants_data('r16') ) >>> cropped = ants.crop_image(fi) >>> cropped = ants.crop_image(fi, fi, 100 ) """ inpixeltype = image.pixeltype ndim = image.dimension if image.pixeltype != 'float': image = image.clone('float') if label_image is None: label_image = get_mask(image) if label_image.pixeltype != 'float': label_image = label_image.clone('float') libfn = utils.get_lib_fn('cropImageF%i' % ndim) itkimage = libfn(image.pointer, label_image.pointer, label, 0, [], []) return iio.ANTsImage(pixeltype='float', dimension=ndim, components=image.components, pointer=itkimage).clone(inpixeltype)
[ "def", "crop_image", "(", "image", ",", "label_image", "=", "None", ",", "label", "=", "1", ")", ":", "inpixeltype", "=", "image", ".", "pixeltype", "ndim", "=", "image", ".", "dimension", "if", "image", ".", "pixeltype", "!=", "'float'", ":", "image", "=", "image", ".", "clone", "(", "'float'", ")", "if", "label_image", "is", "None", ":", "label_image", "=", "get_mask", "(", "image", ")", "if", "label_image", ".", "pixeltype", "!=", "'float'", ":", "label_image", "=", "label_image", ".", "clone", "(", "'float'", ")", "libfn", "=", "utils", ".", "get_lib_fn", "(", "'cropImageF%i'", "%", "ndim", ")", "itkimage", "=", "libfn", "(", "image", ".", "pointer", ",", "label_image", ".", "pointer", ",", "label", ",", "0", ",", "[", "]", ",", "[", "]", ")", "return", "iio", ".", "ANTsImage", "(", "pixeltype", "=", "'float'", ",", "dimension", "=", "ndim", ",", "components", "=", "image", ".", "components", ",", "pointer", "=", "itkimage", ")", ".", "clone", "(", "inpixeltype", ")" ]
Use a label image to crop a smaller ANTsImage from within a larger ANTsImage ANTsR function: `cropImage` Arguments --------- image : ANTsImage image to crop label_image : ANTsImage image with label values. If not supplied, estimated from data. label : integer the label value to use Returns ------- ANTsImage Example ------- >>> import ants >>> fi = ants.image_read( ants.get_ants_data('r16') ) >>> cropped = ants.crop_image(fi) >>> cropped = ants.crop_image(fi, fi, 100 )
[ "Use", "a", "label", "image", "to", "crop", "a", "smaller", "ANTsImage", "from", "within", "a", "larger", "ANTsImage" ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/crop_image.py#L14-L56
237,223
ANTsX/ANTsPy
ants/utils/crop_image.py
decrop_image
def decrop_image(cropped_image, full_image): """ The inverse function for `ants.crop_image` ANTsR function: `decropImage` Arguments --------- cropped_image : ANTsImage cropped image full_image : ANTsImage image in which the cropped image will be put back Returns ------- ANTsImage Example ------- >>> import ants >>> fi = ants.image_read(ants.get_ants_data('r16')) >>> mask = ants.get_mask(fi) >>> cropped = ants.crop_image(fi, mask, 1) >>> cropped = ants.smooth_image(cropped, 1) >>> decropped = ants.decrop_image(cropped, fi) """ inpixeltype = 'float' if cropped_image.pixeltype != 'float': inpixeltype= cropped_image.pixeltype cropped_image = cropped_image.clone('float') if full_image.pixeltype != 'float': full_image = full_image.clone('float') libfn = utils.get_lib_fn('cropImageF%i' % cropped_image.dimension) itkimage = libfn(cropped_image.pointer, full_image.pointer, 1, 1, [], []) ants_image = iio.ANTsImage(pixeltype='float', dimension=cropped_image.dimension, components=cropped_image.components, pointer=itkimage) if inpixeltype != 'float': ants_image = ants_image.clone(inpixeltype) return ants_image
python
def decrop_image(cropped_image, full_image): """ The inverse function for `ants.crop_image` ANTsR function: `decropImage` Arguments --------- cropped_image : ANTsImage cropped image full_image : ANTsImage image in which the cropped image will be put back Returns ------- ANTsImage Example ------- >>> import ants >>> fi = ants.image_read(ants.get_ants_data('r16')) >>> mask = ants.get_mask(fi) >>> cropped = ants.crop_image(fi, mask, 1) >>> cropped = ants.smooth_image(cropped, 1) >>> decropped = ants.decrop_image(cropped, fi) """ inpixeltype = 'float' if cropped_image.pixeltype != 'float': inpixeltype= cropped_image.pixeltype cropped_image = cropped_image.clone('float') if full_image.pixeltype != 'float': full_image = full_image.clone('float') libfn = utils.get_lib_fn('cropImageF%i' % cropped_image.dimension) itkimage = libfn(cropped_image.pointer, full_image.pointer, 1, 1, [], []) ants_image = iio.ANTsImage(pixeltype='float', dimension=cropped_image.dimension, components=cropped_image.components, pointer=itkimage) if inpixeltype != 'float': ants_image = ants_image.clone(inpixeltype) return ants_image
[ "def", "decrop_image", "(", "cropped_image", ",", "full_image", ")", ":", "inpixeltype", "=", "'float'", "if", "cropped_image", ".", "pixeltype", "!=", "'float'", ":", "inpixeltype", "=", "cropped_image", ".", "pixeltype", "cropped_image", "=", "cropped_image", ".", "clone", "(", "'float'", ")", "if", "full_image", ".", "pixeltype", "!=", "'float'", ":", "full_image", "=", "full_image", ".", "clone", "(", "'float'", ")", "libfn", "=", "utils", ".", "get_lib_fn", "(", "'cropImageF%i'", "%", "cropped_image", ".", "dimension", ")", "itkimage", "=", "libfn", "(", "cropped_image", ".", "pointer", ",", "full_image", ".", "pointer", ",", "1", ",", "1", ",", "[", "]", ",", "[", "]", ")", "ants_image", "=", "iio", ".", "ANTsImage", "(", "pixeltype", "=", "'float'", ",", "dimension", "=", "cropped_image", ".", "dimension", ",", "components", "=", "cropped_image", ".", "components", ",", "pointer", "=", "itkimage", ")", "if", "inpixeltype", "!=", "'float'", ":", "ants_image", "=", "ants_image", ".", "clone", "(", "inpixeltype", ")", "return", "ants_image" ]
The inverse function for `ants.crop_image` ANTsR function: `decropImage` Arguments --------- cropped_image : ANTsImage cropped image full_image : ANTsImage image in which the cropped image will be put back Returns ------- ANTsImage Example ------- >>> import ants >>> fi = ants.image_read(ants.get_ants_data('r16')) >>> mask = ants.get_mask(fi) >>> cropped = ants.crop_image(fi, mask, 1) >>> cropped = ants.smooth_image(cropped, 1) >>> decropped = ants.decrop_image(cropped, fi)
[ "The", "inverse", "function", "for", "ants", ".", "crop_image" ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/crop_image.py#L108-L149
237,224
ANTsX/ANTsPy
ants/segmentation/kmeans.py
kmeans_segmentation
def kmeans_segmentation(image, k, kmask=None, mrf=0.1): """ K-means image segmentation that is a wrapper around `ants.atropos` ANTsR function: `kmeansSegmentation` Arguments --------- image : ANTsImage input image k : integer integer number of classes kmask : ANTsImage (optional) segment inside this mask mrf : scalar smoothness, higher is smoother Returns ------- ANTsImage Example ------- >>> import ants >>> fi = ants.image_read(ants.get_ants_data('r16'), 'float') >>> fi = ants.n3_bias_field_correction(fi, 2) >>> seg = ants.kmeans_segmentation(fi, 3) """ dim = image.dimension kmimage = utils.iMath(image, 'Normalize') if kmask is None: kmask = utils.get_mask(kmimage, 0.01, 1, cleanup=2) kmask = utils.iMath(kmask, 'FillHoles').threshold_image(1,2) nhood = 'x'.join(['1']*dim) mrf = '[%s,%s]' % (str(mrf), nhood) kmimage = atropos(a = kmimage, m = mrf, c = '[5,0]', i = 'kmeans[%s]'%(str(k)), x = kmask) kmimage['segmentation'] = kmimage['segmentation'].clone(image.pixeltype) return kmimage
python
def kmeans_segmentation(image, k, kmask=None, mrf=0.1): """ K-means image segmentation that is a wrapper around `ants.atropos` ANTsR function: `kmeansSegmentation` Arguments --------- image : ANTsImage input image k : integer integer number of classes kmask : ANTsImage (optional) segment inside this mask mrf : scalar smoothness, higher is smoother Returns ------- ANTsImage Example ------- >>> import ants >>> fi = ants.image_read(ants.get_ants_data('r16'), 'float') >>> fi = ants.n3_bias_field_correction(fi, 2) >>> seg = ants.kmeans_segmentation(fi, 3) """ dim = image.dimension kmimage = utils.iMath(image, 'Normalize') if kmask is None: kmask = utils.get_mask(kmimage, 0.01, 1, cleanup=2) kmask = utils.iMath(kmask, 'FillHoles').threshold_image(1,2) nhood = 'x'.join(['1']*dim) mrf = '[%s,%s]' % (str(mrf), nhood) kmimage = atropos(a = kmimage, m = mrf, c = '[5,0]', i = 'kmeans[%s]'%(str(k)), x = kmask) kmimage['segmentation'] = kmimage['segmentation'].clone(image.pixeltype) return kmimage
[ "def", "kmeans_segmentation", "(", "image", ",", "k", ",", "kmask", "=", "None", ",", "mrf", "=", "0.1", ")", ":", "dim", "=", "image", ".", "dimension", "kmimage", "=", "utils", ".", "iMath", "(", "image", ",", "'Normalize'", ")", "if", "kmask", "is", "None", ":", "kmask", "=", "utils", ".", "get_mask", "(", "kmimage", ",", "0.01", ",", "1", ",", "cleanup", "=", "2", ")", "kmask", "=", "utils", ".", "iMath", "(", "kmask", ",", "'FillHoles'", ")", ".", "threshold_image", "(", "1", ",", "2", ")", "nhood", "=", "'x'", ".", "join", "(", "[", "'1'", "]", "*", "dim", ")", "mrf", "=", "'[%s,%s]'", "%", "(", "str", "(", "mrf", ")", ",", "nhood", ")", "kmimage", "=", "atropos", "(", "a", "=", "kmimage", ",", "m", "=", "mrf", ",", "c", "=", "'[5,0]'", ",", "i", "=", "'kmeans[%s]'", "%", "(", "str", "(", "k", ")", ")", ",", "x", "=", "kmask", ")", "kmimage", "[", "'segmentation'", "]", "=", "kmimage", "[", "'segmentation'", "]", ".", "clone", "(", "image", ".", "pixeltype", ")", "return", "kmimage" ]
K-means image segmentation that is a wrapper around `ants.atropos` ANTsR function: `kmeansSegmentation` Arguments --------- image : ANTsImage input image k : integer integer number of classes kmask : ANTsImage (optional) segment inside this mask mrf : scalar smoothness, higher is smoother Returns ------- ANTsImage Example ------- >>> import ants >>> fi = ants.image_read(ants.get_ants_data('r16'), 'float') >>> fi = ants.n3_bias_field_correction(fi, 2) >>> seg = ants.kmeans_segmentation(fi, 3)
[ "K", "-", "means", "image", "segmentation", "that", "is", "a", "wrapper", "around", "ants", ".", "atropos" ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/segmentation/kmeans.py#L9-L49
237,225
ANTsX/ANTsPy
ants/registration/reorient_image.py
reorient_image2
def reorient_image2(image, orientation='RAS'): """ Reorient an image. Example ------- >>> import ants >>> mni = ants.image_read(ants.get_data('mni')) >>> mni2 = mni.reorient_image2() """ if image.dimension != 3: raise ValueError('image must have 3 dimensions') inpixeltype = image.pixeltype ndim = image.dimension if image.pixeltype != 'float': image = image.clone('float') libfn = utils.get_lib_fn('reorientImage2') itkimage = libfn(image.pointer, orientation) new_img = iio.ANTsImage(pixeltype='float', dimension=ndim, components=image.components, pointer=itkimage)#.clone(inpixeltype) if inpixeltype != 'float': new_img = new_img.clone(inpixeltype) return new_img
python
def reorient_image2(image, orientation='RAS'): """ Reorient an image. Example ------- >>> import ants >>> mni = ants.image_read(ants.get_data('mni')) >>> mni2 = mni.reorient_image2() """ if image.dimension != 3: raise ValueError('image must have 3 dimensions') inpixeltype = image.pixeltype ndim = image.dimension if image.pixeltype != 'float': image = image.clone('float') libfn = utils.get_lib_fn('reorientImage2') itkimage = libfn(image.pointer, orientation) new_img = iio.ANTsImage(pixeltype='float', dimension=ndim, components=image.components, pointer=itkimage)#.clone(inpixeltype) if inpixeltype != 'float': new_img = new_img.clone(inpixeltype) return new_img
[ "def", "reorient_image2", "(", "image", ",", "orientation", "=", "'RAS'", ")", ":", "if", "image", ".", "dimension", "!=", "3", ":", "raise", "ValueError", "(", "'image must have 3 dimensions'", ")", "inpixeltype", "=", "image", ".", "pixeltype", "ndim", "=", "image", ".", "dimension", "if", "image", ".", "pixeltype", "!=", "'float'", ":", "image", "=", "image", ".", "clone", "(", "'float'", ")", "libfn", "=", "utils", ".", "get_lib_fn", "(", "'reorientImage2'", ")", "itkimage", "=", "libfn", "(", "image", ".", "pointer", ",", "orientation", ")", "new_img", "=", "iio", ".", "ANTsImage", "(", "pixeltype", "=", "'float'", ",", "dimension", "=", "ndim", ",", "components", "=", "image", ".", "components", ",", "pointer", "=", "itkimage", ")", "#.clone(inpixeltype)", "if", "inpixeltype", "!=", "'float'", ":", "new_img", "=", "new_img", ".", "clone", "(", "inpixeltype", ")", "return", "new_img" ]
Reorient an image. Example ------- >>> import ants >>> mni = ants.image_read(ants.get_data('mni')) >>> mni2 = mni.reorient_image2()
[ "Reorient", "an", "image", "." ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/registration/reorient_image.py#L56-L82
237,226
ANTsX/ANTsPy
ants/registration/reorient_image.py
reorient_image
def reorient_image(image, axis1, axis2=None, doreflection=False, doscale=0, txfn=None): """ Align image along a specified axis ANTsR function: `reorientImage` Arguments --------- image : ANTsImage image to reorient axis1 : list/tuple of integers vector of size dim, might need to play w/axis sign axis2 : list/tuple of integers vector of size dim for 3D doreflection : boolean whether to reflect doscale : scalar value 1 allows automated estimate of scaling txfn : string file name for transformation Returns ------- ANTsImage Example ------- >>> import ants >>> image = ants.image_read(ants.get_ants_data('r16')) >>> ants.reorient_image(image, (1,0)) """ inpixeltype = image.pixeltype if image.pixeltype != 'float': image = image.clone('float') axis_was_none = False if axis2 is None: axis_was_none = True axis2 = [0]*image.dimension axis1 = np.array(axis1) axis2 = np.array(axis2) axis1 = axis1 / np.sqrt(np.sum(axis1*axis1)) * (-1) axis1 = axis1.astype('int') if not axis_was_none: axis2 = axis2 / np.sqrt(np.sum(axis2*axis2)) * (-1) axis2 = axis2.astype('int') else: axis2 = np.array([0]*image.dimension).astype('int') if txfn is None: txfn = mktemp(suffix='.mat') if isinstance(doreflection, tuple): doreflection = list(doreflection) if not isinstance(doreflection, list): doreflection = [doreflection] if isinstance(doscale, tuple): doscale = list(doscale) if not isinstance(doscale, list): doscale = [doscale] if len(doreflection) == 1: doreflection = [doreflection[0]]*image.dimension if len(doscale) == 1: doscale = [doscale[0]]*image.dimension libfn = utils.get_lib_fn('reorientImage%s' % image._libsuffix) libfn(image.pointer, txfn, axis1.tolist(), axis2.tolist(), doreflection, doscale) image2 = apply_transforms(image, image, transformlist=[txfn]) if image.pixeltype != inpixeltype: image2 = image2.clone(inpixeltype) return {'reoimage':image2, 'txfn':txfn}
python
def reorient_image(image, axis1, axis2=None, doreflection=False, doscale=0, txfn=None): """ Align image along a specified axis ANTsR function: `reorientImage` Arguments --------- image : ANTsImage image to reorient axis1 : list/tuple of integers vector of size dim, might need to play w/axis sign axis2 : list/tuple of integers vector of size dim for 3D doreflection : boolean whether to reflect doscale : scalar value 1 allows automated estimate of scaling txfn : string file name for transformation Returns ------- ANTsImage Example ------- >>> import ants >>> image = ants.image_read(ants.get_ants_data('r16')) >>> ants.reorient_image(image, (1,0)) """ inpixeltype = image.pixeltype if image.pixeltype != 'float': image = image.clone('float') axis_was_none = False if axis2 is None: axis_was_none = True axis2 = [0]*image.dimension axis1 = np.array(axis1) axis2 = np.array(axis2) axis1 = axis1 / np.sqrt(np.sum(axis1*axis1)) * (-1) axis1 = axis1.astype('int') if not axis_was_none: axis2 = axis2 / np.sqrt(np.sum(axis2*axis2)) * (-1) axis2 = axis2.astype('int') else: axis2 = np.array([0]*image.dimension).astype('int') if txfn is None: txfn = mktemp(suffix='.mat') if isinstance(doreflection, tuple): doreflection = list(doreflection) if not isinstance(doreflection, list): doreflection = [doreflection] if isinstance(doscale, tuple): doscale = list(doscale) if not isinstance(doscale, list): doscale = [doscale] if len(doreflection) == 1: doreflection = [doreflection[0]]*image.dimension if len(doscale) == 1: doscale = [doscale[0]]*image.dimension libfn = utils.get_lib_fn('reorientImage%s' % image._libsuffix) libfn(image.pointer, txfn, axis1.tolist(), axis2.tolist(), doreflection, doscale) image2 = apply_transforms(image, image, transformlist=[txfn]) if image.pixeltype != inpixeltype: image2 = image2.clone(inpixeltype) return {'reoimage':image2, 'txfn':txfn}
[ "def", "reorient_image", "(", "image", ",", "axis1", ",", "axis2", "=", "None", ",", "doreflection", "=", "False", ",", "doscale", "=", "0", ",", "txfn", "=", "None", ")", ":", "inpixeltype", "=", "image", ".", "pixeltype", "if", "image", ".", "pixeltype", "!=", "'float'", ":", "image", "=", "image", ".", "clone", "(", "'float'", ")", "axis_was_none", "=", "False", "if", "axis2", "is", "None", ":", "axis_was_none", "=", "True", "axis2", "=", "[", "0", "]", "*", "image", ".", "dimension", "axis1", "=", "np", ".", "array", "(", "axis1", ")", "axis2", "=", "np", ".", "array", "(", "axis2", ")", "axis1", "=", "axis1", "/", "np", ".", "sqrt", "(", "np", ".", "sum", "(", "axis1", "*", "axis1", ")", ")", "*", "(", "-", "1", ")", "axis1", "=", "axis1", ".", "astype", "(", "'int'", ")", "if", "not", "axis_was_none", ":", "axis2", "=", "axis2", "/", "np", ".", "sqrt", "(", "np", ".", "sum", "(", "axis2", "*", "axis2", ")", ")", "*", "(", "-", "1", ")", "axis2", "=", "axis2", ".", "astype", "(", "'int'", ")", "else", ":", "axis2", "=", "np", ".", "array", "(", "[", "0", "]", "*", "image", ".", "dimension", ")", ".", "astype", "(", "'int'", ")", "if", "txfn", "is", "None", ":", "txfn", "=", "mktemp", "(", "suffix", "=", "'.mat'", ")", "if", "isinstance", "(", "doreflection", ",", "tuple", ")", ":", "doreflection", "=", "list", "(", "doreflection", ")", "if", "not", "isinstance", "(", "doreflection", ",", "list", ")", ":", "doreflection", "=", "[", "doreflection", "]", "if", "isinstance", "(", "doscale", ",", "tuple", ")", ":", "doscale", "=", "list", "(", "doscale", ")", "if", "not", "isinstance", "(", "doscale", ",", "list", ")", ":", "doscale", "=", "[", "doscale", "]", "if", "len", "(", "doreflection", ")", "==", "1", ":", "doreflection", "=", "[", "doreflection", "[", "0", "]", "]", "*", "image", ".", "dimension", "if", "len", "(", "doscale", ")", "==", "1", ":", "doscale", "=", "[", "doscale", "[", "0", "]", "]", "*", "image", ".", "dimension", "libfn", "=", "utils", ".", "get_lib_fn", "(", "'reorientImage%s'", "%", "image", ".", "_libsuffix", ")", "libfn", "(", "image", ".", "pointer", ",", "txfn", ",", "axis1", ".", "tolist", "(", ")", ",", "axis2", ".", "tolist", "(", ")", ",", "doreflection", ",", "doscale", ")", "image2", "=", "apply_transforms", "(", "image", ",", "image", ",", "transformlist", "=", "[", "txfn", "]", ")", "if", "image", ".", "pixeltype", "!=", "inpixeltype", ":", "image2", "=", "image2", ".", "clone", "(", "inpixeltype", ")", "return", "{", "'reoimage'", ":", "image2", ",", "'txfn'", ":", "txfn", "}" ]
Align image along a specified axis ANTsR function: `reorientImage` Arguments --------- image : ANTsImage image to reorient axis1 : list/tuple of integers vector of size dim, might need to play w/axis sign axis2 : list/tuple of integers vector of size dim for 3D doreflection : boolean whether to reflect doscale : scalar value 1 allows automated estimate of scaling txfn : string file name for transformation Returns ------- ANTsImage Example ------- >>> import ants >>> image = ants.image_read(ants.get_ants_data('r16')) >>> ants.reorient_image(image, (1,0))
[ "Align", "image", "along", "a", "specified", "axis" ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/registration/reorient_image.py#L85-L168
237,227
ANTsX/ANTsPy
ants/registration/reorient_image.py
get_center_of_mass
def get_center_of_mass(image): """ Compute an image center of mass in physical space which is defined as the mean of the intensity weighted voxel coordinate system. ANTsR function: `getCenterOfMass` Arguments --------- image : ANTsImage image from which center of mass will be computed Returns ------- scalar Example ------- >>> fi = ants.image_read( ants.get_ants_data("r16")) >>> com1 = ants.get_center_of_mass( fi ) >>> fi = ants.image_read( ants.get_ants_data("r64")) >>> com2 = ants.get_center_of_mass( fi ) """ if image.pixeltype != 'float': image = image.clone('float') libfn = utils.get_lib_fn('centerOfMass%s' % image._libsuffix) com = libfn(image.pointer) return tuple(com)
python
def get_center_of_mass(image): """ Compute an image center of mass in physical space which is defined as the mean of the intensity weighted voxel coordinate system. ANTsR function: `getCenterOfMass` Arguments --------- image : ANTsImage image from which center of mass will be computed Returns ------- scalar Example ------- >>> fi = ants.image_read( ants.get_ants_data("r16")) >>> com1 = ants.get_center_of_mass( fi ) >>> fi = ants.image_read( ants.get_ants_data("r64")) >>> com2 = ants.get_center_of_mass( fi ) """ if image.pixeltype != 'float': image = image.clone('float') libfn = utils.get_lib_fn('centerOfMass%s' % image._libsuffix) com = libfn(image.pointer) return tuple(com)
[ "def", "get_center_of_mass", "(", "image", ")", ":", "if", "image", ".", "pixeltype", "!=", "'float'", ":", "image", "=", "image", ".", "clone", "(", "'float'", ")", "libfn", "=", "utils", ".", "get_lib_fn", "(", "'centerOfMass%s'", "%", "image", ".", "_libsuffix", ")", "com", "=", "libfn", "(", "image", ".", "pointer", ")", "return", "tuple", "(", "com", ")" ]
Compute an image center of mass in physical space which is defined as the mean of the intensity weighted voxel coordinate system. ANTsR function: `getCenterOfMass` Arguments --------- image : ANTsImage image from which center of mass will be computed Returns ------- scalar Example ------- >>> fi = ants.image_read( ants.get_ants_data("r16")) >>> com1 = ants.get_center_of_mass( fi ) >>> fi = ants.image_read( ants.get_ants_data("r64")) >>> com2 = ants.get_center_of_mass( fi )
[ "Compute", "an", "image", "center", "of", "mass", "in", "physical", "space", "which", "is", "defined", "as", "the", "mean", "of", "the", "intensity", "weighted", "voxel", "coordinate", "system", "." ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/registration/reorient_image.py#L171-L200
237,228
ANTsX/ANTsPy
ants/utils/convert_nibabel.py
to_nibabel
def to_nibabel(image): """ Convert an ANTsImage to a Nibabel image """ if image.dimension != 3: raise ValueError('Only 3D images currently supported') import nibabel as nib array_data = image.numpy() affine = np.hstack([image.direction*np.diag(image.spacing),np.array(image.origin).reshape(3,1)]) affine = np.vstack([affine, np.array([0,0,0,1.])]) affine[:2,:] *= -1 new_img = nib.Nifti1Image(array_data, affine) return new_img
python
def to_nibabel(image): """ Convert an ANTsImage to a Nibabel image """ if image.dimension != 3: raise ValueError('Only 3D images currently supported') import nibabel as nib array_data = image.numpy() affine = np.hstack([image.direction*np.diag(image.spacing),np.array(image.origin).reshape(3,1)]) affine = np.vstack([affine, np.array([0,0,0,1.])]) affine[:2,:] *= -1 new_img = nib.Nifti1Image(array_data, affine) return new_img
[ "def", "to_nibabel", "(", "image", ")", ":", "if", "image", ".", "dimension", "!=", "3", ":", "raise", "ValueError", "(", "'Only 3D images currently supported'", ")", "import", "nibabel", "as", "nib", "array_data", "=", "image", ".", "numpy", "(", ")", "affine", "=", "np", ".", "hstack", "(", "[", "image", ".", "direction", "*", "np", ".", "diag", "(", "image", ".", "spacing", ")", ",", "np", ".", "array", "(", "image", ".", "origin", ")", ".", "reshape", "(", "3", ",", "1", ")", "]", ")", "affine", "=", "np", ".", "vstack", "(", "[", "affine", ",", "np", ".", "array", "(", "[", "0", ",", "0", ",", "0", ",", "1.", "]", ")", "]", ")", "affine", "[", ":", "2", ",", ":", "]", "*=", "-", "1", "new_img", "=", "nib", ".", "Nifti1Image", "(", "array_data", ",", "affine", ")", "return", "new_img" ]
Convert an ANTsImage to a Nibabel image
[ "Convert", "an", "ANTsImage", "to", "a", "Nibabel", "image" ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/convert_nibabel.py#L10-L23
237,229
ANTsX/ANTsPy
ants/utils/convert_nibabel.py
from_nibabel
def from_nibabel(nib_image): """ Convert a nibabel image to an ANTsImage """ tmpfile = mktemp(suffix='.nii.gz') nib_image.to_filename(tmpfile) new_img = iio2.image_read(tmpfile) os.remove(tmpfile) return new_img
python
def from_nibabel(nib_image): """ Convert a nibabel image to an ANTsImage """ tmpfile = mktemp(suffix='.nii.gz') nib_image.to_filename(tmpfile) new_img = iio2.image_read(tmpfile) os.remove(tmpfile) return new_img
[ "def", "from_nibabel", "(", "nib_image", ")", ":", "tmpfile", "=", "mktemp", "(", "suffix", "=", "'.nii.gz'", ")", "nib_image", ".", "to_filename", "(", "tmpfile", ")", "new_img", "=", "iio2", ".", "image_read", "(", "tmpfile", ")", "os", ".", "remove", "(", "tmpfile", ")", "return", "new_img" ]
Convert a nibabel image to an ANTsImage
[ "Convert", "a", "nibabel", "image", "to", "an", "ANTsImage" ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/convert_nibabel.py#L26-L34
237,230
ANTsX/ANTsPy
ants/contrib/sampling/affine3d.py
RandomShear3D.transform
def transform(self, X=None, y=None): """ Transform an image using an Affine transform with shear parameters randomly generated from the user-specified range. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('ch2')) >>> tx = ants.contrib.RandomShear3D(shear_range=(-10,10)) >>> img2 = tx.transform(img) """ # random draw in shear range shear_x = random.gauss(self.shear_range[0], self.shear_range[1]) shear_y = random.gauss(self.shear_range[0], self.shear_range[1]) shear_z = random.gauss(self.shear_range[0], self.shear_range[1]) self.params = (shear_x, shear_y, shear_z) tx = Shear3D((shear_x, shear_y, shear_z), reference=self.reference, lazy=self.lazy) return tx.transform(X,y)
python
def transform(self, X=None, y=None): """ Transform an image using an Affine transform with shear parameters randomly generated from the user-specified range. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('ch2')) >>> tx = ants.contrib.RandomShear3D(shear_range=(-10,10)) >>> img2 = tx.transform(img) """ # random draw in shear range shear_x = random.gauss(self.shear_range[0], self.shear_range[1]) shear_y = random.gauss(self.shear_range[0], self.shear_range[1]) shear_z = random.gauss(self.shear_range[0], self.shear_range[1]) self.params = (shear_x, shear_y, shear_z) tx = Shear3D((shear_x, shear_y, shear_z), reference=self.reference, lazy=self.lazy) return tx.transform(X,y)
[ "def", "transform", "(", "self", ",", "X", "=", "None", ",", "y", "=", "None", ")", ":", "# random draw in shear range", "shear_x", "=", "random", ".", "gauss", "(", "self", ".", "shear_range", "[", "0", "]", ",", "self", ".", "shear_range", "[", "1", "]", ")", "shear_y", "=", "random", ".", "gauss", "(", "self", ".", "shear_range", "[", "0", "]", ",", "self", ".", "shear_range", "[", "1", "]", ")", "shear_z", "=", "random", ".", "gauss", "(", "self", ".", "shear_range", "[", "0", "]", ",", "self", ".", "shear_range", "[", "1", "]", ")", "self", ".", "params", "=", "(", "shear_x", ",", "shear_y", ",", "shear_z", ")", "tx", "=", "Shear3D", "(", "(", "shear_x", ",", "shear_y", ",", "shear_z", ")", ",", "reference", "=", "self", ".", "reference", ",", "lazy", "=", "self", ".", "lazy", ")", "return", "tx", ".", "transform", "(", "X", ",", "y", ")" ]
Transform an image using an Affine transform with shear parameters randomly generated from the user-specified range. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('ch2')) >>> tx = ants.contrib.RandomShear3D(shear_range=(-10,10)) >>> img2 = tx.transform(img)
[ "Transform", "an", "image", "using", "an", "Affine", "transform", "with", "shear", "parameters", "randomly", "generated", "from", "the", "user", "-", "specified", "range", ".", "Return", "the", "transform", "if", "X", "=", "None", "." ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/contrib/sampling/affine3d.py#L304-L339
237,231
ANTsX/ANTsPy
ants/contrib/sampling/affine3d.py
RandomZoom3D.transform
def transform(self, X=None, y=None): """ Transform an image using an Affine transform with zoom parameters randomly generated from the user-specified range. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('ch2')) >>> tx = ants.contrib.RandomZoom3D(zoom_range=(0.8,0.9)) >>> img2 = tx.transform(img) """ # random draw in zoom range zoom_x = np.exp( random.gauss( np.log( self.zoom_range[0] ), np.log( self.zoom_range[1] ) ) ) zoom_y = np.exp( random.gauss( np.log( self.zoom_range[0] ), np.log( self.zoom_range[1] ) ) ) zoom_z = np.exp( random.gauss( np.log( self.zoom_range[0] ), np.log( self.zoom_range[1] ) ) ) self.params = (zoom_x, zoom_y, zoom_z) tx = Zoom3D((zoom_x,zoom_y,zoom_z), reference=self.reference, lazy=self.lazy) return tx.transform(X,y)
python
def transform(self, X=None, y=None): """ Transform an image using an Affine transform with zoom parameters randomly generated from the user-specified range. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('ch2')) >>> tx = ants.contrib.RandomZoom3D(zoom_range=(0.8,0.9)) >>> img2 = tx.transform(img) """ # random draw in zoom range zoom_x = np.exp( random.gauss( np.log( self.zoom_range[0] ), np.log( self.zoom_range[1] ) ) ) zoom_y = np.exp( random.gauss( np.log( self.zoom_range[0] ), np.log( self.zoom_range[1] ) ) ) zoom_z = np.exp( random.gauss( np.log( self.zoom_range[0] ), np.log( self.zoom_range[1] ) ) ) self.params = (zoom_x, zoom_y, zoom_z) tx = Zoom3D((zoom_x,zoom_y,zoom_z), reference=self.reference, lazy=self.lazy) return tx.transform(X,y)
[ "def", "transform", "(", "self", ",", "X", "=", "None", ",", "y", "=", "None", ")", ":", "# random draw in zoom range", "zoom_x", "=", "np", ".", "exp", "(", "random", ".", "gauss", "(", "np", ".", "log", "(", "self", ".", "zoom_range", "[", "0", "]", ")", ",", "np", ".", "log", "(", "self", ".", "zoom_range", "[", "1", "]", ")", ")", ")", "zoom_y", "=", "np", ".", "exp", "(", "random", ".", "gauss", "(", "np", ".", "log", "(", "self", ".", "zoom_range", "[", "0", "]", ")", ",", "np", ".", "log", "(", "self", ".", "zoom_range", "[", "1", "]", ")", ")", ")", "zoom_z", "=", "np", ".", "exp", "(", "random", ".", "gauss", "(", "np", ".", "log", "(", "self", ".", "zoom_range", "[", "0", "]", ")", ",", "np", ".", "log", "(", "self", ".", "zoom_range", "[", "1", "]", ")", ")", ")", "self", ".", "params", "=", "(", "zoom_x", ",", "zoom_y", ",", "zoom_z", ")", "tx", "=", "Zoom3D", "(", "(", "zoom_x", ",", "zoom_y", ",", "zoom_z", ")", ",", "reference", "=", "self", ".", "reference", ",", "lazy", "=", "self", ".", "lazy", ")", "return", "tx", ".", "transform", "(", "X", ",", "y", ")" ]
Transform an image using an Affine transform with zoom parameters randomly generated from the user-specified range. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('ch2')) >>> tx = ants.contrib.RandomZoom3D(zoom_range=(0.8,0.9)) >>> img2 = tx.transform(img)
[ "Transform", "an", "image", "using", "an", "Affine", "transform", "with", "zoom", "parameters", "randomly", "generated", "from", "the", "user", "-", "specified", "range", ".", "Return", "the", "transform", "if", "X", "=", "None", "." ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/contrib/sampling/affine3d.py#L629-L670
237,232
ANTsX/ANTsPy
ants/contrib/sampling/affine2d.py
Translate2D.transform
def transform(self, X=None, y=None): """ Transform an image using an Affine transform with the given translation parameters. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('r16')) >>> tx = ants.contrib.Translate2D(translation=(10,0)) >>> img2_x = tx.transform(img) >>> tx = ants.contrib.Translate2D(translation=(-10,0)) # other direction >>> img2_x = tx.transform(img) >>> tx = ants.contrib.Translate2D(translation=(0,10)) >>> img2_z = tx.transform(img) >>> tx = ants.contrib.Translate2D(translation=(10,10)) >>> img2 = tx.transform(img) """ # convert to radians and unpack translation_x, translation_y = self.translation translation_matrix = np.array([[1, 0, translation_x], [0, 1, translation_y]]) self.tx.set_parameters(translation_matrix) if self.lazy or X is None: return self.tx else: return self.tx.apply_to_image(X, reference=self.reference)
python
def transform(self, X=None, y=None): """ Transform an image using an Affine transform with the given translation parameters. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('r16')) >>> tx = ants.contrib.Translate2D(translation=(10,0)) >>> img2_x = tx.transform(img) >>> tx = ants.contrib.Translate2D(translation=(-10,0)) # other direction >>> img2_x = tx.transform(img) >>> tx = ants.contrib.Translate2D(translation=(0,10)) >>> img2_z = tx.transform(img) >>> tx = ants.contrib.Translate2D(translation=(10,10)) >>> img2 = tx.transform(img) """ # convert to radians and unpack translation_x, translation_y = self.translation translation_matrix = np.array([[1, 0, translation_x], [0, 1, translation_y]]) self.tx.set_parameters(translation_matrix) if self.lazy or X is None: return self.tx else: return self.tx.apply_to_image(X, reference=self.reference)
[ "def", "transform", "(", "self", ",", "X", "=", "None", ",", "y", "=", "None", ")", ":", "# convert to radians and unpack", "translation_x", ",", "translation_y", "=", "self", ".", "translation", "translation_matrix", "=", "np", ".", "array", "(", "[", "[", "1", ",", "0", ",", "translation_x", "]", ",", "[", "0", ",", "1", ",", "translation_y", "]", "]", ")", "self", ".", "tx", ".", "set_parameters", "(", "translation_matrix", ")", "if", "self", ".", "lazy", "or", "X", "is", "None", ":", "return", "self", ".", "tx", "else", ":", "return", "self", ".", "tx", ".", "apply_to_image", "(", "X", ",", "reference", "=", "self", ".", "reference", ")" ]
Transform an image using an Affine transform with the given translation parameters. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('r16')) >>> tx = ants.contrib.Translate2D(translation=(10,0)) >>> img2_x = tx.transform(img) >>> tx = ants.contrib.Translate2D(translation=(-10,0)) # other direction >>> img2_x = tx.transform(img) >>> tx = ants.contrib.Translate2D(translation=(0,10)) >>> img2_z = tx.transform(img) >>> tx = ants.contrib.Translate2D(translation=(10,10)) >>> img2 = tx.transform(img)
[ "Transform", "an", "image", "using", "an", "Affine", "transform", "with", "the", "given", "translation", "parameters", ".", "Return", "the", "transform", "if", "X", "=", "None", "." ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/contrib/sampling/affine2d.py#L62-L101
237,233
ANTsX/ANTsPy
ants/contrib/sampling/affine2d.py
RandomTranslate2D.transform
def transform(self, X=None, y=None): """ Transform an image using an Affine transform with translation parameters randomly generated from the user-specified range. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('r16')) >>> tx = ants.contrib.RandomShear2D(translation_range=(-10,10)) >>> img2 = tx.transform(img) """ # random draw in translation range translation_x = random.gauss(self.translation_range[0], self.translation_range[1]) translation_y = random.gauss(self.translation_range[0], self.translation_range[1]) self.params = (translation_x, translation_y) tx = Translate2D((translation_x, translation_y), reference=self.reference, lazy=self.lazy) return tx.transform(X,y)
python
def transform(self, X=None, y=None): """ Transform an image using an Affine transform with translation parameters randomly generated from the user-specified range. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('r16')) >>> tx = ants.contrib.RandomShear2D(translation_range=(-10,10)) >>> img2 = tx.transform(img) """ # random draw in translation range translation_x = random.gauss(self.translation_range[0], self.translation_range[1]) translation_y = random.gauss(self.translation_range[0], self.translation_range[1]) self.params = (translation_x, translation_y) tx = Translate2D((translation_x, translation_y), reference=self.reference, lazy=self.lazy) return tx.transform(X,y)
[ "def", "transform", "(", "self", ",", "X", "=", "None", ",", "y", "=", "None", ")", ":", "# random draw in translation range", "translation_x", "=", "random", ".", "gauss", "(", "self", ".", "translation_range", "[", "0", "]", ",", "self", ".", "translation_range", "[", "1", "]", ")", "translation_y", "=", "random", ".", "gauss", "(", "self", ".", "translation_range", "[", "0", "]", ",", "self", ".", "translation_range", "[", "1", "]", ")", "self", ".", "params", "=", "(", "translation_x", ",", "translation_y", ")", "tx", "=", "Translate2D", "(", "(", "translation_x", ",", "translation_y", ")", ",", "reference", "=", "self", ".", "reference", ",", "lazy", "=", "self", ".", "lazy", ")", "return", "tx", ".", "transform", "(", "X", ",", "y", ")" ]
Transform an image using an Affine transform with translation parameters randomly generated from the user-specified range. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('r16')) >>> tx = ants.contrib.RandomShear2D(translation_range=(-10,10)) >>> img2 = tx.transform(img)
[ "Transform", "an", "image", "using", "an", "Affine", "transform", "with", "translation", "parameters", "randomly", "generated", "from", "the", "user", "-", "specified", "range", ".", "Return", "the", "transform", "if", "X", "=", "None", "." ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/contrib/sampling/affine2d.py#L141-L175
237,234
ANTsX/ANTsPy
ants/contrib/sampling/affine2d.py
Shear2D.transform
def transform(self, X=None, y=None): """ Transform an image using an Affine transform with the given shear parameters. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('r16')) >>> tx = ants.contrib.Shear2D(shear=(10,0,0)) >>> img2_x = tx.transform(img)# x axis stays same >>> tx = ants.contrib.Shear2D(shear=(-10,0,0)) # other direction >>> img2_x = tx.transform(img)# x axis stays same >>> tx = ants.contrib.Shear2D(shear=(0,10,0)) >>> img2_y = tx.transform(img) # y axis stays same >>> tx = ants.contrib.Shear2D(shear=(0,0,10)) >>> img2_z = tx.transform(img) # z axis stays same >>> tx = ants.contrib.Shear2D(shear=(10,10,10)) >>> img2 = tx.transform(img) """ # convert to radians and unpack shear = [math.pi / 180 * s for s in self.shear] shear_x, shear_y = shear shear_matrix = np.array([[1, shear_x, 0], [shear_y, 1, 0]]) self.tx.set_parameters(shear_matrix) if self.lazy or X is None: return self.tx else: return self.tx.apply_to_image(X, reference=self.reference)
python
def transform(self, X=None, y=None): """ Transform an image using an Affine transform with the given shear parameters. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('r16')) >>> tx = ants.contrib.Shear2D(shear=(10,0,0)) >>> img2_x = tx.transform(img)# x axis stays same >>> tx = ants.contrib.Shear2D(shear=(-10,0,0)) # other direction >>> img2_x = tx.transform(img)# x axis stays same >>> tx = ants.contrib.Shear2D(shear=(0,10,0)) >>> img2_y = tx.transform(img) # y axis stays same >>> tx = ants.contrib.Shear2D(shear=(0,0,10)) >>> img2_z = tx.transform(img) # z axis stays same >>> tx = ants.contrib.Shear2D(shear=(10,10,10)) >>> img2 = tx.transform(img) """ # convert to radians and unpack shear = [math.pi / 180 * s for s in self.shear] shear_x, shear_y = shear shear_matrix = np.array([[1, shear_x, 0], [shear_y, 1, 0]]) self.tx.set_parameters(shear_matrix) if self.lazy or X is None: return self.tx else: return self.tx.apply_to_image(X, reference=self.reference)
[ "def", "transform", "(", "self", ",", "X", "=", "None", ",", "y", "=", "None", ")", ":", "# convert to radians and unpack", "shear", "=", "[", "math", ".", "pi", "/", "180", "*", "s", "for", "s", "in", "self", ".", "shear", "]", "shear_x", ",", "shear_y", "=", "shear", "shear_matrix", "=", "np", ".", "array", "(", "[", "[", "1", ",", "shear_x", ",", "0", "]", ",", "[", "shear_y", ",", "1", ",", "0", "]", "]", ")", "self", ".", "tx", ".", "set_parameters", "(", "shear_matrix", ")", "if", "self", ".", "lazy", "or", "X", "is", "None", ":", "return", "self", ".", "tx", "else", ":", "return", "self", ".", "tx", ".", "apply_to_image", "(", "X", ",", "reference", "=", "self", ".", "reference", ")" ]
Transform an image using an Affine transform with the given shear parameters. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('r16')) >>> tx = ants.contrib.Shear2D(shear=(10,0,0)) >>> img2_x = tx.transform(img)# x axis stays same >>> tx = ants.contrib.Shear2D(shear=(-10,0,0)) # other direction >>> img2_x = tx.transform(img)# x axis stays same >>> tx = ants.contrib.Shear2D(shear=(0,10,0)) >>> img2_y = tx.transform(img) # y axis stays same >>> tx = ants.contrib.Shear2D(shear=(0,0,10)) >>> img2_z = tx.transform(img) # z axis stays same >>> tx = ants.contrib.Shear2D(shear=(10,10,10)) >>> img2 = tx.transform(img)
[ "Transform", "an", "image", "using", "an", "Affine", "transform", "with", "the", "given", "shear", "parameters", ".", "Return", "the", "transform", "if", "X", "=", "None", "." ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/contrib/sampling/affine2d.py#L217-L259
237,235
ANTsX/ANTsPy
ants/contrib/sampling/affine2d.py
Zoom2D.transform
def transform(self, X=None, y=None): """ Transform an image using an Affine transform with the given zoom parameters. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('r16')) >>> tx = ants.contrib.Zoom2D(zoom=(0.8,0.8,0.8)) >>> img2 = tx.transform(img) """ # unpack zoom range zoom_x, zoom_y= self.zoom self.params = (zoom_x, zoom_y) zoom_matrix = np.array([[zoom_x, 0, 0], [0, zoom_y, 0]]) self.tx.set_parameters(zoom_matrix) if self.lazy or X is None: return self.tx else: return self.tx.apply_to_image(X, reference=self.reference)
python
def transform(self, X=None, y=None): """ Transform an image using an Affine transform with the given zoom parameters. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('r16')) >>> tx = ants.contrib.Zoom2D(zoom=(0.8,0.8,0.8)) >>> img2 = tx.transform(img) """ # unpack zoom range zoom_x, zoom_y= self.zoom self.params = (zoom_x, zoom_y) zoom_matrix = np.array([[zoom_x, 0, 0], [0, zoom_y, 0]]) self.tx.set_parameters(zoom_matrix) if self.lazy or X is None: return self.tx else: return self.tx.apply_to_image(X, reference=self.reference)
[ "def", "transform", "(", "self", ",", "X", "=", "None", ",", "y", "=", "None", ")", ":", "# unpack zoom range", "zoom_x", ",", "zoom_y", "=", "self", ".", "zoom", "self", ".", "params", "=", "(", "zoom_x", ",", "zoom_y", ")", "zoom_matrix", "=", "np", ".", "array", "(", "[", "[", "zoom_x", ",", "0", ",", "0", "]", ",", "[", "0", ",", "zoom_y", ",", "0", "]", "]", ")", "self", ".", "tx", ".", "set_parameters", "(", "zoom_matrix", ")", "if", "self", ".", "lazy", "or", "X", "is", "None", ":", "return", "self", ".", "tx", "else", ":", "return", "self", ".", "tx", ".", "apply_to_image", "(", "X", ",", "reference", "=", "self", ".", "reference", ")" ]
Transform an image using an Affine transform with the given zoom parameters. Return the transform if X=None. Arguments --------- X : ANTsImage Image to transform y : ANTsImage (optional) Another image to transform Returns ------- ANTsImage if y is None, else a tuple of ANTsImage types Examples -------- >>> import ants >>> img = ants.image_read(ants.get_data('r16')) >>> tx = ants.contrib.Zoom2D(zoom=(0.8,0.8,0.8)) >>> img2 = tx.transform(img)
[ "Transform", "an", "image", "using", "an", "Affine", "transform", "with", "the", "given", "zoom", "parameters", ".", "Return", "the", "transform", "if", "X", "=", "None", "." ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/contrib/sampling/affine2d.py#L526-L560
237,236
ANTsX/ANTsPy
ants/segmentation/kelly_kapowski.py
kelly_kapowski
def kelly_kapowski(s, g, w, its=50, r=0.025, m=1.5, **kwargs): """ Compute cortical thickness using the DiReCT algorithm. Diffeomorphic registration-based cortical thickness based on probabilistic segmentation of an image. This is an optimization algorithm. Arguments --------- s : ANTsimage segmentation image g : ANTsImage gray matter probability image w : ANTsImage white matter probability image its : integer convergence params - controls iterations r : scalar gradient descent update parameter m : scalar gradient field smoothing parameter kwargs : keyword arguments anything else, see KellyKapowski help in ANTs Returns ------- ANTsImage Example ------- >>> import ants >>> img = ants.image_read( ants.get_ants_data('r16') ,2) >>> img = ants.resample_image(img, (64,64),1,0) >>> mask = ants.get_mask( img ) >>> segs = ants.kmeans_segmentation( img, k=3, kmask = mask) >>> thick = ants.kelly_kapowski(s=segs['segmentation'], g=segs['probabilityimages'][1], w=segs['probabilityimages'][2], its=45, r=0.5, m=1) """ if isinstance(s, iio.ANTsImage): s = s.clone('unsigned int') d = s.dimension outimg = g.clone() kellargs = {'d': d, 's': s, 'g': g, 'w': w, 'c': its, 'r': r, 'm': m, 'o': outimg} for k, v in kwargs.items(): kellargs[k] = v processed_kellargs = utils._int_antsProcessArguments(kellargs) libfn = utils.get_lib_fn('KellyKapowski') libfn(processed_kellargs) return outimg
python
def kelly_kapowski(s, g, w, its=50, r=0.025, m=1.5, **kwargs): """ Compute cortical thickness using the DiReCT algorithm. Diffeomorphic registration-based cortical thickness based on probabilistic segmentation of an image. This is an optimization algorithm. Arguments --------- s : ANTsimage segmentation image g : ANTsImage gray matter probability image w : ANTsImage white matter probability image its : integer convergence params - controls iterations r : scalar gradient descent update parameter m : scalar gradient field smoothing parameter kwargs : keyword arguments anything else, see KellyKapowski help in ANTs Returns ------- ANTsImage Example ------- >>> import ants >>> img = ants.image_read( ants.get_ants_data('r16') ,2) >>> img = ants.resample_image(img, (64,64),1,0) >>> mask = ants.get_mask( img ) >>> segs = ants.kmeans_segmentation( img, k=3, kmask = mask) >>> thick = ants.kelly_kapowski(s=segs['segmentation'], g=segs['probabilityimages'][1], w=segs['probabilityimages'][2], its=45, r=0.5, m=1) """ if isinstance(s, iio.ANTsImage): s = s.clone('unsigned int') d = s.dimension outimg = g.clone() kellargs = {'d': d, 's': s, 'g': g, 'w': w, 'c': its, 'r': r, 'm': m, 'o': outimg} for k, v in kwargs.items(): kellargs[k] = v processed_kellargs = utils._int_antsProcessArguments(kellargs) libfn = utils.get_lib_fn('KellyKapowski') libfn(processed_kellargs) return outimg
[ "def", "kelly_kapowski", "(", "s", ",", "g", ",", "w", ",", "its", "=", "50", ",", "r", "=", "0.025", ",", "m", "=", "1.5", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "s", ",", "iio", ".", "ANTsImage", ")", ":", "s", "=", "s", ".", "clone", "(", "'unsigned int'", ")", "d", "=", "s", ".", "dimension", "outimg", "=", "g", ".", "clone", "(", ")", "kellargs", "=", "{", "'d'", ":", "d", ",", "'s'", ":", "s", ",", "'g'", ":", "g", ",", "'w'", ":", "w", ",", "'c'", ":", "its", ",", "'r'", ":", "r", ",", "'m'", ":", "m", ",", "'o'", ":", "outimg", "}", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", ":", "kellargs", "[", "k", "]", "=", "v", "processed_kellargs", "=", "utils", ".", "_int_antsProcessArguments", "(", "kellargs", ")", "libfn", "=", "utils", ".", "get_lib_fn", "(", "'KellyKapowski'", ")", "libfn", "(", "processed_kellargs", ")", "return", "outimg" ]
Compute cortical thickness using the DiReCT algorithm. Diffeomorphic registration-based cortical thickness based on probabilistic segmentation of an image. This is an optimization algorithm. Arguments --------- s : ANTsimage segmentation image g : ANTsImage gray matter probability image w : ANTsImage white matter probability image its : integer convergence params - controls iterations r : scalar gradient descent update parameter m : scalar gradient field smoothing parameter kwargs : keyword arguments anything else, see KellyKapowski help in ANTs Returns ------- ANTsImage Example ------- >>> import ants >>> img = ants.image_read( ants.get_ants_data('r16') ,2) >>> img = ants.resample_image(img, (64,64),1,0) >>> mask = ants.get_mask( img ) >>> segs = ants.kmeans_segmentation( img, k=3, kmask = mask) >>> thick = ants.kelly_kapowski(s=segs['segmentation'], g=segs['probabilityimages'][1], w=segs['probabilityimages'][2], its=45, r=0.5, m=1)
[ "Compute", "cortical", "thickness", "using", "the", "DiReCT", "algorithm", "." ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/segmentation/kelly_kapowski.py#L11-L77
237,237
ANTsX/ANTsPy
ants/core/ants_transform_io.py
new_ants_transform
def new_ants_transform(precision='float', dimension=3, transform_type='AffineTransform', parameters=None): """ Create a new ANTsTransform ANTsR function: None Example ------- >>> import ants >>> tx = ants.new_ants_transform() """ libfn = utils.get_lib_fn('newAntsTransform%s%i' % (utils.short_ptype(precision), dimension)) itk_tx = libfn(precision, dimension, transform_type) ants_tx = tio.ANTsTransform(precision=precision, dimension=dimension, transform_type=transform_type, pointer=itk_tx) if parameters is not None: ants_tx.set_parameters(parameters) return ants_tx
python
def new_ants_transform(precision='float', dimension=3, transform_type='AffineTransform', parameters=None): """ Create a new ANTsTransform ANTsR function: None Example ------- >>> import ants >>> tx = ants.new_ants_transform() """ libfn = utils.get_lib_fn('newAntsTransform%s%i' % (utils.short_ptype(precision), dimension)) itk_tx = libfn(precision, dimension, transform_type) ants_tx = tio.ANTsTransform(precision=precision, dimension=dimension, transform_type=transform_type, pointer=itk_tx) if parameters is not None: ants_tx.set_parameters(parameters) return ants_tx
[ "def", "new_ants_transform", "(", "precision", "=", "'float'", ",", "dimension", "=", "3", ",", "transform_type", "=", "'AffineTransform'", ",", "parameters", "=", "None", ")", ":", "libfn", "=", "utils", ".", "get_lib_fn", "(", "'newAntsTransform%s%i'", "%", "(", "utils", ".", "short_ptype", "(", "precision", ")", ",", "dimension", ")", ")", "itk_tx", "=", "libfn", "(", "precision", ",", "dimension", ",", "transform_type", ")", "ants_tx", "=", "tio", ".", "ANTsTransform", "(", "precision", "=", "precision", ",", "dimension", "=", "dimension", ",", "transform_type", "=", "transform_type", ",", "pointer", "=", "itk_tx", ")", "if", "parameters", "is", "not", "None", ":", "ants_tx", ".", "set_parameters", "(", "parameters", ")", "return", "ants_tx" ]
Create a new ANTsTransform ANTsR function: None Example ------- >>> import ants >>> tx = ants.new_ants_transform()
[ "Create", "a", "new", "ANTsTransform" ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_transform_io.py#L16-L35
237,238
ANTsX/ANTsPy
ants/core/ants_transform_io.py
create_ants_transform
def create_ants_transform(transform_type='AffineTransform', precision='float', dimension=3, matrix=None, offset=None, center=None, translation=None, parameters=None, fixed_parameters=None, displacement_field=None, supported_types=False): """ Create and initialize an ANTsTransform ANTsR function: `createAntsrTransform` Arguments --------- transform_type : string type of transform(s) precision : string numerical precision dimension : integer spatial dimension of transform matrix : ndarray matrix for linear transforms offset : tuple/list offset for linear transforms center : tuple/list center for linear transforms translation : tuple/list translation for linear transforms parameters : ndarray/list array of parameters fixed_parameters : ndarray/list array of fixed parameters displacement_field : ANTsImage multichannel ANTsImage for non-linear transform supported_types : boolean flag that returns array of possible transforms types Returns ------- ANTsTransform or list of ANTsTransform types Example ------- >>> import ants >>> translation = (3,4,5) >>> tx = ants.create_ants_transform( type='Euler3DTransform', translation=translation ) """ def _check_arg(arg, dim=1): if arg is None: if dim == 1: return [] elif dim == 2: return [[]] elif isinstance(arg, np.ndarray): return arg.tolist() elif isinstance(arg, (tuple, list)): return list(arg) else: raise ValueError('Incompatible input argument') matrix = _check_arg(matrix, dim=2) offset = _check_arg(offset) center = _check_arg(center) translation = _check_arg(translation) parameters = _check_arg(parameters) fixed_parameters = _check_arg(fixed_parameters) matrix_offset_types = {'AffineTransform', 'CenteredAffineTransform', 'Euler2DTransform', 'Euler3DTransform', 'Rigid3DTransform', 'Rigid2DTransform', 'QuaternionRigidTransform', 'Similarity2DTransform', 'CenteredSimilarity2DTransform', 'Similarity3DTransform', 'CenteredRigid2DTransform', 'CenteredEuler3DTransform'} #user_matrix_types = {'Affine','CenteredAffine', # 'Euler', 'CenteredEuler', # 'Rigid', 'CenteredRigid', 'QuaternionRigid', # 'Similarity', 'CenteredSimilarity'} if supported_types: return set(list(matrix_offset_types) + ['DisplacementFieldTransform']) # Check for valid dimension if (dimension < 2) or (dimension > 4): raise ValueError('Unsupported dimension: %i' % dimension) # Check for valid precision precision_types = ('float', 'double') if precision not in precision_types: raise ValueError('Unsupported Precision %s' % str(precision)) # Check for supported transform type if (transform_type not in matrix_offset_types) and (transform_type != 'DisplacementFieldTransform'): raise ValueError('Unsupported type %s' % str(transform_type)) # Check parameters with type if (transform_type=='Euler3DTransform'): dimension = 3 elif (transform_type=='Euler2DTransform'): dimension = 2 elif (transform_type=='Rigid3DTransform'): dimension = 3 elif (transform_type=='QuaternionRigidTransform'): dimension = 3 elif (transform_type=='Rigid2DTransform'): dimension = 2 elif (transform_type=='CenteredRigid2DTransform'): dimension = 2 elif (transform_type=='CenteredEuler3DTransform'): dimension = 3 elif (transform_type=='Similarity3DTransform'): dimension = 3 elif (transform_type=='Similarity2DTransform'): dimension = 2 elif (transform_type=='CenteredSimilarity2DTransform'): dimension = 2 # If displacement field if displacement_field is not None: raise ValueError('Displacement field transform not currently supported') # itk_tx = transform_from_displacement_field(displacement_field) # return tio.ants_transform(itk_tx) # Transforms that derive from itk::MatrixOffsetTransformBase libfn = utils.get_lib_fn('matrixOffset%s%i' % (utils.short_ptype(precision), dimension)) itk_tx = libfn(transform_type, precision, dimension, matrix, offset, center, translation, parameters, fixed_parameters) return tio.ANTsTransform(precision=precision, dimension=dimension, transform_type=transform_type, pointer=itk_tx)
python
def create_ants_transform(transform_type='AffineTransform', precision='float', dimension=3, matrix=None, offset=None, center=None, translation=None, parameters=None, fixed_parameters=None, displacement_field=None, supported_types=False): """ Create and initialize an ANTsTransform ANTsR function: `createAntsrTransform` Arguments --------- transform_type : string type of transform(s) precision : string numerical precision dimension : integer spatial dimension of transform matrix : ndarray matrix for linear transforms offset : tuple/list offset for linear transforms center : tuple/list center for linear transforms translation : tuple/list translation for linear transforms parameters : ndarray/list array of parameters fixed_parameters : ndarray/list array of fixed parameters displacement_field : ANTsImage multichannel ANTsImage for non-linear transform supported_types : boolean flag that returns array of possible transforms types Returns ------- ANTsTransform or list of ANTsTransform types Example ------- >>> import ants >>> translation = (3,4,5) >>> tx = ants.create_ants_transform( type='Euler3DTransform', translation=translation ) """ def _check_arg(arg, dim=1): if arg is None: if dim == 1: return [] elif dim == 2: return [[]] elif isinstance(arg, np.ndarray): return arg.tolist() elif isinstance(arg, (tuple, list)): return list(arg) else: raise ValueError('Incompatible input argument') matrix = _check_arg(matrix, dim=2) offset = _check_arg(offset) center = _check_arg(center) translation = _check_arg(translation) parameters = _check_arg(parameters) fixed_parameters = _check_arg(fixed_parameters) matrix_offset_types = {'AffineTransform', 'CenteredAffineTransform', 'Euler2DTransform', 'Euler3DTransform', 'Rigid3DTransform', 'Rigid2DTransform', 'QuaternionRigidTransform', 'Similarity2DTransform', 'CenteredSimilarity2DTransform', 'Similarity3DTransform', 'CenteredRigid2DTransform', 'CenteredEuler3DTransform'} #user_matrix_types = {'Affine','CenteredAffine', # 'Euler', 'CenteredEuler', # 'Rigid', 'CenteredRigid', 'QuaternionRigid', # 'Similarity', 'CenteredSimilarity'} if supported_types: return set(list(matrix_offset_types) + ['DisplacementFieldTransform']) # Check for valid dimension if (dimension < 2) or (dimension > 4): raise ValueError('Unsupported dimension: %i' % dimension) # Check for valid precision precision_types = ('float', 'double') if precision not in precision_types: raise ValueError('Unsupported Precision %s' % str(precision)) # Check for supported transform type if (transform_type not in matrix_offset_types) and (transform_type != 'DisplacementFieldTransform'): raise ValueError('Unsupported type %s' % str(transform_type)) # Check parameters with type if (transform_type=='Euler3DTransform'): dimension = 3 elif (transform_type=='Euler2DTransform'): dimension = 2 elif (transform_type=='Rigid3DTransform'): dimension = 3 elif (transform_type=='QuaternionRigidTransform'): dimension = 3 elif (transform_type=='Rigid2DTransform'): dimension = 2 elif (transform_type=='CenteredRigid2DTransform'): dimension = 2 elif (transform_type=='CenteredEuler3DTransform'): dimension = 3 elif (transform_type=='Similarity3DTransform'): dimension = 3 elif (transform_type=='Similarity2DTransform'): dimension = 2 elif (transform_type=='CenteredSimilarity2DTransform'): dimension = 2 # If displacement field if displacement_field is not None: raise ValueError('Displacement field transform not currently supported') # itk_tx = transform_from_displacement_field(displacement_field) # return tio.ants_transform(itk_tx) # Transforms that derive from itk::MatrixOffsetTransformBase libfn = utils.get_lib_fn('matrixOffset%s%i' % (utils.short_ptype(precision), dimension)) itk_tx = libfn(transform_type, precision, dimension, matrix, offset, center, translation, parameters, fixed_parameters) return tio.ANTsTransform(precision=precision, dimension=dimension, transform_type=transform_type, pointer=itk_tx)
[ "def", "create_ants_transform", "(", "transform_type", "=", "'AffineTransform'", ",", "precision", "=", "'float'", ",", "dimension", "=", "3", ",", "matrix", "=", "None", ",", "offset", "=", "None", ",", "center", "=", "None", ",", "translation", "=", "None", ",", "parameters", "=", "None", ",", "fixed_parameters", "=", "None", ",", "displacement_field", "=", "None", ",", "supported_types", "=", "False", ")", ":", "def", "_check_arg", "(", "arg", ",", "dim", "=", "1", ")", ":", "if", "arg", "is", "None", ":", "if", "dim", "==", "1", ":", "return", "[", "]", "elif", "dim", "==", "2", ":", "return", "[", "[", "]", "]", "elif", "isinstance", "(", "arg", ",", "np", ".", "ndarray", ")", ":", "return", "arg", ".", "tolist", "(", ")", "elif", "isinstance", "(", "arg", ",", "(", "tuple", ",", "list", ")", ")", ":", "return", "list", "(", "arg", ")", "else", ":", "raise", "ValueError", "(", "'Incompatible input argument'", ")", "matrix", "=", "_check_arg", "(", "matrix", ",", "dim", "=", "2", ")", "offset", "=", "_check_arg", "(", "offset", ")", "center", "=", "_check_arg", "(", "center", ")", "translation", "=", "_check_arg", "(", "translation", ")", "parameters", "=", "_check_arg", "(", "parameters", ")", "fixed_parameters", "=", "_check_arg", "(", "fixed_parameters", ")", "matrix_offset_types", "=", "{", "'AffineTransform'", ",", "'CenteredAffineTransform'", ",", "'Euler2DTransform'", ",", "'Euler3DTransform'", ",", "'Rigid3DTransform'", ",", "'Rigid2DTransform'", ",", "'QuaternionRigidTransform'", ",", "'Similarity2DTransform'", ",", "'CenteredSimilarity2DTransform'", ",", "'Similarity3DTransform'", ",", "'CenteredRigid2DTransform'", ",", "'CenteredEuler3DTransform'", "}", "#user_matrix_types = {'Affine','CenteredAffine', ", "# 'Euler', 'CenteredEuler',", "# 'Rigid', 'CenteredRigid', 'QuaternionRigid',", "# 'Similarity', 'CenteredSimilarity'}", "if", "supported_types", ":", "return", "set", "(", "list", "(", "matrix_offset_types", ")", "+", "[", "'DisplacementFieldTransform'", "]", ")", "# Check for valid dimension", "if", "(", "dimension", "<", "2", ")", "or", "(", "dimension", ">", "4", ")", ":", "raise", "ValueError", "(", "'Unsupported dimension: %i'", "%", "dimension", ")", "# Check for valid precision", "precision_types", "=", "(", "'float'", ",", "'double'", ")", "if", "precision", "not", "in", "precision_types", ":", "raise", "ValueError", "(", "'Unsupported Precision %s'", "%", "str", "(", "precision", ")", ")", "# Check for supported transform type", "if", "(", "transform_type", "not", "in", "matrix_offset_types", ")", "and", "(", "transform_type", "!=", "'DisplacementFieldTransform'", ")", ":", "raise", "ValueError", "(", "'Unsupported type %s'", "%", "str", "(", "transform_type", ")", ")", "# Check parameters with type", "if", "(", "transform_type", "==", "'Euler3DTransform'", ")", ":", "dimension", "=", "3", "elif", "(", "transform_type", "==", "'Euler2DTransform'", ")", ":", "dimension", "=", "2", "elif", "(", "transform_type", "==", "'Rigid3DTransform'", ")", ":", "dimension", "=", "3", "elif", "(", "transform_type", "==", "'QuaternionRigidTransform'", ")", ":", "dimension", "=", "3", "elif", "(", "transform_type", "==", "'Rigid2DTransform'", ")", ":", "dimension", "=", "2", "elif", "(", "transform_type", "==", "'CenteredRigid2DTransform'", ")", ":", "dimension", "=", "2", "elif", "(", "transform_type", "==", "'CenteredEuler3DTransform'", ")", ":", "dimension", "=", "3", "elif", "(", "transform_type", "==", "'Similarity3DTransform'", ")", ":", "dimension", "=", "3", "elif", "(", "transform_type", "==", "'Similarity2DTransform'", ")", ":", "dimension", "=", "2", "elif", "(", "transform_type", "==", "'CenteredSimilarity2DTransform'", ")", ":", "dimension", "=", "2", "# If displacement field", "if", "displacement_field", "is", "not", "None", ":", "raise", "ValueError", "(", "'Displacement field transform not currently supported'", ")", "# itk_tx = transform_from_displacement_field(displacement_field)", "# return tio.ants_transform(itk_tx)", "# Transforms that derive from itk::MatrixOffsetTransformBase", "libfn", "=", "utils", ".", "get_lib_fn", "(", "'matrixOffset%s%i'", "%", "(", "utils", ".", "short_ptype", "(", "precision", ")", ",", "dimension", ")", ")", "itk_tx", "=", "libfn", "(", "transform_type", ",", "precision", ",", "dimension", ",", "matrix", ",", "offset", ",", "center", ",", "translation", ",", "parameters", ",", "fixed_parameters", ")", "return", "tio", ".", "ANTsTransform", "(", "precision", "=", "precision", ",", "dimension", "=", "dimension", ",", "transform_type", "=", "transform_type", ",", "pointer", "=", "itk_tx", ")" ]
Create and initialize an ANTsTransform ANTsR function: `createAntsrTransform` Arguments --------- transform_type : string type of transform(s) precision : string numerical precision dimension : integer spatial dimension of transform matrix : ndarray matrix for linear transforms offset : tuple/list offset for linear transforms center : tuple/list center for linear transforms translation : tuple/list translation for linear transforms parameters : ndarray/list array of parameters fixed_parameters : ndarray/list array of fixed parameters displacement_field : ANTsImage multichannel ANTsImage for non-linear transform supported_types : boolean flag that returns array of possible transforms types Returns ------- ANTsTransform or list of ANTsTransform types Example ------- >>> import ants >>> translation = (3,4,5) >>> tx = ants.create_ants_transform( type='Euler3DTransform', translation=translation )
[ "Create", "and", "initialize", "an", "ANTsTransform" ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_transform_io.py#L38-L187
237,239
ANTsX/ANTsPy
ants/core/ants_transform_io.py
read_transform
def read_transform(filename, dimension=2, precision='float'): """ Read a transform from file ANTsR function: `readAntsrTransform` Arguments --------- filename : string filename of transform dimension : integer spatial dimension of transform precision : string numerical precision of transform Returns ------- ANTsTransform Example ------- >>> import ants >>> tx = ants.new_ants_transform(dimension=2) >>> tx.set_parameters((0.9,0,0,1.1,10,11)) >>> ants.write_transform(tx, '~/desktop/tx.mat') >>> tx2 = ants.read_transform('~/desktop/tx.mat') """ filename = os.path.expanduser(filename) if not os.path.exists(filename): raise ValueError('filename does not exist!') libfn1 = utils.get_lib_fn('getTransformDimensionFromFile') dimension = libfn1(filename) libfn2 = utils.get_lib_fn('getTransformNameFromFile') transform_type = libfn2(filename) libfn3 = utils.get_lib_fn('readTransform%s%i' % (utils.short_ptype(precision), dimension)) itk_tx = libfn3(filename, dimension, precision) return tio.ANTsTransform(precision=precision, dimension=dimension, transform_type=transform_type, pointer=itk_tx)
python
def read_transform(filename, dimension=2, precision='float'): """ Read a transform from file ANTsR function: `readAntsrTransform` Arguments --------- filename : string filename of transform dimension : integer spatial dimension of transform precision : string numerical precision of transform Returns ------- ANTsTransform Example ------- >>> import ants >>> tx = ants.new_ants_transform(dimension=2) >>> tx.set_parameters((0.9,0,0,1.1,10,11)) >>> ants.write_transform(tx, '~/desktop/tx.mat') >>> tx2 = ants.read_transform('~/desktop/tx.mat') """ filename = os.path.expanduser(filename) if not os.path.exists(filename): raise ValueError('filename does not exist!') libfn1 = utils.get_lib_fn('getTransformDimensionFromFile') dimension = libfn1(filename) libfn2 = utils.get_lib_fn('getTransformNameFromFile') transform_type = libfn2(filename) libfn3 = utils.get_lib_fn('readTransform%s%i' % (utils.short_ptype(precision), dimension)) itk_tx = libfn3(filename, dimension, precision) return tio.ANTsTransform(precision=precision, dimension=dimension, transform_type=transform_type, pointer=itk_tx)
[ "def", "read_transform", "(", "filename", ",", "dimension", "=", "2", ",", "precision", "=", "'float'", ")", ":", "filename", "=", "os", ".", "path", ".", "expanduser", "(", "filename", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "raise", "ValueError", "(", "'filename does not exist!'", ")", "libfn1", "=", "utils", ".", "get_lib_fn", "(", "'getTransformDimensionFromFile'", ")", "dimension", "=", "libfn1", "(", "filename", ")", "libfn2", "=", "utils", ".", "get_lib_fn", "(", "'getTransformNameFromFile'", ")", "transform_type", "=", "libfn2", "(", "filename", ")", "libfn3", "=", "utils", ".", "get_lib_fn", "(", "'readTransform%s%i'", "%", "(", "utils", ".", "short_ptype", "(", "precision", ")", ",", "dimension", ")", ")", "itk_tx", "=", "libfn3", "(", "filename", ",", "dimension", ",", "precision", ")", "return", "tio", ".", "ANTsTransform", "(", "precision", "=", "precision", ",", "dimension", "=", "dimension", ",", "transform_type", "=", "transform_type", ",", "pointer", "=", "itk_tx", ")" ]
Read a transform from file ANTsR function: `readAntsrTransform` Arguments --------- filename : string filename of transform dimension : integer spatial dimension of transform precision : string numerical precision of transform Returns ------- ANTsTransform Example ------- >>> import ants >>> tx = ants.new_ants_transform(dimension=2) >>> tx.set_parameters((0.9,0,0,1.1,10,11)) >>> ants.write_transform(tx, '~/desktop/tx.mat') >>> tx2 = ants.read_transform('~/desktop/tx.mat')
[ "Read", "a", "transform", "from", "file" ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_transform_io.py#L223-L266
237,240
ANTsX/ANTsPy
ants/core/ants_transform_io.py
write_transform
def write_transform(transform, filename): """ Write ANTsTransform to file ANTsR function: `writeAntsrTransform` Arguments --------- transform : ANTsTransform transform to save filename : string filename of transform (file extension is ".mat" for affine transforms) Returns ------- N/A Example ------- >>> import ants >>> tx = ants.new_ants_transform(dimension=2) >>> tx.set_parameters((0.9,0,0,1.1,10,11)) >>> ants.write_transform(tx, '~/desktop/tx.mat') >>> tx2 = ants.read_transform('~/desktop/tx.mat') """ filename = os.path.expanduser(filename) libfn = utils.get_lib_fn('writeTransform%s' % (transform._libsuffix)) libfn(transform.pointer, filename)
python
def write_transform(transform, filename): """ Write ANTsTransform to file ANTsR function: `writeAntsrTransform` Arguments --------- transform : ANTsTransform transform to save filename : string filename of transform (file extension is ".mat" for affine transforms) Returns ------- N/A Example ------- >>> import ants >>> tx = ants.new_ants_transform(dimension=2) >>> tx.set_parameters((0.9,0,0,1.1,10,11)) >>> ants.write_transform(tx, '~/desktop/tx.mat') >>> tx2 = ants.read_transform('~/desktop/tx.mat') """ filename = os.path.expanduser(filename) libfn = utils.get_lib_fn('writeTransform%s' % (transform._libsuffix)) libfn(transform.pointer, filename)
[ "def", "write_transform", "(", "transform", ",", "filename", ")", ":", "filename", "=", "os", ".", "path", ".", "expanduser", "(", "filename", ")", "libfn", "=", "utils", ".", "get_lib_fn", "(", "'writeTransform%s'", "%", "(", "transform", ".", "_libsuffix", ")", ")", "libfn", "(", "transform", ".", "pointer", ",", "filename", ")" ]
Write ANTsTransform to file ANTsR function: `writeAntsrTransform` Arguments --------- transform : ANTsTransform transform to save filename : string filename of transform (file extension is ".mat" for affine transforms) Returns ------- N/A Example ------- >>> import ants >>> tx = ants.new_ants_transform(dimension=2) >>> tx.set_parameters((0.9,0,0,1.1,10,11)) >>> ants.write_transform(tx, '~/desktop/tx.mat') >>> tx2 = ants.read_transform('~/desktop/tx.mat')
[ "Write", "ANTsTransform", "to", "file" ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_transform_io.py#L269-L297
237,241
ANTsX/ANTsPy
ants/registration/reflect_image.py
reflect_image
def reflect_image(image, axis=None, tx=None, metric='mattes'): """ Reflect an image along an axis ANTsR function: `reflectImage` Arguments --------- image : ANTsImage image to reflect axis : integer (optional) which dimension to reflect across, numbered from 0 to imageDimension-1 tx : string (optional) transformation type to estimate after reflection metric : string similarity metric for image registration. see antsRegistration. Returns ------- ANTsImage Example ------- >>> import ants >>> fi = ants.image_read( ants.get_ants_data('r16'), 'float' ) >>> axis = 2 >>> asym = ants.reflect_image(fi, axis, 'Affine')['warpedmovout'] >>> asym = asym - fi """ if axis is None: axis = image.dimension - 1 if (axis > image.dimension) or (axis < 0): axis = image.dimension - 1 rflct = mktemp(suffix='.mat') libfn = utils.get_lib_fn('reflectionMatrix%s'%image._libsuffix) libfn(image.pointer, axis, rflct) if tx is not None: rfi = registration(image, image, type_of_transform=tx, syn_metric=metric, outprefix=mktemp(), initial_transform=rflct) return rfi else: return apply_transforms(image, image, rflct)
python
def reflect_image(image, axis=None, tx=None, metric='mattes'): """ Reflect an image along an axis ANTsR function: `reflectImage` Arguments --------- image : ANTsImage image to reflect axis : integer (optional) which dimension to reflect across, numbered from 0 to imageDimension-1 tx : string (optional) transformation type to estimate after reflection metric : string similarity metric for image registration. see antsRegistration. Returns ------- ANTsImage Example ------- >>> import ants >>> fi = ants.image_read( ants.get_ants_data('r16'), 'float' ) >>> axis = 2 >>> asym = ants.reflect_image(fi, axis, 'Affine')['warpedmovout'] >>> asym = asym - fi """ if axis is None: axis = image.dimension - 1 if (axis > image.dimension) or (axis < 0): axis = image.dimension - 1 rflct = mktemp(suffix='.mat') libfn = utils.get_lib_fn('reflectionMatrix%s'%image._libsuffix) libfn(image.pointer, axis, rflct) if tx is not None: rfi = registration(image, image, type_of_transform=tx, syn_metric=metric, outprefix=mktemp(), initial_transform=rflct) return rfi else: return apply_transforms(image, image, rflct)
[ "def", "reflect_image", "(", "image", ",", "axis", "=", "None", ",", "tx", "=", "None", ",", "metric", "=", "'mattes'", ")", ":", "if", "axis", "is", "None", ":", "axis", "=", "image", ".", "dimension", "-", "1", "if", "(", "axis", ">", "image", ".", "dimension", ")", "or", "(", "axis", "<", "0", ")", ":", "axis", "=", "image", ".", "dimension", "-", "1", "rflct", "=", "mktemp", "(", "suffix", "=", "'.mat'", ")", "libfn", "=", "utils", ".", "get_lib_fn", "(", "'reflectionMatrix%s'", "%", "image", ".", "_libsuffix", ")", "libfn", "(", "image", ".", "pointer", ",", "axis", ",", "rflct", ")", "if", "tx", "is", "not", "None", ":", "rfi", "=", "registration", "(", "image", ",", "image", ",", "type_of_transform", "=", "tx", ",", "syn_metric", "=", "metric", ",", "outprefix", "=", "mktemp", "(", ")", ",", "initial_transform", "=", "rflct", ")", "return", "rfi", "else", ":", "return", "apply_transforms", "(", "image", ",", "image", ",", "rflct", ")" ]
Reflect an image along an axis ANTsR function: `reflectImage` Arguments --------- image : ANTsImage image to reflect axis : integer (optional) which dimension to reflect across, numbered from 0 to imageDimension-1 tx : string (optional) transformation type to estimate after reflection metric : string similarity metric for image registration. see antsRegistration. Returns ------- ANTsImage Example ------- >>> import ants >>> fi = ants.image_read( ants.get_ants_data('r16'), 'float' ) >>> axis = 2 >>> asym = ants.reflect_image(fi, axis, 'Affine')['warpedmovout'] >>> asym = asym - fi
[ "Reflect", "an", "image", "along", "an", "axis" ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/registration/reflect_image.py#L12-L61
237,242
ANTsX/ANTsPy
ants/contrib/bids/cohort.py
BIDSCohort.create_sampler
def create_sampler(self, inputs, targets, input_reader=None, target_reader=None, input_transform=None, target_transform=None, co_transform=None, input_return_processor=None, target_return_processor=None, co_return_processor=None): """ Create a BIDSSampler that can be used to generate infinite augmented samples """ pass
python
def create_sampler(self, inputs, targets, input_reader=None, target_reader=None, input_transform=None, target_transform=None, co_transform=None, input_return_processor=None, target_return_processor=None, co_return_processor=None): """ Create a BIDSSampler that can be used to generate infinite augmented samples """ pass
[ "def", "create_sampler", "(", "self", ",", "inputs", ",", "targets", ",", "input_reader", "=", "None", ",", "target_reader", "=", "None", ",", "input_transform", "=", "None", ",", "target_transform", "=", "None", ",", "co_transform", "=", "None", ",", "input_return_processor", "=", "None", ",", "target_return_processor", "=", "None", ",", "co_return_processor", "=", "None", ")", ":", "pass" ]
Create a BIDSSampler that can be used to generate infinite augmented samples
[ "Create", "a", "BIDSSampler", "that", "can", "be", "used", "to", "generate", "infinite", "augmented", "samples" ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/contrib/bids/cohort.py#L88-L94
237,243
ANTsX/ANTsPy
ants/utils/slice_image.py
slice_image
def slice_image(image, axis=None, idx=None): """ Slice an image. Example ------- >>> import ants >>> mni = ants.image_read(ants.get_data('mni')) >>> mni2 = ants.slice_image(mni, axis=1, idx=100) """ if image.dimension < 3: raise ValueError('image must have at least 3 dimensions') inpixeltype = image.pixeltype ndim = image.dimension if image.pixeltype != 'float': image = image.clone('float') libfn = utils.get_lib_fn('sliceImageF%i' % ndim) itkimage = libfn(image.pointer, axis, idx) return iio.ANTsImage(pixeltype='float', dimension=ndim-1, components=image.components, pointer=itkimage).clone(inpixeltype)
python
def slice_image(image, axis=None, idx=None): """ Slice an image. Example ------- >>> import ants >>> mni = ants.image_read(ants.get_data('mni')) >>> mni2 = ants.slice_image(mni, axis=1, idx=100) """ if image.dimension < 3: raise ValueError('image must have at least 3 dimensions') inpixeltype = image.pixeltype ndim = image.dimension if image.pixeltype != 'float': image = image.clone('float') libfn = utils.get_lib_fn('sliceImageF%i' % ndim) itkimage = libfn(image.pointer, axis, idx) return iio.ANTsImage(pixeltype='float', dimension=ndim-1, components=image.components, pointer=itkimage).clone(inpixeltype)
[ "def", "slice_image", "(", "image", ",", "axis", "=", "None", ",", "idx", "=", "None", ")", ":", "if", "image", ".", "dimension", "<", "3", ":", "raise", "ValueError", "(", "'image must have at least 3 dimensions'", ")", "inpixeltype", "=", "image", ".", "pixeltype", "ndim", "=", "image", ".", "dimension", "if", "image", ".", "pixeltype", "!=", "'float'", ":", "image", "=", "image", ".", "clone", "(", "'float'", ")", "libfn", "=", "utils", ".", "get_lib_fn", "(", "'sliceImageF%i'", "%", "ndim", ")", "itkimage", "=", "libfn", "(", "image", ".", "pointer", ",", "axis", ",", "idx", ")", "return", "iio", ".", "ANTsImage", "(", "pixeltype", "=", "'float'", ",", "dimension", "=", "ndim", "-", "1", ",", "components", "=", "image", ".", "components", ",", "pointer", "=", "itkimage", ")", ".", "clone", "(", "inpixeltype", ")" ]
Slice an image. Example ------- >>> import ants >>> mni = ants.image_read(ants.get_data('mni')) >>> mni2 = ants.slice_image(mni, axis=1, idx=100)
[ "Slice", "an", "image", "." ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/slice_image.py#L10-L32
237,244
ANTsX/ANTsPy
ants/utils/pad_image.py
pad_image
def pad_image(image, shape=None, pad_width=None, value=0.0, return_padvals=False): """ Pad an image to have the given shape or to be isotropic. Arguments --------- image : ANTsImage image to pad shape : tuple - if shape is given, the image will be padded in each dimension until it has this shape - if shape is not given, the image will be padded along each dimension to match the largest existing dimension so that it has isotropic dimension pad_width : list of pad_value : scalar value with which image will be padded Example ------- >>> import ants >>> img = ants.image_read(ants.get_data('r16')) >>> img2 = ants.pad_image(img, shape=(300,300)) >>> mni = ants.image_read(ants.get_data('mni')) >>> mni2 = ants.pad_image(mni) >>> mni3 = ants.pad_image(mni, pad_width=[(0,4),(0,4),(0,4)]) >>> mni4 = ants.pad_image(mni, pad_width=(4,4,4)) """ inpixeltype = image.pixeltype ndim = image.dimension if image.pixeltype != 'float': image = image.clone('float') if pad_width is None: if shape is None: shape = [max(image.shape)] * image.dimension lower_pad_vals = [math.floor(max(ns-os,0)/2) for os,ns in zip(image.shape, shape)] upper_pad_vals = [math.ceil(max(ns-os,0)/2) for os,ns in zip(image.shape, shape)] else: if shape is not None: raise ValueError('Cannot give both `shape` and `pad_width`. Pick one!') if len(pad_width) != image.dimension: raise ValueError('Must give pad width for each image dimension') lower_pad_vals = [] upper_pad_vals = [] for p in pad_width: if isinstance(p, (list, tuple)): lower_pad_vals.append(p[0]) upper_pad_vals.append(p[1]) else: lower_pad_vals.append(math.floor(p/2)) upper_pad_vals.append(math.ceil(p/2)) libfn = utils.get_lib_fn('padImageF%i' % ndim) itkimage = libfn(image.pointer, lower_pad_vals, upper_pad_vals, value) new_image = iio.ANTsImage(pixeltype='float', dimension=ndim, components=image.components, pointer=itkimage).clone(inpixeltype) if return_padvals: return new_image, lower_pad_vals, upper_pad_vals else: return new_image
python
def pad_image(image, shape=None, pad_width=None, value=0.0, return_padvals=False): """ Pad an image to have the given shape or to be isotropic. Arguments --------- image : ANTsImage image to pad shape : tuple - if shape is given, the image will be padded in each dimension until it has this shape - if shape is not given, the image will be padded along each dimension to match the largest existing dimension so that it has isotropic dimension pad_width : list of pad_value : scalar value with which image will be padded Example ------- >>> import ants >>> img = ants.image_read(ants.get_data('r16')) >>> img2 = ants.pad_image(img, shape=(300,300)) >>> mni = ants.image_read(ants.get_data('mni')) >>> mni2 = ants.pad_image(mni) >>> mni3 = ants.pad_image(mni, pad_width=[(0,4),(0,4),(0,4)]) >>> mni4 = ants.pad_image(mni, pad_width=(4,4,4)) """ inpixeltype = image.pixeltype ndim = image.dimension if image.pixeltype != 'float': image = image.clone('float') if pad_width is None: if shape is None: shape = [max(image.shape)] * image.dimension lower_pad_vals = [math.floor(max(ns-os,0)/2) for os,ns in zip(image.shape, shape)] upper_pad_vals = [math.ceil(max(ns-os,0)/2) for os,ns in zip(image.shape, shape)] else: if shape is not None: raise ValueError('Cannot give both `shape` and `pad_width`. Pick one!') if len(pad_width) != image.dimension: raise ValueError('Must give pad width for each image dimension') lower_pad_vals = [] upper_pad_vals = [] for p in pad_width: if isinstance(p, (list, tuple)): lower_pad_vals.append(p[0]) upper_pad_vals.append(p[1]) else: lower_pad_vals.append(math.floor(p/2)) upper_pad_vals.append(math.ceil(p/2)) libfn = utils.get_lib_fn('padImageF%i' % ndim) itkimage = libfn(image.pointer, lower_pad_vals, upper_pad_vals, value) new_image = iio.ANTsImage(pixeltype='float', dimension=ndim, components=image.components, pointer=itkimage).clone(inpixeltype) if return_padvals: return new_image, lower_pad_vals, upper_pad_vals else: return new_image
[ "def", "pad_image", "(", "image", ",", "shape", "=", "None", ",", "pad_width", "=", "None", ",", "value", "=", "0.0", ",", "return_padvals", "=", "False", ")", ":", "inpixeltype", "=", "image", ".", "pixeltype", "ndim", "=", "image", ".", "dimension", "if", "image", ".", "pixeltype", "!=", "'float'", ":", "image", "=", "image", ".", "clone", "(", "'float'", ")", "if", "pad_width", "is", "None", ":", "if", "shape", "is", "None", ":", "shape", "=", "[", "max", "(", "image", ".", "shape", ")", "]", "*", "image", ".", "dimension", "lower_pad_vals", "=", "[", "math", ".", "floor", "(", "max", "(", "ns", "-", "os", ",", "0", ")", "/", "2", ")", "for", "os", ",", "ns", "in", "zip", "(", "image", ".", "shape", ",", "shape", ")", "]", "upper_pad_vals", "=", "[", "math", ".", "ceil", "(", "max", "(", "ns", "-", "os", ",", "0", ")", "/", "2", ")", "for", "os", ",", "ns", "in", "zip", "(", "image", ".", "shape", ",", "shape", ")", "]", "else", ":", "if", "shape", "is", "not", "None", ":", "raise", "ValueError", "(", "'Cannot give both `shape` and `pad_width`. Pick one!'", ")", "if", "len", "(", "pad_width", ")", "!=", "image", ".", "dimension", ":", "raise", "ValueError", "(", "'Must give pad width for each image dimension'", ")", "lower_pad_vals", "=", "[", "]", "upper_pad_vals", "=", "[", "]", "for", "p", "in", "pad_width", ":", "if", "isinstance", "(", "p", ",", "(", "list", ",", "tuple", ")", ")", ":", "lower_pad_vals", ".", "append", "(", "p", "[", "0", "]", ")", "upper_pad_vals", ".", "append", "(", "p", "[", "1", "]", ")", "else", ":", "lower_pad_vals", ".", "append", "(", "math", ".", "floor", "(", "p", "/", "2", ")", ")", "upper_pad_vals", ".", "append", "(", "math", ".", "ceil", "(", "p", "/", "2", ")", ")", "libfn", "=", "utils", ".", "get_lib_fn", "(", "'padImageF%i'", "%", "ndim", ")", "itkimage", "=", "libfn", "(", "image", ".", "pointer", ",", "lower_pad_vals", ",", "upper_pad_vals", ",", "value", ")", "new_image", "=", "iio", ".", "ANTsImage", "(", "pixeltype", "=", "'float'", ",", "dimension", "=", "ndim", ",", "components", "=", "image", ".", "components", ",", "pointer", "=", "itkimage", ")", ".", "clone", "(", "inpixeltype", ")", "if", "return_padvals", ":", "return", "new_image", ",", "lower_pad_vals", ",", "upper_pad_vals", "else", ":", "return", "new_image" ]
Pad an image to have the given shape or to be isotropic. Arguments --------- image : ANTsImage image to pad shape : tuple - if shape is given, the image will be padded in each dimension until it has this shape - if shape is not given, the image will be padded along each dimension to match the largest existing dimension so that it has isotropic dimension pad_width : list of pad_value : scalar value with which image will be padded Example ------- >>> import ants >>> img = ants.image_read(ants.get_data('r16')) >>> img2 = ants.pad_image(img, shape=(300,300)) >>> mni = ants.image_read(ants.get_data('mni')) >>> mni2 = ants.pad_image(mni) >>> mni3 = ants.pad_image(mni, pad_width=[(0,4),(0,4),(0,4)]) >>> mni4 = ants.pad_image(mni, pad_width=(4,4,4))
[ "Pad", "an", "image", "to", "have", "the", "given", "shape", "or", "to", "be", "isotropic", "." ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/pad_image.py#L10-L75
237,245
ANTsX/ANTsPy
ants/core/ants_metric.py
ANTsImageToImageMetric.set_fixed_image
def set_fixed_image(self, image): """ Set Fixed ANTsImage for metric """ if not isinstance(image, iio.ANTsImage): raise ValueError('image must be ANTsImage type') if image.dimension != self.dimension: raise ValueError('image dim (%i) does not match metric dim (%i)' % (image.dimension, self.dimension)) self._metric.setFixedImage(image.pointer, False) self.fixed_image = image
python
def set_fixed_image(self, image): """ Set Fixed ANTsImage for metric """ if not isinstance(image, iio.ANTsImage): raise ValueError('image must be ANTsImage type') if image.dimension != self.dimension: raise ValueError('image dim (%i) does not match metric dim (%i)' % (image.dimension, self.dimension)) self._metric.setFixedImage(image.pointer, False) self.fixed_image = image
[ "def", "set_fixed_image", "(", "self", ",", "image", ")", ":", "if", "not", "isinstance", "(", "image", ",", "iio", ".", "ANTsImage", ")", ":", "raise", "ValueError", "(", "'image must be ANTsImage type'", ")", "if", "image", ".", "dimension", "!=", "self", ".", "dimension", ":", "raise", "ValueError", "(", "'image dim (%i) does not match metric dim (%i)'", "%", "(", "image", ".", "dimension", ",", "self", ".", "dimension", ")", ")", "self", ".", "_metric", ".", "setFixedImage", "(", "image", ".", "pointer", ",", "False", ")", "self", ".", "fixed_image", "=", "image" ]
Set Fixed ANTsImage for metric
[ "Set", "Fixed", "ANTsImage", "for", "metric" ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_metric.py#L48-L59
237,246
ANTsX/ANTsPy
ants/core/ants_metric.py
ANTsImageToImageMetric.set_moving_image
def set_moving_image(self, image): """ Set Moving ANTsImage for metric """ if not isinstance(image, iio.ANTsImage): raise ValueError('image must be ANTsImage type') if image.dimension != self.dimension: raise ValueError('image dim (%i) does not match metric dim (%i)' % (image.dimension, self.dimension)) self._metric.setMovingImage(image.pointer, False) self.moving_image = image
python
def set_moving_image(self, image): """ Set Moving ANTsImage for metric """ if not isinstance(image, iio.ANTsImage): raise ValueError('image must be ANTsImage type') if image.dimension != self.dimension: raise ValueError('image dim (%i) does not match metric dim (%i)' % (image.dimension, self.dimension)) self._metric.setMovingImage(image.pointer, False) self.moving_image = image
[ "def", "set_moving_image", "(", "self", ",", "image", ")", ":", "if", "not", "isinstance", "(", "image", ",", "iio", ".", "ANTsImage", ")", ":", "raise", "ValueError", "(", "'image must be ANTsImage type'", ")", "if", "image", ".", "dimension", "!=", "self", ".", "dimension", ":", "raise", "ValueError", "(", "'image dim (%i) does not match metric dim (%i)'", "%", "(", "image", ".", "dimension", ",", "self", ".", "dimension", ")", ")", "self", ".", "_metric", ".", "setMovingImage", "(", "image", ".", "pointer", ",", "False", ")", "self", ".", "moving_image", "=", "image" ]
Set Moving ANTsImage for metric
[ "Set", "Moving", "ANTsImage", "for", "metric" ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/core/ants_metric.py#L74-L85
237,247
ANTsX/ANTsPy
ants/utils/image_to_cluster_images.py
image_to_cluster_images
def image_to_cluster_images(image, min_cluster_size=50, min_thresh=1e-06, max_thresh=1): """ Converts an image to several independent images. Produces a unique image for each connected component 1 through N of size > min_cluster_size ANTsR function: `image2ClusterImages` Arguments --------- image : ANTsImage input image min_cluster_size : integer throw away clusters smaller than this value min_thresh : scalar threshold to a statistical map max_thresh : scalar threshold to a statistical map Returns ------- list of ANTsImage types Example ------- >>> import ants >>> image = ants.image_read(ants.get_ants_data('r16')) >>> image = ants.threshold_image(image, 1, 1e15) >>> image_cluster_list = ants.image_to_cluster_images(image) """ if not isinstance(image, iio.ANTsImage): raise ValueError('image must be ANTsImage type') clust = label_clusters(image, min_cluster_size, min_thresh, max_thresh) labs = np.unique(clust[clust > 0]) clustlist = [] for i in range(len(labs)): labimage = image.clone() labimage[clust != labs[i]] = 0 clustlist.append(labimage) return clustlist
python
def image_to_cluster_images(image, min_cluster_size=50, min_thresh=1e-06, max_thresh=1): """ Converts an image to several independent images. Produces a unique image for each connected component 1 through N of size > min_cluster_size ANTsR function: `image2ClusterImages` Arguments --------- image : ANTsImage input image min_cluster_size : integer throw away clusters smaller than this value min_thresh : scalar threshold to a statistical map max_thresh : scalar threshold to a statistical map Returns ------- list of ANTsImage types Example ------- >>> import ants >>> image = ants.image_read(ants.get_ants_data('r16')) >>> image = ants.threshold_image(image, 1, 1e15) >>> image_cluster_list = ants.image_to_cluster_images(image) """ if not isinstance(image, iio.ANTsImage): raise ValueError('image must be ANTsImage type') clust = label_clusters(image, min_cluster_size, min_thresh, max_thresh) labs = np.unique(clust[clust > 0]) clustlist = [] for i in range(len(labs)): labimage = image.clone() labimage[clust != labs[i]] = 0 clustlist.append(labimage) return clustlist
[ "def", "image_to_cluster_images", "(", "image", ",", "min_cluster_size", "=", "50", ",", "min_thresh", "=", "1e-06", ",", "max_thresh", "=", "1", ")", ":", "if", "not", "isinstance", "(", "image", ",", "iio", ".", "ANTsImage", ")", ":", "raise", "ValueError", "(", "'image must be ANTsImage type'", ")", "clust", "=", "label_clusters", "(", "image", ",", "min_cluster_size", ",", "min_thresh", ",", "max_thresh", ")", "labs", "=", "np", ".", "unique", "(", "clust", "[", "clust", ">", "0", "]", ")", "clustlist", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "labs", ")", ")", ":", "labimage", "=", "image", ".", "clone", "(", ")", "labimage", "[", "clust", "!=", "labs", "[", "i", "]", "]", "=", "0", "clustlist", ".", "append", "(", "labimage", ")", "return", "clustlist" ]
Converts an image to several independent images. Produces a unique image for each connected component 1 through N of size > min_cluster_size ANTsR function: `image2ClusterImages` Arguments --------- image : ANTsImage input image min_cluster_size : integer throw away clusters smaller than this value min_thresh : scalar threshold to a statistical map max_thresh : scalar threshold to a statistical map Returns ------- list of ANTsImage types Example ------- >>> import ants >>> image = ants.image_read(ants.get_ants_data('r16')) >>> image = ants.threshold_image(image, 1, 1e15) >>> image_cluster_list = ants.image_to_cluster_images(image)
[ "Converts", "an", "image", "to", "several", "independent", "images", "." ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/image_to_cluster_images.py#L9-L51
237,248
ANTsX/ANTsPy
ants/utils/threshold_image.py
threshold_image
def threshold_image(image, low_thresh=None, high_thresh=None, inval=1, outval=0, binary=True): """ Converts a scalar image into a binary image by thresholding operations ANTsR function: `thresholdImage` Arguments --------- image : ANTsImage Input image to operate on low_thresh : scalar (optional) Lower edge of threshold window hight_thresh : scalar (optional) Higher edge of threshold window inval : scalar Output value for image voxels in between lothresh and hithresh outval : scalar Output value for image voxels lower than lothresh or higher than hithresh binary : boolean if true, returns binary thresholded image if false, return binary thresholded image multiplied by original image Returns ------- ANTsImage Example ------- >>> import ants >>> image = ants.image_read( ants.get_ants_data('r16') ) >>> timage = ants.threshold_image(image, 0.5, 1e15) """ if high_thresh is None: high_thresh = image.max() + 0.01 if low_thresh is None: low_thresh = image.min() - 0.01 dim = image.dimension outimage = image.clone() args = [dim, image, outimage, low_thresh, high_thresh, inval, outval] processed_args = _int_antsProcessArguments(args) libfn = utils.get_lib_fn('ThresholdImage') libfn(processed_args) if binary: return outimage else: return outimage*image
python
def threshold_image(image, low_thresh=None, high_thresh=None, inval=1, outval=0, binary=True): """ Converts a scalar image into a binary image by thresholding operations ANTsR function: `thresholdImage` Arguments --------- image : ANTsImage Input image to operate on low_thresh : scalar (optional) Lower edge of threshold window hight_thresh : scalar (optional) Higher edge of threshold window inval : scalar Output value for image voxels in between lothresh and hithresh outval : scalar Output value for image voxels lower than lothresh or higher than hithresh binary : boolean if true, returns binary thresholded image if false, return binary thresholded image multiplied by original image Returns ------- ANTsImage Example ------- >>> import ants >>> image = ants.image_read( ants.get_ants_data('r16') ) >>> timage = ants.threshold_image(image, 0.5, 1e15) """ if high_thresh is None: high_thresh = image.max() + 0.01 if low_thresh is None: low_thresh = image.min() - 0.01 dim = image.dimension outimage = image.clone() args = [dim, image, outimage, low_thresh, high_thresh, inval, outval] processed_args = _int_antsProcessArguments(args) libfn = utils.get_lib_fn('ThresholdImage') libfn(processed_args) if binary: return outimage else: return outimage*image
[ "def", "threshold_image", "(", "image", ",", "low_thresh", "=", "None", ",", "high_thresh", "=", "None", ",", "inval", "=", "1", ",", "outval", "=", "0", ",", "binary", "=", "True", ")", ":", "if", "high_thresh", "is", "None", ":", "high_thresh", "=", "image", ".", "max", "(", ")", "+", "0.01", "if", "low_thresh", "is", "None", ":", "low_thresh", "=", "image", ".", "min", "(", ")", "-", "0.01", "dim", "=", "image", ".", "dimension", "outimage", "=", "image", ".", "clone", "(", ")", "args", "=", "[", "dim", ",", "image", ",", "outimage", ",", "low_thresh", ",", "high_thresh", ",", "inval", ",", "outval", "]", "processed_args", "=", "_int_antsProcessArguments", "(", "args", ")", "libfn", "=", "utils", ".", "get_lib_fn", "(", "'ThresholdImage'", ")", "libfn", "(", "processed_args", ")", "if", "binary", ":", "return", "outimage", "else", ":", "return", "outimage", "*", "image" ]
Converts a scalar image into a binary image by thresholding operations ANTsR function: `thresholdImage` Arguments --------- image : ANTsImage Input image to operate on low_thresh : scalar (optional) Lower edge of threshold window hight_thresh : scalar (optional) Higher edge of threshold window inval : scalar Output value for image voxels in between lothresh and hithresh outval : scalar Output value for image voxels lower than lothresh or higher than hithresh binary : boolean if true, returns binary thresholded image if false, return binary thresholded image multiplied by original image Returns ------- ANTsImage Example ------- >>> import ants >>> image = ants.image_read( ants.get_ants_data('r16') ) >>> timage = ants.threshold_image(image, 0.5, 1e15)
[ "Converts", "a", "scalar", "image", "into", "a", "binary", "image", "by", "thresholding", "operations" ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/utils/threshold_image.py#L10-L60
237,249
ANTsX/ANTsPy
ants/registration/symmetrize_image.py
symmetrize_image
def symmetrize_image(image): """ Use registration and reflection to make an image symmetric ANTsR function: N/A Arguments --------- image : ANTsImage image to make symmetric Returns ------- ANTsImage Example ------- >>> import ants >>> image = ants.image_read( ants.get_ants_data('r16') , 'float') >>> simage = ants.symimage(image) """ imager = reflect_image(image, axis=0) imageavg = imager * 0.5 + image for i in range(5): w1 = registration(imageavg, image, type_of_transform='SyN') w2 = registration(imageavg, imager, type_of_transform='SyN') xavg = w1['warpedmovout']*0.5 + w2['warpedmovout']*0.5 nada1 = apply_transforms(image, image, w1['fwdtransforms'], compose=w1['fwdtransforms'][0]) nada2 = apply_transforms(image, image, w2['fwdtransforms'], compose=w2['fwdtransforms'][0]) wavg = (iio.image_read(nada1) + iio.image_read(nada2)) * (-0.5) wavgfn = mktemp(suffix='.nii.gz') iio.image_write(wavg, wavgfn) xavg = apply_transforms(image, imageavg, wavgfn) return xavg
python
def symmetrize_image(image): """ Use registration and reflection to make an image symmetric ANTsR function: N/A Arguments --------- image : ANTsImage image to make symmetric Returns ------- ANTsImage Example ------- >>> import ants >>> image = ants.image_read( ants.get_ants_data('r16') , 'float') >>> simage = ants.symimage(image) """ imager = reflect_image(image, axis=0) imageavg = imager * 0.5 + image for i in range(5): w1 = registration(imageavg, image, type_of_transform='SyN') w2 = registration(imageavg, imager, type_of_transform='SyN') xavg = w1['warpedmovout']*0.5 + w2['warpedmovout']*0.5 nada1 = apply_transforms(image, image, w1['fwdtransforms'], compose=w1['fwdtransforms'][0]) nada2 = apply_transforms(image, image, w2['fwdtransforms'], compose=w2['fwdtransforms'][0]) wavg = (iio.image_read(nada1) + iio.image_read(nada2)) * (-0.5) wavgfn = mktemp(suffix='.nii.gz') iio.image_write(wavg, wavgfn) xavg = apply_transforms(image, imageavg, wavgfn) return xavg
[ "def", "symmetrize_image", "(", "image", ")", ":", "imager", "=", "reflect_image", "(", "image", ",", "axis", "=", "0", ")", "imageavg", "=", "imager", "*", "0.5", "+", "image", "for", "i", "in", "range", "(", "5", ")", ":", "w1", "=", "registration", "(", "imageavg", ",", "image", ",", "type_of_transform", "=", "'SyN'", ")", "w2", "=", "registration", "(", "imageavg", ",", "imager", ",", "type_of_transform", "=", "'SyN'", ")", "xavg", "=", "w1", "[", "'warpedmovout'", "]", "*", "0.5", "+", "w2", "[", "'warpedmovout'", "]", "*", "0.5", "nada1", "=", "apply_transforms", "(", "image", ",", "image", ",", "w1", "[", "'fwdtransforms'", "]", ",", "compose", "=", "w1", "[", "'fwdtransforms'", "]", "[", "0", "]", ")", "nada2", "=", "apply_transforms", "(", "image", ",", "image", ",", "w2", "[", "'fwdtransforms'", "]", ",", "compose", "=", "w2", "[", "'fwdtransforms'", "]", "[", "0", "]", ")", "wavg", "=", "(", "iio", ".", "image_read", "(", "nada1", ")", "+", "iio", ".", "image_read", "(", "nada2", ")", ")", "*", "(", "-", "0.5", ")", "wavgfn", "=", "mktemp", "(", "suffix", "=", "'.nii.gz'", ")", "iio", ".", "image_write", "(", "wavg", ",", "wavgfn", ")", "xavg", "=", "apply_transforms", "(", "image", ",", "imageavg", ",", "wavgfn", ")", "return", "xavg" ]
Use registration and reflection to make an image symmetric ANTsR function: N/A Arguments --------- image : ANTsImage image to make symmetric Returns ------- ANTsImage Example ------- >>> import ants >>> image = ants.image_read( ants.get_ants_data('r16') , 'float') >>> simage = ants.symimage(image)
[ "Use", "registration", "and", "reflection", "to", "make", "an", "image", "symmetric" ]
638020af2cdfc5ff4bdb9809ffe67aa505727a3b
https://github.com/ANTsX/ANTsPy/blob/638020af2cdfc5ff4bdb9809ffe67aa505727a3b/ants/registration/symmetrize_image.py#L13-L49
237,250
freakboy3742/pyxero
xero/basemanager.py
BaseManager._get_attachments
def _get_attachments(self, id): """Retrieve a list of attachments associated with this Xero object.""" uri = '/'.join([self.base_url, self.name, id, 'Attachments']) + '/' return uri, {}, 'get', None, None, False
python
def _get_attachments(self, id): """Retrieve a list of attachments associated with this Xero object.""" uri = '/'.join([self.base_url, self.name, id, 'Attachments']) + '/' return uri, {}, 'get', None, None, False
[ "def", "_get_attachments", "(", "self", ",", "id", ")", ":", "uri", "=", "'/'", ".", "join", "(", "[", "self", ".", "base_url", ",", "self", ".", "name", ",", "id", ",", "'Attachments'", "]", ")", "+", "'/'", "return", "uri", ",", "{", "}", ",", "'get'", ",", "None", ",", "None", ",", "False" ]
Retrieve a list of attachments associated with this Xero object.
[ "Retrieve", "a", "list", "of", "attachments", "associated", "with", "this", "Xero", "object", "." ]
5566f17fa06ed1f2fb9426c112951a72276b0f9a
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/xero/basemanager.py#L240-L243
237,251
freakboy3742/pyxero
xero/basemanager.py
BaseManager._put_attachment_data
def _put_attachment_data(self, id, filename, data, content_type, include_online=False): """Upload an attachment to the Xero object.""" uri = '/'.join([self.base_url, self.name, id, 'Attachments', filename]) params = {'IncludeOnline': 'true'} if include_online else {} headers = {'Content-Type': content_type, 'Content-Length': str(len(data))} return uri, params, 'put', data, headers, False
python
def _put_attachment_data(self, id, filename, data, content_type, include_online=False): """Upload an attachment to the Xero object.""" uri = '/'.join([self.base_url, self.name, id, 'Attachments', filename]) params = {'IncludeOnline': 'true'} if include_online else {} headers = {'Content-Type': content_type, 'Content-Length': str(len(data))} return uri, params, 'put', data, headers, False
[ "def", "_put_attachment_data", "(", "self", ",", "id", ",", "filename", ",", "data", ",", "content_type", ",", "include_online", "=", "False", ")", ":", "uri", "=", "'/'", ".", "join", "(", "[", "self", ".", "base_url", ",", "self", ".", "name", ",", "id", ",", "'Attachments'", ",", "filename", "]", ")", "params", "=", "{", "'IncludeOnline'", ":", "'true'", "}", "if", "include_online", "else", "{", "}", "headers", "=", "{", "'Content-Type'", ":", "content_type", ",", "'Content-Length'", ":", "str", "(", "len", "(", "data", ")", ")", "}", "return", "uri", ",", "params", ",", "'put'", ",", "data", ",", "headers", ",", "False" ]
Upload an attachment to the Xero object.
[ "Upload", "an", "attachment", "to", "the", "Xero", "object", "." ]
5566f17fa06ed1f2fb9426c112951a72276b0f9a
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/xero/basemanager.py#L280-L285
237,252
freakboy3742/pyxero
examples/partner_oauth_flow/runserver.py
PartnerCredentialsHandler.page_response
def page_response(self, title='', body=''): """ Helper to render an html page with dynamic content """ f = StringIO() f.write('<!DOCTYPE html>\n') f.write('<html>\n') f.write('<head><title>{}</title><head>\n'.format(title)) f.write('<body>\n<h2>{}</h2>\n'.format(title)) f.write('<div class="content">{}</div>\n'.format(body)) f.write('</body>\n</html>\n') length = f.tell() f.seek(0) self.send_response(200) encoding = sys.getfilesystemencoding() self.send_header("Content-type", "text/html; charset=%s" % encoding) self.send_header("Content-Length", str(length)) self.end_headers() self.copyfile(f, self.wfile) f.close()
python
def page_response(self, title='', body=''): """ Helper to render an html page with dynamic content """ f = StringIO() f.write('<!DOCTYPE html>\n') f.write('<html>\n') f.write('<head><title>{}</title><head>\n'.format(title)) f.write('<body>\n<h2>{}</h2>\n'.format(title)) f.write('<div class="content">{}</div>\n'.format(body)) f.write('</body>\n</html>\n') length = f.tell() f.seek(0) self.send_response(200) encoding = sys.getfilesystemencoding() self.send_header("Content-type", "text/html; charset=%s" % encoding) self.send_header("Content-Length", str(length)) self.end_headers() self.copyfile(f, self.wfile) f.close()
[ "def", "page_response", "(", "self", ",", "title", "=", "''", ",", "body", "=", "''", ")", ":", "f", "=", "StringIO", "(", ")", "f", ".", "write", "(", "'<!DOCTYPE html>\\n'", ")", "f", ".", "write", "(", "'<html>\\n'", ")", "f", ".", "write", "(", "'<head><title>{}</title><head>\\n'", ".", "format", "(", "title", ")", ")", "f", ".", "write", "(", "'<body>\\n<h2>{}</h2>\\n'", ".", "format", "(", "title", ")", ")", "f", ".", "write", "(", "'<div class=\"content\">{}</div>\\n'", ".", "format", "(", "body", ")", ")", "f", ".", "write", "(", "'</body>\\n</html>\\n'", ")", "length", "=", "f", ".", "tell", "(", ")", "f", ".", "seek", "(", "0", ")", "self", ".", "send_response", "(", "200", ")", "encoding", "=", "sys", ".", "getfilesystemencoding", "(", ")", "self", ".", "send_header", "(", "\"Content-type\"", ",", "\"text/html; charset=%s\"", "%", "encoding", ")", "self", ".", "send_header", "(", "\"Content-Length\"", ",", "str", "(", "length", ")", ")", "self", ".", "end_headers", "(", ")", "self", ".", "copyfile", "(", "f", ",", "self", ".", "wfile", ")", "f", ".", "close", "(", ")" ]
Helper to render an html page with dynamic content
[ "Helper", "to", "render", "an", "html", "page", "with", "dynamic", "content" ]
5566f17fa06ed1f2fb9426c112951a72276b0f9a
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/examples/partner_oauth_flow/runserver.py#L22-L41
237,253
freakboy3742/pyxero
examples/partner_oauth_flow/runserver.py
PartnerCredentialsHandler.redirect_response
def redirect_response(self, url, permanent=False): """ Generate redirect response """ if permanent: self.send_response(301) else: self.send_response(302) self.send_header("Location", url) self.end_headers()
python
def redirect_response(self, url, permanent=False): """ Generate redirect response """ if permanent: self.send_response(301) else: self.send_response(302) self.send_header("Location", url) self.end_headers()
[ "def", "redirect_response", "(", "self", ",", "url", ",", "permanent", "=", "False", ")", ":", "if", "permanent", ":", "self", ".", "send_response", "(", "301", ")", "else", ":", "self", ".", "send_response", "(", "302", ")", "self", ".", "send_header", "(", "\"Location\"", ",", "url", ")", "self", ".", "end_headers", "(", ")" ]
Generate redirect response
[ "Generate", "redirect", "response" ]
5566f17fa06ed1f2fb9426c112951a72276b0f9a
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/examples/partner_oauth_flow/runserver.py#L43-L52
237,254
freakboy3742/pyxero
xero/auth.py
PublicCredentials._init_credentials
def _init_credentials(self, oauth_token, oauth_token_secret): "Depending on the state passed in, get self._oauth up and running" if oauth_token and oauth_token_secret: if self.verified: # If provided, this is a fully verified set of # credentials. Store the oauth_token and secret # and initialize OAuth around those self._init_oauth(oauth_token, oauth_token_secret) else: # If provided, we are reconstructing an initalized # (but non-verified) set of public credentials. self.oauth_token = oauth_token self.oauth_token_secret = oauth_token_secret else: # This is a brand new set of credentials - we need to generate # an oauth token so it's available for the url property. oauth = OAuth1( self.consumer_key, client_secret=self.consumer_secret, callback_uri=self.callback_uri, rsa_key=self.rsa_key, signature_method=self._signature_method ) url = self.base_url + REQUEST_TOKEN_URL headers = {'User-Agent': self.user_agent} response = requests.post(url=url, headers=headers, auth=oauth) self._process_oauth_response(response)
python
def _init_credentials(self, oauth_token, oauth_token_secret): "Depending on the state passed in, get self._oauth up and running" if oauth_token and oauth_token_secret: if self.verified: # If provided, this is a fully verified set of # credentials. Store the oauth_token and secret # and initialize OAuth around those self._init_oauth(oauth_token, oauth_token_secret) else: # If provided, we are reconstructing an initalized # (but non-verified) set of public credentials. self.oauth_token = oauth_token self.oauth_token_secret = oauth_token_secret else: # This is a brand new set of credentials - we need to generate # an oauth token so it's available for the url property. oauth = OAuth1( self.consumer_key, client_secret=self.consumer_secret, callback_uri=self.callback_uri, rsa_key=self.rsa_key, signature_method=self._signature_method ) url = self.base_url + REQUEST_TOKEN_URL headers = {'User-Agent': self.user_agent} response = requests.post(url=url, headers=headers, auth=oauth) self._process_oauth_response(response)
[ "def", "_init_credentials", "(", "self", ",", "oauth_token", ",", "oauth_token_secret", ")", ":", "if", "oauth_token", "and", "oauth_token_secret", ":", "if", "self", ".", "verified", ":", "# If provided, this is a fully verified set of", "# credentials. Store the oauth_token and secret", "# and initialize OAuth around those", "self", ".", "_init_oauth", "(", "oauth_token", ",", "oauth_token_secret", ")", "else", ":", "# If provided, we are reconstructing an initalized", "# (but non-verified) set of public credentials.", "self", ".", "oauth_token", "=", "oauth_token", "self", ".", "oauth_token_secret", "=", "oauth_token_secret", "else", ":", "# This is a brand new set of credentials - we need to generate", "# an oauth token so it's available for the url property.", "oauth", "=", "OAuth1", "(", "self", ".", "consumer_key", ",", "client_secret", "=", "self", ".", "consumer_secret", ",", "callback_uri", "=", "self", ".", "callback_uri", ",", "rsa_key", "=", "self", ".", "rsa_key", ",", "signature_method", "=", "self", ".", "_signature_method", ")", "url", "=", "self", ".", "base_url", "+", "REQUEST_TOKEN_URL", "headers", "=", "{", "'User-Agent'", ":", "self", ".", "user_agent", "}", "response", "=", "requests", ".", "post", "(", "url", "=", "url", ",", "headers", "=", "headers", ",", "auth", "=", "oauth", ")", "self", ".", "_process_oauth_response", "(", "response", ")" ]
Depending on the state passed in, get self._oauth up and running
[ "Depending", "on", "the", "state", "passed", "in", "get", "self", ".", "_oauth", "up", "and", "running" ]
5566f17fa06ed1f2fb9426c112951a72276b0f9a
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/xero/auth.py#L134-L163
237,255
freakboy3742/pyxero
xero/auth.py
PublicCredentials._init_oauth
def _init_oauth(self, oauth_token, oauth_token_secret): "Store and initialize a verified set of OAuth credentials" self.oauth_token = oauth_token self.oauth_token_secret = oauth_token_secret self._oauth = OAuth1( self.consumer_key, client_secret=self.consumer_secret, resource_owner_key=self.oauth_token, resource_owner_secret=self.oauth_token_secret, rsa_key=self.rsa_key, signature_method=self._signature_method )
python
def _init_oauth(self, oauth_token, oauth_token_secret): "Store and initialize a verified set of OAuth credentials" self.oauth_token = oauth_token self.oauth_token_secret = oauth_token_secret self._oauth = OAuth1( self.consumer_key, client_secret=self.consumer_secret, resource_owner_key=self.oauth_token, resource_owner_secret=self.oauth_token_secret, rsa_key=self.rsa_key, signature_method=self._signature_method )
[ "def", "_init_oauth", "(", "self", ",", "oauth_token", ",", "oauth_token_secret", ")", ":", "self", ".", "oauth_token", "=", "oauth_token", "self", ".", "oauth_token_secret", "=", "oauth_token_secret", "self", ".", "_oauth", "=", "OAuth1", "(", "self", ".", "consumer_key", ",", "client_secret", "=", "self", ".", "consumer_secret", ",", "resource_owner_key", "=", "self", ".", "oauth_token", ",", "resource_owner_secret", "=", "self", ".", "oauth_token_secret", ",", "rsa_key", "=", "self", ".", "rsa_key", ",", "signature_method", "=", "self", ".", "_signature_method", ")" ]
Store and initialize a verified set of OAuth credentials
[ "Store", "and", "initialize", "a", "verified", "set", "of", "OAuth", "credentials" ]
5566f17fa06ed1f2fb9426c112951a72276b0f9a
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/xero/auth.py#L165-L177
237,256
freakboy3742/pyxero
xero/auth.py
PublicCredentials._process_oauth_response
def _process_oauth_response(self, response): "Extracts the fields from an oauth response" if response.status_code == 200: credentials = parse_qs(response.text) # Initialize the oauth credentials self._init_oauth( credentials.get('oauth_token')[0], credentials.get('oauth_token_secret')[0] ) # If tokens are refreshable, we'll get a session handle self.oauth_session_handle = credentials.get( 'oauth_session_handle', [None])[0] # Calculate token/auth expiry oauth_expires_in = credentials.get( 'oauth_expires_in', [OAUTH_EXPIRY_SECONDS])[0] oauth_authorisation_expires_in = credentials.get( 'oauth_authorization_expires_in', [OAUTH_EXPIRY_SECONDS])[0] self.oauth_expires_at = datetime.datetime.now() + \ datetime.timedelta(seconds=int( oauth_expires_in)) self.oauth_authorization_expires_at = \ datetime.datetime.now() + \ datetime.timedelta(seconds=int( oauth_authorisation_expires_in)) else: self._handle_error_response(response)
python
def _process_oauth_response(self, response): "Extracts the fields from an oauth response" if response.status_code == 200: credentials = parse_qs(response.text) # Initialize the oauth credentials self._init_oauth( credentials.get('oauth_token')[0], credentials.get('oauth_token_secret')[0] ) # If tokens are refreshable, we'll get a session handle self.oauth_session_handle = credentials.get( 'oauth_session_handle', [None])[0] # Calculate token/auth expiry oauth_expires_in = credentials.get( 'oauth_expires_in', [OAUTH_EXPIRY_SECONDS])[0] oauth_authorisation_expires_in = credentials.get( 'oauth_authorization_expires_in', [OAUTH_EXPIRY_SECONDS])[0] self.oauth_expires_at = datetime.datetime.now() + \ datetime.timedelta(seconds=int( oauth_expires_in)) self.oauth_authorization_expires_at = \ datetime.datetime.now() + \ datetime.timedelta(seconds=int( oauth_authorisation_expires_in)) else: self._handle_error_response(response)
[ "def", "_process_oauth_response", "(", "self", ",", "response", ")", ":", "if", "response", ".", "status_code", "==", "200", ":", "credentials", "=", "parse_qs", "(", "response", ".", "text", ")", "# Initialize the oauth credentials", "self", ".", "_init_oauth", "(", "credentials", ".", "get", "(", "'oauth_token'", ")", "[", "0", "]", ",", "credentials", ".", "get", "(", "'oauth_token_secret'", ")", "[", "0", "]", ")", "# If tokens are refreshable, we'll get a session handle", "self", ".", "oauth_session_handle", "=", "credentials", ".", "get", "(", "'oauth_session_handle'", ",", "[", "None", "]", ")", "[", "0", "]", "# Calculate token/auth expiry", "oauth_expires_in", "=", "credentials", ".", "get", "(", "'oauth_expires_in'", ",", "[", "OAUTH_EXPIRY_SECONDS", "]", ")", "[", "0", "]", "oauth_authorisation_expires_in", "=", "credentials", ".", "get", "(", "'oauth_authorization_expires_in'", ",", "[", "OAUTH_EXPIRY_SECONDS", "]", ")", "[", "0", "]", "self", ".", "oauth_expires_at", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "+", "datetime", ".", "timedelta", "(", "seconds", "=", "int", "(", "oauth_expires_in", ")", ")", "self", ".", "oauth_authorization_expires_at", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "+", "datetime", ".", "timedelta", "(", "seconds", "=", "int", "(", "oauth_authorisation_expires_in", ")", ")", "else", ":", "self", ".", "_handle_error_response", "(", "response", ")" ]
Extracts the fields from an oauth response
[ "Extracts", "the", "fields", "from", "an", "oauth", "response" ]
5566f17fa06ed1f2fb9426c112951a72276b0f9a
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/xero/auth.py#L179-L210
237,257
freakboy3742/pyxero
xero/auth.py
PublicCredentials.state
def state(self): """Obtain the useful state of this credentials object so that we can reconstruct it independently. """ return dict( (attr, getattr(self, attr)) for attr in ( 'consumer_key', 'consumer_secret', 'callback_uri', 'verified', 'oauth_token', 'oauth_token_secret', 'oauth_session_handle', 'oauth_expires_at', 'oauth_authorization_expires_at', 'scope' ) if getattr(self, attr) is not None )
python
def state(self): """Obtain the useful state of this credentials object so that we can reconstruct it independently. """ return dict( (attr, getattr(self, attr)) for attr in ( 'consumer_key', 'consumer_secret', 'callback_uri', 'verified', 'oauth_token', 'oauth_token_secret', 'oauth_session_handle', 'oauth_expires_at', 'oauth_authorization_expires_at', 'scope' ) if getattr(self, attr) is not None )
[ "def", "state", "(", "self", ")", ":", "return", "dict", "(", "(", "attr", ",", "getattr", "(", "self", ",", "attr", ")", ")", "for", "attr", "in", "(", "'consumer_key'", ",", "'consumer_secret'", ",", "'callback_uri'", ",", "'verified'", ",", "'oauth_token'", ",", "'oauth_token_secret'", ",", "'oauth_session_handle'", ",", "'oauth_expires_at'", ",", "'oauth_authorization_expires_at'", ",", "'scope'", ")", "if", "getattr", "(", "self", ",", "attr", ")", "is", "not", "None", ")" ]
Obtain the useful state of this credentials object so that we can reconstruct it independently.
[ "Obtain", "the", "useful", "state", "of", "this", "credentials", "object", "so", "that", "we", "can", "reconstruct", "it", "independently", "." ]
5566f17fa06ed1f2fb9426c112951a72276b0f9a
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/xero/auth.py#L245-L258
237,258
freakboy3742/pyxero
xero/auth.py
PublicCredentials.verify
def verify(self, verifier): "Verify an OAuth token" # Construct the credentials for the verification request oauth = OAuth1( self.consumer_key, client_secret=self.consumer_secret, resource_owner_key=self.oauth_token, resource_owner_secret=self.oauth_token_secret, verifier=verifier, rsa_key=self.rsa_key, signature_method=self._signature_method ) # Make the verification request, gettiung back an access token url = self.base_url + ACCESS_TOKEN_URL headers = {'User-Agent': self.user_agent} response = requests.post(url=url, headers=headers, auth=oauth) self._process_oauth_response(response) self.verified = True
python
def verify(self, verifier): "Verify an OAuth token" # Construct the credentials for the verification request oauth = OAuth1( self.consumer_key, client_secret=self.consumer_secret, resource_owner_key=self.oauth_token, resource_owner_secret=self.oauth_token_secret, verifier=verifier, rsa_key=self.rsa_key, signature_method=self._signature_method ) # Make the verification request, gettiung back an access token url = self.base_url + ACCESS_TOKEN_URL headers = {'User-Agent': self.user_agent} response = requests.post(url=url, headers=headers, auth=oauth) self._process_oauth_response(response) self.verified = True
[ "def", "verify", "(", "self", ",", "verifier", ")", ":", "# Construct the credentials for the verification request", "oauth", "=", "OAuth1", "(", "self", ".", "consumer_key", ",", "client_secret", "=", "self", ".", "consumer_secret", ",", "resource_owner_key", "=", "self", ".", "oauth_token", ",", "resource_owner_secret", "=", "self", ".", "oauth_token_secret", ",", "verifier", "=", "verifier", ",", "rsa_key", "=", "self", ".", "rsa_key", ",", "signature_method", "=", "self", ".", "_signature_method", ")", "# Make the verification request, gettiung back an access token", "url", "=", "self", ".", "base_url", "+", "ACCESS_TOKEN_URL", "headers", "=", "{", "'User-Agent'", ":", "self", ".", "user_agent", "}", "response", "=", "requests", ".", "post", "(", "url", "=", "url", ",", "headers", "=", "headers", ",", "auth", "=", "oauth", ")", "self", ".", "_process_oauth_response", "(", "response", ")", "self", ".", "verified", "=", "True" ]
Verify an OAuth token
[ "Verify", "an", "OAuth", "token" ]
5566f17fa06ed1f2fb9426c112951a72276b0f9a
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/xero/auth.py#L260-L279
237,259
freakboy3742/pyxero
xero/auth.py
PublicCredentials.url
def url(self): "Returns the URL that can be visited to obtain a verifier code" # The authorize url is always api.xero.com query_string = {'oauth_token': self.oauth_token} if self.scope: query_string['scope'] = self.scope url = XERO_BASE_URL + AUTHORIZE_URL + '?' + \ urlencode(query_string) return url
python
def url(self): "Returns the URL that can be visited to obtain a verifier code" # The authorize url is always api.xero.com query_string = {'oauth_token': self.oauth_token} if self.scope: query_string['scope'] = self.scope url = XERO_BASE_URL + AUTHORIZE_URL + '?' + \ urlencode(query_string) return url
[ "def", "url", "(", "self", ")", ":", "# The authorize url is always api.xero.com", "query_string", "=", "{", "'oauth_token'", ":", "self", ".", "oauth_token", "}", "if", "self", ".", "scope", ":", "query_string", "[", "'scope'", "]", "=", "self", ".", "scope", "url", "=", "XERO_BASE_URL", "+", "AUTHORIZE_URL", "+", "'?'", "+", "urlencode", "(", "query_string", ")", "return", "url" ]
Returns the URL that can be visited to obtain a verifier code
[ "Returns", "the", "URL", "that", "can", "be", "visited", "to", "obtain", "a", "verifier", "code" ]
5566f17fa06ed1f2fb9426c112951a72276b0f9a
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/xero/auth.py#L282-L292
237,260
freakboy3742/pyxero
xero/auth.py
PartnerCredentials.refresh
def refresh(self): "Refresh an expired token" # Construct the credentials for the verification request oauth = OAuth1( self.consumer_key, client_secret=self.consumer_secret, resource_owner_key=self.oauth_token, resource_owner_secret=self.oauth_token_secret, rsa_key=self.rsa_key, signature_method=self._signature_method ) # Make the verification request, getting back an access token headers = {'User-Agent': self.user_agent} params = {'oauth_session_handle': self.oauth_session_handle} response = requests.post(url=self.base_url + ACCESS_TOKEN_URL, params=params, headers=headers, auth=oauth) self._process_oauth_response(response)
python
def refresh(self): "Refresh an expired token" # Construct the credentials for the verification request oauth = OAuth1( self.consumer_key, client_secret=self.consumer_secret, resource_owner_key=self.oauth_token, resource_owner_secret=self.oauth_token_secret, rsa_key=self.rsa_key, signature_method=self._signature_method ) # Make the verification request, getting back an access token headers = {'User-Agent': self.user_agent} params = {'oauth_session_handle': self.oauth_session_handle} response = requests.post(url=self.base_url + ACCESS_TOKEN_URL, params=params, headers=headers, auth=oauth) self._process_oauth_response(response)
[ "def", "refresh", "(", "self", ")", ":", "# Construct the credentials for the verification request", "oauth", "=", "OAuth1", "(", "self", ".", "consumer_key", ",", "client_secret", "=", "self", ".", "consumer_secret", ",", "resource_owner_key", "=", "self", ".", "oauth_token", ",", "resource_owner_secret", "=", "self", ".", "oauth_token_secret", ",", "rsa_key", "=", "self", ".", "rsa_key", ",", "signature_method", "=", "self", ".", "_signature_method", ")", "# Make the verification request, getting back an access token", "headers", "=", "{", "'User-Agent'", ":", "self", ".", "user_agent", "}", "params", "=", "{", "'oauth_session_handle'", ":", "self", ".", "oauth_session_handle", "}", "response", "=", "requests", ".", "post", "(", "url", "=", "self", ".", "base_url", "+", "ACCESS_TOKEN_URL", ",", "params", "=", "params", ",", "headers", "=", "headers", ",", "auth", "=", "oauth", ")", "self", ".", "_process_oauth_response", "(", "response", ")" ]
Refresh an expired token
[ "Refresh", "an", "expired", "token" ]
5566f17fa06ed1f2fb9426c112951a72276b0f9a
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/xero/auth.py#L375-L393
237,261
freakboy3742/pyxero
xero/filesmanager.py
FilesManager._get_files
def _get_files(self, folderId): """Retrieve the list of files contained in a folder""" uri = '/'.join([self.base_url, self.name, folderId, 'Files']) return uri, {}, 'get', None, None, False, None
python
def _get_files(self, folderId): """Retrieve the list of files contained in a folder""" uri = '/'.join([self.base_url, self.name, folderId, 'Files']) return uri, {}, 'get', None, None, False, None
[ "def", "_get_files", "(", "self", ",", "folderId", ")", ":", "uri", "=", "'/'", ".", "join", "(", "[", "self", ".", "base_url", ",", "self", ".", "name", ",", "folderId", ",", "'Files'", "]", ")", "return", "uri", ",", "{", "}", ",", "'get'", ",", "None", ",", "None", ",", "False", ",", "None" ]
Retrieve the list of files contained in a folder
[ "Retrieve", "the", "list", "of", "files", "contained", "in", "a", "folder" ]
5566f17fa06ed1f2fb9426c112951a72276b0f9a
https://github.com/freakboy3742/pyxero/blob/5566f17fa06ed1f2fb9426c112951a72276b0f9a/xero/filesmanager.py#L118-L121
237,262
dmulcahey/zha-device-handlers
zhaquirks/hivehome/__init__.py
MotionCluster.handle_cluster_request
def handle_cluster_request(self, tsn, command_id, args): """Handle the cluster command.""" if command_id == 0: if self._timer_handle: self._timer_handle.cancel() loop = asyncio.get_event_loop() self._timer_handle = loop.call_later(30, self._turn_off)
python
def handle_cluster_request(self, tsn, command_id, args): """Handle the cluster command.""" if command_id == 0: if self._timer_handle: self._timer_handle.cancel() loop = asyncio.get_event_loop() self._timer_handle = loop.call_later(30, self._turn_off)
[ "def", "handle_cluster_request", "(", "self", ",", "tsn", ",", "command_id", ",", "args", ")", ":", "if", "command_id", "==", "0", ":", "if", "self", ".", "_timer_handle", ":", "self", ".", "_timer_handle", ".", "cancel", "(", ")", "loop", "=", "asyncio", ".", "get_event_loop", "(", ")", "self", ".", "_timer_handle", "=", "loop", ".", "call_later", "(", "30", ",", "self", ".", "_turn_off", ")" ]
Handle the cluster command.
[ "Handle", "the", "cluster", "command", "." ]
bab2a53724c6fb5caee2e796dd46ebcb45400f93
https://github.com/dmulcahey/zha-device-handlers/blob/bab2a53724c6fb5caee2e796dd46ebcb45400f93/zhaquirks/hivehome/__init__.py#L21-L27
237,263
dmulcahey/zha-device-handlers
zhaquirks/xiaomi/__init__.py
BasicCluster._parse_attributes
def _parse_attributes(self, value): """Parse non standard atrributes.""" from zigpy.zcl import foundation as f attributes = {} attribute_names = { 1: BATTERY_VOLTAGE_MV, 3: TEMPERATURE, 4: XIAOMI_ATTR_4, 5: XIAOMI_ATTR_5, 6: XIAOMI_ATTR_6, 10: PATH } result = {} while value: skey = int(value[0]) svalue, value = f.TypeValue.deserialize(value[1:]) result[skey] = svalue.value for item, value in result.items(): key = attribute_names[item] \ if item in attribute_names else "0xff01-" + str(item) attributes[key] = value if BATTERY_VOLTAGE_MV in attributes: attributes[BATTERY_LEVEL] = int( self._calculate_remaining_battery_percentage( attributes[BATTERY_VOLTAGE_MV] ) ) return attributes
python
def _parse_attributes(self, value): """Parse non standard atrributes.""" from zigpy.zcl import foundation as f attributes = {} attribute_names = { 1: BATTERY_VOLTAGE_MV, 3: TEMPERATURE, 4: XIAOMI_ATTR_4, 5: XIAOMI_ATTR_5, 6: XIAOMI_ATTR_6, 10: PATH } result = {} while value: skey = int(value[0]) svalue, value = f.TypeValue.deserialize(value[1:]) result[skey] = svalue.value for item, value in result.items(): key = attribute_names[item] \ if item in attribute_names else "0xff01-" + str(item) attributes[key] = value if BATTERY_VOLTAGE_MV in attributes: attributes[BATTERY_LEVEL] = int( self._calculate_remaining_battery_percentage( attributes[BATTERY_VOLTAGE_MV] ) ) return attributes
[ "def", "_parse_attributes", "(", "self", ",", "value", ")", ":", "from", "zigpy", ".", "zcl", "import", "foundation", "as", "f", "attributes", "=", "{", "}", "attribute_names", "=", "{", "1", ":", "BATTERY_VOLTAGE_MV", ",", "3", ":", "TEMPERATURE", ",", "4", ":", "XIAOMI_ATTR_4", ",", "5", ":", "XIAOMI_ATTR_5", ",", "6", ":", "XIAOMI_ATTR_6", ",", "10", ":", "PATH", "}", "result", "=", "{", "}", "while", "value", ":", "skey", "=", "int", "(", "value", "[", "0", "]", ")", "svalue", ",", "value", "=", "f", ".", "TypeValue", ".", "deserialize", "(", "value", "[", "1", ":", "]", ")", "result", "[", "skey", "]", "=", "svalue", ".", "value", "for", "item", ",", "value", "in", "result", ".", "items", "(", ")", ":", "key", "=", "attribute_names", "[", "item", "]", "if", "item", "in", "attribute_names", "else", "\"0xff01-\"", "+", "str", "(", "item", ")", "attributes", "[", "key", "]", "=", "value", "if", "BATTERY_VOLTAGE_MV", "in", "attributes", ":", "attributes", "[", "BATTERY_LEVEL", "]", "=", "int", "(", "self", ".", "_calculate_remaining_battery_percentage", "(", "attributes", "[", "BATTERY_VOLTAGE_MV", "]", ")", ")", "return", "attributes" ]
Parse non standard atrributes.
[ "Parse", "non", "standard", "atrributes", "." ]
bab2a53724c6fb5caee2e796dd46ebcb45400f93
https://github.com/dmulcahey/zha-device-handlers/blob/bab2a53724c6fb5caee2e796dd46ebcb45400f93/zhaquirks/xiaomi/__init__.py#L64-L91
237,264
dmulcahey/zha-device-handlers
zhaquirks/xiaomi/__init__.py
BasicCluster._calculate_remaining_battery_percentage
def _calculate_remaining_battery_percentage(self, voltage): """Calculate percentage.""" min_voltage = 2500 max_voltage = 3000 percent = (voltage - min_voltage) / (max_voltage - min_voltage) * 200 return min(200, percent)
python
def _calculate_remaining_battery_percentage(self, voltage): """Calculate percentage.""" min_voltage = 2500 max_voltage = 3000 percent = (voltage - min_voltage) / (max_voltage - min_voltage) * 200 return min(200, percent)
[ "def", "_calculate_remaining_battery_percentage", "(", "self", ",", "voltage", ")", ":", "min_voltage", "=", "2500", "max_voltage", "=", "3000", "percent", "=", "(", "voltage", "-", "min_voltage", ")", "/", "(", "max_voltage", "-", "min_voltage", ")", "*", "200", "return", "min", "(", "200", ",", "percent", ")" ]
Calculate percentage.
[ "Calculate", "percentage", "." ]
bab2a53724c6fb5caee2e796dd46ebcb45400f93
https://github.com/dmulcahey/zha-device-handlers/blob/bab2a53724c6fb5caee2e796dd46ebcb45400f93/zhaquirks/xiaomi/__init__.py#L93-L98
237,265
dmulcahey/zha-device-handlers
zhaquirks/xiaomi/__init__.py
PowerConfigurationCluster.battery_reported
def battery_reported(self, voltage, rawVoltage): """Battery reported.""" self._update_attribute(BATTERY_PERCENTAGE_REMAINING, voltage) self._update_attribute(self.BATTERY_VOLTAGE_ATTR, int(rawVoltage / 100))
python
def battery_reported(self, voltage, rawVoltage): """Battery reported.""" self._update_attribute(BATTERY_PERCENTAGE_REMAINING, voltage) self._update_attribute(self.BATTERY_VOLTAGE_ATTR, int(rawVoltage / 100))
[ "def", "battery_reported", "(", "self", ",", "voltage", ",", "rawVoltage", ")", ":", "self", ".", "_update_attribute", "(", "BATTERY_PERCENTAGE_REMAINING", ",", "voltage", ")", "self", ".", "_update_attribute", "(", "self", ".", "BATTERY_VOLTAGE_ATTR", ",", "int", "(", "rawVoltage", "/", "100", ")", ")" ]
Battery reported.
[ "Battery", "reported", "." ]
bab2a53724c6fb5caee2e796dd46ebcb45400f93
https://github.com/dmulcahey/zha-device-handlers/blob/bab2a53724c6fb5caee2e796dd46ebcb45400f93/zhaquirks/xiaomi/__init__.py#L122-L126
237,266
dmulcahey/zha-device-handlers
zhaquirks/smartthings/tag_v4.py
FastPollingPowerConfigurationCluster.configure_reporting
async def configure_reporting(self, attribute, min_interval, max_interval, reportable_change): """Configure reporting.""" result = await super().configure_reporting( PowerConfigurationCluster.BATTERY_VOLTAGE_ATTR, self.FREQUENCY, self.FREQUENCY, self.MINIMUM_CHANGE ) return result
python
async def configure_reporting(self, attribute, min_interval, max_interval, reportable_change): """Configure reporting.""" result = await super().configure_reporting( PowerConfigurationCluster.BATTERY_VOLTAGE_ATTR, self.FREQUENCY, self.FREQUENCY, self.MINIMUM_CHANGE ) return result
[ "async", "def", "configure_reporting", "(", "self", ",", "attribute", ",", "min_interval", ",", "max_interval", ",", "reportable_change", ")", ":", "result", "=", "await", "super", "(", ")", ".", "configure_reporting", "(", "PowerConfigurationCluster", ".", "BATTERY_VOLTAGE_ATTR", ",", "self", ".", "FREQUENCY", ",", "self", ".", "FREQUENCY", ",", "self", ".", "MINIMUM_CHANGE", ")", "return", "result" ]
Configure reporting.
[ "Configure", "reporting", "." ]
bab2a53724c6fb5caee2e796dd46ebcb45400f93
https://github.com/dmulcahey/zha-device-handlers/blob/bab2a53724c6fb5caee2e796dd46ebcb45400f93/zhaquirks/smartthings/tag_v4.py#L23-L32
237,267
F5Networks/f5-common-python
f5/bigip/tm/sys/folder.py
Folder.update
def update(self, **kwargs): '''Update the object, removing device group if inherited If inheritedDevicegroup is the string "true" we need to remove deviceGroup from the args before we update or we get the following error: The floating traffic-group: /Common/traffic-group-1 can only be set on /testfolder if its device-group is inherited from the root folder ''' inherit_device_group = self.__dict__.get('inheritedDevicegroup', False) if inherit_device_group == 'true': self.__dict__.pop('deviceGroup') return self._update(**kwargs)
python
def update(self, **kwargs): '''Update the object, removing device group if inherited If inheritedDevicegroup is the string "true" we need to remove deviceGroup from the args before we update or we get the following error: The floating traffic-group: /Common/traffic-group-1 can only be set on /testfolder if its device-group is inherited from the root folder ''' inherit_device_group = self.__dict__.get('inheritedDevicegroup', False) if inherit_device_group == 'true': self.__dict__.pop('deviceGroup') return self._update(**kwargs)
[ "def", "update", "(", "self", ",", "*", "*", "kwargs", ")", ":", "inherit_device_group", "=", "self", ".", "__dict__", ".", "get", "(", "'inheritedDevicegroup'", ",", "False", ")", "if", "inherit_device_group", "==", "'true'", ":", "self", ".", "__dict__", ".", "pop", "(", "'deviceGroup'", ")", "return", "self", ".", "_update", "(", "*", "*", "kwargs", ")" ]
Update the object, removing device group if inherited If inheritedDevicegroup is the string "true" we need to remove deviceGroup from the args before we update or we get the following error: The floating traffic-group: /Common/traffic-group-1 can only be set on /testfolder if its device-group is inherited from the root folder
[ "Update", "the", "object", "removing", "device", "group", "if", "inherited" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/sys/folder.py#L90-L103
237,268
F5Networks/f5-common-python
f5/bigip/tm/cm/device_group.py
Device_Group.sync_to
def sync_to(self): """Wrapper method that synchronizes configuration to DG. Executes the containing object's cm :meth:`~f5.bigip.cm.Cm.exec_cmd` method to sync the configuration TO the device-group. :note:: Both sync_to, and sync_from methods are convenience methods which usually are not what this SDK offers. It is best to execute config-sync with the use of exec_cmd() method on the cm endpoint. """ device_group_collection = self._meta_data['container'] cm = device_group_collection._meta_data['container'] sync_cmd = 'config-sync to-group %s' % self.name cm.exec_cmd('run', utilCmdArgs=sync_cmd)
python
def sync_to(self): """Wrapper method that synchronizes configuration to DG. Executes the containing object's cm :meth:`~f5.bigip.cm.Cm.exec_cmd` method to sync the configuration TO the device-group. :note:: Both sync_to, and sync_from methods are convenience methods which usually are not what this SDK offers. It is best to execute config-sync with the use of exec_cmd() method on the cm endpoint. """ device_group_collection = self._meta_data['container'] cm = device_group_collection._meta_data['container'] sync_cmd = 'config-sync to-group %s' % self.name cm.exec_cmd('run', utilCmdArgs=sync_cmd)
[ "def", "sync_to", "(", "self", ")", ":", "device_group_collection", "=", "self", ".", "_meta_data", "[", "'container'", "]", "cm", "=", "device_group_collection", ".", "_meta_data", "[", "'container'", "]", "sync_cmd", "=", "'config-sync to-group %s'", "%", "self", ".", "name", "cm", ".", "exec_cmd", "(", "'run'", ",", "utilCmdArgs", "=", "sync_cmd", ")" ]
Wrapper method that synchronizes configuration to DG. Executes the containing object's cm :meth:`~f5.bigip.cm.Cm.exec_cmd` method to sync the configuration TO the device-group. :note:: Both sync_to, and sync_from methods are convenience methods which usually are not what this SDK offers. It is best to execute config-sync with the use of exec_cmd() method on the cm endpoint.
[ "Wrapper", "method", "that", "synchronizes", "configuration", "to", "DG", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/cm/device_group.py#L62-L77
237,269
F5Networks/f5-common-python
f5/bigip/tm/sys/application.py
Service._create
def _create(self, **kwargs): '''Create service on device and create accompanying Python object. :params kwargs: keyword arguments passed in from create call :raises: HTTPError :returns: Python Service object ''' try: return super(Service, self)._create(**kwargs) except HTTPError as ex: if "The configuration was updated successfully but could not be " \ "retrieved" not in ex.response.text: raise # BIG-IP® will create in Common partition if none is given. # In order to create the uri properly in this class's load, # drop in Common as the partition in kwargs. if 'partition' not in kwargs: kwargs['partition'] = 'Common' # Pop all but the necessary load kwargs from the kwargs given to # create. Otherwise, load may fail. kwargs_copy = kwargs.copy() for key in kwargs_copy: if key not in self._meta_data['required_load_parameters']: kwargs.pop(key) # If response was created successfully, do a local_update. # If not, call to overridden _load method via load return self.load(**kwargs)
python
def _create(self, **kwargs): '''Create service on device and create accompanying Python object. :params kwargs: keyword arguments passed in from create call :raises: HTTPError :returns: Python Service object ''' try: return super(Service, self)._create(**kwargs) except HTTPError as ex: if "The configuration was updated successfully but could not be " \ "retrieved" not in ex.response.text: raise # BIG-IP® will create in Common partition if none is given. # In order to create the uri properly in this class's load, # drop in Common as the partition in kwargs. if 'partition' not in kwargs: kwargs['partition'] = 'Common' # Pop all but the necessary load kwargs from the kwargs given to # create. Otherwise, load may fail. kwargs_copy = kwargs.copy() for key in kwargs_copy: if key not in self._meta_data['required_load_parameters']: kwargs.pop(key) # If response was created successfully, do a local_update. # If not, call to overridden _load method via load return self.load(**kwargs)
[ "def", "_create", "(", "self", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "super", "(", "Service", ",", "self", ")", ".", "_create", "(", "*", "*", "kwargs", ")", "except", "HTTPError", "as", "ex", ":", "if", "\"The configuration was updated successfully but could not be \"", "\"retrieved\"", "not", "in", "ex", ".", "response", ".", "text", ":", "raise", "# BIG-IP® will create in Common partition if none is given.", "# In order to create the uri properly in this class's load,", "# drop in Common as the partition in kwargs.", "if", "'partition'", "not", "in", "kwargs", ":", "kwargs", "[", "'partition'", "]", "=", "'Common'", "# Pop all but the necessary load kwargs from the kwargs given to", "# create. Otherwise, load may fail.", "kwargs_copy", "=", "kwargs", ".", "copy", "(", ")", "for", "key", "in", "kwargs_copy", ":", "if", "key", "not", "in", "self", ".", "_meta_data", "[", "'required_load_parameters'", "]", ":", "kwargs", ".", "pop", "(", "key", ")", "# If response was created successfully, do a local_update.", "# If not, call to overridden _load method via load", "return", "self", ".", "load", "(", "*", "*", "kwargs", ")" ]
Create service on device and create accompanying Python object. :params kwargs: keyword arguments passed in from create call :raises: HTTPError :returns: Python Service object
[ "Create", "service", "on", "device", "and", "create", "accompanying", "Python", "object", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/sys/application.py#L105-L133
237,270
F5Networks/f5-common-python
f5/bigip/tm/sys/application.py
Service._build_service_uri
def _build_service_uri(self, base_uri, partition, name): '''Build the proper uri for a service resource. This follows the scheme: <base_uri>/~<partition>~<<name>.app>~<name> :param base_uri: str -- base uri for container :param partition: str -- partition for this service :param name: str -- name of the service :returns: str -- uri to access this service ''' name = name.replace('/', '~') return '%s~%s~%s.app~%s' % (base_uri, partition, name, name)
python
def _build_service_uri(self, base_uri, partition, name): '''Build the proper uri for a service resource. This follows the scheme: <base_uri>/~<partition>~<<name>.app>~<name> :param base_uri: str -- base uri for container :param partition: str -- partition for this service :param name: str -- name of the service :returns: str -- uri to access this service ''' name = name.replace('/', '~') return '%s~%s~%s.app~%s' % (base_uri, partition, name, name)
[ "def", "_build_service_uri", "(", "self", ",", "base_uri", ",", "partition", ",", "name", ")", ":", "name", "=", "name", ".", "replace", "(", "'/'", ",", "'~'", ")", "return", "'%s~%s~%s.app~%s'", "%", "(", "base_uri", ",", "partition", ",", "name", ",", "name", ")" ]
Build the proper uri for a service resource. This follows the scheme: <base_uri>/~<partition>~<<name>.app>~<name> :param base_uri: str -- base uri for container :param partition: str -- partition for this service :param name: str -- name of the service :returns: str -- uri to access this service
[ "Build", "the", "proper", "uri", "for", "a", "service", "resource", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/sys/application.py#L168-L180
237,271
F5Networks/f5-common-python
f5/bigiq/cm/device/licensing/pool/utility.py
Members.delete
def delete(self, **kwargs): """Deletes a member from a license pool You need to be careful with this method. When you use it, and it succeeds on the remote BIG-IP, the configuration of the BIG-IP will be reloaded. During this process, you will not be able to access the REST interface. This method overrides the Resource class's method because it requires that extra json kwargs be supplied. This is not a behavior that is part of the normal Resource class's delete method. :param kwargs: :return: """ if 'id' not in kwargs: # BIG-IQ requires that you provide the ID of the members to revoke # a license from. This ID is already part of the deletion URL though. # Therefore, if you do not provide it, we enumerate it for you. delete_uri = self._meta_data['uri'] if delete_uri.endswith('/'): delete_uri = delete_uri[0:-1] kwargs['id'] = os.path.basename(delete_uri) uid = uuid.UUID(kwargs['id'], version=4) if uid.hex != kwargs['id'].replace('-', ''): raise F5SDKError( "The specified ID is invalid" ) requests_params = self._handle_requests_params(kwargs) kwargs = self._check_for_python_keywords(kwargs) kwargs = self._prepare_request_json(kwargs) delete_uri = self._meta_data['uri'] session = self._meta_data['bigip']._meta_data['icr_session'] # Check the generation for match before delete force = self._check_force_arg(kwargs.pop('force', True)) if not force: self._check_generation() response = session.delete(delete_uri, json=kwargs, **requests_params) if response.status_code == 200: self.__dict__ = {'deleted': True} # This sleep is necessary to prevent BIG-IQ from being able to remove # a license. It happens in certain cases that assignments can be revoked # (and license deletion started) too quickly. Therefore, we must introduce # an artificial delay here to prevent revoking from returning before # BIG-IQ would be ready to remove the license. time.sleep(1)
python
def delete(self, **kwargs): """Deletes a member from a license pool You need to be careful with this method. When you use it, and it succeeds on the remote BIG-IP, the configuration of the BIG-IP will be reloaded. During this process, you will not be able to access the REST interface. This method overrides the Resource class's method because it requires that extra json kwargs be supplied. This is not a behavior that is part of the normal Resource class's delete method. :param kwargs: :return: """ if 'id' not in kwargs: # BIG-IQ requires that you provide the ID of the members to revoke # a license from. This ID is already part of the deletion URL though. # Therefore, if you do not provide it, we enumerate it for you. delete_uri = self._meta_data['uri'] if delete_uri.endswith('/'): delete_uri = delete_uri[0:-1] kwargs['id'] = os.path.basename(delete_uri) uid = uuid.UUID(kwargs['id'], version=4) if uid.hex != kwargs['id'].replace('-', ''): raise F5SDKError( "The specified ID is invalid" ) requests_params = self._handle_requests_params(kwargs) kwargs = self._check_for_python_keywords(kwargs) kwargs = self._prepare_request_json(kwargs) delete_uri = self._meta_data['uri'] session = self._meta_data['bigip']._meta_data['icr_session'] # Check the generation for match before delete force = self._check_force_arg(kwargs.pop('force', True)) if not force: self._check_generation() response = session.delete(delete_uri, json=kwargs, **requests_params) if response.status_code == 200: self.__dict__ = {'deleted': True} # This sleep is necessary to prevent BIG-IQ from being able to remove # a license. It happens in certain cases that assignments can be revoked # (and license deletion started) too quickly. Therefore, we must introduce # an artificial delay here to prevent revoking from returning before # BIG-IQ would be ready to remove the license. time.sleep(1)
[ "def", "delete", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "'id'", "not", "in", "kwargs", ":", "# BIG-IQ requires that you provide the ID of the members to revoke", "# a license from. This ID is already part of the deletion URL though.", "# Therefore, if you do not provide it, we enumerate it for you.", "delete_uri", "=", "self", ".", "_meta_data", "[", "'uri'", "]", "if", "delete_uri", ".", "endswith", "(", "'/'", ")", ":", "delete_uri", "=", "delete_uri", "[", "0", ":", "-", "1", "]", "kwargs", "[", "'id'", "]", "=", "os", ".", "path", ".", "basename", "(", "delete_uri", ")", "uid", "=", "uuid", ".", "UUID", "(", "kwargs", "[", "'id'", "]", ",", "version", "=", "4", ")", "if", "uid", ".", "hex", "!=", "kwargs", "[", "'id'", "]", ".", "replace", "(", "'-'", ",", "''", ")", ":", "raise", "F5SDKError", "(", "\"The specified ID is invalid\"", ")", "requests_params", "=", "self", ".", "_handle_requests_params", "(", "kwargs", ")", "kwargs", "=", "self", ".", "_check_for_python_keywords", "(", "kwargs", ")", "kwargs", "=", "self", ".", "_prepare_request_json", "(", "kwargs", ")", "delete_uri", "=", "self", ".", "_meta_data", "[", "'uri'", "]", "session", "=", "self", ".", "_meta_data", "[", "'bigip'", "]", ".", "_meta_data", "[", "'icr_session'", "]", "# Check the generation for match before delete", "force", "=", "self", ".", "_check_force_arg", "(", "kwargs", ".", "pop", "(", "'force'", ",", "True", ")", ")", "if", "not", "force", ":", "self", ".", "_check_generation", "(", ")", "response", "=", "session", ".", "delete", "(", "delete_uri", ",", "json", "=", "kwargs", ",", "*", "*", "requests_params", ")", "if", "response", ".", "status_code", "==", "200", ":", "self", ".", "__dict__", "=", "{", "'deleted'", ":", "True", "}", "# This sleep is necessary to prevent BIG-IQ from being able to remove", "# a license. It happens in certain cases that assignments can be revoked", "# (and license deletion started) too quickly. Therefore, we must introduce", "# an artificial delay here to prevent revoking from returning before", "# BIG-IQ would be ready to remove the license.", "time", ".", "sleep", "(", "1", ")" ]
Deletes a member from a license pool You need to be careful with this method. When you use it, and it succeeds on the remote BIG-IP, the configuration of the BIG-IP will be reloaded. During this process, you will not be able to access the REST interface. This method overrides the Resource class's method because it requires that extra json kwargs be supplied. This is not a behavior that is part of the normal Resource class's delete method. :param kwargs: :return:
[ "Deletes", "a", "member", "from", "a", "license", "pool" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigiq/cm/device/licensing/pool/utility.py#L137-L187
237,272
F5Networks/f5-common-python
f5/multi_device/trust_domain.py
TrustDomain._set_attributes
def _set_attributes(self, **kwargs): '''Set attributes for instance in one place :param kwargs: dict -- dictionary of keyword arguments ''' self.devices = kwargs['devices'][:] self.partition = kwargs['partition'] self.device_group_name = 'device_trust_group' self.device_group_type = 'sync-only'
python
def _set_attributes(self, **kwargs): '''Set attributes for instance in one place :param kwargs: dict -- dictionary of keyword arguments ''' self.devices = kwargs['devices'][:] self.partition = kwargs['partition'] self.device_group_name = 'device_trust_group' self.device_group_type = 'sync-only'
[ "def", "_set_attributes", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "devices", "=", "kwargs", "[", "'devices'", "]", "[", ":", "]", "self", ".", "partition", "=", "kwargs", "[", "'partition'", "]", "self", ".", "device_group_name", "=", "'device_trust_group'", "self", ".", "device_group_type", "=", "'sync-only'" ]
Set attributes for instance in one place :param kwargs: dict -- dictionary of keyword arguments
[ "Set", "attributes", "for", "instance", "in", "one", "place" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/multi_device/trust_domain.py#L76-L85
237,273
F5Networks/f5-common-python
f5/multi_device/trust_domain.py
TrustDomain.validate
def validate(self): '''Validate that devices are each trusted by one another :param kwargs: dict -- keyword args for devices and partition :raises: DeviceNotTrusted ''' self._populate_domain() missing = [] for domain_device in self.domain: for truster, trustees in iteritems(self.domain): if domain_device not in trustees: missing.append((domain_device, truster, trustees)) if missing: msg = '' for item in missing: msg += '\n%r is not trusted by %r, which trusts: %r' % \ (item[0], item[1], item[2]) raise DeviceNotTrusted(msg) self.device_group = DeviceGroup( devices=self.devices, device_group_name=self.device_group_name, device_group_type=self.device_group_type, device_group_partition=self.partition )
python
def validate(self): '''Validate that devices are each trusted by one another :param kwargs: dict -- keyword args for devices and partition :raises: DeviceNotTrusted ''' self._populate_domain() missing = [] for domain_device in self.domain: for truster, trustees in iteritems(self.domain): if domain_device not in trustees: missing.append((domain_device, truster, trustees)) if missing: msg = '' for item in missing: msg += '\n%r is not trusted by %r, which trusts: %r' % \ (item[0], item[1], item[2]) raise DeviceNotTrusted(msg) self.device_group = DeviceGroup( devices=self.devices, device_group_name=self.device_group_name, device_group_type=self.device_group_type, device_group_partition=self.partition )
[ "def", "validate", "(", "self", ")", ":", "self", ".", "_populate_domain", "(", ")", "missing", "=", "[", "]", "for", "domain_device", "in", "self", ".", "domain", ":", "for", "truster", ",", "trustees", "in", "iteritems", "(", "self", ".", "domain", ")", ":", "if", "domain_device", "not", "in", "trustees", ":", "missing", ".", "append", "(", "(", "domain_device", ",", "truster", ",", "trustees", ")", ")", "if", "missing", ":", "msg", "=", "''", "for", "item", "in", "missing", ":", "msg", "+=", "'\\n%r is not trusted by %r, which trusts: %r'", "%", "(", "item", "[", "0", "]", ",", "item", "[", "1", "]", ",", "item", "[", "2", "]", ")", "raise", "DeviceNotTrusted", "(", "msg", ")", "self", ".", "device_group", "=", "DeviceGroup", "(", "devices", "=", "self", ".", "devices", ",", "device_group_name", "=", "self", ".", "device_group_name", ",", "device_group_type", "=", "self", ".", "device_group_type", ",", "device_group_partition", "=", "self", ".", "partition", ")" ]
Validate that devices are each trusted by one another :param kwargs: dict -- keyword args for devices and partition :raises: DeviceNotTrusted
[ "Validate", "that", "devices", "are", "each", "trusted", "by", "one", "another" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/multi_device/trust_domain.py#L87-L112
237,274
F5Networks/f5-common-python
f5/multi_device/trust_domain.py
TrustDomain._populate_domain
def _populate_domain(self): '''Populate TrustDomain's domain attribute. This entails an inspection of each device's certificate-authority devices in its trust domain and recording them. After which, we get a dictionary of who trusts who in the domain. ''' self.domain = {} for device in self.devices: device_name = get_device_info(device).name ca_devices = \ device.tm.cm.trust_domains.trust_domain.load( name='Root' ).caDevices self.domain[device_name] = [ d.replace('/%s/' % self.partition, '') for d in ca_devices ]
python
def _populate_domain(self): '''Populate TrustDomain's domain attribute. This entails an inspection of each device's certificate-authority devices in its trust domain and recording them. After which, we get a dictionary of who trusts who in the domain. ''' self.domain = {} for device in self.devices: device_name = get_device_info(device).name ca_devices = \ device.tm.cm.trust_domains.trust_domain.load( name='Root' ).caDevices self.domain[device_name] = [ d.replace('/%s/' % self.partition, '') for d in ca_devices ]
[ "def", "_populate_domain", "(", "self", ")", ":", "self", ".", "domain", "=", "{", "}", "for", "device", "in", "self", ".", "devices", ":", "device_name", "=", "get_device_info", "(", "device", ")", ".", "name", "ca_devices", "=", "device", ".", "tm", ".", "cm", ".", "trust_domains", ".", "trust_domain", ".", "load", "(", "name", "=", "'Root'", ")", ".", "caDevices", "self", ".", "domain", "[", "device_name", "]", "=", "[", "d", ".", "replace", "(", "'/%s/'", "%", "self", ".", "partition", ",", "''", ")", "for", "d", "in", "ca_devices", "]" ]
Populate TrustDomain's domain attribute. This entails an inspection of each device's certificate-authority devices in its trust domain and recording them. After which, we get a dictionary of who trusts who in the domain.
[ "Populate", "TrustDomain", "s", "domain", "attribute", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/multi_device/trust_domain.py#L114-L131
237,275
F5Networks/f5-common-python
f5/multi_device/trust_domain.py
TrustDomain.create
def create(self, **kwargs): '''Add trusted peers to the root bigip device. When adding a trusted device to a device, the trust is reflexive. That is, the truster trusts the trustee and the trustee trusts the truster. So we only need to add the trusted devices to one device. :param kwargs: dict -- devices and partition ''' self._set_attributes(**kwargs) for device in self.devices[1:]: self._add_trustee(device) pollster(self.validate)()
python
def create(self, **kwargs): '''Add trusted peers to the root bigip device. When adding a trusted device to a device, the trust is reflexive. That is, the truster trusts the trustee and the trustee trusts the truster. So we only need to add the trusted devices to one device. :param kwargs: dict -- devices and partition ''' self._set_attributes(**kwargs) for device in self.devices[1:]: self._add_trustee(device) pollster(self.validate)()
[ "def", "create", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_set_attributes", "(", "*", "*", "kwargs", ")", "for", "device", "in", "self", ".", "devices", "[", "1", ":", "]", ":", "self", ".", "_add_trustee", "(", "device", ")", "pollster", "(", "self", ".", "validate", ")", "(", ")" ]
Add trusted peers to the root bigip device. When adding a trusted device to a device, the trust is reflexive. That is, the truster trusts the trustee and the trustee trusts the truster. So we only need to add the trusted devices to one device. :param kwargs: dict -- devices and partition
[ "Add", "trusted", "peers", "to", "the", "root", "bigip", "device", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/multi_device/trust_domain.py#L133-L146
237,276
F5Networks/f5-common-python
f5/multi_device/trust_domain.py
TrustDomain.teardown
def teardown(self): '''Teardown trust domain by removing trusted devices.''' for device in self.devices: self._remove_trustee(device) self._populate_domain() self.domain = {}
python
def teardown(self): '''Teardown trust domain by removing trusted devices.''' for device in self.devices: self._remove_trustee(device) self._populate_domain() self.domain = {}
[ "def", "teardown", "(", "self", ")", ":", "for", "device", "in", "self", ".", "devices", ":", "self", ".", "_remove_trustee", "(", "device", ")", "self", ".", "_populate_domain", "(", ")", "self", ".", "domain", "=", "{", "}" ]
Teardown trust domain by removing trusted devices.
[ "Teardown", "trust", "domain", "by", "removing", "trusted", "devices", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/multi_device/trust_domain.py#L148-L154
237,277
F5Networks/f5-common-python
f5/multi_device/trust_domain.py
TrustDomain._add_trustee
def _add_trustee(self, device): '''Add a single trusted device to the trust domain. :param device: ManagementRoot object -- device to add to trust domain ''' device_name = get_device_info(device).name if device_name in self.domain: msg = 'Device: %r is already in this trust domain.' % device_name raise DeviceAlreadyInTrustDomain(msg) self._modify_trust(self.devices[0], self._get_add_trustee_cmd, device)
python
def _add_trustee(self, device): '''Add a single trusted device to the trust domain. :param device: ManagementRoot object -- device to add to trust domain ''' device_name = get_device_info(device).name if device_name in self.domain: msg = 'Device: %r is already in this trust domain.' % device_name raise DeviceAlreadyInTrustDomain(msg) self._modify_trust(self.devices[0], self._get_add_trustee_cmd, device)
[ "def", "_add_trustee", "(", "self", ",", "device", ")", ":", "device_name", "=", "get_device_info", "(", "device", ")", ".", "name", "if", "device_name", "in", "self", ".", "domain", ":", "msg", "=", "'Device: %r is already in this trust domain.'", "%", "device_name", "raise", "DeviceAlreadyInTrustDomain", "(", "msg", ")", "self", ".", "_modify_trust", "(", "self", ".", "devices", "[", "0", "]", ",", "self", ".", "_get_add_trustee_cmd", ",", "device", ")" ]
Add a single trusted device to the trust domain. :param device: ManagementRoot object -- device to add to trust domain
[ "Add", "a", "single", "trusted", "device", "to", "the", "trust", "domain", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/multi_device/trust_domain.py#L156-L166
237,278
F5Networks/f5-common-python
f5/multi_device/trust_domain.py
TrustDomain._remove_trustee
def _remove_trustee(self, device): '''Remove a trustee from the trust domain. :param device: MangementRoot object -- device to remove ''' trustee_name = get_device_info(device).name name_object_map = get_device_names_to_objects(self.devices) delete_func = self._get_delete_trustee_cmd for truster in self.domain: if trustee_name in self.domain[truster] and \ truster != trustee_name: truster_obj = name_object_map[truster] self._modify_trust(truster_obj, delete_func, trustee_name) self._populate_domain() for trustee in self.domain[trustee_name]: if trustee_name != trustee: self._modify_trust(device, delete_func, trustee) self.devices.remove(name_object_map[trustee_name])
python
def _remove_trustee(self, device): '''Remove a trustee from the trust domain. :param device: MangementRoot object -- device to remove ''' trustee_name = get_device_info(device).name name_object_map = get_device_names_to_objects(self.devices) delete_func = self._get_delete_trustee_cmd for truster in self.domain: if trustee_name in self.domain[truster] and \ truster != trustee_name: truster_obj = name_object_map[truster] self._modify_trust(truster_obj, delete_func, trustee_name) self._populate_domain() for trustee in self.domain[trustee_name]: if trustee_name != trustee: self._modify_trust(device, delete_func, trustee) self.devices.remove(name_object_map[trustee_name])
[ "def", "_remove_trustee", "(", "self", ",", "device", ")", ":", "trustee_name", "=", "get_device_info", "(", "device", ")", ".", "name", "name_object_map", "=", "get_device_names_to_objects", "(", "self", ".", "devices", ")", "delete_func", "=", "self", ".", "_get_delete_trustee_cmd", "for", "truster", "in", "self", ".", "domain", ":", "if", "trustee_name", "in", "self", ".", "domain", "[", "truster", "]", "and", "truster", "!=", "trustee_name", ":", "truster_obj", "=", "name_object_map", "[", "truster", "]", "self", ".", "_modify_trust", "(", "truster_obj", ",", "delete_func", ",", "trustee_name", ")", "self", ".", "_populate_domain", "(", ")", "for", "trustee", "in", "self", ".", "domain", "[", "trustee_name", "]", ":", "if", "trustee_name", "!=", "trustee", ":", "self", ".", "_modify_trust", "(", "device", ",", "delete_func", ",", "trustee", ")", "self", ".", "devices", ".", "remove", "(", "name_object_map", "[", "trustee_name", "]", ")" ]
Remove a trustee from the trust domain. :param device: MangementRoot object -- device to remove
[ "Remove", "a", "trustee", "from", "the", "trust", "domain", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/multi_device/trust_domain.py#L168-L189
237,279
F5Networks/f5-common-python
f5/multi_device/trust_domain.py
TrustDomain._modify_trust
def _modify_trust(self, truster, mod_peer_func, trustee): '''Modify a trusted peer device by deploying an iapp. :param truster: ManagementRoot object -- device on which to perform commands :param mod_peer_func: function -- function to call to modify peer :param trustee: ManagementRoot object or str -- device to modify ''' iapp_name = 'trusted_device' mod_peer_cmd = mod_peer_func(trustee) iapp_actions = self.iapp_actions.copy() iapp_actions['definition']['implementation'] = mod_peer_cmd self._deploy_iapp(iapp_name, iapp_actions, truster) self._delete_iapp(iapp_name, truster)
python
def _modify_trust(self, truster, mod_peer_func, trustee): '''Modify a trusted peer device by deploying an iapp. :param truster: ManagementRoot object -- device on which to perform commands :param mod_peer_func: function -- function to call to modify peer :param trustee: ManagementRoot object or str -- device to modify ''' iapp_name = 'trusted_device' mod_peer_cmd = mod_peer_func(trustee) iapp_actions = self.iapp_actions.copy() iapp_actions['definition']['implementation'] = mod_peer_cmd self._deploy_iapp(iapp_name, iapp_actions, truster) self._delete_iapp(iapp_name, truster)
[ "def", "_modify_trust", "(", "self", ",", "truster", ",", "mod_peer_func", ",", "trustee", ")", ":", "iapp_name", "=", "'trusted_device'", "mod_peer_cmd", "=", "mod_peer_func", "(", "trustee", ")", "iapp_actions", "=", "self", ".", "iapp_actions", ".", "copy", "(", ")", "iapp_actions", "[", "'definition'", "]", "[", "'implementation'", "]", "=", "mod_peer_cmd", "self", ".", "_deploy_iapp", "(", "iapp_name", ",", "iapp_actions", ",", "truster", ")", "self", ".", "_delete_iapp", "(", "iapp_name", ",", "truster", ")" ]
Modify a trusted peer device by deploying an iapp. :param truster: ManagementRoot object -- device on which to perform commands :param mod_peer_func: function -- function to call to modify peer :param trustee: ManagementRoot object or str -- device to modify
[ "Modify", "a", "trusted", "peer", "device", "by", "deploying", "an", "iapp", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/multi_device/trust_domain.py#L191-L206
237,280
F5Networks/f5-common-python
f5/multi_device/trust_domain.py
TrustDomain._delete_iapp
def _delete_iapp(self, iapp_name, deploying_device): '''Delete an iapp service and template on the root device. :param iapp_name: str -- name of iapp :param deploying_device: ManagementRoot object -- device where the iapp will be deleted ''' iapp = deploying_device.tm.sys.application iapp_serv = iapp.services.service.load( name=iapp_name, partition=self.partition ) iapp_serv.delete() iapp_tmpl = iapp.templates.template.load( name=iapp_name, partition=self.partition ) iapp_tmpl.delete()
python
def _delete_iapp(self, iapp_name, deploying_device): '''Delete an iapp service and template on the root device. :param iapp_name: str -- name of iapp :param deploying_device: ManagementRoot object -- device where the iapp will be deleted ''' iapp = deploying_device.tm.sys.application iapp_serv = iapp.services.service.load( name=iapp_name, partition=self.partition ) iapp_serv.delete() iapp_tmpl = iapp.templates.template.load( name=iapp_name, partition=self.partition ) iapp_tmpl.delete()
[ "def", "_delete_iapp", "(", "self", ",", "iapp_name", ",", "deploying_device", ")", ":", "iapp", "=", "deploying_device", ".", "tm", ".", "sys", ".", "application", "iapp_serv", "=", "iapp", ".", "services", ".", "service", ".", "load", "(", "name", "=", "iapp_name", ",", "partition", "=", "self", ".", "partition", ")", "iapp_serv", ".", "delete", "(", ")", "iapp_tmpl", "=", "iapp", ".", "templates", ".", "template", ".", "load", "(", "name", "=", "iapp_name", ",", "partition", "=", "self", ".", "partition", ")", "iapp_tmpl", ".", "delete", "(", ")" ]
Delete an iapp service and template on the root device. :param iapp_name: str -- name of iapp :param deploying_device: ManagementRoot object -- device where the iapp will be deleted
[ "Delete", "an", "iapp", "service", "and", "template", "on", "the", "root", "device", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/multi_device/trust_domain.py#L208-L224
237,281
F5Networks/f5-common-python
f5/multi_device/trust_domain.py
TrustDomain._deploy_iapp
def _deploy_iapp(self, iapp_name, actions, deploying_device): '''Deploy iapp to add trusted device :param iapp_name: str -- name of iapp :param actions: dict -- actions definition of iapp sections :param deploying_device: ManagementRoot object -- device where the iapp will be created ''' tmpl = deploying_device.tm.sys.application.templates.template serv = deploying_device.tm.sys.application.services.service tmpl.create(name=iapp_name, partition=self.partition, actions=actions) pollster(deploying_device.tm.sys.application.templates.template.load)( name=iapp_name, partition=self.partition ) serv.create( name=iapp_name, partition=self.partition, template='/%s/%s' % (self.partition, iapp_name) )
python
def _deploy_iapp(self, iapp_name, actions, deploying_device): '''Deploy iapp to add trusted device :param iapp_name: str -- name of iapp :param actions: dict -- actions definition of iapp sections :param deploying_device: ManagementRoot object -- device where the iapp will be created ''' tmpl = deploying_device.tm.sys.application.templates.template serv = deploying_device.tm.sys.application.services.service tmpl.create(name=iapp_name, partition=self.partition, actions=actions) pollster(deploying_device.tm.sys.application.templates.template.load)( name=iapp_name, partition=self.partition ) serv.create( name=iapp_name, partition=self.partition, template='/%s/%s' % (self.partition, iapp_name) )
[ "def", "_deploy_iapp", "(", "self", ",", "iapp_name", ",", "actions", ",", "deploying_device", ")", ":", "tmpl", "=", "deploying_device", ".", "tm", ".", "sys", ".", "application", ".", "templates", ".", "template", "serv", "=", "deploying_device", ".", "tm", ".", "sys", ".", "application", ".", "services", ".", "service", "tmpl", ".", "create", "(", "name", "=", "iapp_name", ",", "partition", "=", "self", ".", "partition", ",", "actions", "=", "actions", ")", "pollster", "(", "deploying_device", ".", "tm", ".", "sys", ".", "application", ".", "templates", ".", "template", ".", "load", ")", "(", "name", "=", "iapp_name", ",", "partition", "=", "self", ".", "partition", ")", "serv", ".", "create", "(", "name", "=", "iapp_name", ",", "partition", "=", "self", ".", "partition", ",", "template", "=", "'/%s/%s'", "%", "(", "self", ".", "partition", ",", "iapp_name", ")", ")" ]
Deploy iapp to add trusted device :param iapp_name: str -- name of iapp :param actions: dict -- actions definition of iapp sections :param deploying_device: ManagementRoot object -- device where the iapp will be created
[ "Deploy", "iapp", "to", "add", "trusted", "device" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/multi_device/trust_domain.py#L226-L245
237,282
F5Networks/f5-common-python
f5/multi_device/trust_domain.py
TrustDomain._get_add_trustee_cmd
def _get_add_trustee_cmd(self, trustee): '''Get tmsh command to add a trusted device. :param trustee: ManagementRoot object -- device to add as trusted :returns: str -- tmsh command to add trustee ''' trustee_info = pollster(get_device_info)(trustee) username = trustee._meta_data['username'] password = trustee._meta_data['password'] return 'tmsh::modify cm trust-domain Root ca-devices add ' \ '\\{ %s \\} name %s username %s password %s' % \ (trustee_info.managementIp, trustee_info.name, username, password)
python
def _get_add_trustee_cmd(self, trustee): '''Get tmsh command to add a trusted device. :param trustee: ManagementRoot object -- device to add as trusted :returns: str -- tmsh command to add trustee ''' trustee_info = pollster(get_device_info)(trustee) username = trustee._meta_data['username'] password = trustee._meta_data['password'] return 'tmsh::modify cm trust-domain Root ca-devices add ' \ '\\{ %s \\} name %s username %s password %s' % \ (trustee_info.managementIp, trustee_info.name, username, password)
[ "def", "_get_add_trustee_cmd", "(", "self", ",", "trustee", ")", ":", "trustee_info", "=", "pollster", "(", "get_device_info", ")", "(", "trustee", ")", "username", "=", "trustee", ".", "_meta_data", "[", "'username'", "]", "password", "=", "trustee", ".", "_meta_data", "[", "'password'", "]", "return", "'tmsh::modify cm trust-domain Root ca-devices add '", "'\\\\{ %s \\\\} name %s username %s password %s'", "%", "(", "trustee_info", ".", "managementIp", ",", "trustee_info", ".", "name", ",", "username", ",", "password", ")" ]
Get tmsh command to add a trusted device. :param trustee: ManagementRoot object -- device to add as trusted :returns: str -- tmsh command to add trustee
[ "Get", "tmsh", "command", "to", "add", "a", "trusted", "device", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/multi_device/trust_domain.py#L247-L259
237,283
F5Networks/f5-common-python
f5/bigip/tm/vcmp/virtual_disk.py
Virtual_Disk.load
def load(self, **kwargs): """Loads a given resource Loads a given resource provided a 'name' and an optional 'slot' parameter. The 'slot' parameter is not a required load parameter because it is provided as an optional way of constructing the correct 'name' of the vCMP resource. :param kwargs: :return: """ kwargs['transform_name'] = True kwargs = self._mutate_name(kwargs) return self._load(**kwargs)
python
def load(self, **kwargs): """Loads a given resource Loads a given resource provided a 'name' and an optional 'slot' parameter. The 'slot' parameter is not a required load parameter because it is provided as an optional way of constructing the correct 'name' of the vCMP resource. :param kwargs: :return: """ kwargs['transform_name'] = True kwargs = self._mutate_name(kwargs) return self._load(**kwargs)
[ "def", "load", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'transform_name'", "]", "=", "True", "kwargs", "=", "self", ".", "_mutate_name", "(", "kwargs", ")", "return", "self", ".", "_load", "(", "*", "*", "kwargs", ")" ]
Loads a given resource Loads a given resource provided a 'name' and an optional 'slot' parameter. The 'slot' parameter is not a required load parameter because it is provided as an optional way of constructing the correct 'name' of the vCMP resource. :param kwargs: :return:
[ "Loads", "a", "given", "resource" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/vcmp/virtual_disk.py#L53-L66
237,284
F5Networks/f5-common-python
f5/utils/iapp_parser.py
IappParser._get_section_end_index
def _get_section_end_index(self, section, section_start): '''Get end of section's content. In the loop to match braces, we must not count curly braces that are within a doubly quoted string. :param section: string name of section :param section_start: integer index of section's beginning :return: integer index of section's end :raises: CurlyBraceMismatchException ''' brace_count = 0 in_quote = False in_escape = False for index, char in enumerate(self.template_str[section_start:]): # This check is to look for items inside of an escape sequence. # # For example, in the iApp team's iApps, there is a proc called # "iapp_get_items" which has a line that looks like this. # # set val [string map {\" ""} $val] # # This will cause this parser to fail because of the unbalanced # quotes. Therefore, this conditional takes this into consideration # if char == '\\' and not in_escape: in_escape = True elif char == '\\' and in_escape: in_escape = False if not in_escape: if char == '"' and not in_quote: in_quote = True elif char == '"' and in_quote: in_quote = False if char == '{' and not in_quote: brace_count += 1 elif char == '}' and not in_quote: brace_count -= 1 if brace_count is 0: return index + section_start if brace_count is not 0: raise CurlyBraceMismatchException( 'Curly braces mismatch in section %s.' % section )
python
def _get_section_end_index(self, section, section_start): '''Get end of section's content. In the loop to match braces, we must not count curly braces that are within a doubly quoted string. :param section: string name of section :param section_start: integer index of section's beginning :return: integer index of section's end :raises: CurlyBraceMismatchException ''' brace_count = 0 in_quote = False in_escape = False for index, char in enumerate(self.template_str[section_start:]): # This check is to look for items inside of an escape sequence. # # For example, in the iApp team's iApps, there is a proc called # "iapp_get_items" which has a line that looks like this. # # set val [string map {\" ""} $val] # # This will cause this parser to fail because of the unbalanced # quotes. Therefore, this conditional takes this into consideration # if char == '\\' and not in_escape: in_escape = True elif char == '\\' and in_escape: in_escape = False if not in_escape: if char == '"' and not in_quote: in_quote = True elif char == '"' and in_quote: in_quote = False if char == '{' and not in_quote: brace_count += 1 elif char == '}' and not in_quote: brace_count -= 1 if brace_count is 0: return index + section_start if brace_count is not 0: raise CurlyBraceMismatchException( 'Curly braces mismatch in section %s.' % section )
[ "def", "_get_section_end_index", "(", "self", ",", "section", ",", "section_start", ")", ":", "brace_count", "=", "0", "in_quote", "=", "False", "in_escape", "=", "False", "for", "index", ",", "char", "in", "enumerate", "(", "self", ".", "template_str", "[", "section_start", ":", "]", ")", ":", "# This check is to look for items inside of an escape sequence.", "#", "# For example, in the iApp team's iApps, there is a proc called", "# \"iapp_get_items\" which has a line that looks like this.", "#", "# set val [string map {\\\" \"\"} $val]", "#", "# This will cause this parser to fail because of the unbalanced", "# quotes. Therefore, this conditional takes this into consideration", "#", "if", "char", "==", "'\\\\'", "and", "not", "in_escape", ":", "in_escape", "=", "True", "elif", "char", "==", "'\\\\'", "and", "in_escape", ":", "in_escape", "=", "False", "if", "not", "in_escape", ":", "if", "char", "==", "'\"'", "and", "not", "in_quote", ":", "in_quote", "=", "True", "elif", "char", "==", "'\"'", "and", "in_quote", ":", "in_quote", "=", "False", "if", "char", "==", "'{'", "and", "not", "in_quote", ":", "brace_count", "+=", "1", "elif", "char", "==", "'}'", "and", "not", "in_quote", ":", "brace_count", "-=", "1", "if", "brace_count", "is", "0", ":", "return", "index", "+", "section_start", "if", "brace_count", "is", "not", "0", ":", "raise", "CurlyBraceMismatchException", "(", "'Curly braces mismatch in section %s.'", "%", "section", ")" ]
Get end of section's content. In the loop to match braces, we must not count curly braces that are within a doubly quoted string. :param section: string name of section :param section_start: integer index of section's beginning :return: integer index of section's end :raises: CurlyBraceMismatchException
[ "Get", "end", "of", "section", "s", "content", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/utils/iapp_parser.py#L80-L129
237,285
F5Networks/f5-common-python
f5/utils/iapp_parser.py
IappParser._get_section_start_index
def _get_section_start_index(self, section): '''Get start of a section's content. :param section: string name of section :return: integer index of section's beginning :raises: NonextantSectionException ''' sec_start_re = r'%s\s*\{' % section found = re.search(sec_start_re, self.template_str) if found: return found.end() - 1 raise NonextantSectionException( 'Section %s not found in template' % section )
python
def _get_section_start_index(self, section): '''Get start of a section's content. :param section: string name of section :return: integer index of section's beginning :raises: NonextantSectionException ''' sec_start_re = r'%s\s*\{' % section found = re.search(sec_start_re, self.template_str) if found: return found.end() - 1 raise NonextantSectionException( 'Section %s not found in template' % section )
[ "def", "_get_section_start_index", "(", "self", ",", "section", ")", ":", "sec_start_re", "=", "r'%s\\s*\\{'", "%", "section", "found", "=", "re", ".", "search", "(", "sec_start_re", ",", "self", ".", "template_str", ")", "if", "found", ":", "return", "found", ".", "end", "(", ")", "-", "1", "raise", "NonextantSectionException", "(", "'Section %s not found in template'", "%", "section", ")" ]
Get start of a section's content. :param section: string name of section :return: integer index of section's beginning :raises: NonextantSectionException
[ "Get", "start", "of", "a", "section", "s", "content", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/utils/iapp_parser.py#L131-L147
237,286
F5Networks/f5-common-python
f5/utils/iapp_parser.py
IappParser._get_template_name
def _get_template_name(self): '''Find template name. :returns: string of template name :raises: NonextantTemplateNameException ''' start_pattern = r"sys application template\s+" \ r"(\/[\w\.\-]+\/)?" \ r"(?P<name>[\w\.\-]+)\s*\{" template_start = re.search(start_pattern, self.template_str) if template_start: return template_start.group('name') raise NonextantTemplateNameException('Template name not found.')
python
def _get_template_name(self): '''Find template name. :returns: string of template name :raises: NonextantTemplateNameException ''' start_pattern = r"sys application template\s+" \ r"(\/[\w\.\-]+\/)?" \ r"(?P<name>[\w\.\-]+)\s*\{" template_start = re.search(start_pattern, self.template_str) if template_start: return template_start.group('name') raise NonextantTemplateNameException('Template name not found.')
[ "def", "_get_template_name", "(", "self", ")", ":", "start_pattern", "=", "r\"sys application template\\s+\"", "r\"(\\/[\\w\\.\\-]+\\/)?\"", "r\"(?P<name>[\\w\\.\\-]+)\\s*\\{\"", "template_start", "=", "re", ".", "search", "(", "start_pattern", ",", "self", ".", "template_str", ")", "if", "template_start", ":", "return", "template_start", ".", "group", "(", "'name'", ")", "raise", "NonextantTemplateNameException", "(", "'Template name not found.'", ")" ]
Find template name. :returns: string of template name :raises: NonextantTemplateNameException
[ "Find", "template", "name", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/utils/iapp_parser.py#L149-L164
237,287
F5Networks/f5-common-python
f5/utils/iapp_parser.py
IappParser._get_template_attr
def _get_template_attr(self, attr): '''Find the attribute value for a specific attribute. :param attr: string of attribute name :returns: string of attribute value ''' attr_re = r'{0}\s+.*'.format(attr) attr_found = re.search(attr_re, self.template_str) if attr_found: attr_value = attr_found.group(0).replace(attr, '', 1) return attr_value.strip()
python
def _get_template_attr(self, attr): '''Find the attribute value for a specific attribute. :param attr: string of attribute name :returns: string of attribute value ''' attr_re = r'{0}\s+.*'.format(attr) attr_found = re.search(attr_re, self.template_str) if attr_found: attr_value = attr_found.group(0).replace(attr, '', 1) return attr_value.strip()
[ "def", "_get_template_attr", "(", "self", ",", "attr", ")", ":", "attr_re", "=", "r'{0}\\s+.*'", ".", "format", "(", "attr", ")", "attr_found", "=", "re", ".", "search", "(", "attr_re", ",", "self", ".", "template_str", ")", "if", "attr_found", ":", "attr_value", "=", "attr_found", ".", "group", "(", "0", ")", ".", "replace", "(", "attr", ",", "''", ",", "1", ")", "return", "attr_value", ".", "strip", "(", ")" ]
Find the attribute value for a specific attribute. :param attr: string of attribute name :returns: string of attribute value
[ "Find", "the", "attribute", "value", "for", "a", "specific", "attribute", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/utils/iapp_parser.py#L166-L178
237,288
F5Networks/f5-common-python
f5/utils/iapp_parser.py
IappParser._add_sections
def _add_sections(self): '''Add the found and required sections to the templ_dict.''' for section in self.template_sections: try: sec_start = self._get_section_start_index(section) except NonextantSectionException: if section in self.sections_not_required: continue raise sec_end = self._get_section_end_index(section, sec_start) section_value = self.template_str[sec_start+1:sec_end].strip() section, section_value = self._transform_key_value( section, section_value, self.section_map ) self.templ_dict['actions']['definition'][section] = section_value self.template_str = self.template_str[:sec_start+1] + \ self.template_str[sec_end:]
python
def _add_sections(self): '''Add the found and required sections to the templ_dict.''' for section in self.template_sections: try: sec_start = self._get_section_start_index(section) except NonextantSectionException: if section in self.sections_not_required: continue raise sec_end = self._get_section_end_index(section, sec_start) section_value = self.template_str[sec_start+1:sec_end].strip() section, section_value = self._transform_key_value( section, section_value, self.section_map ) self.templ_dict['actions']['definition'][section] = section_value self.template_str = self.template_str[:sec_start+1] + \ self.template_str[sec_end:]
[ "def", "_add_sections", "(", "self", ")", ":", "for", "section", "in", "self", ".", "template_sections", ":", "try", ":", "sec_start", "=", "self", ".", "_get_section_start_index", "(", "section", ")", "except", "NonextantSectionException", ":", "if", "section", "in", "self", ".", "sections_not_required", ":", "continue", "raise", "sec_end", "=", "self", ".", "_get_section_end_index", "(", "section", ",", "sec_start", ")", "section_value", "=", "self", ".", "template_str", "[", "sec_start", "+", "1", ":", "sec_end", "]", ".", "strip", "(", ")", "section", ",", "section_value", "=", "self", ".", "_transform_key_value", "(", "section", ",", "section_value", ",", "self", ".", "section_map", ")", "self", ".", "templ_dict", "[", "'actions'", "]", "[", "'definition'", "]", "[", "section", "]", "=", "section_value", "self", ".", "template_str", "=", "self", ".", "template_str", "[", ":", "sec_start", "+", "1", "]", "+", "self", ".", "template_str", "[", "sec_end", ":", "]" ]
Add the found and required sections to the templ_dict.
[ "Add", "the", "found", "and", "required", "sections", "to", "the", "templ_dict", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/utils/iapp_parser.py#L180-L198
237,289
F5Networks/f5-common-python
f5/utils/iapp_parser.py
IappParser._add_cli_scripts
def _add_cli_scripts(self): '''Add the found external sections to the templ_dict.''' pattern = r"cli script\s+" \ r"(\/[\w\.\-]+\/)?" \ r"(?P<name>[\w\.\-]+)\s*\{" sections = re.finditer(pattern, self.template_str) for section in sections: if 'scripts' not in self.templ_dict: self.templ_dict['scripts'] = [] try: sec_start = self._get_section_start_index( section.group('name') ) except NonextantSectionException: continue sec_end = self._get_section_end_index( section.group('name'), sec_start ) section_value = self.template_str[sec_start+1:sec_end].strip() self.templ_dict['scripts'].append(dict( name=section.group('name'), script=section_value )) self.template_str = self.template_str[:sec_start+1] + \ self.template_str[sec_end:]
python
def _add_cli_scripts(self): '''Add the found external sections to the templ_dict.''' pattern = r"cli script\s+" \ r"(\/[\w\.\-]+\/)?" \ r"(?P<name>[\w\.\-]+)\s*\{" sections = re.finditer(pattern, self.template_str) for section in sections: if 'scripts' not in self.templ_dict: self.templ_dict['scripts'] = [] try: sec_start = self._get_section_start_index( section.group('name') ) except NonextantSectionException: continue sec_end = self._get_section_end_index( section.group('name'), sec_start ) section_value = self.template_str[sec_start+1:sec_end].strip() self.templ_dict['scripts'].append(dict( name=section.group('name'), script=section_value )) self.template_str = self.template_str[:sec_start+1] + \ self.template_str[sec_end:]
[ "def", "_add_cli_scripts", "(", "self", ")", ":", "pattern", "=", "r\"cli script\\s+\"", "r\"(\\/[\\w\\.\\-]+\\/)?\"", "r\"(?P<name>[\\w\\.\\-]+)\\s*\\{\"", "sections", "=", "re", ".", "finditer", "(", "pattern", ",", "self", ".", "template_str", ")", "for", "section", "in", "sections", ":", "if", "'scripts'", "not", "in", "self", ".", "templ_dict", ":", "self", ".", "templ_dict", "[", "'scripts'", "]", "=", "[", "]", "try", ":", "sec_start", "=", "self", ".", "_get_section_start_index", "(", "section", ".", "group", "(", "'name'", ")", ")", "except", "NonextantSectionException", ":", "continue", "sec_end", "=", "self", ".", "_get_section_end_index", "(", "section", ".", "group", "(", "'name'", ")", ",", "sec_start", ")", "section_value", "=", "self", ".", "template_str", "[", "sec_start", "+", "1", ":", "sec_end", "]", ".", "strip", "(", ")", "self", ".", "templ_dict", "[", "'scripts'", "]", ".", "append", "(", "dict", "(", "name", "=", "section", ".", "group", "(", "'name'", ")", ",", "script", "=", "section_value", ")", ")", "self", ".", "template_str", "=", "self", ".", "template_str", "[", ":", "sec_start", "+", "1", "]", "+", "self", ".", "template_str", "[", "sec_end", ":", "]" ]
Add the found external sections to the templ_dict.
[ "Add", "the", "found", "external", "sections", "to", "the", "templ_dict", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/utils/iapp_parser.py#L200-L230
237,290
F5Networks/f5-common-python
f5/utils/iapp_parser.py
IappParser._add_attrs
def _add_attrs(self): '''Add the found and required attrs to the templ_dict.''' for attr in self.template_attrs: attr_value = self._get_template_attr(attr) if not attr_value: continue attr, attr_value = self._transform_key_value( attr, attr_value, self.attr_map ) self.templ_dict[attr] = attr_value
python
def _add_attrs(self): '''Add the found and required attrs to the templ_dict.''' for attr in self.template_attrs: attr_value = self._get_template_attr(attr) if not attr_value: continue attr, attr_value = self._transform_key_value( attr, attr_value, self.attr_map ) self.templ_dict[attr] = attr_value
[ "def", "_add_attrs", "(", "self", ")", ":", "for", "attr", "in", "self", ".", "template_attrs", ":", "attr_value", "=", "self", ".", "_get_template_attr", "(", "attr", ")", "if", "not", "attr_value", ":", "continue", "attr", ",", "attr_value", "=", "self", ".", "_transform_key_value", "(", "attr", ",", "attr_value", ",", "self", ".", "attr_map", ")", "self", ".", "templ_dict", "[", "attr", "]", "=", "attr_value" ]
Add the found and required attrs to the templ_dict.
[ "Add", "the", "found", "and", "required", "attrs", "to", "the", "templ_dict", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/utils/iapp_parser.py#L232-L245
237,291
F5Networks/f5-common-python
f5/utils/iapp_parser.py
IappParser._parse_tcl_list
def _parse_tcl_list(self, attr, list_str): '''Turns a string representation of a TCL list into a Python list. :param attr: string name of attribute :param list_str: string representation of a list :returns: Python list ''' list_str = list_str.strip() if not list_str: return [] if list_str[0] != '{' and list_str[-1] != '}': if list_str.find('none') >= 0: return list_str if not re.search(self.tcl_list_patterns[attr], list_str): raise MalformedTCLListException( 'TCL list for "%s" is malformed. ' % attr ) list_str = list_str.strip('{').strip('}') list_str = list_str.strip() return list_str.split()
python
def _parse_tcl_list(self, attr, list_str): '''Turns a string representation of a TCL list into a Python list. :param attr: string name of attribute :param list_str: string representation of a list :returns: Python list ''' list_str = list_str.strip() if not list_str: return [] if list_str[0] != '{' and list_str[-1] != '}': if list_str.find('none') >= 0: return list_str if not re.search(self.tcl_list_patterns[attr], list_str): raise MalformedTCLListException( 'TCL list for "%s" is malformed. ' % attr ) list_str = list_str.strip('{').strip('}') list_str = list_str.strip() return list_str.split()
[ "def", "_parse_tcl_list", "(", "self", ",", "attr", ",", "list_str", ")", ":", "list_str", "=", "list_str", ".", "strip", "(", ")", "if", "not", "list_str", ":", "return", "[", "]", "if", "list_str", "[", "0", "]", "!=", "'{'", "and", "list_str", "[", "-", "1", "]", "!=", "'}'", ":", "if", "list_str", ".", "find", "(", "'none'", ")", ">=", "0", ":", "return", "list_str", "if", "not", "re", ".", "search", "(", "self", ".", "tcl_list_patterns", "[", "attr", "]", ",", "list_str", ")", ":", "raise", "MalformedTCLListException", "(", "'TCL list for \"%s\" is malformed. '", "%", "attr", ")", "list_str", "=", "list_str", ".", "strip", "(", "'{'", ")", ".", "strip", "(", "'}'", ")", "list_str", "=", "list_str", ".", "strip", "(", ")", "return", "list_str", ".", "split", "(", ")" ]
Turns a string representation of a TCL list into a Python list. :param attr: string name of attribute :param list_str: string representation of a list :returns: Python list
[ "Turns", "a", "string", "representation", "of", "a", "TCL", "list", "into", "a", "Python", "list", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/utils/iapp_parser.py#L247-L271
237,292
F5Networks/f5-common-python
f5/utils/iapp_parser.py
IappParser._transform_key_value
def _transform_key_value(self, key, value, map_dict): '''Massage keys and values for iapp dict to look like JSON. :param key: string dictionary key :param value: string dictionary value :param map_dict: dictionary to map key names ''' if key in self.tcl_list_patterns: value = self._parse_tcl_list(key, value) if key in map_dict: key = map_dict[key] return key, value
python
def _transform_key_value(self, key, value, map_dict): '''Massage keys and values for iapp dict to look like JSON. :param key: string dictionary key :param value: string dictionary value :param map_dict: dictionary to map key names ''' if key in self.tcl_list_patterns: value = self._parse_tcl_list(key, value) if key in map_dict: key = map_dict[key] return key, value
[ "def", "_transform_key_value", "(", "self", ",", "key", ",", "value", ",", "map_dict", ")", ":", "if", "key", "in", "self", ".", "tcl_list_patterns", ":", "value", "=", "self", ".", "_parse_tcl_list", "(", "key", ",", "value", ")", "if", "key", "in", "map_dict", ":", "key", "=", "map_dict", "[", "key", "]", "return", "key", ",", "value" ]
Massage keys and values for iapp dict to look like JSON. :param key: string dictionary key :param value: string dictionary value :param map_dict: dictionary to map key names
[ "Massage", "keys", "and", "values", "for", "iapp", "dict", "to", "look", "like", "JSON", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/utils/iapp_parser.py#L273-L287
237,293
F5Networks/f5-common-python
f5/utils/iapp_parser.py
IappParser.parse_template
def parse_template(self): '''Parse the template string into a dict. Find the (large) inner sections first, save them, and remove them from a modified string. Then find the template attributes in the modified string. :returns: dictionary of parsed template ''' self.templ_dict = {'actions': {'definition': {}}} self.templ_dict['name'] = self._get_template_name() self._add_cli_scripts() self._add_sections() self._add_attrs() return self.templ_dict
python
def parse_template(self): '''Parse the template string into a dict. Find the (large) inner sections first, save them, and remove them from a modified string. Then find the template attributes in the modified string. :returns: dictionary of parsed template ''' self.templ_dict = {'actions': {'definition': {}}} self.templ_dict['name'] = self._get_template_name() self._add_cli_scripts() self._add_sections() self._add_attrs() return self.templ_dict
[ "def", "parse_template", "(", "self", ")", ":", "self", ".", "templ_dict", "=", "{", "'actions'", ":", "{", "'definition'", ":", "{", "}", "}", "}", "self", ".", "templ_dict", "[", "'name'", "]", "=", "self", ".", "_get_template_name", "(", ")", "self", ".", "_add_cli_scripts", "(", ")", "self", ".", "_add_sections", "(", ")", "self", ".", "_add_attrs", "(", ")", "return", "self", ".", "templ_dict" ]
Parse the template string into a dict. Find the (large) inner sections first, save them, and remove them from a modified string. Then find the template attributes in the modified string. :returns: dictionary of parsed template
[ "Parse", "the", "template", "string", "into", "a", "dict", "." ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/utils/iapp_parser.py#L289-L307
237,294
F5Networks/f5-common-python
f5/bigip/shared/authn.py
Root._create
def _create(self, **kwargs): """wrapped by `create` override that in subclasses to customize""" if 'uri' in self._meta_data: error = "There was an attempt to assign a new uri to this "\ "resource, the _meta_data['uri'] is %s and it should"\ " not be changed." % (self._meta_data['uri']) raise URICreationCollision(error) self._check_exclusive_parameters(**kwargs) requests_params = self._handle_requests_params(kwargs) self._minimum_one_is_missing(**kwargs) self._check_create_parameters(**kwargs) kwargs = self._check_for_python_keywords(kwargs) # Reduce boolean pairs as specified by the meta_data entry below for key1, key2 in self._meta_data['reduction_forcing_pairs']: kwargs = self._reduce_boolean_pair(kwargs, key1, key2) # Make convenience variable with short names for this method. _create_uri = self._meta_data['container']._meta_data['uri'] session = self._meta_data['bigip']._meta_data['icr_session'] kwargs = self._prepare_request_json(kwargs) # Invoke the REST operation on the device. response = session.post(_create_uri, json=kwargs, **requests_params) # Make new instance of self result = self._produce_instance(response) return result
python
def _create(self, **kwargs): """wrapped by `create` override that in subclasses to customize""" if 'uri' in self._meta_data: error = "There was an attempt to assign a new uri to this "\ "resource, the _meta_data['uri'] is %s and it should"\ " not be changed." % (self._meta_data['uri']) raise URICreationCollision(error) self._check_exclusive_parameters(**kwargs) requests_params = self._handle_requests_params(kwargs) self._minimum_one_is_missing(**kwargs) self._check_create_parameters(**kwargs) kwargs = self._check_for_python_keywords(kwargs) # Reduce boolean pairs as specified by the meta_data entry below for key1, key2 in self._meta_data['reduction_forcing_pairs']: kwargs = self._reduce_boolean_pair(kwargs, key1, key2) # Make convenience variable with short names for this method. _create_uri = self._meta_data['container']._meta_data['uri'] session = self._meta_data['bigip']._meta_data['icr_session'] kwargs = self._prepare_request_json(kwargs) # Invoke the REST operation on the device. response = session.post(_create_uri, json=kwargs, **requests_params) # Make new instance of self result = self._produce_instance(response) return result
[ "def", "_create", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "'uri'", "in", "self", ".", "_meta_data", ":", "error", "=", "\"There was an attempt to assign a new uri to this \"", "\"resource, the _meta_data['uri'] is %s and it should\"", "\" not be changed.\"", "%", "(", "self", ".", "_meta_data", "[", "'uri'", "]", ")", "raise", "URICreationCollision", "(", "error", ")", "self", ".", "_check_exclusive_parameters", "(", "*", "*", "kwargs", ")", "requests_params", "=", "self", ".", "_handle_requests_params", "(", "kwargs", ")", "self", ".", "_minimum_one_is_missing", "(", "*", "*", "kwargs", ")", "self", ".", "_check_create_parameters", "(", "*", "*", "kwargs", ")", "kwargs", "=", "self", ".", "_check_for_python_keywords", "(", "kwargs", ")", "# Reduce boolean pairs as specified by the meta_data entry below", "for", "key1", ",", "key2", "in", "self", ".", "_meta_data", "[", "'reduction_forcing_pairs'", "]", ":", "kwargs", "=", "self", ".", "_reduce_boolean_pair", "(", "kwargs", ",", "key1", ",", "key2", ")", "# Make convenience variable with short names for this method.", "_create_uri", "=", "self", ".", "_meta_data", "[", "'container'", "]", ".", "_meta_data", "[", "'uri'", "]", "session", "=", "self", ".", "_meta_data", "[", "'bigip'", "]", ".", "_meta_data", "[", "'icr_session'", "]", "kwargs", "=", "self", ".", "_prepare_request_json", "(", "kwargs", ")", "# Invoke the REST operation on the device.", "response", "=", "session", ".", "post", "(", "_create_uri", ",", "json", "=", "kwargs", ",", "*", "*", "requests_params", ")", "# Make new instance of self", "result", "=", "self", ".", "_produce_instance", "(", "response", ")", "return", "result" ]
wrapped by `create` override that in subclasses to customize
[ "wrapped", "by", "create", "override", "that", "in", "subclasses", "to", "customize" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/shared/authn.py#L55-L83
237,295
F5Networks/f5-common-python
f5sdk_plugins/fixtures.py
peer
def peer(opt_peer, opt_username, opt_password, scope="module"): '''peer bigip fixture''' p = BigIP(opt_peer, opt_username, opt_password) return p
python
def peer(opt_peer, opt_username, opt_password, scope="module"): '''peer bigip fixture''' p = BigIP(opt_peer, opt_username, opt_password) return p
[ "def", "peer", "(", "opt_peer", ",", "opt_username", ",", "opt_password", ",", "scope", "=", "\"module\"", ")", ":", "p", "=", "BigIP", "(", "opt_peer", ",", "opt_username", ",", "opt_password", ")", "return", "p" ]
peer bigip fixture
[ "peer", "bigip", "fixture" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5sdk_plugins/fixtures.py#L116-L119
237,296
F5Networks/f5-common-python
f5/bigip/tm/gtm/topology.py
Topology.exists
def exists(self, **kwargs): """Providing a partition is not necessary on topology; causes errors""" kwargs.pop('partition', None) kwargs['transform_name'] = True return self._exists(**kwargs)
python
def exists(self, **kwargs): """Providing a partition is not necessary on topology; causes errors""" kwargs.pop('partition', None) kwargs['transform_name'] = True return self._exists(**kwargs)
[ "def", "exists", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "pop", "(", "'partition'", ",", "None", ")", "kwargs", "[", "'transform_name'", "]", "=", "True", "return", "self", ".", "_exists", "(", "*", "*", "kwargs", ")" ]
Providing a partition is not necessary on topology; causes errors
[ "Providing", "a", "partition", "is", "not", "necessary", "on", "topology", ";", "causes", "errors" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/bigip/tm/gtm/topology.py#L149-L153
237,297
F5Networks/f5-common-python
f5/utils/responses/handlers.py
Stats._key_dot_replace
def _key_dot_replace(self, rdict): """Replace fullstops in returned keynames""" temp_dict = {} for key, value in iteritems(rdict): if isinstance(value, dict): value = self._key_dot_replace(value) temp_dict[key.replace('.', '_')] = value return temp_dict
python
def _key_dot_replace(self, rdict): """Replace fullstops in returned keynames""" temp_dict = {} for key, value in iteritems(rdict): if isinstance(value, dict): value = self._key_dot_replace(value) temp_dict[key.replace('.', '_')] = value return temp_dict
[ "def", "_key_dot_replace", "(", "self", ",", "rdict", ")", ":", "temp_dict", "=", "{", "}", "for", "key", ",", "value", "in", "iteritems", "(", "rdict", ")", ":", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "value", "=", "self", ".", "_key_dot_replace", "(", "value", ")", "temp_dict", "[", "key", ".", "replace", "(", "'.'", ",", "'_'", ")", "]", "=", "value", "return", "temp_dict" ]
Replace fullstops in returned keynames
[ "Replace", "fullstops", "in", "returned", "keynames" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/utils/responses/handlers.py#L43-L50
237,298
F5Networks/f5-common-python
f5/utils/responses/handlers.py
Stats._get_nest_stats
def _get_nest_stats(self): """Helper method to deal with nestedStats as json format changed in v12.x """ for x in self.rdict: check = urlparse(x) if check.scheme: nested_dict = self.rdict[x]['nestedStats'] tmp_dict = nested_dict['entries'] return self._key_dot_replace(tmp_dict) return self._key_dot_replace(self.rdict)
python
def _get_nest_stats(self): """Helper method to deal with nestedStats as json format changed in v12.x """ for x in self.rdict: check = urlparse(x) if check.scheme: nested_dict = self.rdict[x]['nestedStats'] tmp_dict = nested_dict['entries'] return self._key_dot_replace(tmp_dict) return self._key_dot_replace(self.rdict)
[ "def", "_get_nest_stats", "(", "self", ")", ":", "for", "x", "in", "self", ".", "rdict", ":", "check", "=", "urlparse", "(", "x", ")", "if", "check", ".", "scheme", ":", "nested_dict", "=", "self", ".", "rdict", "[", "x", "]", "[", "'nestedStats'", "]", "tmp_dict", "=", "nested_dict", "[", "'entries'", "]", "return", "self", ".", "_key_dot_replace", "(", "tmp_dict", ")", "return", "self", ".", "_key_dot_replace", "(", "self", ".", "rdict", ")" ]
Helper method to deal with nestedStats as json format changed in v12.x
[ "Helper", "method", "to", "deal", "with", "nestedStats" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/utils/responses/handlers.py#L52-L64
237,299
F5Networks/f5-common-python
f5/utils/responses/handlers.py
Stats.refresh
def refresh(self, **kwargs): """Refreshes stats attached to an object""" self.resource.refresh(**kwargs) self.rdict = self.resource.entries self._update_stats()
python
def refresh(self, **kwargs): """Refreshes stats attached to an object""" self.resource.refresh(**kwargs) self.rdict = self.resource.entries self._update_stats()
[ "def", "refresh", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "resource", ".", "refresh", "(", "*", "*", "kwargs", ")", "self", ".", "rdict", "=", "self", ".", "resource", ".", "entries", "self", ".", "_update_stats", "(", ")" ]
Refreshes stats attached to an object
[ "Refreshes", "stats", "attached", "to", "an", "object" ]
7e67d5acd757a60e3d5f8c88c534bd72208f5494
https://github.com/F5Networks/f5-common-python/blob/7e67d5acd757a60e3d5f8c88c534bd72208f5494/f5/utils/responses/handlers.py#L71-L75