idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
24,500
def cli ( ctx ) : dir_path = os . path . join ( os . path . expanduser ( '~' ) , '.keep' ) if os . path . exists ( dir_path ) : if click . confirm ( '[CRITICAL] Remove everything inside ~/.keep ?' , abort = True ) : shutil . rmtree ( dir_path ) utils . first_time_use ( ctx )
Initializes the CLI environment .
24,501
def cli ( ctx , pattern , arguments , safe ) : matches = utils . grep_commands ( pattern ) if matches : selected = utils . select_command ( matches ) if selected >= 0 : cmd , desc = matches [ selected ] pcmd = utils . create_pcmd ( cmd ) raw_params , params , defaults = utils . get_params_in_pcmd ( pcmd ) arguments = l...
Executes a saved command .
24,502
def cli ( ctx ) : cmd = click . prompt ( 'Command' ) desc = click . prompt ( 'Description ' ) alias = click . prompt ( 'Alias (optional)' , default = '' ) utils . save_command ( cmd , desc , alias ) utils . log ( ctx , 'Saved the new command - {} - with the description - {}.' . format ( cmd , desc ) )
Saves a new command
24,503
def log ( self , msg , * args ) : if args : msg %= args click . echo ( msg , file = sys . stderr )
Logs a message to stderr .
24,504
def vlog ( self , msg , * args ) : if self . verbose : self . log ( msg , * args )
Logs a message to stderr only if verbose is enabled .
24,505
def cli ( ctx ) : utils . check_update ( ctx , forced = True ) click . secho ( "Keep is at its latest version v{}" . format ( about . __version__ ) , fg = 'green' )
Check for an update of Keep .
24,506
def cli ( ctx , pattern ) : matches = utils . grep_commands ( pattern ) if matches : for cmd , desc in matches : click . secho ( "$ {} :: {}" . format ( cmd , desc ) , fg = 'green' ) elif matches == [ ] : click . echo ( 'No saved commands matches the pattern {}' . format ( pattern ) ) else : click . echo ( 'No commands...
Searches for a saved command .
24,507
def cli ( ctx ) : json_path = os . path . join ( os . path . expanduser ( '~' ) , '.keep' , 'commands.json' ) if not os . path . exists ( json_path ) : click . echo ( 'No commands to show. Add one by `keep new`.' ) else : utils . list_commands ( ctx )
Shows the saved commands .
24,508
def cli ( ctx , overwrite ) : credentials_path = os . path . join ( os . path . expanduser ( '~' ) , '.keep' , '.credentials' ) if not os . path . exists ( credentials_path ) : click . echo ( 'You are not registered.' ) utils . register ( ) else : utils . pull ( ctx , overwrite )
Updates the local database with remote .
24,509
def cli ( ctx ) : dir_path = os . path . join ( os . path . expanduser ( '~' ) , '.keep' , '.credentials' ) if os . path . exists ( dir_path ) : if click . confirm ( '[CRITICAL] Reset credentials saved in ~/.keep/.credentials ?' , abort = True ) : os . remove ( dir_path ) utils . register ( )
Register user over server .
24,510
def check_update ( ctx , forced = False ) : try : if ctx . update_checked and not forced : return except AttributeError : update_check_file = os . path . join ( dir_path , 'update_check.txt' ) today = datetime . date . today ( ) . strftime ( "%m/%d/%Y" ) if os . path . exists ( update_check_file ) : date = open ( updat...
Check for update on pypi . Limit to 1 check per day if not forced
24,511
def cli ( ctx , editor ) : commands = utils . read_commands ( ) if commands is [ ] : click . echo ( "No commands to edit, Add one by 'keep new'. " ) else : edit_header = "# Unchanged file will abort the operation\n" new_commands = utils . edit_commands ( commands , editor , edit_header ) if new_commands and new_command...
Edit saved commands .
24,512
def cli ( ctx , pattern ) : matches = utils . grep_commands ( pattern ) if matches : selected = utils . select_command ( matches ) if selected >= 0 : cmd , desc = matches [ selected ] command = "$ {} :: {}" . format ( cmd , desc ) if click . confirm ( "Remove\n\t{}\n\n?" . format ( command ) , default = True ) : utils ...
Deletes a saved command .
24,513
def show_mesh ( mesh ) : r lim_max = sp . amax ( mesh . verts , axis = 0 ) lim_min = sp . amin ( mesh . verts , axis = 0 ) fig = plt . figure ( ) ax = fig . add_subplot ( 111 , projection = '3d' ) mesh = Poly3DCollection ( mesh . verts [ mesh . faces ] ) mesh . set_edgecolor ( 'k' ) ax . add_collection3d ( mesh ) ax . ...
r Visualizes the mesh of a region as obtained by get_mesh function in the metrics submodule .
24,514
def representative_elementary_volume ( im , npoints = 1000 ) : r im_temp = sp . zeros_like ( im ) crds = sp . array ( sp . rand ( npoints , im . ndim ) * im . shape , dtype = int ) pads = sp . array ( sp . rand ( npoints ) * sp . amin ( im . shape ) / 2 + 10 , dtype = int ) im_temp [ tuple ( crds . T ) ] = True labels ...
r Calculates the porosity of the image as a function subdomain size . This function extracts a specified number of subdomains of random size then finds their porosity .
24,515
def porosity_profile ( im , axis ) : r if axis >= im . ndim : raise Exception ( 'axis out of range' ) im = np . atleast_3d ( im ) a = set ( range ( im . ndim ) ) . difference ( set ( [ axis ] ) ) a1 , a2 = a prof = np . sum ( np . sum ( im , axis = a2 ) , axis = a1 ) / ( im . shape [ a2 ] * im . shape [ a1 ] ) return p...
r Returns a porosity profile along the specified axis
24,516
def porosity ( im ) : r im = sp . array ( im , dtype = int ) Vp = sp . sum ( im == 1 ) Vs = sp . sum ( im == 0 ) e = Vp / ( Vs + Vp ) return e
r Calculates the porosity of an image assuming 1 s are void space and 0 s are solid phase .
24,517
def _radial_profile ( autocorr , r_max , nbins = 100 ) : r if len ( autocorr . shape ) == 2 : adj = sp . reshape ( autocorr . shape , [ 2 , 1 , 1 ] ) inds = sp . indices ( autocorr . shape ) - adj / 2 dt = sp . sqrt ( inds [ 0 ] ** 2 + inds [ 1 ] ** 2 ) elif len ( autocorr . shape ) == 3 : adj = sp . reshape ( autocorr...
r Helper functions to calculate the radial profile of the autocorrelation Masks the image in radial segments from the center and averages the values The distance values are normalized and 100 bins are used as default .
24,518
def two_point_correlation_fft ( im ) : r hls = ( np . ceil ( np . shape ( im ) ) / 2 ) . astype ( int ) F = sp_ft . ifftshift ( sp_ft . fftn ( sp_ft . fftshift ( im ) ) ) P = sp . absolute ( F ** 2 ) autoc = sp . absolute ( sp_ft . ifftshift ( sp_ft . ifftn ( sp_ft . fftshift ( P ) ) ) ) tpcf = _radial_profile ( autoc ...
r Calculates the two - point correlation function using fourier transforms
24,519
def pore_size_distribution ( im , bins = 10 , log = True , voxel_size = 1 ) : r im = im . flatten ( ) vals = im [ im > 0 ] * voxel_size if log : vals = sp . log10 ( vals ) h = _parse_histogram ( sp . histogram ( vals , bins = bins , density = True ) ) psd = namedtuple ( 'pore_size_distribution' , ( log * 'log' + 'R' , ...
r Calculate a pore - size distribution based on the image produced by the porosimetry or local_thickness functions .
24,520
def chord_counts ( im ) : r labels , N = spim . label ( im > 0 ) props = regionprops ( labels , coordinates = 'xy' ) chord_lens = sp . array ( [ i . filled_area for i in props ] ) return chord_lens
r Finds the length of each chord in the supplied image and returns a list of their individual sizes
24,521
def chord_length_distribution ( im , bins = None , log = False , voxel_size = 1 , normalization = 'count' ) : r x = chord_counts ( im ) if bins is None : bins = sp . array ( range ( 0 , x . max ( ) + 2 ) ) * voxel_size x = x * voxel_size if log : x = sp . log10 ( x ) if normalization == 'length' : h = list ( sp . histo...
r Determines the distribution of chord lengths in an image containing chords .
24,522
def region_interface_areas ( regions , areas , voxel_size = 1 , strel = None ) : r print ( '_' * 60 ) print ( 'Finding interfacial areas between each region' ) from skimage . morphology import disk , square , ball , cube im = regions . copy ( ) if im . ndim != im . squeeze ( ) . ndim : warnings . warn ( 'Input image co...
r Calculates the interfacial area between all pairs of adjecent regions
24,523
def region_surface_areas ( regions , voxel_size = 1 , strel = None ) : r print ( '_' * 60 ) print ( 'Finding surface area of each region' ) im = regions . copy ( ) slices = spim . find_objects ( im ) Ps = sp . arange ( 1 , sp . amax ( im ) + 1 ) sa = sp . zeros_like ( Ps , dtype = float ) for i in tqdm ( Ps ) : reg = i...
r Extracts the surface area of each region in a labeled image .
24,524
def mesh_surface_area ( mesh = None , verts = None , faces = None ) : r if mesh : verts = mesh . verts faces = mesh . faces else : if ( verts is None ) or ( faces is None ) : raise Exception ( 'Either mesh or verts and faces must be given' ) surface_area = measure . mesh_surface_area ( verts , faces ) return surface_ar...
r Calculates the surface area of a meshed region
24,525
def show_planes ( im ) : r if sp . squeeze ( im . ndim ) < 3 : raise Exception ( 'This view is only necessary for 3D images' ) x , y , z = ( sp . array ( im . shape ) / 2 ) . astype ( int ) im_xy = im [ : , : , z ] im_xz = im [ : , y , : ] im_yz = sp . rot90 ( im [ x , : , : ] ) new_x = im_xy . shape [ 0 ] + im_yz . sh...
r Create a quick montage showing a 3D image in all three directions
24,526
def sem ( im , direction = 'X' ) : r im = sp . array ( ~ im , dtype = int ) if direction in [ 'Y' , 'y' ] : im = sp . transpose ( im , axes = [ 1 , 0 , 2 ] ) if direction in [ 'Z' , 'z' ] : im = sp . transpose ( im , axes = [ 2 , 1 , 0 ] ) t = im . shape [ 0 ] depth = sp . reshape ( sp . arange ( 0 , t ) , [ t , 1 , 1 ...
r Simulates an SEM photograph looking into the porous material in the specified direction . Features are colored according to their depth into the image so darker features are further away .
24,527
def xray ( im , direction = 'X' ) : r im = sp . array ( ~ im , dtype = int ) if direction in [ 'Y' , 'y' ] : im = sp . transpose ( im , axes = [ 1 , 0 , 2 ] ) if direction in [ 'Z' , 'z' ] : im = sp . transpose ( im , axes = [ 2 , 1 , 0 ] ) im = sp . sum ( im , axis = 0 ) return im
r Simulates an X - ray radiograph looking through the porouls material in the specfied direction . The resulting image is colored according to the amount of attenuation an X - ray would experience so regions with more solid will appear darker .
24,528
def props_to_DataFrame ( regionprops ) : r metrics = [ ] reg = regionprops [ 0 ] for item in reg . __dir__ ( ) : if not item . startswith ( '_' ) : try : if sp . shape ( getattr ( reg , item ) ) == ( ) : metrics . append ( item ) except ( TypeError , NotImplementedError , AttributeError ) : pass d = { } for k in metric...
r Returns a Pandas DataFrame containing all the scalar metrics for each region such as volume sphericity and so on calculated by regionprops_3D .
24,529
def props_to_image ( regionprops , shape , prop ) : r im = sp . zeros ( shape = shape ) for r in regionprops : if prop == 'convex' : mask = r . convex_image else : mask = r . image temp = mask * r [ prop ] s = bbox_to_slices ( r . bbox ) im [ s ] += temp return im
r Creates an image with each region colored according the specified prop as obtained by regionprops_3d .
24,530
def regionprops_3D ( im ) : r print ( '_' * 60 ) print ( 'Calculating regionprops' ) results = regionprops ( im , coordinates = 'xy' ) for i in tqdm ( range ( len ( results ) ) ) : mask = results [ i ] . image mask_padded = sp . pad ( mask , pad_width = 1 , mode = 'constant' ) temp = spim . distance_transform_edt ( mas...
r Calculates various metrics for each labeled region in a 3D image .
24,531
def snow_n ( im , voxel_size = 1 , boundary_faces = [ 'top' , 'bottom' , 'left' , 'right' , 'front' , 'back' ] , marching_cubes_area = False , alias = None ) : r al = _create_alias_map ( im , alias = alias ) snow = snow_partitioning_n ( im , r_max = 4 , sigma = 0.4 , return_all = True , mask = True , randomize = False ...
r Analyzes an image that has been segemented into N phases and extracts all a network for each of the N phases including geometerical information as well as network connectivity between each phase .
24,532
def dict_to_vtk ( data , path = './dictvtk' , voxel_size = 1 , origin = ( 0 , 0 , 0 ) ) : r vs = voxel_size for entry in data : if data [ entry ] . dtype == bool : data [ entry ] = data [ entry ] . astype ( np . int8 ) if data [ entry ] . flags [ 'C_CONTIGUOUS' ] : data [ entry ] = np . ascontiguousarray ( data [ entry...
r Accepts multiple images as a dictionary and compiles them into a vtk file
24,533
def to_openpnm ( net , filename ) : r from openpnm . network import GenericNetwork pn = GenericNetwork ( ) pn . update ( net ) pn . project . save_project ( filename ) ws = pn . project . workspace ws . close_project ( pn . project )
r Save the result of the snow network extraction function in a format suitable for opening in OpenPNM .
24,534
def to_vtk ( im , path = './voxvtk' , divide = False , downsample = False , voxel_size = 1 , vox = False ) : r if len ( im . shape ) == 2 : im = im [ : , : , np . newaxis ] if im . dtype == bool : vox = True if vox : im = im . astype ( np . int8 ) vs = voxel_size if divide : split = np . round ( im . shape [ 2 ] / 2 ) ...
r Converts an array to a vtk file .
24,535
def to_palabos ( im , filename , solid = 0 ) : r bin_im = im == solid bin_im = bin_im . astype ( int ) dt = nd . distance_transform_edt ( bin_im ) dt [ dt > np . sqrt ( 2 ) ] = 2 dt [ ( dt > 0 ) * ( dt <= np . sqrt ( 2 ) ) ] = 1 dt = dt . astype ( int ) with open ( filename , 'w' ) as f : out_data = dt . flatten ( ) . ...
r Converts an ND - array image to a text file that Palabos can read in as a geometry for Lattice Boltzmann simulations . Uses a Euclidean distance transform to identify solid voxels neighboring fluid voxels and labels them as the interface .
24,536
def distance_transform_lin ( im , axis = 0 , mode = 'both' ) : r if im . ndim != im . squeeze ( ) . ndim : warnings . warn ( 'Input image conains a singleton axis:' + str ( im . shape ) + ' Reduce dimensionality with np.squeeze(im) to avoid' + ' unexpected behavior.' ) if mode in [ 'backward' , 'reverse' ] : im = sp . ...
r Replaces each void voxel with the linear distance to the nearest solid voxel along the specified axis .
24,537
def snow_partitioning ( im , dt = None , r_max = 4 , sigma = 0.4 , return_all = False , mask = True , randomize = True ) : r tup = namedtuple ( 'results' , field_names = [ 'im' , 'dt' , 'peaks' , 'regions' ] ) print ( '_' * 60 ) print ( "Beginning SNOW Algorithm" ) im_shape = sp . array ( im . shape ) if im . dtype is ...
r Partitions the void space into pore regions using a marker - based watershed algorithm with specially filtered peaks as markers .
24,538
def snow_partitioning_n ( im , r_max = 4 , sigma = 0.4 , return_all = True , mask = True , randomize = False , alias = None ) : r al = _create_alias_map ( im = im , alias = alias ) phases_num = sp . unique ( im * 1 ) phases_num = sp . trim_zeros ( phases_num ) combined_dt = 0 combined_region = 0 num = [ 0 ] for i in ph...
r This function partitions an imaging oontain an arbitrary number of phases into regions using a marker - based watershed segmentation . Its an extension of snow_partitioning function with all phases partitioned together .
24,539
def find_peaks ( dt , r_max = 4 , footprint = None ) : r im = dt > 0 if im . ndim != im . squeeze ( ) . ndim : warnings . warn ( 'Input image conains a singleton axis:' + str ( im . shape ) + ' Reduce dimensionality with np.squeeze(im) to avoid' + ' unexpected behavior.' ) if footprint is None : if im . ndim == 2 : foo...
r Returns all local maxima in the distance transform
24,540
def reduce_peaks ( peaks ) : r if peaks . ndim == 2 : strel = square else : strel = cube markers , N = spim . label ( input = peaks , structure = strel ( 3 ) ) inds = spim . measurements . center_of_mass ( input = peaks , labels = markers , index = sp . arange ( 1 , N + 1 ) ) inds = sp . floor ( inds ) . astype ( int )...
r Any peaks that are broad or elongated are replaced with a single voxel that is located at the center of mass of the original voxels .
24,541
def trim_saddle_points ( peaks , dt , max_iters = 10 ) : r peaks = sp . copy ( peaks ) if dt . ndim == 2 : from skimage . morphology import square as cube else : from skimage . morphology import cube labels , N = spim . label ( peaks ) slices = spim . find_objects ( labels ) for i in range ( N ) : s = extend_slice ( s ...
r Removes peaks that were mistakenly identified because they lied on a saddle or ridge in the distance transform that was not actually a true local peak .
24,542
def trim_nearby_peaks ( peaks , dt ) : r peaks = sp . copy ( peaks ) if dt . ndim == 2 : from skimage . morphology import square as cube else : from skimage . morphology import cube peaks , N = spim . label ( peaks , structure = cube ( 3 ) ) crds = spim . measurements . center_of_mass ( peaks , labels = peaks , index =...
r Finds pairs of peaks that are nearer to each other than to the solid phase and removes the peak that is closer to the solid .
24,543
def fill_blind_pores ( im ) : r im = sp . copy ( im ) holes = find_disconnected_voxels ( im ) im [ holes ] = False return im
r Fills all pores that are not connected to the edges of the image .
24,544
def trim_floating_solid ( im ) : r im = sp . copy ( im ) holes = find_disconnected_voxels ( ~ im ) im [ holes ] = True return im
r Removes all solid that that is not attached to the edges of the image .
24,545
def trim_nonpercolating_paths ( im , inlet_axis = 0 , outlet_axis = 0 ) : r if im . ndim != im . squeeze ( ) . ndim : warnings . warn ( 'Input image conains a singleton axis:' + str ( im . shape ) + ' Reduce dimensionality with np.squeeze(im) to avoid' + ' unexpected behavior.' ) im = trim_floating_solid ( ~ im ) label...
r Removes all nonpercolating paths between specified edges
24,546
def trim_extrema ( im , h , mode = 'maxima' ) : r result = im if mode in [ 'maxima' , 'extrema' ] : result = reconstruction ( seed = im - h , mask = im , method = 'dilation' ) elif mode in [ 'minima' , 'extrema' ] : result = reconstruction ( seed = im + h , mask = im , method = 'erosion' ) return result
r Trims local extrema in greyscale values by a specified amount .
24,547
def find_dt_artifacts ( dt ) : r temp = sp . ones ( shape = dt . shape ) * sp . inf for ax in range ( dt . ndim ) : dt_lin = distance_transform_lin ( sp . ones_like ( temp , dtype = bool ) , axis = ax , mode = 'both' ) temp = sp . minimum ( temp , dt_lin ) result = sp . clip ( dt - temp , a_min = 0 , a_max = sp . inf )...
r Finds points in a distance transform that are closer to wall than solid .
24,548
def region_size ( im ) : r if im . dtype == bool : im = spim . label ( im ) [ 0 ] counts = sp . bincount ( im . flatten ( ) ) counts [ 0 ] = 0 chords = counts [ im ] return chords
r Replace each voxel with size of region to which it belongs
24,549
def apply_chords ( im , spacing = 1 , axis = 0 , trim_edges = True , label = False ) : r if im . ndim != im . squeeze ( ) . ndim : warnings . warn ( 'Input image conains a singleton axis:' + str ( im . shape ) + ' Reduce dimensionality with np.squeeze(im) to avoid' + ' unexpected behavior.' ) if spacing < 0 : raise Exc...
r Adds chords to the void space in the specified direction . The chords are separated by 1 voxel plus the provided spacing .
24,550
def apply_chords_3D ( im , spacing = 0 , trim_edges = True ) : r if im . ndim != im . squeeze ( ) . ndim : warnings . warn ( 'Input image conains a singleton axis:' + str ( im . shape ) + ' Reduce dimensionality with np.squeeze(im) to avoid' + ' unexpected behavior.' ) if im . ndim < 3 : raise Exception ( 'Must be a 3D...
r Adds chords to the void space in all three principle directions . The chords are seprated by 1 voxel plus the provided spacing . Chords in the X Y and Z directions are labelled 1 2 and 3 resepctively .
24,551
def porosimetry ( im , sizes = 25 , inlets = None , access_limited = True , mode = 'hybrid' ) : r if im . ndim != im . squeeze ( ) . ndim : warnings . warn ( 'Input image conains a singleton axis:' + str ( im . shape ) + ' Reduce dimensionality with np.squeeze(im) to avoid' + ' unexpected behavior.' ) dt = spim . dista...
r Performs a porosimetry simulution on the image
24,552
def trim_disconnected_blobs ( im , inlets ) : r temp = sp . zeros_like ( im ) temp [ inlets ] = True labels , N = spim . label ( im + temp ) im = im ^ ( clear_border ( labels = labels ) > 0 ) return im
r Removes foreground voxels not connected to specified inlets
24,553
def _make_stack ( im , include_diagonals = False ) : r ndim = len ( np . shape ( im ) ) axial_shift = _get_axial_shifts ( ndim , include_diagonals ) if ndim == 2 : stack = np . zeros ( [ np . shape ( im ) [ 0 ] , np . shape ( im ) [ 1 ] , len ( axial_shift ) + 1 ] ) stack [ : , : , 0 ] = im for i in range ( len ( axial...
r Creates a stack of images with one extra dimension to the input image with length equal to the number of borders to search + 1 . Image is rolled along the axial shifts so that the border pixel is overlapping the original pixel . First image in stack is the original . Stacking makes direct vectorized array comparisons...
24,554
def map_to_regions ( regions , values ) : r values = sp . array ( values ) . flatten ( ) if sp . size ( values ) != regions . max ( ) + 1 : raise Exception ( 'Number of values does not match number of regions' ) im = sp . zeros_like ( regions ) im = values [ regions ] return im
r Maps pore values from a network onto the image from which it was extracted
24,555
def label_boundary_cells ( network = None , boundary_faces = None ) : r f = boundary_faces if f is not None : coords = network [ 'pore.coords' ] condition = coords [ ~ network [ 'pore.boundary' ] ] dic = { 'left' : 0 , 'right' : 0 , 'front' : 1 , 'back' : 1 , 'top' : 2 , 'bottom' : 2 } if all ( coords [ : , 2 ] == 0 ) ...
r Takes 2D or 3D network and assign labels to boundary pores
24,556
def insert_shape ( im , element , center = None , corner = None , value = 1 , mode = 'overwrite' ) : r im = im . copy ( ) if im . ndim != element . ndim : raise Exception ( 'Image shape ' + str ( im . shape ) + ' and element shape ' + str ( element . shape ) + ' do not match' ) s_im = [ ] s_el = [ ] if ( center is not ...
r Inserts sub - image into a larger image at the specified location .
24,557
def bundle_of_tubes ( shape : List [ int ] , spacing : int ) : r shape = sp . array ( shape ) if sp . size ( shape ) == 1 : shape = sp . full ( ( 3 , ) , int ( shape ) ) if sp . size ( shape ) == 2 : shape = sp . hstack ( ( shape , [ 1 ] ) ) temp = sp . zeros ( shape = shape [ : 2 ] ) Xi = sp . ceil ( sp . linspace ( s...
r Create a 3D image of a bundle of tubes in the form of a rectangular plate with randomly sized holes through it .
24,558
def polydisperse_spheres ( shape : List [ int ] , porosity : float , dist , nbins : int = 5 , r_min : int = 5 ) : r shape = sp . array ( shape ) if sp . size ( shape ) == 1 : shape = sp . full ( ( 3 , ) , int ( shape ) ) Rs = dist . interval ( sp . linspace ( 0.05 , 0.95 , nbins ) ) Rs = sp . vstack ( Rs ) . T Rs = ( R...
r Create an image of randomly place overlapping spheres with a distribution of radii .
24,559
def _get_Voronoi_edges ( vor ) : r edges = [ [ ] , [ ] ] for facet in vor . ridge_vertices : edges [ 0 ] . extend ( facet [ : - 1 ] + [ facet [ - 1 ] ] ) edges [ 1 ] . extend ( facet [ 1 : ] + [ facet [ 0 ] ] ) edges = sp . vstack ( edges ) . T mask = sp . any ( edges == - 1 , axis = 1 ) edges = edges [ ~ mask ] edges ...
r Given a Voronoi object as produced by the scipy . spatial . Voronoi class this function calculates the start and end points of eeach edge in the Voronoi diagram in terms of the vertex indices used by the received Voronoi object .
24,560
def overlapping_spheres ( shape : List [ int ] , radius : int , porosity : float , iter_max : int = 10 , tol : float = 0.01 ) : r shape = sp . array ( shape ) if sp . size ( shape ) == 1 : shape = sp . full ( ( 3 , ) , int ( shape ) ) ndim = ( shape != 1 ) . sum ( ) s_vol = ps_disk ( radius ) . sum ( ) if ndim == 2 els...
r Generate a packing of overlapping mono - disperse spheres
24,561
def generate_noise ( shape : List [ int ] , porosity = None , octaves : int = 3 , frequency : int = 32 , mode : str = 'simplex' ) : r try : import noise except ModuleNotFoundError : raise Exception ( "The noise package must be installed" ) shape = sp . array ( shape ) if sp . size ( shape ) == 1 : Lx , Ly , Lz = sp . f...
r Generate a field of spatially correlated random noise using the Perlin noise algorithm or the updated Simplex noise algorithm .
24,562
def blobs ( shape : List [ int ] , porosity : float = 0.5 , blobiness : int = 1 ) : blobiness = sp . array ( blobiness ) shape = sp . array ( shape ) if sp . size ( shape ) == 1 : shape = sp . full ( ( 3 , ) , int ( shape ) ) sigma = sp . mean ( shape ) / ( 40 * blobiness ) im = sp . random . random ( shape ) im = spim...
Generates an image containing amorphous blobs
24,563
def cylinders ( shape : List [ int ] , radius : int , ncylinders : int , phi_max : float = 0 , theta_max : float = 90 ) : r shape = sp . array ( shape ) if sp . size ( shape ) == 1 : shape = sp . full ( ( 3 , ) , int ( shape ) ) elif sp . size ( shape ) == 2 : raise Exception ( "2D cylinders don't make sense" ) R = sp ...
r Generates a binary image of overlapping cylinders . This is a good approximation of a fibrous mat .
24,564
def line_segment ( X0 , X1 ) : r X0 = sp . around ( X0 ) . astype ( int ) X1 = sp . around ( X1 ) . astype ( int ) if len ( X0 ) == 3 : L = sp . amax ( sp . absolute ( [ [ X1 [ 0 ] - X0 [ 0 ] ] , [ X1 [ 1 ] - X0 [ 1 ] ] , [ X1 [ 2 ] - X0 [ 2 ] ] ] ) ) + 1 x = sp . rint ( sp . linspace ( X0 [ 0 ] , X1 [ 0 ] , L ) ) . as...
r Calculate the voxel coordinates of a straight line between the two given end points
24,565
def _remove_edge ( im , r ) : r edge = sp . ones_like ( im ) if len ( im . shape ) == 2 : sx , sy = im . shape edge [ r : sx - r , r : sy - r ] = im [ r : sx - r , r : sy - r ] else : sx , sy , sz = im . shape edge [ r : sx - r , r : sy - r , r : sz - r ] = im [ r : sx - r , r : sy - r , r : sz - r ] return edge
r Fill in the edges of the input image . Used by RSA to ensure that no elements are placed too close to the edge .
24,566
def align_image_with_openpnm ( im ) : r if im . ndim != im . squeeze ( ) . ndim : warnings . warn ( 'Input image conains a singleton axis:' + str ( im . shape ) + ' Reduce dimensionality with np.squeeze(im) to avoid' + ' unexpected behavior.' ) im = sp . copy ( im ) if im . ndim == 2 : im = ( sp . swapaxes ( im , 1 , 0...
r Rotates an image to agree with the coordinates used in OpenPNM . It is unclear why they are not in agreement to start with . This is necessary for overlaying the image and the network in Paraview .
24,567
def fftmorphology ( im , strel , mode = 'opening' ) : r def erode ( im , strel ) : t = fftconvolve ( im , strel , mode = 'same' ) > ( strel . sum ( ) - 0.1 ) return t def dilate ( im , strel ) : t = fftconvolve ( im , strel , mode = 'same' ) > 0.1 return t if im . ndim != im . squeeze ( ) . ndim : warnings . warn ( 'In...
r Perform morphological operations on binary images using fft approach for improved performance
24,568
def subdivide ( im , divs = 2 ) : r if isinstance ( divs , int ) : divs = [ divs for i in range ( im . ndim ) ] s = shape_split ( im . shape , axis = divs ) return s
r Returns slices into an image describing the specified number of sub - arrays .
24,569
def bbox_to_slices ( bbox ) : r if len ( bbox ) == 4 : ret = ( slice ( bbox [ 0 ] , bbox [ 2 ] ) , slice ( bbox [ 1 ] , bbox [ 3 ] ) ) else : ret = ( slice ( bbox [ 0 ] , bbox [ 3 ] ) , slice ( bbox [ 1 ] , bbox [ 4 ] ) , slice ( bbox [ 2 ] , bbox [ 5 ] ) ) return ret
r Given a tuple containing bounding box coordinates return a tuple of slice objects .
24,570
def get_slice ( im , center , size , pad = 0 ) : r p = sp . ones ( shape = im . ndim , dtype = int ) * sp . array ( pad ) s = sp . ones ( shape = im . ndim , dtype = int ) * sp . array ( size ) slc = [ ] for dim in range ( im . ndim ) : lower_im = sp . amax ( ( center [ dim ] - s [ dim ] - p [ dim ] , 0 ) ) upper_im = ...
r Given a center location and radius of a feature returns the slice object into the im that bounds the feature but does not extend beyond the image boundaries .
24,571
def find_outer_region ( im , r = 0 ) : r if r == 0 : dt = spim . distance_transform_edt ( input = im ) r = int ( sp . amax ( dt ) ) * 2 im_padded = sp . pad ( array = im , pad_width = r , mode = 'constant' , constant_values = True ) dt = spim . distance_transform_edt ( input = im_padded ) seeds = ( dt >= r ) + get_bord...
r Finds regions of the image that are outside of the solid matrix .
24,572
def extract_cylinder ( im , r = None , axis = 0 ) : r if r is None : a = list ( im . shape ) a . pop ( axis ) r = sp . floor ( sp . amin ( a ) / 2 ) dim = [ range ( int ( - s / 2 ) , int ( s / 2 ) + s % 2 ) for s in im . shape ] inds = sp . meshgrid ( * dim , indexing = 'ij' ) inds [ axis ] = inds [ axis ] * 0 d = sp ....
r Returns a cylindrical section of the image of specified radius .
24,573
def extract_subsection ( im , shape ) : r shape = sp . array ( shape ) if shape [ 0 ] < 1 : shape = sp . array ( im . shape ) * shape center = sp . array ( im . shape ) / 2 s_im = [ ] for dim in range ( im . ndim ) : r = shape [ dim ] / 2 lower_im = sp . amax ( ( center [ dim ] - r , 0 ) ) upper_im = sp . amin ( ( cent...
r Extracts the middle section of a image
24,574
def get_planes ( im , squeeze = True ) : r x , y , z = ( sp . array ( im . shape ) / 2 ) . astype ( int ) planes = [ im [ x , : , : ] , im [ : , y , : ] , im [ : , : , z ] ] if not squeeze : imx = planes [ 0 ] planes [ 0 ] = sp . reshape ( imx , [ 1 , imx . shape [ 0 ] , imx . shape [ 1 ] ] ) imy = planes [ 1 ] planes ...
r Extracts three planar images from the volumetric image one for each principle axis . The planes are taken from the middle of the domain .
24,575
def extend_slice ( s , shape , pad = 1 ) : r pad = int ( pad ) a = [ ] for i , dim in zip ( s , shape ) : start = 0 stop = dim if i . start - pad >= 0 : start = i . start - pad if i . stop + pad < dim : stop = i . stop + pad a . append ( slice ( start , stop , None ) ) return tuple ( a )
r Adjust slice indices to include additional voxles around the slice .
24,576
def randomize_colors ( im , keep_vals = [ 0 ] ) : r im_flat = im . flatten ( ) keep_vals = sp . array ( keep_vals ) swap_vals = ~ sp . in1d ( im_flat , keep_vals ) im_vals = sp . unique ( im_flat [ swap_vals ] ) new_vals = sp . random . permutation ( im_vals ) im_map = sp . zeros ( shape = [ sp . amax ( im_vals ) + 1 ,...
r Takes a greyscale image and randomly shuffles the greyscale values so that all voxels labeled X will be labelled Y and all voxels labeled Y will be labeled Z where X Y Z and so on are randomly selected from the values in the input image .
24,577
def make_contiguous ( im , keep_zeros = True ) : r im = sp . copy ( im ) if keep_zeros : mask = ( im == 0 ) im [ mask ] = im . min ( ) - 1 im = im - im . min ( ) im_flat = im . flatten ( ) im_vals = sp . unique ( im_flat ) im_map = sp . zeros ( shape = sp . amax ( im_flat ) + 1 ) im_map [ im_vals ] = sp . arange ( 0 , ...
r Take an image with arbitrary greyscale values and adjust them to ensure all values fall in a contiguous range starting at 0 .
24,578
def get_border ( shape , thickness = 1 , mode = 'edges' , return_indices = False ) : r ndims = len ( shape ) t = thickness border = sp . ones ( shape , dtype = bool ) if mode == 'faces' : if ndims == 2 : border [ t : - t , t : - t ] = False if ndims == 3 : border [ t : - t , t : - t , t : - t ] = False elif mode == 'ed...
r Creates an array of specified size with corners edges or faces labelled as True . This can be used as mask to manipulate values laying on the perimeter of an image .
24,579
def in_hull ( points , hull ) : from scipy . spatial import Delaunay , ConvexHull if isinstance ( hull , ConvexHull ) : hull = hull . points hull = Delaunay ( hull ) return hull . find_simplex ( points ) >= 0
Test if a list of coordinates are inside a given convex hull
24,580
def functions_to_table ( mod , colwidth = [ 27 , 48 ] ) : r temp = mod . __dir__ ( ) funcs = [ i for i in temp if not i [ 0 ] . startswith ( '_' ) ] funcs . sort ( ) row = '+' + '-' * colwidth [ 0 ] + '+' + '-' * colwidth [ 1 ] + '+' fmt = '{0:1s} {1:' + str ( colwidth [ 0 ] - 2 ) + 's} {2:1s} {3:' + str ( colwidth [ 1...
r Given a module of functions returns a ReST formatted text string that outputs a table when printed .
24,581
def mesh_region ( region : bool , strel = None ) : r im = region if im . ndim != im . squeeze ( ) . ndim : warnings . warn ( 'Input image conains a singleton axis:' + str ( im . shape ) + ' Reduce dimensionality with np.squeeze(im) to avoid' + ' unexpected behavior.' ) if strel is None : if region . ndim == 3 : strel =...
r Creates a tri - mesh of the provided region using the marching cubes algorithm
24,582
def ps_disk ( radius ) : r rad = int ( sp . ceil ( radius ) ) other = sp . ones ( ( 2 * rad + 1 , 2 * rad + 1 ) , dtype = bool ) other [ rad , rad ] = False disk = spim . distance_transform_edt ( other ) < radius return disk
r Creates circular disk structuring element for morphological operations
24,583
def ps_ball ( radius ) : r rad = int ( sp . ceil ( radius ) ) other = sp . ones ( ( 2 * rad + 1 , 2 * rad + 1 , 2 * rad + 1 ) , dtype = bool ) other [ rad , rad , rad ] = False ball = spim . distance_transform_edt ( other ) < radius return ball
r Creates spherical ball structuring element for morphological operations
24,584
def overlay ( im1 , im2 , c ) : r shape = im2 . shape for ni in shape : if ni % 2 == 0 : raise Exception ( "Structuring element must be odd-voxeled..." ) nx , ny , nz = [ ( ni - 1 ) // 2 for ni in shape ] cx , cy , cz = c im1 [ cx - nx : cx + nx + 1 , cy - ny : cy + ny + 1 , cz - nz : cz + nz + 1 ] += im2 return im1
r Overlays im2 onto im1 given voxel coords of center of im2 in im1 .
24,585
def insert_sphere ( im , c , r ) : r c = sp . array ( c , dtype = int ) if c . size != im . ndim : raise Exception ( 'Coordinates do not match dimensionality of image' ) bbox = [ ] [ bbox . append ( sp . clip ( c [ i ] - r , 0 , im . shape [ i ] ) ) for i in range ( im . ndim ) ] [ bbox . append ( sp . clip ( c [ i ] +...
r Inserts a sphere of a specified radius into a given image
24,586
def insert_cylinder ( im , xyz0 , xyz1 , r ) : r if im . ndim != 3 : raise Exception ( 'This function is only implemented for 3D images' ) xyz0 , xyz1 = [ sp . array ( xyz ) . astype ( int ) for xyz in ( xyz0 , xyz1 ) ] r = int ( r ) L = sp . absolute ( xyz0 - xyz1 ) . max ( ) + 1 xyz_line = [ sp . linspace ( xyz0 [ i ...
r Inserts a cylinder of given radius onto a given image
24,587
def pad_faces ( im , faces ) : r if im . ndim != im . squeeze ( ) . ndim : warnings . warn ( 'Input image conains a singleton axis:' + str ( im . shape ) + ' Reduce dimensionality with np.squeeze(im) to avoid' + ' unexpected behavior.' ) f = faces if f is not None : if im . ndim == 2 : faces = [ ( int ( 'left' in f ) *...
r Pads the input image at specified faces . This shape of image is same as the output image of add_boundary_regions function .
24,588
def _create_alias_map ( im , alias = None ) : r phases_num = sp . unique ( im * 1 ) phases_num = sp . trim_zeros ( phases_num ) al = { } for values in phases_num : al [ values ] = 'phase{}' . format ( values ) if alias is not None : alias_sort = dict ( sorted ( alias . items ( ) ) ) phase_labels = sp . array ( [ * alia...
r Creates an alias mapping between phases in original image and identifyable names . This mapping is used during network extraction to label interconnection between and properties of each phase .
24,589
def _filehash ( filepath , blocksize = 4096 ) : sha = hashlib . sha256 ( ) with open ( filepath , 'rb' ) as fp : while 1 : data = fp . read ( blocksize ) if data : sha . update ( data ) else : break return sha
Return the hash object for the file filepath processing the file by chunk of blocksize .
24,590
def compress_to ( self , archive_path = None ) : if archive_path is None : archive = tempfile . NamedTemporaryFile ( delete = False ) tar_args = ( ) tar_kwargs = { 'fileobj' : archive } _return = archive . name else : tar_args = ( archive_path ) tar_kwargs = { } _return = archive_path tar_kwargs . update ( { 'mode' : '...
Compress the directory with gzip using tarlib .
24,591
def iterfiles ( self , pattern = None , abspath = False ) : if pattern is not None : globster = Globster ( [ pattern ] ) for root , dirs , files in self . walk ( ) : for f in files : if pattern is None or ( pattern is not None and globster . match ( f ) ) : if abspath : yield os . path . join ( root , f ) else : yield ...
Generator for all the files not excluded recursively .
24,592
def size ( self ) : dir_size = 0 for f in self . iterfiles ( abspath = True ) : dir_size += os . path . getsize ( f ) return dir_size
Return directory size in bytes .
24,593
def is_excluded ( self , path ) : match = self . globster . match ( self . relpath ( path ) ) if match : log . debug ( "{0} matched {1} for exclusion" . format ( path , match ) ) return True return False
Return True if path should be excluded given patterns in the exclude_file .
24,594
def find_projects ( self , file_identifier = ".project" ) : projects = [ ] for d in self . subdirs ( ) : project_file = os . path . join ( self . directory , d , file_identifier ) if os . path . isfile ( project_file ) : projects . append ( d ) return projects
Search all directory recursively for subdirs with file_identifier in it .
24,595
def relpath ( self , path ) : return os . path . relpath ( path , start = self . path )
Return a relative filepath to path from Dir path .
24,596
def compute_state ( self ) : data = { } data [ 'directory' ] = self . _dir . path data [ 'files' ] = list ( self . _dir . files ( ) ) data [ 'subdirs' ] = list ( self . _dir . subdirs ( ) ) data [ 'index' ] = self . index ( ) return data
Generate the index .
24,597
def basic_auth_required ( view_func ) : @ wraps ( view_func ) def wrapper ( * args , ** kwargs ) : if app . config . get ( 'BASIC_AUTH_ACTIVE' , False ) : if basic_auth . authenticate ( ) : return view_func ( * args , ** kwargs ) else : return basic_auth . challenge ( ) else : return view_func ( * args , ** kwargs ) re...
A decorator that can be used to protect specific views with HTTP basic access authentication . Conditional on having BASIC_AUTH_USERNAME and BASIC_AUTH_PASSWORD set as env vars .
24,598
def badge ( pipeline_id ) : if not pipeline_id . startswith ( './' ) : pipeline_id = './' + pipeline_id pipeline_status = status . get ( pipeline_id ) status_color = 'lightgray' if pipeline_status . pipeline_details : status_text = pipeline_status . state ( ) . lower ( ) last_execution = pipeline_status . get_last_exec...
An individual pipeline status
24,599
def badge_collection ( pipeline_path ) : all_pipeline_ids = sorted ( status . all_pipeline_ids ( ) ) if not pipeline_path . startswith ( './' ) : pipeline_path = './' + pipeline_path path_pipeline_ids = [ p for p in all_pipeline_ids if p . startswith ( pipeline_path ) ] statuses = [ ] for pipeline_id in path_pipeline_i...
Status badge for a collection of pipelines .