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 = list ( arguments ) kargs = { } for r , p , d in zip ( raw_params , params , defaults ) : if arguments : val = arguments . pop ( 0 ) click . echo ( "{}: {}" . format ( p , val ) ) kargs [ r ] = val elif safe : if d : kargs [ r ] = d else : p_default = d if d else None val = click . prompt ( "Enter value for '{}'" . format ( p ) , default = p_default ) kargs [ r ] = val click . echo ( "\n" ) final_cmd = utils . substitute_pcmd ( pcmd , kargs , safe ) command = "$ {} :: {}" . format ( final_cmd , desc ) if click . confirm ( "Execute\n\t{}\n\n?" . format ( command ) , default = True ) : os . system ( final_cmd ) elif matches == [ ] : click . echo ( 'No saved commands matches the pattern {}' . format ( pattern ) ) else : click . echo ( "No commands to run, Add one by 'keep new'. " ) | 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 to show. Add one by `keep new`.' ) | 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 ( update_check_file , 'r' ) . read ( ) else : date = [ ] if forced or today != date : ctx . update_checked = True date = today with open ( update_check_file , 'w' ) as f : f . write ( date ) r = requests . get ( "https://pypi.org/pypi/keep/json" ) . json ( ) version = r [ 'info' ] [ 'version' ] curr_version = about . __version__ if version > curr_version : click . secho ( "Keep seems to be outdated. Current version = " "{}, Latest version = {}" . format ( curr_version , version ) + "\n\nPlease update with " , bold = True , fg = 'red' ) click . secho ( "\tpip3 --no-cache-dir install -U keep==" + str ( version ) , fg = 'green' ) click . secho ( "\n\n" ) | 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_commands != commands : click . echo ( "Replace:\n" ) click . secho ( "\t{}" . format ( '\n\t' . join ( utils . format_commands ( commands ) ) ) , fg = "green" ) click . echo ( "With:\n\t" ) click . secho ( "\t{}" . format ( '\n\t' . join ( utils . format_commands ( new_commands ) ) ) , fg = "green" ) if click . confirm ( "" , default = False ) : utils . write_commands ( new_commands ) | 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 . remove_command ( cmd ) click . echo ( 'Command successfully removed!' ) elif matches == [ ] : click . echo ( 'No saved commands matches the pattern {}' . format ( pattern ) ) else : click . echo ( "No commands to remove, Add one by 'keep new'. " ) | 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 . set_xlabel ( "x-axis" ) ax . set_ylabel ( "y-axis" ) ax . set_zlabel ( "z-axis" ) ax . set_xlim ( lim_min [ 0 ] , lim_max [ 0 ] ) ax . set_ylim ( lim_min [ 1 ] , lim_max [ 1 ] ) ax . set_zlim ( lim_min [ 2 ] , lim_max [ 2 ] ) return fig | 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 , N = spim . label ( input = im_temp ) slices = spim . find_objects ( input = labels ) porosity = sp . zeros ( shape = ( N , ) , dtype = float ) volume = sp . zeros ( shape = ( N , ) , dtype = int ) for i in tqdm ( sp . arange ( 0 , N ) ) : s = slices [ i ] p = pads [ i ] new_s = extend_slice ( s , shape = im . shape , pad = p ) temp = im [ new_s ] Vp = sp . sum ( temp ) Vt = sp . size ( temp ) porosity [ i ] = Vp / Vt volume [ i ] = Vt profile = namedtuple ( 'profile' , ( 'volume' , 'porosity' ) ) profile . volume = volume profile . porosity = porosity return profile | 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 prof * 100 | 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 . shape , [ 3 , 1 , 1 , 1 ] ) inds = sp . indices ( autocorr . shape ) - adj / 2 dt = sp . sqrt ( inds [ 0 ] ** 2 + inds [ 1 ] ** 2 + inds [ 2 ] ** 2 ) else : raise Exception ( 'Image dimensions must be 2 or 3' ) bin_size = np . int ( np . ceil ( r_max / nbins ) ) bins = np . arange ( bin_size , r_max , step = bin_size ) radial_sum = np . zeros_like ( bins ) for i , r in enumerate ( bins ) : mask = ( dt <= r ) * ( dt > ( r - bin_size ) ) radial_sum [ i ] = np . sum ( autocorr [ mask ] ) / np . sum ( mask ) norm_autoc_radial = radial_sum / np . max ( autocorr ) tpcf = namedtuple ( 'two_point_correlation_function' , ( 'distance' , 'probability' ) ) return tpcf ( bins , norm_autoc_radial ) | 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_max = np . min ( hls ) ) return tpcf | 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' , 'pdf' , 'cdf' , 'satn' , 'bin_centers' , 'bin_edges' , 'bin_widths' ) ) return psd ( h . bin_centers , h . pdf , h . cdf , h . relfreq , h . bin_centers , h . bin_edges , h . bin_widths ) | 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 . histogram ( x , bins = bins , density = False ) ) h [ 0 ] = h [ 0 ] * ( h [ 1 ] [ 1 : ] + h [ 1 ] [ : - 1 ] ) / 2 h [ 0 ] = h [ 0 ] / h [ 0 ] . sum ( ) / ( h [ 1 ] [ 1 : ] - h [ 1 ] [ : - 1 ] ) elif normalization in [ 'number' , 'count' ] : h = sp . histogram ( x , bins = bins , density = True ) else : raise Exception ( 'Unsupported normalization:' , normalization ) h = _parse_histogram ( h ) cld = namedtuple ( 'chord_length_distribution' , ( log * 'log' + 'L' , 'pdf' , 'cdf' , 'relfreq' , 'bin_centers' , 'bin_edges' , 'bin_widths' ) ) return cld ( h . bin_centers , h . pdf , h . cdf , h . relfreq , h . bin_centers , h . bin_edges , h . bin_widths ) | 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 conains a singleton axis:' + str ( im . shape ) + ' Reduce dimensionality with np.squeeze(im) to avoid' + ' unexpected behavior.' ) if im . ndim == 2 : cube = square ball = disk slices = spim . find_objects ( im ) Ps = sp . arange ( 1 , sp . amax ( im ) + 1 ) sa = sp . zeros_like ( Ps , dtype = float ) sa_combined = [ ] cn = [ ] for i in tqdm ( Ps ) : reg = i - 1 if slices [ reg ] is not None : s = extend_slice ( slices [ reg ] , im . shape ) sub_im = im [ s ] mask_im = sub_im == i sa [ reg ] = areas [ reg ] im_w_throats = spim . binary_dilation ( input = mask_im , structure = ball ( 1 ) ) im_w_throats = im_w_throats * sub_im Pn = sp . unique ( im_w_throats ) [ 1 : ] - 1 for j in Pn : if j > reg : cn . append ( [ reg , j ] ) merged_region = im [ ( min ( slices [ reg ] [ 0 ] . start , slices [ j ] [ 0 ] . start ) ) : max ( slices [ reg ] [ 0 ] . stop , slices [ j ] [ 0 ] . stop ) , ( min ( slices [ reg ] [ 1 ] . start , slices [ j ] [ 1 ] . start ) ) : max ( slices [ reg ] [ 1 ] . stop , slices [ j ] [ 1 ] . stop ) ] merged_region = ( ( merged_region == reg + 1 ) + ( merged_region == j + 1 ) ) mesh = mesh_region ( region = merged_region , strel = strel ) sa_combined . append ( mesh_surface_area ( mesh ) ) cn = sp . array ( cn ) ia = 0.5 * ( sa [ cn [ : , 0 ] ] + sa [ cn [ : , 1 ] ] - sa_combined ) ia [ ia <= 0 ] = 1 result = namedtuple ( 'interfacial_areas' , ( 'conns' , 'area' ) ) result . conns = cn result . area = ia * voxel_size ** 2 return result | 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 - 1 if slices [ reg ] is not None : s = extend_slice ( slices [ reg ] , im . shape ) sub_im = im [ s ] mask_im = sub_im == i mesh = mesh_region ( region = mask_im , strel = strel ) sa [ reg ] = mesh_surface_area ( mesh ) result = sa * voxel_size ** 2 return result | 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_area | 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 . shape [ 0 ] + 10 new_y = im_xy . shape [ 1 ] + im_xz . shape [ 1 ] + 10 new_im = sp . zeros ( [ new_x + 20 , new_y + 20 ] , dtype = im . dtype ) new_im [ 10 : im_xy . shape [ 0 ] + 10 , 10 : im_xy . shape [ 1 ] + 10 ] = im_xy x_off = im_xy . shape [ 0 ] + 20 y_off = im_xy . shape [ 1 ] + 20 new_im [ 10 : 10 + im_xz . shape [ 0 ] , y_off : y_off + im_xz . shape [ 1 ] ] = im_xz new_im [ x_off : x_off + im_yz . shape [ 0 ] , 10 : 10 + im_yz . shape [ 1 ] ] = im_yz return new_im | 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 ] ) im = im * depth im = sp . amax ( im , axis = 0 ) return im | 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 metrics : try : d [ k ] = sp . array ( [ r [ k ] for r in regionprops ] ) except ValueError : print ( 'Error encountered evaluating ' + k + ' so skipping it' ) df = DataFrame ( d ) return df | 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 ( mask_padded ) dt = extract_subsection ( temp , shape = mask . shape ) results [ i ] . slice = results [ i ] . _slice results [ i ] . volume = results [ i ] . area results [ i ] . bbox_volume = sp . prod ( mask . shape ) results [ i ] . border = dt == 1 r = dt . max ( ) inv_dt = spim . distance_transform_edt ( dt < r ) results [ i ] . inscribed_sphere = inv_dt < r tmp = sp . pad ( sp . atleast_3d ( mask ) , pad_width = 1 , mode = 'constant' ) tmp = spim . convolve ( tmp , weights = ball ( 1 ) ) / 5 verts , faces , norms , vals = marching_cubes_lewiner ( volume = tmp , level = 0 ) results [ i ] . surface_mesh_vertices = verts results [ i ] . surface_mesh_simplices = faces area = mesh_surface_area ( verts , faces ) results [ i ] . surface_area = area vol = results [ i ] . volume r = ( 3 / 4 / sp . pi * vol ) ** ( 1 / 3 ) a_equiv = 4 * sp . pi * ( r ) ** 2 a_region = results [ i ] . surface_area results [ i ] . sphericity = a_equiv / a_region results [ i ] . skeleton = skeletonize_3d ( mask ) results [ i ] . convex_volume = results [ i ] . convex_area return results | 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 , alias = al ) f = boundary_faces regions = add_boundary_regions ( regions = snow . regions , faces = f ) dt = pad_faces ( im = snow . dt , faces = f ) phases_num = sp . unique ( im ) . astype ( int ) phases_num = sp . trim_zeros ( phases_num ) if len ( phases_num ) == 1 : if f is not None : snow . im = pad_faces ( im = snow . im , faces = f ) regions = regions * ( snow . im . astype ( bool ) ) regions = make_contiguous ( regions ) net = regions_to_network ( im = regions , dt = dt , voxel_size = voxel_size ) if marching_cubes_area : areas = region_surface_areas ( regions = regions ) interface_area = region_interface_areas ( regions = regions , areas = areas , voxel_size = voxel_size ) net [ 'pore.surface_area' ] = areas * voxel_size ** 2 net [ 'throat.area' ] = interface_area . area net = add_phase_interconnections ( net = net , snow_partitioning_n = snow , marching_cubes_area = marching_cubes_area , alias = al ) net = label_boundary_cells ( network = net , boundary_faces = f ) temp = _net_dict ( net ) temp . im = im . copy ( ) temp . dt = dt temp . regions = regions return temp | 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 ] ) imageToVTK ( path , cellData = data , spacing = ( vs , vs , vs ) , origin = origin ) | 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 ) . astype ( np . int ) im1 = im [ : , : , 0 : split ] im2 = im [ : , : , split : ] imageToVTK ( path + '1' , cellData = { 'im' : np . ascontiguousarray ( im1 ) } , spacing = ( vs , vs , vs ) ) imageToVTK ( path + '2' , origin = ( 0.0 , 0.0 , split * vs ) , cellData = { 'im' : np . ascontiguousarray ( im2 ) } , spacing = ( vs , vs , vs ) ) elif downsample : im = spim . interpolation . zoom ( im , zoom = 0.5 , order = 0 , mode = 'reflect' ) imageToVTK ( path , cellData = { 'im' : np . ascontiguousarray ( im ) } , spacing = ( 2 * vs , 2 * vs , 2 * vs ) ) else : imageToVTK ( path , cellData = { 'im' : np . ascontiguousarray ( im ) } , spacing = ( vs , vs , vs ) ) | 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 ( ) . tolist ( ) f . write ( '\n' . join ( map ( repr , out_data ) ) ) | 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 . flip ( im , axis ) im = distance_transform_lin ( im = im , axis = axis , mode = 'forward' ) im = sp . flip ( im , axis ) return im elif mode in [ 'both' ] : im_f = distance_transform_lin ( im = im , axis = axis , mode = 'forward' ) im_b = distance_transform_lin ( im = im , axis = axis , mode = 'backward' ) return sp . minimum ( im_f , im_b ) else : b = sp . cumsum ( im > 0 , axis = axis ) c = sp . diff ( b * ( im == 0 ) , axis = axis ) d = sp . minimum . accumulate ( c , axis = axis ) if im . ndim == 1 : e = sp . pad ( d , pad_width = [ 1 , 0 ] , mode = 'constant' , constant_values = 0 ) elif im . ndim == 2 : ax = [ [ [ 1 , 0 ] , [ 0 , 0 ] ] , [ [ 0 , 0 ] , [ 1 , 0 ] ] ] e = sp . pad ( d , pad_width = ax [ axis ] , mode = 'constant' , constant_values = 0 ) elif im . ndim == 3 : ax = [ [ [ 1 , 0 ] , [ 0 , 0 ] , [ 0 , 0 ] ] , [ [ 0 , 0 ] , [ 1 , 0 ] , [ 0 , 0 ] ] , [ [ 0 , 0 ] , [ 0 , 0 ] , [ 1 , 0 ] ] ] e = sp . pad ( d , pad_width = ax [ axis ] , mode = 'constant' , constant_values = 0 ) f = im * ( b + e ) return f | 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 not bool : print ( 'Converting supplied image (im) to boolean' ) im = im > 0 if dt is None : print ( 'Peforming Distance Transform' ) if sp . any ( im_shape == 1 ) : ax = sp . where ( im_shape == 1 ) [ 0 ] [ 0 ] dt = spim . distance_transform_edt ( input = im . squeeze ( ) ) dt = sp . expand_dims ( dt , ax ) else : dt = spim . distance_transform_edt ( input = im ) tup . im = im tup . dt = dt if sigma > 0 : print ( 'Applying Gaussian blur with sigma =' , str ( sigma ) ) dt = spim . gaussian_filter ( input = dt , sigma = sigma ) peaks = find_peaks ( dt = dt , r_max = r_max ) print ( 'Initial number of peaks: ' , spim . label ( peaks ) [ 1 ] ) peaks = trim_saddle_points ( peaks = peaks , dt = dt , max_iters = 500 ) print ( 'Peaks after trimming saddle points: ' , spim . label ( peaks ) [ 1 ] ) peaks = trim_nearby_peaks ( peaks = peaks , dt = dt ) peaks , N = spim . label ( peaks ) print ( 'Peaks after trimming nearby peaks: ' , N ) tup . peaks = peaks if mask : mask_solid = im > 0 else : mask_solid = None regions = watershed ( image = - dt , markers = peaks , mask = mask_solid ) if randomize : regions = randomize_colors ( regions ) if return_all : tup . regions = regions return tup else : return regions | 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 phases_num : print ( '_' * 60 ) if alias is None : print ( 'Processing Phase {}' . format ( i ) ) else : print ( 'Processing Phase {}' . format ( al [ i ] ) ) phase_snow = snow_partitioning ( im == i , dt = None , r_max = r_max , sigma = sigma , return_all = return_all , mask = mask , randomize = randomize ) if len ( phases_num ) == 1 and phases_num == 1 : combined_dt = phase_snow . dt combined_region = phase_snow . regions else : combined_dt += phase_snow . dt phase_snow . regions *= phase_snow . im phase_snow . regions += num [ i - 1 ] phase_ws = phase_snow . regions * phase_snow . im phase_ws [ phase_ws == num [ i - 1 ] ] = 0 combined_region += phase_ws num . append ( sp . amax ( combined_region ) ) if return_all : tup = namedtuple ( 'results' , field_names = [ 'im' , 'dt' , 'phase_max_label' , 'regions' ] ) tup . im = im tup . dt = combined_dt tup . phase_max_label = num [ 1 : ] tup . regions = combined_region return tup else : return combined_region | 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 : footprint = disk elif im . ndim == 3 : footprint = ball else : raise Exception ( "only 2-d and 3-d images are supported" ) mx = spim . maximum_filter ( dt + 2 * ( ~ im ) , footprint = footprint ( r_max ) ) peaks = ( dt == mx ) * im return peaks | 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 ) peaks_new = sp . zeros_like ( peaks , dtype = bool ) peaks_new [ tuple ( inds . T ) ] = True return peaks_new | 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 = slices [ i ] , shape = peaks . shape , pad = 10 ) peaks_i = labels [ s ] == i + 1 dt_i = dt [ s ] im_i = dt_i > 0 iters = 0 peaks_dil = sp . copy ( peaks_i ) while iters < max_iters : iters += 1 peaks_dil = spim . binary_dilation ( input = peaks_dil , structure = cube ( 3 ) ) peaks_max = peaks_dil * sp . amax ( dt_i * peaks_dil ) peaks_extended = ( peaks_max == dt_i ) * im_i if sp . all ( peaks_extended == peaks_i ) : break elif sp . sum ( peaks_extended * peaks_i ) == 0 : peaks_i = False break peaks [ s ] = peaks_i if iters >= max_iters : print ( 'Maximum number of iterations reached, consider' + 'running again with a larger value of max_iters' ) return peaks | 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 = sp . arange ( 1 , N + 1 ) ) crds = sp . vstack ( crds ) . astype ( int ) tree = sptl . cKDTree ( data = crds ) temp = tree . query ( x = crds , k = 2 ) nearest_neighbor = temp [ 1 ] [ : , 1 ] dist_to_neighbor = temp [ 0 ] [ : , 1 ] del temp , tree dist_to_solid = dt [ tuple ( crds . T ) ] hits = sp . where ( dist_to_neighbor < dist_to_solid ) [ 0 ] drop_peaks = [ ] for peak in hits : if dist_to_solid [ peak ] < dist_to_solid [ nearest_neighbor [ peak ] ] : drop_peaks . append ( peak ) else : drop_peaks . append ( nearest_neighbor [ peak ] ) drop_peaks = sp . unique ( drop_peaks ) slices = spim . find_objects ( input = peaks ) for s in drop_peaks : peaks [ slices [ s ] ] = 0 return ( peaks > 0 ) | 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 ) labels = spim . label ( ~ im ) [ 0 ] inlet = sp . zeros_like ( im , dtype = int ) outlet = sp . zeros_like ( im , dtype = int ) if im . ndim == 3 : if inlet_axis == 0 : inlet [ 0 , : , : ] = 1 elif inlet_axis == 1 : inlet [ : , 0 , : ] = 1 elif inlet_axis == 2 : inlet [ : , : , 0 ] = 1 if outlet_axis == 0 : outlet [ - 1 , : , : ] = 1 elif outlet_axis == 1 : outlet [ : , - 1 , : ] = 1 elif outlet_axis == 2 : outlet [ : , : , - 1 ] = 1 if im . ndim == 2 : if inlet_axis == 0 : inlet [ 0 , : ] = 1 elif inlet_axis == 1 : inlet [ : , 0 ] = 1 if outlet_axis == 0 : outlet [ - 1 , : ] = 1 elif outlet_axis == 1 : outlet [ : , - 1 ] = 1 IN = sp . unique ( labels * inlet ) OUT = sp . unique ( labels * outlet ) new_im = sp . isin ( labels , list ( set ( IN ) ^ set ( OUT ) ) , invert = True ) im [ new_im == 0 ] = True return ~ im | 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 ) return result | 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 Exception ( 'Spacing cannot be less than 0' ) if spacing == 0 : label = True result = sp . zeros ( im . shape , dtype = int ) slxyz = [ slice ( None , None , spacing * ( axis != i ) + 1 ) for i in [ 0 , 1 , 2 ] ] slices = tuple ( slxyz [ : im . ndim ] ) s = [ [ 0 , 1 , 0 ] , [ 0 , 1 , 0 ] , [ 0 , 1 , 0 ] ] if im . ndim == 3 : s = sp . pad ( sp . atleast_3d ( s ) , pad_width = ( ( 0 , 0 ) , ( 0 , 0 ) , ( 1 , 1 ) ) , mode = 'constant' , constant_values = 0 ) im = im [ slices ] s = sp . swapaxes ( s , 0 , axis ) chords = spim . label ( im , structure = s ) [ 0 ] if trim_edges : chords = clear_border ( chords ) result [ slices ] = chords if label is False : result = result > 0 return result | 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 image to use this function' ) if spacing < 0 : raise Exception ( 'Spacing cannot be less than 0' ) ch = sp . zeros_like ( im , dtype = int ) ch [ : , : : 4 + 2 * spacing , : : 4 + 2 * spacing ] = 1 ch [ : : 4 + 2 * spacing , : , 2 : : 4 + 2 * spacing ] = 2 ch [ 2 : : 4 + 2 * spacing , 2 : : 4 + 2 * spacing , : ] = 3 chords = ch * im if trim_edges : temp = clear_border ( spim . label ( chords > 0 ) [ 0 ] ) > 0 chords = temp * chords return chords | 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 . distance_transform_edt ( im > 0 ) if inlets is None : inlets = get_border ( im . shape , mode = 'faces' ) if isinstance ( sizes , int ) : sizes = sp . logspace ( start = sp . log10 ( sp . amax ( dt ) ) , stop = 0 , num = sizes ) else : sizes = sp . unique ( sizes ) [ - 1 : : - 1 ] if im . ndim == 2 : strel = ps_disk else : strel = ps_ball if mode == 'mio' : pw = int ( sp . floor ( dt . max ( ) ) ) impad = sp . pad ( im , mode = 'symmetric' , pad_width = pw ) inletspad = sp . pad ( inlets , mode = 'symmetric' , pad_width = pw ) inlets = sp . where ( inletspad ) imresults = sp . zeros ( sp . shape ( impad ) ) for r in tqdm ( sizes ) : imtemp = fftmorphology ( impad , strel ( r ) , mode = 'erosion' ) if access_limited : imtemp = trim_disconnected_blobs ( imtemp , inlets ) imtemp = fftmorphology ( imtemp , strel ( r ) , mode = 'dilation' ) if sp . any ( imtemp ) : imresults [ ( imresults == 0 ) * imtemp ] = r imresults = extract_subsection ( imresults , shape = im . shape ) elif mode == 'dt' : inlets = sp . where ( inlets ) imresults = sp . zeros ( sp . shape ( im ) ) for r in tqdm ( sizes ) : imtemp = dt >= r if access_limited : imtemp = trim_disconnected_blobs ( imtemp , inlets ) if sp . any ( imtemp ) : imtemp = spim . distance_transform_edt ( ~ imtemp ) < r imresults [ ( imresults == 0 ) * imtemp ] = r elif mode == 'hybrid' : inlets = sp . where ( inlets ) imresults = sp . zeros ( sp . shape ( im ) ) for r in tqdm ( sizes ) : imtemp = dt >= r if access_limited : imtemp = trim_disconnected_blobs ( imtemp , inlets ) if sp . any ( imtemp ) : imtemp = fftconvolve ( imtemp , strel ( r ) , mode = 'same' ) > 0.0001 imresults [ ( imresults == 0 ) * imtemp ] = r else : raise Exception ( 'Unreckognized mode ' + mode ) return imresults | 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_shift ) ) : ax0 , ax1 = axial_shift [ i ] temp = np . roll ( np . roll ( im , ax0 , 0 ) , ax1 , 1 ) stack [ : , : , i + 1 ] = temp return stack elif ndim == 3 : stack = np . zeros ( [ np . shape ( im ) [ 0 ] , np . shape ( im ) [ 1 ] , np . shape ( im ) [ 2 ] , len ( axial_shift ) + 1 ] ) stack [ : , : , : , 0 ] = im for i in range ( len ( axial_shift ) ) : ax0 , ax1 , ax2 = axial_shift [ i ] temp = np . roll ( np . roll ( np . roll ( im , ax0 , 0 ) , ax1 , 1 ) , ax2 , 2 ) stack [ : , : , : , i + 1 ] = temp return stack | 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 possible . |
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 ) : dic [ 'top' ] = 1 dic [ 'bottom' ] = 1 for i in f : if i in [ 'left' , 'front' , 'bottom' ] : network [ 'pore.{}' . format ( i ) ] = ( coords [ : , dic [ i ] ] < min ( condition [ : , dic [ i ] ] ) ) elif i in [ 'right' , 'back' , 'top' ] : network [ 'pore.{}' . format ( i ) ] = ( coords [ : , dic [ i ] ] > max ( condition [ : , dic [ i ] ] ) ) return network | 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 None ) and ( corner is None ) : for dim in range ( im . ndim ) : r , d = sp . divmod ( element . shape [ dim ] , 2 ) if d == 0 : raise Exception ( 'Cannot specify center point when element ' + 'has one or more even dimension' ) lower_im = sp . amax ( ( center [ dim ] - r , 0 ) ) upper_im = sp . amin ( ( center [ dim ] + r + 1 , im . shape [ dim ] ) ) s_im . append ( slice ( lower_im , upper_im ) ) lower_el = sp . amax ( ( lower_im - center [ dim ] + r , 0 ) ) upper_el = sp . amin ( ( upper_im - center [ dim ] + r , element . shape [ dim ] ) ) s_el . append ( slice ( lower_el , upper_el ) ) elif ( corner is not None ) and ( center is None ) : for dim in range ( im . ndim ) : L = int ( element . shape [ dim ] ) lower_im = sp . amax ( ( corner [ dim ] , 0 ) ) upper_im = sp . amin ( ( corner [ dim ] + L , im . shape [ dim ] ) ) s_im . append ( slice ( lower_im , upper_im ) ) lower_el = sp . amax ( ( lower_im - corner [ dim ] , 0 ) ) upper_el = sp . amin ( ( upper_im - corner [ dim ] , element . shape [ dim ] ) ) s_el . append ( slice ( min ( lower_el , upper_el ) , upper_el ) ) else : raise Exception ( 'Cannot specify both corner and center' ) if mode == 'overlay' : im [ tuple ( s_im ) ] = im [ tuple ( s_im ) ] + element [ tuple ( s_el ) ] * value elif mode == 'overwrite' : im [ tuple ( s_im ) ] = element [ tuple ( s_el ) ] * value else : raise Exception ( 'Invalid mode ' + mode ) return im | 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 ( spacing / 2 , shape [ 0 ] - ( spacing / 2 ) - 1 , int ( shape [ 0 ] / spacing ) ) ) Xi = sp . array ( Xi , dtype = int ) Yi = sp . ceil ( sp . linspace ( spacing / 2 , shape [ 1 ] - ( spacing / 2 ) - 1 , int ( shape [ 1 ] / spacing ) ) ) Yi = sp . array ( Yi , dtype = int ) temp [ tuple ( sp . meshgrid ( Xi , Yi ) ) ] = 1 inds = sp . where ( temp ) for i in range ( len ( inds [ 0 ] ) ) : r = sp . random . randint ( 1 , ( spacing / 2 ) ) try : s1 = slice ( inds [ 0 ] [ i ] - r , inds [ 0 ] [ i ] + r + 1 ) s2 = slice ( inds [ 1 ] [ i ] - r , inds [ 1 ] [ i ] + r + 1 ) temp [ s1 , s2 ] = ps_disk ( r ) except ValueError : odd_shape = sp . shape ( temp [ s1 , s2 ] ) temp [ s1 , s2 ] = ps_disk ( r ) [ : odd_shape [ 0 ] , : odd_shape [ 1 ] ] im = sp . broadcast_to ( array = sp . atleast_3d ( temp ) , shape = shape ) return im | 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 = ( Rs [ : - 1 ] + Rs [ 1 : ] ) / 2 Rs = sp . clip ( Rs . flatten ( ) , a_min = r_min , a_max = None ) phi_desired = 1 - ( 1 - porosity ) / ( len ( Rs ) ) im = sp . ones ( shape , dtype = bool ) for r in Rs : phi_im = im . sum ( ) / sp . prod ( shape ) phi_corrected = 1 - ( 1 - phi_desired ) / phi_im temp = overlapping_spheres ( shape = shape , radius = r , porosity = phi_corrected ) im = im * temp return im | 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 = sp . sort ( edges , axis = 1 ) edges = edges [ : , 0 ] + 1j * edges [ : , 1 ] edges = sp . unique ( edges ) edges = sp . vstack ( ( sp . real ( edges ) , sp . imag ( edges ) ) ) . T edges = sp . array ( edges , dtype = int ) return 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 else ps_ball ( radius ) . sum ( ) bulk_vol = sp . prod ( shape ) N = int ( sp . ceil ( ( 1 - porosity ) * bulk_vol / s_vol ) ) im = sp . random . random ( size = shape ) f = lambda N : spim . distance_transform_edt ( im > N / bulk_vol ) < radius g = lambda im : 1 - im . sum ( ) / sp . prod ( shape ) N_low , N_high = N , 4 * N for i in range ( iter_max ) : N = sp . mean ( [ N_high , N_low ] , dtype = int ) err = g ( f ( N ) ) - porosity if err > 0 : N_low = N else : N_high = N if abs ( err ) <= tol : break return ~ f ( N ) | 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 . full ( ( 3 , ) , int ( shape ) ) elif len ( shape ) == 2 : Lx , Ly = shape Lz = 1 elif len ( shape ) == 3 : Lx , Ly , Lz = shape if mode == 'simplex' : f = noise . snoise3 else : f = noise . pnoise3 frequency = sp . atleast_1d ( frequency ) if frequency . size == 1 : freq = sp . full ( shape = [ 3 , ] , fill_value = frequency [ 0 ] ) elif frequency . size == 2 : freq = sp . concatenate ( ( frequency , [ 1 ] ) ) else : freq = sp . array ( frequency ) im = sp . zeros ( shape = [ Lx , Ly , Lz ] , dtype = float ) for x in range ( Lx ) : for y in range ( Ly ) : for z in range ( Lz ) : im [ x , y , z ] = f ( x = x / freq [ 0 ] , y = y / freq [ 1 ] , z = z / freq [ 2 ] , octaves = octaves ) im = im . squeeze ( ) if porosity : im = norm_to_uniform ( im , scale = [ 0 , 1 ] ) im = im < porosity return im | 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 . gaussian_filter ( im , sigma = sigma ) im = norm_to_uniform ( im , scale = [ 0 , 1 ] ) if porosity : im = im < porosity return im | 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 . sqrt ( sp . sum ( sp . square ( shape ) ) ) . astype ( int ) im = sp . zeros ( shape ) if ( phi_max > 90 ) or ( phi_max < 0 ) : raise Exception ( 'phi_max must be betwen 0 and 90' ) if ( theta_max > 90 ) or ( theta_max < 0 ) : raise Exception ( 'theta_max must be betwen 0 and 90' ) n = 0 while n < ncylinders : x = sp . rand ( 3 ) * shape phi = ( sp . pi / 2 - sp . pi * sp . rand ( ) ) * phi_max / 90 theta = ( sp . pi / 2 - sp . pi * sp . rand ( ) ) * theta_max / 90 X0 = R * sp . array ( [ sp . cos ( phi ) * sp . cos ( theta ) , sp . cos ( phi ) * sp . sin ( theta ) , sp . sin ( phi ) ] ) [ X0 , X1 ] = [ x + X0 , x - X0 ] crds = line_segment ( X0 , X1 ) lower = ~ sp . any ( sp . vstack ( crds ) . T < [ 0 , 0 , 0 ] , axis = 1 ) upper = ~ sp . any ( sp . vstack ( crds ) . T >= shape , axis = 1 ) valid = upper * lower if sp . any ( valid ) : im [ crds [ 0 ] [ valid ] , crds [ 1 ] [ valid ] , crds [ 2 ] [ valid ] ] = 1 n += 1 im = sp . array ( im , dtype = bool ) dt = spim . distance_transform_edt ( ~ im ) < radius return ~ dt | 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 ) ) . astype ( int ) y = sp . rint ( sp . linspace ( X0 [ 1 ] , X1 [ 1 ] , L ) ) . astype ( int ) z = sp . rint ( sp . linspace ( X0 [ 2 ] , X1 [ 2 ] , L ) ) . astype ( int ) return [ x , y , z ] else : L = sp . amax ( sp . absolute ( [ [ X1 [ 0 ] - X0 [ 0 ] ] , [ X1 [ 1 ] - X0 [ 1 ] ] ] ) ) + 1 x = sp . rint ( sp . linspace ( X0 [ 0 ] , X1 [ 0 ] , L ) ) . astype ( int ) y = sp . rint ( sp . linspace ( X0 [ 1 ] , X1 [ 1 ] , L ) ) . astype ( int ) return [ x , y ] | 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 ) ) im = im [ - 1 : : - 1 , : ] elif im . ndim == 3 : im = ( sp . swapaxes ( im , 2 , 0 ) ) im = im [ : , - 1 : : - 1 , : ] return im | 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 ( 'Input image conains a singleton axis:' + str ( im . shape ) + ' Reduce dimensionality with np.squeeze(im) to avoid' + ' unexpected behavior.' ) temp = sp . pad ( array = im , pad_width = 1 , mode = 'constant' , constant_values = 0 ) if mode . startswith ( 'ero' ) : temp = erode ( temp , strel ) if mode . startswith ( 'dila' ) : temp = dilate ( temp , strel ) if im . ndim == 2 : result = temp [ 1 : - 1 , 1 : - 1 ] elif im . ndim == 3 : result = temp [ 1 : - 1 , 1 : - 1 , 1 : - 1 ] if mode . startswith ( 'open' ) : temp = fftmorphology ( im = im , strel = strel , mode = 'erosion' ) result = fftmorphology ( im = temp , strel = strel , mode = 'dilation' ) if mode . startswith ( 'clos' ) : temp = fftmorphology ( im = im , strel = strel , mode = 'dilation' ) result = fftmorphology ( im = temp , strel = strel , mode = 'erosion' ) return result | 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 = sp . amin ( ( center [ dim ] + s [ dim ] + 1 + p [ dim ] , im . shape [ dim ] ) ) slc . append ( slice ( lower_im , upper_im ) ) return slc | 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_border ( shape = im_padded . shape ) labels = spim . label ( seeds ) [ 0 ] mask = labels == 1 dt = spim . distance_transform_edt ( ~ mask ) outer_region = dt < r outer_region = extract_subsection ( im = outer_region , shape = im . shape ) return outer_region | 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 . sqrt ( sp . sum ( sp . square ( inds ) , axis = 0 ) ) mask = d < r im_temp = im * mask return im_temp | 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 ( ( center [ dim ] + r , im . shape [ dim ] ) ) s_im . append ( slice ( int ( lower_im ) , int ( upper_im ) ) ) return im [ tuple ( s_im ) ] | 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 [ 1 ] = sp . reshape ( imy , [ imy . shape [ 0 ] , 1 , imy . shape [ 1 ] ] ) imz = planes [ 2 ] planes [ 2 ] = sp . reshape ( imz , [ imz . shape [ 0 ] , imz . shape [ 1 ] , 1 ] ) return 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 , ] , dtype = int ) im_map [ im_vals ] = new_vals im_new = im_map [ im_flat ] im_new = sp . reshape ( im_new , newshape = sp . shape ( im ) ) return im_new | 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 , sp . size ( sp . unique ( im_flat ) ) ) im_new = im_map [ im_flat ] im_new = sp . reshape ( im_new , newshape = sp . shape ( im ) ) im_new = sp . array ( im_new , dtype = im_flat . dtype ) return im_new | 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 == 'edges' : if ndims == 2 : border [ t : - t , t : - t ] = False if ndims == 3 : border [ 0 : : , t : - t , t : - t ] = False border [ t : - t , 0 : : , t : - t ] = False border [ t : - t , t : - t , 0 : : ] = False elif mode == 'corners' : if ndims == 2 : border [ t : - t , 0 : : ] = False border [ 0 : : , t : - t ] = False if ndims == 3 : border [ t : - t , 0 : : , 0 : : ] = False border [ 0 : : , t : - t , 0 : : ] = False border [ 0 : : , 0 : : , t : - t ] = False if return_indices : border = sp . where ( border ) return border | 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 ] - 2 ) + 's} {4:1s}' lines = [ ] lines . append ( row ) lines . append ( fmt . format ( '|' , 'Method' , '|' , 'Description' , '|' ) ) lines . append ( row . replace ( '-' , '=' ) ) for i , item in enumerate ( funcs ) : try : s = getattr ( mod , item ) . __doc__ . strip ( ) end = s . find ( '\n' ) if end > colwidth [ 1 ] - 2 : s = s [ : colwidth [ 1 ] - 5 ] + '...' lines . append ( fmt . format ( '|' , item , '|' , s [ : end ] , '|' ) ) lines . append ( row ) except AttributeError : pass s = '\n' . join ( lines ) return s | 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 = ball ( 1 ) if region . ndim == 2 : strel = disk ( 1 ) pad_width = sp . amax ( strel . shape ) if im . ndim == 3 : padded_mask = sp . pad ( im , pad_width = pad_width , mode = 'constant' ) padded_mask = spim . convolve ( padded_mask * 1.0 , weights = strel ) / sp . sum ( strel ) else : padded_mask = sp . reshape ( im , ( 1 , ) + im . shape ) padded_mask = sp . pad ( padded_mask , pad_width = pad_width , mode = 'constant' ) verts , faces , norm , val = marching_cubes_lewiner ( padded_mask ) result = namedtuple ( 'mesh' , ( 'verts' , 'faces' , 'norm' , 'val' ) ) result . verts = verts - pad_width result . faces = faces result . norm = norm result . val = val return result | 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 , 0 , im . shape [ i ] ) ) for i in range ( im . ndim ) ] bbox = sp . ravel ( bbox ) s = bbox_to_slices ( bbox ) temp = im [ s ] blank = sp . ones_like ( temp ) blank [ tuple ( c - bbox [ 0 : im . ndim ] ) ] = 0 blank = spim . distance_transform_edt ( blank ) < r im [ s ] = blank return im | 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 ] , xyz1 [ i ] , L ) . astype ( int ) for i in range ( 3 ) ] xyz_min = sp . amin ( xyz_line , axis = 1 ) - r xyz_max = sp . amax ( xyz_line , axis = 1 ) + r shape_template = xyz_max - xyz_min + 1 template = sp . zeros ( shape = shape_template ) if ( xyz0 == xyz1 ) . sum ( ) == 2 : unique_dim = [ xyz0 [ i ] != xyz1 [ i ] for i in range ( 3 ) ] . index ( True ) shape_template [ unique_dim ] = 1 template_2D = disk ( radius = r ) . reshape ( shape_template ) template = sp . repeat ( template_2D , repeats = L , axis = unique_dim ) xyz_min [ unique_dim ] += r xyz_max [ unique_dim ] += - r else : xyz_line_in_template_coords = [ xyz_line [ i ] - xyz_min [ i ] for i in range ( 3 ) ] template [ tuple ( xyz_line_in_template_coords ) ] = 1 template = spim . distance_transform_edt ( template == 0 ) <= r im [ xyz_min [ 0 ] : xyz_max [ 0 ] + 1 , xyz_min [ 1 ] : xyz_max [ 1 ] + 1 , xyz_min [ 2 ] : xyz_max [ 2 ] + 1 ] += template return im | 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 ) * 3 , int ( 'right' in f ) * 3 ) , ( int ( ( 'front' ) in f ) * 3 or int ( ( 'bottom' ) in f ) * 3 , int ( ( 'back' ) in f ) * 3 or int ( ( 'top' ) in f ) * 3 ) ] if im . ndim == 3 : faces = [ ( int ( 'left' in f ) * 3 , int ( 'right' in f ) * 3 ) , ( int ( 'front' in f ) * 3 , int ( 'back' in f ) * 3 ) , ( int ( 'top' in f ) * 3 , int ( 'bottom' in f ) * 3 ) ] im = sp . pad ( im , pad_width = faces , mode = 'edge' ) else : im = im return im | 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 ( [ * alias_sort ] ) al = alias if set ( phase_labels ) != set ( phases_num ) : raise Exception ( 'Alias labels does not match with image labels ' 'please provide correct image labels' ) return al | 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' : 'w:gz' } ) with closing ( tarfile . open ( * tar_args , ** tar_kwargs ) ) as tar : tar . add ( self . path , arcname = self . file ) return _return | 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 self . relpath ( os . path . join ( root , f ) ) | 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 ) return wrapper | 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_execution ( ) success = last_execution . success if last_execution else None if success is True : stats = last_execution . stats if last_execution else None record_count = stats . get ( 'count_of_rows' ) if record_count is not None : status_text += ' (%d records)' % record_count status_color = 'brightgreen' elif success is False : status_color = 'red' else : status_text = "not found" return _make_badge_response ( 'pipeline' , status_text , status_color ) | 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_ids : pipeline_status = status . get ( pipeline_id ) if pipeline_status is None : abort ( 404 ) status_text = pipeline_status . state ( ) . lower ( ) statuses . append ( status_text ) status_color = 'lightgray' status_counter = Counter ( statuses ) if status_counter : if len ( status_counter ) == 1 and status_counter [ 'succeeded' ] > 0 : status_color = 'brightgreen' elif status_counter [ 'failed' ] > 0 : status_color = 'red' elif status_counter [ 'failed' ] == 0 : status_color = 'yellow' status_text = ', ' . join ( [ '{} {}' . format ( v , k ) for k , v in status_counter . items ( ) ] ) else : status_text = "not found" return _make_badge_response ( 'pipelines' , status_text , status_color ) | Status badge for a collection of pipelines . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.