_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q20800
find_neighbor_sites
train
def find_neighbor_sites(sites, am, flatten=True, include_input=False, logic='or'): r""" Given a symmetric adjacency matrix, finds all sites that are connected to the input sites. Parameters ---------- am : scipy.sparse matrix The adjacency matrix of the network. Must be symmetrical such that if sites *i* and *j* are connected, the matrix contains non-zero values at locations (i, j) and (j, i). flatten : boolean If ``True`` (default) the returned result is a compressed array of all neighbors, or a list of lists with each sub-list containing the neighbors for each input site. Note that an *unflattened* list might be slow to generate since it is a Python ``list`` rather than a Numpy array. include_input : boolean If ``False`` (default) the input sites will be removed from the result. logic : string Specifies logic to filter the resulting list. Options are: **'or'** : (default) All neighbors of the input sites. This is also known as the 'union' in set theory or 'any' in boolean logic. Both keywords are accepted and treated as 'or'. **'xor'** : Only neighbors of one and only one input site. This is useful for finding the sites that are not shared by any of the input sites. 'exclusive_or' is also accepted. **'xnor'** : Neighbors that are shared by two or more input sites. This is equivalent to finding all neighbors with 'or', minus those found with 'xor', and is useful for finding neighbors that the inputs have in common. 'nxor' is also accepted. **'and'** : Only neighbors shared by all input sites. This is also known as 'intersection' in set theory and (somtimes) as 'all' in boolean logic. Both keywords are accepted and treated as 'and'. Returns ------- An array containing the neighboring sites filtered by the given logic. If ``flatten`` is ``False`` then the result is a list of lists containing the neighbors of each input site. See Also -------- find_complement Notes ----- The ``logic`` options are applied to neighboring sites only, thus it is not possible to obtain sites that are part of the global set but not neighbors. This is because (a) the list global sites might be very large, and (b) it is not possible to return a list of neighbors for each input site if global sites are considered. """ if am.format != 'lil': am = am.tolil(copy=False) n_sites = am.shape[0] rows = [am.rows[i] for i in sp.array(sites, ndmin=1)]
python
{ "resource": "" }
q20801
find_connected_sites
train
def find_connected_sites(bonds, am, flatten=True, logic='or'): r""" Given an adjacency matrix, finds which sites are connected to the input bonds. Parameters ---------- am : scipy.sparse matrix The adjacency matrix of the network. Must be symmetrical such that if sites *i* and *j* are connected, the matrix contains non-zero values at locations (i, j) and (j, i). flatten : boolean (default is ``True``) Indicates whether the returned result is a compressed array of all neighbors, or a list of lists with each sub-list containing the neighbors for each input site. Note that an *unflattened* list might be slow to generate since it is a Python ``list`` rather than a Numpy array. logic : string Specifies logic to filter the resulting list. Options are: **'or'** : (default) All neighbors of the input bonds. This is also known as the 'union' in set theory or (sometimes) 'any' in boolean logic. Both keywords are accepted and treated as 'or'. **'xor'** : Only neighbors of one and only one input bond. This is useful for finding the sites that are not shared by any of the input bonds. 'exclusive_or' is also accepted. **'xnor'** : Neighbors that are shared by two or more input bonds. This is equivalent to finding all neighbors with 'or', minus those found with 'xor', and is useful for finding neighbors that the inputs have in common. 'nxor' is also accepted. **'and'** : Only neighbors shared by all input bonds. This is also known as 'intersection' in set theory and (somtimes) as 'all' in boolean logic. Both keywords are accepted and treated as 'and'. Returns ------- An array containing the connected sites, filtered by the given logic. If ``flatten`` is ``False`` then the result is a list of lists containing the neighbors of each given input bond. In this latter case, sites that have been removed by the given logic are indicated by ``nans``, thus the array is of type ``float`` and is not suitable for indexing. See Also -------- find_complement """ if am.format != 'coo': raise Exception('Adjacency matrix must be in COO format') bonds = sp.array(bonds, ndmin=1) if len(bonds) == 0: return [] neighbors = sp.hstack((am.row[bonds], am.col[bonds])).astype(sp.int64) if neighbors.size: n_sites = sp.amax(neighbors) if logic in ['or', 'union', 'any']: neighbors = sp.unique(neighbors) elif logic in ['xor', 'exclusive_or']:
python
{ "resource": "" }
q20802
find_connecting_bonds
train
def find_connecting_bonds(sites, am): r""" Given pairs of sites, finds the bonds which connects each pair. Parameters ---------- sites : array_like A 2-column vector containing pairs of site indices on each row. am : scipy.sparse matrix The adjacency matrix of the network. Must be symmetrical such that if sites *i* and *j* are connected, the matrix contains non-zero values at locations (i, j) and (j, i). Returns ------- Returns a list the same length as P1 (and P2) with each element containing the throat number that connects the corresponding pores, or `None`` if pores are not connected. Notes ----- The returned list
python
{ "resource": "" }
q20803
istriu
train
def istriu(am): r""" Returns ``True`` is the sparse adjacency matrix is upper triangular """ if am.shape[0] != am.shape[1]: print('Matrix is not square, triangularity is irrelevant')
python
{ "resource": "" }
q20804
istriangular
train
def istriangular(am): r""" Returns ``True`` is the sparse adjacency matrix is either upper or lower triangular """ if
python
{ "resource": "" }
q20805
issymmetric
train
def issymmetric(am): r""" A method to check if a square matrix is symmetric Returns ``True`` if the sparse adjacency matrix is symmetric """ if am.shape[0] != am.shape[1]: logger.warning('Matrix is not square, symmetrical is irrelevant') return False if am.format != 'coo': am = am.tocoo(copy=False)
python
{ "resource": "" }
q20806
am_to_im
train
def am_to_im(am): r""" Convert an adjacency matrix into an incidence matrix """ if am.shape[0] != am.shape[1]: raise Exception('Adjacency matrices must be square') if am.format != 'coo': am = am.tocoo(copy=False) conn = sp.vstack((am.row, am.col)).T row = conn[:, 0] data = am.data col = sp.arange(sp.size(am.data)) if istriangular(am):
python
{ "resource": "" }
q20807
im_to_am
train
def im_to_am(im): r""" Convert an incidence matrix into an adjacency matrix """ if im.shape[0] == im.shape[1]: print('Warning: Received matrix is square which is unlikely') if im.shape[0] > im.shape[1]:
python
{ "resource": "" }
q20808
tri_to_am
train
def tri_to_am(tri): r""" Given a Delaunay Triangulation object from Scipy's ``spatial`` module, converts to a sparse adjacency matrix network representation. Parameters ---------- tri : Delaunay Triangulation Object This object is produced by ``scipy.spatial.Delaunay`` Returns ------- A sparse adjacency matrix in COO format. The network is undirected and unweighted, so the adjacency matrix is upper-triangular and all the weights are set to 1. """ # Create an empty list-of-list matrix lil = sprs.lil_matrix((tri.npoints, tri.npoints)) # Scan through Delaunay triangulation to retrieve pairs indices, indptr = tri.vertex_neighbor_vertices for k in range(tri.npoints): lil.rows[k] = indptr[indices[k]:indices[k+1]]
python
{ "resource": "" }
q20809
vor_to_am
train
def vor_to_am(vor): r""" Given a Voronoi tessellation object from Scipy's ``spatial`` module, converts to a sparse adjacency matrix network representation in COO format. Parameters ---------- vor : Voronoi Tessellation object This object is produced by ``scipy.spatial.Voronoi`` Returns ------- A sparse adjacency matrix in COO format. The network is undirected and unweighted, so the adjacency matrix is upper-triangular and all the weights are set to 1. """ # Create adjacency matrix in lil format for quick matrix construction N = vor.vertices.shape[0] rc = [[], []] for ij in vor.ridge_dict.keys(): row = vor.ridge_dict[ij].copy() # Make sure voronoi cell closes upon itself row.append(row[0]) # Add connections to rc
python
{ "resource": "" }
q20810
conns_to_am
train
def conns_to_am(conns, shape=None, force_triu=True, drop_diag=True, drop_dupes=True, drop_negs=True): r""" Converts a list of connections into a Scipy sparse adjacency matrix Parameters ---------- conns : array_like, N x 2 The list of site-to-site connections shape : list, optional The shape of the array. If none is given then it is inferred from the maximum value in ``conns`` array. force_triu : boolean If True (default), then all connections are assumed undirected, and moved to the upper triangular portion of the array drop_diag : boolean If True (default), then connections from a site and itself are removed. drop_dupes : boolean If True (default), then all pairs of sites sharing multiple connections are reduced to a single connection. drop_negs : boolean If True (default), then all connections with one or both ends pointing to a negative number are removed. """ if force_triu: # Sort connections to [low, high] conns = sp.sort(conns, axis=1) if drop_negs: # Remove connections to -1 keep = ~sp.any(conns < 0, axis=1) conns = conns[keep] if drop_diag: # Remove connections of [self, self]
python
{ "resource": "" }
q20811
isoutside
train
def isoutside(coords, shape): r""" Identifies points that lie outside the specified region. Parameters ---------- domain_size : array_like The size and shape of the domain beyond which points should be trimmed. The argument is treated as follows: **sphere** : If a scalar or single element list is received, it's treated as the radius [r] of a sphere centered on [0, 0, 0]. **cylinder** : If a two-element list is received it's treated as the radius and height of a cylinder [r, z] whose central axis starts at [0, 0, 0] and extends in the positive z-direction. **rectangle** : If a three element list is received, it's treated as the outer corner of rectangle [x, y, z] whose opposite corner lies at [0, 0, 0]. Returns ------- An Np-long mask of True values indicating pores that lie outside the domain. """ # Label external pores for trimming below if len(shape) == 1: # Spherical # Find external points r = sp.sqrt(sp.sum(coords**2, axis=1)) Ps = r > shape[0] elif len(shape) == 2: # Cylindrical # Find external pores outside radius
python
{ "resource": "" }
q20812
ispercolating
train
def ispercolating(am, inlets, outlets, mode='site'): r""" Determines if a percolating clusters exists in the network spanning the given inlet and outlet sites Parameters ---------- am : adjacency_matrix The adjacency matrix with the ``data`` attribute indicating if a bond is occupied or not inlets : array_like An array of indices indicating which sites are part of the inlets outlets : array_like An array of indices indicating which sites are part of the outlets mode : string Indicates which type of percolation to apply, either `'site'` or `'bond'` """ if am.format is not 'coo': am = am.to_coo() ij = sp.vstack((am.col, am.row)).T
python
{ "resource": "" }
q20813
site_percolation
train
def site_percolation(ij, occupied_sites): r""" Calculates the site and bond occupancy status for a site percolation process given a list of occupied sites. Parameters ---------- ij : array_like An N x 2 array of [site_A, site_B] connections. If two connected sites are both occupied they are part of the same cluster, as it the bond connecting them. occupied_sites : boolean A list indicating whether sites are occupied or not Returns ------- A tuple containing a list of site and bond labels, indicating which cluster each belongs to. A value of -1 indicates unoccupied. Notes ----- The ``connected_components`` function of scipy.csgraph will give ALL sites a cluster number whether they are occupied or not, so this function essentially adjusts the cluster numbers to represent a percolation process. """ from
python
{ "resource": "" }
q20814
bond_percolation
train
def bond_percolation(ij, occupied_bonds): r""" Calculates the site and bond occupancy status for a bond percolation process given a list of occupied bonds. Parameters ---------- ij : array_like An N x 2 array of [site_A, site_B] connections. A site is considered occupied if any of it's connecting bonds are occupied. occupied_bonds: boolean A list indicating whether a bond is occupied or not Returns ------- A tuple contain a list of site and bond labels, indicating which cluster each belongs to. A value of -1 indicates uninvaded. Notes
python
{ "resource": "" }
q20815
trim
train
def trim(network, pores=[], throats=[]): ''' Remove pores or throats from the network. Parameters ---------- network : OpenPNM Network Object The Network from which pores or throats should be removed pores (or throats) : array_like The indices of the of the pores or throats to be removed from the network. Notes ----- This is an in-place operation, meaning the received Network object will be altered directly. Examples -------- >>> import openpnm as op >>> pn = op.network.Cubic(shape=[5, 5, 5]) >>> pn.Np 125 >>> pn.Nt 300 >>> op.topotools.trim(network=pn, pores=[1]) >>> pn.Np 124 >>> pn.Nt 296 ''' pores = sp.array(pores, ndmin=1) throats = sp.array(throats, ndmin=1) Pkeep = sp.copy(network['pore.all']) Tkeep = sp.copy(network['throat.all']) if sp.size(pores) > 0: Pkeep[pores] = False if not sp.any(Pkeep): raise Exception('Cannot delete ALL pores') # Performing customized find_neighbor_throats which is much faster, but # not general for other types of queries # temp = sp.in1d(network['throat.conns'].flatten(), pores) # temp = sp.reshape(temp, (network.Nt, 2)) # Ts = sp.any(temp, axis=1) # Ts = network.Ts[Ts] # tic() Ts = network.find_neighbor_throats(pores=~Pkeep, mode='union') # toc() if len(Ts) > 0: Tkeep[Ts] = False if sp.size(throats) > 0: Tkeep[throats] = False # The following IF catches the special case of deleting ALL throats # It removes all throat props, adds 'all', and skips rest of function if not sp.any(Tkeep): logger.info('Removing ALL throats from network') for item in network.keys(): if item.split('.')[0] == 'throat': del network[item] network['throat.all'] = sp.array([], ndmin=1) return # Temporarily store throat conns and pore map for processing later Np_old = network.Np Nt_old = network.Nt Pkeep_inds = sp.where(Pkeep)[0] Tkeep_inds = sp.where(Tkeep)[0]
python
{ "resource": "" }
q20816
find_surface_pores
train
def find_surface_pores(network, markers=None, label='surface'): r""" Find the pores on the surface of the domain by performing a Delaunay triangulation between the network pores and some external ``markers``. All pores connected to these external marker points are considered surface pores. Parameters ---------- network: OpenPNM Network Object The network for which the surface pores are to be found markers: array_like 3 x N array of the marker coordinates to use in the triangulation. The labeling is performed in one step, so all points are added, and then any pores connected to at least one marker is given the provided label. By default, this function will automatically generate 6 points outside each axis of the network domain. Users may wish to specify a single external marker point and provide an appropriate label in order to identify specific faces. For instance, the marker may be *above* the domain, and the label might be 'top_surface'. label : string The label to apply to the pores. The default is 'surface'. Notes ----- This function does not check whether the given markers actually lie outside the domain, allowing the labeling of *internal* sufaces. If this method fails to mark some surface pores, consider sending more markers on each face. Examples -------- >>> import openpnm as op >>> net = op.network.Cubic(shape=[5, 5, 5]) >>> op.topotools.find_surface_pores(network=net) >>> net.num_pores('surface') 98 When cubic networks are created, the surfaces are already labeled: >>> net.num_pores(['top','bottom', 'left', 'right', 'front','back']) 98 This function is mostly useful for unique networks such as spheres, random
python
{ "resource": "" }
q20817
clone_pores
train
def clone_pores(network, pores, labels=['clone'], mode='parents'): r''' Clones the specified pores and adds them to the network Parameters ---------- network : OpenPNM Network Object The Network object to which the new pores are to be added pores : array_like List of pores to clone labels : string, or list of strings The labels to apply to the clones, default is 'clone' mode : string Controls the connections between parents and clones. Options are: - 'parents': (Default) Each clone is connected only to its parent - 'siblings': Clones are only connected to each other in the same manner as parents were connected - 'isolated': No connections between parents or siblings ''' if len(network.project.geometries()) > 0: logger.warning('Network has active Geometries, new pores must be \ assigned a Geometry') if len(network.project.phases()) > 0: raise Exception('Network has active Phases, cannot proceed') if type(labels) == str: labels = [labels] Np = network.Np Nt = network.Nt # Clone pores parents = sp.array(pores, ndmin=1) pcurrent = network['pore.coords'] pclone = pcurrent[pores, :] pnew = sp.concatenate((pcurrent, pclone), axis=0) Npnew = sp.shape(pnew)[0] clones = sp.arange(Np, Npnew) # Add clone labels to network for item in labels: network['pore.'+item] = False
python
{ "resource": "" }
q20818
stitch
train
def stitch(network, donor, P_network, P_donor, method='nearest', len_max=sp.inf, len_min=0, label_suffix=''): r''' Stitches a second a network to the current network. Parameters ---------- networK : OpenPNM Network Object The Network to which to donor Network will be attached donor : OpenPNM Network Object The Network to stitch on to the current Network P_network : array_like The pores on the current Network P_donor : array_like The pores on the donor Network label_suffix : string or None Some text to append to each label in the donor Network before inserting them into the recipient. The default is to append no text, but a common option would be to append the donor Network's name. To insert none of the donor labels, use None. len_max : float Set a length limit on length of new throats method : string (default = 'delaunay') The method to use when making pore to pore connections. Options are: - 'delaunay' : Use a Delaunay tessellation - 'nearest' : Connects each pore on the receptor network to its nearest pore on the donor network Notes ----- Before stitching it is necessary to translate the pore coordinates of one of the Networks so that it is positioned correctly relative to the other. Examples -------- >>> import openpnm as op >>> pn = op.network.Cubic(shape=[5, 5, 5]) >>> pn2 = op.network.Cubic(shape=[5, 5, 5]) >>> [pn.Np, pn.Nt] [125, 300] >>> [pn2.Np, pn2.Nt] [125, 300] >>> pn2['pore.coords'][:, 2] += 5.0 >>> op.topotools.stitch(network=pn, donor=pn2, P_network=pn.pores('top'), ... P_donor=pn2.pores('bottom'), method='nearest', ... len_max=1.0) >>> [pn.Np, pn.Nt] [250, 625] ''' # Ensure Networks have no associated objects yet if (len(network.project) > 1) or (len(donor.project) > 1): raise Exception('Cannot stitch a Network with active objects') network['throat.stitched'] = False # Get the initial number of pores and throats N_init = {} N_init['pore'] = network.Np N_init['throat'] = network.Nt if method == 'nearest': P1 = P_network P2 = P_donor + N_init['pore'] # Increment pores on donor C1 = network['pore.coords'][P_network] C2 = donor['pore.coords'][P_donor] D = sp.spatial.distance.cdist(C1, C2) [P1_ind, P2_ind] = sp.where(D <= len_max) conns = sp.vstack((P1[P1_ind], P2[P2_ind])).T else: raise Exception('<{}> method not
python
{ "resource": "" }
q20819
connect_pores
train
def connect_pores(network, pores1, pores2, labels=[], add_conns=True): r''' Returns the possible connections between two group of pores, and optionally makes the connections. See ``Notes`` for advanced usage. Parameters ---------- network : OpenPNM Network Object pores1 : array_like The first group of pores on the network pores2 : array_like The second group of pores on the network labels : list of strings The labels to apply to the new throats. This argument is only needed if ``add_conns`` is True. add_conns : bool Indicates whether the connections should be added to the supplied network (default is True). Otherwise, the connections are returned as an Nt x 2 array that can be passed directly to ``extend``. Notes ----- (1) The method also works if ``pores1`` and ``pores2`` are list of lists, in which case it consecutively connects corresponding members of the two lists in a 1-to-1 fashion. Example: pores1 = [[0, 1], [2, 3]] and pores2 = [[5], [7, 9]] leads to creation of the following connections: 0 --> 5
python
{ "resource": "" }
q20820
find_pore_to_pore_distance
train
def find_pore_to_pore_distance(network, pores1=None, pores2=None): r''' Find the distance between all pores on set one to each pore in set 2 Parameters ---------- network : OpenPNM Network Object The network object containing the pore coordinates pores1 : array_like The pore indices of the first set pores2 : array_Like The pore
python
{ "resource": "" }
q20821
merge_pores
train
def merge_pores(network, pores, labels=['merged']): r""" Combines a selection of pores into a new single pore located at the centroid of the selected pores and connected to all of their neighbors. Parameters ---------- network : OpenPNM Network Object pores : array_like The list of pores which are to be combined into a new single pore labels : string or list of strings The labels to apply to the new pore and new throat connections Notes ----- (1) The method also works if a list of lists is passed, in which case it consecutively merges the given selections of pores. (2) The selection of pores should be chosen carefully, preferrable so that they all form a continuous cluster. For instance, it is recommended to use the ``find_nearby_pores`` method to find all pores within a certain distance of a given pore, and these can then be merged without causing any abnormal connections. Examples -------- >>> import openpnm as op >>> pn = op.network.Cubic(shape=[20, 20, 1]) >>> Ps = pn.find_nearby_pores(pores=111, r=5, flatten=True) >>> op.topotools.merge_pores(network=pn, pores=Ps, labels=['merged']) >>> print(pn.Np) 321 >>> pn.pores('merged') array([320]) >>> pn.num_throats('merged') 32 """ # Assert that `pores` is list of lists try: len(pores[0]) except (TypeError, IndexError): pores = [pores] N = len(pores) NBs, XYZs = [], [] for Ps in pores: NBs.append(network.find_neighbor_pores(pores=Ps, mode='union', flatten=True, include_input=False)) XYZs.append(network['pore.coords'][Ps].mean(axis=0))
python
{ "resource": "" }
q20822
template_sphere_shell
train
def template_sphere_shell(outer_radius, inner_radius=0): r""" This method generates an image array of a sphere-shell. It is useful for passing to Cubic networks as a ``template`` to make spherical shaped networks. Parameters ---------- outer_radius : int Number of nodes in the
python
{ "resource": "" }
q20823
template_cylinder_annulus
train
def template_cylinder_annulus(height, outer_radius, inner_radius=0): r""" This method generates an image array of a disc-ring. It is useful for passing to Cubic networks as a ``template`` to make circular-shaped 2D networks. Parameters ---------- height : int The height of the cylinder outer_radius : int Number of nodes in the outer radius of the cylinder inner_radius : int Number of the nodes in the inner radius of the annulus. A value of 0 will result in a solid cylinder. Returns
python
{ "resource": "" }
q20824
plot_connections
train
def plot_connections(network, throats=None, fig=None, **kwargs): r""" Produces a 3D plot of the network topology showing how throats connect for quick visualization without having to export data to veiw in Paraview. Parameters ---------- network : OpenPNM Network Object The network whose topological connections to plot throats : array_like (optional) The list of throats to plot if only a sub-sample is desired. This is useful for inspecting a small region of the network. If no throats are specified then all throats are shown. fig : Matplotlib figure handle and line property arguments If a ``fig`` is supplied, then the topology will be overlaid on this plot. This makes it possible to combine coordinates and connections, and to color different throats differently (see ``kwargs``) kwargs : other named arguments By also in different line properties such as ``color`` it's possible to plot several different sets of connections with unique colors. For information on available line style options, visit the Matplotlib documentation on the `web <http://matplotlib.org/api/lines_api.html#matplotlib.lines.Line2D>`_ Notes ----- The figure handle returned by this method can be passed into ``plot_coordinates`` to create a plot that combines pore coordinates and throat connections, and
python
{ "resource": "" }
q20825
plot_coordinates
train
def plot_coordinates(network, pores=None, fig=None, **kwargs): r""" Produces a 3D plot showing specified pore coordinates as markers Parameters ---------- network : OpenPNM Network Object The network whose topological connections to plot pores : array_like (optional) The list of pores to plot if only a sub-sample is desired. This is useful for inspecting a small region of the network. If no pores are specified then all are shown. fig : Matplotlib figure handle If a ``fig`` is supplied, then the coordinates will be overlaid. This enables the plotting of multiple different sets of pores as well as throat connections from ``plot_connections``. kwargs : dict By also in different marker properties such as size (``s``) and color (``c``). For information on available marker style options, visit the Matplotlib documentation on the `web <http://matplotlib.org/api/lines_api.html#matplotlib.lines.Line2D>`_ Notes ----- The figure handle returned by this method can be passed into ``plot_topology`` to create a plot that combines pore coordinates and throat connections, and vice versa. See Also -------- plot_connections Examples -------- >>> import openpnm as op >>> pn = op.network.Cubic(shape=[10, 10, 3]) >>> pn.add_boundary_pores() >>> Ps = pn.pores('internal') >>> # Create figure showing internal pores >>> fig = op.topotools.plot_coordinates(network=pn, pores=Ps, c='b') >>> Ps = pn.pores('*boundary') >>> # Pass existing fig back into function to plot boundary pores
python
{ "resource": "" }
q20826
plot_networkx
train
def plot_networkx(network, plot_throats=True, labels=None, colors=None, scale=10): r''' Returns a pretty 2d plot for 2d OpenPNM networks. Parameters ---------- network : OpenPNM Network object plot_throats : boolean Plots throats as well as pores, if True. labels : list List of OpenPNM labels colors : list List of corresponding colors to the given `labels`. scale : float Scale factor for size of pores. ''' import networkx as nx x, y, z = network['pore.coords'].T x, y = [j for j in [x, y, z] if not sp.allclose(j, j.mean())] G = nx.Graph() pos = {network.Ps[i]: [x[i], y[i]] for i in range(network.Np)} if 'pore.diameter' in network.keys(): node_size = scale * network['pore.diameter'] else: node_size = scale node_color = sp.array(['r'] * len(network.Ps)) if labels: if type(labels) is not list: labels = [labels] if type(colors) is not list: colors = [colors] if len(labels) != len(colors):
python
{ "resource": "" }
q20827
reflect_base_points
train
def reflect_base_points(base_pts, domain_size): r''' Helper function for relecting a set of points about the faces of a given domain. Parameters ---------- base_pts : array_like The coordinates of the base_pts to be reflected in the coordinate system corresponding to the the domain as follows: **spherical** : [r, theta, phi] **cylindrical** or **circular** : [r, theta, z] **rectangular** or **square** : [x, y, z] domain_size : list or array Controls the size and shape of the domain, as follows: **sphere** : If a single value is received, its treated as the radius [r] of a sphere centered on [0, 0, 0]. **cylinder** : If a two-element list is received it's treated as the radius and height of a cylinder [r, z] positioned at [0, 0, 0] and extending in the positive z-direction. If the z dimension is 0, a disk of radius r is created. **rectangle** : If a three element list is received, it's treated as the outer corner of rectangle [x, y, z] whose opposite corner lies at
python
{ "resource": "" }
q20828
find_clusters
train
def find_clusters(network, mask=[], t_labels=False): r""" Identify connected clusters of pores in the network. This method can also return a list of throat cluster numbers, which correspond to the cluster numbers of the pores to which the throat is connected. Either site and bond percolation can be considered, see description of input arguments for details. Parameters ---------- network : OpenPNM Network Object The network mask : array_like, boolean A list of active bonds or sites (throats or pores). If the mask is Np long, then the method will perform a site percolation, and if the mask is Nt long bond percolation will be performed. Returns
python
{ "resource": "" }
q20829
add_boundary_pores
train
def add_boundary_pores(network, pores, offset, apply_label='boundary'): r""" This method uses ``clone_pores`` to clone the input pores, then shifts them the specified amount and direction, then applies the given label. Parameters ---------- pores : array_like List of pores to offset. If no pores are specified, then it assumes that all surface pores are to be cloned. offset : 3 x 1 array The distance in vector form which the cloned boundary pores should be offset. apply_label : string This label is applied to the boundary pores. Default is 'boundary'. Examples -------- >>> import openpnm as op >>> pn = op.network.Cubic(shape=[5, 5, 5]) >>> print(pn.Np)
python
{ "resource": "" }
q20830
find_path
train
def find_path(network, pore_pairs, weights=None): r""" Find the shortest path between pairs of pores. Parameters ---------- network : OpenPNM Network Object The Network object on which the search should be performed pore_pairs : array_like An N x 2 array containing N pairs of pores for which the shortest path is sought. weights : array_like, optional An Nt-long list of throat weights for the search. Typically this would be the throat lengths, but could also be used to represent the phase configuration. If no weights are given then the standard topological connections of the Network are used. Returns ------- A dictionary containing both the pores and throats that define the shortest path connecting each pair of input pores. Notes ----- The shortest path is found using Dijkstra's algorithm included in the scipy.sparse.csgraph module TODO: The returned throat path contains the correct values, but not necessarily in the true order Examples -------- >>> import openpnm as op >>> pn = op.network.Cubic(shape=[3, 3, 3]) >>> a = op.topotools.find_path(network=pn, pore_pairs=[[0, 4], [0, 10]]) >>> a['pores'] [array([0, 1, 4]), array([ 0, 1, 10])] >>> a['throats'] [array([ 0, 19]), array([ 0, 37])] """ Ps = sp.array(pore_pairs, ndmin=2) if weights is None: weights = sp.ones_like(network.Ts)
python
{ "resource": "" }
q20831
iscoplanar
train
def iscoplanar(coords): r''' Determines if given pores are coplanar with each other Parameters ---------- coords : array_like List of pore coords to check for coplanarity. At least 3 pores are required. Returns ------- A boolean value of whether given points are coplanar (True) or not (False) ''' coords = sp.array(coords, ndmin=1) if sp.shape(coords)[0] < 3: raise Exception('At least 3 input pores are required') Px = coords[:, 0] Py = coords[:, 1] Pz = coords[:, 2] # Do easy check first, for common coordinate if sp.shape(sp.unique(Px))[0] == 1: return True if sp.shape(sp.unique(Py))[0] == 1:
python
{ "resource": "" }
q20832
OhmicConduction.calc_effective_conductivity
train
def calc_effective_conductivity(self, inlets=None, outlets=None, domain_area=None, domain_length=None): r""" This calculates the effective electrical conductivity. Parameters ---------- inlets : array_like The pores where the inlet voltage boundary conditions were applied. If not given an attempt is made to infer them from the algorithm. outlets : array_like The pores where the outlet voltage boundary conditions were applied. If not given an attempt is made to infer them from the algorithm. domain_area : scalar, optional The area of the inlet (and outlet) boundary faces. If not given then an attempt is made to estimate it, but it is usually underestimated. domain_length : scalar, optional The length of the domain between the inlet and outlet boundary faces. If not given then an attempt
python
{ "resource": "" }
q20833
washburn
train
def washburn(target, surface_tension='pore.surface_tension', contact_angle='pore.contact_angle', diameter='throat.diameter'): r""" Computes the capillary entry pressure assuming the throat in a cylindrical tube. Parameters ---------- target : OpenPNM Object The object for which these values are being calculated. This controls the length of the calculated array, and also provides access to other necessary thermofluid properties. surface_tension : string The dictionary key containing the surface tension values to be used. If a pore property is given, it is interpolated to a throat list. contact_angle : string The dictionary key containing the contact angle values to be used. If
python
{ "resource": "" }
q20834
purcell
train
def purcell(target, r_toroid, surface_tension='pore.surface_tension', contact_angle='pore.contact_angle', diameter='throat.diameter'): r""" Computes the throat capillary entry pressure assuming the throat is a toroid. Parameters ---------- target : OpenPNM Object The object for which these values are being calculated. This controls the length of the calculated array, and also provides access to other necessary thermofluid properties. r_toroid : float or array_like The radius of the toroid surrounding the pore surface_tension : dict key (string) The dictionary key containing the surface tension values to be used. If a pore property is given, it is interpolated to a throat list. contact_angle : dict key (string) The dictionary key containing the contact angle values to be used. If a pore property is given, it is interpolated to a throat list. diameter : dict key (string) The dictionary key containing the throat diameter values to be used. Notes ----- This approach accounts for the converging-diverging nature of many throat types. Advancing the meniscus beyond the apex of the toroid requires an increase in capillary pressure beyond that for a cylindical tube of the same radius. The details of this equation are described by Mason and Morrow [1]_, and explored by Gostick [2]_ in the context of a pore network model. References ---------- .. [1] G. Mason, N. R. Morrow, Effect of contact angle on capillary displacement curvatures in pore throats formed by spheres. J.
python
{ "resource": "" }
q20835
ransohoff_snap_off
train
def ransohoff_snap_off(target, shape_factor=2.0, wavelength=5e-6, require_pair=False, surface_tension='pore.surface_tension', contact_angle='pore.contact_angle', diameter='throat.diameter', vertices='throat.offset_vertices', **kwargs): r""" Computes the capillary snap-off pressure assuming the throat is cylindrical with converging-diverging change in diamater - like the Purcell model. The wavelength of the change in diamater is the fiber radius. Parameters ---------- target : OpenPNM Object The object for which these values are being calculated. This controls the length of the calculated array, and also provides access to other necessary thermofluid properties. shape_factor : constant dependent on the shape of throat cross-section 1.75 - 2.0, see Ref wavelength : float or array like The transverse interfacial radius of curvature at the neck (fiber radius in fibrous media) require_pair : bool Controls whether snap-off requires a pair of arc meniscii to occur. surface_tension : dict key (string) The dictionary key containing the surface tension values to be used. If a pore property is given, it is interpolated to a throat list. contact_angle : dict key (string) The dictionary key containing the contact angle values to be used. If a pore property is given, it is interpolated to a throat list. throat_diameter : dict key (string) The dictionary key containing the throat diameter values to be used. Notes ----- This equation should be used to calculate the snap off capillary pressure in fribrous media References ---------- [1]: Ransohoff, T.C., Gauglitz, P.A. and Radke, C.J., 1987. Snap‐off of gas bubbles in smoothly constricted noncircular capillaries. AIChE Journal, 33(5), pp.753-765. """ phase = target.project.find_phase(target) geometry = target.project.find_geometry(target) element, sigma, theta = _get_key_props(phase=phase, diameter=diameter, surface_tension=surface_tension, contact_angle=contact_angle) try: all_verts = geometry[vertices] # Work out whether throat geometry can support at least one pair of # adjacent arc menisci that can grow and merge to form snap-off # Only works if throat vertices are in convex hull order angles_ok = np.zeros(geometry.Nt, dtype=bool) for T in range(geometry.Nt): verts = all_verts[T] x = verts[:, 0] y = verts[:, 1] z = verts[:, 2] # PLus p = 1 # Minus m = -1 verts_p = np.vstack((np.roll(x, p), np.roll(y, p), np.roll(z, p))).T verts_m = np.vstack((np.roll(x, m), np.roll(y, m),
python
{ "resource": "" }
q20836
purcell_bidirectional
train
def purcell_bidirectional(target, r_toroid, num_points=1e2, surface_tension='pore.surface_tension', contact_angle='pore.contact_angle', throat_diameter='throat.diameter', pore_diameter='pore.diameter'): r""" Computes the throat capillary entry pressure assuming the throat is a toroid. Makes use of the toroidal meniscus model with mode touch. This model accounts for mensicus protrusion into adjacent pores and touching solid features. It is bidirectional becauase the connected pores generally have different sizes and this determines how far the meniscus can protrude. Parameters ---------- target : OpenPNM Object The object for which these values are being calculated. This controls the length of the calculated array, and also provides access to other necessary thermofluid properties. r_toroid : float or array_like The radius of the toroid surrounding the pore num_points : float (Default 100) The number of divisions to make along the profile length to assess the meniscus properties in order to find the touch length. surface_tension : dict key (string) The dictionary key containing the surface tension values to be used. If a pore property is given, it is interpolated to a throat list. contact_angle : dict key (string) The dictionary key containing the contact angle values to be used. If a pore property is given, it is interpolated to a throat list.
python
{ "resource": "" }
q20837
sinusoidal_bidirectional
train
def sinusoidal_bidirectional(target, num_points=1e2, surface_tension='pore.surface_tension', contact_angle='pore.contact_angle', throat_diameter='throat.diameter', throat_amplitude='throat.amplitude', throat_length='throat.length', pore_diameter='pore.diameter'): r""" Computes the throat capillary entry pressure assuming the throat has a sinusoisal profile. Makes use of the toroidal meniscus model with mode touch. This model accounts for mensicus protrusion into adjacent pores and touching solid features. It is bidirectional becauase the connected pores generally have different sizes and this determines how far the meniscus can protrude. Parameters ---------- target : OpenPNM Object The object for which these values are being calculated. This controls the length of the calculated array, and also provides access to other necessary thermofluid properties num_points : float (Default 100) The number of divisions to make along the profile length to assess the meniscus properties in order to find the touch length. surface_tension : dict key (string) The dictionary key containing the surface tension values to be used. If a pore property is given, it is interpolated to a throat list. contact_angle : dict key (string) The dictionary key containing the contact angle values to be used. If a pore property is given, it is interpolated to a throat list. throat_diameter : dict key (string) The dictionary key containing the throat diameter values to be
python
{ "resource": "" }
q20838
NetworkX.to_networkx
train
def to_networkx(cls, network): r""" Write OpenPNM Network to a NetworkX object. Parameters ---------- network : OpenPNM Network Object The OpenPNM Network to be converted to a NetworkX object Returns ------- A NetworkX object with all pore/throat properties attached to it """ # Ensure network is an OpenPNM Network object. if not isinstance(network, GenericNetwork): raise('Provided network is not an OpenPNM Network.') G = nx.Graph() # Extracting node list and connectivity matrix from Network nodes = map(int, network.Ps) conns = network['throat.conns'] # Explicitly add nodes and connectivity matrix G.add_nodes_from(nodes) G.add_edges_from(conns) # Attach Network properties to G for prop in network.props(deep=True) + network.labels(): if 'pore.' in prop: if len(network[prop].shape) > 1:
python
{ "resource": "" }
q20839
conduit_conductance
train
def conduit_conductance(target, throat_conductance, throat_occupancy='throat.occupancy', pore_occupancy='pore.occupancy', mode='strict', factor=1e-6): r""" Determines the conductance of a pore-throat-pore conduit based on the invaded state of each element. Parameters ---------- target : OpenPNM Object The OpenPNM object where the model is attached. Should either be a Physics or a Phase. throat_conductance : string The transport conductance of the phase associated with the ``target`` object at single-phase conditions. pore_occupancy : string The property name containing the occupancy of the phase associated with the ``target`` object. An occupancy of 1 means the pore is completely filled with the phase and it fully conducts. throat_occupancy : string The property name containing the occupancy of the phase associated with the ``target`` object. An occupancy of 1 means the throat is completely filled with the phase and it fully conducts. mode : 'strict' or 'medium' or 'loose' How agressive the method should be when determining if a conduit is closed. **'strict'** : If any pore or throat in the conduit is unoccupied by the given phase, the conduit is closed. **'medium'** : If either the throat or both pores are unoccupied, the
python
{ "resource": "" }
q20840
pore_coords
train
def pore_coords(target): r""" The average of the pore coords """ network = target.project.network
python
{ "resource": "" }
q20841
ModelsDict.dependency_list
train
def dependency_list(self): r''' Returns a list of dependencies in the order with which they should be called to ensure data is calculated by one model before it's asked for by another. Notes ----- This raises an exception if the graph has cycles which means the dependencies are unresolvable (i.e. there is no order which the models can be called that will work). In this case it is possible to visually inspect the graph using ``dependency_graph``. See Also -------- dependency_graph
python
{ "resource": "" }
q20842
ModelsDict.dependency_graph
train
def dependency_graph(self): r""" Returns a NetworkX graph object of the dependencies See Also -------- dependency_list dependency_map Notes ----- To visualize the dependencies, the following NetworkX function and settings is helpful: nx.draw_spectral(d, arrowsize=50, font_size=32, with_labels=True, node_size=2000, width=3.0, edge_color='lightgrey', font_weight='bold') """
python
{ "resource": "" }
q20843
ModelsDict.dependency_map
train
def dependency_map(self): r""" Create a graph of the dependency graph in a decent format See Also -------- dependency_graph dependency_list """ dtree = self.dependency_graph() fig = nx.draw_spectral(dtree, with_labels=True, arrowsize=50,
python
{ "resource": "" }
q20844
ModelsMixin.regenerate_models
train
def regenerate_models(self, propnames=None, exclude=[], deep=False): r""" Re-runs the specified model or models. Parameters ---------- propnames : string or list of strings The list of property names to be regenerated. If None are given then ALL models are re-run (except for those whose ``regen_mode`` is 'constant'). exclude : list of strings Since the default behavior is to run ALL models, this can be used to exclude specific models. It may be more convenient to supply as list of 2 models to exclude than to specify 8 models to include. deep : boolean Specifies whether or not to regenerate models on all associated objects. For instance, if ``True``, then all Physics models will be regenerated when method is called on the corresponding Phase. The default is ``False``. The method does not work in reverse, so regenerating models on a Physics will not update a Phase. """ # If empty list of propnames was given, do nothing and return if type(propnames) is list and len(propnames) == 0: return if type(propnames) is str: # Convert string to list if necessary propnames = [propnames] if propnames is None: # If no props given, then regenerate them all propnames = self.models.dependency_list() # If some props are to be excluded, remove them from list if len(exclude) > 0: propnames = [i for i in propnames if i not in exclude] # Re-order given propnames according to dependency tree self_models = self.models.dependency_list() propnames = [i for i in self_models if i in propnames] if deep: other_models = None # Will trigger regen of ALL models else: # Make list of given propnames that are not in self
python
{ "resource": "" }
q20845
ModelsMixin.remove_model
train
def remove_model(self, propname=None, mode=['model', 'data']): r""" Removes model and data from object. Parameters ---------- propname : string or list of strings The property or list of properties to remove mode : list of strings Controls what is removed. Options are: *'model'* : Removes the model but not any numerical data that may already exist. *'data'* : Removes the data but leaves the model. The default is both.
python
{ "resource": "" }
q20846
equivalent_diameter
train
def equivalent_diameter(target, throat_area='throat.area', throat_shape='circle'): r""" Calculates the diameter of a cirlce or edge-length of a sqaure with same area as the throat. Parameters ---------- target : OpenPNM Object The object which this model is associated with. This controls the length of the calculated array, and also provides access to other necessary properties. thorat_area : string The dictionary key to the throat area values throat_shape : string The shape cross-sectional shape of the throat to assume when
python
{ "resource": "" }
q20847
TransientReactiveTransport.set_IC
train
def set_IC(self, values): r""" A method to set simulation initial conditions Parameters ---------- values : ND-array or scalar Set the initial conditions using an 'Np' long array. 'Np' being the number of pores. If a scalar is given, the same value is
python
{ "resource": "" }
q20848
TransientReactiveTransport._t_update_A
train
def _t_update_A(self): r""" A method to update 'A' matrix at each time step according to 't_scheme' """ network = self.project.network Vi = network['pore.volume'] dt = self.settings['t_step'] s = self.settings['t_scheme'] if (s == 'implicit'): f1, f2 = 1, 1 elif (s == 'cranknicolson'): f1, f2 = 0.5, 1 elif (s == 'steady'): f1, f2 = 1, 0 # Compute A (operations involve conversion to
python
{ "resource": "" }
q20849
TransientReactiveTransport._t_update_b
train
def _t_update_b(self): r""" A method to update 'b' array at each time step according to 't_scheme' and the source term value """ network = self.project.network phase = self.project.phases()[self.settings['phase']] Vi = network['pore.volume'] dt = self.settings['t_step'] s = self.settings['t_scheme'] if (s == 'implicit'): f1, f2, f3 = 1, 1, 0 elif (s == 'cranknicolson'): f1, f2, f3 = 0.5, 1, 0 elif (s == 'steady'):
python
{ "resource": "" }
q20850
TransientReactiveTransport._t_run_reactive
train
def _t_run_reactive(self, x): """r Repeatedly updates transient 'A', 'b', and the solution guess within each time step according to the applied source term then calls '_solve' to solve the resulting system of linear equations. Stops when the residual falls below 'r_tolerance'. Parameters ---------- x : ND-array Initial guess of unknown variable Returns ------- x_new : ND-array Solution array. Notes ----- Description of 'relaxation_quantity' and 'max_iter' settings can be found in the parent class 'ReactiveTransport' documentation. """ if x is None: x = np.zeros(shape=[self.Np, ], dtype=float) self[self.settings['quantity']] = x relax = self.settings['relaxation_quantity'] res = 1e+06 for itr in range(int(self.settings['max_iter'])): if res >= self.settings['r_tolerance']: logger.info('Tolerance not met: ' + str(res)) self[self.settings['quantity']] = x self._A
python
{ "resource": "" }
q20851
general_symbolic
train
def general_symbolic(target, eqn=None, arg_map=None): r''' A general function to interpret a sympy equation and evaluate the linear components of the source term. Parameters ---------- target : OpenPNM object The OpenPNM object where the result will be applied. eqn : sympy symbolic expression for the source terms e.g. y = a*x**b + c arg_map : Dict mapping the symbols in the expression to OpenPNM data on the target. Must contain 'x' which is the independent variable. e.g. arg_map={'a':'pore.a', 'b':'pore.b', 'c':'pore.c', 'x':'pore.x'} Example ---------- >>> import openpnm as op >>> from openpnm.models.physics import generic_source_term as gst >>> import scipy as sp >>> import sympy as _syp >>> pn = op.network.Cubic(shape=[5, 5, 5], spacing=0.0001) >>> water = op.phases.Water(network=pn) >>> water['pore.a'] = 1 >>> water['pore.b'] = 2 >>> water['pore.c'] = 3 >>> water['pore.x'] = sp.random.random(water.Np) >>> a, b, c, x = _syp.symbols('a,b,c,x') >>> y = a*x**b + c >>> arg_map = {'a':'pore.a', 'b':'pore.b', 'c':'pore.c', 'x':'pore.x'} >>> water.add_model(propname='pore.general', ... model=gst.general_symbolic, ... eqn=y, arg_map=arg_map, ... regen_mode='normal') >>> assert 'pore.general.rate' in water.props() >>> assert 'pore.general.S1' in water.props() >>> assert 'pore.general.S1' in water.props()
python
{ "resource": "" }
q20852
toc
train
def toc(quiet=False): r""" Homemade version of matlab tic and toc function, tic starts or resets the clock, toc reports the time since the last call of tic. Parameters ---------- quiet : Boolean If False (default) then a message is output to the console. If True
python
{ "resource": "" }
q20853
flat_list
train
def flat_list(input_list): r""" Given a list of nested lists of arbitrary depth, returns a single level or 'flat' list. """ x
python
{ "resource": "" }
q20854
sanitize_dict
train
def sanitize_dict(input_dict): r""" Given a nested dictionary, ensures that all nested dicts are normal Python dicts. This is necessary for pickling, or just converting an 'auto-vivifying' dict to something that acts normal. """ plain_dict = dict() for key in input_dict.keys(): value =
python
{ "resource": "" }
q20855
models_to_table
train
def models_to_table(obj, params=True): r""" Converts a ModelsDict object to a ReST compatible table Parameters ---------- obj : OpenPNM object Any object that has a ``models`` attribute params : boolean Indicates whether or not to include a list of parameter values in the table. Set to False for just a list of models, and True for a more verbose table with all parameter values. """ if not hasattr(obj, 'models'): raise Exception('Received object does not have any models') row = '+' + '-'*4 + '+' + '-'*22 + '+' + '-'*18 + '+' + '-'*26 + '+' fmt = '{0:1s} {1:2s} {2:1s} {3:20s} {4:1s} {5:16s} {6:1s} {7:24s} {8:1s}' lines = [] lines.append(row) lines.append(fmt.format('|', '#', '|', 'Property Name', '|', 'Parameter', '|', 'Value', '|')) lines.append(row.replace('-', '=')) for i, item in enumerate(obj.models.keys()): prop = item if len(prop) > 20: prop = item[:17] + "..." temp = obj.models[item].copy() model = str(temp.pop('model')).split(' ')[1] lines.append(fmt.format('|', str(i+1), '|', prop, '|',
python
{ "resource": "" }
q20856
conduit_lengths
train
def conduit_lengths(network, throats=None, mode='pore'): r""" Return the respective lengths of the conduit components defined by the throat conns P1 T P2 mode = 'pore' - uses pore coordinates mode = 'centroid' uses pore and throat centroids """ if throats is None: throats = network.throats() Ps = network['throat.conns'] pdia = network['pore.diameter'] if mode == 'centroid': try: pcentroids = network['pore.centroid'] tcentroids = network['throat.centroid'] if _sp.sum(_sp.isnan(pcentroids)) + _sp.sum(_sp.isnan(tcentroids)) > 0: mode = 'pore' else: plen1 = _sp.sqrt(_sp.sum(_sp.square(pcentroids[Ps[:, 0]] - tcentroids), 1))-network['throat.length']/2 plen2 = _sp.sqrt(_sp.sum(_sp.square(pcentroids[Ps[:, 1]] - tcentroids), 1))-network['throat.length']/2 except KeyError: mode = 'pore' if mode == 'pore': # Find half-lengths of each
python
{ "resource": "" }
q20857
FickianDiffusion.calc_effective_diffusivity
train
def calc_effective_diffusivity(self, inlets=None, outlets=None, domain_area=None, domain_length=None): r""" This calculates the effective diffusivity in this linear transport algorithm. Parameters ---------- inlets : array_like The pores where the inlet composition boundary conditions were applied. If not given an attempt is made to infer them from the algorithm. outlets : array_like The pores where the outlet composition boundary conditions were applied. If not given an attempt is made to infer them from the algorithm. domain_area : scalar, optional The area of the inlet (and outlet) boundary faces. If not given then an attempt is made to estimate it, but it is usually underestimated. domain_length : scalar, optional The length of the domain between the inlet and outlet boundary faces. If
python
{ "resource": "" }
q20858
Subdomain._set_locations
train
def _set_locations(self, element, indices, mode, complete=False): r""" This private method is called by ``set_locations`` and ``remove_locations`` as needed. """ boss = self.project.find_full_domain(self) element = self._parse_element(element=element, single=True) # Make sure label array exists in boss if (element+'.'+self.name) not in boss.keys(): boss[element+'.'+self.name] = False # Check to ensure indices aren't already assigned if mode == 'add': if self._isa('geometry'): objs = self.project.geometries().keys() else: objs = self.project.physics().keys() for name in objs: if element+'.'+name in boss.keys(): if np.any(boss[element+'.'+name][indices]): raise Exception('Given indices are already assigned ' + 'to ' + name) # Find mask of existing locations (network indexing) mask = boss[element+'.'+self.name] # Update mask with new locations (either add or
python
{ "resource": "" }
q20859
ctc
train
def ctc(target, pore_diameter='pore.diameter'): r""" Calculate throat length assuming point-like pores, i.e. center-to-center distance between pores. Also, this models assumes that pores and throat centroids are colinear. Parameters ---------- target : OpenPNM Object The object which this model is associated with. This controls the length of the calculated array, and also provides
python
{ "resource": "" }
q20860
piecewise
train
def piecewise(target, throat_endpoints='throat.endpoints', throat_centroid='throat.centroid'): r""" Calculate throat length from end points and optionally a centroid Parameters ---------- target : OpenPNM Object The object which this model is associated with. This controls the length of the calculated array, and also provides access to other necessary properties. throat_endpoints : string Dictionary key of the throat endpoint values. throat_centroid : string Dictionary key of the throat centroid values, optional. Returns ------- Lt : ndarray Array containing throat lengths for the given geometry. Notes ----- (1) By default, the model assumes that the centroids of pores and the connecting throat in each conduit are colinear. (2) If `throat_centroid` is passed, the model accounts for the extra length. This could be useful for Voronoi or extracted networks.
python
{ "resource": "" }
q20861
conduit_lengths
train
def conduit_lengths(target, throat_endpoints='throat.endpoints', throat_length='throat.length'): r""" Calculate conduit lengths. A conduit is defined as half pore + throat + half pore. Parameters ---------- target : OpenPNM Object The object which this model is associated with. This controls the length of the calculated array, and also provides access to other necessary properties. throat_endpoints : string Dictionary key of the throat endpoint values. throat_diameter : string Dictionary key of the throat length values. throat_length : string (optional) Dictionary key of the throat length values. If not given then the direct distance bewteen the two throat end points is used. Returns ------- Dictionary containing conduit lengths, which can be accessed via the dict keys 'pore1', 'pore2', and 'throat'. """ _np.warnings.filterwarnings('ignore', category=RuntimeWarning) network = target.project.network throats = network.map_throats(throats=target.Ts, origin=target)
python
{ "resource": "" }
q20862
standard
train
def standard(target, mol_weight='pore.molecular_weight', molar_density='pore.molar_density'): r""" Calculates the mass density from the molecular weight and molar density Parameters ---------- mol_weight : string The dictionary key containing the molecular weight values molar_density : string
python
{ "resource": "" }
q20863
Dict.save
train
def save(cls, dct, filename): r""" Saves data from the given dictionary into the specified file. Parameters ---------- dct : dictionary A dictionary to save to file, presumably obtained from the ``to_dict`` method of this class. filename : string or path object
python
{ "resource": "" }
q20864
Dict.load
train
def load(cls, filename): r""" Load data from the specified file into a Python dictionary Parameters ---------- filename : string The path to the file to be opened Notes ----- This returns a Python dictionary which can be converted
python
{ "resource": "" }
q20865
OrdinaryPercolation.set_inlets
train
def set_inlets(self, pores=[], overwrite=False): r""" Set the locations from which the invader enters the network Parameters ---------- pores : array_like Locations that are initially filled with invader, from which clusters grow and invade into the network overwrite : boolean If ``True`` then all existing inlet locations will be removed and then the supplied locations will be added. If ``False`` (default), then supplied locations are added to any already existing inlet locations.
python
{ "resource": "" }
q20866
OrdinaryPercolation.set_residual
train
def set_residual(self, pores=[], throats=[], overwrite=False): r""" Specify locations of any residual invader. These locations are set to invaded at the start of the simulation. Parameters ---------- pores : array_like The pores locations that are to be filled with invader at the beginning of the simulation. throats : array_like The throat locations that are to be filled with invader at the beginning of the simulation. overwrite : boolean If ``True`` then all existing inlet locations will be removed and then
python
{ "resource": "" }
q20867
OrdinaryPercolation.get_percolation_threshold
train
def get_percolation_threshold(self): r""" Find the invasion threshold at which a cluster spans from the inlet to the outlet sites """ if np.sum(self['pore.inlets']) == 0: raise Exception('Inlet pores must be specified first') if np.sum(self['pore.outlets']) == 0: raise Exception('Outlet pores must be specified first') else: Pout = self['pore.outlets'] # Do a simple check of pressures on the outlet pores first...
python
{ "resource": "" }
q20868
OrdinaryPercolation.is_percolating
train
def is_percolating(self, applied_pressure): r""" Returns a True or False value to indicate if a percolating cluster spans between the inlet and outlet pores that were specified at the given applied pressure. Parameters ---------- applied_pressure : scalar, float The pressure at which percolation should be checked Returns ------- A simple boolean True or False if percolation has occured or not. """ if np.sum(self['pore.inlets']) == 0: raise Exception('Inlet pores must be specified first')
python
{ "resource": "" }
q20869
OrdinaryPercolation.run
train
def run(self, points=25, start=None, stop=None): r""" Runs the percolation algorithm to determine which pores and throats will be invaded at each given pressure point. Parameters ---------- points: int or array_like An array containing the pressure points to apply. If a scalar is given then an array will be generated with the given number of points spaced between the lowest and highest values of throat entry pressures using logarithmic spacing. To specify low and high pressure points use the ``start`` and ``stop`` arguments. start : int The optional starting point to use when generating pressure points. stop : int The optional stopping point to use when generating pressure points. """ phase = self.project.find_phase(self) # Parse inputs and generate list of invasion points if necessary if self.settings['mode'] == 'bond': self['throat.entry_pressure'] = \ phase[self.settings['throat_entry_threshold']] if start is None: start = sp.amin(self['throat.entry_pressure'])*0.95 if stop is None: stop = sp.amax(self['throat.entry_pressure'])*1.05 elif self.settings['mode'] == 'site': self['pore.entry_pressure'] = \ phase[self.settings['pore_entry_threshold']] if start is None: start = sp.amin(self['pore.entry_pressure'])*0.95 if stop is None: stop = sp.amax(self['pore.entry_pressure'])*1.05 else: raise Exception('Percolation type has not been set') if type(points) is int: points = sp.logspace(start=sp.log10(max(1, start)), stop=sp.log10(stop), num=points) # Ensure pore inlets have been set IF access limitations is True if self.settings['access_limited']: if sp.sum(self['pore.inlets']) == 0: raise Exception('Inlet pores must be specified first') else: Pin = self['pore.inlets'] # Generate curve from points conns = self.project.network['throat.conns'] for inv_val in points:
python
{ "resource": "" }
q20870
OrdinaryPercolation.get_intrusion_data
train
def get_intrusion_data(self, Pc=None): r""" Obtain the numerical values of the calculated intrusion curve Returns ------- A named-tuple containing arrays of applied capillary pressures and invading phase saturation. """ net = self.project.network if Pc is None: # Infer list of applied capillary pressures points = np.unique(self['throat.invasion_pressure']) # Add a low pressure point to the list to improve graph points = np.concatenate(([0], points)) if points[-1] == np.inf: # Remove infinity from points if present points = points[:-1] else: points = np.array(Pc) # Get pore and throat volumes Pvol = net[self.settings['pore_volume']] Tvol = net[self.settings['throat_volume']] Total_vol = np.sum(Pvol) + np.sum(Tvol) # Find cumulative filled volume at each applied capillary pressure Vnwp_t = [] Vnwp_p = [] Vnwp_all = []
python
{ "resource": "" }
q20871
OrdinaryPercolation.plot_intrusion_curve
train
def plot_intrusion_curve(self, fig=None): r""" Plot the percolation curve as the invader volume or number fraction vs the applied capillary pressure. """ # Begin creating nicely formatted plot x, y = self.get_intrusion_data() if fig is None:
python
{ "resource": "" }
q20872
OrdinaryPercolation.results
train
def results(self, Pc): r""" This method determines which pores and throats are filled with invading phase at the specified capillary pressure, and creates several arrays indicating the occupancy status of each pore and throat for the given pressure. Parameters ---------- Pc : scalar The capillary pressure for which an invading phase configuration is desired. Returns ------- A dictionary containing an assortment of data about distribution of the invading phase at the specified capillary pressure. The data include: **'pore.occupancy'** : A value between 0 and 1 indicating the fractional volume of each pore that is invaded. If no late pore filling model was applied, then this will only
python
{ "resource": "" }
q20873
percolating_continua
train
def percolating_continua(target, phi_crit, tau, volume_fraction='pore.volume_fraction', bulk_property='pore.intrinsic_conductivity'): r''' Calculates the effective property of a continua using percolation theory Parameters ---------- target : OpenPNM Object The object for which these values are being calculated. This controls the length of the calculated array, and also provides access to other necessary thermofluid properties. volume_fraction : string The dictionary key in the Phase object containing the volume fraction of the conducting component bulk_property : string The dictionary key in the Phase object containing the intrinsic property of the conducting component
python
{ "resource": "" }
q20874
ReactiveTransport.set_source
train
def set_source(self, propname, pores): r""" Applies a given source term to the specified pores Parameters ---------- propname : string The property name of the source term model to be applied pores : array_like The pore indices where the source term should be applied Notes ----- Source terms cannot be applied in pores where boundary conditions have already been set. Attempting to do so will result in an error being raised. """ locs = self.tomask(pores=pores) if (not np.all(np.isnan(self['pore.bc_value'][locs]))) or
python
{ "resource": "" }
q20875
ReactiveTransport._set_BC
train
def _set_BC(self, pores, bctype, bcvalues=None, mode='merge'): r""" Apply boundary conditions to specified pores if no source terms are already assigned to these pores. Otherwise, raise an error. Parameters ---------- pores : array_like The pores where the boundary conditions should be applied bctype : string Specifies the type or the name of boundary condition to apply. The types can be one one of the following: - *'value'* : Specify the value of the quantity in each location - *'rate'* : Specify the flow rate into each location bcvalues : int or array_like The boundary value to apply, such as concentration or rate. If a single value is given, it's assumed to apply to all locations. Different values can be applied to all pores in the form of an array of the same length as ``pores``. mode : string, optional Controls how the conditions are applied. Options are: *'merge'*: (Default) Adds supplied boundary conditions to already existing conditions. *'overwrite'*: Deletes all boundary condition on object then add the given ones
python
{ "resource": "" }
q20876
ReactiveTransport._update_physics
train
def _update_physics(self): """r Update physics using the current value of 'quantity' Notes ----- The algorithm directly writes the value of 'quantity' into the phase. This method was implemented relaxing one of the OpenPNM rules of algorithms not being able to write into phases. """ phase = self.project.phases()[self.settings['phase']] physics = self.project.find_physics(phase=phase) for item in self.settings['sources']: # Regenerate models with new guess quantity = self.settings['quantity'] # Put quantity on phase
python
{ "resource": "" }
q20877
ReactiveTransport._apply_sources
train
def _apply_sources(self): """r Update 'A' and 'b' applying source terms to specified pores Notes ----- Applying source terms to 'A' and 'b' is performed after (optionally) under-relaxing the source term to improve numerical stability. Physics are also updated before applying source terms to ensure that source terms values are associated with the current value of 'quantity'. In the case of a transient simulation, the updates in 'A' and 'b' also depend on the time scheme. """ if self.settings['t_scheme'] == 'cranknicolson': f1 = 0.5 else: f1 = 1 phase = self.project.phases()[self.settings['phase']] relax = self.settings['relaxation_source'] for item in self.settings['sources']: Ps = self.pores(item) # Add S1 to diagonal of A # TODO: We need this to NOT overwrite the A and b, but create # copy, otherwise we have to regenerate A and b on each loop datadiag = self._A.diagonal().copy() # Source term relaxation
python
{ "resource": "" }
q20878
ReactiveTransport.run
train
def run(self, x=None): r""" Builds the A and b matrices, and calls the solver specified in the ``settings`` attribute. Parameters ---------- x : ND-array Initial guess of unknown variable
python
{ "resource": "" }
q20879
ReactiveTransport._run_reactive
train
def _run_reactive(self, x): """r Repeatedly updates 'A', 'b', and the solution guess within according to the applied source term then calls '_solve' to solve the resulting system of linear equations. Stops when the residual falls below 'r_tolerance' or when the maximum number of iterations is reached. Parameters ---------- x : ND-array Initial guess of unknown variable Returns ------- x_new : ND-array Solution array. """ if x is None: x = np.zeros(shape=[self.Np, ], dtype=float) self[self.settings['quantity']] = x relax = self.settings['relaxation_quantity'] res = 1e+06 # Initialize the residual for itr in range(int(self.settings['max_iter'])): if res >= self.settings['r_tolerance']: logger.info('Tolerance not met: ' + str(res)) self[self.settings['quantity']] = x self._build_A(force=True) self._build_b(force=True)
python
{ "resource": "" }
q20880
sphere
train
def sphere(target, pore_diameter='pore.diameter'): r""" Calculate pore volume from diameter assuming a spherical pore body Parameters ---------- target : OpenPNM Object The object which this model is associated with. This controls the length of the calculated array, and also provides access to other necessary geometric
python
{ "resource": "" }
q20881
cylinder
train
def cylinder(target, throat_length='throat.length', throat_diameter='throat.diameter'): r""" Calculate throat volume assuing a cylindrical shape Parameters ---------- target : OpenPNM Object The object which this model is associated with. This controls the length of the calculated array, and also provides access
python
{ "resource": "" }
q20882
cuboid
train
def cuboid(target, throat_length='throat.length', throat_diameter='throat.diameter'): r""" Calculate throat volume assuing a square cross-section Parameters ---------- target : OpenPNM Object The object which this model is associated with. This controls the length of the calculated array, and also provides
python
{ "resource": "" }
q20883
extrusion
train
def extrusion(target, throat_length='throat.length', throat_area='throat.area'): r""" Calculate throat volume from the throat area and the throat length. This method is useful for abnormal shaped throats. Parameters ---------- target : OpenPNM Object The object which this model is associated with. This controls the length of the calculated array, and also provides access to other necessary properties. throat_length and throat_area : strings The dictionary keys containing the arrays with the throat area and length values.
python
{ "resource": "" }
q20884
HDF5.to_hdf5
train
def to_hdf5(cls, network=None, phases=[], element=['pore', 'throat'], filename='', interleave=True, flatten=False, categorize_by=[]): r""" Creates an HDF5 file containing data from the specified objects, and categorized according to the given arguments. Parameters ---------- network : OpenPNM Network Object The network containing the desired data phases : list of OpenPNM Phase Objects (optional, default is none) A list of phase objects whose data are to be included element : string or list of strings An indication of whether 'pore' and/or 'throat' data are desired. The default is both. interleave : boolean (default is ``True``) When ``True`` (default) the data from all Geometry objects (and Physics objects if ``phases`` are given) is interleaved into a single array and stored as a network property (or Phase property for Physics data). When ``False``, the data for each object are stored under their own dictionary key, the structuring of which depends on the value of the ``flatten`` argument. flatten : boolean (default is ``True``) When ``True``, all objects are accessible from the top level of the dictionary. When ``False`` objects are nested under their parent object. If ``interleave`` is ``True`` this argument is ignored. categorize_by : string or list of strings Indicates how the dictionaries should be organized. The list can contain any, all or none of the following strings: **'objects'** : If specified the dictionary keys will be stored under a general level corresponding to their type (e.g. 'network/net_01/pore.all'). If ``interleave`` is ``True`` then only the only categories are *network* and *phase*, since *geometry* and *physics* data get stored under their respective *network* and *phase*. **'data'** : If specified the data arrays are additionally categorized by ``label`` and ``property`` to separate *boolean* from *numeric* data. **'elements'** : If specified the data arrays are additionally
python
{ "resource": "" }
q20885
get_objects_in_sequence
train
def get_objects_in_sequence(brain_or_object, ctype, cref): """Return a list of items """ obj = api.get_object(brain_or_object) if ctype == "backreference": return get_backreferences(obj, cref) if
python
{ "resource": "" }
q20886
get_backreferences
train
def get_backreferences(obj, relationship): """Returns the backreferences """ refs = get_backuidreferences(obj, relationship) # TODO remove after all ReferenceField get ported to UIDReferenceField # At this moment, there are still some content types that are
python
{ "resource": "" }
q20887
get_type_id
train
def get_type_id(context, **kw): """Returns the type id for the context passed in """ portal_type = kw.get("portal_type", None) if portal_type: return portal_type # Override by provided marker interface if IAnalysisRequestPartition.providedBy(context): return "AnalysisRequestPartition"
python
{ "resource": "" }
q20888
strip_suffix
train
def strip_suffix(id): """Split off any suffix from ID This mimics the old behavior of the Sample ID. """ suffix = get_suffix(id)
python
{ "resource": "" }
q20889
get_partition_count
train
def get_partition_count(context, default=0): """Returns the number of partitions of this AR """ if not is_ar(context): return default parent =
python
{ "resource": "" }
q20890
get_secondary_count
train
def get_secondary_count(context, default=0): """Returns the number of secondary ARs of this AR """ if not is_ar(context): return default primary = context.getPrimaryAnalysisRequest()
python
{ "resource": "" }
q20891
get_config
train
def get_config(context, **kw): """Fetch the config dict from the Bika Setup for the given portal_type """ # get the ID formatting config config_map = api.get_bika_setup().getIDFormatting() # allow portal_type override portal_type = get_type_id(context, **kw) # check if we have a config for the given portal_type for config in config_map: if config['portal_type'].lower() ==
python
{ "resource": "" }
q20892
get_variables
train
def get_variables(context, **kw): """Prepares a dictionary of key->value pairs usable for ID formatting """ # allow portal_type override portal_type = get_type_id(context, **kw) # The variables map hold the values that might get into the constructed id variables = { "context": context, "id": api.get_id(context), "portal_type": portal_type, "year": get_current_year(), "parent": api.get_parent(context), "seq": 0, "alpha": Alphanumber(0), } # Augment the variables map depending on the portal type if portal_type in AR_TYPES: now = DateTime() sampling_date = context.getSamplingDate() sampling_date = sampling_date and DT2dt(sampling_date) or DT2dt(now) date_sampled = context.getDateSampled() date_sampled = date_sampled and DT2dt(date_sampled) or DT2dt(now) test_count = 1 variables.update({ "clientId": context.getClientID(), "dateSampled": date_sampled, "samplingDate": sampling_date, "sampleType": context.getSampleType().getPrefix(), "test_count": test_count }) # Partition if portal_type == "AnalysisRequestPartition": parent_ar = context.getParentAnalysisRequest() parent_ar_id = api.get_id(parent_ar) parent_base_id = strip_suffix(parent_ar_id) partition_count = get_partition_count(context) variables.update({ "parent_analysisrequest": parent_ar, "parent_ar_id": parent_ar_id, "parent_base_id": parent_base_id, "partition_count": partition_count, }) # Retest elif portal_type == "AnalysisRequestRetest": # Note: we use "parent" instead of "invalidated" for simplicity parent_ar = context.getInvalidated() parent_ar_id = api.get_id(parent_ar) parent_base_id = strip_suffix(parent_ar_id) # keep the full ID if the retracted AR is a partition if context.isPartition(): parent_base_id = parent_ar_id
python
{ "resource": "" }
q20893
slice
train
def slice(string, separator="-", start=None, end=None): """Slice out a segment of a string, which is splitted on both the wildcards and the separator passed in, if any """ # split by wildcards/keywords first # AR-{sampleType}-{parentId}{alpha:3a2d} segments = filter(None, re.split('(\{.+?\})', string)) # ['AR-', '{sampleType}', '-', '{parentId}', '{alpha:3a2d}'] if separator: # Keep track of singleton separators as empties # We need to do this to prevent duplicates later, when splitting segments = map(lambda seg: seg!=separator and seg or "", segments) # ['AR-', '{sampleType}', '', '{parentId}', '{alpha:3a2d}'] # Split each segment at the given separator segments = map(lambda seg: split(seg, separator), segments) # [['AR', ''], ['{sampleType}'], [''], ['{parentId}'], ['{alpha:3a2d}']] # Flatten the list segments = list(itertools.chain.from_iterable(segments)) # ['AR', '', '{sampleType}', '', '{parentId}', '{alpha:3a2d}']
python
{ "resource": "" }
q20894
search_by_prefix
train
def search_by_prefix(portal_type, prefix): """Returns brains which share the same portal_type and ID prefix """ catalog = api.get_tool("uid_catalog")
python
{ "resource": "" }
q20895
get_ids_with_prefix
train
def get_ids_with_prefix(portal_type, prefix): """Return a list of ids sharing the same portal
python
{ "resource": "" }
q20896
get_seq_number_from_id
train
def get_seq_number_from_id(id, id_template, prefix, **kw): """Return the sequence number of the given ID """ separator = kw.get("separator", "-") postfix = id.replace(prefix, "").strip(separator) postfix_segments = postfix.split(separator) seq_number = 0 possible_seq_nums = filter(lambda n: n.isalnum(), postfix_segments) if possible_seq_nums: seq_number = possible_seq_nums[-1]
python
{ "resource": "" }
q20897
get_alpha_or_number
train
def get_alpha_or_number(number, template): """Returns an Alphanumber that represents the number passed in, expressed as defined in the template. Otherwise, returns the number """ match = re.match(r".*\{alpha:(\d+a\d+d)\}$", template.strip())
python
{ "resource": "" }
q20898
get_counted_number
train
def get_counted_number(context, config, variables, **kw): """Compute the number for the sequence type "Counter" """ # This "context" is defined by the user in the Setup and can be actually # anything. However, we assume it is something like "sample" or similar ctx = config.get("context") # get object behind the context name (falls back to the current context) obj = variables.get(ctx, context) # get the counter type, which is either "backreference" or "contained" counter_type = config.get("counter_type")
python
{ "resource": "" }
q20899
get_generated_number
train
def get_generated_number(context, config, variables, **kw): """Generate a new persistent number with the number generator for the sequence type "Generated" """ # separator where to split the ID separator = kw.get('separator', '-') # allow portal_type override portal_type = get_type_id(context, **kw) # The ID format for string interpolation, e.g. WS-{seq:03d} id_template = config.get("form", "") # The split length defines where the key is splitted from the value split_length = config.get("split_length", 1) # The prefix template is the static part of the ID prefix_template = slice(id_template, separator=separator, end=split_length) # get the number generator number_generator = getUtility(INumberGenerator) # generate the key for the number generator storage prefix = prefix_template.format(**variables) # normalize out any unicode characters like Ö, É, etc. from the prefix prefix = api.normalize_filename(prefix) # The key used for the storage key = make_storage_key(portal_type, prefix) # Handle flushed storage if key not in number_generator: max_num = 0 existing = get_ids_with_prefix(portal_type, prefix) numbers = map(lambda id: get_seq_number_from_id(id, id_template, prefix), existing) # figure out the highest number in the sequence if numbers: max_num = max(numbers) #
python
{ "resource": "" }