_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q20700
cylinder
train
def cylinder(target, throat_diameter='throat.diameter'): r""" Calculate throat cross-sectional area for a cylindrical 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. throat_diameter : string Dictionary key of the throat diameter values """ diams = target[throat_diameter] value = _pi/4*(diams)**2 return value
python
{ "resource": "" }
q20701
DelaunayGeometry._t_normals
train
def _t_normals(self): r""" Update the throat normals from the voronoi vertices """ verts = self['throat.vertices'] value = sp.zeros([len(verts), 3]) for i in range(len(verts)): if len(sp.unique(verts[i][:, 0])) == 1: verts_2d = sp.vstack((verts[i][:, 1], verts[i][:, 2])).T elif len(sp.unique(verts[i][:, 1])) == 1: verts_2d = sp.vstack((verts[i][:, 0], verts[i][:, 2])).T else: verts_2d = sp.vstack((verts[i][:, 0], verts[i][:, 1])).T hull = sptl.ConvexHull(verts_2d, qhull_options='QJ Pp') sorted_verts = verts[i][hull.vertices].astype(float) v1 = sorted_verts[-1]-sorted_verts[0] v2 = sorted_verts[1]-sorted_verts[0] value[i] = tr.unit_vector(sp.cross(v1, v2)) return value
python
{ "resource": "" }
q20702
DelaunayGeometry._centroids
train
def _centroids(self, verts): r''' Function to calculate the centroid as the mean of a set of vertices. Used for pore and throat. ''' value = sp.zeros([len(verts), 3]) for i, i_verts in enumerate(verts): value[i] = np.mean(i_verts, axis=0) return value
python
{ "resource": "" }
q20703
DelaunayGeometry._indiameter_from_fibers
train
def _indiameter_from_fibers(self): r""" Calculate an indiameter by distance transforming sections of the fiber image. By definition the maximum value will be the largest radius of an inscribed sphere inside the fibrous hull """ Np = self.num_pores() indiam = np.zeros(Np, dtype=float) incen = np.zeros([Np, 3], dtype=float) hull_pores = np.unique(self._hull_image) (Lx, Ly, Lz) = np.shape(self._hull_image) (indx, indy, indz) = np.indices([Lx, Ly, Lz]) indx = indx.flatten() indy = indy.flatten() indz = indz.flatten() for i, pore in enumerate(hull_pores): logger.info("Processing pore: "+str(i)+" of "+str(len(hull_pores))) dt_pore = self._dt_image*(self._hull_image == pore) indiam[pore] = dt_pore.max()*2 max_ind = np.argmax(dt_pore) incen[pore, 0] = indx[max_ind] incen[pore, 1] = indy[max_ind] incen[pore, 2] = indz[max_ind] indiam *= self.network.resolution incen *= self.network.resolution return (indiam, incen)
python
{ "resource": "" }
q20704
DelaunayGeometry._throat_c2c
train
def _throat_c2c(self): r""" Calculate the center to center distance from centroid of pore1 to centroid of throat to centroid of pore2. """ net = self.network Nt = net.num_throats() p_cen = net['pore.centroid'] t_cen = net['throat.centroid'] conns = net['throat.conns'] p1 = conns[:, 0] p2 = conns[:, 1] v1 = t_cen-p_cen[p1] v2 = t_cen-p_cen[p2] check_nan = ~sp.any(sp.isnan(v1 + v2), axis=1) value = sp.ones([Nt, 3], dtype=float)*sp.nan for i in range(Nt): if check_nan[i]: value[i, 0] = sp.linalg.norm(v1[i]) - self.network.fiber_rad value[i, 1] = self.network.fiber_rad*2 value[i, 2] = sp.linalg.norm(v2[i]) - self.network.fiber_rad return value[net.throats(self.name)]
python
{ "resource": "" }
q20705
DelaunayGeometry.in_hull_volume
train
def in_hull_volume(self): r""" Work out the voxels inside the convex hull of the voronoi vertices of each pore """ i = self.network['pore.internal'] s = self.network['pore.surface'] d = self.network['pore.delaunay'] Ps = self.network.pores()[np.logical_and(d, np.logical_or(i, s))] inds = self.network._map(ids=self['pore._id'][Ps], element='pore', filtered=True) # Get the fiber image self._get_fiber_image(inds) hull_image = np.ones_like(self._fiber_image, dtype=np.uint16)*-1 self._hull_image = hull_image for pore in Ps: logger.info("Processing Pore: "+str(pore+1)+" of "+str(len(Ps))) verts = self['pore.vertices'][pore] verts = np.asarray(unique_list(np.around(verts, 6))) verts /= self.network.resolution self.inhull(verts, pore) self._process_pore_voxels()
python
{ "resource": "" }
q20706
DelaunayGeometry._process_pore_voxels
train
def _process_pore_voxels(self): r''' Function to count the number of voxels in the pore and fiber space Which are assigned to each hull volume ''' num_Ps = self.num_pores() pore_vox = sp.zeros(num_Ps, dtype=int) fiber_vox = sp.zeros(num_Ps, dtype=int) pore_space = self._hull_image.copy() fiber_space = self._hull_image.copy() pore_space[self._fiber_image == 0] = -1 fiber_space[self._fiber_image == 1] = -1 freq_pore_vox = itemfreq(pore_space) freq_pore_vox = freq_pore_vox[freq_pore_vox[:, 0] > -1] freq_fiber_vox = itemfreq(fiber_space) freq_fiber_vox = freq_fiber_vox[freq_fiber_vox[:, 0] > -1] pore_vox[freq_pore_vox[:, 0]] = freq_pore_vox[:, 1] fiber_vox[freq_fiber_vox[:, 0]] = freq_fiber_vox[:, 1] self['pore.volume'] = pore_vox*self.network.resolution**3 del pore_space del fiber_space
python
{ "resource": "" }
q20707
DelaunayGeometry._bresenham
train
def _bresenham(self, faces, dx): r''' A Bresenham line function to generate points to fill in for the fibers ''' line_points = [] for face in faces: # Get in hull order fx = face[:, 0] fy = face[:, 1] fz = face[:, 2] # Find the axis with the smallest spread and remove it to make 2D if (np.std(fx) < np.std(fy)) and (np.std(fx) < np.std(fz)): f2d = np.vstack((fy, fz)).T elif (np.std(fy) < np.std(fx)) and (np.std(fy) < np.std(fz)): f2d = np.vstack((fx, fz)).T else: f2d = np.vstack((fx, fy)).T hull = sptl.ConvexHull(f2d, qhull_options='QJ Pp') face = np.around(face[hull.vertices].astype(float), 6) for i in range(len(face)): vec = face[i]-face[i-1] vec_length = np.linalg.norm(vec) increments = np.ceil(vec_length/dx) check_p_old = np.array([-1, -1, -1]) for x in np.linspace(0, 1, increments): check_p_new = face[i-1]+(vec*x) if np.sum(check_p_new - check_p_old) != 0: line_points.append(check_p_new) check_p_old = check_p_new return np.asarray(line_points)
python
{ "resource": "" }
q20708
DelaunayGeometry._get_fiber_slice
train
def _get_fiber_slice(self, plane=None, index=None): r""" Plot an image of a slice through the fiber image plane contains percentage values of the length of the image in each axis Parameters ---------- plane : array_like List of 3 values, [x,y,z], 2 must be zero and the other must be between zero and one representing the fraction of the domain to slice along the non-zero axis index : array_like similar to plane but instead of the fraction an index of the image is used """ if hasattr(self, '_fiber_image') is False: logger.warning('This method only works when a fiber image exists') return None if plane is None and index is None: logger.warning('Please provide a plane array or index array') return None if plane is not None: if 'array' not in plane.__class__.__name__: plane = sp.asarray(plane) if sp.sum(plane == 0) != 2: logger.warning('Plane argument must have two zero valued ' + 'elements to produce a planar slice') return None l = sp.asarray(sp.shape(self._fiber_image)) s = sp.around(plane*l).astype(int) s[s>=self._fiber_image.shape] -= 1 elif index is not None: if 'array' not in index.__class__.__name__: index = sp.asarray(index) if sp.sum(index == 0) != 2: logger.warning('Index argument must have two zero valued ' + 'elements to produce a planar slice') return None if 'int' not in str(index.dtype): index = sp.around(index).astype(int) s = index if s[0] != 0: slice_image = self._fiber_image[s[0], :, :] elif s[1] != 0: slice_image = self._fiber_image[:, s[1], :] else: slice_image = self._fiber_image[:, :, s[2]] return slice_image
python
{ "resource": "" }
q20709
DelaunayGeometry.plot_fiber_slice
train
def plot_fiber_slice(self, plane=None, index=None, fig=None): r""" Plot one slice from the fiber image Parameters ---------- plane : array_like List of 3 values, [x,y,z], 2 must be zero and the other must be between zero and one representing the fraction of the domain to slice along the non-zero axis index : array_like similar to plane but instead of the fraction an index of the image is used """ if hasattr(self, '_fiber_image') is False: logger.warning('This method only works when a fiber image exists') return slice_image = self._get_fiber_slice(plane, index) if slice_image is not None: if fig is None: plt.figure() plt.imshow(slice_image.T, cmap='Greys', origin='lower', interpolation='nearest') return fig
python
{ "resource": "" }
q20710
DelaunayGeometry.plot_porosity_profile
train
def plot_porosity_profile(self, fig=None): r""" Return a porosity profile in all orthogonal directions by summing the voxel volumes in consectutive slices. """ if hasattr(self, '_fiber_image') is False: logger.warning('This method only works when a fiber image exists') return l = sp.asarray(sp.shape(self._fiber_image)) px = sp.zeros(l[0]) py = sp.zeros(l[1]) pz = sp.zeros(l[2]) for x in sp.arange(l[0]): px[x] = sp.sum(self._fiber_image[x, :, :]) px[x] /= sp.size(self._fiber_image[x, :, :]) for y in sp.arange(l[1]): py[y] = sp.sum(self._fiber_image[:, y, :]) py[y] /= sp.size(self._fiber_image[:, y, :]) for z in sp.arange(l[2]): pz[z] = sp.sum(self._fiber_image[:, :, z]) pz[z] /= sp.size(self._fiber_image[:, :, z]) if fig is None: fig = plt.figure() ax = fig.gca() plots = [] plots.append(plt.plot(sp.arange(l[0])/l[0], px, 'r', label='x')) plots.append(plt.plot(sp.arange(l[1])/l[1], py, 'g', label='y')) plots.append(plt.plot(sp.arange(l[2])/l[2], pz, 'b', label='z')) plt.xlabel('Normalized Distance') plt.ylabel('Porosity') handles, labels = ax.get_legend_handles_labels() ax.legend(handles, labels, loc=1) plt.legend(bbox_to_anchor=(1, 1), loc=2, borderaxespad=0.) return fig
python
{ "resource": "" }
q20711
VoronoiGeometry._throat_props
train
def _throat_props(self): r''' Helper Function to calculate the throat normal vectors ''' network = self.network net_Ts = network.throats(self.name) conns = network['throat.conns'][net_Ts] p1 = conns[:, 0] p2 = conns[:, 1] coords = network['pore.coords'] normals = tr.unit_vector(coords[p2]-coords[p1]) self['throat.normal'] = normals self['throat.centroid'] = (coords[p1] + coords[p2])/2 self['throat.incenter'] = self['throat.centroid']
python
{ "resource": "" }
q20712
pore_to_pore
train
def pore_to_pore(target): r""" Calculates throat vector as straight path between connected pores. Parameters ---------- geometry : OpenPNM Geometry object The object containing the geometrical properties of the throats Notes ----- There is an important impicit assumption here: the positive direction is taken as the direction from the pore with the lower index to the higher. This corresponds to the pores in the 1st and 2nd columns of the 'throat.conns' array as stored on the etwork. """ network = target.project.network throats = network.throats(target.name) conns = network['throat.conns'] P1 = conns[:, 0] P2 = conns[:, 1] coords = network['pore.coords'] vec = coords[P2] - coords[P1] unit_vec = tr.unit_vector(vec, axis=1) return unit_vec[throats]
python
{ "resource": "" }
q20713
GenericTransport.setup
train
def setup(self, phase=None, quantity='', conductance='', **kwargs): r""" This method takes several arguments that are essential to running the algorithm and adds them to the settings. Parameters ---------- phase : OpenPNM Phase object The phase on which the algorithm is to be run. quantity : string The name of the physical quantity to be calculated. conductance : string The name of the pore-scale transport conductance values. These are typically calculated by a model attached to a *Physics* object associated with the given *Phase*. solver : string To use the default scipy solver, set this value to `spsolve` or `umfpack`. To use an iterative solver or a non-scipy solver, additional arguments are required as described next. solver_family : string The solver package to use. OpenPNM currently supports ``scipy``, ``pyamg`` and ``petsc`` (if you have it installed). The default is ``scipy``. solver_type : string The specific solver to use. For instance, if ``solver_family`` is ``scipy`` then you can specify any of the iterative solvers such as ``cg`` or ``gmres``. [More info here] (https://docs.scipy.org/doc/scipy/reference/sparse.linalg.html) solver_preconditioner : string This is used by the PETSc solver to specify which preconditioner to use. The default is ``jacobi``. solver_atol : scalar Used to control the accuracy to which the iterative solver aims. The default is 1e-6. solver_rtol : scalar Used by PETSc as an additional tolerance control. The default is 1e-6. solver_maxiter : scalar Limits the number of iterations to attempt before quiting when aiming for the specified tolerance. The default is 5000. """ if phase: self.settings['phase'] = phase.name if quantity: self.settings['quantity'] = quantity if conductance: self.settings['conductance'] = conductance self.settings.update(**kwargs)
python
{ "resource": "" }
q20714
GenericTransport.set_value_BC
train
def set_value_BC(self, pores, values): r""" Apply constant value boundary conditons to the specified pore locations. These are sometimes referred to as Dirichlet conditions. Parameters ---------- pores : array_like The pore indices where the condition should be applied values : scalar or array_like The value to of the boundary condition. If a scalar is supplied it is assigne to all locations, and if a vector is applied it corresponds directy to the locations given in ``pores``. Notes ----- The definition of ``quantity`` is specified in the algorithm's ``settings``, e.g. ``alg.settings['quentity'] = 'pore.pressure'``. """ self._set_BC(pores=pores, bctype='value', bcvalues=values, mode='merge')
python
{ "resource": "" }
q20715
GenericTransport.set_rate_BC
train
def set_rate_BC(self, pores, values): r""" Apply constant rate boundary conditons to the specified pore locations. This is similar to a Neumann boundary condition, but is slightly different since it's the conductance multiplied by the gradient, while Neumann conditions specify just the gradient. Parameters ---------- pores : array_like The pore indices where the condition should be applied values : scalar or array_like The value to of the boundary condition. If a scalar is supplied it is assigne to all locations, and if a vector is applied it corresponds directy to the locations given in ``pores``. Notes ----- The definition of ``quantity`` is specified in the algorithm's ``settings``, e.g. ``alg.settings['quentity'] = 'pore.pressure'``. """ self._set_BC(pores=pores, bctype='rate', bcvalues=values, mode='merge')
python
{ "resource": "" }
q20716
GenericTransport._set_BC
train
def _set_BC(self, pores, bctype, bcvalues=None, mode='merge'): r""" Apply boundary conditions to specified pores 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 Notes ----- It is not possible to have multiple boundary conditions for a specified location in one algorithm. Use ``remove_BCs`` to clear existing BCs before applying new ones or ``mode='overwrite'`` which removes all existing BC's before applying the new ones. """ # Hijack the parse_mode function to verify bctype argument bctype = self._parse_mode(bctype, allowed=['value', 'rate'], single=True) mode = self._parse_mode(mode, allowed=['merge', 'overwrite', 'remove'], single=True) pores = self._parse_indices(pores) values = np.array(bcvalues) if values.size > 1 and values.size != pores.size: raise Exception('The number of boundary values must match the ' + 'number of locations') # Store boundary values if ('pore.bc_'+bctype not in self.keys()) or (mode == 'overwrite'): self['pore.bc_'+bctype] = np.nan self['pore.bc_'+bctype][pores] = values
python
{ "resource": "" }
q20717
GenericTransport.remove_BC
train
def remove_BC(self, pores=None): r""" Removes all boundary conditions from the specified pores Parameters ---------- pores : array_like The pores from which boundary conditions are to be removed. If no pores are specified, then BCs are removed from all pores. No error is thrown if the provided pores do not have any BCs assigned. """ if pores is None: pores = self.Ps if 'pore.bc_value' in self.keys(): self['pore.bc_value'][pores] = np.nan if 'pore.bc_rate' in self.keys(): self['pore.bc_rate'][pores] = np.nan
python
{ "resource": "" }
q20718
GenericTransport._build_b
train
def _build_b(self, force=False): r""" Builds the RHS matrix, without applying any boundary conditions or source terms. This method is trivial an basically creates a column vector of 0's. Parameters ---------- force : Boolean (default is ``False``) If set to ``True`` then the b matrix is built from new. If ``False`` (the default), a cached version of b is returned. The cached version is *clean* in the sense that no boundary conditions or sources terms have been added to it. """ if force: self._pure_b = None if self._pure_b is None: b = np.zeros(shape=(self.Np, ), dtype=float) # Create vector of 0s self._pure_b = b self.b = self._pure_b.copy()
python
{ "resource": "" }
q20719
GenericTransport.results
train
def results(self, times='all', t_precision=12, **kwargs): r""" Fetches the calculated quantity from the algorithm and returns it as an array. Parameters ---------- times : scalar or list Time steps to be returned. The default value is 'all' which results in returning all time steps. If a scalar is given, only the corresponding time step is returned. If a range is given (e.g., 'range(0, 1, 1e-3)'), time steps in this range are returned. t_precision : integer The time precision (number of decimal places). Default value is 12. Notes ----- The keyword steps is interpreted in the same way as times. """ if 'steps' in kwargs.keys(): times = kwargs['steps'] t_pre = t_precision quantity = self.settings['quantity'] q = [k for k in list(self.keys()) if quantity in k] if times == 'all': t = q elif type(times) in [float, int]: n = int(-dc(str(round(times, t_pre))).as_tuple().exponent * (round(times, t_pre) != int(times))) t_str = (str(int(round(times, t_pre)*10**n)) + ('e-'+str(n))*(n != 0)) t = [k for k in q if t_str == k.split('@')[-1]] elif 'range' in times: t = times.replace(' ', '') t = t[6:-1] t = t.split(',') out = np.arange(float(t[0]), float(t[1]), float(t[2])) out = np.append(out, float(t[1])) out = np.unique(out) out = np.around(out, decimals=t_pre) t = [] for i in out: n = int(-dc(str(round(i, t_pre))).as_tuple().exponent * (round(i, t_pre) != int(i))) j = (str(int(round(i, t_pre)*10**n))+('e-'+str(n))*(n != 0)) t_str = [k for k in q if j == k.split('@')[-1]] t += (t_str) d = {k: self[k] for k in t} return d
python
{ "resource": "" }
q20720
GenericTransport.rate
train
def rate(self, pores=[], throats=[], mode='group'): r""" Calculates the net rate of material moving into a given set of pores or throats Parameters ---------- pores : array_like The pores for which the rate should be calculated throats : array_like The throats through which the rate should be calculated mode : string, optional Controls how to return the rate. Options are: *'group'*: (default) Returns the cumulative rate of material moving into the given set of pores *'single'* : Calculates the rate for each pore individually Returns ------- If ``pores`` are specified, then the returned values indicate the net rate of material exiting the pore or pores. Thus a positive rate indicates material is leaving the pores, and negative values mean material is entering. If ``throats`` are specified the rate is calculated in the direction of the gradient, thus is always positive. If ``mode`` is 'single' then the cumulative rate through the given pores (or throats) are returned as a vector, if ``mode`` is 'group' then the individual rates are summed and returned as a scalar. """ pores = self._parse_indices(pores) throats = self._parse_indices(throats) network = self.project.network phase = self.project.phases()[self.settings['phase']] g = phase[self.settings['conductance']] quantity = self[self.settings['quantity']] P12 = network['throat.conns'] X12 = quantity[P12] f = (-1)**np.argsort(X12, axis=1)[:, 1] Dx = np.abs(np.diff(X12, axis=1).squeeze()) Qt = -f*g*Dx if len(throats) and len(pores): raise Exception('Must specify either pores or throats, not both') elif len(throats): R = np.absolute(Qt[throats]) if mode == 'group': R = np.sum(R) elif len(pores): Qp = np.zeros((self.Np, )) np.add.at(Qp, P12[:, 0], -Qt) np.add.at(Qp, P12[:, 1], Qt) R = Qp[pores] if mode == 'group': R = np.sum(R) return np.array(R, ndmin=1)
python
{ "resource": "" }
q20721
GenericTransport._calc_eff_prop
train
def _calc_eff_prop(self, inlets=None, outlets=None, domain_area=None, domain_length=None): r""" Calculate the effective transport through the network Parameters ---------- inlets : array_like The pores where the inlet 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 boundary conditions were applied. If not given an attempt is made to infer them from the algorithm. domain_area : scalar The area of the inlet and/or outlet face (which shold match) domain_length : scalar The length of the domain between the inlet and outlet faces Returns ------- The effective transport property through the network """ if self.settings['quantity'] not in self.keys(): raise Exception('The algorithm has not been run yet. Cannot ' + 'calculate effective property.') Ps = np.isfinite(self['pore.bc_value']) BCs = np.unique(self['pore.bc_value'][Ps]) Dx = np.abs(np.diff(BCs)) if inlets is None: inlets = self._get_inlets() flow = self.rate(pores=inlets) # Fetch area and length of domain if domain_area is None: domain_area = self._get_domain_area(inlets=inlets, outlets=outlets) if domain_length is None: domain_length = self._get_domain_length(inlets=inlets, outlets=outlets) D = np.sum(flow)*domain_length/domain_area/Dx return D
python
{ "resource": "" }
q20722
Base.get
train
def get(self, keys, default=None): r""" This subclassed method can be used to obtain a dictionary containing subset of data on the object Parameters ---------- keys : string or list of strings The item or items to retrieve. default : any object The value to return in the event that the requested key(s) is not found. The default is ``None``. Returns ------- If a single string is given in ``keys``, this method behaves exactly as the ``dict's`` native ``get`` method and returns just the item requested (or the ``default`` if not found). If, however, a list of strings is received, then a dictionary containing each of the requested items is returned. Notes ----- This is useful for creating Pandas Dataframes of a specific subset of data. Note that a Dataframe can be initialized with a ``dict``, but all columns must be the same length. (e.g. ``df = pd.Dataframe(d)``) Examples -------- >>> import openpnm as op >>> pn = op.network.Cubic(shape=[5, 5, 5]) >>> pore_props = pn.props(element='pore') >>> subset = pn.get(keys=pore_props) >>> print(len(subset)) # Only pore.coords, so gives dict with 1 array 1 >>> subset = pn.get(['pore.top', 'pore.bottom']) >>> print(len(subset)) # Returns a dict with the 2 requested array 2 It behaves exactly as normal with a dict key string is supplied: >>> array = pn.get('pore.coords') >>> print(array.shape) # Returns requested array (125, 3) """ # If a list of several keys is passed, then create a subdict if isinstance(keys, list): ret = {} for k in keys: ret[k] = super().get(k, default) else: # Otherwise return numpy array ret = super().get(keys, default) return ret
python
{ "resource": "" }
q20723
Base.props
train
def props(self, element=None, mode='all', deep=False): r""" Returns a list containing the names of all defined pore or throat properties. Parameters ---------- element : string, optional Can be either 'pore' or 'throat' to specify what properties are returned. If no element is given, both are returned mode : string, optional Controls what type of properties are returned. Options are: **'all'** : Returns all properties on the object (default) **'models'** : Returns only properties that are associated with a model **'constants'** : returns data values that were *not* generated by a model, but manaully created. deep : boolean If ``True`` this will also return the data on any associated subdomain objects Returns ------- A an alphabetically sorted list containing the string name of all pore or throat properties currently defined. This list is an iterable, so is useful for scanning through properties. See Also -------- labels keys Examples -------- >>> import openpnm as op >>> pn = op.network.Cubic(shape=[3, 3, 3]) >>> pn.props('pore') ['pore.coords'] >>> pn.props('throat') ['throat.conns'] >>> pn.props() ['pore.coords', 'throat.conns'] """ # Parse Inputs element = self._parse_element(element=element) allowed_modes = ['all', 'constants', 'models'] mode = self._parse_mode(mode=mode, allowed=allowed_modes, single=True) if mode == 'all': vals = set(self.keys(mode='props')) if mode == 'constants': if hasattr(self, 'models'): temp = set(self.keys(mode='props')) vals = temp.difference(self.models.keys()) else: vals = set(self.keys(mode='props')) if mode == 'models': if hasattr(self, 'models'): temp = set(self.keys(mode='props')) vals = temp.intersection(self.models.keys()) else: logger.warning('Object does not have a models attribute') vals = set() # Deal with hidden props hide = set([i for i in self.keys() if i.split('.')[1].startswith('_')]) vals = vals.difference(hide) # Remove values of the wrong element temp = set([i for i in vals if i.split('.')[0] not in element]) vals = set(vals).difference(temp) # Convert to nice list for printing vals = PrintableList(list(vals)) # Repeat for associated objects if deep is True if deep: if self._isa('phase'): for item in self.project.find_physics(phase=self): vals += item.props(element=element, mode=mode, deep=False) if self._isa('network'): for item in self.project.geometries().values(): vals += item.props(element=element, mode=mode, deep=False) return vals
python
{ "resource": "" }
q20724
Base._get_labels
train
def _get_labels(self, element, locations, mode): r""" This is the actual label getter method, but it should not be called directly. Use ``labels`` instead. """ # Parse inputs locations = self._parse_indices(locations) element = self._parse_element(element=element) # Collect list of all pore OR throat labels labels = self.keys(mode='labels', element=element) labels.sort() labels = sp.array(labels) # Convert to ND-array for following checks # Make an 2D array with locations in rows and labels in cols arr = sp.vstack([self[item][locations] for item in labels]).T num_hits = sp.sum(arr, axis=0) # Number of locations with each label if mode in ['or', 'union', 'any']: temp = labels[num_hits > 0] elif mode in ['and', 'intersection']: temp = labels[num_hits == locations.size] elif mode in ['xor', 'exclusive_or']: temp = labels[num_hits == 1] elif mode in ['nor', 'not', 'none']: temp = labels[num_hits == 0] elif mode in ['nand']: temp = labels[num_hits == (locations.size - 1)] elif mode in ['xnor', 'nxor']: temp = labels[num_hits > 1] else: raise Exception('Unrecognized mode:'+str(mode)) return PrintableList(temp)
python
{ "resource": "" }
q20725
Base.labels
train
def labels(self, pores=[], throats=[], element=None, mode='union'): r""" Returns a list of labels present on the object Additionally, this function can return labels applied to a specified set of pores or throats Parameters ---------- element : string Controls whether pore or throat labels are returned. If empty then both are returned (default). pores (or throats) : array_like The pores (or throats) whose labels are sought. If left empty a list containing all pore and throat labels is returned. mode : string, optional Controls how the query should be performed. Only applicable when ``pores`` or ``throats`` are specified: **'or', 'union', 'any'**: (default) Returns the labels that are assigned to *any* of the given locations. **'and', 'intersection', 'all'**: Labels that are present on *all* the given locations. **'xor', 'exclusive_or'** : Labels that are present on *only one* of the given locations. **'nor', 'none', 'not'**: Labels that are *not* present on any of the given locations. **'nand'**: Labels that are present on *all but one* of the given locations **'xnor'**: Labels that are present on *more than one* of the given locations. 'nxor' is also accepted. Returns ------- A list containing the labels on the object. If ``pores`` or ``throats`` are given, the results are filtered according to the specified ``mode``. See Also -------- props keys Notes ----- Technically, *'nand'* and *'xnor'* should also return pores with *none* of the labels but these are not included. This makes the returned list more useful. Examples -------- >>> import openpnm as op >>> pn = op.network.Cubic(shape=[5, 5, 5]) >>> pn.labels(pores=[11, 12]) ['pore.all', 'pore.front', 'pore.internal', 'pore.surface'] """ # Short-circuit query when no pores or throats are given if (sp.size(pores) == 0) and (sp.size(throats) == 0): labels = PrintableList(self.keys(element=element, mode='labels')) elif (sp.size(pores) > 0) and (sp.size(throats) > 0): raise Exception('Cannot perform label query on pores and ' + 'throats simultaneously') elif sp.size(pores) > 0: labels = self._get_labels(element='pore', locations=pores, mode=mode) elif sp.size(throats) > 0: labels = self._get_labels(element='throat', locations=throats, mode=mode) return labels
python
{ "resource": "" }
q20726
Base._get_indices
train
def _get_indices(self, element, labels='all', mode='or'): r""" This is the actual method for getting indices, but should not be called directly. Use ``pores`` or ``throats`` instead. """ # Parse and validate all input values. element = self._parse_element(element, single=True) labels = self._parse_labels(labels=labels, element=element) if element+'.all' not in self.keys(): raise Exception('Cannot proceed without {}.all'.format(element)) # Begin computing label array if mode in ['or', 'any', 'union']: union = sp.zeros_like(self[element+'.all'], dtype=bool) for item in labels: # Iterate over labels and collect all indices union = union + self[element+'.'+item.split('.')[-1]] ind = union elif mode in ['and', 'all', 'intersection']: intersect = sp.ones_like(self[element+'.all'], dtype=bool) for item in labels: # Iterate over labels and collect all indices intersect = intersect*self[element+'.'+item.split('.')[-1]] ind = intersect elif mode in ['xor', 'exclusive_or']: xor = sp.zeros_like(self[element+'.all'], dtype=int) for item in labels: # Iterate over labels and collect all indices info = self[element+'.'+item.split('.')[-1]] xor = xor + sp.int8(info) ind = (xor == 1) elif mode in ['nor', 'not', 'none']: nor = sp.zeros_like(self[element+'.all'], dtype=int) for item in labels: # Iterate over labels and collect all indices info = self[element+'.'+item.split('.')[-1]] nor = nor + sp.int8(info) ind = (nor == 0) elif mode in ['nand']: nand = sp.zeros_like(self[element+'.all'], dtype=int) for item in labels: # Iterate over labels and collect all indices info = self[element+'.'+item.split('.')[-1]] nand = nand + sp.int8(info) ind = (nand < len(labels)) * (nand > 0) elif mode in ['xnor', 'nxor']: xnor = sp.zeros_like(self[element+'.all'], dtype=int) for item in labels: # Iterate over labels and collect all indices info = self[element+'.'+item.split('.')[-1]] xnor = xnor + sp.int8(info) ind = (xnor > 1) else: raise Exception('Unsupported mode: '+mode) # Extract indices from boolean mask ind = sp.where(ind)[0] ind = ind.astype(dtype=int) return ind
python
{ "resource": "" }
q20727
Base.pores
train
def pores(self, labels='all', mode='or', asmask=False): r""" Returns pore indicies where given labels exist, according to the logic specified by the ``mode`` argument. Parameters ---------- labels : string or list of strings The label(s) whose pores locations are requested. This argument also accepts '*' for wildcard searches. mode : string Specifies how the query should be performed. The options are: **'or', 'union', 'any'** : (default) Pores with *one or more* of the given labels are returned. **'and', 'intersection', 'all'** : Pores with *all* of the given labels are returned. **'xor', 'exclusive_or'** : Pores with *only one* of the given labels are returned. **'nor', 'none', 'not'** : Pores with *none* of the given labels are returned. **'nand'** : Pores with *not all* of the given labels are returned. **'xnor'** : Pores with *more than one* of the given labels are returned. asmask : boolean If ``True`` then a boolean array of length Np is returned with ``True`` values indicating the pores that satisfy the query. Returns ------- A Numpy array containing pore indices filtered by the logic specified in ``mode``. See Also -------- throats Notes ----- Technically, *nand* and *xnor* should also return pores with *none* of the labels but these are not included. This makes the returned list more useful. To perform more complex or compound queries, you can opt to receive the result a a boolean mask (``asmask=True``), then manipulate the arrays manually. Examples -------- >>> import openpnm as op >>> pn = op.network.Cubic(shape=[5, 5, 5]) >>> Ps = pn.pores(labels=['top', 'front'], mode='union') >>> Ps[:5] # Look at first 5 pore indices array([0, 1, 2, 3, 4]) >>> pn.pores(labels=['top', 'front'], mode='xnor') array([ 4, 9, 14, 19, 24]) """ ind = self._get_indices(element='pore', labels=labels, mode=mode) if asmask: ind = self.tomask(pores=ind) return ind
python
{ "resource": "" }
q20728
Base.map_pores
train
def map_pores(self, pores, origin, filtered=True): r""" Given a list of pore on a target object, finds indices of those pores on the calling object Parameters ---------- pores : array_like The indices of the pores on the object specifiedin ``origin`` origin : OpenPNM Base object The object corresponding to the indices given in ``pores`` filtered : boolean (default is ``True``) If ``True`` then a ND-array of indices is returned with missing indices removed, otherwise a named-tuple containing both the ``indices`` and a boolean ``mask`` with ``False`` indicating which locations were not found. Returns ------- Pore indices on the calling object corresponding to the same pores on the ``origin`` object. Can be an array or a tuple containing an array and a mask, depending on the value of ``filtered``. """ ids = origin['pore._id'][pores] return self._map(element='pore', ids=ids, filtered=filtered)
python
{ "resource": "" }
q20729
Base.map_throats
train
def map_throats(self, throats, origin, filtered=True): r""" Given a list of throats on a target object, finds indices of those throats on the calling object Parameters ---------- throats : array_like The indices of the throats on the object specified in ``origin`` origin : OpenPNM Base object The object corresponding to the indices given in ``throats`` filtered : boolean (default is ``True``) If ``True`` then a ND-array of indices is returned with missing indices removed, otherwise a named-tuple containing both the ``indices`` and a boolean ``mask`` with ``False`` indicating which locations were not found. Returns ------- Throat indices on the calling object corresponding to the same throats on the target object. Can be an array or a tuple containing an array and a mask, depending on the value of ``filtered``. """ ids = origin['throat._id'][throats] return self._map(element='throat', ids=ids, filtered=filtered)
python
{ "resource": "" }
q20730
Base._tomask
train
def _tomask(self, indices, element): r""" This is a generalized version of tomask that accepts a string of 'pore' or 'throat' for programmatic access. """ element = self._parse_element(element, single=True) indices = self._parse_indices(indices) N = sp.shape(self[element + '.all'])[0] ind = sp.array(indices, ndmin=1) mask = sp.zeros((N, ), dtype=bool) mask[ind] = True return mask
python
{ "resource": "" }
q20731
Base.tomask
train
def tomask(self, pores=None, throats=None): r""" Convert a list of pore or throat indices into a boolean mask of the correct length Parameters ---------- pores or throats : array_like List of pore or throat indices. Only one of these can be specified at a time, and the returned result will be of the corresponding length. Returns ------- A boolean mask of length Np or Nt with True in the specified pore or throat locations. See Also -------- toindices Examples -------- >>> import openpnm as op >>> pn = op.network.Cubic(shape=[5, 5, 5]) >>> mask = pn.tomask(pores=[0, 10, 20]) >>> sum(mask) # 3 non-zero elements exist in the mask (0, 10 and 20) 3 >>> len(mask) # Mask size is equal to the number of pores in network 125 >>> mask = pn.tomask(throats=[0, 10, 20]) >>> len(mask) # Mask is now equal to number of throats in network 300 """ if (pores is not None) and (throats is None): mask = self._tomask(element='pore', indices=pores) elif (throats is not None) and (pores is None): mask = self._tomask(element='throat', indices=throats) else: raise Exception('Cannot specify both pores and throats') return mask
python
{ "resource": "" }
q20732
Base.toindices
train
def toindices(self, mask): r""" Convert a boolean mask to a list of pore or throat indices Parameters ---------- mask : array_like booleans A boolean array with True at locations where indices are desired. The appropriate indices are returned based an the length of mask, which must be either Np or Nt long. Returns ------- A list of pore or throat indices corresponding the locations where the received mask was True. See Also -------- tomask Notes ----- This behavior could just as easily be accomplished by using the mask in ``pn.pores()[mask]`` or ``pn.throats()[mask]``. This method is just a convenience function and is a complement to ``tomask``. """ if sp.amax(mask) > 1: raise Exception('Received mask is invalid, with values above 1') mask = sp.array(mask, dtype=bool) indices = self._parse_indices(mask) return indices
python
{ "resource": "" }
q20733
Base.interleave_data
train
def interleave_data(self, prop): r""" Retrieves requested property from associated objects, to produce a full Np or Nt length array. Parameters ---------- prop : string The property name to be retrieved Returns ------- A full length (Np or Nt) array of requested property values. Notes ----- This makes an effort to maintain the data 'type' when possible; however when data are missing this can be tricky. Data can be missing in two different ways: A set of pores is not assisgned to a geometry or the network contains multiple geometries and data does not exist on all. Float and boolean data is fine, but missing ints are converted to float when nans are inserted. Examples -------- >>> import openpnm as op >>> pn = op.network.Cubic(shape=[2, 2, 2]) >>> Ps = pn['pore.top'] >>> Ts = pn.find_neighbor_throats(pores=Ps) >>> g1 = op.geometry.GenericGeometry(network=pn, pores=Ps, throats=Ts) >>> Ts = ~pn.tomask(throats=Ts) >>> g2 = op.geometry.GenericGeometry(network=pn, pores=~Ps, throats=Ts) >>> g1['pore.value'] = 1 >>> print(g1['pore.value']) [1 1 1 1] >>> print(g2['pore.value']) # 'pore.value' is defined on g1, not g2 [nan nan nan nan] >>> print(pn['pore.value']) [nan 1. nan 1. nan 1. nan 1.] >>> g2['pore.value'] = 20 >>> print(pn['pore.value']) [20 1 20 1 20 1 20 1] >>> pn['pore.label'] = False >>> print(g1['pore.label']) # 'pore.label' is defined on pn, not g1 [False False False False] """ element = self._parse_element(prop.split('.')[0], single=True) N = self.project.network._count(element) # Fetch sources list depending on object type? proj = self.project if self._isa() in ['network', 'geometry']: sources = list(proj.geometries().values()) elif self._isa() in ['phase', 'physics']: sources = list(proj.find_physics(phase=self)) elif self._isa() in ['algorithm', 'base']: sources = [self] else: raise Exception('Unrecognized object type, cannot find dependents') # Attempt to fetch the requested array from each object arrs = [item.get(prop, None) for item in sources] locs = [self._get_indices(element, item.name) for item in sources] sizes = [sp.size(a) for a in arrs] if sp.all([item is None for item in arrs]): # prop not found anywhere raise KeyError(prop) # Check the general type of each array atype = [] for a in arrs: if a is not None: t = a.dtype.name if t.startswith('int') or t.startswith('float'): atype.append('numeric') elif t.startswith('bool'): atype.append('boolean') else: atype.append('other') if not all([item == atype[0] for item in atype]): raise Exception('The array types are not compatible') else: dummy_val = {'numeric': sp.nan, 'boolean': False, 'other': None} # Create an empty array of the right type and shape for item in arrs: if item is not None: if len(item.shape) == 1: temp_arr = sp.zeros((N, ), dtype=item.dtype) else: temp_arr = sp.zeros((N, item.shape[1]), dtype=item.dtype) temp_arr.fill(dummy_val[atype[0]]) # Convert int arrays to float IF NaNs are expected if temp_arr.dtype.name.startswith('int') and \ (sp.any([i is None for i in arrs]) or sp.sum(sizes) != N): temp_arr = temp_arr.astype(float) temp_arr.fill(sp.nan) # Fill new array with values in the corresponding locations for vals, inds in zip(arrs, locs): if vals is not None: temp_arr[inds] = vals else: temp_arr[inds] = dummy_val[atype[0]] return temp_arr
python
{ "resource": "" }
q20734
Base.num_pores
train
def num_pores(self, labels='all', mode='or'): r""" Returns the number of pores of the specified labels Parameters ---------- labels : list of strings, optional The pore labels that should be included in the count. If not supplied, all pores are counted. labels : list of strings Label of pores to be returned mode : string, optional Specifies how the count should be performed. The options are: **'or', 'union', 'any'** : (default) Pores with *one or more* of the given labels are counted. **'and', 'intersection', 'all'** : Pores with *all* of the given labels are counted. **'xor', 'exclusive_or'** : Pores with *only one* of the given labels are counted. **'nor', 'none', 'not'** : Pores with *none* of the given labels are counted. **'nand'** : Pores with *some but not all* of the given labels are counted. **'xnor'** : Pores with *more than one* of the given labels are counted. Returns ------- Np : int Number of pores with the specified labels See Also -------- num_throats count Notes ----- Technically, *'nand'* and *'xnor'* should also count pores with *none* of the labels, however, to make the count more useful these are not included. Examples -------- >>> import openpnm as op >>> pn = op.network.Cubic(shape=[5, 5, 5]) >>> pn.num_pores() 125 >>> pn.num_pores(labels=['top']) 25 >>> pn.num_pores(labels=['top', 'front'], mode='or') 45 >>> pn.num_pores(labels=['top', 'front'], mode='xnor') 5 """ # Count number of pores of specified type Ps = self._get_indices(labels=labels, mode=mode, element='pore') Np = sp.shape(Ps)[0] return Np
python
{ "resource": "" }
q20735
Base.num_throats
train
def num_throats(self, labels='all', mode='union'): r""" Return the number of throats of the specified labels Parameters ---------- labels : list of strings, optional The throat labels that should be included in the count. If not supplied, all throats are counted. mode : string, optional Specifies how the count should be performed. The options are: **'or', 'union', 'any'** : (default) Throats with *one or more* of the given labels are counted. **'and', 'intersection', 'all'** : Throats with *all* of the given labels are counted. **'xor', 'exclusive_or'** : Throats with *only one* of the given labels are counted. **'nor', 'none', 'not'** : Throats with *none* of the given labels are counted. **'nand'** : Throats with *some but not all* of the given labels are counted. **'xnor'** : Throats with *more than one* of the given labels are counted. Returns ------- Nt : int Number of throats with the specified labels See Also -------- num_pores count Notes ----- Technically, *'nand'* and *'xnor'* should also count throats with *none* of the labels, however, to make the count more useful these are not included. """ # Count number of pores of specified type Ts = self._get_indices(labels=labels, mode=mode, element='throat') Nt = sp.shape(Ts)[0] return Nt
python
{ "resource": "" }
q20736
Base._count
train
def _count(self, element=None): r""" Returns a dictionary containing the number of pores and throats in the network, stored under the keys 'pore' or 'throat' Parameters ---------- element : string, optional Can be either 'pore' , 'pores', 'throat' or 'throats', which specifies which count to return. Returns ------- A dictionary containing the number of pores and throats under the 'pore' and 'throat' key respectively. See Also -------- num_pores num_throats Notes ----- The ability to send plurals is useful for some types of 'programmatic' access. For instance, the standard argument for locations is pores or throats. If these are bundled up in a **kwargs dict then you can just use the dict key in count() without removing the 's'. Examples -------- >>> import openpnm as op >>> pn = op.network.Cubic(shape=[5, 5, 5]) >>> pn._count('pore') 125 >>> pn._count('throat') 300 """ element = self._parse_element(element=element, single=True) temp = sp.size(super(Base, self).__getitem__(element+'.all')) return temp
python
{ "resource": "" }
q20737
Base.show_hist
train
def show_hist(self, props=[], bins=20, **kwargs): r""" Show a quick plot of key property distributions. Parameters ---------- props : string or list of strings The pore and/or throat properties to be plotted as histograms bins : int or array_like The number of bins to use when generating the histogram. If an array is given they are used as the bin spacing instead. Notes ----- Other keyword arguments are passed to the ``matplotlib.pyplot.hist`` function. """ if type(props) is str: props = [props] N = len(props) if N == 1: r = 1 c = 1 elif N < 4: r = 1 c = N else: r = int(sp.ceil(N**0.5)) c = int(sp.floor(N**0.5)) for i in range(len(props)): plt.subplot(r, c, i+1) plt.hist(self[props[i]], bins=bins, **kwargs)
python
{ "resource": "" }
q20738
Base.check_data_health
train
def check_data_health(self, props=[], element=None): r""" Check the health of pore and throat data arrays. Parameters ---------- element : string, optional Can be either 'pore' or 'throat', which will limit the checks to only those data arrays. props : list of pore (or throat) properties, optional If given, will limit the health checks to only the specfied properties. Also useful for checking existance. Returns ------- Returns a HealthDict object which a basic dictionary with an added ``health`` attribute that is True is all entries in the dict are deemed healthy (empty lists), or False otherwise. Examples -------- >>> import openpnm >>> pn = openpnm.network.Cubic(shape=[5, 5, 5]) >>> h = pn.check_data_health() >>> h.health True """ health = HealthDict() if props == []: props = self.props(element) else: if type(props) == str: props = [props] for item in props: health[item] = [] if self[item].dtype == 'O': health[item] = 'No checks on object' elif sp.sum(sp.isnan(self[item])) > 0: health[item] = 'Has NaNs' elif sp.shape(self[item])[0] != self._count(item.split('.')[0]): health[item] = 'Wrong Length' return health
python
{ "resource": "" }
q20739
Base._parse_indices
train
def _parse_indices(self, indices): r""" This private method accepts a list of pores or throats and returns a properly structured Numpy array of indices. Parameters ---------- indices : multiple options This argument can accept numerous different data types including boolean masks, integers and arrays. Returns ------- A Numpy array of indices. Notes ----- This method should only be called by the method that is actually using the locations, to avoid calling it multiple times. """ if indices is None: indices = sp.array([], ndmin=1, dtype=int) locs = sp.array(indices, ndmin=1) # If boolean array, convert to indices if locs.dtype == bool: if sp.size(locs) == self.Np: locs = self.Ps[locs] elif sp.size(locs) == self.Nt: locs = self.Ts[locs] else: raise Exception('Mask of locations must be either ' + 'Np nor Nt long') locs = locs.astype(dtype=int) return locs
python
{ "resource": "" }
q20740
Base._parse_element
train
def _parse_element(self, element, single=False): r""" This private method is used to parse the keyword \'element\' in many of the above methods. Parameters ---------- element : string or list of strings The element argument to check. If is None is recieved, then a list containing both \'pore\' and \'throat\' is returned. single : boolean (default is False) When set to True only a single element is allowed and it will also return a string containing the element. Returns ------- When ``single`` is False (default) a list contain the element(s) is returned. When ``single`` is True a bare string containing the element is returned. """ if element is None: element = ['pore', 'throat'] # Convert element to a list for subsequent processing if type(element) is str: element = [element] # Convert 'pore.prop' and 'throat.prop' into just 'pore' and 'throat' element = [item.split('.')[0] for item in element] # Make sure all are lowercase element = [item.lower() for item in element] # Deal with an plurals element = [item.rsplit('s', maxsplit=1)[0] for item in element] for item in element: if item not in ['pore', 'throat']: raise Exception('Invalid element received: '+item) # Remove duplicates if any [element.remove(L) for L in element if element.count(L) > 1] if single: if len(element) > 1: raise Exception('Both elements recieved when single element ' + 'allowed') else: element = element[0] return element
python
{ "resource": "" }
q20741
Base._parse_mode
train
def _parse_mode(self, mode, allowed=None, single=False): r""" This private method is for checking the \'mode\' used in the calling method. Parameters ---------- mode : string or list of strings The mode(s) to be parsed allowed : list of strings A list containing the allowed modes. This list is defined by the calling method. If any of the received modes are not in the allowed list an exception is raised. single : boolean (default is False) Indicates if only a single mode is allowed. If this argument is True than a string is returned rather than a list of strings, which makes it easier to work with in the caller method. Returns ------- A list containing the received modes as strings, checked to ensure they are all within the allowed set (if provoided). Also, if the ``single`` argument was True, then a string is returned. """ if type(mode) is str: mode = [mode] for item in mode: if (allowed is not None) and (item not in allowed): raise Exception('\'mode\' must be one of the following: ' + allowed.__str__()) # Remove duplicates, if any [mode.remove(L) for L in mode if mode.count(L) > 1] if single: if len(mode) > 1: raise Exception('Multiple modes received when only one mode ' + 'allowed') else: mode = mode[0] return mode
python
{ "resource": "" }
q20742
sphere
train
def sphere(target, pore_diameter='pore.diameter', throat_area='throat.area'): r""" Calculates internal surface area of pore bodies assuming they are spherical then subtracts the area of the neighboring throats in a crude way, by simply considering the throat cross-sectional area, thus not accounting for the actual curvature of the intersection. 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. pore_diameter : string The dictionary key to the pore diameter array. throat_area : string The dictioanry key to the throat area array. Throat areas are needed since their insection with the pore are removed from the computation. """ network = target.project.network R = target[pore_diameter]/2 Asurf = 4*_np.pi*R**2 Tn = network.find_neighbor_throats(pores=target.Ps, flatten=False) Tsurf = _np.array([_np.sum(network[throat_area][Ts]) for Ts in Tn]) value = Asurf - Tsurf return value
python
{ "resource": "" }
q20743
cube
train
def cube(target, pore_diameter='pore.diameter', throat_area='throat.area'): r""" Calculates internal surface area of pore bodies assuming they are cubes then subtracts the area of the neighboring throats. 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. pore_diameter : string The dictionary key to the pore diameter array. throat_area : string The dictioanry key to the throat area array. Throat areas are needed since their insection with the pore are removed from the computation. """ network = target.project.network D = target[pore_diameter] Tn = network.find_neighbor_throats(pores=target.Ps, flatten=False) Tsurf = _np.array([_np.sum(network[throat_area][Ts]) for Ts in Tn]) value = 6*D**2 - Tsurf return value
python
{ "resource": "" }
q20744
MixedInvasionPercolation.set_outlets
train
def set_outlets(self, pores=[], overwrite=False): r""" Set the locations through which defender exits the network. This is only necessary if 'trapping' was set to True when ``setup`` was called. Parameters ---------- pores : array_like Locations where the defender can exit the network. Any defender that does not have access to these sites will be trapped. overwrite : boolean If ``True`` then all existing outlet locations will be removed and then the supplied locations will be added. If ``False`` (default), then supplied locations are added to any already existing outlet locations. """ if self.settings['trapping'] is False: logger.warning('Setting outlets is meaningless unless trapping ' + 'was set to True during setup') Ps = self._parse_indices(pores) if np.sum(self['pore.inlets'][Ps]) > 0: raise Exception('Some outlets are already defined as inlets') if overwrite: self['pore.outlets'] = False self['pore.outlets'][Ps] = True
python
{ "resource": "" }
q20745
MixedInvasionPercolation._add_ts2q
train
def _add_ts2q(self, pore, queue): """ Helper method to add throats to the cluster queue """ net = self.project.network elem_type = 'throat' # Find throats connected to newly invaded pore Ts = net.find_neighbor_throats(pores=pore) # Remove already invaded throats from Ts Ts = Ts[self['throat.invasion_sequence'][Ts] <= 0] tcp = self['throat.entry_pressure'] if len(Ts) > 0: self._interface_Ts[Ts] = True for T in Ts: data = [] # Pc if self._bidirectional: # Get index of pore being invaded next and apply correct # entry pressure pmap = net['throat.conns'][T] != pore pind = list(pmap).index(True) data.append(tcp[T][pind]) else: data.append(tcp[T]) # Element Index data.append(T) # Element Type (Pore of Throat) data.append(elem_type) hq.heappush(queue, data)
python
{ "resource": "" }
q20746
MixedInvasionPercolation._add_ps2q
train
def _add_ps2q(self, throat, queue): """ Helper method to add pores to the cluster queue """ net = self.project.network elem_type = 'pore' # Find pores connected to newly invaded throat Ps = net['throat.conns'][throat] # Remove already invaded pores from Ps Ps = Ps[self['pore.invasion_sequence'][Ps] <= 0] if len(Ps) > 0: self._interface_Ps[Ps] = True for P in Ps: data = [] # Pc data.append(self["pore.entry_pressure"][P]) # Element Index data.append(P) # Element Type (Pore of Throat) data.append(elem_type) hq.heappush(queue, data)
python
{ "resource": "" }
q20747
MixedInvasionPercolation._merge_cluster
train
def _merge_cluster(self, c2keep, c2empty): r""" Little helper function to merger clusters but only add the uninvaded elements """ while len(self.queue[c2empty]) > 0: temp = [_pc, _id, _type] = hq.heappop(self.queue[c2empty]) if self[_type+'.invasion_sequence'][_id] == -1: hq.heappush(self.queue[c2keep], temp) self.invasion_running[c2empty] = False
python
{ "resource": "" }
q20748
MixedInvasionPercolation.results
train
def results(self, Pc): r""" Places the results of the IP simulation into the Phase object. Parameters ---------- Pc : float Capillary Pressure at which phase configuration was reached """ phase = self.project.find_phase(self) net = self.project.network inv_p = self['pore.invasion_pressure'].copy() inv_t = self['throat.invasion_pressure'].copy() # Handle trapped pores and throats by moving their pressure up to be # ignored if np.sum(self['pore.invasion_sequence'] == -1) > 0: inv_p[self['pore.invasion_sequence'] == -1] = Pc + 1 if np.sum(self['throat.invasion_sequence'] == -1) > 0: inv_t[self['throat.invasion_sequence'] == -1] = Pc + 1 p_inv = inv_p <= Pc t_inv = inv_t <= Pc if self.settings['late_pore_filling']: # Set pressure on phase to current capillary pressure phase['pore.pressure'] = Pc # Regenerate corresponding physics model for phys in self.project.find_physics(phase=phase): phys.regenerate_models(self.settings['late_pore_filling']) # Fetch partial filling fraction from phase object (0->1) frac = phase[self.settings['late_pore_filling']] p_vol = net['pore.volume']*frac else: p_vol = net['pore.volume'] if self.settings['late_throat_filling']: # Set pressure on phase to current capillary pressure phase['throat.pressure'] = Pc # Regenerate corresponding physics model for phys in self.project.find_physics(phase=phase): phys.regenerate_models(self.settings['late_throat_filling']) # Fetch partial filling fraction from phase object (0->1) frac = phase[self.settings['late_throat_filling']] t_vol = net['throat.volume']*frac else: t_vol = net['throat.volume'] return {'pore.occupancy': p_inv*p_vol, 'throat.occupancy': t_inv*t_vol}
python
{ "resource": "" }
q20749
MixedInvasionPercolation.apply_flow
train
def apply_flow(self, flowrate): r""" Convert the invaded sequence into an invaded time for a given flow rate considering the volume of invaded pores and throats. Parameters ---------- flowrate : float The flow rate of the injected fluid Returns ------- Creates a throat array called 'invasion_time' in the Algorithm dictionary """ net = self.project.network P12 = net['throat.conns'] aa = self['throat.invasion_sequence'] bb = sp.argsort(self['throat.invasion_sequence']) P12_inv = self['pore.invasion_sequence'][P12] # Find if the connected pores were invaded with or before each throat P1_inv = P12_inv[:, 0] <= aa P2_inv = P12_inv[:, 1] <= aa cc = sp.column_stack((P1_inv, P2_inv)) # List of Pores invaded with each throat dd = sp.sum(cc, axis=1, dtype=bool) # Find volume of these pores P12_vol = sp.sum(net['pore.volume'][P12]*cc, axis=1)*dd # Add invaded throat volume to pore volume (if invaded) T_vol = P12_vol + net['throat.volume'] # Cumulative sum on the sorted throats gives cumulated inject volume ee = sp.cumsum(T_vol[bb] / flowrate) t = sp.zeros((self.Nt,)) t[bb] = ee # Convert back to original order phase = self.project.find_phase(self) phase['throat.invasion_time'] = t
python
{ "resource": "" }
q20750
MixedInvasionPercolation._apply_snap_off
train
def _apply_snap_off(self, queue=None): r""" Add all the throats to the queue with snap off pressure This is probably wrong!!!! Each one needs to start a new cluster. """ net = self.project.network phase = self.project.find_phase(self) snap_off = self.settings['snap_off'] if queue is None: queue = self.queue[0] try: Pc_snap_off = phase[snap_off] logger.info("Adding snap off pressures to queue") for T in net.throats(): if not np.isnan(Pc_snap_off[T]): hq.heappush(queue, [Pc_snap_off[T], T, 'throat']) except KeyError: logger.warning("Phase " + phase.name + " doesn't have " + "property " + snap_off)
python
{ "resource": "" }
q20751
MixedInvasionPercolation.set_residual
train
def set_residual(self, pores=[], overwrite=False): r""" Method to start invasion in a network w. residual saturation. Called after inlets are set. Parameters ---------- pores : array_like The pores 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 the supplied locations will be added. If ``False``, then supplied locations are added to any already existing locations. Notes ----- Currently works for pores only and treats inner throats, i.e. those that connect two pores in the cluster as invaded and outer ones as uninvaded. Uninvaded throats are added to a new residual cluster queue but do not start invading independently if not connected to an inlet. Step 1. Identify clusters in the phase occupancy. Step 2. Look for clusters that are connected or contain an inlet Step 3. For those that are merge into inlet cluster. May be connected to more than one - run should sort this out Step 4. For those that are isolated set the queue to not invading. Step 5. (in run) When isolated cluster is met my invading cluster it merges in and starts invading """ Ps = self._parse_indices(pores) if overwrite: self['pore.residual'] = False self['pore.residual'][Ps] = True residual = self['pore.residual'] net = self.project.network conns = net['throat.conns'] rclusters = site_percolation(conns, residual).sites rcluster_ids = np.unique(rclusters[rclusters > -1]) initial_num = len(self.queue)-1 for rcluster_id in rcluster_ids: rPs = rclusters == rcluster_id existing = np.unique(self['pore.cluster'][rPs]) existing = existing[existing > -1] if len(existing) > 0: # There was at least one inlet cluster connected to this # residual cluster, pick the first one. cluster_num = existing[0] else: # Make a new cluster queue cluster_num = len(self.queue) self.queue.append([]) queue = self.queue[cluster_num] # Set the residual pores and inner throats as part of cluster self['pore.cluster'][rPs] = cluster_num Ts = net.find_neighbor_throats(pores=rPs, flatten=True, mode='xnor') self['throat.cluster'][Ts] = cluster_num self['pore.invasion_sequence'][rPs] = 0 self['throat.invasion_sequence'][Ts] = 0 self['pore.invasion_pressure'][rPs] = -np.inf self['throat.invasion_pressure'][Ts] = -np.inf # Add all the outer throats to the queue Ts = net.find_neighbor_throats(pores=rPs, flatten=True, mode='exclusive_or') for T in Ts: data = [] # Pc data.append(self['throat.entry_pressure'][T]) # Element Index data.append(T) # Element Type (Pore of Throat) data.append('throat') hq.heappush(queue, data) self.invasion_running = [True]*len(self.queue) # we have added new clusters that are currently isolated and we # need to stop them invading until they merge into an invading # cluster for c_num in range(len(self.queue)): if c_num > initial_num: self.invasion_running[c_num] = False
python
{ "resource": "" }
q20752
MixedInvasionPercolation._invade_isolated_Ts
train
def _invade_isolated_Ts(self): r""" Throats that are uninvaded connected to pores that are both invaded should be invaded too. """ net = self.project.network Ts = net['throat.conns'].copy() invaded_Ps = self['pore.invasion_sequence'] > -1 uninvaded_Ts = self['throat.invasion_sequence'] == -1 isolated_Ts = np.logical_and(invaded_Ps[Ts[:, 0]], invaded_Ps[Ts[:, 1]]) isolated_Ts = np.logical_and(isolated_Ts, uninvaded_Ts) inv_Pc = self['pore.invasion_pressure'] inv_seq = self['pore.invasion_sequence'] if np.any(isolated_Ts): max_array = Ts[:, 0] second_higher = inv_seq[Ts][:, 1] > inv_seq[Ts][:, 0] max_array[second_higher] = Ts[:, 1][second_higher] mPc = inv_Pc[max_array] mSeq = inv_seq[max_array] mClu = self['pore.cluster'][max_array] self['throat.invasion_pressure'][isolated_Ts] = mPc[isolated_Ts] self['throat.invasion_sequence'][isolated_Ts] = mSeq[isolated_Ts] self['throat.cluster'][isolated_Ts] = mClu[isolated_Ts]
python
{ "resource": "" }
q20753
MixedInvasionPercolation.trilaterate_v
train
def trilaterate_v(self, P1, P2, P3, r1, r2, r3): r''' Find whether 3 spheres intersect ''' temp1 = P2-P1 e_x = temp1/np.linalg.norm(temp1, axis=1)[:, np.newaxis] temp2 = P3-P1 i = self._my_dot(e_x, temp2)[:, np.newaxis] temp3 = temp2 - i*e_x e_y = temp3/np.linalg.norm(temp3, axis=1)[:, np.newaxis] d = np.linalg.norm(P2-P1, axis=1)[:, np.newaxis] j = self._my_dot(e_y, temp2)[:, np.newaxis] x = (r1*r1 - r2*r2 + d*d) / (2*d) y = (r1*r1 - r3*r3 - 2*i*x + (i*i) + (j*j)) / (2*j) temp4 = r1*r1 - x*x - y*y return temp4 >= 0
python
{ "resource": "" }
q20754
MixedInvasionPercolation._get_throat_pairs
train
def _get_throat_pairs(self): r''' Generate an array of pores with all connected throats and pairs of throats that connect to the same pore ''' network = self.project.network # Collect all throat pairs sharing a pore as list of lists neighbor_Ts = network.find_neighbor_throats(pores=network.pores(), flatten=False) # Pores associated to throat Ps = [] # Throats connected to each pore Ts = [] # Pairs of throats sharing a pore T1 = [] T2 = [] start = 0 # Build lookup pair index arrays for each coordination number up to the # Maximum coordination max_c max_c = sp.amax(network.num_neighbors(pores=network.Ps, flatten=False)) pair_T1 = [] pair_T2 = [] logger.info('Building throat pair matrices') for num_t in range(max_c+1): temp1 = [] temp2 = [] for t1 in range(num_t)[:-1]: for t2 in range(num_t)[t1+1:]: temp1.append(t1) temp2.append(t2) pair_T1.append(np.asarray(temp1)) pair_T2.append(np.asarray(temp2)) for p, nTs in enumerate(neighbor_Ts): num_t = len(nTs) for i in range(num_t): Ps.append(p) Ts.append(nTs[i]) # Pair indices into Ts tempt1 = pair_T1[num_t] + start tempt2 = pair_T2[num_t] + start for i in range(len(tempt1)): T1.append(tempt1[i]) T2.append(tempt2[i]) start += num_t # Nt * 2 long Ps = np.asarray(Ps) Ts = np.asarray(Ts) # indices into the above arrays based on throat pairs T1 = np.asarray(T1) T2 = np.asarray(T2) return Ps, Ts, T1, T2
python
{ "resource": "" }
q20755
MixedInvasionPercolation._apply_cen_to_throats
train
def _apply_cen_to_throats(self, p_cen, t_cen, t_norm, men_cen): r''' Take the pore center and throat center and work out which way the throat normal is pointing relative to the vector between centers. Offset the meniscus center along the throat vector in the correct direction ''' v = p_cen - t_cen sign = np.sign(np.sum(v*t_norm, axis=1)) c3 = np.vstack((men_cen*sign, men_cen*sign, men_cen*sign)).T coords = t_cen + c3*t_norm return coords
python
{ "resource": "" }
q20756
MixedInvasionPercolation._check_coop
train
def _check_coop(self, pore, queue): r""" Method run in loop after every pore invasion. All connecting throats are now given access to the invading phase. Two throats with access to the invading phase can cooperatively fill any pores that they are both connected to, common pores. The invasion of theses throats connected to the common pore is handled elsewhere. """ net = self.project.network t_inv = 'throat.invasion_sequence' p_inv = 'pore.invasion_sequence' for throat in net.find_neighbor_throats(pores=pore): # A pore has just been invaded, all it's throats now have # An interface residing inside them if self[t_inv][throat] == -1: # If the throat is not the invading throat that gave access # to this pore, get the pores that this throat connects with a = set(net['throat.conns'][throat]) # Get a list of pre-calculated coop filling pressures for all # Throats this throat can coop fill with ts_Pc = self.tt_Pc.data[throat] # Network indices of throats that can act as filling pairs ts = self.tt_Pc.rows[throat] # If there are any potential coop filling throats if np.any(~np.isnan(ts_Pc)): ts_Pc = np.asarray(ts_Pc) ts = np.asarray(ts) ts = ts[~np.isnan(ts_Pc)] ts_Pc = ts_Pc[~np.isnan(ts_Pc)] # For each throat find the common pore and the uncommon # pores for i, t in enumerate(ts): # Find common pore (cP) and uncommon pores (uPs) b = set(net['throat.conns'][t]) cP = list(a.intersection(b)) uPs = list(a.symmetric_difference(b)) # If the common pore is not invaded but the others are # The potential coop filling event can now happen # Add the coop pressure to the queue if ((np.all(self[p_inv][uPs] > -1)) and (self[p_inv][cP] == -1)): # Coop pore filling fills the common pore # The throats that gave access are not invaded now # However, isolated throats between invaded pores # Are taken care of elsewhere... hq.heappush(queue, [ts_Pc[i], list(cP), 'pore'])
python
{ "resource": "" }
q20757
cylinder
train
def cylinder(target, throat_diameter='throat.diameter', throat_length='throat.length'): r""" Calculate surface area for a cylindrical 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. throat_diameter : string Dictionary key to the throat diameter array. Default is 'throat.diameter'. throat_length : string Dictionary key to the throat length array. Default is 'throat.length'. """ D = target[throat_diameter] L = target[throat_length] value = _sp.pi*D*L return value
python
{ "resource": "" }
q20758
cuboid
train
def cuboid(target, throat_diameter='throat.diameter', throat_length='throat.length'): r""" Calculate surface area for a cuboid 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. throat_diameter : string Dictionary key to the throat diameter array. Default is 'throat.diameter'. throat_length : string Dictionary key to the throat length array. Default is 'throat.length'. """ D = target[throat_diameter] L = target[throat_length] value = 4*D*L return value
python
{ "resource": "" }
q20759
extrusion
train
def extrusion(target, throat_perimeter='throat.perimeter', throat_length='throat.length'): r""" Calculate surface area for an arbitrary shaped throat give the perimeter and length. 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_perimeter : string Dictionary key to the throat perimeter array. Default is 'throat.perimeter'. throat_length : string Dictionary key to the throat length array. Default is 'throat.length'. """ P = target[throat_perimeter] L = target[throat_length] value = P*L return value
python
{ "resource": "" }
q20760
cubic_pores
train
def cubic_pores(target, pore_diameter='pore.diameter'): r""" Calculate coordinates of throat endpoints, assuming throats don't overlap with their adjacent pores. This model could be applied to conduits such as cuboids or cylinders in series. 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. pore_diameter : string Dictionary key of the pore diameter values Returns ------- EP : dictionary Coordinates of throat endpoints stored in Dict form. Can be accessed via the dict keys 'head' and 'tail'. Notes ----- This model is only accurate for cubic networks without diagonal connections. """ network = target.project.network throats = network.map_throats(throats=target.Ts, origin=target) xyz = network['pore.coords'] cn = network['throat.conns'][throats] L = _ctc(target=target, pore_diameter=pore_diameter) D1 = network[pore_diameter][cn[:, 0]] D2 = network[pore_diameter][cn[:, 1]] unit_vec = (xyz[cn[:, 1]] - xyz[cn[:, 0]]) / L[:, None] EP1 = xyz[cn[:, 0]] + 0.5 * D1[:, _sp.newaxis] * unit_vec EP2 = xyz[cn[:, 1]] - 0.5 * D2[:, _sp.newaxis] * unit_vec # Handle overlapping pores overlap = L - 0.5 * (D1+D2) < 0 mask = (D1 >= D2) & overlap EP2[mask] = EP1[mask] mask = (D1 < D2) & overlap EP1[mask] = EP2[mask] return {'head': EP1, 'tail': EP2}
python
{ "resource": "" }
q20761
spherical_pores
train
def spherical_pores(target, pore_diameter='pore.diameter', throat_diameter='throat.diameter', throat_centroid='throat.centroid'): r""" Calculate the coordinates of throat endpoints, assuming spherical pores. This model accounts for the overlapping lens between pores and 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. pore_diameter : string Dictionary key of the pore diameter values. throat_diameter : string Dictionary key of the throat diameter values. throat_centroid : string, optional Dictionary key of the throat centroid values. See the notes. Returns ------- EP : dictionary Coordinates of throat endpoints stored in Dict form. Can be accessed via the dict keys 'head' and 'tail'. Notes ----- (1) This model should not be applied to true 2D networks. Use `circular_pores` model instead. (2) By default, this model assumes that throat centroid and pore coordinates are colinear. If that's not the case, such as in extracted networks, `throat_centroid` could be passed as an optional argument, and the model takes care of the rest. """ network = target.project.network throats = network.map_throats(throats=target.Ts, origin=target) xyz = network['pore.coords'] cn = network['throat.conns'][throats] L = _ctc(target=target, pore_diameter=pore_diameter) Dt = network[throat_diameter][throats] D1 = network[pore_diameter][cn[:, 0]] D2 = network[pore_diameter][cn[:, 1]] L1 = _sp.zeros_like(L) L2 = _sp.zeros_like(L) # Handle the case where Dt > Dp mask = Dt > D1 L1[mask] = 0.5 * D1[mask] L1[~mask] = _sp.sqrt(D1[~mask]**2 - Dt[~mask]**2) / 2 mask = Dt > D2 L2[mask] = 0.5 * D2[mask] L2[~mask] = _sp.sqrt(D2[~mask]**2 - Dt[~mask]**2) / 2 # Handle non-colinear pores and throat centroids try: TC = network[throat_centroid][throats] LP1T = _sp.linalg.norm(TC - xyz[cn[:, 0]], axis=1) LP2T = _sp.linalg.norm(TC - xyz[cn[:, 1]], axis=1) unit_vec_P1T = (TC - xyz[cn[:, 0]]) / LP1T[:, None] unit_vec_P2T = (TC - xyz[cn[:, 1]]) / LP2T[:, None] except KeyError: unit_vec_P1T = (xyz[cn[:, 1]] - xyz[cn[:, 0]]) / L[:, None] unit_vec_P2T = -1 * unit_vec_P1T # Find throat endpoints EP1 = xyz[cn[:, 0]] + L1[:, None] * unit_vec_P1T EP2 = xyz[cn[:, 1]] + L2[:, None] * unit_vec_P2T # Handle throats w/ overlapping pores L1 = (4*L**2 + D1**2 - D2**2) / (8*L) # L2 = (4*L**2 + D2**2 - D1**2) / (8*L) h = (2*_sp.sqrt(D1**2/4 - L1**2)).real overlap = L - 0.5 * (D1+D2) < 0 mask = overlap & (Dt < h) EP1[mask] = EP2[mask] = (xyz[cn[:, 0]] + L1[:, None] * unit_vec_P1T)[mask] return {'head': EP1, 'tail': EP2}
python
{ "resource": "" }
q20762
circular_pores
train
def circular_pores(target, pore_diameter='pore.diameter', throat_diameter='throat.diameter', throat_centroid='throat.centroid'): r""" Calculate the coordinates of throat endpoints, assuming circular pores. This model accounts for the overlapping lens between pores and 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. pore_diameter : string Dictionary key of the pore diameter values. throat_diameter : string Dictionary key of the throat diameter values. throat_centroid : string, optional Dictionary key of the throat centroid values. See the notes. Returns ------- EP : dictionary Coordinates of throat endpoints stored in Dict form. Can be accessed via the dict keys 'head' and 'tail'. Notes ----- (1) This model should only be applied to ture 2D networks. (2) By default, this model assumes that throat centroid and pore coordinates are colinear. If that's not the case, such as in extracted networks, `throat_centroid` could be passed as an optional argument, and the model takes care of the rest. """ return spherical_pores(target=target, pore_diameter=pore_diameter, throat_diameter=throat_diameter)
python
{ "resource": "" }
q20763
straight_throat
train
def straight_throat(target, throat_centroid='throat.centroid', throat_vector='throat.vector', throat_length='throat.length'): r""" Calculate the coordinates of throat endpoints given a central coordinate, unit vector along the throat direction and a length. 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_centroid : string Dictionary key of the throat center coordinates. throat_vector : string Dictionary key of the throat vector pointing along the length of the throats. throat_length : string Dictionary key of the throat length. Returns ------- EP : dictionary Coordinates of throat endpoints stored in Dict form. Can be accessed via the dict keys 'head' and 'tail'. """ network = target.project.network throats = network.map_throats(throats=target.Ts, origin=target) center = network[throat_centroid][throats] vector = network[throat_vector][throats] length = network[throat_length][throats] EP1 = center - 0.5 * length[:, _sp.newaxis] * vector EP2 = center + 0.5 * length[:, _sp.newaxis] * vector return {'head': EP1, 'tail': EP2}
python
{ "resource": "" }
q20764
Cubic.add_boundary_pores
train
def add_boundary_pores(self, labels=['top', 'bottom', 'front', 'back', 'left', 'right'], spacing=None): r""" Add pores to the faces of the network for use as boundary pores. Pores are offset from the faces by 1/2 a lattice spacing such that they lie directly on the boundaries. Parameters ---------- labels : string or list of strings The labels indicating the pores defining each face where boundary pores are to be added (e.g. 'left' or ['left', 'right']) spacing : scalar or array_like The spacing of the network (e.g. [1, 1, 1]). This should be given since it can be quite difficult to infer from the network, for instance if boundary pores have already added to other faces. """ if type(labels) == str: labels = [labels] x, y, z = self['pore.coords'].T if spacing is None: spacing = self._spacing else: spacing = sp.array(spacing) if spacing.size == 1: spacing = sp.ones(3)*spacing Lcx, Lcy, Lcz = spacing offset = {} offset['front'] = offset['left'] = offset['bottom'] = [0, 0, 0] offset['back'] = [Lcx*self._shape[0], 0, 0] offset['right'] = [0, Lcy*self._shape[1], 0] offset['top'] = [0, 0, Lcz*self._shape[2]] scale = {} scale['front'] = scale['back'] = [0, 1, 1] scale['left'] = scale['right'] = [1, 0, 1] scale['bottom'] = scale['top'] = [1, 1, 0] for label in labels: Ps = self.pores(label) topotools.clone_pores(network=self, pores=Ps, labels=label+'_boundary') # Translate cloned pores ind = self.pores(label+'_boundary') coords = self['pore.coords'][ind] coords = coords*scale[label] + offset[label] self['pore.coords'][ind] = coords
python
{ "resource": "" }
q20765
Cubic.to_array
train
def to_array(self, values): r""" Converts the values to a rectangular array with the same shape as the network Parameters ---------- values : array_like An Np-long array of values to convert to Notes ----- This method can break on networks that have had boundaries added. It will usually work IF the given values came only from 'internal' pores. """ if sp.shape(values)[0] > self.num_pores('internal'): raise Exception('The array shape does not match the network') Ps = sp.array(self['pore.index'][self.pores('internal')], dtype=int) arr = sp.ones(self._shape)*sp.nan ind = sp.unravel_index(Ps, self._shape) arr[ind[0], ind[1], ind[2]] = values return arr
python
{ "resource": "" }
q20766
Cubic.from_array
train
def from_array(self, array, propname): r""" Apply data to the network based on a rectangular array filled with values. Each array location corresponds to a pore in the network. Parameters ---------- array : array_like The rectangular array containing the values to be added to the network. This array must be the same shape as the original network. propname : string The name of the pore property being added. """ array = sp.atleast_3d(array) if sp.shape(array) != self._shape: raise Exception('The array shape does not match the network') temp = array.flatten() Ps = sp.array(self['pore.index'][self.pores('internal')], dtype=int) propname = 'pore.' + propname.split('.')[-1] self[propname] = sp.nan self[propname][self.pores('internal')] = temp[Ps]
python
{ "resource": "" }
q20767
GenericNetwork.get_adjacency_matrix
train
def get_adjacency_matrix(self, fmt='coo'): r""" Returns an adjacency matrix in the specified sparse format, with 1's indicating the non-zero values. Parameters ---------- fmt : string, optional The sparse storage format to return. Options are: **'coo'** : (default) This is the native format of OpenPNM data **'lil'** : Enables row-wise slice of the matrix **'csr'** : Favored by most linear algebra routines **'dok'** : Enables subscript access of locations Notes ----- This method will only create the requested matrix in the specified format if one is not already saved on the object. If not present, this method will create and return the matrix, as well as store it for future use. To obtain a matrix with weights other than ones at each non-zero location use ``create_adjacency_matrix``. """ # Retrieve existing matrix if available if fmt in self._am.keys(): am = self._am[fmt] elif self._am.keys(): am = self._am[list(self._am.keys())[0]] tofmt = getattr(am, 'to'+fmt) am = tofmt() self._am[fmt] = am else: am = self.create_adjacency_matrix(weights=self.Ts, fmt=fmt) self._am[fmt] = am return am
python
{ "resource": "" }
q20768
GenericNetwork.get_incidence_matrix
train
def get_incidence_matrix(self, fmt='coo'): r""" Returns an incidence matrix in the specified sparse format, with 1's indicating the non-zero values. Parameters ---------- fmt : string, optional The sparse storage format to return. Options are: **'coo'** : (default) This is the native format of OpenPNM data **'lil'** : Enables row-wise slice of the matrix **'csr'** : Favored by most linear algebra routines **'dok'** : Enables subscript access of locations Notes ----- This method will only create the requested matrix in the specified format if one is not already saved on the object. If not present, this method will create and return the matrix, as well as store it for future use. To obtain a matrix with weights other than ones at each non-zero location use ``create_incidence_matrix``. """ if fmt in self._im.keys(): im = self._im[fmt] elif self._im.keys(): im = self._am[list(self._im.keys())[0]] tofmt = getattr(im, 'to'+fmt) im = tofmt() self._im[fmt] = im else: im = self.create_incidence_matrix(weights=self.Ts, fmt=fmt) self._im[fmt] = im return im
python
{ "resource": "" }
q20769
GenericNetwork.create_adjacency_matrix
train
def create_adjacency_matrix(self, weights=None, fmt='coo', triu=False, drop_zeros=False): r""" Generates a weighted adjacency matrix in the desired sparse format Parameters ---------- weights : array_like, optional An array containing the throat values to enter into the matrix (in graph theory these are known as the 'weights'). If the array is Nt-long, it implies that the matrix is symmetric, so the upper and lower triangular regions are mirror images. If it is 2*Nt-long then it is assumed that the first Nt elements are for the upper triangle, and the last Nt element are for the lower triangular. If omitted, ones are used to create a standard adjacency matrix representing connectivity only. fmt : string, optional The sparse storage format to return. Options are: **'coo'** : (default) This is the native format of OpenPNM data **'lil'** : Enables row-wise slice of the matrix **'csr'** : Favored by most linear algebra routines **'dok'** : Enables subscript access of locations triu : boolean (default is ``False``) If ``True``, the returned sparse matrix only contains the upper- triangular elements. This argument is ignored if the ``weights`` array is 2*Nt-long. drop_zeros : boolean (default is ``False``) If ``True``, applies the ``eliminate_zeros`` method of the sparse array to remove all zero locations. Returns ------- An adjacency matrix in the specified Scipy sparse format. Notes ----- The adjacency matrix is used by OpenPNM for finding the pores connected to a give pore or set of pores. Specifically, an adjacency matrix has Np rows and Np columns. Each row represents a pore, containing non-zero values at the locations corresponding to the indices of the pores connected to that pore. The ``weights`` argument indicates what value to place at each location, with the default being 1's to simply indicate connections. Another useful option is throat indices, such that the data values on each row indicate which throats are connected to the pore. Examples -------- >>> import openpnm as op >>> pn = op.network.Cubic(shape=[5, 5, 5]) >>> weights = sp.rand(pn.num_throats(), ) < 0.5 >>> am = pn.create_adjacency_matrix(weights=weights, fmt='csr') """ # Check if provided data is valid if weights is None: weights = sp.ones((self.Nt,), dtype=int) elif sp.shape(weights)[0] not in [self.Nt, 2*self.Nt, (self.Nt, 2)]: raise Exception('Received weights are of incorrect length') # Append row & col to each other, and data to itself conn = self['throat.conns'] row = conn[:, 0] col = conn[:, 1] if weights.shape == (2*self.Nt,): row = sp.append(row, conn[:, 1]) col = sp.append(col, conn[:, 0]) elif weights.shape == (self.Nt, 2): row = sp.append(row, conn[:, 1]) col = sp.append(col, conn[:, 0]) weights = weights.flatten(order='F') elif not triu: row = sp.append(row, conn[:, 1]) col = sp.append(col, conn[:, 0]) weights = sp.append(weights, weights) # Generate sparse adjacency matrix in 'coo' format temp = sprs.coo_matrix((weights, (row, col)), (self.Np, self.Np)) if drop_zeros: temp.eliminate_zeros() # Convert to requested format if fmt == 'coo': pass # temp is already in coo format elif fmt == 'csr': temp = temp.tocsr() elif fmt == 'lil': temp = temp.tolil() elif fmt == 'dok': temp = temp.todok() return temp
python
{ "resource": "" }
q20770
GenericNetwork.create_incidence_matrix
train
def create_incidence_matrix(self, weights=None, fmt='coo', drop_zeros=False): r""" Creates a weighted incidence matrix in the desired sparse format Parameters ---------- weights : array_like, optional An array containing the throat values to enter into the matrix (In graph theory these are known as the 'weights'). If omitted, ones are used to create a standard incidence matrix representing connectivity only. fmt : string, optional The sparse storage format to return. Options are: **'coo'** : (default) This is the native format of OpenPNMs data **'lil'** : Enables row-wise slice of the matrix **'csr'** : Favored by most linear algebra routines **'dok'** : Enables subscript access of locations drop_zeros : boolean (default is ``False``) If ``True``, applies the ``eliminate_zeros`` method of the sparse array to remove all zero locations. Returns ------- An incidence matrix in the specified sparse format Notes ----- The incidence matrix is a cousin to the adjacency matrix, and used by OpenPNM for finding the throats connected to a give pore or set of pores. Specifically, an incidence matrix has Np rows and Nt columns, and each row represents a pore, containing non-zero values at the locations corresponding to the indices of the throats connected to that pore. The ``weights`` argument indicates what value to place at each location, with the default being 1's to simply indicate connections. Another useful option is throat indices, such that the data values on each row indicate which throats are connected to the pore, though this is redundant as it is identical to the locations of non-zeros. Examples -------- >>> import openpnm as op >>> pn = op.network.Cubic(shape=[5, 5, 5]) >>> weights = sp.rand(pn.num_throats(), ) < 0.5 >>> im = pn.create_incidence_matrix(weights=weights, fmt='csr') """ # Check if provided data is valid if weights is None: weights = sp.ones((self.Nt,), dtype=int) elif sp.shape(weights)[0] != self.Nt: raise Exception('Received dataset of incorrect length') conn = self['throat.conns'] row = conn[:, 0] row = sp.append(row, conn[:, 1]) col = sp.arange(self.Nt) col = sp.append(col, col) weights = sp.append(weights, weights) temp = sprs.coo.coo_matrix((weights, (row, col)), (self.Np, self.Nt)) if drop_zeros: temp.eliminate_zeros() # Convert to requested format if fmt == 'coo': pass # temp is already in coo format elif fmt == 'csr': temp = temp.tocsr() elif fmt == 'lil': temp = temp.tolil() elif fmt == 'dok': temp = temp.todok() return temp
python
{ "resource": "" }
q20771
GenericNetwork.find_connected_pores
train
def find_connected_pores(self, throats=[], flatten=False, mode='union'): r""" Return a list of pores connected to the given list of throats Parameters ---------- throats : array_like List of throats numbers flatten : boolean, optional If ``True`` (default) a 1D array of unique pore numbers is returned. If ``False`` each location in the the returned array contains a sub-arras of neighboring pores for each input throat, in the order they were sent. mode : string Specifies logic to filter the resulting list. Options are: **'or'** : (default) All neighbors of the input throats. 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 throat. This is useful for finding the sites that are not shared by any of the input throats. **'xnor'** : Neighbors that are shared by two or more input throats. 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. **'and'** : Only neighbors shared by all input throats. 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 ------- 1D array (if ``flatten`` is ``True``) or ndarray of arrays (if ``flatten`` is ``False``) Examples -------- >>> import openpnm as op >>> pn = op.network.Cubic(shape=[5, 5, 5]) >>> Ps = pn.find_connected_pores(throats=[0, 1]) >>> print(Ps) [[0 1] [1 2]] >>> Ps = pn.find_connected_pores(throats=[0, 1], flatten=True) >>> print(Ps) [0 1 2] """ Ts = self._parse_indices(throats) am = self.get_adjacency_matrix(fmt='coo') pores = topotools.find_connected_sites(bonds=Ts, am=am, flatten=flatten, logic=mode) return pores
python
{ "resource": "" }
q20772
GenericNetwork.find_connecting_throat
train
def find_connecting_throat(self, P1, P2): r""" Return the throat index connecting pairs of pores Parameters ---------- P1 , P2 : array_like The indices of the pores whose throats are sought. These can be vectors of indices, but must be the same length Returns ------- Returns a list the same length as P1 (and P2) with the each element containing the throat index that connects the corresponding pores, or `None`` if pores are not connected. Notes ----- The returned list can be converted to an ND-array, which will convert the ``None`` values to ``nan``. These can then be found using ``scipy.isnan``. Examples -------- >>> import openpnm as op >>> pn = op.network.Cubic(shape=[5, 5, 5]) >>> Ts = pn.find_connecting_throat([0, 1, 2], [2, 2, 2]) >>> print(Ts) [None, 1, None] """ am = self.create_adjacency_matrix(weights=self.Ts, fmt='coo') sites = sp.vstack((P1, P2)).T Ts = topotools.find_connecting_bonds(sites=sites, am=am) return Ts
python
{ "resource": "" }
q20773
GenericNetwork.num_neighbors
train
def num_neighbors(self, pores, mode='or', flatten=False): r""" Returns the number of neigbhoring pores for each given input pore Parameters ---------- pores : array_like Pores whose neighbors are to be counted flatten : boolean (optional) If ``False`` (default) the number of pores neighboring each input pore as an array the same length as ``pores``. If ``True`` the sum total number of is counted. mode : string The logic to apply to the returned count of pores. **'or'** : (default) All neighbors of the input pores. 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 pore. This is useful for counting the pores that are not shared by any of the input pores. This is known as 'exclusive_or' in set theory, and is an accepted input. **'xnor'** : Neighbors that are shared by two or more input pores. This is equivalent to counting all neighbors with 'or', minus those found with 'xor', and is useful for finding neighbors that the inputs have in common. **'and'** : Only neighbors shared by all input pores. 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 ------- If ``flatten`` is False, a 1D array with number of neighbors in each element, otherwise a scalar value of the number of neighbors. Notes ----- This method literally just counts the number of elements in the array returned by ``find_neighbor_pores`` using the same logic. Explore those methods if uncertain about the meaning of the ``mode`` argument here. See Also -------- find_neighbor_pores find_neighbor_throats Examples -------- >>> import openpnm as op >>> pn = op.network.Cubic(shape=[5, 5, 5]) >>> Np = pn.num_neighbors(pores=[0, 1], flatten=False) >>> print(Np) [3 4] >>> Np = pn.num_neighbors(pores=[0, 2], flatten=True) >>> print(Np) 6 >>> Np = pn.num_neighbors(pores=[0, 2], mode='and', flatten=True) >>> print(Np) 1 """ pores = self._parse_indices(pores) # Count number of neighbors num = self.find_neighbor_pores(pores, flatten=flatten, mode=mode, include_input=True) if flatten: num = sp.size(num) else: num = sp.array([sp.size(i) for i in num], dtype=int) return num
python
{ "resource": "" }
q20774
fuller
train
def fuller(target, MA, MB, vA, vB, temperature='pore.temperature', pressure='pore.pressure'): r""" Uses Fuller model to estimate diffusion coefficient for gases from first principles at conditions of interest 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. MA : float, array_like Molecular weight of component A [kg/mol] MB : float, array_like Molecular weight of component B [kg/mol] vA: float, array_like Sum of atomic diffusion volumes for component A vB: float, array_like Sum of atomic diffusion volumes for component B pressure : string The dictionary key containing the pressure values in Pascals (Pa) temperature : string The dictionary key containing the temperature values in Kelvin (K) """ T = target[temperature] P = target[pressure] MAB = 2*(1.0/MA+1.0/MB)**(-1) MAB = MAB*1e3 P = P*1e-5 value = 0.00143*T**1.75/(P*(MAB**0.5)*(vA**(1./3)+vB**(1./3))**2)*1e-4 return value
python
{ "resource": "" }
q20775
fuller_scaling
train
def fuller_scaling(target, DABo, To, Po, temperature='pore.temperature', pressure='pore.pressure'): r""" Uses Fuller model to adjust a diffusion coefficient for gases from reference conditions to conditions of interest 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. DABo : float, array_like Diffusion coefficient at reference conditions Po, To : float, array_like Pressure & temperature at reference conditions, respectively pressure : string The dictionary key containing the pressure values in Pascals (Pa) temperature : string The dictionary key containing the temperature values in Kelvin (K) """ Ti = target[temperature] Pi = target[pressure] value = DABo*(Ti/To)**1.75*(Po/Pi) return value
python
{ "resource": "" }
q20776
tyn_calus
train
def tyn_calus(target, VA, VB, sigma_A, sigma_B, temperature='pore.temperature', viscosity='pore.viscosity'): r""" Uses Tyn_Calus model to estimate diffusion coefficient in a dilute liquid solution of A in B from first principles at conditions of interest 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. VA : float, array_like Molar volume of component A at boiling temperature (m3/mol) VB : float, array_like Molar volume of component B at boiling temperature (m3/mol) sigmaA: float, array_like Surface tension of component A at boiling temperature (N/m) sigmaB: float, array_like Surface tension of component B at boiling temperature (N/m) pressure : string The dictionary key containing the pressure values in Pascals (Pa) temperature : string The dictionary key containing the temperature values in Kelvin (K) """ T = target[temperature] mu = target[viscosity] A = 8.93e-8*(VB*1e6)**0.267/(VA*1e6)**0.433*T B = (sigma_B/sigma_A)**0.15/(mu*1e3) value = A*B return value
python
{ "resource": "" }
q20777
tyn_calus_scaling
train
def tyn_calus_scaling(target, DABo, To, mu_o, viscosity='pore.viscosity', temperature='pore.temperature'): r""" Uses Tyn_Calus model to adjust a diffusion coeffciient for liquids from reference conditions to conditions of interest 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. DABo : float, array_like Diffusion coefficient at reference conditions mu_o, To : float, array_like Viscosity & temperature at reference conditions, respectively pressure : string The dictionary key containing the pressure values in Pascals (Pa) temperature : string The dictionary key containing the temperature values in Kelvin (K) """ Ti = target[temperature] mu_i = target[viscosity] value = DABo*(Ti/To)*(mu_o/mu_i) return value
python
{ "resource": "" }
q20778
brock_bird_scaling
train
def brock_bird_scaling(target, sigma_o, To, temperature='pore.temperature', critical_temperature='pore.critical_temperature'): r""" Uses Brock_Bird model to adjust surface tension from it's value at a given reference temperature to temperature of interest 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. To : float Reference temperature (K) sigma_o : float Surface tension at reference temperature (N/m) temperature : string The dictionary key containing the temperature values (K) critical_temperature : string The dictionary key containing the critical temperature values (K) """ Tc = target[critical_temperature] Ti = target[temperature] Tro = To/Tc Tri = Ti/Tc value = sigma_o*(1-Tri)**(11/9)/(1-Tro)**(11/9) return value
python
{ "resource": "" }
q20779
water
train
def water(target, temperature='pore.temperature', salinity='pore.salinity'): r""" Calculates thermal conductivity of pure water or seawater at atmospheric pressure using the correlation given by Jamieson and Tudhope. Values at temperature higher the normal boiling temperature are calculated at the saturation pressure. 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. temperature : string The dictionary key containing the temperature values. Temperature must be in Kelvin for this emperical equation to work salinity : string The dictionary key containing the salinity values. Salinity must be expressed in g of salt per kg of solution (ppt). Returns ------- The thermal conductivity of water/seawater in [W/m.K] Notes ----- T must be in K, and S in g of salt per kg of phase, or ppt (parts per thousand) VALIDITY: 273 < T < 453 K; 0 < S < 160 g/kg; ACCURACY: 3 % References ---------- D. T. Jamieson, and J. S. Tudhope, Desalination, 8, 393-401, 1970. """ T = target[temperature] if salinity in target.keys(): S = target[salinity] else: S = 0 T68 = 1.00024*T # convert from T_90 to T_68 SP = S/1.00472 # convert from S to S_P k_sw = 0.001*(10**(sp.log10(240+0.0002*SP) + 0.434*(2.3-(343.5+0.037*SP)/T68) * ((1-T68/(647.3+0.03*SP)))**(1/3))) value = k_sw return value
python
{ "resource": "" }
q20780
sato
train
def sato(target, mol_weight='pore.molecular_weight', boiling_temperature='pore.boiling_point', temperature='pore.temperature', critical_temperature='pore.critical_temperature'): r""" Uses Sato et al. model to estimate thermal conductivity for pure liquids from first principles at conditions of interest 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. boiling_temperature : string Dictionary key containing the toiling temperature of the component (K) mol_weight : string Dictionary key containing the molecular weight of the component (kg/mol) temperature : string The dictionary key containing the temperature values (K) critical_temperature : string The dictionary key containing the critical temperature values (K) """ T = target[temperature] Tc = target[critical_temperature] MW = target[mol_weight] Tbr = target[boiling_temperature]/Tc Tr = T/Tc value = (1.11/((MW*1e3)**0.5))*(3+20*(1-Tr)**(2/3))/(3+20*(1-Tbr)**(2/3)) return value
python
{ "resource": "" }
q20781
largest_sphere
train
def largest_sphere(target, fixed_diameter='pore.fixed_diameter', iters=5): r""" Finds the maximum diameter pore that can be placed in each location without overlapping any neighbors. This method iteratively expands pores by increasing their diameter to encompass half of the distance to the nearest neighbor. If the neighbor is not growing because it's already touching a different neighbor, then the given pore will never quite touch this neighbor. Increating the value of ``iters`` will get it closer, but it's case of [Zeno's paradox](https://en.wikipedia.org/wiki/Zeno%27s_paradoxes) with each step cutting the remaining distance in half 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. fixed_diameter : string The dictionary key containing the pore diameter values already assigned to network, if any. If not provided a starting value is assumed as half-way to the nearest neighbor. iters : integer The number of iterations to perform when searching for maximum diameter. This function iteratively grows pores until they touch their nearest neighbor, which is also growing, so this parameter limits the maximum number of iterations. The default is 10, but 5 is usally enough. Notes ----- This model looks into all pores in the network when finding the diameter. This means that when multiple Geometry objects are defined, it will consider the diameter of pores on adjacent Geometries. If no diameters have been assigned to these neighboring pores it will assume 0. If diameter value are assigned to the neighboring pores AFTER this model is run, the pores will overlap. This can be remedied by running this model again. """ network = target.project.network P12 = network['throat.conns'] C1 = network['pore.coords'][network['throat.conns'][:, 0]] C2 = network['pore.coords'][network['throat.conns'][:, 1]] L = _np.sqrt(_np.sum((C1 - C2)**2, axis=1)) try: # Fetch any existing pore diameters on the network D = network[fixed_diameter] # Set any unassigned values (nans) to 0 D[_np.isnan(D)] = 0 except KeyError: _logger.info('Pore sizes not present, calculating starting values ' + 'as half-way to the nearest neighbor') D = _np.inf*_np.ones([network.Np, ], dtype=float) _np.minimum.at(D, P12[:, 0], L) _np.minimum.at(D, P12[:, 1], L) while iters >= 0: iters -= 1 Lt = L - _np.sum(D[P12], axis=1)/2 Dadd = _np.ones_like(D)*_np.inf _np.minimum.at(Dadd, P12[:, 0], Lt) _np.minimum.at(Dadd, P12[:, 1], Lt) D += Dadd if _np.any(D < 0): _logger.info('Negative pore diameters found! Neighboring pores are ' + 'larger than the pore spacing.') return D[network.pores(target.name)]
python
{ "resource": "" }
q20782
equivalent_diameter
train
def equivalent_diameter(target, pore_volume='pore.volume', pore_shape='sphere'): r""" Calculates the diameter of a sphere or edge-length of a cube with same volume as the pore. Parameters ---------- target : OpenPNM Geometry Object The Geometry object which this model is associated with. This controls the length of the calculated array, and also provides access to other necessary geometric properties. pore_volume : string The dictionary key containing the pore volume values pore_shape : string The shape of the pore body to assume when back-calculating from volume. Options are 'sphere' (default) or 'cube'. """ from scipy.special import cbrt pore_vols = target[pore_volume] if pore_shape.startswith('sph'): value = cbrt(6*pore_vols/_np.pi) elif pore_shape.startswith('cub'): value = cbrt(pore_vols) return value
python
{ "resource": "" }
q20783
VTK.save
train
def save(cls, network, phases=[], filename='', delim=' | ', fill_nans=None): r""" Save network and phase data to a single vtp file for visualizing in Paraview Parameters ---------- network : OpenPNM Network Object The Network containing the data to be written phases : list, optional A list containing OpenPNM Phase object(s) containing data to be written filename : string, optional Filename to write data. If no name is given the file is named after the network delim : string Specify which character is used to delimit the data names. The default is ' | ' which creates a nice clean output in the Paraview pipeline viewer (e.g. net | property | pore | diameter) fill_nans : scalar The value to use to replace NaNs with. The VTK file format does not work with NaNs, so they must be dealt with. The default is `None` which means property arrays with NaNs are not written to the file. Other useful options might be 0 or -1, but the user must be aware that these are not real values, only place holders. """ project, network, phases = cls._parse_args(network=network, phases=phases) am = Dict.to_dict(network=network, phases=phases, interleave=True, categorize_by=['object', 'data']) am = FlatDict(am, delimiter=delim) key_list = list(sorted(am.keys())) network = network[0] points = network['pore.coords'] pairs = network['throat.conns'] num_points = np.shape(points)[0] num_throats = np.shape(pairs)[0] root = ET.fromstring(VTK._TEMPLATE) piece_node = root.find('PolyData').find('Piece') piece_node.set("NumberOfPoints", str(num_points)) piece_node.set("NumberOfLines", str(num_throats)) points_node = piece_node.find('Points') coords = VTK._array_to_element("coords", points.T.ravel('F'), n=3) points_node.append(coords) lines_node = piece_node.find('Lines') connectivity = VTK._array_to_element("connectivity", pairs) lines_node.append(connectivity) offsets = VTK._array_to_element("offsets", 2*np.arange(len(pairs))+2) lines_node.append(offsets) point_data_node = piece_node.find('PointData') cell_data_node = piece_node.find('CellData') for key in key_list: array = am[key] if array.dtype == 'O': logger.warning(key + ' has dtype object,' + ' will not write to file') else: if array.dtype == np.bool: array = array.astype(int) if np.any(np.isnan(array)): if fill_nans is None: logger.warning(key + ' has nans,' + ' will not write to file') continue else: array[np.isnan(array)] = fill_nans element = VTK._array_to_element(key, array) if (array.size == num_points): point_data_node.append(element) elif (array.size == num_throats): cell_data_node.append(element) if filename == '': filename = project.name filename = cls._parse_filename(filename=filename, ext='vtp') tree = ET.ElementTree(root) tree.write(filename) with open(filename, 'r+') as f: string = f.read() string = string.replace('</DataArray>', '</DataArray>\n\t\t\t') f.seek(0) # consider adding header: '<?xml version="1.0"?>\n'+ f.write(string)
python
{ "resource": "" }
q20784
VTK.load
train
def load(cls, filename, project=None, delim=' | '): r""" Read in pore and throat data from a saved VTK file. Parameters ---------- filename : string (optional) The name of the file containing the data to import. The formatting of this file is outlined below. project : OpenPNM Project object A GenericNetwork is created and added to the specified Project. If no Project is supplied then one will be created and returned. """ net = {} filename = cls._parse_filename(filename, ext='vtp') tree = ET.parse(filename) piece_node = tree.find('PolyData').find('Piece') # Extract connectivity conn_element = piece_node.find('Lines').find('DataArray') conns = VTK._element_to_array(conn_element, 2) # Extract coordinates coord_element = piece_node.find('Points').find('DataArray') coords = VTK._element_to_array(coord_element, 3) # Extract pore data for item in piece_node.find('PointData').iter('DataArray'): key = item.get('Name') array = VTK._element_to_array(item) net[key] = array # Extract throat data for item in piece_node.find('CellData').iter('DataArray'): key = item.get('Name') array = VTK._element_to_array(item) net[key] = array if project is None: project = ws.new_project() project = Dict.from_dict(dct=net, project=project, delim=delim) # Clean up data values, if necessary, like convert array's of # 1's and 0's into boolean. project = cls._convert_data(project) # Add coords and conns to network network = project.network network.update({'throat.conns': conns}) network.update({'pore.coords': coords}) return project
python
{ "resource": "" }
q20785
standard
train
def standard(target, mol_weight='pore.molecular_weight', density='pore.density'): r""" Calculates the molar density from the molecular weight and mass density 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. pore_MW : string The dictionary key containing the molecular weight in kg/mol pore_temperature : string The dictionary key containing the density in kg/m3 """ MW = target[mol_weight] rho = target[density] value = rho/MW return value
python
{ "resource": "" }
q20786
ideal_gas
train
def ideal_gas(target, pressure='pore.pressure', temperature='pore.temperature'): r""" Uses ideal gas law to calculate the molar density of an ideal gas 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. temperature : string The dictionary key containing the density in kg/m3 pressure : string The dictionary key containing the pressure values in Pascals (Pa) Returns ------- rho, the density in [mol/m3] Notes ----- This method uses the SI value for the ideal gas constant, hence the need to provide the temperature and pressure in SI. In general, OpenPNM use SI throughout for consistency. """ R = 8.31447 P = target[pressure] T = target[temperature] value = P/(R*T) return value
python
{ "resource": "" }
q20787
vanderwaals
train
def vanderwaals(target, pressure='pore.pressure', temperature='pore.temperature', critical_pressure='pore.critical_pressure', critical_temperature='pore.critical_temperature'): r""" Uses Van der Waals equation of state to calculate the density of a real gas 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. pressure : string The dictionary key containing the pressure values in Pascals (Pa) temperature : string The dictionary key containing the temperature values in Kelvin (K) critical_pressure : string The dictionary key containing the critical pressure values in Pascals (Pa) critical_temperature : string The dictionary key containing the critical temperature values in Kelvin (K) Returns ------- rho, the density in [mol/m3] """ P = target[pressure]/100000 T = target[temperature] Pc = target[critical_pressure]/100000 # convert to bars Tc = target[critical_temperature] R = 83.1447 a = 27*(R**2)*(Tc**2)/(64*Pc) b = R*Tc/(8*Pc) a1 = -1/b a2 = (R*T+b*P)/(a*b) a3 = -P/(a*b) a0 = sp.ones(sp.shape(a1)) coeffs = sp.vstack((a0, a1, a2, a3)).T density = sp.array([sp.roots(C) for C in coeffs]) value = sp.real(density[:, 2])*1e6 # Convert it to mol/m3 return value
python
{ "resource": "" }
q20788
DelaunayVoronoiDual.find_throat_facets
train
def find_throat_facets(self, throats=None): r""" Finds the indicies of the Voronoi nodes that define the facet or ridge between the Delaunay nodes connected by the given throat. Parameters ---------- throats : array_like The throats whose facets are sought. The given throats should be from the 'delaunay' network. If no throats are specified, all 'delaunay' throats are assumed. Notes ----- The method is not well optimized as it scans through each given throat inside a for-loop, so it could be slow for large networks. """ if throats is None: throats = self.throats('delaunay') temp = [] tvals = self['throat.interconnect'].astype(int) am = self.create_adjacency_matrix(weights=tvals, fmt='lil', drop_zeros=True) for t in throats: P12 = self['throat.conns'][t] Ps = list(set(am.rows[P12][0]).intersection(am.rows[P12][1])) temp.append(Ps) return sp.array(temp, dtype=object)
python
{ "resource": "" }
q20789
DelaunayVoronoiDual.find_pore_hulls
train
def find_pore_hulls(self, pores=None): r""" Finds the indices of the Voronoi nodes that define the convex hull around the given Delaunay nodes. Parameters ---------- pores : array_like The pores whose convex hull are sought. The given pores should be from the 'delaunay' network. If no pores are given, then the hull is found for all 'delaunay' pores. Notes ----- This metod is not fully optimized as it scans through each pore in a for-loop, so could be slow for large networks. """ if pores is None: pores = self.pores('delaunay') temp = [] tvals = self['throat.interconnect'].astype(int) am = self.create_adjacency_matrix(weights=tvals, fmt='lil', drop_zeros=True) for p in pores: Ps = am.rows[p] temp.append(Ps) return sp.array(temp, dtype=object)
python
{ "resource": "" }
q20790
DelaunayVoronoiDual._label_faces
train
def _label_faces(self): r''' Label the pores sitting on the faces of the domain in accordance with the conventions used for cubic etc. ''' coords = sp.around(self['pore.coords'], decimals=10) min_labels = ['front', 'left', 'bottom'] max_labels = ['back', 'right', 'top'] min_coords = sp.amin(coords, axis=0) max_coords = sp.amax(coords, axis=0) for ax in range(3): self['pore.' + min_labels[ax]] = coords[:, ax] == min_coords[ax] self['pore.' + max_labels[ax]] = coords[:, ax] == max_coords[ax]
python
{ "resource": "" }
q20791
DelaunayVoronoiDual.add_boundary_pores
train
def add_boundary_pores(self, labels=['top', 'bottom', 'front', 'back', 'left', 'right'], offset=None): r""" Add boundary pores to the specified faces of the network Pores are offset from the faces of the domain. Parameters ---------- labels : string or list of strings The labels indicating the pores defining each face where boundary pores are to be added (e.g. 'left' or ['left', 'right']) offset : scalar or array_like The spacing of the network (e.g. [1, 1, 1]). This must be given since it can be quite difficult to infer from the network, for instance if boundary pores have already added to other faces. """ offset = sp.array(offset) if offset.size == 1: offset = sp.ones(3)*offset for item in labels: Ps = self.pores(item) coords = sp.absolute(self['pore.coords'][Ps]) axis = sp.count_nonzero(sp.diff(coords, axis=0), axis=0) == 0 ax_off = sp.array(axis, dtype=int)*offset if sp.amin(coords) == sp.amin(coords[:, sp.where(axis)[0]]): ax_off = -1*ax_off topotools.add_boundary_pores(network=self, pores=Ps, offset=ax_off, apply_label=item + '_boundary')
python
{ "resource": "" }
q20792
MAT.save
train
def save(cls, network, phases=[], filename=''): r""" Write Network to a Mat file for exporting to Matlab. Parameters ---------- network : OpenPNM Network Object filename : string Desired file name, defaults to network name if not given phases : list of phase objects ([]) Phases that have properties we want to write to file """ project, network, phases = cls._parse_args(network=network, phases=phases) network = network[0] # Write to file if filename == '': filename = project.name filename = cls._parse_filename(filename=filename, ext='mat') d = Dict.to_dict(network=network, phases=phases, interleave=True) d = FlatDict(d, delimiter='|') d = sanitize_dict(d) new_d = {} for key in list(d.keys()): new_key = key.replace('|', '_').replace('.', '_') new_d[new_key] = d.pop(key) spio.savemat(file_name=filename, mdict=new_d)
python
{ "resource": "" }
q20793
Workspace._create_console_handles
train
def _create_console_handles(self, project): r""" Adds all objects in the given project to the console as variables with handle names taken from each object's name. """ import __main__ for item in project: __main__.__dict__[item.name] = item
python
{ "resource": "" }
q20794
Workspace.save_workspace
train
def save_workspace(self, filename=''): r""" Saves all the current Projects to a 'pnm' file Parameters ---------- filename : string, optional If no filename is given, a name is genrated using the current time and date. See Notes for more information on valid file names. See Also -------- save_project Notes ----- The filename can be a string such as 'saved_file.pnm'. The string can include absolute path such as 'C:\networks\saved_file.pnm', or can be a relative path such as '..\..\saved_file.pnm', which will look 2 directories above the current working directory. It can also be a path object object such as that produced by ``pathlib`` or ``os.path`` in the Python standard library. """ if filename == '': filename = 'workspace' + '_' + time.strftime('%Y%b%d_%H%M%p') filename = self._parse_filename(filename=filename, ext='pnm') d = {} for sim in self.values(): d[sim.name] = sim with open(filename, 'wb') as f: pickle.dump(d, f)
python
{ "resource": "" }
q20795
Workspace.save_project
train
def save_project(self, project, filename=''): r""" Saves given Project to a 'pnm' file This will include all of associated objects, including algorithms. Parameters ---------- project : OpenPNM Project The project to save. filename : string, optional If no filename is given, the given project name is used. See Notes for more information. See Also -------- save_workspace Notes ----- The filename can be a string such as 'saved_file.pnm'. The string can include absolute path such as 'C:\networks\saved_file.pnm', or can be a relative path such as '..\..\saved_file.pnm', which will look 2 directories above the current working directory. Can also be a path object object such as that produced by ``pathlib`` or ``os.path`` in the Python standard library. """ if filename == '': filename = project.name filename = self._parse_filename(filename=filename, ext='pnm') # Save dictionary as pickle d = {project.name: project} with open(filename, 'wb') as f: pickle.dump(d, f)
python
{ "resource": "" }
q20796
Workspace.load_project
train
def load_project(self, filename, overwrite=False): r""" Loads a Project from the specified 'pnm' file The loaded project is added to the Workspace . This will *not* delete any existing Projects in the Workspace and will rename any Projects being loaded if necessary. Parameters ---------- filename : string or path object The name of the file to open. See Notes for more information. See Also -------- load_workspace Notes ----- The filename can be a string such as 'saved_file.pnm'. The string can include absolute path such as 'C:\networks\saved_file.pnm', or can be a relative path such as '..\..\saved_file.pnm', which will look 2 directories above the current working directory. Can also be a path object object such as that produced by ``pathlib`` or ``os.path`` in the Python standard library. """ filename = self._parse_filename(filename=filename, ext='pnm') temp = {} # Read file into temporary dict with open(filename, 'rb') as f: d = pickle.load(f) # A normal pnm file is a dict of lists (projects) if type(d) is dict: for name in d.keys(): # If dict item is a list, assume it's a valid project if isinstance(d[name], list): temp[name] = d[name] else: warnings.warn('File contents must be a dictionary, ' + 'of lists, or a single list') else: if isinstance(d, list): # If pickle contains a single list temp[filename] = d else: warnings.warn('File contents must be a dictionary, ' + 'of lists, or a single list') # Now scan through temp dict to ensure valid types and names conflicts = set(temp.keys()).intersection(set(self.keys())) for name in list(temp.keys()): if name in conflicts: new_name = self._gen_name() warnings.warn('A project named ' + name + ' already exists, ' + 'renaming to ' + new_name) self[new_name] = temp[name] else: self[name] = temp[name]
python
{ "resource": "" }
q20797
Workspace.new_project
train
def new_project(self, name=None): r""" Creates a new empty Project object Parameters ---------- name : string (optional) The unique name to give to the project. If none is given, one will be automatically generated (e.g. 'sim_01`) Returns ------- An empty project object, suitable for passing into a Network generator """ sim = openpnm.utils.Project(name=name) return sim
python
{ "resource": "" }
q20798
Workspace._gen_name
train
def _gen_name(self): r""" Generates a valid name for projects """ n = [0] for item in self.keys(): if item.startswith('sim_'): n.append(int(item.split('sim_')[1])) name = 'sim_'+str(max(n)+1).zfill(2) return name
python
{ "resource": "" }
q20799
Workspace._gen_ids
train
def _gen_ids(self, size): r""" Generates a sequence of integers of the given ``size``, starting at 1 greater than the last produced value. The Workspace object keeps track of the most recent value, which persists until the current python session is restarted, so the returned array contains unique values for the given session. Parameters ---------- size : int The number of values to generate. Returns ------- A Numpy array of the specified size, containing integer values starting from the last used values. Notes ----- When a new Workspace is created the """ if not hasattr(self, '_next_id'): # If _next_id has not been set, then assign it self._next_id = 0 # But check ids in any objects present first for proj in self.values(): if len(proj) > 0: if 'pore._id' in proj.network.keys(): Pmax = proj.network['pore._id'].max() + 1 Tmax = proj.network['throat._id'].max() + 1 self._next_id = max([Pmax, Tmax, self._next_id]) ids = np.arange(self._next_id, self._next_id + size, dtype=np.int64) self._next_id += size return ids
python
{ "resource": "" }