idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
231,100
def transform ( self , X , y = None ) : insuffix = X . _libsuffix multires_fn = utils . get_lib_fn ( 'multiResolutionAntsImage%s' % ( insuffix ) ) casted_ptrs = multires_fn ( X . pointer , self . levels ) imgs = [ ] for casted_ptr in casted_ptrs : img = iio . ANTsImage ( pixeltype = X . pixeltype , dimension = X . dimension , components = X . components , pointer = casted_ptr ) if self . keep_shape : img = img . resample_image_to_target ( X ) imgs . append ( img ) return imgs
Generate a set of multi - resolution ANTsImage types
157
12
231,101
def transform ( self , X , y = None ) : #if X.pixeltype != 'float': # raise ValueError('image.pixeltype must be float ... use TypeCast transform or clone to float') insuffix = X . _libsuffix cast_fn = utils . get_lib_fn ( 'locallyBlurAntsImage%s' % ( insuffix ) ) casted_ptr = cast_fn ( X . pointer , self . iters , self . conductance ) return iio . ANTsImage ( pixeltype = X . pixeltype , dimension = X . dimension , components = X . components , pointer = casted_ptr )
Locally blur an image by applying a gradient anisotropic diffusion filter .
143
15
231,102
def get_data ( name = None ) : if name is None : files = [ ] for fname in os . listdir ( data_path ) : if ( fname . endswith ( '.nii.gz' ) ) or ( fname . endswith ( '.jpg' ) or ( fname . endswith ( '.csv' ) ) ) : fname = os . path . join ( data_path , fname ) files . append ( fname ) return files else : datapath = None for fname in os . listdir ( data_path ) : if ( name == fname . split ( '.' ) [ 0 ] ) or ( ( name + 'slice' ) == fname . split ( '.' ) [ 0 ] ) : datapath = os . path . join ( data_path , fname ) if datapath is None : raise ValueError ( 'File doesnt exist. Options: ' , os . listdir ( data_path ) ) return datapath
Get ANTsPy test data filename
215
7
231,103
def convolve_image ( image , kernel_image , crop = True ) : if not isinstance ( image , iio . ANTsImage ) : raise ValueError ( 'image must be ANTsImage type' ) if not isinstance ( kernel_image , iio . ANTsImage ) : raise ValueError ( 'kernel must be ANTsImage type' ) orig_ptype = image . pixeltype if image . pixeltype != 'float' : image = image . clone ( 'float' ) if kernel_image . pixeltype != 'float' : kernel_image = kernel_image . clone ( 'float' ) if crop : kernel_image_mask = utils . get_mask ( kernel_image ) kernel_image = utils . crop_image ( kernel_image , kernel_image_mask ) kernel_image_mask = utils . crop_image ( kernel_image_mask , kernel_image_mask ) kernel_image [ kernel_image_mask == 0 ] = kernel_image [ kernel_image_mask == 1 ] . mean ( ) libfn = utils . get_lib_fn ( 'convolveImageF%i' % image . dimension ) conv_itk_image = libfn ( image . pointer , kernel_image . pointer ) conv_ants_image = iio . ANTsImage ( pixeltype = image . pixeltype , dimension = image . dimension , components = image . components , pointer = conv_itk_image ) if orig_ptype != 'float' : conv_ants_image = conv_ants_image . clone ( orig_ptype ) return conv_ants_image
Convolve one image with another
349
7
231,104
def ndimage_to_list ( image ) : inpixeltype = image . pixeltype dimension = image . dimension components = 1 imageShape = image . shape nSections = imageShape [ dimension - 1 ] subdimension = dimension - 1 suborigin = iio . get_origin ( image ) [ 0 : subdimension ] subspacing = iio . get_spacing ( image ) [ 0 : subdimension ] subdirection = np . eye ( subdimension ) for i in range ( subdimension ) : subdirection [ i , : ] = iio . get_direction ( image ) [ i , 0 : subdimension ] subdim = image . shape [ 0 : subdimension ] imagelist = [ ] for i in range ( nSections ) : img = utils . slice_image ( image , axis = subdimension , idx = i ) iio . set_spacing ( img , subspacing ) iio . set_origin ( img , suborigin ) iio . set_direction ( img , subdirection ) imagelist . append ( img ) return imagelist
Split a n dimensional ANTsImage into a list of n - 1 dimensional ANTsImages
231
18
231,105
def _int_antsProcessArguments ( args ) : p_args = [ ] if isinstance ( args , dict ) : for argname , argval in args . items ( ) : if '-MULTINAME-' in argname : # have this little hack because python doesnt support # multiple dict entries w/ the same key like R lists argname = argname [ : argname . find ( '-MULTINAME-' ) ] if argval is not None : if len ( argname ) > 1 : p_args . append ( '--%s' % argname ) else : p_args . append ( '-%s' % argname ) if isinstance ( argval , iio . ANTsImage ) : p_args . append ( _ptrstr ( argval . pointer ) ) elif isinstance ( argval , list ) : for av in argval : if isinstance ( av , iio . ANTsImage ) : av = _ptrstr ( av . pointer ) p_args . append ( av ) else : p_args . append ( str ( argval ) ) elif isinstance ( args , list ) : for arg in args : if isinstance ( arg , iio . ANTsImage ) : pointer_string = _ptrstr ( arg . pointer ) p_arg = pointer_string elif arg is None : pass else : p_arg = str ( arg ) p_args . append ( p_arg ) return p_args
Needs to be better validated .
315
7
231,106
def initialize_eigenanatomy ( initmat , mask = None , initlabels = None , nreps = 1 , smoothing = 0 ) : if isinstance ( initmat , iio . ANTsImage ) : # create initmat from each of the unique labels if mask is not None : selectvec = mask > 0 else : selectvec = initmat > 0 initmatvec = initmat [ selectvec ] if initlabels is None : ulabs = np . sort ( np . unique ( initmatvec ) ) ulabs = ulabs [ ulabs > 0 ] else : ulabs = initlabels nvox = len ( initmatvec ) temp = np . zeros ( ( len ( ulabs ) , nvox ) ) for x in range ( len ( ulabs ) ) : timg = utils . threshold_image ( initmat , ulabs [ x ] - 1e-4 , ulabs [ x ] + 1e-4 ) if smoothing > 0 : timg = utils . smooth_image ( timg , smoothing ) temp [ x , : ] = timg [ selectvec ] initmat = temp nclasses = initmat . shape [ 0 ] classlabels = [ 'init%i' % i for i in range ( nclasses ) ] initlist = [ ] if mask is None : maskmat = np . zeros ( initmat . shape ) maskmat [ 0 , : ] = 1 mask = core . from_numpy ( maskmat . astype ( 'float32' ) ) eanatnames = [ 'A' ] * ( nclasses * nreps ) ct = 0 for i in range ( nclasses ) : vecimg = mask . clone ( 'float' ) initf = initmat [ i , : ] vecimg [ mask == 1 ] = initf for nr in range ( nreps ) : initlist . append ( vecimg ) eanatnames [ ct + nr - 1 ] = str ( classlabels [ i ] ) ct = ct + 1 return { 'initlist' : initlist , 'mask' : mask , 'enames' : eanatnames }
InitializeEigenanatomy is a helper function to initialize sparseDecom and sparseDecom2 . Can be used to estimate sparseness parameters per eigenvector . The user then only chooses nvecs and optional regularization parameters .
469
50
231,107
def eig_seg ( mask , img_list , apply_segmentation_to_images = False , cthresh = 0 , smooth = 1 ) : maskvox = mask > 0 maskseg = mask . clone ( ) maskseg [ maskvox ] = 0 if isinstance ( img_list , np . ndarray ) : mydata = img_list elif isinstance ( img_list , ( tuple , list ) ) : mydata = core . image_list_to_matrix ( img_list , mask ) if ( smooth > 0 ) : for i in range ( mydata . shape [ 0 ] ) : temp_img = core . make_image ( mask , mydata [ i , : ] , pixeltype = 'float' ) temp_img = utils . smooth_image ( temp_img , smooth , sigma_in_physical_coordinates = True ) mydata [ i , : ] = temp_img [ mask >= 0.5 ] segids = np . argmax ( np . abs ( mydata ) , axis = 0 ) + 1 segmax = np . max ( np . abs ( mydata ) , axis = 0 ) maskseg [ maskvox ] = ( segids * ( segmax > 1e-09 ) ) if cthresh > 0 : for kk in range ( int ( maskseg . max ( ) ) ) : timg = utils . threshold_image ( maskseg , kk , kk ) timg = utils . label_clusters ( timg , cthresh ) timg = utils . threshold_image ( timg , 1 , 1e15 ) * float ( kk ) maskseg [ maskseg == kk ] = timg [ maskseg == kk ] if ( apply_segmentation_to_images ) and ( not isinstance ( img_list , np . ndarray ) ) : for i in range ( len ( img_list ) ) : img = img_list [ i ] img [ maskseg != float ( i ) ] = 0 img_list [ i ] = img return maskseg
Segment a mask into regions based on the max value in an image list . At a given voxel the segmentation label will contain the index to the image that has the largest value . If the 3rd image has the greatest value the segmentation label will be 3 at that voxel .
468
61
231,108
def label_stats ( image , label_image ) : image_float = image . clone ( 'float' ) label_image_int = label_image . clone ( 'unsigned int' ) libfn = utils . get_lib_fn ( 'labelStats%iD' % image . dimension ) df = libfn ( image_float . pointer , label_image_int . pointer ) #df = df[order(df$LabelValue), ] return pd . DataFrame ( df )
Get label statistics from image
106
5
231,109
def spacing ( self ) : libfn = utils . get_lib_fn ( 'getSpacing%s' % self . _libsuffix ) return libfn ( self . pointer )
Get image spacing
41
3
231,110
def set_spacing ( self , new_spacing ) : if not isinstance ( new_spacing , ( tuple , list ) ) : raise ValueError ( 'arg must be tuple or list' ) if len ( new_spacing ) != self . dimension : raise ValueError ( 'must give a spacing value for each dimension (%i)' % self . dimension ) libfn = utils . get_lib_fn ( 'setSpacing%s' % self . _libsuffix ) libfn ( self . pointer , new_spacing )
Set image spacing
117
3
231,111
def origin ( self ) : libfn = utils . get_lib_fn ( 'getOrigin%s' % self . _libsuffix ) return libfn ( self . pointer )
Get image origin
40
3
231,112
def set_origin ( self , new_origin ) : if not isinstance ( new_origin , ( tuple , list ) ) : raise ValueError ( 'arg must be tuple or list' ) if len ( new_origin ) != self . dimension : raise ValueError ( 'must give a origin value for each dimension (%i)' % self . dimension ) libfn = utils . get_lib_fn ( 'setOrigin%s' % self . _libsuffix ) libfn ( self . pointer , new_origin )
Set image origin
111
3
231,113
def direction ( self ) : libfn = utils . get_lib_fn ( 'getDirection%s' % self . _libsuffix ) return libfn ( self . pointer )
Get image direction
41
3
231,114
def set_direction ( self , new_direction ) : if isinstance ( new_direction , ( tuple , list ) ) : new_direction = np . asarray ( new_direction ) if not isinstance ( new_direction , np . ndarray ) : raise ValueError ( 'arg must be np.ndarray or tuple or list' ) if len ( new_direction ) != self . dimension : raise ValueError ( 'must give a origin value for each dimension (%i)' % self . dimension ) libfn = utils . get_lib_fn ( 'setDirection%s' % self . _libsuffix ) libfn ( self . pointer , new_direction )
Set image direction
145
3
231,115
def astype ( self , dtype ) : if dtype not in _supported_dtypes : raise ValueError ( 'Datatype %s not supported. Supported types are %s' % ( dtype , _supported_dtypes ) ) pixeltype = _npy_to_itk_map [ dtype ] return self . clone ( pixeltype )
Cast & clone an ANTsImage to a given numpy datatype .
77
16
231,116
def new_image_like ( self , data ) : if not isinstance ( data , np . ndarray ) : raise ValueError ( 'data must be a numpy array' ) if not self . has_components : if data . shape != self . shape : raise ValueError ( 'given array shape (%s) and image array shape (%s) do not match' % ( data . shape , self . shape ) ) else : if ( data . shape [ - 1 ] != self . components ) or ( data . shape [ : - 1 ] != self . shape ) : raise ValueError ( 'given array shape (%s) and image array shape (%s) do not match' % ( data . shape [ 1 : ] , self . shape ) ) return iio2 . from_numpy ( data , origin = self . origin , spacing = self . spacing , direction = self . direction , has_components = self . has_components )
Create a new ANTsImage with the same header information but with a new image array .
202
18
231,117
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
56
7
231,118
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 .
41
9
231,119
def sum ( self , axis = None , keepdims = False ) : return self . numpy ( ) . sum ( axis = axis , keepdims = keepdims )
Return sum along specified axis
38
5
231,120
def range ( self , axis = None ) : return ( self . min ( axis = axis ) , self . max ( axis = axis ) )
Return range tuple along specified axis
30
6
231,121
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
65
6
231,122
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
44
7
231,123
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
72
8
231,124
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
133
22
231,125
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
251
7
231,126
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
361
16
231,127
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
95
11
231,128
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
490
8
231,129
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
303
17
231,130
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
196
11
231,131
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 .
256
25
231,132
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 .
60
10
231,133
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 .
80
9
231,134
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
163
6
231,135
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
659
7
231,136
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 .
196
39
231,137
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
144
7
231,138
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
54
6
231,139
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
184
18
231,140
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
206
9
231,141
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
219
16
231,142
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 .
172
5
231,143
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
512
7
231,144
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 .
73
26
231,145
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
150
11
231,146
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
64
11
231,147
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 .
176
29
231,148
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 .
204
28
231,149
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 .
112
22
231,150
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 .
125
28
231,151
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 .
136
23
231,152
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 .
122
22
231,153
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 .
200
11
231,154
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
141
6
231,155
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
195
5
231,156
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
58
6
231,157
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
176
7
231,158
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
68
16
231,159
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 .
152
5
231,160
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 .
438
15
231,161
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
102
7
231,162
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
102
7
231,163
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 .
154
9
231,164
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
169
14
231,165
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
299
10
231,166
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 .
58
13
231,167
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 .
119
9
231,168
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
247
9
231,169
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
54
4
231,170
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
290
15
231,171
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
126
10
231,172
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
311
10
231,173
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 .
114
17
231,174
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
177
6
231,175
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
82
13
231,176
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
183
5
231,177
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
57
10
231,178
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 .
79
5
231,179
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 .
240
8
231,180
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 .
63
5
231,181
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 .
67
3
231,182
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 .
77
4
231,183
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
72
8
231,184
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 .
78
10
231,185
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 .
243
10
231,186
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 .
60
10
231,187
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
453
8
231,188
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
72
7
231,189
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
175
10
231,190
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 .
102
8
231,191
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 .
56
10
231,192
def teardown ( self ) : for device in self . devices : self . _remove_trustee ( device ) self . _populate_domain ( ) self . domain = { }
Teardown trust domain by removing trusted devices .
40
10
231,193
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 .
91
10
231,194
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 .
185
8
231,195
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 .
127
13
231,196
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 .
114
13
231,197
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
156
8
231,198
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 .
113
11
231,199
def load ( self , * * kwargs ) : kwargs [ 'transform_name' ] = True kwargs = self . _mutate_name ( kwargs ) return self . _load ( * * kwargs )
Loads a given resource
52
5