code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def rate(self, pores=[], throats=[], mode='group'): """ 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 : str, optional Controls how to return the rate. The default value is 'group'. Options are: =========== ===================================================== mode meaning =========== ===================================================== 'group' Returns the cumulative rate of material '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) if throats.size > 0 and pores.size > 0: raise Exception('Must specify either pores or throats, not both') if (throats.size == 0) and (pores.size == 0): raise Exception('Must specify either pores or throats') network = self.project.network phase = self.project[self.settings['phase']] g = phase[self.settings['conductance']] P12 = network['throat.conns'] X12 = self.x[P12] if g.size == self.Nt: g = np.tile(g, (2, 1)).T # Make conductance an Nt by 2 matrix # The next line is critical for rates to be correct # We could also do "g.T.flatten()" or "g.flatten('F')" g = np.flip(g, axis=1) Qt = np.diff(g*X12, axis=1).ravel() if throats.size: R = np.absolute(Qt[throats]) if mode == 'group': R = np.sum(R) elif pores.size: 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)
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 : str, optional Controls how to return the rate. The default value is 'group'. Options are: =========== ===================================================== mode meaning =========== ===================================================== 'group' Returns the cumulative rate of material '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.
rate
python
PMEAL/OpenPNM
openpnm/algorithms/_transport.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/algorithms/_transport.py
MIT
def add_phases(self, phases): """ Adds supplied phases to MultiPhase object and sets occupancy to 0. Parameters ---------- phases : list[Phase] or Phase """ phases = np.array(phases, ndmin=1) for phase in phases: if phase.name in self.settings["phases"]: continue self.settings['phases'].add(phase.name) self[f'pore.occupancy.{phase.name}'] = 0.0 self[f'throat.occupancy.{phase.name}'] = 0.0
Adds supplied phases to MultiPhase object and sets occupancy to 0. Parameters ---------- phases : list[Phase] or Phase
add_phases
python
PMEAL/OpenPNM
openpnm/contrib/_multiphase.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/contrib/_multiphase.py
MIT
def set_occupancy(self, phase, *, pores=[], throats=[], values=1): r""" Specifies occupancy of a phase in each pore or throat. This method doesn't return any value. Parameters ---------- phase : Phase The phase whose occupancy is being specified. pores : ndarray The location of pores whose occupancy is to be set. throats : ndarray The location of throats whose occupancy is to be set. values : ndarray or float Pore/throat occupancy values. """ pores = np.array(pores, ndmin=1) throats = np.array(throats, ndmin=1) if not(pores.size ^ throats.size): raise Exception("Must either pass 'pores' or 'throats'") if phase not in self.project: raise Exception(f"{phase.name} doesn't belong to this project") self.add_phases(phase) if pores.size: self[f'pore.occupancy.{phase.name}'][pores] = values if throats.size: self[f'throat.occupancy.{phase.name}'][throats] = values if self.settings["throat_occupancy"] == "automatic": self.regenerate_models(propnames=f"throat.occupancy.{phase.name}")
Specifies occupancy of a phase in each pore or throat. This method doesn't return any value. Parameters ---------- phase : Phase The phase whose occupancy is being specified. pores : ndarray The location of pores whose occupancy is to be set. throats : ndarray The location of throats whose occupancy is to be set. values : ndarray or float Pore/throat occupancy values.
set_occupancy
python
PMEAL/OpenPNM
openpnm/contrib/_multiphase.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/contrib/_multiphase.py
MIT
def regenerate_models(self, propnames=None, exclude=[]): r""" Regenerate models associated with the Multiphase object This method works by first regenerating the models associated with the constituent phases, and then regenerating Multiphase models. Parameters ---------- propnames : list[str] or str The list of property names to be regenerated. If None are given then ALL models are re-run (except for those whose ``regen_mode`` is 'constant'). exclude : list[str] Since the default behavior is to run ALL models, this can be used to exclude specific models. It may be more convenient to supply as list of 2 models to exclude than to specify 8 models to include. """ # Regenerate models associated with phases within MultiPhase object for phase in self.phases.values(): phase.regenerate_models(propnames=propnames, exclude=exclude) # Regenerate models specific to MultiPhase object super().regenerate_models(propnames=propnames, exclude=exclude)
Regenerate models associated with the Multiphase object This method works by first regenerating the models associated with the constituent phases, and then regenerating Multiphase models. Parameters ---------- propnames : list[str] or str The list of property names to be regenerated. If None are given then ALL models are re-run (except for those whose ``regen_mode`` is 'constant'). exclude : list[str] Since the default behavior is to run ALL models, this can be used to exclude specific models. It may be more convenient to supply as list of 2 models to exclude than to specify 8 models to include.
regenerate_models
python
PMEAL/OpenPNM
openpnm/contrib/_multiphase.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/contrib/_multiphase.py
MIT
def set_binary_partition_coef(self, phases, model, **kwargs): """ Sets binary partition coefficient as defined by the interface concentration ratio of phase 1 to phase 2. Parameters ---------- phases : list[Phase] List of the two phases for which the binary partition coefficient model is being added. model : OpenPNM model Model for calculating the binary partition coefficient. kwargs : dict Keyword arguments to be passed to the ``model``. """ assert len(phases) == 2 # Add partition coefficient interface model to the MultiPhase propname_prefix = self.settings["partition_coef_prefix"] self._add_interface_prop(propname_prefix, phases, model, **kwargs) self._build_K()
Sets binary partition coefficient as defined by the interface concentration ratio of phase 1 to phase 2. Parameters ---------- phases : list[Phase] List of the two phases for which the binary partition coefficient model is being added. model : OpenPNM model Model for calculating the binary partition coefficient. kwargs : dict Keyword arguments to be passed to the ``model``.
set_binary_partition_coef
python
PMEAL/OpenPNM
openpnm/contrib/_multiphase.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/contrib/_multiphase.py
MIT
def _add_interface_prop(self, propname, phases, model, **kwargs): """ Adds an interface model to the MultiPhase object. See Notes. Notes ----- Let's say the two phases corresponding to the interface model are named: 'air' and 'water', and the interface propname to be added is 'throat.foo'. After augmentation, 'throat.foo.air:water' will be the propname that's stored on the ``MultiPhase`` object. Note that because of this convention, the order of the phases that are passed to this method is important. """ # Add "throat" keyword to the begining of propname if no identifier is found if propname.split(".")[0] not in ["pore", "throat"]: propname = f"throat.{propname}" # Check propname is throat property if propname.startswith("pore"): raise Exception("'propname' must be a throat property") # Add model to Multiphase propname = self._format_interface_prop(propname, phases) self.add_model(propname, model, **kwargs)
Adds an interface model to the MultiPhase object. See Notes. Notes ----- Let's say the two phases corresponding to the interface model are named: 'air' and 'water', and the interface propname to be added is 'throat.foo'. After augmentation, 'throat.foo.air:water' will be the propname that's stored on the ``MultiPhase`` object. Note that because of this convention, the order of the phases that are passed to this method is important.
_add_interface_prop
python
PMEAL/OpenPNM
openpnm/contrib/_multiphase.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/contrib/_multiphase.py
MIT
def _format_interface_prop(self, propname, phases): """Formats propname as {propname}.{phase[0].name}:{phase[1].name}""" prefix = propname suffix = ":".join(phase.name for phase in phases) return f"{prefix}.{suffix}"
Formats propname as {propname}.{phase[0].name}:{phase[1].name}
_format_interface_prop
python
PMEAL/OpenPNM
openpnm/contrib/_multiphase.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/contrib/_multiphase.py
MIT
def _build_K(self): """Updates the global partition coefficient array""" prefix = self.settings["partition_coef_prefix"] self._K = np.ones(self.Nt, dtype=float) # Find all binary partition coefficient models models = [k for k in self.models.keys() if k.startswith(prefix)] # Modify the global partition coefficient for each phase pair for model in models: K12 = self[model] phase1, phase2 = self._get_phase_labels(model) idx12, idx21 = self._get_interface_throats(phase1, phase2) self._K[idx12] = K12[idx12] self._K[idx21] = 1 / K12[idx21] # Store a reference in self as a propname for convenience self[f"{prefix}.global"][:] = self._K
Updates the global partition coefficient array
_build_K
python
PMEAL/OpenPNM
openpnm/contrib/_multiphase.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/contrib/_multiphase.py
MIT
def _interleave_data(self, prop): """Gathers property values from component phases to build a single array.""" element = self._parse_element(prop)[0] vals = np.zeros(self._count(element=element), dtype=float) # Retrieve property from constituent phases (weight = occupancy) for phase in self.phases.values(): vals += phase[prop] * self[f"{element}.occupancy.{phase.name}"] return vals
Gathers property values from component phases to build a single array.
_interleave_data
python
PMEAL/OpenPNM
openpnm/contrib/_multiphase.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/contrib/_multiphase.py
MIT
def _set_automatic_throat_occupancy(self, mode="mean"): """ Automatically interpolates throat occupancy based on that in adjacent pores. This method doesn't return any value. Parameters ---------- mode : str Interpolation method. Options are: =========== ===================================================== mode meaning =========== ===================================================== 'mean' sets the throat occupancy as the average of that in adjacent pores. 'min' sets the throat occupancy as the minimum value of that in adjacent pores. 'max' sets the throat occupancy as the maximum value of that in adjacent pores. =========== ===================================================== """ self.settings['throat_occupancy'] = 'automatic' for phase in self.phases.values(): self.add_model(propname=f"throat.occupancy.{phase.name}", model=misc.from_neighbor_pores, prop=f"pore.occupancy.{phase.name}", mode=mode)
Automatically interpolates throat occupancy based on that in adjacent pores. This method doesn't return any value. Parameters ---------- mode : str Interpolation method. Options are: =========== ===================================================== mode meaning =========== ===================================================== 'mean' sets the throat occupancy as the average of that in adjacent pores. 'min' sets the throat occupancy as the minimum value of that in adjacent pores. 'max' sets the throat occupancy as the maximum value of that in adjacent pores. =========== =====================================================
_set_automatic_throat_occupancy
python
PMEAL/OpenPNM
openpnm/contrib/_multiphase.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/contrib/_multiphase.py
MIT
def multiphase_diffusion(phase, pore_diffusivity="pore.diffusivity", throat_diffusivity="throat.diffusivity", size_factors="throat.diffusive_size_factors", partition_coef_global="throat.partition_coef.global"): r""" Calculates the diffusive conductance of conduits for multiphase systems. Parameters ---------- %(phase)s pore_diffusivity : str %(dict_blurb)s pore diffusivity throat_diffusivity : str %(dict_blurb)s throat diffusivity size_factors : str %(dict_blurb)s conduit size factors Returns ------- %(return_arr)s diffusive conductance Notes ----- This method assumes that ``phase["partition_coef"]`` contains information on binary phase partitioning. See ``MultiPhase`` class documentation for more information. """ network = phase.network cn = network.conns SF = network[size_factors] if isinstance(SF, dict): F1, Ft, F2 = SF.values() elif SF.ndim > 1: F1, Ft, F2 = SF.T else: F1, Ft, F2 = np.inf, SF, np.inf # Fetch model parameters D1, D2 = phase[pore_diffusivity][cn].T Dt = phase[throat_diffusivity] g1 = D1 * F1 gt = Dt * Ft g2 = D2 * F2 # Apply Henry's partitioning coefficient # Note: m12 = (G21*c1 - G12*c2) NOT (G12*c1 - G21*c2) K12 = phase[partition_coef_global] G21 = (1/g1 + 0.5/gt + K12 * (1/g2 + 0.5/gt)) ** -1 G12 = K12 * G21 return np.vstack((G12, G21)).T
Calculates the diffusive conductance of conduits for multiphase systems. Parameters ---------- %(phase)s pore_diffusivity : str %(dict_blurb)s pore diffusivity throat_diffusivity : str %(dict_blurb)s throat diffusivity size_factors : str %(dict_blurb)s conduit size factors Returns ------- %(return_arr)s diffusive conductance Notes ----- This method assumes that ``phase["partition_coef"]`` contains information on binary phase partitioning. See ``MultiPhase`` class documentation for more information.
multiphase_diffusion
python
PMEAL/OpenPNM
openpnm/contrib/_multiphase.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/contrib/_multiphase.py
MIT
def run(self, x0, tspan, saveat=None, integrator=None): """ Runs all of the transient algorithms simultaneoulsy and returns the solution. Parameters ---------- x0 : ndarray or float Array (or scalar) containing initial condition values. tspan : array_like Tuple (or array) containing the integration time span. saveat : array_like or float, optional If an array is passed, it signifies the time points at which the solution is to be stored, and if a scalar is passed, it refers to the interval at which the solution is to be stored. integrator : Integrator, optional Integrator object which will be used to to the time stepping. Can be instantiated using openpnm.integrators module. Returns ------- TransientSolution The solution object, which is basically a numpy array with the added functionality that it can be called to return the solution at intermediate times (i.e., those not stored in the solution object). In the case of multiphysics, the solution object is a combined array of solutions for each physics. The solution for each physics is available on each algorithm object independently. """ logger.info('Running TransientMultiphysics') if np.isscalar(saveat): saveat = np.arange(*tspan, saveat) if (saveat is not None) and (tspan[1] not in saveat): saveat = np.hstack((saveat, [tspan[1]])) integrator = ScipyRK45() if integrator is None else integrator for i, alg in enumerate(self._algs): # Perform pre-solve validations alg._validate_settings() alg._validate_topology_health() alg._validate_linear_system() # Write x0 to algorithm the obj (needed by _update_iterative_props) x0_i = self._get_x0(x0, i) alg['pore.ic'] = x0_i = np.ones(alg.Np, dtype=float) * x0_i alg._merge_inital_and_boundary_values() # Build RHS (dx/dt = RHS), then integrate the system of ODEs rhs = self._build_rhs() # Integrate RHS using the given solver soln = integrator.solve(rhs, x0, tspan, saveat) # Return dictionary containing solution self.soln = SolutionContainer() for i, alg in enumerate(self._algs): # Slice soln and attach as TransientSolution object to each alg t = soln.t x = soln[i*alg.Np:(i+1)*alg.Np, :] alg.soln = TransientSolution(t, x) # Add solution of each alg to solution dictionary self.soln[alg.settings['quantity']] = alg.soln
Runs all of the transient algorithms simultaneoulsy and returns the solution. Parameters ---------- x0 : ndarray or float Array (or scalar) containing initial condition values. tspan : array_like Tuple (or array) containing the integration time span. saveat : array_like or float, optional If an array is passed, it signifies the time points at which the solution is to be stored, and if a scalar is passed, it refers to the interval at which the solution is to be stored. integrator : Integrator, optional Integrator object which will be used to to the time stepping. Can be instantiated using openpnm.integrators module. Returns ------- TransientSolution The solution object, which is basically a numpy array with the added functionality that it can be called to return the solution at intermediate times (i.e., those not stored in the solution object). In the case of multiphysics, the solution object is a combined array of solutions for each physics. The solution for each physics is available on each algorithm object independently.
run
python
PMEAL/OpenPNM
openpnm/contrib/_transient_multiphysics.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/contrib/_transient_multiphysics.py
MIT
def _build_rhs(self): """ Returns a function handle, which calculates dy/dt = rhs(y, t). Notes ----- ``y`` is a composite array that contains ALL the variables that the multiphysics algorithm solves for, e.g., if the constituent algorithms are ``TransientFickianDiffusion``, and ``TransientFourierConduction``, ``y[0:Np-1]`` refers to the concentration, and ``[Np:2*Np-1]`` refers to the temperature values. """ def ode_func(t, y): # Initialize RHS rhs = [] for i, alg in enumerate(self._algs): # Get x from y, assume alg.Np is same for all algs x = self._get_x0(y, i) # again use helper function # Store x onto algorithm, alg.x = x # Build A and b alg._update_A_and_b() A = alg.A.tocsc() b = alg.b # Retrieve volume V = alg.network[alg.settings["pore_volume"]] # Calcualte RHS rhs_alg = np.hstack(-A.dot(x) + b)/V rhs = np.hstack((rhs, rhs_alg)) return rhs return ode_func
Returns a function handle, which calculates dy/dt = rhs(y, t). Notes ----- ``y`` is a composite array that contains ALL the variables that the multiphysics algorithm solves for, e.g., if the constituent algorithms are ``TransientFickianDiffusion``, and ``TransientFourierConduction``, ``y[0:Np-1]`` refers to the concentration, and ``[Np:2*Np-1]`` refers to the temperature values.
_build_rhs
python
PMEAL/OpenPNM
openpnm/contrib/_transient_multiphysics.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/contrib/_transient_multiphysics.py
MIT
def clear(self, mode=None): r""" Clears or deletes certain things from object. If no arguments are provided it defaults to the normal `dict` behavior. Parameters ---------- mode : str Controls which things are to be deleted. Options are: =========== ============================================================ `mode` Description =========== ============================================================ 'props' Deletes all pore and throat properties (i.e numerical data) in the object's dictionary (except 'pore.coords' and 'throat.conns' if it is a network object). 'labels' Deletes all labels (i.e. boolean data) in the object's dictionary. 'models' Delete are pore and throat properties that were produced by a pore-scale model. =========== ============================================================ """ if mode is None: super().clear() else: if isinstance(mode, str): mode = [mode] if 'props' in mode: for item in self.props(): if item not in ['pore.coords', 'throat.conns']: del self[item] if 'labels' in mode: for item in self.labels(): if item not in ['pore.'+self.name, 'throat.'+self.name]: del self[item] if 'models' in mode: for item in self.models.keys(): _ = self.pop(item.split('@')[0], None)
Clears or deletes certain things from object. If no arguments are provided it defaults to the normal `dict` behavior. Parameters ---------- mode : str Controls which things are to be deleted. Options are: =========== ============================================================ `mode` Description =========== ============================================================ 'props' Deletes all pore and throat properties (i.e numerical data) in the object's dictionary (except 'pore.coords' and 'throat.conns' if it is a network object). 'labels' Deletes all labels (i.e. boolean data) in the object's dictionary. 'models' Delete are pore and throat properties that were produced by a pore-scale model. =========== ============================================================
clear
python
PMEAL/OpenPNM
openpnm/core/_base2.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/core/_base2.py
MIT
def keys(self, mode=None): r""" An overloaded version of ``keys`` that optionally accepts a ``mode`` Parameters ---------- mode : str If given, optionally, it controls which type of keys are returned. Options are: ========== ======================================================= mode description ========== ======================================================= props Returns only keys that contain numerical arrays labels Returns only keys that contain boolean arrays models Returns only keys that were generated by a pore-scale model constants Returns only keys are were *not* generated by a pore- scale model ========== ======================================================= """ if mode is None: return super().keys() else: if isinstance(mode, str): mode = [mode] vals = set() if 'props' in mode: for item in self.props(): vals.add(item) if 'labels' in mode: for item in self.labels(): vals.add(item) if 'models' in mode: for item in self.models.keys(): propname = item.split('@')[0] if propname in self.keys(): vals.add(propname) if 'constants' in mode: vals = vals.union(set(self.props())) for item in self.models.keys(): propname = item.split('@')[0] if propname in vals: vals.remove(propname) return PrintableList(vals)
An overloaded version of ``keys`` that optionally accepts a ``mode`` Parameters ---------- mode : str If given, optionally, it controls which type of keys are returned. Options are: ========== ======================================================= mode description ========== ======================================================= props Returns only keys that contain numerical arrays labels Returns only keys that contain boolean arrays models Returns only keys that were generated by a pore-scale model constants Returns only keys are were *not* generated by a pore- scale model ========== =======================================================
keys
python
PMEAL/OpenPNM
openpnm/core/_base2.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/core/_base2.py
MIT
def to_mask(self, pores=None, throats=None): r""" Generates a boolean mask with `True` values in the given locations Parameters ---------- pores : array_like The pore indices where `True` values will be placed. If `pores` is given the `throats` is ignored. throats : array_like The throat indices where `True` values will be placed. If `pores` is given the `throats` is ignored. Returns ------- mask : ndarray, boolean A boolean array of length Np is `pores` was given or Nt if `throats` was given. """ if pores is not None: indices = np.array(pores, ndmin=1) N = self.Np elif throats is not None: indices = np.array(throats, ndmin=1) N = self.Nt else: raise Exception('Must specify either pores or throats') mask = np.zeros((N, ), dtype=bool) mask[indices] = True return mask
Generates a boolean mask with `True` values in the given locations Parameters ---------- pores : array_like The pore indices where `True` values will be placed. If `pores` is given the `throats` is ignored. throats : array_like The throat indices where `True` values will be placed. If `pores` is given the `throats` is ignored. Returns ------- mask : ndarray, boolean A boolean array of length Np is `pores` was given or Nt if `throats` was given.
to_mask
python
PMEAL/OpenPNM
openpnm/core/_base2.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/core/_base2.py
MIT
def to_indices(self, mask): r""" Converts a boolean mask to pore or throat indices Parameters ---------- mask : ndarray A boolean mask with `True` values indicating either pore or throat indices. This array must either be Nt or Np long, otherwise an Exception is raised. Returns ------- indices : ndarray An array containing numerical indices of where `mask` was `True`. Notes ----- This function is equivalent to just calling `np.where(mask)[0]` but does check to ensure that `mask` is a valid length. """ mask = np.array(mask, dtype=bool) if mask.shape[0] not in [self.Np, self.Nt]: raise Exception('Mask must be either Nt or Np long') return np.where(mask)[0]
Converts a boolean mask to pore or throat indices Parameters ---------- mask : ndarray A boolean mask with `True` values indicating either pore or throat indices. This array must either be Nt or Np long, otherwise an Exception is raised. Returns ------- indices : ndarray An array containing numerical indices of where `mask` was `True`. Notes ----- This function is equivalent to just calling `np.where(mask)[0]` but does check to ensure that `mask` is a valid length.
to_indices
python
PMEAL/OpenPNM
openpnm/core/_base2.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/core/_base2.py
MIT
def props(self, element=['pore', 'throat']): r""" Retrieves a list of keys that contain numerical data (i.e. "properties") Parameters ---------- element : str, list of strings Indicates whether `'pore'` or `'throat'` properties should be returned. The default is `['pore', 'throat']`, so both are returned. Returns ------- props : list of strings The names of all dictionary keys on the object that contain numerical data. """ if element is None: element = ['pore', 'throat'] if isinstance(element, str): element = [element] props = [] for k, v in self.items(): el, prop = k.split('.', 1) if (el in element) and (v.dtype != bool) and not prop.startswith('_'): props.append(k) props = sorted(props) props = PrintableList(props) return props
Retrieves a list of keys that contain numerical data (i.e. "properties") Parameters ---------- element : str, list of strings Indicates whether `'pore'` or `'throat'` properties should be returned. The default is `['pore', 'throat']`, so both are returned. Returns ------- props : list of strings The names of all dictionary keys on the object that contain numerical data.
props
python
PMEAL/OpenPNM
openpnm/core/_base2.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/core/_base2.py
MIT
def interpolate_data(self, propname, mode='mean'): r""" Generates an array of the requested pore/throat data by interpolating the neighboring throat/pore data. Parameters ---------- propname : str The data to be generated. mode : str Dictate how the interpolation is done. Options are 'mean', 'min', and 'max'. Returns ------- data : ndarray An ndarray containing the interpolated data. E.g. Requesting 'throat.temperature' will read the values of 'pore.temperature' in each of the neighboring pores and compute the average (if `mode='mean'`). """ from openpnm.models.misc import from_neighbor_throats, from_neighbor_pores element, prop = propname.split('.', 1) if element == 'throat': if self['pore.'+prop].dtype == bool: raise Exception('The requested datatype is boolean, cannot interpolate') values = from_neighbor_pores(self, prop='pore.'+prop, mode=mode) elif element == 'pore': if self['throat.'+prop].dtype == bool: raise Exception('The requested datatype is boolean, cannot interpolate') values = from_neighbor_throats(self, prop='throat.'+prop, mode=mode) return values
Generates an array of the requested pore/throat data by interpolating the neighboring throat/pore data. Parameters ---------- propname : str The data to be generated. mode : str Dictate how the interpolation is done. Options are 'mean', 'min', and 'max'. Returns ------- data : ndarray An ndarray containing the interpolated data. E.g. Requesting 'throat.temperature' will read the values of 'pore.temperature' in each of the neighboring pores and compute the average (if `mode='mean'`).
interpolate_data
python
PMEAL/OpenPNM
openpnm/core/_base2.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/core/_base2.py
MIT
def get_conduit_data(self, propname): r""" Fetches an Nt-by-3 array of the requested property Parameters ---------- propname : str The dictionary key of the property to fetch. Returns ------- data : ndarray An Nt-by-3 array with each column containing the requrested data for pore1, throat, and pore2 respectively. """ poreprop = 'pore.' + propname.split('.', 1)[-1] throatprop = 'throat.' + propname.split('.', 1)[-1] conns = self.network.conns try: T = self[throatprop] if T.ndim > 1: raise Exception(f'{throatprop} must be a single column wide') except KeyError: T = np.ones([self.Nt, ], dtype=float)*np.nan try: P1, P2 = self[poreprop][conns.T] except KeyError: P1 = np.ones([self.Nt, ], dtype=float)*np.nan P2 = np.ones([self.Nt, ], dtype=float)*np.nan vals = np.vstack((P1, T, P2)).T if np.isnan(vals).sum() == vals.size: raise KeyError(f'{propname} not found') return vals
Fetches an Nt-by-3 array of the requested property Parameters ---------- propname : str The dictionary key of the property to fetch. Returns ------- data : ndarray An Nt-by-3 array with each column containing the requrested data for pore1, throat, and pore2 respectively.
get_conduit_data
python
PMEAL/OpenPNM
openpnm/core/_base2.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/core/_base2.py
MIT
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 : int or array_like 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 = np.array([], ndmin=1, dtype=int) locs = np.array(indices, ndmin=1) # If boolean array, convert to indices if locs.dtype == bool: if np.size(locs) == self.Np: locs = self.Ps[locs] elif np.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
This private method accepts a list of pores or throats and returns a properly structured Numpy array of indices. Parameters ---------- indices : int or array_like 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.
_parse_indices
python
PMEAL/OpenPNM
openpnm/core/_mixins.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/core/_mixins.py
MIT
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 : str or List[str] The element argument to check. If is None is recieved, then a list containing both \'pore\' and \'throat\' is returned. single : bool (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 containing 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 isinstance(element, str): element = [element] # Convert 'pore.prop' and 'throat.prop' into just 'pore' and 'throat' element = [item.split('.', 1)[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('All keys must start with either pore or throat') # 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') element = element[0] return element
This private method is used to parse the keyword \'element\' in many of the above methods. Parameters ---------- element : str or List[str] The element argument to check. If is None is recieved, then a list containing both \'pore\' and \'throat\' is returned. single : bool (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 containing the element(s) is returned. When ``single`` is ``True`` a bare string containing the element is returned.
_parse_element
python
PMEAL/OpenPNM
openpnm/core/_mixins.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/core/_mixins.py
MIT
def _parse_labels(self, labels, element): r""" This private method is used for converting \'labels\' to a proper format, including dealing with wildcards (\*). Parameters ---------- labels : str or List[str] The label or list of labels to be parsed. Note that the \* can be used as a wildcard. Returns ------- A list of label strings, with all wildcard matches included if applicable. """ if labels is None: raise Exception('Labels cannot be None') if isinstance(labels, str): labels = [labels] # Parse the labels list parsed_labels = [] for label in labels: # Remove element from label, if present if element in label: label = label.split('.', 1)[-1] # Deal with wildcards if '*' in label: Ls = [L.split('.', 1)[-1] for L in self.labels(element=element)] if label.startswith('*'): temp = [L for L in Ls if L.endswith(label.strip('*'))] if label.endswith('*'): temp = [L for L in Ls if L.startswith(label.strip('*'))] temp = [element+'.'+L for L in temp] elif element+'.'+label in self.keys(): temp = [element+'.'+label] else: temp = [element+'.'+label] parsed_labels.extend(temp) # Remove duplicates if any _ = [parsed_labels.remove(L) for L in parsed_labels if parsed_labels.count(L) > 1] return parsed_labels
This private method is used for converting \'labels\' to a proper format, including dealing with wildcards (\*). Parameters ---------- labels : str or List[str] The label or list of labels to be parsed. Note that the \* can be used as a wildcard. Returns ------- A list of label strings, with all wildcard matches included if applicable.
_parse_labels
python
PMEAL/OpenPNM
openpnm/core/_mixins.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/core/_mixins.py
MIT
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 : str or List[str] The mode(s) to be parsed allowed : List[str] 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 : bool (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 isinstance(mode, 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 ' + 'is allowed by this method') mode = mode[0] return mode
This private method is for checking the \'mode\' used in the calling method. Parameters ---------- mode : str or List[str] The mode(s) to be parsed allowed : List[str] 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 : bool (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.
_parse_mode
python
PMEAL/OpenPNM
openpnm/core/_mixins.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/core/_mixins.py
MIT
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 = [i for i in self.keys(mode='labels') if i.split('.', 1)[0] in element] labels.sort() labels = np.array(labels) # Convert to ndarray for following checks # Make an 2D array with locations in rows and labels in cols arr = np.vstack([self[item][locations] for item in labels]).T num_hits = np.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)
This is the actual label getter method, but it should not be called directly. Use ``labels`` instead.
_get_labels
python
PMEAL/OpenPNM
openpnm/core/_mixins.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/core/_mixins.py
MIT
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 : str 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 : str, optional Controls how the query should be performed. Only applicable when ``pores`` or ``throats`` are specified: ============== =================================================== mode meaning ============== =================================================== 'or' Returns the labels that are assigned to *any* of the given locations. Also accepts 'union' and 'any' 'and' Labels that are present on all the given locations. also accepts 'intersection' and 'all' 'xor' Labels that are present on *only one* of the given locations.Also accepts 'exclusive_or' 'nor' Labels that are *not* present on any of the given locations. Also accepts 'not' and 'none' '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. ============== =================================================== 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. """ # Short-circuit query when no pores or throats are given if (np.size(pores) == 0) and (np.size(throats) == 0): if element is None: element = ['pore', 'throat'] if isinstance(element, str): element = [element] labels = PrintableList() for k, v in self.items(): el, prop = k.split('.', 1) if (el in element) and (v.dtype == bool) and not prop.startswith('_'): labels.append(k) elif (np.size(pores) > 0) and (np.size(throats) > 0): raise Exception('Cannot perform label query on pores and ' + 'throats simultaneously') elif np.size(pores) > 0: labels = self._get_labels(element='pore', locations=pores, mode=mode) elif np.size(throats) > 0: labels = self._get_labels(element='throat', locations=throats, mode=mode) return sorted(labels)
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 : str 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 : str, optional Controls how the query should be performed. Only applicable when ``pores`` or ``throats`` are specified: ============== =================================================== mode meaning ============== =================================================== 'or' Returns the labels that are assigned to *any* of the given locations. Also accepts 'union' and 'any' 'and' Labels that are present on all the given locations. also accepts 'intersection' and 'all' 'xor' Labels that are present on *only one* of the given locations.Also accepts 'exclusive_or' 'nor' Labels that are *not* present on any of the given locations. Also accepts 'not' and 'none' '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. ============== =================================================== 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.
labels
python
PMEAL/OpenPNM
openpnm/core/_mixins.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/core/_mixins.py
MIT
def set_label(self, label, pores=None, throats=None, mode='add'): r""" Creates or updates a label array Parameters ---------- label : str The label to apply to the specified locations pores : array_like A list of pore indices or a boolean mask of where given label should be added or removed (see ``mode``) throats : array_like A list of throat indices or a boolean mask of where given label should be added or removed (see ``mode``) mode : str Controls how the labels are handled. Options are: =========== ====================================================== mode description =========== ====================================================== 'add' (default) Adds the given label to the specified locations while keeping existing labels 'overwrite' Removes existing label from all locations before adding the label in the specified locations 'remove' Removes the given label from the specified locations leaving the remainder intact 'purge' Removes the specified label from the object completely. This ignores the ``pores`` and ``throats`` arguments. 'clear' Sets all the labels to ``False`` but does not remove the label array =========== ====================================================== """ self._parse_mode(mode=mode, allowed=['add', 'overwrite', 'remove', 'purge', 'clear']) if label.split('.', 1)[0] in ['pore', 'throat']: label = label.split('.', 1)[1] if (pores is not None) and (throats is not None): self.set_label(label=label, pores=pores, mode=mode) self.set_label(label=label, throats=throats, mode=mode) return elif pores is not None: locs = self._parse_indices(pores) element = 'pore' elif throats is not None: locs = self._parse_indices(throats) element = 'throat' if mode == 'add': if element + '.' + label not in self.keys(): self[element + '.' + label] = False self[element + '.' + label][locs] = True if mode == 'overwrite': self[element + '.' + label] = False self[element + '.' + label][locs] = True if mode == 'remove': self[element + '.' + label][locs] = False if mode == 'clear': self['pore' + '.' + label] = False self['throat' + '.' + label] = False if mode == 'purge': _ = self.pop('pore.' + label, None) _ = self.pop('throat.' + label, None)
Creates or updates a label array Parameters ---------- label : str The label to apply to the specified locations pores : array_like A list of pore indices or a boolean mask of where given label should be added or removed (see ``mode``) throats : array_like A list of throat indices or a boolean mask of where given label should be added or removed (see ``mode``) mode : str Controls how the labels are handled. Options are: =========== ====================================================== mode description =========== ====================================================== 'add' (default) Adds the given label to the specified locations while keeping existing labels 'overwrite' Removes existing label from all locations before adding the label in the specified locations 'remove' Removes the given label from the specified locations leaving the remainder intact 'purge' Removes the specified label from the object completely. This ignores the ``pores`` and ``throats`` arguments. 'clear' Sets all the labels to ``False`` but does not remove the label array =========== ======================================================
set_label
python
PMEAL/OpenPNM
openpnm/core/_mixins.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/core/_mixins.py
MIT
def _get_indices(self, element, labels, 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) # Begin computing label array if mode in ['or', 'any', 'union']: union = np.zeros([self._count(element), ], dtype=bool) for item in labels: # Iterate over labels and collect all indices union = union + self[element+'.'+item.split('.', 1)[-1]] ind = union elif mode in ['and', 'all', 'intersection']: intersect = np.ones([self._count(element), ], dtype=bool) for item in labels: # Iterate over labels and collect all indices intersect = intersect*self[element+'.'+item.split('.', 1)[-1]] ind = intersect elif mode in ['xor', 'exclusive_or']: xor = np.zeros([self._count(element), ], dtype=int) for item in labels: # Iterate over labels and collect all indices info = self[element+'.'+item.split('.', 1)[-1]] xor = xor + np.int8(info) ind = (xor == 1) elif mode in ['nor', 'not', 'none']: nor = np.zeros([self._count(element), ], dtype=int) for item in labels: # Iterate over labels and collect all indices info = self[element+'.'+item.split('.', 1)[-1]] nor = nor + np.int8(info) ind = (nor == 0) elif mode in ['nand']: nand = np.zeros([self._count(element), ], dtype=int) for item in labels: # Iterate over labels and collect all indices info = self[element+'.'+item.split('.', 1)[-1]] nand = nand + np.int8(info) ind = (nand < len(labels)) * (nand > 0) elif mode in ['xnor', 'nxor']: xnor = np.zeros([self._count(element), ], dtype=int) for item in labels: # Iterate over labels and collect all indices info = self[element+'.'+item.split('.', 1)[-1]] xnor = xnor + np.int8(info) ind = (xnor > 1) else: raise Exception('Unsupported mode: '+mode) # Extract indices from boolean mask ind = np.where(ind)[0] ind = ind.astype(dtype=int) return ind
This is the actual method for getting indices, but should not be called directly. Use ``pores`` or ``throats`` instead.
_get_indices
python
PMEAL/OpenPNM
openpnm/core/_mixins.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/core/_mixins.py
MIT
def pores(self, labels=None, mode='or', asmask=False): r""" Returns pore indicies where given labels exist, according to the logic specified by the ``mode`` argument. Parameters ---------- labels : str or list[str] The label(s) whose pores locations are requested. This argument also accepts '*' for wildcard searches. mode : str Specifies how the query should be performed. The options are: ============== =================================================== mode meaning ============== =================================================== 'or' Returns the labels that are assigned to *any* of the given locations. Also accepts 'union' and 'any' 'and' Labels that are present on all the given locations. also accepts 'intersection' and 'all' 'xor' Labels that are present on *only one* of the given locations.Also accepts 'exclusive_or' 'nor' Labels that are *not* present on any of the given locations. Also accepts 'not' and 'none' '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. ============== =================================================== asmask : bool 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. """ if labels is None: labels = self.name ind = self._get_indices(element='pore', labels=labels, mode=mode) if asmask: ind = self.to_mask(pores=ind) return ind
Returns pore indicies where given labels exist, according to the logic specified by the ``mode`` argument. Parameters ---------- labels : str or list[str] The label(s) whose pores locations are requested. This argument also accepts '*' for wildcard searches. mode : str Specifies how the query should be performed. The options are: ============== =================================================== mode meaning ============== =================================================== 'or' Returns the labels that are assigned to *any* of the given locations. Also accepts 'union' and 'any' 'and' Labels that are present on all the given locations. also accepts 'intersection' and 'all' 'xor' Labels that are present on *only one* of the given locations.Also accepts 'exclusive_or' 'nor' Labels that are *not* present on any of the given locations. Also accepts 'not' and 'none' '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. ============== =================================================== asmask : bool 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.
pores
python
PMEAL/OpenPNM
openpnm/core/_mixins.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/core/_mixins.py
MIT
def filter_by_label(self, pores=[], throats=[], labels=None, mode='or'): r""" Returns which of the supplied pores (or throats) has the specified label(s) Parameters ---------- pores, or throats : array_like List of pores or throats to be filtered labels : list of strings The labels to apply as a filter mode : str Controls how the filter is applied. The default value is 'or'. Options include: ============== =================================================== mode meaning ============== =================================================== 'or' Returns the labels that are assigned to *any* of the given locations. Also accepts 'union' and 'any' 'and' Labels that are present on all the given locations. also accepts 'intersection' and 'all' 'xor' Labels that are present on *only one* of the given locations.Also accepts 'exclusive_or' 'nor' Labels that are *not* present on any of the given locations. Also accepts 'not' and 'none' '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. ============== =================================================== Returns ------- A list of pores (or throats) that have been filtered according the given criteria. The returned list is a subset of the received list of pores (or throats). See Also -------- pores throats """ # Convert inputs to locations and element if (np.size(throats) > 0) and (np.size(pores) > 0): raise Exception('Can only filter either pores OR labels') if np.size(pores) > 0: element = 'pore' locations = self._parse_indices(pores) elif np.size(throats) > 0: element = 'throat' locations = self._parse_indices(throats) else: return np.array([], dtype=int) labels = self._parse_labels(labels=labels, element=element) labels = [element+'.'+item.split('.', 1)[-1] for item in labels] all_locs = self._get_indices(element=element, labels=labels, mode=mode) mask = self._tomask(indices=all_locs, element=element) ind = mask[locations] return locations[ind]
Returns which of the supplied pores (or throats) has the specified label(s) Parameters ---------- pores, or throats : array_like List of pores or throats to be filtered labels : list of strings The labels to apply as a filter mode : str Controls how the filter is applied. The default value is 'or'. Options include: ============== =================================================== mode meaning ============== =================================================== 'or' Returns the labels that are assigned to *any* of the given locations. Also accepts 'union' and 'any' 'and' Labels that are present on all the given locations. also accepts 'intersection' and 'all' 'xor' Labels that are present on *only one* of the given locations.Also accepts 'exclusive_or' 'nor' Labels that are *not* present on any of the given locations. Also accepts 'not' and 'none' '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. ============== =================================================== Returns ------- A list of pores (or throats) that have been filtered according the given criteria. The returned list is a subset of the received list of pores (or throats). See Also -------- pores throats
filter_by_label
python
PMEAL/OpenPNM
openpnm/core/_mixins.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/core/_mixins.py
MIT
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 : str, optional Specifies how the count should be performed. The options are: ============== =================================================== mode meaning ============== =================================================== 'or' Returns the labels that are assigned to *any* of the given locations. Also accepts 'union' and 'any' 'and' Labels that are present on all the given locations. also accepts 'intersection' and 'all' 'xor' Labels that are present on *only one* of the given locations.Also accepts 'exclusive_or' 'nor' Labels that are *not* present on any of the given locations. Also accepts 'not' and 'none' '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. ============== =================================================== 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. """ # Count number of pores of specified type Ps = self._get_indices(labels=labels, mode=mode, element='pore') Np = np.shape(Ps)[0] return Np
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 : str, optional Specifies how the count should be performed. The options are: ============== =================================================== mode meaning ============== =================================================== 'or' Returns the labels that are assigned to *any* of the given locations. Also accepts 'union' and 'any' 'and' Labels that are present on all the given locations. also accepts 'intersection' and 'all' 'xor' Labels that are present on *only one* of the given locations.Also accepts 'exclusive_or' 'nor' Labels that are *not* present on any of the given locations. Also accepts 'not' and 'none' '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. ============== =================================================== 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.
num_pores
python
PMEAL/OpenPNM
openpnm/core/_mixins.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/core/_mixins.py
MIT
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 : str, optional Specifies how the count should be performed. The options are: ============== =================================================== mode meaning ============== =================================================== 'or' Returns the labels that are assigned to *any* of the given locations. Also accepts 'union' and 'any' 'and' Labels that are present on all the given locations. also accepts 'intersection' and 'all' 'xor' Labels that are present on *only one* of the given locations.Also accepts 'exclusive_or' 'nor' Labels that are *not* present on any of the given locations. Also accepts 'not' and 'none' '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. ============== =================================================== 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 = np.shape(Ts)[0] return Nt
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 : str, optional Specifies how the count should be performed. The options are: ============== =================================================== mode meaning ============== =================================================== 'or' Returns the labels that are assigned to *any* of the given locations. Also accepts 'union' and 'any' 'and' Labels that are present on all the given locations. also accepts 'intersection' and 'all' 'xor' Labels that are present on *only one* of the given locations.Also accepts 'exclusive_or' 'nor' Labels that are *not* present on any of the given locations. Also accepts 'not' and 'none' '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. ============== =================================================== 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.
num_throats
python
PMEAL/OpenPNM
openpnm/core/_mixins.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/core/_mixins.py
MIT
def _find_target(self): """ Finds and returns the target object to which this ModelsDict is associated. """ for proj in ws.values(): for obj in proj: if hasattr(obj, "models"): if obj.models is self: return obj raise Exception("No target object found!")
Finds and returns the target object to which this ModelsDict is associated.
_find_target
python
PMEAL/OpenPNM
openpnm/core/_models.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/core/_models.py
MIT
def dependency_list(self): r""" Returns a list of dependencies in the order with which they should be called to ensure data is calculated by one model before it's asked for by another. Notes ----- This raises an exception if the graph has cycles which means the dependencies are unresolvable (i.e. there is no order which the models can be called that will work). In this case it is possible to visually inspect the graph using ``dependency_graph``. See Also -------- dependency_graph dependency_map """ import networkx as nx dtree = self.dependency_graph() cycles = list(nx.simple_cycles(dtree)) if cycles: msg = 'Cyclic dependency: ' + ' -> '.join(cycles[0] + [cycles[0][0]]) raise Exception(msg) d = nx.algorithms.dag.lexicographical_topological_sort(dtree, sorted) return list(d)
Returns a list of dependencies in the order with which they should be called to ensure data is calculated by one model before it's asked for by another. Notes ----- This raises an exception if the graph has cycles which means the dependencies are unresolvable (i.e. there is no order which the models can be called that will work). In this case it is possible to visually inspect the graph using ``dependency_graph``. See Also -------- dependency_graph dependency_map
dependency_list
python
PMEAL/OpenPNM
openpnm/core/_models.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/core/_models.py
MIT
def dependency_graph(self, deep=False): """ Returns a NetworkX graph object of the dependencies Parameters ---------- deep : bool, optional Defines whether intra- or inter-object dependency graph is desired. Default is False, i.e. only returns dependencies within the object. See Also -------- dependency_list dependency_map """ import networkx as nx dtree = nx.DiGraph() models = list(self.keys()) for model in models: propname = model.split("@")[0] dtree.add_node(propname) # Filter pore/throat props only args = op.utils.flat_list(self[model].values()) dependencies = [arg for arg in args if is_valid_propname(arg)] # Add dependency from model's parameters for d in dependencies: dtree.add_edge(d, propname) return dtree
Returns a NetworkX graph object of the dependencies Parameters ---------- deep : bool, optional Defines whether intra- or inter-object dependency graph is desired. Default is False, i.e. only returns dependencies within the object. See Also -------- dependency_list dependency_map
dependency_graph
python
PMEAL/OpenPNM
openpnm/core/_models.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/core/_models.py
MIT
def dependency_map(self, ax=None, figsize=None, deep=False, style='shell'): # pragma: no cover """ Create a graph of the dependency graph in a decent format Parameters ---------- ax : matplotlib.axis, optional Matplotlib axis object on which dependency map is to be drawn. figsize : tuple, optional Tuple containing frame size. See Also -------- dependency_graph dependency_list """ import networkx as nx import matplotlib.pyplot as plt if ax is None: fig, ax = plt.subplots() if figsize is not None: fig.set_size_inches(figsize) labels = {} node_shapes = {} dtree = self.dependency_graph(deep=deep) for node in dtree.nodes: labels[node] = node.split(".")[1] node_shapes[node] = "o" if node.startswith("pore") else "s" nx.set_node_attributes(dtree, node_shapes, "node_shape") layout = getattr(nx, f"{style}_layout") pos = layout(dtree) Pprops = [prop for prop in dtree.nodes if prop.startswith("pore")] Tprops = [prop for prop in dtree.nodes if prop.startswith("throat")] colors = ["yellowgreen", "coral"] shapes = ["o", "s"] for props, color, shape in zip([Pprops, Tprops], colors, shapes): nx.draw( dtree, pos=pos, nodelist=props, node_shape=shape, labels=labels, with_labels=True, edge_color='lightgrey', node_color=color, font_size=12, width=2.0 ) ax = plt.gca() ax.margins(x=0.2, y=0.05) return ax
Create a graph of the dependency graph in a decent format Parameters ---------- ax : matplotlib.axis, optional Matplotlib axis object on which dependency map is to be drawn. figsize : tuple, optional Tuple containing frame size. See Also -------- dependency_graph dependency_list
dependency_map
python
PMEAL/OpenPNM
openpnm/core/_models.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/core/_models.py
MIT
def _info(self): # Pragma: no cover r""" Prints a nicely formatted list of model names and the domain to which they apply. Notes ----- This is a hidden function for now, but could be exposed if useful. """ names = {} for item in self: name, _, domain = item.partition('@') if name not in names.keys(): names[name] = [] names[name].append(domain) D = PrintableDict(names, key='Model', value='Domain') print(D)
Prints a nicely formatted list of model names and the domain to which they apply. Notes ----- This is a hidden function for now, but could be exposed if useful.
_info
python
PMEAL/OpenPNM
openpnm/core/_models.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/core/_models.py
MIT
def target(self): """ Finds and returns the object to which this model is assigned """ for proj in ws.values(): for obj in proj: if hasattr(obj, "models"): for mod in obj.models.values(): if mod is self: return obj raise Exception("No target object found!")
Finds and returns the object to which this model is assigned
target
python
PMEAL/OpenPNM
openpnm/core/_models.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/core/_models.py
MIT
def add_model(self, propname, model, domain='all', regen_mode='normal', **kwargs): r""" Add a pore-scale model to the object, along with the desired arguments Parameters ---------- propname : str The name of the property being computed. E.g. if ``propname='pore.diameter'`` then the computed results will be stored in ``obj['pore.diameter']``. model : function handle The function that produces the values domain : str The label indicating the locations in which results generated by ``model`` should be stored. See `Notes` for more details. regen_mode : str How the model should be regenerated. Options are: ============ ===================================================== regen_mode description ============ ===================================================== normal (default) The model is run immediately upon being added, and is also run each time ``regenerate_models`` is called. deferred The model is NOT run when added, but is run each time ``regenerate_models`` is called. This is useful for models that depend on other data that may not exist yet. constant The model is run immediately upon being added, but is is not run when ``regenerate_models`` is called, effectively turning the property into a constant. ============ ===================================================== kwargs : keyword arguments All additional keyword arguments are passed on to the model Notes ----- The ``domain`` argument dictates where the results of ``model`` should be stored. For instance, given ``propname='pore.diameter'`` and ``domain='left'`` then when `model` is run, the results are stored in in the pores labelled left. Note that if ``model`` returns ``Np`` values, then values not belonging to ``'pore.left'`` are discarded. The following steps outline the process: 1. Find the pore indices: .. code-block:: python Ps = obj.pores('left') 2. Run the model: .. code-block:: python vals = model(**kwargs) 3. If the model returns a full Np-length array, then extract the correct values and apply them to the corresponding locations: .. code-block:: python if len(vals) == obj.Np: obj['pore.diameter'][Ps] = vals[Ps] 4. If the model was designed to return only the subset of values then: .. code-block:: python if len(vals) == obj.num_pores('left'): obj['pore.diameter'][Ps] = vals """ if '@' in propname: propname, domain = propname.split('@') elif domain is None: domain = self.settings['default_domain'] element, prop = propname.split('.', 1) domain = domain.split('.', 1)[-1] # Add model and regen_mode to kwargs dictionary kwargs.update({'model': model, 'regen_mode': regen_mode}) # Insepct model to extract arguments and default values kwargs.update(self._inspect_model(model, kwargs)) self.models[propname+'@'+domain] = ModelWrapper(**kwargs) if regen_mode != 'deferred': self.run_model(propname+'@'+domain)
Add a pore-scale model to the object, along with the desired arguments Parameters ---------- propname : str The name of the property being computed. E.g. if ``propname='pore.diameter'`` then the computed results will be stored in ``obj['pore.diameter']``. model : function handle The function that produces the values domain : str The label indicating the locations in which results generated by ``model`` should be stored. See `Notes` for more details. regen_mode : str How the model should be regenerated. Options are: ============ ===================================================== regen_mode description ============ ===================================================== normal (default) The model is run immediately upon being added, and is also run each time ``regenerate_models`` is called. deferred The model is NOT run when added, but is run each time ``regenerate_models`` is called. This is useful for models that depend on other data that may not exist yet. constant The model is run immediately upon being added, but is is not run when ``regenerate_models`` is called, effectively turning the property into a constant. ============ ===================================================== kwargs : keyword arguments All additional keyword arguments are passed on to the model Notes ----- The ``domain`` argument dictates where the results of ``model`` should be stored. For instance, given ``propname='pore.diameter'`` and ``domain='left'`` then when `model` is run, the results are stored in in the pores labelled left. Note that if ``model`` returns ``Np`` values, then values not belonging to ``'pore.left'`` are discarded. The following steps outline the process: 1. Find the pore indices: .. code-block:: python Ps = obj.pores('left') 2. Run the model: .. code-block:: python vals = model(**kwargs) 3. If the model returns a full Np-length array, then extract the correct values and apply them to the corresponding locations: .. code-block:: python if len(vals) == obj.Np: obj['pore.diameter'][Ps] = vals[Ps] 4. If the model was designed to return only the subset of values then: .. code-block:: python if len(vals) == obj.num_pores('left'): obj['pore.diameter'][Ps] = vals
add_model
python
PMEAL/OpenPNM
openpnm/core/_models.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/core/_models.py
MIT
def add_model_collection(self, models, domain='all', regen_mode='deferred'): r""" Add a ``collection`` of several models at once Parameters ---------- models : dict The collection of models to add. regen_mode : str By default the models are not regenerated upon addition. See the docstring for ``add_model`` for more information. domain : str The label indicating which locations the supplied collection of models should be applied to. Notes ----- Collections are dictionaries that are formatted the same as ``obj.models``. Several model collections are available in ``openpnm.models.collections``. """ models = deepcopy(models) for k, v in models.items(): if 'domain' not in v.keys(): v['domain'] = domain if 'regen_mode' not in v.keys(): v['regen_mode'] = regen_mode self.add_model(propname=k, **v)
Add a ``collection`` of several models at once Parameters ---------- models : dict The collection of models to add. regen_mode : str By default the models are not regenerated upon addition. See the docstring for ``add_model`` for more information. domain : str The label indicating which locations the supplied collection of models should be applied to. Notes ----- Collections are dictionaries that are formatted the same as ``obj.models``. Several model collections are available in ``openpnm.models.collections``.
add_model_collection
python
PMEAL/OpenPNM
openpnm/core/_models.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/core/_models.py
MIT
def regenerate_models(self, propnames=None, exclude=[]): r""" Runs all the models stored in the object's ``models`` attribute Parameters ---------- propnames : list of strings If given then only the specified models are run exclude : list of strings If given then these models will *not* be run Notes ----- This function will ensure that models are called in the correct order such that 'pore.diameter' will be run before 'pore.volume', since the diameter is required to compute the volume. """ all_models = self.models.dependency_list() # Regenerate all properties by default if propnames is None: propnames = all_models else: propnames = np.atleast_1d(propnames).tolist() # Remove any that are specifically excluded propnames = np.setdiff1d(propnames, exclude).tolist() # Reorder given propnames according to dependency tree tmp = [e.split("@")[0] for e in propnames] idx_sorted = [all_models.index(e) for e in tmp] propnames = [elem for i, elem in sorted(zip(idx_sorted, propnames))] # Now run each on in sequence for item in propnames: try: self.run_model(item) except KeyError as e: msg = (f"{item} was not run since the following property" f" is missing: {e}") logger.warning(msg) self.models[item]['regen_mode'] = 'deferred'
Runs all the models stored in the object's ``models`` attribute Parameters ---------- propnames : list of strings If given then only the specified models are run exclude : list of strings If given then these models will *not* be run Notes ----- This function will ensure that models are called in the correct order such that 'pore.diameter' will be run before 'pore.volume', since the diameter is required to compute the volume.
regenerate_models
python
PMEAL/OpenPNM
openpnm/core/_models.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/core/_models.py
MIT
def run_model(self, propname, domain=None): r""" Runs the requested model and places the result into the correct locations Parameters ---------- propname : str The name of the model to run. domain : str The label of the domain for which the model should be run. Passing ``propname='pore.diameter@domain1`` and ``domain=None`` is equivalent to passing ``propname='pore.diameter`` and ``domain=domain1``. Passing ``domain=None`` will regenerate all models starting with ``propname``. """ if domain is None: if '@' in propname: # Get domain from propname if present propname, _, domain = propname.partition('@') self.run_model(propname=propname, domain=domain) else: # No domain means run model for ALL domains for item in self.models.keys(): if item.startswith(propname+"@"): _, _, domain = item.partition("@") self.run_model(propname=propname, domain=domain) else: # domain was given explicitly domain = domain.split('.', 1)[-1] element, prop = propname.split('@')[0].split('.', 1) propname = f'{element}.{prop}' mod_dict = self.models[propname+'@'+domain] # Collect kwargs kwargs = {'domain': f'{element}.{domain}'} for item in mod_dict.keys(): if item not in ['model', 'regen_mode']: kwargs[item] = mod_dict[item] # Deal with models that don't have domain argument yet if 'domain' not in inspect.getfullargspec(mod_dict['model']).args: _ = kwargs.pop('domain', None) vals = mod_dict['model'](self, **kwargs) if isinstance(vals, dict): # Handle models that return a dict for k, v in vals.items(): v = np.atleast_1d(v) if v.shape[0] == 1: # Returned item was a scalar v = np.tile(v, self._count(element)) vals[k] = v[self[f'{element}.{domain}']] elif isinstance(vals, (int, float)): # Handle models that return a float vals = np.atleast_1d(vals) else: # Index into full domain result for use below vals = vals[self[f'{element}.{domain}']] else: # Model that accepts domain arg vals = mod_dict['model'](self, **kwargs) # Finally add model results to self if isinstance(vals, np.ndarray): # If model returns single array if propname not in self.keys(): temp = self._initialize_empty_array_like(vals, element) self[f'{element}.{prop}'] = temp self[propname][self[f'{element}.{domain}']] = vals elif isinstance(vals, dict): # If model returns a dict of arrays for k, v in vals.items(): if f'{propname}.{k}' not in self.keys(): temp = self._initialize_empty_array_like(v, element) self[f'{propname}.{k}'] = temp self[f'{propname}.{k}'][self[f'{element}.{domain}']] = v
Runs the requested model and places the result into the correct locations Parameters ---------- propname : str The name of the model to run. domain : str The label of the domain for which the model should be run. Passing ``propname='pore.diameter@domain1`` and ``domain=None`` is equivalent to passing ``propname='pore.diameter`` and ``domain=domain1``. Passing ``domain=None`` will regenerate all models starting with ``propname``.
run_model
python
PMEAL/OpenPNM
openpnm/core/_models.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/core/_models.py
MIT
def solve(self, rhs, x0, tspan, saveat, **kwargs): """ Solves the system of ODEs defined by dy/dt = rhs(t, y). Parameters ---------- rhs : function handle RHS vector in the system of ODEs defined by dy/dt = rhs(t, y) x0 : array_like Initial value for the system of ODEs tspan : array_like 2-element tuple (or array) representing the timespan for the system of ODEs saveat : float or array_like If float, defines the time interval at which the solution is to be stored. If array_like, defines the time points at which the solution is to be stored. **kwargs : keyword arguments Other keyword arguments that might get used by the integrator Returns ------- TransientSolution Solution of the system of ODEs stored in a subclass of numpy's ndarray with some added functionalities (ex. you can get the solution at intermediate time points via: y = soln(t_i)). """ options = { "atol": self.atol, "rtol": self.rtol, "t_eval": saveat, # FIXME: uncomment next line when/if scipy#11815 is merged # "verbose": self.verbose, } sol = solve_ivp(rhs, tspan, x0, method="RK45", **options) if sol.success: return TransientSolution(sol.t, sol.y) raise Exception(sol.message)
Solves the system of ODEs defined by dy/dt = rhs(t, y). Parameters ---------- rhs : function handle RHS vector in the system of ODEs defined by dy/dt = rhs(t, y) x0 : array_like Initial value for the system of ODEs tspan : array_like 2-element tuple (or array) representing the timespan for the system of ODEs saveat : float or array_like If float, defines the time interval at which the solution is to be stored. If array_like, defines the time points at which the solution is to be stored. **kwargs : keyword arguments Other keyword arguments that might get used by the integrator Returns ------- TransientSolution Solution of the system of ODEs stored in a subclass of numpy's ndarray with some added functionalities (ex. you can get the solution at intermediate time points via: y = soln(t_i)).
solve
python
PMEAL/OpenPNM
openpnm/integrators/_scipy.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/integrators/_scipy.py
MIT
def network_to_comsol(network, filename=None): r""" Saves the network and geometry data from the given objects into the specified file. This exports in 2D only where throats and pores have rectangular and circular shapes, respectively. Parameters ---------- network : Network The network containing the desired data Notes ----- - The exported files contain COMSOL geometry objects, not meshes. - This class exports in 2D only. """ if op.topotools.dimensionality(network).sum() == 3: raise Exception("COMSOL I/O class only works for 2D networks!") filename = network.name if filename is None else filename f = open(f"{filename}.mphtxt", 'w') header(file=f, Nr=network.Nt, Nc=network.Np) cn = network['throat.conns'] p1 = network['pore.coords'][cn[:, 0]] p2 = network['pore.coords'][cn[:, 1]] # Compute the rotation angle of throats dif_x = p2[:, 0]-p1[:, 0] dif_y = p2[:, 1]-p1[:, 1] # Avoid division by 0 m = np.array([dif_x_i != 0 for dif_x_i in dif_x]) r = np.zeros((len(dif_x))) r[~m] = np.inf r[m] = dif_y[m]/dif_x[m] angles = np.arctan(r) r_w = network['throat.diameter'] rectangles(file=f, pores1=p1, pores2=p2, alphas=angles, widths=r_w) c_c = network['pore.coords'] c_r = network['pore.diameter']/2.0 circles(file=f, centers=c_c, radii=c_r) f.close()
Saves the network and geometry data from the given objects into the specified file. This exports in 2D only where throats and pores have rectangular and circular shapes, respectively. Parameters ---------- network : Network The network containing the desired data Notes ----- - The exported files contain COMSOL geometry objects, not meshes. - This class exports in 2D only.
network_to_comsol
python
PMEAL/OpenPNM
openpnm/io/_comsol.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/io/_comsol.py
MIT
def project_to_csv(project, filename=''): r""" Save all the pore and throat data on the Network and Phase objects to a CSV file Parameters ---------- project : list An openpnm ``project`` object filename : str or path object The name of the file to store the data """ df = project_to_pandas(project=project, join=True, delim='.') if filename == '': filename = project.name fname = _parse_filename(filename=filename, ext='csv') df.to_csv(fname, index=False)
Save all the pore and throat data on the Network and Phase objects to a CSV file Parameters ---------- project : list An openpnm ``project`` object filename : str or path object The name of the file to store the data
project_to_csv
python
PMEAL/OpenPNM
openpnm/io/_csv.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/io/_csv.py
MIT
def project_to_dict(project, categorize_by=['name'], flatten=False, element=None, delim=' | '): r""" Returns a single dictionary object containing data from the given OpenPNM project, with the keys organized differently depending on optional arguments. Parameters ---------- project : list An OpenPNM project object categorize_by : str or list[str] Indicates how the dictionaries should be organized. The list can contain any, all or none of the following strings: **'object'** : If specified the dictionary keys will be stored under a general level corresponding to their type (e.g. 'network/net_01/pore.all'). **'name'** : If specified, then the data arrays are additionally categorized by their name. This is enabled by default. **'data'** : If specified the data arrays are additionally categorized by ``label`` and ``property`` to separate *boolean* from *numeric* data. **'element'** : If specified the data arrays are additionally categorized by ``pore`` and ``throat``, meaning that the propnames are no longer prepended by a 'pore.' or 'throat.' Returns ------- A dictionary with the data stored in a hierarchical data structure, the actual format of which depends on the arguments to the function. """ network = project.network phases = project.phases algs = project.algorithms if flatten: d = {} else: d = NestedDict(delimiter=delim) def build_path(obj, key): propname = key name = '' prefix = '' datatype = '' arr = obj[key] if 'object' in categorize_by: if hasattr(obj, 'coords'): prefix = 'network' + delim else: prefix = 'phase' + delim if 'element' in categorize_by: propname = key.replace('.', delim) if 'data' in categorize_by: if arr.dtype == bool: datatype = 'labels' + delim else: datatype = 'properties' + delim if 'name' in categorize_by: name = obj.name + delim path = prefix + name + datatype + propname return path for key in network.props(element=element) + network.labels(element=element): path = build_path(obj=network, key=key) d[path] = network[key] for phase in phases: for key in phase.props(element=element) + phase.labels(element=element): path = build_path(obj=phase, key=key) d[path] = phase[key] for alg in algs: try: # 'quantity' is missing for multiphysics algorithm key = alg.settings['quantity'] except AttributeError: break # only for transient algs transient = is_transient(alg) path = build_path(alg, key) if transient: times = alg.soln[key].t for i, t in enumerate(times): d[path + '#' + nbr_to_str(t)] = alg.soln[key][:, i] else: d[path] = alg.soln[key] return d
Returns a single dictionary object containing data from the given OpenPNM project, with the keys organized differently depending on optional arguments. Parameters ---------- project : list An OpenPNM project object categorize_by : str or list[str] Indicates how the dictionaries should be organized. The list can contain any, all or none of the following strings: **'object'** : If specified the dictionary keys will be stored under a general level corresponding to their type (e.g. 'network/net_01/pore.all'). **'name'** : If specified, then the data arrays are additionally categorized by their name. This is enabled by default. **'data'** : If specified the data arrays are additionally categorized by ``label`` and ``property`` to separate *boolean* from *numeric* data. **'element'** : If specified the data arrays are additionally categorized by ``pore`` and ``throat``, meaning that the propnames are no longer prepended by a 'pore.' or 'throat.' Returns ------- A dictionary with the data stored in a hierarchical data structure, the actual format of which depends on the arguments to the function.
project_to_dict
python
PMEAL/OpenPNM
openpnm/io/_dict.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/io/_dict.py
MIT
def project_to_hdf5(project, filename=''): r""" Creates an HDF5 file containing data from the specified objects Parameters ---------- network : Network The network containing the desired data phases : list[Phase]s (optional, default is none) A list of phase objects whose data are to be included Returns ------- f : hdf5 file handle A handle to an hdf5 file. This must be closed when done (i.e. ``f.close()``. """ from h5py import File as hdfFile if filename == '': filename = project.name filename = _parse_filename(filename, ext='hdf') dct = project_to_dict(project=project) d = pd.json_normalize(dct, sep='.').to_dict(orient='records')[0] for k in list(d.keys()): d[k.replace('.', '/')] = d.pop(k) f = hdfFile(filename, "w") for item in list(d.keys()): tempname = '_'.join(item.split('.')) arr = d[item] if d[item].dtype == 'O': logger.warning(item + ' has dtype object, will not write to file') del d[item] elif 'U' in str(arr[0].dtype): pass else: f.create_dataset(name='/'+tempname, shape=arr.shape, dtype=arr.dtype, data=arr) return f
Creates an HDF5 file containing data from the specified objects Parameters ---------- network : Network The network containing the desired data phases : list[Phase]s (optional, default is none) A list of phase objects whose data are to be included Returns ------- f : hdf5 file handle A handle to an hdf5 file. This must be closed when done (i.e. ``f.close()``.
project_to_hdf5
python
PMEAL/OpenPNM
openpnm/io/_hdf5.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/io/_hdf5.py
MIT
def print_hdf5(f, flat=False): r""" Given an hdf5 file handle, prints to console in a human readable manner Parameters ---------- f : file handle The hdf5 file to print flat : bool Flag to indicate if print should be nested or flat. The default is ``flat==False`` resulting in a nested view. """ if flat is False: def print_level(f, p='', indent='-'): for item in f.keys(): if hasattr(f[item], 'keys'): p = print_level(f[item], p=p, indent=indent + indent[0]) elif indent[-1] != ' ': indent = indent + '' p = indent + item + '\n' + p return p p = print_level(f) print(p) else: f.visit(print)
Given an hdf5 file handle, prints to console in a human readable manner Parameters ---------- f : file handle The hdf5 file to print flat : bool Flag to indicate if print should be nested or flat. The default is ``flat==False`` resulting in a nested view.
print_hdf5
python
PMEAL/OpenPNM
openpnm/io/_hdf5.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/io/_hdf5.py
MIT
def network_to_jsongraph(network, filename=''): r""" Write the network to disk as a JGF file. Parameters ---------- network : Network filename : str Desired file name, defaults to network name if not given """ # Ensure output file is valid filename = _parse_filename(filename=filename, ext='json') # Ensure network contains the required properties try: required_props = {'pore.diameter', 'pore.coords', 'throat.length', 'throat.conns', 'throat.diameter'} assert required_props.issubset(network.props()) except AssertionError: raise Exception('Error - network is missing one of: ' + str(required_props)) # Create 'metadata' JSON object graph_metadata_obj = {'number_of_nodes': network.Np, 'number_of_links': network.Nt} # Create 'nodes' JSON object nodes_obj = [ { 'id': str(ps), 'metadata': { 'node_squared_radius': int(network['pore.diameter'][ps] / 2)**2, 'node_coordinates': { 'x': int(network['pore.coords'][ps, 0]), 'y': int(network['pore.coords'][ps, 1]), 'z': int(network['pore.coords'][ps, 2]) } } } for ps in network.Ps] # Create 'edges' JSON object edges_obj = [ { 'id': str(ts), 'source': str(network['throat.conns'][ts, 0]), 'target': str(network['throat.conns'][ts, 1]), 'metadata': { 'link_length': float(network['throat.length'][ts]), 'link_squared_radius': float(network['throat.diameter'][ts] / 2)**2 } } for ts in network.Ts] # Build 'graph' JSON object from 'metadata', 'nodes' and 'edges' graph_obj = {'metadata': graph_metadata_obj, 'nodes': nodes_obj, 'edges': edges_obj} # Build full JSON object json_obj = {'graph': graph_obj} # Load and validate input JSON with open(filename, 'w') as file: json.dump(json_obj, file, indent=2)
Write the network to disk as a JGF file. Parameters ---------- network : Network filename : str Desired file name, defaults to network name if not given
network_to_jsongraph
python
PMEAL/OpenPNM
openpnm/io/_jsongraph.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/io/_jsongraph.py
MIT
def network_from_jsongraph(filename): r""" Loads the JGF file onto the given project. Parameters ---------- filename : str The name of the file containing the data to import. The formatting of this file is outlined below. Returns ------- network : dict An OpenPNM Network dictionary """ # Ensure input file is valid filename = _parse_filename(filename=filename, ext='json') # Load and validate input JSON with open(filename, 'r') as file: json_file = json.load(file) if not _validate_json(json_file): raise Exception('File is not in the JSON Graph Format') # Extract graph metadata from JSON number_of_nodes = json_file['graph']['metadata']['number_of_nodes'] number_of_links = json_file['graph']['metadata']['number_of_links'] # Extract node properties from JSON nodes = sorted(json_file['graph']['nodes'], key=lambda node: int(node['id'])) x = np.array([node['metadata']['node_coordinates']['x'] for node in nodes]) y = np.array([node['metadata']['node_coordinates']['y'] for node in nodes]) z = np.array([node['metadata']['node_coordinates']['z'] for node in nodes]) # Extract link properties from JSON edges = sorted(json_file['graph']['edges'], key=lambda edge: int(edge['id'])) source = np.array([int(edge['source']) for edge in edges]) target = np.array([int(edge['target']) for edge in edges]) link_length = np.array([edge['metadata']['link_length'] for edge in edges]) link_squared_radius = np.array( [edge['metadata']['link_squared_radius'] for edge in edges]) # Generate network object network = Network() network['pore.all'] = np.ones([number_of_nodes, ], dtype=bool) network['throat.all'] = np.ones([number_of_links, ], dtype=bool) # Define primitive throat properties network['throat.length'] = link_length network['throat.conns'] = np.column_stack([source, target]) network['throat.diameter'] = 2.0 * np.sqrt(link_squared_radius) # Define primitive pore properties network['pore.index'] = np.arange(number_of_nodes) network['pore.coords'] = np.column_stack([x, y, z]) network['pore.diameter'] = np.zeros(number_of_nodes) return network
Loads the JGF file onto the given project. Parameters ---------- filename : str The name of the file containing the data to import. The formatting of this file is outlined below. Returns ------- network : dict An OpenPNM Network dictionary
network_from_jsongraph
python
PMEAL/OpenPNM
openpnm/io/_jsongraph.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/io/_jsongraph.py
MIT
def network_from_marock(filename, voxel_size=1): r""" Load data from a 3DMA-Rock extracted network. Parameters ---------- filename : str The location of the 'np2th' and 'th2np' files. This can be an absolute path or relative to the current working directory. voxel_size : scalar The resolution of the image on which 3DMA-Rock was run, in terms of the linear length of eac voxel. The default is 1. This is used to scale the voxel counts to actual dimension. It is recommended that this value be in SI units [m] to work well with OpenPNM. Returns ------- network : dict An OpenPNM Network dictionary Notes ----- This format consists of two files: 'rockname.np2th' and 'rockname.th2pn'. They should be stored together in a folder which is referred to by the path argument. These files are binary and therefore not human readable. References ---------- 3DMA-Rock is a network extraction algorithm developed by Brent Lindquist and his group It uses Medial Axis thinning to find the skeleton of the pore space, then extracts geometrical features such as pore volume and throat cross-sectional area. [1] Lindquist, W. Brent, S. M. Lee, W. Oh, A. B. Venkatarangan, H. Shin, and M. Prodanovic. "3DMA-Rock: A software package for automated analysis of rock pore structure in 3-D computed microtomography images." SUNY Stony Brook (2005). """ net = {} path = Path(filename) path = path.resolve() for file in os.listdir(path): if file.endswith(".np2th"): np2th_file = os.path.join(path, file) elif file.endswith(".th2np"): th2np_file = os.path.join(path, file) with open(np2th_file, mode='rb') as f: [Np, Nt] = np.fromfile(file=f, count=2, dtype='u4') net['pore.boundary_type'] = np.ndarray([Np, ], int) net['throat.conns'] = np.ones([Nt, 2], int)*(-1) net['pore.coordination'] = np.ndarray([Np, ], int) net['pore.ID_number'] = np.ndarray([Np, ], int) for i in range(0, Np): ID = np.fromfile(file=f, count=1, dtype='u4') net['pore.ID_number'][i] = ID net['pore.boundary_type'][i] = np.fromfile(file=f, count=1, dtype='u1') z = np.fromfile(file=f, count=1, dtype='u4')[0] net['pore.coordination'][i] = z att_pores = np.fromfile(file=f, count=z, dtype='u4') att_throats = np.fromfile(file=f, count=z, dtype='u4') for j in range(0, len(att_throats)): t = att_throats[j] - 1 p = att_pores[j] - 1 net['throat.conns'][t] = [i, p] net['throat.conns'] = np.sort(net['throat.conns'], axis=1) net['pore.volume'] = np.fromfile(file=f, count=Np, dtype='u4') nx = np.fromfile(file=f, count=1, dtype='u4') nxy = np.fromfile(file=f, count=1, dtype='u4') pos = np.fromfile(file=f, count=Np, dtype='u4') ny = nxy/nx ni = np.mod(pos, nx) nj = np.mod(np.floor(pos/nx), ny) nk = np.floor(np.floor(pos/nx)/ny) net['pore.coords'] = np.array([ni, nj, nk]).T with open(th2np_file, mode='rb') as f: Nt = np.fromfile(file=f, count=1, dtype='u4')[0] net['throat.cross_sectional_area'] = \ np.ones([Nt, ], dtype=int)*(-1) for i in range(0, Nt): ID = np.fromfile(file=f, count=1, dtype='u4') net['throat.cross_sectional_area'][i] = \ np.fromfile(file=f, count=1, dtype='f4') # numvox = np.fromfile(file=f, count=1, dtype='u4') att_pores = np.fromfile(file=f, count=2, dtype='u4') nx = np.fromfile(file=f, count=1, dtype='u4') nxy = np.fromfile(file=f, count=1, dtype='u4') pos = np.fromfile(file=f, count=Nt, dtype='u4') ny = nxy/nx ni = np.mod(pos, nx) nj = np.mod(np.floor(pos/nx), ny) nk = np.floor(np.floor(pos/nx)/ny) net['throat.coords'] = np.array([ni, nj, nk]).T net['pore.internal'] = net['pore.boundary_type'] == 0 # Convert voxel area and volume to actual dimensions net['throat.cross_sectional_area'] = \ (voxel_size**2)*net['throat.cross_sectional_area'] net['pore.volume'] = (voxel_size**3)*net['pore.volume'] network = Network() network.update(net) # Trim headless throats before returning ind = np.where(network['throat.conns'][:, 0] == -1)[0] trim(network=network, throats=ind) return network
Load data from a 3DMA-Rock extracted network. Parameters ---------- filename : str The location of the 'np2th' and 'th2np' files. This can be an absolute path or relative to the current working directory. voxel_size : scalar The resolution of the image on which 3DMA-Rock was run, in terms of the linear length of eac voxel. The default is 1. This is used to scale the voxel counts to actual dimension. It is recommended that this value be in SI units [m] to work well with OpenPNM. Returns ------- network : dict An OpenPNM Network dictionary Notes ----- This format consists of two files: 'rockname.np2th' and 'rockname.th2pn'. They should be stored together in a folder which is referred to by the path argument. These files are binary and therefore not human readable. References ---------- 3DMA-Rock is a network extraction algorithm developed by Brent Lindquist and his group It uses Medial Axis thinning to find the skeleton of the pore space, then extracts geometrical features such as pore volume and throat cross-sectional area. [1] Lindquist, W. Brent, S. M. Lee, W. Oh, A. B. Venkatarangan, H. Shin, and M. Prodanovic. "3DMA-Rock: A software package for automated analysis of rock pore structure in 3-D computed microtomography images." SUNY Stony Brook (2005).
network_from_marock
python
PMEAL/OpenPNM
openpnm/io/_marock.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/io/_marock.py
MIT
def network_from_networkx(G): r""" Creates an OpenPNM Network from a undirected NetworkX graph object Parameters ---------- G : networkx.classes.graph.Graph Object The NetworkX graph. G should be undirected. The numbering of nodes should be numeric (int's), zero-based and should not contain any gaps, i.e. ``G.nodes() = [0,1,3,4,5]`` is not allowed and should be mapped to ``G.nodes() = [0,1,2,3,4]``. Returns ------- network : dict An OpenPNM network dictionary Notes ----- 1. Each node in a NetworkX object (i.e. ``G``) can be assigned properties using syntax like ``G.node[n]['diameter'] = 0.5`` where ``n`` is the node number. There is no need to precede the property name with any indication that it is pore data such as \'pore\_\'. OpenPNM will prepend \'pore.\' to each property name. 2. Since \'pore.coords\' is so central to OpenPNM it should be specified in the NetworkX object as \'coords\', and the [X, Y, Z] coordinates of each node should be a 1x3 list. 3. Edges in a NetworkX object are accessed using the index numbers of the two nodes it connects, such as ``G.adj[2][3]['length'] = 0.1`` indicating the edge that connects nodes 2 and 3. There is no need to precede the property name with any indication that it is throat data such as \'throat\_\'. OpenPNM will prepend \'throat.\' to each property name. 4. The \'throat.conns\' property is essential to OpenPNM, but this does NOT need to be specified explicitly as a property in NetworkX. The connectivity is embedded into the network representation and is extracted by OpenPNM. """ import networkx as nx from openpnm.network import Network net = {} # Ensure G is an undirected networkX graph with numerically numbered # nodes for which numbering starts at 0 and does not contain any gaps if not isinstance(G, nx.Graph): # pragma: no cover raise Exception('Provided object is not a NetworkX graph.') if nx.is_directed(G): # pragma: no cover raise Exception('Provided graph is directed. Convert to undirected graph.') if not all(isinstance(n, int) for n in G.nodes()): # pragma: no cover raise Exception('Node numbering is not numeric. Convert to int.') if min(G.nodes()) != 0: # pragma: no cover raise Exception('Node numbering does not start at zero.') if max(G.nodes()) + 1 != len(G.nodes()): # pragma: no cover raise Exception('Node numbering contains gaps. Map nodes to remove gaps.') # Parsing node data Np = len(G) net.update({'pore.all': np.ones((Np,), dtype=bool)}) for n, props in G.nodes(data=True): for item in props.keys(): val = props[item] dtype = type(val) # Remove prepended pore. and pore_ if present for b in ['pore.', 'pore_']: item = item.replace(b, '') # Create arrays for subsequent indexing, if not present already if 'pore.'+item not in net.keys(): if dtype == str: # handle strings of arbitrary length net['pore.'+item] = np.ndarray((Np,), dtype='object') elif dtype is list: dtype = type(val[0]) if dtype == str: dtype = 'object' cols = len(val) net['pore.'+item] = np.ndarray((Np, cols), dtype=dtype) else: net['pore.'+item] = np.ndarray((Np,), dtype=dtype) net['pore.'+item][n] = val # Parsing edge data # Deal with conns explicitly try: conns = list(G.edges) # NetworkX V2 except Exception: # pragma: no cover conns = G.edges() # NetworkX V1 conns.sort() # Add conns to Network Nt = len(conns) net.update({'throat.all': np.ones(Nt, dtype=bool)}) net.update({'throat.conns': np.array(conns)}) # Scan through each edge and extract all its properties i = 0 for t in conns: props = G[t[0]][t[1]] for item in props: val = props[item] dtype = type(val) # Remove prepended throat. and throat_ if present for b in ['throat.', 'throat_']: item = item.replace(b, '') # Create arrays for subsequent indexing, if not present already if 'throat.'+item not in net.keys(): if dtype == str: net['throat.'+item] = np.ndarray((Nt,), dtype='object') if dtype is list: dtype = type(val[0]) if dtype == str: dtype = 'object' cols = len(val) net['throat.'+item] = np.ndarray((Nt, cols), dtype=dtype) else: net['throat.'+item] = np.ndarray((Nt,), dtype=dtype) net['throat.'+item][i] = val i += 1 network = Network() network.update(net) return network
Creates an OpenPNM Network from a undirected NetworkX graph object Parameters ---------- G : networkx.classes.graph.Graph Object The NetworkX graph. G should be undirected. The numbering of nodes should be numeric (int's), zero-based and should not contain any gaps, i.e. ``G.nodes() = [0,1,3,4,5]`` is not allowed and should be mapped to ``G.nodes() = [0,1,2,3,4]``. Returns ------- network : dict An OpenPNM network dictionary Notes ----- 1. Each node in a NetworkX object (i.e. ``G``) can be assigned properties using syntax like ``G.node[n]['diameter'] = 0.5`` where ``n`` is the node number. There is no need to precede the property name with any indication that it is pore data such as \'pore\_\'. OpenPNM will prepend \'pore.\' to each property name. 2. Since \'pore.coords\' is so central to OpenPNM it should be specified in the NetworkX object as \'coords\', and the [X, Y, Z] coordinates of each node should be a 1x3 list. 3. Edges in a NetworkX object are accessed using the index numbers of the two nodes it connects, such as ``G.adj[2][3]['length'] = 0.1`` indicating the edge that connects nodes 2 and 3. There is no need to precede the property name with any indication that it is throat data such as \'throat\_\'. OpenPNM will prepend \'throat.\' to each property name. 4. The \'throat.conns\' property is essential to OpenPNM, but this does NOT need to be specified explicitly as a property in NetworkX. The connectivity is embedded into the network representation and is extracted by OpenPNM.
network_from_networkx
python
PMEAL/OpenPNM
openpnm/io/_networkx.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/io/_networkx.py
MIT
def network_to_networkx(network): r""" Write OpenPNM Network to a NetworkX object. Parameters ---------- network : dict The OpenPNM Network to be converted to a NetworkX object Returns ------- G : undirected graph object A NetworkX object with all pore/throat properties attached to it """ import networkx as nx from openpnm.network import Network # Ensure network is an Network. if not isinstance(network, Network): # pragma: no cover raise Exception('Provided network is not an OpenPNM Network.') G = nx.Graph() # Extracting node list and connectivity matrix from Network nodes = map(int, network.Ps) conns = network['throat.conns'] # Explicitly add nodes and connectivity matrix G.add_nodes_from(nodes) G.add_edges_from(conns) # Attach Network properties to G for prop in network.props() + network.labels(): if 'pore.' in prop: if len(network[prop].shape) > 1: val = {i: list(network[prop][i]) for i in network.Ps} else: val = {i: network[prop][i] for i in network.Ps} nx.set_node_attributes(G, name=prop[5:], values=val) if 'throat.' in prop: val = {tuple(conn): network[prop][i] for i, conn in enumerate(conns)} nx.set_edge_attributes(G, name=prop[7:], values=val) return G
Write OpenPNM Network to a NetworkX object. Parameters ---------- network : dict The OpenPNM Network to be converted to a NetworkX object Returns ------- G : undirected graph object A NetworkX object with all pore/throat properties attached to it
network_to_networkx
python
PMEAL/OpenPNM
openpnm/io/_networkx.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/io/_networkx.py
MIT
def network_to_pandas(network, join=False, delim='.'): """Converts network data to a Pandas DataFrame.""" proj = Project() proj.append(network) # Initialize pore and throat data dictionary using Dict class pdata = project_to_dict(project=proj, element='pore', flatten=True, categorize_by=[], delim=delim) tdata = project_to_dict(project=proj, element='throat', flatten=True, categorize_by=[], delim=delim) data = _to_pandas(pdata, tdata, join, Np=network.Np, Nt=network.Nt) return data
Converts network data to a Pandas DataFrame.
network_to_pandas
python
PMEAL/OpenPNM
openpnm/io/_pandas.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/io/_pandas.py
MIT
def project_to_pandas(project, join=False, delim='.'): r""" Convert the Network and Phase data to a Pandas DataFrame(s) Parameters ---------- project : list An OpenPNM ``project`` object join : bool If ``False`` (default), two DataFrames are returned with *pore* data in one, and *throat* data in the other. If ``True`` the pore and throat data are combined into a single DataFrame. This can be problematic as it will put NaNs into all the *pore* columns which are shorter than the *throat* columns. Returns ------- Pandas ``DataFrame`` object(s) containing property and label data in each column. If ``join`` was ``False`` (default) the two DataFrames are returned in a dict, otherwise a single DataFrame with pore and throat data in the same file, despite the column length being different. """ network = project.network # Initialize pore and throat data dictionary using Dict class pdata = project_to_dict(project=project, element='pore', flatten=True, categorize_by=['name'], delim=delim) tdata = project_to_dict(project=project, element='throat', flatten=True, categorize_by=['name'], delim=delim) data = _to_pandas(pdata, tdata, join, Np=network.Np, Nt=network.Nt) return data
Convert the Network and Phase data to a Pandas DataFrame(s) Parameters ---------- project : list An OpenPNM ``project`` object join : bool If ``False`` (default), two DataFrames are returned with *pore* data in one, and *throat* data in the other. If ``True`` the pore and throat data are combined into a single DataFrame. This can be problematic as it will put NaNs into all the *pore* columns which are shorter than the *throat* columns. Returns ------- Pandas ``DataFrame`` object(s) containing property and label data in each column. If ``join`` was ``False`` (default) the two DataFrames are returned in a dict, otherwise a single DataFrame with pore and throat data in the same file, despite the column length being different.
project_to_pandas
python
PMEAL/OpenPNM
openpnm/io/_pandas.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/io/_pandas.py
MIT
def project_to_paraview(project, filename): # pragma: no cover r""" Exports an OpenPNM network to a paraview state file. Parameters ---------- network : Network The network containing the desired data. filename : str Path to saved .vtp file. Notes ----- Outputs a pvsm file that can be opened in Paraview. The pvsm file will be saved with the same name as .vtp file """ try: import paraview.simple except ModuleNotFoundError: msg = ( "The paraview python bindings must be installed using " "conda install -c conda-forge paraview, however this may require" " using a virtualenv since conflicts with other packages are common." " This is why it is not explicitly included as a dependency in" " OpenPNM." ) raise ModuleNotFoundError(msg) paraview.simple._DisableFirstRenderCameraReset() file = os.path.splitext(filename)[0] network = project.network x, y, z = np.ptp(network.coords, axis=0) if sum(op.topotools.dimensionality(network)) == 2: zshape = 0 xshape = y yshape = x elif sum(op.topotools.dimensionality(network)) == 3: zshape = x xshape = z yshape = y maxshape = max(xshape, yshape, zshape) shape = np.array([xshape, yshape, zshape]) # Create a new 'XML PolyData Reader' Path = os.getcwd() + "\\" + file + '.vtp' net_vtp = paraview.simple.XMLPolyDataReader(FileName=[Path]) p = op.io.Dict.to_dict(project=project, element=['pore'], flatten=False, categorize_by=['data' 'object']) # The folloing lines are bit complex but avoid using the flatdict lib p = pd.json_normalize(p, sep='.').to_dict(orient='records')[0] for k in list(p.keys()): p[k.replace('.', ' | ')] = p.pop(k) t = op.io.Dict.to_dict(project=project, element=['throat'], flatten=False, categorize_by=['data' 'object']) t = pd.json_normalize(t, sep='.').to_dict(orient='records')[0] for k in list(t.keys()): t[k.replace('.', '/')] = t.pop(k) # Now write the p and t dictionaries net_vtp.CellArrayStatus = t.keys() net_vtp.PointArrayStatus = p.keys() # Get active view render_view = paraview.simple.GetActiveViewOrCreate('RenderView') # Uncomment following to set a specific view size # render_view.ViewSize = [1524, 527] # Get layout _ = paraview.simple.GetLayout() # Show data in view net_vtp_display = paraview.simple.Show( net_vtp, render_view, 'GeometryRepresentation' ) # Trace defaults for the display properties. net_vtp_display.Representation = 'Surface' net_vtp_display.ColorArrayName = [None, ''] net_vtp_display.OSPRayScaleArray = [ f'network | {network.name} | labels | pore.all'] net_vtp_display.OSPRayScaleFunction = 'PiecewiseFunction' net_vtp_display.SelectOrientationVectors = 'None' net_vtp_display.ScaleFactor = (maxshape-1)/10 net_vtp_display.SelectScaleArray = 'None' net_vtp_display.GlyphType = 'Arrow' net_vtp_display.GlyphTableIndexArray = 'None' net_vtp_display.GaussianRadius = (maxshape-1)/200 net_vtp_display.SetScaleArray = \ ['POINTS', 'network | ' + network.name + ' | labels | pore.all'] net_vtp_display.ScaleTransferFunction = 'PiecewiseFunction' net_vtp_display.OpacityArray = \ ['POINTS', 'network | ' + network.name + ' | labels | pore.all'] net_vtp_display.OpacityTransferFunction = 'PiecewiseFunction' net_vtp_display.DataAxesGrid = 'GridAxesRepresentation' net_vtp_display.PolarAxes = 'PolarAxesRepresentation' # Init the 'PiecewiseFunction' selected for 'ScaleTransferFunction' net_vtp_display.ScaleTransferFunction.Points = [1, 0, 0.5, 0, 1, 1, 0.5, 0] # Init the 'PiecewiseFunction' selected for 'OpacityTransferFunction' net_vtp_display.OpacityTransferFunction.Points = [1, 0, 0.5, 0, 1, 1, 0.5, 0] # Reset view to fit data render_view.ResetCamera() # Get the material library _ = paraview.simple.GetMaterialLibrary() # Update the view to ensure updated data information render_view.Update() # Create a new 'Glyph' glyph = paraview.simple.Glyph(Input=net_vtp, GlyphType='Arrow') glyph.OrientationArray = ['POINTS', 'No orientation array'] glyph.ScaleArray = ['POINTS', 'No scale array'] glyph.ScaleFactor = 1 glyph.GlyphTransform = 'Transform2' # Properties modified on glyph glyph.GlyphType = 'Sphere' glyph.ScaleArray = \ ['POINTS', 'network | ' + network.name + ' | properties | pore.diameter'] # Show data in view glyph_display = paraview.simple.Show( glyph, render_view, 'GeometryRepresentation') # Trace defaults for the display properties. glyph_display.Representation = 'Surface' glyph_display.ColorArrayName = [None, ''] glyph_display.OSPRayScaleArray = 'Normals' glyph_display.OSPRayScaleFunction = 'PiecewiseFunction' glyph_display.SelectOrientationVectors = 'None' glyph_display.ScaleFactor = (maxshape - 1) / 10 glyph_display.SelectScaleArray = 'None' glyph_display.GlyphType = 'Arrow' glyph_display.GlyphTableIndexArray = 'None' glyph_display.GaussianRadius = (maxshape - 1) / 200 glyph_display.SetScaleArray = ['POINTS', 'Normals'] glyph_display.ScaleTransferFunction = 'PiecewiseFunction' glyph_display.OpacityArray = ['POINTS', 'Normals'] glyph_display.OpacityTransferFunction = 'PiecewiseFunction' glyph_display.DataAxesGrid = 'GridAxesRepresentation' glyph_display.PolarAxes = 'PolarAxesRepresentation' # Init the 'PiecewiseFunction' selected for 'ScaleTransferFunction' glyph_display.ScaleTransferFunction.Points = [-0.97, 0, 0.5, 0, 0.97, 1, 0.5, 0] # Init the 'PiecewiseFunction' selected for 'OpacityTransferFunction' glyph_display.OpacityTransferFunction.Points = [-0.97, 0, 0.5, 0, 0.97, 1, 0.5, 0] # Update the view to ensure updated data information render_view.Update() # Set active source paraview.simple.SetActiveSource(net_vtp) # Create a new 'Shrink' shrink1 = paraview.simple.Shrink(Input=net_vtp) # Properties modified on shrink1 shrink1.ShrinkFactor = 1.0 # Show data in view shrink_display = paraview.simple.Show( shrink1, render_view, 'UnstructuredGridRepresentation') # Trace defaults for the display properties. shrink_display.Representation = 'Surface' shrink_display.ColorArrayName = [None, ''] shrink_display.OSPRayScaleArray = \ ['network | ' + network.name + ' | labels | pore.all'] shrink_display.OSPRayScaleFunction = 'PiecewiseFunction' shrink_display.SelectOrientationVectors = 'None' shrink_display.ScaleFactor = (maxshape-1)/10 shrink_display.SelectScaleArray = 'None' shrink_display.GlyphType = 'Arrow' shrink_display.GlyphTableIndexArray = 'None' shrink_display.GaussianRadius = (maxshape-1)/200 shrink_display.SetScaleArray = \ ['POINTS', 'network | ' + network.name + ' | labels | pore.all'] shrink_display.ScaleTransferFunction = 'PiecewiseFunction' shrink_display.OpacityArray = \ ['POINTS', 'network | ' + network.name + ' | labels | pore.all'] shrink_display.OpacityTransferFunction = 'PiecewiseFunction' shrink_display.DataAxesGrid = 'GridAxesRepresentation' shrink_display.PolarAxes = 'PolarAxesRepresentation' shrink_display.ScalarOpacityUnitDistance = 1.0349360947089783 # Init the 'PiecewiseFunction' selected for 'ScaleTransferFunction' shrink_display.ScaleTransferFunction.Points = [1, 0, 0.5, 0, 1, 1, 0.5, 0] # Init the 'PiecewiseFunction' selected for 'OpacityTransferFunction' shrink_display.OpacityTransferFunction.Points = [1, 0, 0.5, 0, 1, 1, 0.5, 0] # Hide data in view paraview.simple.Hide(net_vtp, render_view) # Update the view to ensure updated data information render_view.Update() # Create a new 'Cell Data to Point Data' cellDatatoPointData1 = paraview.simple.CellDatatoPointData(Input=shrink1) cellDatatoPointData1.CellDataArraytoprocess = t # Show data in view cell_data_to_point_data_display = paraview.simple.Show( cellDatatoPointData1, render_view, 'UnstructuredGridRepresentation' ) # Trace defaults for the display properties. cell_data_to_point_data_display.Representation = 'Surface' cell_data_to_point_data_display.ColorArrayName = [None, ''] cell_data_to_point_data_display.OSPRayScaleArray = \ ['network | ' + network.name + ' | labels | pore.all'] cell_data_to_point_data_display.OSPRayScaleFunction = 'PiecewiseFunction' cell_data_to_point_data_display.SelectOrientationVectors = 'None' cell_data_to_point_data_display.ScaleFactor = (maxshape-1)/10 cell_data_to_point_data_display.SelectScaleArray = 'None' cell_data_to_point_data_display.GlyphType = 'Arrow' cell_data_to_point_data_display.GlyphTableIndexArray = 'None' cell_data_to_point_data_display.GaussianRadius = (maxshape-1)/200 cell_data_to_point_data_display.SetScaleArray = \ ['POINTS', 'network | ' + network.name + ' | labels | pore.all'] cell_data_to_point_data_display.ScaleTransferFunction = 'PiecewiseFunction' cell_data_to_point_data_display.OpacityArray = \ ['POINTS', 'network | ' + network.name + ' | labels | pore.all'] cell_data_to_point_data_display.OpacityTransferFunction = 'PiecewiseFunction' cell_data_to_point_data_display.DataAxesGrid = 'GridAxesRepresentation' cell_data_to_point_data_display.PolarAxes = 'PolarAxesRepresentation' cell_data_to_point_data_display.ScalarOpacityUnitDistance = 1.0349360947089783 # Init the 'PiecewiseFunction' selected for 'ScaleTransferFunction' cell_data_to_point_data_display.ScaleTransferFunction.Points = [ 1, 0, 0.5, 0, 1, 1, 0.5, 0] # Init the 'PiecewiseFunction' selected for 'OpacityTransferFunction' cell_data_to_point_data_display.OpacityTransferFunction.Points = [ 1, 0, 0.5, 0, 1, 1, 0.5, 0] # Hide data in view paraview.simple.Hide(shrink1, render_view) # Update the view to ensure updated data information render_view.Update() # Set active source paraview.simple.SetActiveSource(shrink1) # Set active source paraview.simple.SetActiveSource(cellDatatoPointData1) # Set active source paraview.simple.SetActiveSource(shrink1) # Create a new 'Extract Surface' extractSurface1 = paraview.simple.ExtractSurface(Input=shrink1) # Show data in view extract_surface_display = paraview.simple.Show( extractSurface1, render_view, 'GeometryRepresentation') # Trace defaults for the display properties. extract_surface_display.Representation = 'Surface' extract_surface_display.ColorArrayName = [None, ''] extract_surface_display.OSPRayScaleArray = \ ['network | ' + network.name + ' | labels | pore.all'] extract_surface_display.OSPRayScaleFunction = 'PiecewiseFunction' extract_surface_display.SelectOrientationVectors = 'None' extract_surface_display.ScaleFactor = (maxshape-1)/10 extract_surface_display.SelectScaleArray = 'None' extract_surface_display.GlyphType = 'Arrow' extract_surface_display.GlyphTableIndexArray = 'None' extract_surface_display.GaussianRadius = (maxshape-1)/200 extract_surface_display.SetScaleArray = \ ['POINTS', 'network | ' + network.name + ' | labels | pore.all'] extract_surface_display.ScaleTransferFunction = 'PiecewiseFunction' extract_surface_display.OpacityArray = \ ['POINTS', 'network | ' + network.name + ' | labels | pore.all'] extract_surface_display.OpacityTransferFunction = 'PiecewiseFunction' extract_surface_display.DataAxesGrid = 'GridAxesRepresentation' extract_surface_display.PolarAxes = 'PolarAxesRepresentation' # Init the 'PiecewiseFunction' selected for 'ScaleTransferFunction' extract_surface_display.ScaleTransferFunction.Points = [ 1, 0, 0.5, 0, 1, 1, 0.5, 0] # Init the 'PiecewiseFunction' selected for 'OpacityTransferFunction' extract_surface_display.OpacityTransferFunction.Points = [ 1, 0, 0.5, 0, 1, 1, 0.5, 0] # Hide data in view paraview.simple.Hide(shrink1, render_view) # Update the view to ensure updated data information render_view.Update() # create a new 'Tube' tube = paraview.simple.Tube(Input=extractSurface1) tube.Scalars = ['POINTS', 'network |' + network.name + '| labels | pore.all'] tube.Vectors = [None, '1'] tube.Radius = 0.04 # Set active source paraview.simple.SetActiveSource(extractSurface1) # Destroy tube paraview.simple.Delete(tube) del tube # Set active source paraview.simple.SetActiveSource(shrink1) # Set active source paraview.simple.SetActiveSource(cellDatatoPointData1) # Set active source paraview.simple.SetActiveSource(extractSurface1) # Create a new 'Tube' tube = paraview.simple.Tube(Input=extractSurface1) tube.Scalars = [ 'POINTS', 'network |' + network.name + ' | labels | pore.all'] tube.Vectors = [None, '1'] tube.Radius = 0.04 # Properties modified on tube tube.Vectors = ['POINTS', '1'] # Show data in view tube_display = paraview.simple.Show(tube, render_view, 'GeometryRepresentation') # Trace defaults for the display properties. tube_display.Representation = 'Surface' tube_display.ColorArrayName = [None, ''] tube_display.OSPRayScaleArray = 'TubeNormals' tube_display.OSPRayScaleFunction = 'PiecewiseFunction' tube_display.SelectOrientationVectors = 'None' tube_display.ScaleFactor = (maxshape)/10 tube_display.SelectScaleArray = 'None' tube_display.GlyphType = 'Arrow' tube_display.GlyphTableIndexArray = 'None' tube_display.GaussianRadius = (maxshape)/200 tube_display.SetScaleArray = ['POINTS', 'TubeNormals'] tube_display.ScaleTransferFunction = 'PiecewiseFunction' tube_display.OpacityArray = ['POINTS', 'TubeNormals'] tube_display.OpacityTransferFunction = 'PiecewiseFunction' tube_display.DataAxesGrid = 'GridAxesRepresentation' tube_display.PolarAxes = 'PolarAxesRepresentation' # Init the 'PiecewiseFunction' selected for 'ScaleTransferFunction' tube_display.ScaleTransferFunction.Points = [-1, 0, 0.5, 0, 1, 1, 0.5, 0] # Init the 'PiecewiseFunction' selected for 'OpacityTransferFunction' tube_display.OpacityTransferFunction.Points = [-1, 0, 0.5, 0, 1, 1, 0.5, 0] # Hide data in view paraview.simple.Hide(extractSurface1, render_view) # Update the view to ensure updated data information render_view.Update() # Saving camera placements for all active views # Current camera placement for render_view render_view.CameraPosition = [ (xshape + 1) / 2, (yshape + 1) / 2, 4.3 * np.sqrt(np.sum(shape / 2)**2) ] render_view.CameraFocalPoint = [(xi+1) / 2 for xi in shape] render_view.CameraParallelScale = np.sqrt(np.sum(shape / 2)**2) paraview.simple.SaveState(f"{file}.pvsm")
Exports an OpenPNM network to a paraview state file. Parameters ---------- network : Network The network containing the desired data. filename : str Path to saved .vtp file. Notes ----- Outputs a pvsm file that can be opened in Paraview. The pvsm file will be saved with the same name as .vtp file
project_to_paraview
python
PMEAL/OpenPNM
openpnm/io/_paraview.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/io/_paraview.py
MIT
def network_from_pergeos(filename): r""" Loads a network from a PerGeos file. Notes ----- PerGeos is the format used by the Avizo software. See `here for more details <https://cases.pergeos.com/>`_. """ net = {} # --------------------------------------------------------------------- # Parse the link1 file filename = _parse_filename(filename=filename, ext='am') with open(filename, mode='r') as f: Np = None Nt = None while (Np is None) or (Nt is None): s = f.readline()[:-1].split(' ') if s[0] == 'define': if s[1] == 'VERTEX': Np = int(s[2]) if s[1] == 'EDGE': Nt = int(s[2]) net = {} propmap = {} typemap = {} shapemap = {} while True: s = f.readline()[:-1].split(' ') if s[0] == 'VERTEX': dshape = [Np] if s[2].endswith(']'): ncols = int(s[2].split('[', 1)[1].split(']')[0]) dshape.append(ncols) dtype = s[2].split('[')[0] temp = np.zeros(dshape, dtype=dtype) net['pore.'+s[3]] = temp key = int(s[-1].replace('@', '')) propmap[key] = 'pore.'+s[3] typemap[key] = dtype shapemap[key] = dshape elif s[0] == 'EDGE': dshape = [Nt] if s[2].endswith(']'): ncols = int(s[2].split('[', 1)[1].split(']')[0]) dshape.append(ncols) dtype = s[2].split('[')[0] temp = np.zeros(dshape, dtype=dtype) net['throat.'+s[3]] = temp key = int(s[-1].replace('@', '')) propmap[key] = 'throat.'+s[3] typemap[key] = dtype shapemap[key] = dshape elif s[0] == '#': break s = f.read().split('@') for key in propmap.keys(): if key in s: data = s[key].split('\n')[1:] data = ' '.join(data) arr = np.fromstring(data, dtype=typemap[key], sep=' ') arr = np.reshape(arr, newshape=shapemap[key]) net[propmap[key]] = arr # End file parsing net['pore.coords'] = net['pore.VertexCoordinates'] net['throat.conns'] = np.sort(net['throat.EdgeConnectivity'], axis=1) network = Network() network.update(net) return network
Loads a network from a PerGeos file. Notes ----- PerGeos is the format used by the Avizo software. See `here for more details <https://cases.pergeos.com/>`_.
network_from_pergeos
python
PMEAL/OpenPNM
openpnm/io/_pergeos.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/io/_pergeos.py
MIT
def network_from_porespy(filename): r""" Load a network extracted using the PoreSpy package Parameters ---------- filename : str or dict Can either be a filename pointing to a pickled dictionary, or a handle to a dictionary in memory. The second option lets users avoid the step of saving the dictionary to a file. Returns ------- network : dict An OpenPNM network dictionary """ # Parse the filename if isinstance(filename, dict): net = filename else: filename = _parse_filename(filename=filename) with open(filename, mode='rb') as f: net = pk.load(f) network = Network() network.update(net) return network
Load a network extracted using the PoreSpy package Parameters ---------- filename : str or dict Can either be a filename pointing to a pickled dictionary, or a handle to a dictionary in memory. The second option lets users avoid the step of saving the dictionary to a file. Returns ------- network : dict An OpenPNM network dictionary
network_from_porespy
python
PMEAL/OpenPNM
openpnm/io/_porespy.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/io/_porespy.py
MIT
def network_to_salome(network, filename=None, explicit=False): r""" Saves the network data and writes a Salome .py instruction file. Parameters ---------- network : Network The network containing the desired data Notes ----- This method only saves the data, not any of the pore-scale models or other attributes. To save an actual OpenPNM Project use the ``Workspace`` object. """ # Temporarily add endpoints to network so STL class works network["throat.endpoints.head"] = network.coords[network.conns[:, 0]] network["throat.endpoints.tail"] = network.coords[network.conns[:, 1]] filename = network.name if filename is None else filename filename = _parse_filename(filename=filename, ext='py') f = open(filename, 'w') f.write(_header+'\n') x = network['throat.endpoints.head'] s = str(x.shape) f.write('cylinder_head = np.array([') np.savetxt(f, X=[x.flatten()], fmt='%.18e', delimiter=',', newline='') f.write('])\n') f.write('cylinder_head = np.reshape(cylinder_head, '+s+')\n') x = network['throat.endpoints.tail'] s = str(x.shape) f.write('cylinder_tail = np.array([') np.savetxt(f, X=[x.flatten()], fmt='%.18e', delimiter=',', newline='') f.write('])\n') f.write('cylinder_tail = np.reshape(cylinder_tail, '+s+')\n') x = network['throat.diameter']/2 s = str(x.shape) f.write('cylinder_r = np.array([') np.savetxt(f, X=[x.flatten()], fmt='%.18e', delimiter=',', newline='') f.write('])\n') f.write('cylinder_r = np.reshape(cylinder_r, '+s+')\n') x = network['pore.coords'] s = str(x.shape) f.write('sphere_c = np.array([') np.savetxt(f, X=[x.flatten()], fmt='%.18e', delimiter=',', newline='') f.write('])\n') f.write('sphere_c = np.reshape(sphere_c, '+s+')\n') x = network['pore.diameter']/2 s = str(x.shape) f.write('sphere_r = np.array([') np.savetxt(f, X=[x.flatten()], fmt='%.18e', delimiter=',', newline='') f.write('])\n') f.write('sphere_r = np.reshape(sphere_r, '+s+')\n') f.write('explicit = '+str(explicit)) f.write(_footer) f.close()
Saves the network data and writes a Salome .py instruction file. Parameters ---------- network : Network The network containing the desired data Notes ----- This method only saves the data, not any of the pore-scale models or other attributes. To save an actual OpenPNM Project use the ``Workspace`` object.
network_to_salome
python
PMEAL/OpenPNM
openpnm/io/_salome.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/io/_salome.py
MIT
def network_from_statoil(path, prefix): r""" Load data from the \'dat\' files located in specified folder. Parameters ---------- path : str The full path to the folder containing the set of \'dat\' files. prefix : str The file name prefix on each file. The data files are stored as \<prefix\>_node1.dat. network : Network If given then the data will be loaded on it and returned. If not given, a Network will be created and returned. Returns ------- Project An OpenPNM Project containing a Network holding all the data Notes ----- The StatOil format is used by the Maximal Ball network extraction code of the Imperial College London group This class can be used to load and work with those networks. Numerous datasets are available for download from the group's `website <http://tinyurl.com/zurko4q>`_. The 'Statoil' format consists of 4 different files in a single folder. The data is stored in columns with each corresponding to a specific property. Headers are not provided in the files, so one must refer to various theses and documents to interpret their meaning. """ net = {} # Parse the link1 file path = Path(path) filename = Path(path.resolve(), prefix+'_link1.dat') with open(filename, mode='r') as f: link1 = read_table(filepath_or_buffer=f, header=None, skiprows=1, sep=' ', skipinitialspace=True, index_col=0) link1.columns = ['throat.pore1', 'throat.pore2', 'throat.radius', 'throat.shape_factor', 'throat.total_length'] # Add link1 props to net net['throat.conns'] = np.vstack((link1['throat.pore1']-1, link1['throat.pore2']-1)).T net['throat.conns'] = np.sort(net['throat.conns'], axis=1) net['throat.radius'] = np.array(link1['throat.radius']) net['throat.shape_factor'] = np.array(link1['throat.shape_factor']) net['throat.total_length'] = np.array(link1['throat.total_length']) filename = Path(path.resolve(), prefix+'_link2.dat') with open(filename, mode='r') as f: link2 = read_table(filepath_or_buffer=f, header=None, sep=' ', skipinitialspace=True, index_col=0) link2.columns = ['throat.pore1', 'throat.pore2', 'throat.pore1_length', 'throat.pore2_length', 'throat.length', 'throat.volume', 'throat.clay_volume'] # Add link2 props to net cl_t = np.array(link2['throat.length']) net['throat.length'] = cl_t net['throat.conduit_lengths.throat'] = cl_t net['throat.volume'] = np.array(link2['throat.volume']) cl_p1 = np.array(link2['throat.pore1_length']) net['throat.conduit_lengths.pore1'] = cl_p1 cl_p2 = np.array(link2['throat.pore2_length']) net['throat.conduit_lengths.pore2'] = cl_p2 net['throat.clay_volume'] = np.array(link2['throat.clay_volume']) # --------------------------------------------------------------------- # Parse the node1 file filename = Path(path.resolve(), prefix+'_node1.dat') with open(filename, mode='r') as f: row_0 = f.readline().split() num_lines = int(row_0[0]) array = np.ndarray([num_lines, 6]) for i in range(num_lines): row = f.readline()\ .replace('\t', ' ').replace('\n', ' ').split() array[i, :] = row[0:6] node1 = DataFrame(array[:, [1, 2, 3, 4]]) node1.columns = ['pore.x_coord', 'pore.y_coord', 'pore.z_coord', 'pore.coordination_number'] # Add node1 props to net net['pore.coords'] = np.vstack((node1['pore.x_coord'], node1['pore.y_coord'], node1['pore.z_coord'])).T # --------------------------------------------------------------------- # Parse the node2 file filename = Path(path.resolve(), prefix+'_node2.dat') with open(filename, mode='r') as f: node2 = read_table(filepath_or_buffer=f, header=None, sep=' ', skipinitialspace=True, index_col=0) node2.columns = ['pore.volume', 'pore.radius', 'pore.shape_factor', 'pore.clay_volume'] # Add node2 props to net net['pore.volume'] = np.array(node2['pore.volume']) net['pore.radius'] = np.array(node2['pore.radius']) net['pore.shape_factor'] = np.array(node2['pore.shape_factor']) net['pore.clay_volume'] = np.array(node2['pore.clay_volume']) net['throat.cross_sectional_area'] = ((net['throat.radius']**2) / (4.0*net['throat.shape_factor'])) net['pore.area'] = ((net['pore.radius']**2) / (4.0*net['pore.shape_factor'])) network = Network() network.update(net) # Use OpenPNM Tools to clean up network # Trim throats connected to 'inlet' or 'outlet' reservoirs trim1 = np.where(np.any(net['throat.conns'] == -1, axis=1))[0] # Apply 'outlet' label to these pores outlets = network['throat.conns'][trim1, 1] network['pore.outlets'] = False network['pore.outlets'][outlets] = True trim2 = np.where(np.any(net['throat.conns'] == -2, axis=1))[0] # Apply 'inlet' label to these pores inlets = network['throat.conns'][trim2, 1] network['pore.inlets'] = False network['pore.inlets'][inlets] = True # Now trim the throats to_trim = np.hstack([trim1, trim2]) trim(network=network, throats=to_trim) return network
Load data from the \'dat\' files located in specified folder. Parameters ---------- path : str The full path to the folder containing the set of \'dat\' files. prefix : str The file name prefix on each file. The data files are stored as \<prefix\>_node1.dat. network : Network If given then the data will be loaded on it and returned. If not given, a Network will be created and returned. Returns ------- Project An OpenPNM Project containing a Network holding all the data Notes ----- The StatOil format is used by the Maximal Ball network extraction code of the Imperial College London group This class can be used to load and work with those networks. Numerous datasets are available for download from the group's `website <http://tinyurl.com/zurko4q>`_. The 'Statoil' format consists of 4 different files in a single folder. The data is stored in columns with each corresponding to a specific property. Headers are not provided in the files, so one must refer to various theses and documents to interpret their meaning.
network_from_statoil
python
PMEAL/OpenPNM
openpnm/io/_statoil.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/io/_statoil.py
MIT
def network_to_stl(network, filename=None, maxsize='auto', fileformat='STL Format', logger_level=0): r""" Saves (transient/steady-state) data from the given objects into the specified file. Parameters ---------- network : Network. The network containing the desired data. phases : list[Phase] (place holder, default is None). List of phases containing the desired data. filename : str (optional). The name of the file containing the data to export. maxsize : a float or a string "auto" (optional). The maximum size of the mesh elements allowed. "auto" corresponds to an automatic determination based on pores and throats sizes. Any float value will be used as a maximum size. Small values result in finner meshes, but slower mesh calculations. fileformat : str (optional). Default is "STL Format" which corresponds to STL format. Other formats such as Gmsh and Fluent are supported (see ngsolve.org). logger_level : integer between 0 and 7 (optional). Default is 0. The logger level set in netgen package. Notes ----- The STL Format is a Standard Triangle (or Tessellation) Language supported by many CAD packages and used for 3D printing. Export to this format may be slow since a 3D closed surface mesh is built. Requires installation of "netgen". """ try: import netgen.csg as csg except ModuleNotFoundError: raise Exception('Module "netgen" not found.') try: from netgen.meshing import SetMessageImportance as log log(logger_level) except ModuleNotFoundError: logger.warning('Module "netgen.meshing" not found.' + ' The "logger_level" will be ignored.') # Temporarily add endpoints to network so STL class works network["throat.endpoints.head"] = network.coords[network.conns[:, 0]] network["throat.endpoints.tail"] = network.coords[network.conns[:, 1]] filename = network.name if filename is None else filename path = _parse_filename(filename=filename, ext='stl') # Path is a pathlib object, so slice it up as needed fname_stl = path.name # Correct connections where 'pore.diameter' = 'throat.diameter' dt = network['throat.diameter'].copy() dp = network['pore.diameter'][network['throat.conns']] dt[dp[:, 0] == dt] *= 0.99 dt[dp[:, 1] == dt] *= 0.99 scale = max(network['pore.diameter'].max(), dt.max(), network['throat.length'].max()) if maxsize == 'auto': maxsize = min(network['pore.diameter'].min(), dt.min(), network['throat.length'].min()) geo = csg.CSGeometry() # Define pores geometry = csg.Sphere(csg.Pnt(network['pore.coords'][0, 0]/scale, network['pore.coords'][0, 1]/scale, network['pore.coords'][0, 2]/scale), network['pore.diameter'][0]/scale/2) for p in range(1, network.Np): pore = csg.Sphere(csg.Pnt(network['pore.coords'][p, 0]/scale, network['pore.coords'][p, 1]/scale, network['pore.coords'][p, 2]/scale), network['pore.diameter'][p]/scale/2) geometry += pore # Define throats for t in range(network.Nt): A = network['throat.endpoints.tail'][t, :]/scale B = network['throat.endpoints.head'][t, :]/scale V = (B-A)/_np.linalg.norm(B-A) plane1 = csg.Plane(csg.Pnt(A[0], A[1], A[2]), csg.Vec(-V[0], -V[1], -V[2])) plane2 = csg.Plane(csg.Pnt(B[0], B[1], B[2]), csg.Vec(V[0], V[1], V[2])) cylinder = csg.Cylinder(csg.Pnt(A[0], A[1], A[2]), csg.Pnt(B[0], B[1], B[2]), dt[t]/scale/2) throat = cylinder * plane1 * plane2 geometry += throat # Add pore and throats to geometry, build mesh, rescale, and export geo.Add(geometry) mesh = geo.GenerateMesh(maxh=maxsize/scale) mesh.Scale(scale) mesh.Export(filename=fname_stl, format=fileformat) # Remove endpoints label from network del network["throat.endpoints"]
Saves (transient/steady-state) data from the given objects into the specified file. Parameters ---------- network : Network. The network containing the desired data. phases : list[Phase] (place holder, default is None). List of phases containing the desired data. filename : str (optional). The name of the file containing the data to export. maxsize : a float or a string "auto" (optional). The maximum size of the mesh elements allowed. "auto" corresponds to an automatic determination based on pores and throats sizes. Any float value will be used as a maximum size. Small values result in finner meshes, but slower mesh calculations. fileformat : str (optional). Default is "STL Format" which corresponds to STL format. Other formats such as Gmsh and Fluent are supported (see ngsolve.org). logger_level : integer between 0 and 7 (optional). Default is 0. The logger level set in netgen package. Notes ----- The STL Format is a Standard Triangle (or Tessellation) Language supported by many CAD packages and used for 3D printing. Export to this format may be slow since a 3D closed surface mesh is built. Requires installation of "netgen".
network_to_stl
python
PMEAL/OpenPNM
openpnm/io/_stl.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/io/_stl.py
MIT
def project_to_vtk(project, filename="", fill_nans=None, fill_infs=None): r""" Save network and phase data to a single vtp file for visualizing in Paraview. Parameters ---------- network : Network The Network containing the data to be written phases : list, optional A list containing Phase(s) containing data to be written filename : str, optional Filename to write data. If no name is given the file is named after the network 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. fill_infs : scalar The value to use to replace infs with. The default is ``None`` which means that property arrays containing ``None`` will *not* be written to the file, and a warning will be issued. A useful value is """ network = project.network algs = project.algorithms # Check if any of the phases has time series transient = is_transient(algs) if transient: logger.warning( "vtp format does not support transient data, " + "use xdmf instead" ) if filename == "": filename = project.name filename = _parse_filename(filename=filename, ext="vtp") am = project_to_dict(project=project, categorize_by=["object", "data"]) am = pd.json_normalize(am, sep='.').to_dict(orient='records')[0] for k in list(am.keys()): am[k.replace('.', ' | ')] = am.pop(k) key_list = list(sorted(am.keys())) points = network["pore.coords"] pairs = network["throat.conns"] num_points = np.shape(points)[0] num_throats = np.shape(pairs)[0] root = ET.fromstring(_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 = _array_to_element("coords", points.T.ravel("F"), n=3) points_node.append(coords) lines_node = piece_node.find("Lines") connectivity = _array_to_element("connectivity", pairs) lines_node.append(connectivity) offsets = _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 == 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 if np.any(np.isinf(array)): if fill_infs is None: logger.warning(key + " has infs," + " will not write to file") continue else: array[np.isinf(array)] = fill_infs element = _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) 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)
Save network and phase data to a single vtp file for visualizing in Paraview. Parameters ---------- network : Network The Network containing the data to be written phases : list, optional A list containing Phase(s) containing data to be written filename : str, optional Filename to write data. If no name is given the file is named after the network 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. fill_infs : scalar The value to use to replace infs with. The default is ``None`` which means that property arrays containing ``None`` will *not* be written to the file, and a warning will be issued. A useful value is
project_to_vtk
python
PMEAL/OpenPNM
openpnm/io/_vtk.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/io/_vtk.py
MIT
def project_to_xdmf(project, filename=''): r""" Saves (transient/steady-state) data from the given objects into the specified file. Parameters ---------- network : Network The network containing the desired data phases : list[Phase] (optional, default is None) A list of phase objects whose data are to be included Notes ----- This method only saves the data, not any of the pore-scale models or other attributes. """ import h5py network = project.network algs = project.algorithms # Check if any of the phases has time series transient = is_transient(algs) if filename == '': filename = project.name path = _parse_filename(filename=filename, ext='xmf') # Path is a pathlib object, so slice it up as needed fname_xdf = path.name d = project_to_dict(project=project, flatten=False, categorize_by=['element', 'data']) D = pd.json_normalize(d, sep='.').to_dict(orient='records')[0] for k in list(D.keys()): D[k.replace('.', '/')] = D.pop(k) # Identify time steps t_steps = [] if transient: for key in D.keys(): if '#' in key: t_steps.append(key.split('#')[1]) t_steps = list(set(t_steps)) t_grid = create_grid(Name="TimeSeries", GridType="Collection", CollectionType="Temporal") # If steady-state, define '0' time step if not transient: t_steps.append('0') # Setup xdmf file root = create_root('Xdmf') domain = create_domain() # Iterate over time steps present for i, t_step in enumerate(t_steps): # Define the hdf file if not transient: fname_hdf = path.stem+".hdf" else: fname_hdf = path.stem+'#'+t_step+".hdf" path_p = path.parent f = h5py.File(path_p.joinpath(fname_hdf), "w") # Add coordinate and connection information to top of HDF5 file f["coordinates"] = network["pore.coords"] f["connections"] = network["throat.conns"] # geometry coordinates row, col = f["coordinates"].shape dims = ' '.join((str(row), str(col))) hdf_loc = fname_hdf + ":coordinates" geo_data = create_data_item(value=hdf_loc, Dimensions=dims, Format='HDF', DataType="Float") geo = create_geometry(GeometryType="XYZ") geo.append(geo_data) # topolgy connections row, col = f["connections"].shape # col first then row dims = ' '.join((str(row), str(col))) hdf_loc = fname_hdf + ":connections" topo_data = create_data_item(value=hdf_loc, Dimensions=dims, Format="HDF", NumberType="Int") topo = create_topology(TopologyType="Polyline", NodesPerElement=str(2), NumberOfElements=str(row)) topo.append(topo_data) # Make HDF5 file with all datasets, and no groups for item in list(D.keys()): if D[item].dtype == 'O': logger.warning(item + ' has dtype object,' + ' will not write to file') del D[item] elif 'U' in str(D[item][0].dtype): pass elif ('#' in item and t_step == item.split('#')[1]): f.create_dataset(name='/'+item.split('#')[0]+'#t', shape=D[item].shape, dtype=D[item].dtype, data=D[item], compression="gzip") elif ('#' not in item and i == 0): f.create_dataset(name='/'+item, shape=D[item].shape, dtype=D[item].dtype, data=D[item], compression="gzip") # Create a grid grid = create_grid(Name=t_step, GridType="Uniform") time = create_time(mode='Single', Value=t_step) grid.append(time) # Add pore and throat properties for item in list(D.keys()): if item not in ['coordinates', 'connections']: if ("#" in item and t_step == item.split("#")[1]) or ( "#" not in item ): attr_type = 'Scalar' shape = D[item].shape dims = (' '.join([str(i) for i in shape])) if '#' in item: item = item.split('#')[0]+'#t' hdf_loc = fname_hdf + ":" + item elif ('#' not in item and i == 0): hdf_loc = fname_hdf + ":" + item elif ('#' not in item and i > 0): hdf_loc = path.stem + '#' + t_steps[0] + ".hdf" + ":" + item attr = create_data_item(value=hdf_loc, Dimensions=dims, Format='HDF', Precision='8', DataType='Float') name = item.replace('/', ' | ') if 'throat' in item: Center = "Cell" else: Center = "Node" el_attr = create_attribute(Name=name, Center=Center, AttributeType=attr_type) el_attr.append(attr) grid.append(el_attr) else: pass grid.append(topo) grid.append(geo) t_grid.append(grid) # CLose the HDF5 file f.close() domain.append(t_grid) root.append(domain) with open(path_p.joinpath(fname_xdf), 'w') as file: file.write(_header) file.write(ET.tostring(root).decode("utf-8"))
Saves (transient/steady-state) data from the given objects into the specified file. Parameters ---------- network : Network The network containing the desired data phases : list[Phase] (optional, default is None) A list of phase objects whose data are to be included Notes ----- This method only saves the data, not any of the pore-scale models or other attributes.
project_to_xdmf
python
PMEAL/OpenPNM
openpnm/io/_xdmf.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/io/_xdmf.py
MIT
def spheres_and_cylinders( network, pore_diameter="pore.diameter", throat_diameter="throat.diameter", ): r""" Calculates conduit lengths in the network assuming pores are spheres and throats are cylinders. A conduit is defined as ( 1/2 pore - full throat - 1/2 pore ). Parameters ---------- %(network)s %(Dp)s %(Dt)s Returns ------- lengths : ndarray Array (Nt by 3) containing conduit values for each element of the pore-throat-pore conduits. The array is formatted as ``[pore1, throat, pore2]``. """ L_ctc = _get_L_ctc(network) D1, Dt, D2 = network.get_conduit_data(pore_diameter.split(".", 1)[-1]).T # Handle the case where Dt > Dp if (Dt > D1).any() or (Dt > D2).any(): _raise_incompatible_data() # If spheres do not overlap: L1 = np.sqrt(D1**2 - Dt**2) / 2 L2 = np.sqrt(D2**2 - Dt**2) / 2 Lt = L_ctc - (L1 + L2) if np.any(Lt < 0): # Find pores that touch/overlap # Find diameter of overlap between spheres d = L_ctc R1 = D1/2 R2 = D2/2 # Check distance to the intersection L1_int = (d**2 - R2**2 + R1**2) / (2*d) if np.any(L1_int < 0) or np.any(L1_int > L_ctc): raise Exception('The pores overlap too much') D_int = 2/(2*d) * np.sqrt(4*d**2 * R1**2 - (d**2 - R2**2 + R1**2)**2) mask = D_int > Dt if np.any(mask): d = d[mask] R1 = R1[mask] R2 = R2[mask] L1[mask] = (d**2 - R2**2 + R1**2) / (2*d) L2[mask] = L_ctc[mask] - L1[mask] Lt[mask] = 1e-15 return np.vstack((L1, Lt, L2)).T
Calculates conduit lengths in the network assuming pores are spheres and throats are cylinders. A conduit is defined as ( 1/2 pore - full throat - 1/2 pore ). Parameters ---------- %(network)s %(Dp)s %(Dt)s Returns ------- lengths : ndarray Array (Nt by 3) containing conduit values for each element of the pore-throat-pore conduits. The array is formatted as ``[pore1, throat, pore2]``.
spheres_and_cylinders
python
PMEAL/OpenPNM
openpnm/models/geometry/conduit_lengths/_funcs.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/conduit_lengths/_funcs.py
MIT
def circles_and_rectangles( network, pore_diameter="pore.diameter", throat_diameter="throat.diameter" ): r""" Calculates conduit lengths in the network assuming pores are circles and throats are rectangles. A conduit is defined as ( 1/2 pore - full throat - 1/2 pore ). Parameters ---------- %(network)s %(Dp)s %(Dt)s Returns ------- Notes ----- This model should only be used for true 2D networks, i.e. with planar symmetry. """ return spheres_and_cylinders( network=network, pore_diameter=pore_diameter, throat_diameter=throat_diameter, )
Calculates conduit lengths in the network assuming pores are circles and throats are rectangles. A conduit is defined as ( 1/2 pore - full throat - 1/2 pore ). Parameters ---------- %(network)s %(Dp)s %(Dt)s Returns ------- Notes ----- This model should only be used for true 2D networks, i.e. with planar symmetry.
circles_and_rectangles
python
PMEAL/OpenPNM
openpnm/models/geometry/conduit_lengths/_funcs.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/conduit_lengths/_funcs.py
MIT
def cones_and_cylinders( network, pore_diameter="pore.diameter", throat_diameter="throat.diameter" ): r""" Calculates conduit lengths in the network assuming pores are cones and throats are cylinders. A conduit is defined as ( 1/2 pore - full throat - 1/2 pore ). Parameters ---------- %(network)s %(Dp)s %(Dt)s Returns ------- """ L_ctc = _get_L_ctc(network) D1, Dt, D2 = network.get_conduit_data(pore_diameter.split(".", 1)[-1]).T L1 = D1 / 2 L2 = D2 / 2 # Handle throats w/ overlapping pores _L1 = (4 * L_ctc**2 + D1**2 - D2**2) / (8 * L_ctc) mask = L_ctc - 0.5 * (D1 + D2) < 0 L1[mask] = _L1[mask] L2[mask] = (L_ctc - L1)[mask] Lt = np.maximum(L_ctc - (L1 + L2), 1e-15) return np.vstack((L1, Lt, L2)).T
Calculates conduit lengths in the network assuming pores are cones and throats are cylinders. A conduit is defined as ( 1/2 pore - full throat - 1/2 pore ). Parameters ---------- %(network)s %(Dp)s %(Dt)s Returns -------
cones_and_cylinders
python
PMEAL/OpenPNM
openpnm/models/geometry/conduit_lengths/_funcs.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/conduit_lengths/_funcs.py
MIT
def intersecting_cones(network, pore_coords="pore.coords", throat_coords="throat.coords"): r""" Calculates conduit lengths in the network assuming pores are cones that intersect. Therefore, the throat is the cross sectional plane where two pores meet and has negligible/zero volume. A conduit is defined as ( 1/2 pore - 1/2 pore ). Parameters ---------- %(network)s %(Pcoords)s %(Tcoords)s Returns ------- """ P12 = network["throat.conns"] p_coords = network[pore_coords] t_coords = network[throat_coords] L1 = np.sqrt(np.sum(((p_coords[P12[:, 0]] - t_coords)) ** 2, axis=1)) L2 = np.sqrt(np.sum(((p_coords[P12[:, 1]] - t_coords)) ** 2, axis=1)) Lt = np.zeros(len(network.Ts)) return np.vstack((L1, Lt, L2)).T
Calculates conduit lengths in the network assuming pores are cones that intersect. Therefore, the throat is the cross sectional plane where two pores meet and has negligible/zero volume. A conduit is defined as ( 1/2 pore - 1/2 pore ). Parameters ---------- %(network)s %(Pcoords)s %(Tcoords)s Returns -------
intersecting_cones
python
PMEAL/OpenPNM
openpnm/models/geometry/conduit_lengths/_funcs.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/conduit_lengths/_funcs.py
MIT
def hybrid_cones_and_cylinders( network, pore_diameter="pore.diameter", throat_coords="throat.coords" ): r""" Calculates conduit lengths in the network assuming pores are cones and throats are cylinders. A conduit is defined as ( 1/2 pore - full throat - 1/2 pore ). Parameters ---------- %(network)s %(Dp)s %(Tcoords)s Returns ------- """ L_ctc = _get_L_ctc(network) D1, Dt, D2 = network.get_conduit_data(pore_diameter.split(".", 1)[-1]).T L1 = D1 / 2 L2 = D2 / 2 Lt = np.maximum(L_ctc - (L1 + L2), 1e-15) # Handle intersecting pores XYp = network.coords[network.conns] XYt = network[throat_coords] _L1, _L2 = np.linalg.norm(XYp - XYt[:, None], axis=2).T mask1 = _L1 < L1 mask2 = _L2 < L2 mask = np.logical_or(mask1, mask2) if mask.any(): L1[mask] = _L1[mask] L2[mask] = _L2[mask] Lt[mask] = 0.0 return np.vstack((L1, Lt, L2)).T
Calculates conduit lengths in the network assuming pores are cones and throats are cylinders. A conduit is defined as ( 1/2 pore - full throat - 1/2 pore ). Parameters ---------- %(network)s %(Dp)s %(Tcoords)s Returns -------
hybrid_cones_and_cylinders
python
PMEAL/OpenPNM
openpnm/models/geometry/conduit_lengths/_funcs.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/conduit_lengths/_funcs.py
MIT
def trapezoids_and_rectangles( network, pore_diameter="pore.diameter", throat_diameter="throat.diameter" ): r""" Calculates conduit lengths in the network assuming pores are trapezoids and throats are rectangles. Parameters ---------- %(network)s %(Dp)s %(Dt)s Returns ------- Notes ----- This model should only be used for true 2D networks, i.e. with planar symmetry. """ return cones_and_cylinders( network=network, pore_diameter=pore_diameter, throat_diameter=throat_diameter, )
Calculates conduit lengths in the network assuming pores are trapezoids and throats are rectangles. Parameters ---------- %(network)s %(Dp)s %(Dt)s Returns ------- Notes ----- This model should only be used for true 2D networks, i.e. with planar symmetry.
trapezoids_and_rectangles
python
PMEAL/OpenPNM
openpnm/models/geometry/conduit_lengths/_funcs.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/conduit_lengths/_funcs.py
MIT
def intersecting_trapezoids( network, pore_coords="pore.coords", throat_coords="throat.coords" ): r""" Calculates conduit lengths in the network assuming pores are intersecting trapezoids. Parameters ---------- %(network)s %(Pcoords)s %(Tcoords)s Returns ------- Notes ----- This model should only be used for true 2D networks, i.e. with planar symmetry. """ return intersecting_cones( network=network, pore_coords=pore_coords, throat_coords=throat_coords, )
Calculates conduit lengths in the network assuming pores are intersecting trapezoids. Parameters ---------- %(network)s %(Pcoords)s %(Tcoords)s Returns ------- Notes ----- This model should only be used for true 2D networks, i.e. with planar symmetry.
intersecting_trapezoids
python
PMEAL/OpenPNM
openpnm/models/geometry/conduit_lengths/_funcs.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/conduit_lengths/_funcs.py
MIT
def hybrid_trapezoids_and_rectangles( network, pore_diameter="pore.diameter", throat_coords="throat.coords" ): r""" Calculates conduit lengths in the network assuming pores are trapezoids and throats are rectangles. Parameters ---------- %(network)s %(Dp)s %(Tcoords)s Returns ------- Notes ----- This model should only be used for true 2D networks, i.e. with planar symmetry. """ return hybrid_cones_and_cylinders( network=network, pore_diameter=pore_diameter, throat_coords=throat_coords, )
Calculates conduit lengths in the network assuming pores are trapezoids and throats are rectangles. Parameters ---------- %(network)s %(Dp)s %(Tcoords)s Returns ------- Notes ----- This model should only be used for true 2D networks, i.e. with planar symmetry.
hybrid_trapezoids_and_rectangles
python
PMEAL/OpenPNM
openpnm/models/geometry/conduit_lengths/_funcs.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/conduit_lengths/_funcs.py
MIT
def pyramids_and_cuboids( network, pore_diameter="pore.diameter", throat_diameter="throat.diameter" ): r""" Calculates conduit lengths in the network assuming pores are truncated pyramids and throats are cuboids. Parameters ---------- %(network)s %(Dp)s %(Dt)s Returns ------- """ return cones_and_cylinders( network=network, pore_diameter=pore_diameter, throat_diameter=throat_diameter, )
Calculates conduit lengths in the network assuming pores are truncated pyramids and throats are cuboids. Parameters ---------- %(network)s %(Dp)s %(Dt)s Returns -------
pyramids_and_cuboids
python
PMEAL/OpenPNM
openpnm/models/geometry/conduit_lengths/_funcs.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/conduit_lengths/_funcs.py
MIT
def intersecting_pyramids( network, pore_coords="pore.coords", throat_coords="throat.coords" ): r""" Calculates conduit lengths in the network assuming pores are intersecting pyramids. Parameters ---------- %(network)s %(Pcoords)s %(Tcoords)s Returns ------- """ return intersecting_cones( network=network, pore_coords=pore_coords, throat_coords=throat_coords, )
Calculates conduit lengths in the network assuming pores are intersecting pyramids. Parameters ---------- %(network)s %(Pcoords)s %(Tcoords)s Returns -------
intersecting_pyramids
python
PMEAL/OpenPNM
openpnm/models/geometry/conduit_lengths/_funcs.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/conduit_lengths/_funcs.py
MIT
def hybrid_pyramids_and_cuboids( network, pore_diameter="pore.diameter", throat_coords="throat.coords" ): r""" Calculates conduit lengths in the network assuming pores are truncated pyramids that intersect. Therefore, the throat is the cross sectional plane where two pores meet and has negligible/zero volume. Parameters ---------- %(network)s %(Dp)s %(Tcoords)s Returns ------- """ return hybrid_cones_and_cylinders( network=network, pore_diameter=pore_diameter, throat_coords=throat_coords, )
Calculates conduit lengths in the network assuming pores are truncated pyramids that intersect. Therefore, the throat is the cross sectional plane where two pores meet and has negligible/zero volume. Parameters ---------- %(network)s %(Dp)s %(Tcoords)s Returns -------
hybrid_pyramids_and_cuboids
python
PMEAL/OpenPNM
openpnm/models/geometry/conduit_lengths/_funcs.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/conduit_lengths/_funcs.py
MIT
def cubes_and_cuboids( network, pore_diameter="pore.diameter", throat_diameter="throat.diameter" ): r""" Calculates conduit lengths in the network assuming pores are cubes and throats are cuboids. Parameters ---------- %(network)s %(Dp)s %(Dt)s Returns ------- """ L_ctc = _get_L_ctc(network) D1, Dt, D2 = network.get_conduit_data(pore_diameter.split(".", 1)[-1]).T L1 = D1 / 2 L2 = D2 / 2 Lt = L_ctc - (L1 + L2) # Handle overlapping pores mask = (Lt < 0) & (L1 > L2) L2[mask] = (L_ctc - L1)[mask] mask = (Lt < 0) & (L2 > L1) L1[mask] = (L_ctc - L2)[mask] Lt = np.maximum(Lt, 1e-15) return np.vstack((L1, Lt, L2)).T
Calculates conduit lengths in the network assuming pores are cubes and throats are cuboids. Parameters ---------- %(network)s %(Dp)s %(Dt)s Returns -------
cubes_and_cuboids
python
PMEAL/OpenPNM
openpnm/models/geometry/conduit_lengths/_funcs.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/conduit_lengths/_funcs.py
MIT
def squares_and_rectangles( network, pore_diameter="pore.diameter", throat_diameter="throat.diameter" ): r""" Calculates conduit lengths in the network assuming pores are squares and throats are rectangles. Parameters ---------- %(network)s %(Dp)s %(Dt)s Returns ------- Notes ----- This model should only be used for true 2D networks, i.e. with planar symmetry. """ return cubes_and_cuboids( network=network, pore_diameter=pore_diameter, throat_diameter=throat_diameter, )
Calculates conduit lengths in the network assuming pores are squares and throats are rectangles. Parameters ---------- %(network)s %(Dp)s %(Dt)s Returns ------- Notes ----- This model should only be used for true 2D networks, i.e. with planar symmetry.
squares_and_rectangles
python
PMEAL/OpenPNM
openpnm/models/geometry/conduit_lengths/_funcs.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/conduit_lengths/_funcs.py
MIT
def _get_L_ctc(network): """Returns throat spacing if it exists, otherwise calculates it.""" try: L_ctc = network["throat.spacing"] except KeyError: P12 = network["throat.conns"] C1 = network["pore.coords"][P12[:, 0]] C2 = network["pore.coords"][P12[:, 1]] L_ctc = np.linalg.norm(C1 - C2, axis=1) return L_ctc
Returns throat spacing if it exists, otherwise calculates it.
_get_L_ctc
python
PMEAL/OpenPNM
openpnm/models/geometry/conduit_lengths/_funcs.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/conduit_lengths/_funcs.py
MIT
def spheres_and_cylinders( network, pore_diameter="pore.diameter", throat_diameter="throat.diameter", ): r""" Computes diffusive shape coefficient for conduits assuming pores are spheres and throats are cylinders. Parameters ---------- %(network)s %(Dp)s %(Dt)s Returns ------- size_factors : ndarray Array (Nt by 3) containing conduit values for each element of the pore-throat-pore conduits. The array is formatted as ``[pore1, throat, pore2]``. Notes ----- The diffusive size factor is the geometrical part of the pre-factor in Fick's law: .. math:: n_A = \frac{A}{L} \Delta C_A = S_{diffusive} D_{AB} \Delta C_A Thus :math:`S_{diffusive}` represents the combined effect of the area and length of the *conduit*, which consists of a throat and 1/2 of the pore on each end. """ D1, Dt, D2 = network.get_conduit_data(pore_diameter.split('.', 1)[1]).T L1, Lt, L2 = _conduit_lengths.spheres_and_cylinders( network, pore_diameter=pore_diameter, throat_diameter=throat_diameter ).T # Fi is the integral of (1/A) dx, x = [0, Li] F1 = 2 / (D1 * _np.pi) * _np.arctanh(2 * L1 / D1) F2 = 2 / (D2 * _np.pi) * _np.arctanh(2 * L2 / D2) Ft = Lt / (_np.pi / 4 * Dt ** 2) vals = _np.vstack([1/F1, 1/Ft, 1/F2]).T return vals
Computes diffusive shape coefficient for conduits assuming pores are spheres and throats are cylinders. Parameters ---------- %(network)s %(Dp)s %(Dt)s Returns ------- size_factors : ndarray Array (Nt by 3) containing conduit values for each element of the pore-throat-pore conduits. The array is formatted as ``[pore1, throat, pore2]``. Notes ----- The diffusive size factor is the geometrical part of the pre-factor in Fick's law: .. math:: n_A = \frac{A}{L} \Delta C_A = S_{diffusive} D_{AB} \Delta C_A Thus :math:`S_{diffusive}` represents the combined effect of the area and length of the *conduit*, which consists of a throat and 1/2 of the pore on each end.
spheres_and_cylinders
python
PMEAL/OpenPNM
openpnm/models/geometry/diffusive_size_factors/_funcs.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/diffusive_size_factors/_funcs.py
MIT
def circles_and_rectangles( network, pore_diameter="pore.diameter", throat_diameter="throat.diameter", ): r""" Computes diffusive shape coefficient for conduits assuming pores are circles and throats are rectangles Parameters ---------- %(network)s %(Dp)s %(Dt)s Returns ------- Notes ----- This model should only be used for true 2D networks, i.e. with planar symmetry. """ D1, Dt, D2 = network.get_conduit_data(pore_diameter.split('.', 1)[1]).T L1, Lt, L2 = _conduit_lengths.circles_and_rectangles( network, pore_diameter=pore_diameter, throat_diameter=throat_diameter ).T # Fi is the integral of (1/A) dx, x = [0, Li] F1 = 0.5 * _np.arcsin(2 * L1 / D1) F2 = 0.5 * _np.arcsin(2 * L2 / D2) Ft = Lt / Dt vals = _np.vstack([1/F1, 1/Ft, 1/F2]).T return vals
Computes diffusive shape coefficient for conduits assuming pores are circles and throats are rectangles Parameters ---------- %(network)s %(Dp)s %(Dt)s Returns ------- Notes ----- This model should only be used for true 2D networks, i.e. with planar symmetry.
circles_and_rectangles
python
PMEAL/OpenPNM
openpnm/models/geometry/diffusive_size_factors/_funcs.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/diffusive_size_factors/_funcs.py
MIT
def cones_and_cylinders( network, pore_diameter="pore.diameter", throat_diameter="throat.diameter", ): r""" Computes diffusive shape coefficient assuming pores are truncated cones and throats are cylinders. Parameters ---------- %(network)s %(Dp)s %(Dt)s Returns ------- Notes ----- This model should only be used for true 2D networks, i.e. with planar symmetry. """ D1, Dt, D2 = network.get_conduit_data(pore_diameter.split('.', 1)[1]).T L1, Lt, L2 = _conduit_lengths.cones_and_cylinders( network, pore_diameter=pore_diameter, throat_diameter=throat_diameter ).T # Fi is the integral of (1/A) dx, x = [0, Li] F1 = 4 * L1 / (D1 * Dt * _np.pi) F2 = 4 * L2 / (D2 * Dt * _np.pi) Ft = Lt / (_np.pi * Dt**2 / 4) vals = _np.vstack([1/F1, 1/Ft, 1/F2]).T return vals
Computes diffusive shape coefficient assuming pores are truncated cones and throats are cylinders. Parameters ---------- %(network)s %(Dp)s %(Dt)s Returns ------- Notes ----- This model should only be used for true 2D networks, i.e. with planar symmetry.
cones_and_cylinders
python
PMEAL/OpenPNM
openpnm/models/geometry/diffusive_size_factors/_funcs.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/diffusive_size_factors/_funcs.py
MIT
def intersecting_cones( network, pore_diameter="pore.diameter", throat_coords="throat.coords" ): r""" Computes diffusive shape coefficient assuming pores are intersecting cones. Parameters ---------- %(network)s %(Dp)s %(Tcoords)s Returns ------- Notes ----- This model should only be used for true 2D networks, i.e. with planar symmetry. """ D1, Dt, D2 = network.get_conduit_data(pore_diameter.split('.', 1)[1]).T L1, Lt, L2 = _conduit_lengths.intersecting_cones( network, throat_coords=throat_coords ).T # Fi is the integral of (1/A) dx, x = [0, Li] F1 = 4 * L1 / (D1 * Dt * _np.pi) F2 = 4 * L2 / (D2 * Dt * _np.pi) inv_F_t = _np.full(len(Lt), _np.inf) vals = _np.vstack([1/F1, inv_F_t, 1/F2]).T return vals
Computes diffusive shape coefficient assuming pores are intersecting cones. Parameters ---------- %(network)s %(Dp)s %(Tcoords)s Returns ------- Notes ----- This model should only be used for true 2D networks, i.e. with planar symmetry.
intersecting_cones
python
PMEAL/OpenPNM
openpnm/models/geometry/diffusive_size_factors/_funcs.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/diffusive_size_factors/_funcs.py
MIT
def hybrid_cones_and_cylinders( network, pore_diameter="pore.diameter", throat_coords="throat.coords" ): r""" Computes diffusive shape coefficient assuming pores are truncated cones and throats are cylinders. Parameters ---------- %(network)s %(Dp)s %(Tcoords)s Returns ------- Notes ----- This model should only be used for true 2D networks, i.e. with planar symmetry. """ D1, Dt, D2 = network.get_conduit_data(pore_diameter.split('.', 1)[1]).T L1, Lt, L2 = _conduit_lengths.hybrid_cones_and_cylinders( network, pore_diameter=pore_diameter, throat_coords=throat_coords ).T # Fi is the integral of (1/A) dx, x = [0, Li] F1 = 4 * L1 / (D1 * Dt * _np.pi) F2 = 4 * L2 / (D2 * Dt * _np.pi) Ft = Lt / (_np.pi * Dt**2 / 4) mask = Lt == 0.0 if mask.any(): inv_F_t = _np.zeros(len(Ft)) inv_F_t[~mask] = 1/Ft[~mask] inv_F_t[mask] = _np.inf else: inv_F_t = 1/Ft vals = _np.vstack([1/F1, inv_F_t, 1/F2]).T return vals
Computes diffusive shape coefficient assuming pores are truncated cones and throats are cylinders. Parameters ---------- %(network)s %(Dp)s %(Tcoords)s Returns ------- Notes ----- This model should only be used for true 2D networks, i.e. with planar symmetry.
hybrid_cones_and_cylinders
python
PMEAL/OpenPNM
openpnm/models/geometry/diffusive_size_factors/_funcs.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/diffusive_size_factors/_funcs.py
MIT
def trapezoids_and_rectangles( network, pore_diameter="pore.diameter", throat_diameter="throat.diameter", ): r""" Compute diffusive shape coefficient for conduits assuming pores are trapezoids and throats are rectangles. Parameters ---------- %(network)s %(Dp)s %(Dt)s Returns ------- Notes ----- This model should only be used for true 2D networks, i.e. with planar symmetry. """ D1, Dt, D2 = network.get_conduit_data(pore_diameter.split('.', 1)[-1]).T L1, Lt, L2 = _conduit_lengths.trapezoids_and_rectangles( network, pore_diameter=pore_diameter, throat_diameter=throat_diameter ).T # Fi is the integral of (1/A) dx, x = [0, Li] F1 = L1 * _np.log(Dt / D1) / (Dt - D1) F2 = L2 * _np.log(Dt / D2) / (Dt - D2) Ft = Lt / Dt # Edge case where Di = Dt mask = _np.isclose(D1, Dt) F1[mask] = (L1 / D1)[mask] mask = _np.isclose(D2, Dt) F2[mask] = (L2 / D2)[mask] vals = _np.vstack([1/F1, 1/Ft, 1/F2]).T return vals
Compute diffusive shape coefficient for conduits assuming pores are trapezoids and throats are rectangles. Parameters ---------- %(network)s %(Dp)s %(Dt)s Returns ------- Notes ----- This model should only be used for true 2D networks, i.e. with planar symmetry.
trapezoids_and_rectangles
python
PMEAL/OpenPNM
openpnm/models/geometry/diffusive_size_factors/_funcs.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/diffusive_size_factors/_funcs.py
MIT
def intersecting_trapezoids( network, pore_diameter="pore.diameter", throat_coords="throat.coords" ): r""" Computes diffusive shape coefficient for conduits of intersecting trapezoids. Parameters ---------- %(network)s %(Dp)s %(Tcoords)s Returns ------- Notes ----- This model should only be used for true 2D networks, i.e. with planar symmetry. """ D1, Dt, D2 = network.get_conduit_data(pore_diameter.split('.', 1)[-1]).T L1, Lt, L2 = _conduit_lengths.intersecting_trapezoids( network, throat_coords=throat_coords ).T # Fi is the integral of (1/A) dx, x = [0, Li] F1 = L1 * _np.log(Dt / D1) / (Dt - D1) F2 = L2 * _np.log(Dt / D2) / (Dt - D2) # Edge case where Di = Dt mask = _np.isclose(D1, Dt) F1[mask] = (L1 / D1)[mask] mask = _np.isclose(D2, Dt) F2[mask] = (L2 / D2)[mask] inv_F_t = _np.full(len(Lt), _np.inf) vals = _np.vstack([1/F1, inv_F_t, 1/F2]).T return vals
Computes diffusive shape coefficient for conduits of intersecting trapezoids. Parameters ---------- %(network)s %(Dp)s %(Tcoords)s Returns ------- Notes ----- This model should only be used for true 2D networks, i.e. with planar symmetry.
intersecting_trapezoids
python
PMEAL/OpenPNM
openpnm/models/geometry/diffusive_size_factors/_funcs.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/diffusive_size_factors/_funcs.py
MIT
def hybrid_trapezoids_and_rectangles( network, pore_diameter="pore.diameter", throat_coords="throat.coords" ): r""" Compute diffusive shape coefficient for conduits assuming pores are trapezoids and throats are rectangles. Parameters ---------- %(network)s %(Dp)s %(Tcoords)s Returns ------- Notes ----- This model should only be used for true 2D networks, i.e. with planar symmetry. """ D1, Dt, D2 = network.get_conduit_data(pore_diameter.split('.', 1)[-1]).T L1, Lt, L2 = _conduit_lengths.hybrid_trapezoids_and_rectangles( network, pore_diameter=pore_diameter, throat_coords=throat_coords ).T # Fi is the integral of (1/A) dx, x = [0, Li] F1 = L1 * _np.log(Dt / D1) / (Dt - D1) F2 = L2 * _np.log(Dt / D2) / (Dt - D2) Ft = Lt / Dt # Edge case where Di = Dt mask = _np.isclose(D1, Dt) F1[mask] = (L1 / D1)[mask] mask = _np.isclose(D2, Dt) F2[mask] = (L2 / D2)[mask] mask = Lt == 0.0 if mask.any(): inv_F_t = _np.zeros(len(Ft)) inv_F_t[~mask] = 1/Ft[~mask] inv_F_t[mask] = _np.inf else: inv_F_t = 1/Ft vals = _np.vstack([1/F1, inv_F_t, 1/F2]).T return vals
Compute diffusive shape coefficient for conduits assuming pores are trapezoids and throats are rectangles. Parameters ---------- %(network)s %(Dp)s %(Tcoords)s Returns ------- Notes ----- This model should only be used for true 2D networks, i.e. with planar symmetry.
hybrid_trapezoids_and_rectangles
python
PMEAL/OpenPNM
openpnm/models/geometry/diffusive_size_factors/_funcs.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/diffusive_size_factors/_funcs.py
MIT
def pyramids_and_cuboids( network, pore_diameter="pore.diameter", throat_diameter="throat.diameter", ): r""" Computes diffusive size factor for conduits of truncated pyramids and cuboids. Parameters ---------- %(network)s %(Dp)s %(Dt)s Returns ------- Notes ----- This model should only be used for true 2D networks, i.e. with planar symmetry. """ D1, Dt, D2 = network.get_conduit_data(pore_diameter.split('.', 1)[-1]).T L1, Lt, L2 = _conduit_lengths.pyramids_and_cuboids( network, pore_diameter=pore_diameter, throat_diameter=throat_diameter ).T # Fi is the integral of (1/A) dx, x = [0, Li] F1 = L1 / (D1 * Dt) F2 = L2 / (D2 * Dt) Ft = Lt / Dt**2 vals = _np.vstack([1/F1, 1/Ft, 1/F2]).T return vals
Computes diffusive size factor for conduits of truncated pyramids and cuboids. Parameters ---------- %(network)s %(Dp)s %(Dt)s Returns ------- Notes ----- This model should only be used for true 2D networks, i.e. with planar symmetry.
pyramids_and_cuboids
python
PMEAL/OpenPNM
openpnm/models/geometry/diffusive_size_factors/_funcs.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/diffusive_size_factors/_funcs.py
MIT
def hybrid_pyramids_and_cuboids( network, pore_diameter="pore.diameter", throat_coords="throat.coords" ): r""" Computes diffusive size factor for conduits of truncated pyramids and cuboids. Parameters ---------- %(network)s %(Dp)s %(Tcoords)s Returns ------- Notes ----- This model should only be used for true 2D networks, i.e. with planar symmetry. """ D1, Dt, D2 = network.get_conduit_data(pore_diameter.split('.', 1)[-1]).T L1, Lt, L2 = _conduit_lengths.hybrid_pyramids_and_cuboids( network, pore_diameter=pore_diameter, throat_coords=throat_coords ).T # Fi is the integral of (1/A) dx, x = [0, Li] F1 = L1 / (D1 * Dt) F2 = L2 / (D2 * Dt) Ft = Lt / Dt**2 mask = Lt == 0.0 if mask.any(): inv_F_t = _np.zeros(len(Ft)) inv_F_t[~mask] = 1/Ft[~mask] inv_F_t[mask] = _np.inf else: inv_F_t = 1/Ft vals = _np.vstack([1/F1, inv_F_t, 1/F2]).T return vals
Computes diffusive size factor for conduits of truncated pyramids and cuboids. Parameters ---------- %(network)s %(Dp)s %(Tcoords)s Returns ------- Notes ----- This model should only be used for true 2D networks, i.e. with planar symmetry.
hybrid_pyramids_and_cuboids
python
PMEAL/OpenPNM
openpnm/models/geometry/diffusive_size_factors/_funcs.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/diffusive_size_factors/_funcs.py
MIT
def intersecting_pyramids( network, pore_diameter="pore.diameter", throat_coords="throat.coords" ): r""" Computes diffusive size factor for conduits of pores with intersecting pyramids. Parameters ---------- %(network)s %(Dp)s %(Tcoords)s Returns ------- Notes ----- This model should only be used for true 2D networks, i.e. with planar symmetry. """ D1, Dt, D2 = network.get_conduit_data(pore_diameter.split('.', 1)[-1]).T L1, Lt, L2 = _conduit_lengths.intersecting_pyramids( network, throat_coords=throat_coords ).T # Fi is the integral of (1/A) dx, x = [0, Li] F1 = L1 / (D1 * Dt) F2 = L2 / (D2 * Dt) inv_F_t = _np.full(len(Lt), _np.inf) vals = _np.vstack([1/F1, inv_F_t, 1/F2]).T return vals
Computes diffusive size factor for conduits of pores with intersecting pyramids. Parameters ---------- %(network)s %(Dp)s %(Tcoords)s Returns ------- Notes ----- This model should only be used for true 2D networks, i.e. with planar symmetry.
intersecting_pyramids
python
PMEAL/OpenPNM
openpnm/models/geometry/diffusive_size_factors/_funcs.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/diffusive_size_factors/_funcs.py
MIT
def cubes_and_cuboids( network, pore_diameter="pore.diameter", throat_diameter="throat.diameter", pore_aspect=[1, 1, 1], throat_aspect=[1, 1, 1], ): r""" Computes diffusive shape coefficient for conduits assuming pores are cubes and throats are cuboids. Parameters ---------- %(network)s %(Dp)s %(Dt)s pore_aspect : list Aspect ratio of the pores throat_aspect : list Aspect ratio of the throats Returns ------- Notes ----- This model should only be used for true 2D networks, i.e. with planar symmetry. """ D1, Dt, D2 = network.get_conduit_data(pore_diameter.split('.', 1)[-1]).T L1, Lt, L2 = _conduit_lengths.cubes_and_cuboids( network, pore_diameter=pore_diameter, throat_diameter=throat_diameter ).T # Fi is the integral of (1/A) dx, x = [0, Li] F1 = L1 / D1**2 F2 = L2 / D2**2 Ft = Lt / Dt**2 vals = _np.vstack([1/F1, 1/Ft, 1/F2]).T return vals
Computes diffusive shape coefficient for conduits assuming pores are cubes and throats are cuboids. Parameters ---------- %(network)s %(Dp)s %(Dt)s pore_aspect : list Aspect ratio of the pores throat_aspect : list Aspect ratio of the throats Returns ------- Notes ----- This model should only be used for true 2D networks, i.e. with planar symmetry.
cubes_and_cuboids
python
PMEAL/OpenPNM
openpnm/models/geometry/diffusive_size_factors/_funcs.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/diffusive_size_factors/_funcs.py
MIT
def squares_and_rectangles( network, pore_diameter="pore.diameter", throat_diameter="throat.diameter", pore_aspect=[1, 1], throat_aspect=[1, 1], ): r""" Computes diffusive size factor for conduits assuming pores are squares and throats are rectangles. Parameters ---------- %(network)s %(Dp)s %(Dt)s pore_aspect : list Aspect ratio of the pores throat_aspect : list Aspect ratio of the throats Returns ------- Notes ----- This model should only be used for true 2D networks, i.e. with planar symmetry. """ D1, Dt, D2 = network.get_conduit_data(pore_diameter.split('.', 1)[-1]).T L1, Lt, L2 = _conduit_lengths.squares_and_rectangles( network, pore_diameter=pore_diameter, throat_diameter=throat_diameter ).T # Fi is the integral of (1/A) dx, x = [0, Li] F1 = L1 / D1 F2 = L2 / D2 Ft = Lt / Dt vals = _np.vstack([1/F1, 1/Ft, 1/F2]).T return vals
Computes diffusive size factor for conduits assuming pores are squares and throats are rectangles. Parameters ---------- %(network)s %(Dp)s %(Dt)s pore_aspect : list Aspect ratio of the pores throat_aspect : list Aspect ratio of the throats Returns ------- Notes ----- This model should only be used for true 2D networks, i.e. with planar symmetry.
squares_and_rectangles
python
PMEAL/OpenPNM
openpnm/models/geometry/diffusive_size_factors/_funcs.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/diffusive_size_factors/_funcs.py
MIT
def ncylinders_in_series( network, pore_diameter="pore.diameter", throat_diameter="throat.diameter", n=5 ): r""" Computes diffusive size factors for conduits of spheres and cylinders with the spheres approximated as N cylinders in series. Parameters ---------- %(network)s %(Dp)s %(Dt)s n : int Number of cylindrical divisions for each pore and throat Returns ------- Notes ----- """ D1, Dt, D2 = network.get_conduit_data(pore_diameter.split('.', 1)[-1]).T # Ensure throats are never bigger than connected pores Dt = _np.minimum(Dt, 0.99 * _np.minimum(D1, D2)) L1, Lt, L2 = _conduit_lengths.spheres_and_cylinders( network, pore_diameter=pore_diameter, throat_diameter=throat_diameter ).T dL1 = _np.linspace(0, L1, num=n) dL2 = _np.linspace(0, L2, num=n) r1 = D1 / 2 * _np.sin(_np.arccos(dL1 / (D1 / 2))) r2 = D2 / 2 * _np.sin(_np.arccos(dL2 / (D2 / 2))) gtemp = (_np.pi * r1**2 / (L1 / n)).T F1 = 1 / _np.sum(1 / gtemp, axis=1) gtemp = (_np.pi * r2 ** 2 / (L2 / n)).T F2 = 1 / _np.sum(1 / gtemp, axis=1) Ft = (_np.pi * (Dt / 2)**2 / (Lt)).T vals = _np.vstack([F1, Ft, F2]).T return vals
Computes diffusive size factors for conduits of spheres and cylinders with the spheres approximated as N cylinders in series. Parameters ---------- %(network)s %(Dp)s %(Dt)s n : int Number of cylindrical divisions for each pore and throat Returns ------- Notes -----
ncylinders_in_series
python
PMEAL/OpenPNM
openpnm/models/geometry/diffusive_size_factors/_funcs.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/diffusive_size_factors/_funcs.py
MIT
def spheres_and_cylinders( network, pore_diameter="pore.diameter", throat_diameter="throat.diameter", ): r""" Computes hydraulic size factors for conduits assuming pores are spheres and throats are cylinders. Parameters ---------- %(network)s %(Dp)s %(Dt)s Returns ------- size_factors : ndarray Array (Nt by 3) containing conduit values for each element of the pore-throat-pore conduits. The array is formatted as ``[pore1, throat, pore2]``. Notes ----- The hydraulic size factor is the geometrical part of the pre-factor in Stoke's flow: .. math:: Q = \frac{A^2}{8 \pi \mu L} \Delta P = \frac{S_{hydraulic}}{\mu} \Delta P Thus :math:`S_{hydraulic}` represents the combined effect of the area and length of the *conduit*, which consists of a throat and 1/2 of the pores on each end. """ D1, Dt, D2 = network.get_conduit_data(pore_diameter.split('.', 1)[-1]).T L1, Lt, L2 = _conduit_lengths.spheres_and_cylinders( network=network, pore_diameter=pore_diameter, throat_diameter=throat_diameter ).T # Fi is the integral of (1/A^2) dx, x = [0, Li] a = 4 / (D1**3 * _np.pi**2) b = 2 * D1 * L1 / (D1**2 - 4 * L1**2) + _np.arctanh(2 * L1 / D1) F1 = a * b a = 4 / (D2**3 * _np.pi**2) b = 2 * D2 * L2 / (D2**2 - 4 * L2**2) + _np.arctanh(2 * L2 / D2) F2 = a * b Ft = Lt / (_np.pi / 4 * Dt**2)**2 # I is the integral of (y^2 + z^2) dA, divided by A^2 I1 = I2 = It = 1 / (2 * _np.pi) # S is 1 / (16 * pi^2 * I * F) S1 = 1 / (16 * _np.pi**2 * I1 * F1) St = 1 / (16 * _np.pi**2 * It * Ft) S2 = 1 / (16 * _np.pi**2 * I2 * F2) return _np.vstack([S1, St, S2]).T
Computes hydraulic size factors for conduits assuming pores are spheres and throats are cylinders. Parameters ---------- %(network)s %(Dp)s %(Dt)s Returns ------- size_factors : ndarray Array (Nt by 3) containing conduit values for each element of the pore-throat-pore conduits. The array is formatted as ``[pore1, throat, pore2]``. Notes ----- The hydraulic size factor is the geometrical part of the pre-factor in Stoke's flow: .. math:: Q = \frac{A^2}{8 \pi \mu L} \Delta P = \frac{S_{hydraulic}}{\mu} \Delta P Thus :math:`S_{hydraulic}` represents the combined effect of the area and length of the *conduit*, which consists of a throat and 1/2 of the pores on each end.
spheres_and_cylinders
python
PMEAL/OpenPNM
openpnm/models/geometry/hydraulic_size_factors/_funcs.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/hydraulic_size_factors/_funcs.py
MIT
def circles_and_rectangles( network, pore_diameter="pore.diameter", throat_diameter="throat.diameter", ): r""" Computes hydraulic size factors for conduits assuming pores are circles and throats are rectangles. Parameters ---------- %(network)s %(Dp)s %(Dt)s Returns ------- Notes ----- """ D1, Dt, D2 = network.get_conduit_data(pore_diameter.split('.', 1)[-1]).T L1, Lt, L2 = _conduit_lengths.circles_and_rectangles( network=network, pore_diameter=pore_diameter, throat_diameter=throat_diameter ).T # Fi is the integral of (1/A^3) dx, x = [0, Li] F1 = L1 / (D1**2 * _np.sqrt(D1**2 - 4 * L1**2)) F2 = L2 / (D2**2 * _np.sqrt(D2**2 - 4 * L2**2)) Ft = Lt / Dt**3 # S is 1 / (12 * F) S1, St, S2 = [1 / (Fi * 12) for Fi in [F1, Ft, F2]] return _np.vstack([S1, St, S2]).T
Computes hydraulic size factors for conduits assuming pores are circles and throats are rectangles. Parameters ---------- %(network)s %(Dp)s %(Dt)s Returns ------- Notes -----
circles_and_rectangles
python
PMEAL/OpenPNM
openpnm/models/geometry/hydraulic_size_factors/_funcs.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/hydraulic_size_factors/_funcs.py
MIT
def cones_and_cylinders( network, pore_diameter="pore.diameter", throat_diameter="throat.diameter", ): r""" Computes hydraulic size factors for conduits assuming pores are truncated cones and throats are cylinders. Parameters ---------- %(network)s %(Dp)s %(Dt)s Returns ------- Notes ----- """ D1, Dt, D2 = network.get_conduit_data(pore_diameter.split('.', 1)[-1]).T L1, Lt, L2 = _conduit_lengths.cones_and_cylinders( network=network, pore_diameter=pore_diameter, throat_diameter=throat_diameter ).T # Fi is the integral of (1/A^2) dx, x = [0, Li] F1 = 16 / 3 * (L1 * (D1**2 + D1 * Dt + Dt**2) / (D1**3 * Dt**3 * _np.pi**2)) F2 = 16 / 3 * (L2 * (D2**2 + D2 * Dt + Dt**2) / (D2**3 * Dt**3 * _np.pi**2)) Ft = Lt / (_np.pi * Dt**2 / 4) ** 2 # I is the integral of (y^2 + z^2) dA, divided by A^2 I1 = I2 = It = 1 / (2 * _np.pi) # S is 1 / (16 * pi^2 * I * F) S1 = 1 / (16 * _np.pi**2 * I1 * F1) St = 1 / (16 * _np.pi**2 * It * Ft) S2 = 1 / (16 * _np.pi**2 * I2 * F2) return _np.vstack([S1, St, S2]).T
Computes hydraulic size factors for conduits assuming pores are truncated cones and throats are cylinders. Parameters ---------- %(network)s %(Dp)s %(Dt)s Returns ------- Notes -----
cones_and_cylinders
python
PMEAL/OpenPNM
openpnm/models/geometry/hydraulic_size_factors/_funcs.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/hydraulic_size_factors/_funcs.py
MIT
def intersecting_cones( network, pore_diameter="pore.diameter", throat_coords="throat.coords" ): r""" Computes hydraulic size factors of intersecting cones. Parameters ---------- %(network)s %(Dp)s %(Dt)s Returns ------- Notes ----- """ D1, Dt, D2 = network.get_conduit_data(pore_diameter.split('.', 1)[-1]).T L1, Lt, L2 = _conduit_lengths.intersecting_cones( network=network, throat_coords=throat_coords ).T # Fi is the integral of (1/A^2) dx, x = [0, Li] F1 = 16 / 3 * (L1 * (D1**2 + D1 * Dt + Dt**2) / (D1**3 * Dt**3 * _np.pi**2)) F2 = 16 / 3 * (L2 * (D2**2 + D2 * Dt + Dt**2) / (D2**3 * Dt**3 * _np.pi**2)) # I is the integral of (y^2 + z^2) dA, divided by A^2 I1 = I2 = 1 / (2 * _np.pi) # S is 1 / (16 * pi^2 * I * F) S1 = 1 / (16 * _np.pi**2 * I1 * F1) S2 = 1 / (16 * _np.pi**2 * I2 * F2) St = _np.full(len(Lt), _np.inf) return _np.vstack([S1, St, S2]).T
Computes hydraulic size factors of intersecting cones. Parameters ---------- %(network)s %(Dp)s %(Dt)s Returns ------- Notes -----
intersecting_cones
python
PMEAL/OpenPNM
openpnm/models/geometry/hydraulic_size_factors/_funcs.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/hydraulic_size_factors/_funcs.py
MIT
def hybrid_cones_and_cylinders( network, pore_diameter="pore.diameter", throat_coords="throat.coords" ): r""" Computes hydraulic size factors for conduits assuming pores are truncated cones and throats are cylinders. Parameters ---------- %(network)s %(Dp)s %(Tcoords)s Returns ------- Notes ----- """ D1, Dt, D2 = network.get_conduit_data(pore_diameter.split('.', 1)[-1]).T L1, Lt, L2 = _conduit_lengths.hybrid_cones_and_cylinders( network=network, pore_diameter=pore_diameter, throat_coords=throat_coords ).T # Fi is the integral of (1/A^2) dx, x = [0, Li] F1 = 16 / 3 * (L1 * (D1**2 + D1 * Dt + Dt**2) / (D1**3 * Dt**3 * _np.pi**2)) F2 = 16 / 3 * (L2 * (D2**2 + D2 * Dt + Dt**2) / (D2**3 * Dt**3 * _np.pi**2)) Ft = Lt / (_np.pi * Dt**2 / 4) ** 2 # I is the integral of (y^2 + z^2) dA, divided by A^2 I1 = I2 = It = 1 / (2 * _np.pi) mask = Lt == 0.0 if mask.any(): inv_F_t = _np.zeros(len(Ft)) inv_F_t[~mask] = 1/Ft[~mask] inv_F_t[mask] = _np.inf else: inv_F_t = 1/Ft # S is 1 / (16 * pi^2 * I * F) S1 = 1 / (16 * _np.pi**2 * I1 * F1) St = inv_F_t / (16 * _np.pi**2 * It) S2 = 1 / (16 * _np.pi**2 * I2 * F2) return _np.vstack([S1, St, S2]).T
Computes hydraulic size factors for conduits assuming pores are truncated cones and throats are cylinders. Parameters ---------- %(network)s %(Dp)s %(Tcoords)s Returns ------- Notes -----
hybrid_cones_and_cylinders
python
PMEAL/OpenPNM
openpnm/models/geometry/hydraulic_size_factors/_funcs.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/hydraulic_size_factors/_funcs.py
MIT
def trapezoids_and_rectangles( network, pore_diameter="pore.diameter", throat_diameter="throat.diameter", ): r""" Computes hydraulic size factors for conduits assuming pores are trapezoids and throats are rectangles. Parameters ---------- %(network)s %(Dp)s %(Dt)s Returns ------- Notes ----- This model should only be used for true 2D networks, i.e. with planar symmetry. """ D1, Dt, D2 = network.get_conduit_data(pore_diameter.split('.', 1)[-1]).T L1, Lt, L2 = _conduit_lengths.cones_and_cylinders( network=network, pore_diameter=pore_diameter, throat_diameter=throat_diameter ).T # Fi is the integral of (1/A^3) dx, x = [0, Li] F1 = L1 / 2 * (D1 + Dt) / (D1 * Dt)**2 F2 = L2 / 2 * (D2 + Dt) / (D2 * Dt)**2 Ft = Lt / Dt**3 # S is 1 / (12 * F) S1, St, S2 = [1 / (Fi * 12) for Fi in [F1, Ft, F2]] return _np.vstack([S1, St, S2]).T
Computes hydraulic size factors for conduits assuming pores are trapezoids and throats are rectangles. Parameters ---------- %(network)s %(Dp)s %(Dt)s Returns ------- Notes ----- This model should only be used for true 2D networks, i.e. with planar symmetry.
trapezoids_and_rectangles
python
PMEAL/OpenPNM
openpnm/models/geometry/hydraulic_size_factors/_funcs.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/hydraulic_size_factors/_funcs.py
MIT
def intersecting_trapezoids( network, pore_diameter="pore.diameter", throat_coords="throat.coords" ): r""" Computes hydraulic size factors for conduits of intersecting trapezoids. Parameters ---------- %(network)s %(Dp)s %(Tcoords)s Returns ------- Notes ----- This model should only be used for true 2D networks, i.e. with planar symmetry. """ D1, Dt, D2 = network.get_conduit_data(pore_diameter.split('.', 1)[-1]).T L1, Lt, L2 = _conduit_lengths.intersecting_trapezoids( network=network, throat_coords=throat_coords ).T # Fi is the integral of (1/A^3) dx, x = [0, Li] F1 = L1 / 2 * (D1 + Dt) / (D1 * Dt)**2 F2 = L2 / 2 * (D2 + Dt) / (D2 * Dt)**2 # S is 1 / (12 * F) S1 = 1 / (F1 * 12) S2 = 1 / (F2 * 12) St = _np.full(len(Lt), _np.inf) return _np.vstack([S1, St, S2]).T
Computes hydraulic size factors for conduits of intersecting trapezoids. Parameters ---------- %(network)s %(Dp)s %(Tcoords)s Returns ------- Notes ----- This model should only be used for true 2D networks, i.e. with planar symmetry.
intersecting_trapezoids
python
PMEAL/OpenPNM
openpnm/models/geometry/hydraulic_size_factors/_funcs.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/hydraulic_size_factors/_funcs.py
MIT
def hybrid_trapezoids_and_rectangles( network, pore_diameter="pore.diameter", throat_coords="throat.coords" ): r""" Computes hydraulic size factors for conduits assuming pores are trapezoids and throats are rectangles. Parameters ---------- %(network)s %(Dp)s %(Tcoords)s Returns ------- Notes ----- This model should only be used for true 2D networks, i.e. with planar symmetry. """ D1, Dt, D2 = network.get_conduit_data(pore_diameter.split('.', 1)[-1]).T L1, Lt, L2 = _conduit_lengths.hybrid_trapezoids_and_rectangles( network=network, pore_diameter=pore_diameter, throat_coords=throat_coords ).T # Fi is the integral of (1/A^3) dx, x = [0, Li] F1 = L1 / 2 * (D1 + Dt) / (D1 * Dt)**2 F2 = L2 / 2 * (D2 + Dt) / (D2 * Dt)**2 Ft = Lt / Dt**3 mask = Lt == 0.0 if mask.any(): inv_F_t = _np.zeros(len(Ft)) inv_F_t[~mask] = 1/Ft[~mask] inv_F_t[mask] = _np.inf else: inv_F_t = 1/Ft # S is 1 / (12 * F) S1 = 1 / (F1 * 12) St = inv_F_t / 12 S2 = 1 / (F2 * 12) return _np.vstack([S1, St, S2]).T
Computes hydraulic size factors for conduits assuming pores are trapezoids and throats are rectangles. Parameters ---------- %(network)s %(Dp)s %(Tcoords)s Returns ------- Notes ----- This model should only be used for true 2D networks, i.e. with planar symmetry.
hybrid_trapezoids_and_rectangles
python
PMEAL/OpenPNM
openpnm/models/geometry/hydraulic_size_factors/_funcs.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/hydraulic_size_factors/_funcs.py
MIT
def pyramids_and_cuboids( network, pore_diameter="pore.diameter", throat_diameter="throat.diameter", ): r""" Computes hydraulic size factors for conduits assuming pores are truncated pyramids and throats are cuboids. Parameters ---------- %(network)s %(Dp)s %(Dt)s Returns ------- Notes ----- """ D1, Dt, D2 = network.get_conduit_data(pore_diameter.split('.', 1)[-1]).T L1, Lt, L2 = _conduit_lengths.pyramids_and_cuboids( network=network, pore_diameter=pore_diameter, throat_diameter=throat_diameter ).T # Fi is the integral of (1/A^2) dx, x = [0, Li] F1 = 1 / 3 * (L1 * (D1**2 + D1 * Dt + Dt**2) / (D1**3 * Dt**3)) F2 = 1 / 3 * (L2 * (D2**2 + D2 * Dt + Dt**2) / (D2**3 * Dt**3)) Ft = Lt / Dt**4 # I is the integral of (y^2 + z^2) dA, divided by A^2 I1 = I2 = It = 1 / 6 # S is 1 / (16 * pi^2 * I * F) S1 = 1 / (16 * _np.pi**2 * I1 * F1) St = 1 / (16 * _np.pi**2 * It * Ft) S2 = 1 / (16 * _np.pi**2 * I2 * F2) return _np.vstack([S1, St, S2]).T
Computes hydraulic size factors for conduits assuming pores are truncated pyramids and throats are cuboids. Parameters ---------- %(network)s %(Dp)s %(Dt)s Returns ------- Notes -----
pyramids_and_cuboids
python
PMEAL/OpenPNM
openpnm/models/geometry/hydraulic_size_factors/_funcs.py
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/hydraulic_size_factors/_funcs.py
MIT