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 intersecting_pyramids(
network,
pore_diameter="pore.diameter",
throat_coords="throat.coords"
):
r"""
Computes hydraulic size factors of intersecting pyramids.
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.intersecting_pyramids(
network=network,
throat_coords=throat_coords
).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))
# I is the integral of (y^2 + z^2) dA, divided by A^2
I1 = I2 = 1 / 6
# 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 pyramids.
Parameters
----------
%(network)s
%(Dp)s
%(Tcoords)s
Returns
-------
Notes
-----
|
intersecting_pyramids
|
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_pyramids_and_cuboids(
network,
pore_diameter="pore.diameter",
throat_coords="throat.coords"
):
r"""
Computes hydraulic size factors for conduits assuming pores are
truncated pyramids and throats are cuboids.
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_pyramids_and_cuboids(
network=network,
pore_diameter=pore_diameter,
throat_coords=throat_coords
).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
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 pyramids and throats are cuboids.
Parameters
----------
%(network)s
%(Dp)s
%(Tcoords)s
Returns
-------
Notes
-----
|
hybrid_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
|
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 hydraulic size factors 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
-----
"""
D1, Dt, D2 = network.get_conduit_data(pore_diameter.split('.', 1)[-1]).T
L1, Lt, L2 = _conduit_lengths.cubes_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 = L1 / D1**4
F2 = L2 / D2**4
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 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
-----
|
cubes_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
|
def squares_and_rectangles(
network,
pore_diameter="pore.diameter",
throat_diameter="throat.diameter",
pore_aspect=[1, 1],
throat_aspect=[1, 1],
):
r"""
Computes hydraulic size factors 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=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**3
F2 = L2 / D2**3
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
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/hydraulic_size_factors/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/hydraulic_size_factors/_funcs.py
|
MIT
|
def ncylinders_in_series(
network,
pore_diameter="pore.diameter",
throat_diameter="throat.diameter",
n=5,
):
r"""
Computes hydraulic 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
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=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 ** 4 / (8 * L1 / n)).T
F1 = 1 / _np.sum(1 / gtemp, axis=1)
gtemp = (_np.pi * r2 ** 4 / (8 * L2 / n)).T
F2 = 1 / _np.sum(1 / gtemp, axis=1)
Ft = (_np.pi * (Dt / 2) ** 4 / (8 * Lt)).T
return _np.vstack([F1, Ft, F2]).T
|
Computes hydraulic 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
Returns
-------
Notes
-----
|
ncylinders_in_series
|
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 sphere(
network,
pore_diameter='pore.diameter'
):
r"""
Calculate cross-sectional area assuming the pore body is a sphere
Parameters
----------
%(network)s
%(Dp)s
Returns
-------
areas : ndarray
A numpy ndarry containing pore cross-sectional area values
"""
D = network[pore_diameter]
return _pi/4 * D**2
|
Calculate cross-sectional area assuming the pore body is a sphere
Parameters
----------
%(network)s
%(Dp)s
Returns
-------
areas : ndarray
A numpy ndarry containing pore cross-sectional area values
|
sphere
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/pore_cross_sectional_area/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/pore_cross_sectional_area/_funcs.py
|
MIT
|
def cone(
network,
pore_diameter='pore.diameter'
):
r"""
Calculate cross-sectional area assuming the pore body is a cone
Parameters
----------
%(network)s
%(Dp)s
Returns
-------
"""
D = network[pore_diameter]
return _pi / 4 * D**2
|
Calculate cross-sectional area assuming the pore body is a cone
Parameters
----------
%(network)s
%(Dp)s
Returns
-------
|
cone
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/pore_cross_sectional_area/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/pore_cross_sectional_area/_funcs.py
|
MIT
|
def cube(
network,
pore_diameter='pore.diameter'
):
r"""
Calculate cross-sectional area assuming the pore body is a cube
Parameters
----------
%(network)s
%(Dp)s
Returns
-------
"""
D = network[pore_diameter]
return D**2
|
Calculate cross-sectional area assuming the pore body is a cube
Parameters
----------
%(network)s
%(Dp)s
Returns
-------
|
cube
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/pore_cross_sectional_area/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/pore_cross_sectional_area/_funcs.py
|
MIT
|
def circle(
network,
pore_diameter='pore.diameter'
):
r"""
Calculate cross-sectional area assuming the pore body is a circle
Parameters
----------
%(network)s
%(Dp)s
Returns
-------
Notes
-----
This model should only be used for true 2D networks, i.e. with planar
symmetry.
"""
return network[pore_diameter]
|
Calculate cross-sectional area assuming the pore body is a circle
Parameters
----------
%(network)s
%(Dp)s
Returns
-------
Notes
-----
This model should only be used for true 2D networks, i.e. with planar
symmetry.
|
circle
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/pore_cross_sectional_area/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/pore_cross_sectional_area/_funcs.py
|
MIT
|
def square(
network,
pore_diameter='pore.diameter'
):
r"""
Calculate cross-sectional area assuming the pore body is a square
Parameters
----------
%(network)s
%(Dp)s
Returns
-------
Notes
-----
This model should only be used for true 2D networks, i.e. with planar
symmetry.
"""
return network[pore_diameter]
|
Calculate cross-sectional area assuming the pore body is a square
Parameters
----------
%(network)s
%(Dp)s
Returns
-------
Notes
-----
This model should only be used for true 2D networks, i.e. with planar
symmetry.
|
square
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/pore_cross_sectional_area/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/pore_cross_sectional_area/_funcs.py
|
MIT
|
def equivalent_diameter(
network,
pore_volume='pore.volume',
pore_shape='sphere'
):
r"""
Calculate the diameter of a sphere or edge-length of a cube with same
volume as the pore.
Parameters
----------
%(network)s
%(Vp)s
pore_shape : str
The shape of the pore body to assume when back-calculating from
volume. Options are 'sphere' (default) or 'cube'.
Returns
-------
diameters : ndarray
A number ndarray containing pore diameter values
"""
from scipy.special import cbrt
pore_vols = network[pore_volume]
if pore_shape.startswith('sph'):
value = cbrt(6*pore_vols/_np.pi)
elif pore_shape.startswith('cub'):
value = cbrt(pore_vols)
return value
|
Calculate the diameter of a sphere or edge-length of a cube with same
volume as the pore.
Parameters
----------
%(network)s
%(Vp)s
pore_shape : str
The shape of the pore body to assume when back-calculating from
volume. Options are 'sphere' (default) or 'cube'.
Returns
-------
diameters : ndarray
A number ndarray containing pore diameter values
|
equivalent_diameter
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/pore_size/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/pore_size/_funcs.py
|
MIT
|
def sphere(
network,
pore_diameter='pore.diameter'
):
r"""
Calculate pore volume from diameter assuming a spherical pore body
Parameters
----------
%(network)s
%(Dp)s
Returns
-------
volumes : ndarray
Numpy ndarray containing pore volume values
"""
return 4/3*_pi*(network[pore_diameter]/2)**3
|
Calculate pore volume from diameter assuming a spherical pore body
Parameters
----------
%(network)s
%(Dp)s
Returns
-------
volumes : ndarray
Numpy ndarray containing pore volume values
|
sphere
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/pore_volume/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/pore_volume/_funcs.py
|
MIT
|
def cube(
network,
pore_diameter='pore.diameter'
):
r"""
Calculate pore volume from diameter assuming a cubic pore body
Parameters
----------
%(network)s
%(Dp)s
Returns
-------
"""
return network[pore_diameter]**3
|
Calculate pore volume from diameter assuming a cubic pore body
Parameters
----------
%(network)s
%(Dp)s
Returns
-------
|
cube
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/pore_volume/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/pore_volume/_funcs.py
|
MIT
|
def circle(
network,
pore_diameter='pore.diameter',
):
r"""
Calculate pore volume from diameter assuming a spherical pore body
Parameters
----------
%(network)s
%(Dp)s
Returns
-------
"""
return _pi/4 * network[pore_diameter]**2
|
Calculate pore volume from diameter assuming a spherical pore body
Parameters
----------
%(network)s
%(Dp)s
Returns
-------
|
circle
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/pore_volume/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/pore_volume/_funcs.py
|
MIT
|
def square(
network,
pore_diameter='pore.diameter',
):
r"""
Calculate pore volume from diameter assuming a cubic pore body
Parameters
----------
%(network)s
%(Dp)s
Returns
-------
"""
return network[pore_diameter]**2
|
Calculate pore volume from diameter assuming a cubic pore body
Parameters
----------
%(network)s
%(Dp)s
Returns
-------
|
square
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/pore_volume/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/pore_volume/_funcs.py
|
MIT
|
def effective(
network,
pore_volume='pore.volume',
throat_volume='throat.volume',
):
r"""
Calculate the effective pore volume for optional use in transient
simulations. The effective pore volume is calculated by adding half
the volume of all neighbouring throats to the pore volume.
Parameters
----------
%(network)s
%(Dp)s
%(Dt)s
Returns
-------
"""
cn = network['throat.conns']
P1 = cn[:, 0]
P2 = cn[:, 1]
eff_vol = np.copy(network[pore_volume])
np.add.at(eff_vol, P1, 1/2*network[throat_volume])
np.add.at(eff_vol, P2, 1/2*network[throat_volume])
return eff_vol
|
Calculate the effective pore volume for optional use in transient
simulations. The effective pore volume is calculated by adding half
the volume of all neighbouring throats to the pore volume.
Parameters
----------
%(network)s
%(Dp)s
%(Dt)s
Returns
-------
|
effective
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/pore_volume/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/pore_volume/_funcs.py
|
MIT
|
def mason_morrow(
network,
throat_perimeter='throat.perimeter',
throat_area='throat.cross_sectional_area',
):
r"""
Mason and Morrow relate the capillary pressure to the shape factor in a
similar way to Mortensen but for triangles.
Parameters
----------
%(network)s
%(Pt)s
%(At)s
Returns
-------
References
----------
Mason, G. and Morrow, N.R.. Capillary behavior of a perfectly wetting
liquid in irregular triangular tubes. Journal of Colloid and Interface
Science, 141(1), pp.262-274 (1991).
"""
# Only apply to throats with an area
ts = network.throats()[network[throat_area] <= 0]
P = network[throat_perimeter]
A = network[throat_area]
value = A/(P**2)
value[ts] = 1/(4*_np.pi)
return value
|
Mason and Morrow relate the capillary pressure to the shape factor in a
similar way to Mortensen but for triangles.
Parameters
----------
%(network)s
%(Pt)s
%(At)s
Returns
-------
References
----------
Mason, G. and Morrow, N.R.. Capillary behavior of a perfectly wetting
liquid in irregular triangular tubes. Journal of Colloid and Interface
Science, 141(1), pp.262-274 (1991).
|
mason_morrow
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/throat_capillary_shape_factor/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/throat_capillary_shape_factor/_funcs.py
|
MIT
|
def jenkins_rao(
network,
throat_perimeter='throat.perimeter',
throat_area='throat.cross_sectional_area',
throat_diameter='throat.indiameter',
):
r"""
Jenkins and Rao relate the capillary pressure in an eliptical throat to
the aspect ratio
Parameters
----------
%(network)s
%(Pt)s
%(At)s
%(Dt)s
Returns
-------
References
----------
Jenkins, R.G. and Rao, M.B., The effect of elliptical pores on
mercury porosimetry results. Powder technology, 38(2), pp.177-180. (1984)
"""
P = network[throat_perimeter]
A = network[throat_area]
r = network[throat_diameter]/2
# Normalized by value for perfect circle
value = (P/A)/(2/r)
return value
|
Jenkins and Rao relate the capillary pressure in an eliptical throat to
the aspect ratio
Parameters
----------
%(network)s
%(Pt)s
%(At)s
%(Dt)s
Returns
-------
References
----------
Jenkins, R.G. and Rao, M.B., The effect of elliptical pores on
mercury porosimetry results. Powder technology, 38(2), pp.177-180. (1984)
|
jenkins_rao
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/throat_capillary_shape_factor/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/throat_capillary_shape_factor/_funcs.py
|
MIT
|
def pore_coords(
network
):
r"""
Calculate throat centroid values by averaging adjacent pore coordinates
Parameters
----------
%(network)s
Returns
-------
values : ndarray
A numpy ndarray containing throat centroid values
"""
conns = network['throat.conns']
coords = network['pore.coords']
return _np.mean(coords[conns], axis=1)
|
Calculate throat centroid values by averaging adjacent pore coordinates
Parameters
----------
%(network)s
Returns
-------
values : ndarray
A numpy ndarray containing throat centroid values
|
pore_coords
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/throat_centroid/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/throat_centroid/_funcs.py
|
MIT
|
def cylinder(
network,
throat_diameter='throat.diameter',
):
r"""
Calculate throat cross-sectional area for a cylindrical throat
Parameters
----------
%(network)s
%(Dt)s
Returns
-------
"""
diams = network[throat_diameter]
value = _pi / 4 * diams**2
return value
|
Calculate throat cross-sectional area for a cylindrical throat
Parameters
----------
%(network)s
%(Dt)s
Returns
-------
|
cylinder
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/throat_cross_sectional_area/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/throat_cross_sectional_area/_funcs.py
|
MIT
|
def cuboid(
network,
throat_diameter='throat.diameter',
):
r"""
Calculate throat cross-sectional area for a cuboid throat
Parameters
----------
%(network)s
%(Dt)s
Returns
-------
"""
diams = network[throat_diameter]
value = (diams)**2
return value
|
Calculate throat cross-sectional area for a cuboid throat
Parameters
----------
%(network)s
%(Dt)s
Returns
-------
|
cuboid
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/throat_cross_sectional_area/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/throat_cross_sectional_area/_funcs.py
|
MIT
|
def rectangle(
network,
throat_diameter='throat.diameter',
):
r"""
Calculate throat cross-sectional area for a rectangular throat
Parameters
----------
%(network)s
%(Dt)s
Returns
-------
"""
return network[throat_diameter]
|
Calculate throat cross-sectional area for a rectangular throat
Parameters
----------
%(network)s
%(Dt)s
Returns
-------
|
rectangle
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/throat_cross_sectional_area/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/throat_cross_sectional_area/_funcs.py
|
MIT
|
def spheres_and_cylinders(
network,
pore_diameter='pore.diameter',
throat_diameter='throat.diameter',
throat_centroid='throat.centroid',
):
r"""
Computes the endpoints of throats when pores are spherical.
The endpoints lie inside the sphere, defined by the lens formed between
the intersection of the sphere and cylinder.
Parameters
----------
%(network)s
%(Dp)s
%(Dt)s
%(Tcen)s
Returns
-------
endpoints : ndarray
An array containing the Nt-2-3 coordinates of the end points of each
throat.
"""
xyz = network.coords
cn = network.conns
L = network['throat.spacing']
Dt = network[throat_diameter]
D1 = network[pore_diameter][cn[:, 0]]
D2 = network[pore_diameter][cn[:, 1]]
L1 = _np.zeros_like(L)
L2 = _np.zeros_like(L)
# Handle the case where Dt > Dp
mask = Dt > D1
L1[mask] = 0.5 * D1[mask]
L1[~mask] = _np.sqrt(D1[~mask]**2 - Dt[~mask]**2) / 2
mask = Dt > D2
L2[mask] = 0.5 * D2[mask]
L2[~mask] = _np.sqrt(D2[~mask]**2 - Dt[~mask]**2) / 2
# Handle non-colinear pores and throat centroids
try:
TC = network[throat_centroid]
LP1T = _np.linalg.norm(TC - xyz[cn[:, 0]], axis=1) + 1e-15
LP2T = _np.linalg.norm(TC - xyz[cn[:, 1]], axis=1) + 1e-15
unit_vec_P1T = (TC - xyz[cn[:, 0]]) / LP1T[:, None]
unit_vec_P2T = (TC - xyz[cn[:, 1]]) / LP2T[:, None]
except KeyError:
unit_vec_P1T = (xyz[cn[:, 1]] - xyz[cn[:, 0]]) / L[:, None]
unit_vec_P2T = -1 * unit_vec_P1T
# Find throat endpoints
EP1 = xyz[cn[:, 0]] + L1[:, None] * unit_vec_P1T
EP2 = xyz[cn[:, 1]] + L2[:, None] * unit_vec_P2T
# Handle throats w/ overlapping pores
L1 = (4 * L**2 + D1**2 - D2**2) / (8 * L)
L2 = (4 * L**2 + D2**2 - D1**2) / (8 * L)
h = (2 * _np.sqrt(D1**2 / 4 - L1**2)).real
overlap = L - 0.5 * (D1 + D2) < 0
mask = overlap & (Dt < h)
EP1[mask] = (xyz[cn[:, 0]] + L1[:, None] * unit_vec_P1T)[mask]
EP2[mask] = (xyz[cn[:, 1]] + L2[:, None] * unit_vec_P2T)[mask]
return {'head': EP1, 'tail': EP2}
|
Computes the endpoints of throats when pores are spherical.
The endpoints lie inside the sphere, defined by the lens formed between
the intersection of the sphere and cylinder.
Parameters
----------
%(network)s
%(Dp)s
%(Dt)s
%(Tcen)s
Returns
-------
endpoints : ndarray
An array containing the Nt-2-3 coordinates of the end points of each
throat.
|
spheres_and_cylinders
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/throat_endpoints/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/throat_endpoints/_funcs.py
|
MIT
|
def spheres_and_cylinders(
network,
pore_diameter='pore.diameter',
throat_diameter='throat.diameter'
):
r"""
Finds throat length assuming pores are spheres and throats are
cylinders.
Parameters
----------
%(network)s
%(Dp)s
%(Dt)s
Returns
-------
lengths : ndarray
A numpy ndarray containing throat length values
"""
from openpnm.models.geometry import conduit_lengths
out = conduit_lengths.spheres_and_cylinders(
network=network,
pore_diameter=pore_diameter,
throat_diameter=throat_diameter
)
return out[:, 1]
|
Finds throat length assuming pores are spheres and throats are
cylinders.
Parameters
----------
%(network)s
%(Dp)s
%(Dt)s
Returns
-------
lengths : ndarray
A numpy ndarray containing throat length values
|
spheres_and_cylinders
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/throat_length/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/throat_length/_funcs.py
|
MIT
|
def circles_and_rectangles(
network,
pore_diameter='pore.diameter',
throat_diameter='throat.diameter',
):
r"""
Finds throat length assuming pores are circles and throats are
rectangles.
Parameters
----------
%(network)s
%(Dp)s
%(Dt)s
Returns
-------
"""
from openpnm.models.geometry import conduit_lengths
out = conduit_lengths.circles_and_rectangles(
network=network,
pore_diameter=pore_diameter,
throat_diameter=throat_diameter
)
return out[:, 1]
|
Finds throat length assuming pores are circles and throats are
rectangles.
Parameters
----------
%(network)s
%(Dp)s
%(Dt)s
Returns
-------
|
circles_and_rectangles
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/throat_length/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/throat_length/_funcs.py
|
MIT
|
def cones_and_cylinders(
network,
pore_diameter='pore.diameter',
throat_diameter='throat.diameter'
):
r"""
Finds throat length assuming pores are cones and throats are
cylinders.
Parameters
----------
%(network)s
%(Dp)s
%(Dt)s
Returns
-------
"""
from openpnm.models.geometry import conduit_lengths
out = conduit_lengths.cones_and_cylinders(
network=network,
pore_diameter=pore_diameter,
throat_diameter=throat_diameter
)
return out[:, 1]
|
Finds throat length assuming pores are cones and throats are
cylinders.
Parameters
----------
%(network)s
%(Dp)s
%(Dt)s
Returns
-------
|
cones_and_cylinders
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/throat_length/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/throat_length/_funcs.py
|
MIT
|
def intersecting_cones(
network,
pore_coords="pore.coords",
throat_coords="throat.coords"
):
r"""
Finds throat length assuming pores are intersecting cones.
Parameters
----------
%(network)s
%(Pcoords)s
%(Tcoords)s
Returns
-------
"""
from openpnm.models.geometry import conduit_lengths
out = conduit_lengths.intersecting_cones(
network=network,
pore_coords=pore_coords,
throat_coords=throat_coords
)
return out[:, 1]
|
Finds throat length assuming pores are intersecting cones.
Parameters
----------
%(network)s
%(Pcoords)s
%(Tcoords)s
Returns
-------
|
intersecting_cones
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/throat_length/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/throat_length/_funcs.py
|
MIT
|
def hybrid_cones_and_cylinders(
network,
pore_diameter="pore.diameter",
throat_coords="throat.coords"
):
r"""
Finds throat length assuming pores are cones and throats are
cylinders.
Parameters
----------
%(network)s
%(Dp)s
%(Tcoords)s
Returns
-------
"""
from openpnm.models.geometry import conduit_lengths
out = conduit_lengths.hybrid_cones_and_cylinders(
network=network,
pore_diameter=pore_diameter,
throat_coords=throat_coords
)
return out[:, 1]
|
Finds throat length assuming pores are cones and throats are
cylinders.
Parameters
----------
%(network)s
%(Dp)s
%(Tcoords)s
Returns
-------
|
hybrid_cones_and_cylinders
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/throat_length/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/throat_length/_funcs.py
|
MIT
|
def trapezoids_and_rectangles(
network,
pore_diameter='pore.diameter',
throat_diameter='throat.diameter'
):
r"""
Finds throat length assuming pores are trapezoids and throats are
rectangles.
Parameters
----------
%(network)s
%(Dp)s
%(Dt)s
Returns
-------
"""
from openpnm.models.geometry import conduit_lengths
out = conduit_lengths.trapezoids_and_rectangles(
network=network,
pore_diameter=pore_diameter,
throat_diameter=throat_diameter
)
return out[:, 1]
|
Finds throat length assuming pores are trapezoids and throats are
rectangles.
Parameters
----------
%(network)s
%(Dp)s
%(Dt)s
Returns
-------
|
trapezoids_and_rectangles
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/throat_length/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/throat_length/_funcs.py
|
MIT
|
def intersecting_trapezoids(
network,
pore_coords="pore.coords",
throat_coords="throat.coords"
):
r"""
Finds throat length assuming pores are intersecting trapezoids.
Parameters
----------
%(network)s
%(Pcoords)s
%(Tcoords)s
Returns
-------
"""
from openpnm.models.geometry import conduit_lengths
out = conduit_lengths.intersecting_trapezoids(
network=network,
pore_coords=pore_coords,
throat_coords=throat_coords
)
return out[:, 1]
|
Finds throat length assuming pores are intersecting trapezoids.
Parameters
----------
%(network)s
%(Pcoords)s
%(Tcoords)s
Returns
-------
|
intersecting_trapezoids
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/throat_length/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/throat_length/_funcs.py
|
MIT
|
def hybrid_trapezoids_and_rectangles(
network,
pore_diameter="pore.diameter",
throat_coords="throat.coords"
):
r"""
Finds throat length assuming pores are trapezoids and throats are
rectangles.
Parameters
----------
%(network)s
%(Dp)s
%(Tcoords)s
Returns
-------
"""
from openpnm.models.geometry import conduit_lengths
out = conduit_lengths.hybrid_trapezoids_and_rectangles(
network=network,
pore_diameter=pore_diameter,
throat_coords=throat_coords
)
return out[:, 1]
|
Finds throat length assuming pores are trapezoids and throats are
rectangles.
Parameters
----------
%(network)s
%(Dp)s
%(Tcoords)s
Returns
-------
|
hybrid_trapezoids_and_rectangles
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/throat_length/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/throat_length/_funcs.py
|
MIT
|
def pyramids_and_cuboids(
network,
pore_diameter='pore.diameter',
throat_diameter='throat.diameter'
):
r"""
Finds throat length assuming pores are pyramids and throats are
cuboids.
Parameters
----------
%(network)s
%(Dp)s
%(Dt)s
Returns
-------
"""
from openpnm.models.geometry import conduit_lengths
out = conduit_lengths.pyramids_and_cuboids(
network=network,
pore_diameter=pore_diameter,
throat_diameter=throat_diameter
)
return out[:, 1]
|
Finds throat length assuming pores are pyramids and throats are
cuboids.
Parameters
----------
%(network)s
%(Dp)s
%(Dt)s
Returns
-------
|
pyramids_and_cuboids
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/throat_length/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/throat_length/_funcs.py
|
MIT
|
def intersecting_pyramids(
network,
pore_coords="pore.coords",
throat_coords="throat.coords"
):
r"""
Finds throat length assuming pores are intersecting pyramids.
Parameters
----------
%(network)s
%(Pcoords)s
%(Tcoords)s
Returns
-------
"""
from openpnm.models.geometry import conduit_lengths
out = conduit_lengths.intersecting_pyramids(
network=network,
pore_coords=pore_coords,
throat_coords=throat_coords
)
return out[:, 1]
|
Finds throat length assuming pores are intersecting pyramids.
Parameters
----------
%(network)s
%(Pcoords)s
%(Tcoords)s
Returns
-------
|
intersecting_pyramids
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/throat_length/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/throat_length/_funcs.py
|
MIT
|
def hybrid_pyramids_and_cuboids(
network,
pore_diameter='pore.diameter',
throat_coords="throat.coords",
):
r"""
Finds throat length assuming pores are pyramids and throats are
cuboids.
Parameters
----------
%(network)s
Returns
-------
"""
from openpnm.models.geometry import conduit_lengths
out = conduit_lengths.hybrid_pyramids_and_cuboids(
network=network,
pore_diameter=pore_diameter,
throat_coords=throat_coords
)
return out[:, 1]
|
Finds throat length assuming pores are pyramids and throats are
cuboids.
Parameters
----------
%(network)s
Returns
-------
|
hybrid_pyramids_and_cuboids
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/throat_length/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/throat_length/_funcs.py
|
MIT
|
def cubes_and_cuboids(
network,
pore_diameter='pore.diameter',
throat_diameter='throat.diameter'
):
r"""
Finds throat length assuming pores are cubes and throats are
cuboids.
Parameters
----------
%(network)s
%(Dp)s
%(Dt)s
Returns
-------
"""
from openpnm.models.geometry import conduit_lengths
out = conduit_lengths.cubes_and_cuboids(
network=network,
pore_diameter=pore_diameter,
throat_diameter=throat_diameter
)
return out[:, 1]
|
Finds throat length 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/throat_length/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/throat_length/_funcs.py
|
MIT
|
def squares_and_rectangles(
network,
pore_diameter='pore.diameter',
throat_diameter='throat.diameter'
):
r"""
Finds throat length assuming pores are squares and throats are
rectangles.
Parameters
----------
%(network)s
%(Dp)s
%(Dt)s
Returns
-------
"""
from openpnm.models.geometry import conduit_lengths
out = conduit_lengths.squares_and_rectangles(
network=network,
pore_diameter=pore_diameter,
throat_diameter=throat_diameter
)
return out[:, 1]
|
Finds throat length assuming pores are squares and throats are
rectangles.
Parameters
----------
%(network)s
%(Dp)s
%(Dt)s
Returns
-------
|
squares_and_rectangles
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/throat_length/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/throat_length/_funcs.py
|
MIT
|
def cylinder(
network,
throat_diameter='throat.diameter',
):
r"""
Calcuate the throat perimeter assuming a circular cross-section
Parameters
----------
%(network)s
%(Dt)s
Returns
-------
perimeters : ndarray
A numpy ndarray containing throat perimeter values
"""
return network[throat_diameter]*_np.pi
|
Calcuate the throat perimeter assuming a circular cross-section
Parameters
----------
%(network)s
%(Dt)s
Returns
-------
perimeters : ndarray
A numpy ndarray containing throat perimeter values
|
cylinder
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/throat_perimeter/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/throat_perimeter/_funcs.py
|
MIT
|
def cuboid(
network,
throat_diameter='throat.diameter',
):
r"""
Calcuate the throat perimeter assuming a square cross-section
Parameters
----------
%(network)s
%(Dt)s
Returns
-------
"""
return network[throat_diameter]*4
|
Calcuate the throat perimeter assuming a square cross-section
Parameters
----------
%(network)s
%(Dt)s
Returns
-------
|
cuboid
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/throat_perimeter/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/throat_perimeter/_funcs.py
|
MIT
|
def rectangle(
network,
throat_diameter='throat.diameter',
):
r"""
Calcuate the throat perimeter assuming a rectangular cross-section (2D)
Parameters
----------
%(network)s
%(Dt)s
Returns
-------
"""
return 1.0
|
Calcuate the throat perimeter assuming a rectangular cross-section (2D)
Parameters
----------
%(network)s
%(Dt)s
Returns
-------
|
rectangle
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/throat_perimeter/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/throat_perimeter/_funcs.py
|
MIT
|
def equivalent_diameter(
network,
throat_area='throat.cross_sectional_area',
throat_shape='circle',
):
r"""
Calculates the diameter of a cirlce or edge-length of a sqaure with same
area as the throat.
Parameters
----------
%(network)s
%(At)s
throat_shape : str
The shape cross-sectional shape of the throat to assume when
back-calculating from the area. Options are 'circle' (default) or
'square'.
Returns
-------
diameters : ndarray
A numpy ndarray containing throat diameter values
"""
area = network[throat_area]
if throat_shape.startswith('circ'):
value = 2*_np.sqrt(area/_np.pi)
elif throat_shape.startswith('square'):
value = _np.sqrt(area)
return value
|
Calculates the diameter of a cirlce or edge-length of a sqaure with same
area as the throat.
Parameters
----------
%(network)s
%(At)s
throat_shape : str
The shape cross-sectional shape of the throat to assume when
back-calculating from the area. Options are 'circle' (default) or
'square'.
Returns
-------
diameters : ndarray
A numpy ndarray containing throat diameter values
|
equivalent_diameter
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/throat_size/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/throat_size/_funcs.py
|
MIT
|
def cylinder(
network,
throat_diameter='throat.diameter',
throat_length='throat.length',
):
r"""
Calculate surface area for a cylindrical throat
Parameters
----------
%(network)s
%(Dt)s
%(Lt)s
Returns
-------
surface_areas : ndarray
A numpy ndarray containing throat surface area values
"""
return _np.pi * network[throat_diameter] * network[throat_length]
|
Calculate surface area for a cylindrical throat
Parameters
----------
%(network)s
%(Dt)s
%(Lt)s
Returns
-------
surface_areas : ndarray
A numpy ndarray containing throat surface area values
|
cylinder
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/throat_surface_area/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/throat_surface_area/_funcs.py
|
MIT
|
def cuboid(
network,
throat_diameter='throat.diameter',
throat_length='throat.length',
):
r"""
Calculate surface area for a cuboid throat
Parameters
----------
%(network)s
%(Dt)s
%(Lt)s
Returns
-------
"""
return 4 * network[throat_diameter] * network[throat_length]
|
Calculate surface area for a cuboid throat
Parameters
----------
%(network)s
%(Dt)s
%(Lt)s
Returns
-------
|
cuboid
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/throat_surface_area/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/throat_surface_area/_funcs.py
|
MIT
|
def extrusion(
network,
throat_perimeter='throat.perimeter',
throat_length='throat.length',
):
r"""
Calculate surface area for an arbitrary shaped throat give the perimeter
and length.
Parameters
----------
%(network)s
%(Pt)s
%(Lt)s
Returns
-------
"""
return network[throat_perimeter] * network[throat_length]
|
Calculate surface area for an arbitrary shaped throat give the perimeter
and length.
Parameters
----------
%(network)s
%(Pt)s
%(Lt)s
Returns
-------
|
extrusion
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/throat_surface_area/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/throat_surface_area/_funcs.py
|
MIT
|
def rectangle(
network,
throat_length='throat.length',
):
r"""
Calculate surface area for a rectangular throat
Only suitable for true 2D simulations
Parameters
----------
%(network)s
%(Lt)s
Returns
-------
"""
return 2 * network[throat_length]
|
Calculate surface area for a rectangular throat
Only suitable for true 2D simulations
Parameters
----------
%(network)s
%(Lt)s
Returns
-------
|
rectangle
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/throat_surface_area/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/throat_surface_area/_funcs.py
|
MIT
|
def pore_to_pore(network):
r"""
Calculates throat vector as straight path between connected pores.
Parameters
----------
%(network)s
Returns
-------
unit_vec : ndarray
A [Nt-by-3] numpy ndarray containing pore-to-pore unit vectors
Notes
-----
There is an important impicit assumption here: the positive direction is
taken as the direction from the pore with the lower index to the higher.
This corresponds to the pores in the 1st and 2nd columns of the
'throat.conns' array as stored on the network.
"""
conns = network['throat.conns']
P1 = conns[:, 0]
P2 = conns[:, 1]
coords = network['pore.coords']
vec = coords[P2] - coords[P1]
unit_vec = tr.unit_vector(vec, axis=1)
return unit_vec
|
Calculates throat vector as straight path between connected pores.
Parameters
----------
%(network)s
Returns
-------
unit_vec : ndarray
A [Nt-by-3] numpy ndarray containing pore-to-pore unit vectors
Notes
-----
There is an important impicit assumption here: the positive direction is
taken as the direction from the pore with the lower index to the higher.
This corresponds to the pores in the 1st and 2nd columns of the
'throat.conns' array as stored on the network.
|
pore_to_pore
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/throat_vector/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/throat_vector/_funcs.py
|
MIT
|
def cylinder(
network,
throat_diameter='throat.diameter',
throat_length='throat.length',
):
r"""
Calculate throat volume assuing a cylindrical shape
Parameters
----------
%(network)s
%(Dt)s
%(Lt)s
Returns
-------
volumes : ndarray
A numpy ndarray containing throat volume values
Notes
-----
This models does not account for the volume reprsented by the
intersection of the throat with a spherical pore body. Use the ``lens``
or ``pendular_ring`` models in addition to this one to account for this
volume.
"""
leng = network[throat_length]
diam = network[throat_diameter]
value = _np.pi/4*leng*diam**2
return value
|
Calculate throat volume assuing a cylindrical shape
Parameters
----------
%(network)s
%(Dt)s
%(Lt)s
Returns
-------
volumes : ndarray
A numpy ndarray containing throat volume values
Notes
-----
This models does not account for the volume reprsented by the
intersection of the throat with a spherical pore body. Use the ``lens``
or ``pendular_ring`` models in addition to this one to account for this
volume.
|
cylinder
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/throat_volume/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/throat_volume/_funcs.py
|
MIT
|
def cuboid(
network,
throat_diameter='throat.diameter',
throat_length='throat.length',
):
r"""
Calculate throat volume assuing a square cross-section
Parameters
----------
%(network)s
%(Dt)s
%(Lt)s
Returns
-------
Notes
-----
At present this models does NOT account for the volume reprsented by the
intersection of the throat with a spherical pore body.
"""
leng = network[throat_length]
diam = network[throat_diameter]
value = leng*diam**2
return value
|
Calculate throat volume assuing a square cross-section
Parameters
----------
%(network)s
%(Dt)s
%(Lt)s
Returns
-------
Notes
-----
At present this models does NOT account for the volume reprsented by the
intersection of the throat with a spherical pore body.
|
cuboid
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/throat_volume/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/throat_volume/_funcs.py
|
MIT
|
def rectangle(
network,
throat_diameter='throat.diameter',
throat_length='throat.length',
):
r"""
Calculate throat volume assuing a rectangular shape
Parameters
----------
%(network)s
%(Dt)s
%(Lt)s
Returns
-------
Notes
-----
At present this models does NOT account for the volume reprsented by the
intersection of the throat with a spherical pore body.
"""
return network[throat_length] * network[throat_diameter]
|
Calculate throat volume assuing a rectangular shape
Parameters
----------
%(network)s
%(Dt)s
%(Lt)s
Returns
-------
Notes
-----
At present this models does NOT account for the volume reprsented by the
intersection of the throat with a spherical pore body.
|
rectangle
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/throat_volume/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/throat_volume/_funcs.py
|
MIT
|
def extrusion(
network,
throat_length='throat.length',
throat_area='throat.cross_sectional_area',
):
r"""
Calculate throat volume from the throat area and the throat length. This
method is useful for abnormal shaped throats.
Parameters
----------
%(network)s
%(Lt)s
%(At)s
Returns
-------
Notes
-----
At present this models does NOT account for the volume reprsented by the
intersection of the throat with a spherical pore body.
"""
leng = network[throat_length]
area = network[throat_area]
value = leng*area
return value
|
Calculate throat volume from the throat area and the throat length. This
method is useful for abnormal shaped throats.
Parameters
----------
%(network)s
%(Lt)s
%(At)s
Returns
-------
Notes
-----
At present this models does NOT account for the volume reprsented by the
intersection of the throat with a spherical pore body.
|
extrusion
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/throat_volume/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/throat_volume/_funcs.py
|
MIT
|
def lens(
network,
throat_diameter='throat.diameter',
pore_diameter='pore.diameter',
):
r"""
Calculates the volume residing the hemispherical caps formed by the
intersection between cylindrical throats and spherical pores.
This volume should be subtracted from throat volumes if the throat lengths
were found using throat end points.
Parameters
----------
%(network)s
%(Dt)s
%(Dp)s
Returns
-------
Notes
-----
This model does not consider the possibility that multiple throats might
overlap in the same location which could happen if throats are large and
connectivity is random.
See Also
--------
pendular_ring
"""
conns = network['throat.conns']
Rp = network[pore_diameter]/2
Rt = network[throat_diameter]/2
a = _np.atleast_2d(Rt).T
q = _np.arcsin(a/Rp[conns])
b = Rp[conns]*_np.cos(q)
h = Rp[conns] - b
V = 1/6*_np.pi*h*(3*a**2 + h**2)
return _np.sum(V, axis=1)
|
Calculates the volume residing the hemispherical caps formed by the
intersection between cylindrical throats and spherical pores.
This volume should be subtracted from throat volumes if the throat lengths
were found using throat end points.
Parameters
----------
%(network)s
%(Dt)s
%(Dp)s
Returns
-------
Notes
-----
This model does not consider the possibility that multiple throats might
overlap in the same location which could happen if throats are large and
connectivity is random.
See Also
--------
pendular_ring
|
lens
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/throat_volume/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/throat_volume/_funcs.py
|
MIT
|
def pendular_ring(
network,
throat_diameter='throat.diameter',
pore_diameter='pore.diameter',
):
r"""
Calculates the volume of the pendular rings residing between the end of
a cylindrical throat and spherical pores that are in contact but not
overlapping.
This volume should be added to the throat volume if the throat length was
found as the center-to-center distance less the pore radii.
Parameters
----------
%(network)s
%(Dt)s
%(Dp)s
Returns
-------
Notes
-----
This model does not consider the possibility that multiple throats might
overlap in the same location which could happen if throats are large and
connectivity is random.
See Also
--------
lens
"""
conns = network['throat.conns']
Rp = network[pore_diameter]/2
Rt = network[throat_diameter]/2
a = _np.atleast_2d(Rt).T
q = _np.arcsin(a/Rp[conns])
b = Rp[conns]*_np.cos(q)
h = Rp[conns] - b
Vlens = 1/6*_np.pi*h*(3*a**2 + h**2)
Vcyl = _np.pi*(a)**2*h
V = Vcyl - Vlens
return _np.sum(V, axis=1)
|
Calculates the volume of the pendular rings residing between the end of
a cylindrical throat and spherical pores that are in contact but not
overlapping.
This volume should be added to the throat volume if the throat length was
found as the center-to-center distance less the pore radii.
Parameters
----------
%(network)s
%(Dt)s
%(Dp)s
Returns
-------
Notes
-----
This model does not consider the possibility that multiple throats might
overlap in the same location which could happen if throats are large and
connectivity is random.
See Also
--------
lens
|
pendular_ring
|
python
|
PMEAL/OpenPNM
|
openpnm/models/geometry/throat_volume/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/geometry/throat_volume/_funcs.py
|
MIT
|
def difference(target, props):
r"""
Subtracts elements 1:N in `props` from element 0
Parameters
----------
target : OpenPNM dict
The object to which the model is associated
props : list
A list of dict keys containing the values to operate on. If the first
element is A, and the next are B and C, then the results is A - B - C.
"""
A = target[props[0]]
for B in props[1:]:
A = A - target[B]
return A
|
Subtracts elements 1:N in `props` from element 0
Parameters
----------
target : OpenPNM dict
The object to which the model is associated
props : list
A list of dict keys containing the values to operate on. If the first
element is A, and the next are B and C, then the results is A - B - C.
|
difference
|
python
|
PMEAL/OpenPNM
|
openpnm/models/misc/_basic_math.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/misc/_basic_math.py
|
MIT
|
def fraction(target, numerator, denominator):
r"""
Calculates the ratio between two values
Parameters
----------
target : Base
The object which this model is associated with. This controls the
length of the calculated array, and also provides access to other
necessary properties.
numerator : str
Dictionary key pointing the numerator values
denominator : str
Dictionary key pointing the denominator values
"""
x = target[numerator]
y = target[denominator]
return x/y
|
Calculates the ratio between two values
Parameters
----------
target : Base
The object which this model is associated with. This controls the
length of the calculated array, and also provides access to other
necessary properties.
numerator : str
Dictionary key pointing the numerator values
denominator : str
Dictionary key pointing the denominator values
|
fraction
|
python
|
PMEAL/OpenPNM
|
openpnm/models/misc/_basic_math.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/misc/_basic_math.py
|
MIT
|
def summation(target, props=[]):
r"""
Sums the values in the given arrays
Parameters
----------
target : Base
The object which this model is associated with. This controls the
length of the calculated array, and also provides access to other
necessary properties.
props : list of dictionary keys
The dictionary keys pointing the arrays whose elements should be summed
"""
vals = np.zeros_like(target[props[0]])
for item in props:
vals += target[item]
return vals
|
Sums the values in the given arrays
Parameters
----------
target : Base
The object which this model is associated with. This controls the
length of the calculated array, and also provides access to other
necessary properties.
props : list of dictionary keys
The dictionary keys pointing the arrays whose elements should be summed
|
summation
|
python
|
PMEAL/OpenPNM
|
openpnm/models/misc/_basic_math.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/misc/_basic_math.py
|
MIT
|
def product(target, props):
r"""
Calculates the product of multiple property values
Parameters
----------
target : Base
The object which this model is associated with. This controls the
length of the calculated array, and also provides access to other
necessary properties.
props : list[str]
The name of the arguments to be used for the product.
Returns
-------
value : ndarray
Array containing product values of ``target[props[0]]``,
``target[props[1]]``, etc.
"""
value = np.ones_like(target[props[0]])
for item in props:
value *= target[item]
return value
|
Calculates the product of multiple property values
Parameters
----------
target : Base
The object which this model is associated with. This controls the
length of the calculated array, and also provides access to other
necessary properties.
props : list[str]
The name of the arguments to be used for the product.
Returns
-------
value : ndarray
Array containing product values of ``target[props[0]]``,
``target[props[1]]``, etc.
|
product
|
python
|
PMEAL/OpenPNM
|
openpnm/models/misc/_basic_math.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/misc/_basic_math.py
|
MIT
|
def from_neighbor_throats(target, prop, mode='min', ignore_nans=True):
r"""
Adopt a value from the values found in neighboring throats
Parameters
----------
target : Base
The object which this model is associated with. This controls the
length of the calculated array, and also provides access to other
necessary properties.
prop : str
The dictionary key of the array containing the throat property to be
used in the calculation.
mode : str
Controls how the pore property is calculated. The default value is
'min'. Options are:
=========== =====================================================
mode meaning
=========== =====================================================
'min' Returns the value of the minimum property of the
neighboring throats
'max' Returns the value of the maximum property of the
neighboring throats
'mean' Returns the value of the mean property of the
neighboring throats
'sum' Returns the sum of the property of the neighboring
throats
=========== =====================================================
Returns
-------
value : ndarray
Array containing customized values based on those of adjacent throats.
"""
network = target.network
data = target[prop]
nans = np.isnan(data)
im = network.create_incidence_matrix()
if mode == 'min':
if ignore_nans:
data[nans] = np.inf
values = np.ones((network.Np, ))*np.inf
np.minimum.at(values, im.row, data[im.col])
if mode == 'max':
if ignore_nans:
data[nans] = -np.inf
values = np.ones((network.Np, ))*-np.inf
np.maximum.at(values, im.row, data[im.col])
if mode == 'mean':
if ignore_nans:
data[nans] = 0
values = np.zeros((network.Np, ))
np.add.at(values, im.row, data[im.col])
counts = np.zeros((network.Np, ))
np.add.at(counts, im.row, np.ones((network.Nt, ))[im.col])
if ignore_nans:
np.subtract.at(counts, im.row, nans[im.col])
values = values/counts
if mode == 'sum':
if ignore_nans:
data[nans] = 0
values = np.zeros((network.Np, ))
np.add.at(values, im.row, data[im.col])
return values
|
Adopt a value from the values found in neighboring throats
Parameters
----------
target : Base
The object which this model is associated with. This controls the
length of the calculated array, and also provides access to other
necessary properties.
prop : str
The dictionary key of the array containing the throat property to be
used in the calculation.
mode : str
Controls how the pore property is calculated. The default value is
'min'. Options are:
=========== =====================================================
mode meaning
=========== =====================================================
'min' Returns the value of the minimum property of the
neighboring throats
'max' Returns the value of the maximum property of the
neighboring throats
'mean' Returns the value of the mean property of the
neighboring throats
'sum' Returns the sum of the property of the neighboring
throats
=========== =====================================================
Returns
-------
value : ndarray
Array containing customized values based on those of adjacent throats.
|
from_neighbor_throats
|
python
|
PMEAL/OpenPNM
|
openpnm/models/misc/_neighbor_lookups.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/misc/_neighbor_lookups.py
|
MIT
|
def from_neighbor_pores(target, prop, mode='min', ignore_nans=True):
r"""
Adopt a value based on the values in neighboring pores
Parameters
----------
target : Base
The object which this model is associated with. This controls the
length of the calculated array, and also provides access to other
necessary properties.
prop : str
The dictionary key to the array containing the pore property to be
used in the calculation.
mode : str
Controls how the pore property is calculated. The default value is
'min'. Options are:
=========== =====================================================
mode meaning
=========== =====================================================
'min' Returns the value of the minimum property of the
neighboring pores
'max' Returns the value of the maximum property of the
neighboring pores
'mean' Returns the value of the mean property of the
neighboring pores
'sum' Returns the sum of the property of the neighrboring
pores
=========== =====================================================
ignore_nans : bool (default is ``True``)
If ``True`` the result will ignore ``nans`` in the neighbors
Returns
-------
value : ndarray
Array containing customized values based on those of adjacent pores.
"""
network = target.network
throats = target.Ts
P12 = network.find_connected_pores(throats)
pvalues = target[prop][P12]
if ignore_nans:
pvalues = np.ma.MaskedArray(data=pvalues, mask=np.isnan(pvalues))
try: # If pvalues is not empty
if mode == 'min':
value = np.amin(pvalues, axis=1)
if mode == 'max':
value = np.amax(pvalues, axis=1)
if mode == 'mean':
value = np.mean(pvalues, axis=1)
if mode == 'sum':
value = np.sum(pvalues, axis=1)
except np.AxisError: # Handle case of empty pvalues
value = []
return np.array(value)
|
Adopt a value based on the values in neighboring pores
Parameters
----------
target : Base
The object which this model is associated with. This controls the
length of the calculated array, and also provides access to other
necessary properties.
prop : str
The dictionary key to the array containing the pore property to be
used in the calculation.
mode : str
Controls how the pore property is calculated. The default value is
'min'. Options are:
=========== =====================================================
mode meaning
=========== =====================================================
'min' Returns the value of the minimum property of the
neighboring pores
'max' Returns the value of the maximum property of the
neighboring pores
'mean' Returns the value of the mean property of the
neighboring pores
'sum' Returns the sum of the property of the neighrboring
pores
=========== =====================================================
ignore_nans : bool (default is ``True``)
If ``True`` the result will ignore ``nans`` in the neighbors
Returns
-------
value : ndarray
Array containing customized values based on those of adjacent pores.
|
from_neighbor_pores
|
python
|
PMEAL/OpenPNM
|
openpnm/models/misc/_neighbor_lookups.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/misc/_neighbor_lookups.py
|
MIT
|
def generic_function(target, prop, func, **kwargs):
r"""
Runs an arbitrary function on the given data
This allows users to place a customized calculation into the automatated
model regeneration pipeline.
Parameters
----------
target : Base
The object which this model is associated with. This controls the
length of the calculated array, and also provides access to other
necessary properties.
prop : str
The dictionary key containing the array to be operated on
func : Numpy function
A handle to the function to apply
kwargs : keyward arguments
All arguments required by the specific Numpy function
Returns
-------
result : ndarray
Array containing ``func(target[prop], **kwargs)``.
Examples
--------
The following example shows how to use a Numpy function, but any function
can be used, as long as it returns an array object:
>>> import openpnm as op
>>> import numpy as np
>>> pn = op.network.Cubic(shape=[5, 5, 5])
>>> pn['pore.rand'] = np.random.rand(pn.Np)
>>> pn.add_model(propname='pore.cos',
... model=op.models.misc.generic_function,
... func=np.cos,
... prop='pore.rand')
"""
values = target[prop]
result = func(values, **kwargs)
if not isinstance(result, np.ndarray):
logger.warning('Given function must return a Numpy array')
return result
|
Runs an arbitrary function on the given data
This allows users to place a customized calculation into the automatated
model regeneration pipeline.
Parameters
----------
target : Base
The object which this model is associated with. This controls the
length of the calculated array, and also provides access to other
necessary properties.
prop : str
The dictionary key containing the array to be operated on
func : Numpy function
A handle to the function to apply
kwargs : keyward arguments
All arguments required by the specific Numpy function
Returns
-------
result : ndarray
Array containing ``func(target[prop], **kwargs)``.
Examples
--------
The following example shows how to use a Numpy function, but any function
can be used, as long as it returns an array object:
>>> import openpnm as op
>>> import numpy as np
>>> pn = op.network.Cubic(shape=[5, 5, 5])
>>> pn['pore.rand'] = np.random.rand(pn.Np)
>>> pn.add_model(propname='pore.cos',
... model=op.models.misc.generic_function,
... func=np.cos,
... prop='pore.rand')
|
generic_function
|
python
|
PMEAL/OpenPNM
|
openpnm/models/misc/_simple_equations.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/misc/_simple_equations.py
|
MIT
|
def linear(target, m, b, prop):
r"""
Calculates a property as a linear function of a given property
Parameters
----------
target : Base
The object for which these values are being calculated. This
controls the length of the calculated array, and also provides
access to other necessary thermofluid properties.
m, b : floats
Slope and intercept of the linear corelation
prop : str
The dictionary key containing the independent variable or phase
property to be used in the correlation.
Returns
-------
value : ndarray
Array containing ``m * target[prop] + b``.
"""
x = target[prop]
value = m*x + b
return value
|
Calculates a property as a linear function of a given property
Parameters
----------
target : Base
The object for which these values are being calculated. This
controls the length of the calculated array, and also provides
access to other necessary thermofluid properties.
m, b : floats
Slope and intercept of the linear corelation
prop : str
The dictionary key containing the independent variable or phase
property to be used in the correlation.
Returns
-------
value : ndarray
Array containing ``m * target[prop] + b``.
|
linear
|
python
|
PMEAL/OpenPNM
|
openpnm/models/misc/_simple_equations.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/misc/_simple_equations.py
|
MIT
|
def polynomial(target, a, prop):
r"""
Calculates a property as a polynomial function of a given property
Parameters
----------
target : Base
The object for which these values are being calculated. This
controls the length of the calculated array, and also provides
access to other necessary thermofluid properties.
a : array_like
A list containing the polynomial coefficients, where element 0 in the
list corresponds to a0 and so on. Note that no entries can be skipped
so 0 coefficients must be sent as 0.
prop : str
The dictionary key containing the independent variable or phase
property to be used in the polynomial.
Returns
-------
value : ndarray
Array containing ``Pn(target[prop])``, where ``Pn`` is nth order
polynomial with coefficients stored in ``a``.
"""
x = target[prop].astype(float)
value = 0.0
for i in range(0, len(a)):
value += a[i]*(x**i)
return value
|
Calculates a property as a polynomial function of a given property
Parameters
----------
target : Base
The object for which these values are being calculated. This
controls the length of the calculated array, and also provides
access to other necessary thermofluid properties.
a : array_like
A list containing the polynomial coefficients, where element 0 in the
list corresponds to a0 and so on. Note that no entries can be skipped
so 0 coefficients must be sent as 0.
prop : str
The dictionary key containing the independent variable or phase
property to be used in the polynomial.
Returns
-------
value : ndarray
Array containing ``Pn(target[prop])``, where ``Pn`` is nth order
polynomial with coefficients stored in ``a``.
|
polynomial
|
python
|
PMEAL/OpenPNM
|
openpnm/models/misc/_simple_equations.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/misc/_simple_equations.py
|
MIT
|
def weibull(network, seeds, shape, scale, loc):
r"""
Produces values from a Weibull distribution given a set of random numbers.
Parameters
----------
%(network)s
seeds : str (dict key)
%(dict_blurb) seed
shape : float
Controls the width or skewness of the distribution. For more
information on the effect of this parameter refer to the
corresponding `scipy.stats function
<https://docs.scipy.org/doc/scipy/reference/stats.html>`_.
scale : float
Controls the width of the distribution. For more information on
the effect of this parameter refer to the corresponding
scipy.stats function.
loc : float
Specifies the central value of ???
Returns
-------
values : ndndarray
A numpy ndarray containing values following the distribution
Examples
--------
The following code illustrates the inner workings of this function,
which uses the 'weibull_min' method of the scipy.stats module. This can
be used to find suitable values of 'shape', 'scale'` and 'loc'. Note that
'shape' is represented by 'c' in the actual function call.
.. plot::
import numpy
import scipy.stats
import matplotlib.pyplot as plt
func = scipy.stats.weibull_min(c=1.5, scale=0.0001, loc=0)
plt.hist(func.ppf(q=numpy.random.rand(10000)), bins=50)
plt.show()
"""
seeds = network[seeds]
value = spts.weibull_min.ppf(q=seeds, c=shape, scale=scale, loc=loc)
return value
|
Produces values from a Weibull distribution given a set of random numbers.
Parameters
----------
%(network)s
seeds : str (dict key)
%(dict_blurb) seed
shape : float
Controls the width or skewness of the distribution. For more
information on the effect of this parameter refer to the
corresponding `scipy.stats function
<https://docs.scipy.org/doc/scipy/reference/stats.html>`_.
scale : float
Controls the width of the distribution. For more information on
the effect of this parameter refer to the corresponding
scipy.stats function.
loc : float
Specifies the central value of ???
Returns
-------
values : ndndarray
A numpy ndarray containing values following the distribution
Examples
--------
The following code illustrates the inner workings of this function,
which uses the 'weibull_min' method of the scipy.stats module. This can
be used to find suitable values of 'shape', 'scale'` and 'loc'. Note that
'shape' is represented by 'c' in the actual function call.
.. plot::
import numpy
import scipy.stats
import matplotlib.pyplot as plt
func = scipy.stats.weibull_min(c=1.5, scale=0.0001, loc=0)
plt.hist(func.ppf(q=numpy.random.rand(10000)), bins=50)
plt.show()
|
weibull
|
python
|
PMEAL/OpenPNM
|
openpnm/models/misc/_statistical_distributions.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/misc/_statistical_distributions.py
|
MIT
|
def normal(network, seeds, mean=None, stddev=None, scale=None, loc=None):
r"""
Produces values from a Weibull distribution given a set of random numbers.
Parameters
----------
%(network)s
seeds : str (dict key)
%(dict_blurb) seed
mean : float
The mean value of the distribution. This is referred to as the
``loc`` in the scipy.stats function, and this key word is also
accepted.
stddev : float
The standard deviation of the distribution. This is referred to as
the ``scale`` in the scipy.stats function, and this key word is also
accepted.
Returns
-------
Examples
--------
The following code illustrates the inner workings of this function,
which uses the 'norm' method of the scipy.stats module. This can
be used to find suitable values of 'scale' and 'loc'.
.. plot::
import numpy
import scipy.stats
import matplotlib.pyplot as plt
func = scipy.stats.norm(scale=.0001, loc=0.001)
fig = plt.hist(func.ppf(q=numpy.random.rand(10000)), bins=50)
plt.show()
"""
scale = stddev if stddev is not None else scale
loc = mean if mean is not None else loc
seeds = network[seeds]
value = spts.norm.ppf(q=seeds, scale=scale, loc=loc)
return value
|
Produces values from a Weibull distribution given a set of random numbers.
Parameters
----------
%(network)s
seeds : str (dict key)
%(dict_blurb) seed
mean : float
The mean value of the distribution. This is referred to as the
``loc`` in the scipy.stats function, and this key word is also
accepted.
stddev : float
The standard deviation of the distribution. This is referred to as
the ``scale`` in the scipy.stats function, and this key word is also
accepted.
Returns
-------
Examples
--------
The following code illustrates the inner workings of this function,
which uses the 'norm' method of the scipy.stats module. This can
be used to find suitable values of 'scale' and 'loc'.
.. plot::
import numpy
import scipy.stats
import matplotlib.pyplot as plt
func = scipy.stats.norm(scale=.0001, loc=0.001)
fig = plt.hist(func.ppf(q=numpy.random.rand(10000)), bins=50)
plt.show()
|
normal
|
python
|
PMEAL/OpenPNM
|
openpnm/models/misc/_statistical_distributions.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/misc/_statistical_distributions.py
|
MIT
|
def generic_distribution(network, seeds, func, **kwargs):
r"""
Accepts an object from the Scipy.stats submodule and returns
values from the distribution for the given seeds
Parameters
----------
%(network)s
seeds : str (dict key)
%(dict_blurb) seed
func : object
An object from the scipy.stats library. Can be a 'frozen' object, where all
the parameters were specified upon creation, or a handle to an unintialized
object. In the latter case the parameters for the distribution should be
provided as keyword arguments.
Returns
-------
values : ndarray
An ndarray of either Np or Nt length, with values taken from the supplied
distribution.
Examples
--------
The following code illustrates the process of obtaining a 'frozen' Scipy
stats object and adding it as a model:
.. plot::
import numpy
import scipy.stats
import openpnm as op
import matplotlib.pyplot as plt
pn = op.network.Cubic(shape=[3, 3, 3])
pn.add_model(propname='pore.seed',
model=op.models.geometry.pore_seed.random)
# Now retrieve the stats distribution and add to ``geo`` as a model
stats_obj = scipy.stats.weibull_min(c=2, scale=.0001, loc=0)
pn.add_model(propname='pore.size',
model=op.models.geometry.pore_size.generic_distribution,
seeds='pore.seed',
func=stats_obj)
plt.hist(stats_obj.ppf(q=numpy.random.rand(1000)), bins=50)
plt.show()
"""
if hasattr(func, 'freeze'):
func = func.freeze(**kwargs)
seeds = network[seeds]
value = func.ppf(seeds)
return value
|
Accepts an object from the Scipy.stats submodule and returns
values from the distribution for the given seeds
Parameters
----------
%(network)s
seeds : str (dict key)
%(dict_blurb) seed
func : object
An object from the scipy.stats library. Can be a 'frozen' object, where all
the parameters were specified upon creation, or a handle to an unintialized
object. In the latter case the parameters for the distribution should be
provided as keyword arguments.
Returns
-------
values : ndarray
An ndarray of either Np or Nt length, with values taken from the supplied
distribution.
Examples
--------
The following code illustrates the process of obtaining a 'frozen' Scipy
stats object and adding it as a model:
.. plot::
import numpy
import scipy.stats
import openpnm as op
import matplotlib.pyplot as plt
pn = op.network.Cubic(shape=[3, 3, 3])
pn.add_model(propname='pore.seed',
model=op.models.geometry.pore_seed.random)
# Now retrieve the stats distribution and add to ``geo`` as a model
stats_obj = scipy.stats.weibull_min(c=2, scale=.0001, loc=0)
pn.add_model(propname='pore.size',
model=op.models.geometry.pore_size.generic_distribution,
seeds='pore.seed',
func=stats_obj)
plt.hist(stats_obj.ppf(q=numpy.random.rand(1000)), bins=50)
plt.show()
|
generic_distribution
|
python
|
PMEAL/OpenPNM
|
openpnm/models/misc/_statistical_distributions.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/misc/_statistical_distributions.py
|
MIT
|
def random(network, element, seed=None, num_range=[0, 1]):
r"""
Create an array of random numbers of a specified size.
Parameters
----------
%(network)s
seed : int
The starting seed value to sent to numpy's random number generator.
A value of ``None`` means a different distribution is returned each
time the model is (re)run.
num_range : list
A two element list indicating the low and high end of the returned
numbers. The default is ``[0, 1]``, but a value of ``[0.1, 0.9]``
may be useful if these values are to be used in subsequent
distributions to prevent generating extreme values in the tails.
Returns
-------
"""
range_size = num_range[1] - num_range[0]
range_min = num_range[0]
if seed is not None:
np.random.seed(seed)
value = np.random.rand(network._count(element),)
value = value*range_size + range_min
return value
|
Create an array of random numbers of a specified size.
Parameters
----------
%(network)s
seed : int
The starting seed value to sent to numpy's random number generator.
A value of ``None`` means a different distribution is returned each
time the model is (re)run.
num_range : list
A two element list indicating the low and high end of the returned
numbers. The default is ``[0, 1]``, but a value of ``[0.1, 0.9]``
may be useful if these values are to be used in subsequent
distributions to prevent generating extreme values in the tails.
Returns
-------
|
random
|
python
|
PMEAL/OpenPNM
|
openpnm/models/misc/_statistical_distributions.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/misc/_statistical_distributions.py
|
MIT
|
def match_histogram(network, bin_centers, bin_heights, element='pore'):
r"""
Generate values corresponding to a given histogram
Parameters
----------
%(network)s
bin_centers : array_like
The x-axis of the histogram, such as pore sizes.
bin_heights : array_like
The y-axis of the histogram, such as the number of pores of each size.
element : str
Controls how many values to generate. Can either be 'pore' or 'throat'.
Returns
-------
values : ndarray
Values corresponding to ``bin_centers`` generated in proportion to the
respective ``bin_heights``.
"""
N = network._count(element)
h = np.cumsum(bin_heights)
b = np.digitize(np.random.rand(N)*np.amax(h), bins=h)
vals = np.array(bin_centers)[b]
return vals
|
Generate values corresponding to a given histogram
Parameters
----------
%(network)s
bin_centers : array_like
The x-axis of the histogram, such as pore sizes.
bin_heights : array_like
The y-axis of the histogram, such as the number of pores of each size.
element : str
Controls how many values to generate. Can either be 'pore' or 'throat'.
Returns
-------
values : ndarray
Values corresponding to ``bin_centers`` generated in proportion to the
respective ``bin_heights``.
|
match_histogram
|
python
|
PMEAL/OpenPNM
|
openpnm/models/misc/_statistical_distributions.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/misc/_statistical_distributions.py
|
MIT
|
def cluster_number(network):
r"""
Assign a cluster number to each pore
"""
from scipy.sparse import csgraph as csg
am = network.create_adjacency_matrix(fmt='coo', triu=True)
N, Cs = csg.connected_components(am, directed=False)
return Cs
|
Assign a cluster number to each pore
|
cluster_number
|
python
|
PMEAL/OpenPNM
|
openpnm/models/network/_health.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/network/_health.py
|
MIT
|
def cluster_size(network, cluster=None):
r"""
Find the size of the cluster to which each pore belongs
Parameters
----------
network : dict
The Network
cluster : str, optional
Dict key pointing to the array containing the cluster number of each
pore. If not provided then it will be calculated.
Returns
-------
cluster_size : ndarray
An Np-long array containing the size of the cluster to which each pore
belongs
"""
if cluster is None:
from scipy.sparse import csgraph as csg
am = network.create_adjacency_matrix(fmt='coo', triu=True)
N, cluster_num = csg.connected_components(am, directed=False)
else:
cluster_num = network[cluster]
Cs, ind, N = np.unique(cluster_num, return_inverse=True, return_counts=True)
values = N[ind]
return values
|
Find the size of the cluster to which each pore belongs
Parameters
----------
network : dict
The Network
cluster : str, optional
Dict key pointing to the array containing the cluster number of each
pore. If not provided then it will be calculated.
Returns
-------
cluster_size : ndarray
An Np-long array containing the size of the cluster to which each pore
belongs
|
cluster_size
|
python
|
PMEAL/OpenPNM
|
openpnm/models/network/_health.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/network/_health.py
|
MIT
|
def isolated_pores(network):
r"""
Find which pores, if any, are not connected to a throat
"""
values = np.ones(network.Np, dtype=bool)
hits = np.unique(network.conns)
if np.any(hits >= network.Np):
logger.warning("Some throats point to non-existent pores")
hits = hits[hits < network.Np]
values[hits] = False
return values
|
Find which pores, if any, are not connected to a throat
|
isolated_pores
|
python
|
PMEAL/OpenPNM
|
openpnm/models/network/_health.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/network/_health.py
|
MIT
|
def count_coincident_pores(network, thresh=1e-6):
r"""
Count number of pores that are spatially coincident with other pores
Parameters
----------
network : dict
The Network
thresh : float
The distance below which two pores are considered spatially coincident
Returns
-------
count : ndarray
A numpy array of Np length containing the number of coincident pores
"""
# This needs to be a bit complicated because it cannot be assumed
# the coincident pores are topologically connected
import scipy.spatial as sptl
coords = network.coords
tree = sptl.KDTree(coords)
hits = tree.query_pairs(r=thresh)
arr = np.array(list(hits)).flatten()
v, n = np.unique(arr, return_counts=True)
values = np.zeros(network.Np, dtype=int)
values[v.astype(int)] = n
return values
|
Count number of pores that are spatially coincident with other pores
Parameters
----------
network : dict
The Network
thresh : float
The distance below which two pores are considered spatially coincident
Returns
-------
count : ndarray
A numpy array of Np length containing the number of coincident pores
|
count_coincident_pores
|
python
|
PMEAL/OpenPNM
|
openpnm/models/network/_health.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/network/_health.py
|
MIT
|
def find_coincident_pores(network, thresh=1e-6):
r"""
Find the indices of coincident pores
Parameters
----------
network : dict
The Network
thresh : float
The distance below which two pores are considered spatially coincident
Returns
-------
indices : list of lists
One row corresponding to each pore, with each row listing the indices
of any coincident pores. An empty list means no pores were found
within a distance of ``thresh``.
"""
# This needs to be a bit complicated because it cannot be assumed
# the coincident pores are topologically connected
import scipy.spatial as sptl
coords = network['pore.coords']
tree = sptl.KDTree(coords)
a = tree.sparse_distance_matrix(tree, max_distance=thresh,
output_type='coo_matrix')
a.data += 1.0
a.setdiag(0)
a.eliminate_zeros()
a.data -= 1.0
a = a.tolil()
return a.rows
|
Find the indices of coincident pores
Parameters
----------
network : dict
The Network
thresh : float
The distance below which two pores are considered spatially coincident
Returns
-------
indices : list of lists
One row corresponding to each pore, with each row listing the indices
of any coincident pores. An empty list means no pores were found
within a distance of ``thresh``.
|
find_coincident_pores
|
python
|
PMEAL/OpenPNM
|
openpnm/models/network/_health.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/network/_health.py
|
MIT
|
def gabriel_edges(network):
r"""
Find throats which make a Gabriel subgraph
Returns
-------
throats : ndarray
An ndarray of boolean values with ``True`` indicating that a throat
satisfies the conditions of Gabriel graph, meaning that a circle (or
sphere) can be drawn between its two connected pores that does not
contain any other pores.
Notes
-----
Technically this should only be used on a Delaunay network, but it will
work on any graph. By deleting all throats that are *not* identified by
this fuction one would obtain the Gabriel graph [1].
References
----------
[1] `Wikipedia <https://en.wikipedia.org/wiki/Gabriel_graph>`_
"""
dn = network
# Find centroid or midpoint of each edge in conns
c = dn['pore.coords'][dn['throat.conns']]
m = (c[:, 0, :] + c[:, 1, :])/2
# Find the radius the sphere between each pair of nodes
r = np.sqrt(np.sum((c[:, 0, :] - c[:, 1, :])**2, axis=1))/2
# Use the kd-tree function in Scipy's spatial module
tree = sptl.cKDTree(dn['pore.coords'])
# Find the nearest point for each midpoint
n = tree.query(x=m, k=1)[0]
# If nearest point to m is at distance r, then the edge is a Gabriel edge
g = n >= r*(0.999) # This factor avoids precision errors in the distances
return g
|
Find throats which make a Gabriel subgraph
Returns
-------
throats : ndarray
An ndarray of boolean values with ``True`` indicating that a throat
satisfies the conditions of Gabriel graph, meaning that a circle (or
sphere) can be drawn between its two connected pores that does not
contain any other pores.
Notes
-----
Technically this should only be used on a Delaunay network, but it will
work on any graph. By deleting all throats that are *not* identified by
this fuction one would obtain the Gabriel graph [1].
References
----------
[1] `Wikipedia <https://en.wikipedia.org/wiki/Gabriel_graph>`_
|
gabriel_edges
|
python
|
PMEAL/OpenPNM
|
openpnm/models/network/_topology.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/network/_topology.py
|
MIT
|
def pore_to_pore_distance(network):
r"""
Find the center to center distance between each pair of pores
"""
cn = network['throat.conns']
C1 = network['pore.coords'][cn[:, 0]]
C2 = network['pore.coords'][cn[:, 1]]
values = norm(C1 - C2, axis=1)
return values
|
Find the center to center distance between each pair of pores
|
pore_to_pore_distance
|
python
|
PMEAL/OpenPNM
|
openpnm/models/network/_topology.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/network/_topology.py
|
MIT
|
def distance_to_nearest_neighbor(network):
r"""
Find the distance between each pore and its closest topological neighbor
"""
cn = network['throat.conns']
C1 = network['pore.coords'][cn[:, 0]]
C2 = network['pore.coords'][cn[:, 1]]
D = norm(C1 - C2, axis=1)
im = network.create_incidence_matrix()
values = np.ones((network.Np, ))*np.inf
np.minimum.at(values, im.row, D[im.col])
return np.array(values)
|
Find the distance between each pore and its closest topological neighbor
|
distance_to_nearest_neighbor
|
python
|
PMEAL/OpenPNM
|
openpnm/models/network/_topology.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/network/_topology.py
|
MIT
|
def distance_to_furthest_neighbor(network):
r"""
Find the distance between each pore and its furthest topological neighbor
"""
throats = network.throats(network.name)
cn = network['throat.conns'][throats]
C1 = network['pore.coords'][cn[:, 0]]
C2 = network['pore.coords'][cn[:, 1]]
D = norm(C1 - C2, axis=1)
im = network.create_incidence_matrix()
values = np.zeros((network.Np, ))
np.maximum.at(values, im.row, D[im.col])
return np.array(values)
|
Find the distance between each pore and its furthest topological neighbor
|
distance_to_furthest_neighbor
|
python
|
PMEAL/OpenPNM
|
openpnm/models/network/_topology.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/network/_topology.py
|
MIT
|
def distance_to_nearest_pore(network):
r"""
Find distance to and index of nearest pore even if not topologically
connected
"""
import scipy.spatial as sptl
coords = network.coords
tree = sptl.KDTree(coords)
ds, ids = tree.query(coords, k=2)
values = ds[:, 1]
return values
|
Find distance to and index of nearest pore even if not topologically
connected
|
distance_to_nearest_pore
|
python
|
PMEAL/OpenPNM
|
openpnm/models/network/_topology.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/network/_topology.py
|
MIT
|
def chemicals_wrapper(phase, f, **kwargs):
r"""
Wrapper function for calling models in the ``chemicals`` package
Parameters
----------
phase : dict
The OpenPNM Species object for which this model should calculate
values. This object should ideally have all the necessary chemical
properties in its ``params`` attribute, although this is optional as
discussed below in relation to ``kwargs``.
f : function
The handle of the function to apply, such as
``chemicals.viscosity.Letsou_Stiel``.
kwargs
By default this function will use
``openpnm.models.phase.default_argmap`` to determine which names on
``phase`` correspond to each argument required by ``f``. For
instance, ``default_argmap['Tc'] = 'param.critical_temperature'``
so any functions that need ``Tc`` will receive
``phase['param.critical_temperature']``. Some models only require
the normal thermodynamic parameters, like ``T``, ``Tc``, and ``Pc``,
so in many cases no additional arguments are needed beyond whats in the
default argument map. However, other models require values that are
themselves calcualted by another model, like ``Cvm``, or perhaps a
list of constants like ``a0``, ``a1``, etc. It is necessary to provide
these as keyword arguments, and they will be included in
``default_argmap`` as new entries or overwriting existing ones.
So ``mu='pore.blah'`` will pass ``phase['pore.blah']`` to the
``mu`` argument of ``f``. Any arguments ending with an ``s`` are
assumed to refer to the individual properties of pure components in a
mixture. So ``mus`` means fetch the viscosity of each component as a
list, like ``[1.3e-5, 1.9e-5]``. This function will trim the trailing
``s`` off any argument name before checking the ``default_argmap`` so
that the normal pure component values can be looked up.
Notes
-----
This wrapper works with both pure and mixture phases, but the mixture
models are very slow due to the way ``chemicals`` vectorizes code. For pure
species it allows the computation of values at many different conditions
in a vectorized way. The means that the conditions in each pore, such as
temperature, pressure, etc can be passed and iterpreted as a list of
conditions. For mixture models, however, the vectorization is done over
the compositions, at a *fixed* condition. This means that we must do a
pure-python for-loop (ie. slow) for each individual pore. As such, we
have re-implemented several of the most useful mixing models offered by
``chemicals`` in ``OpenPNM``, and include unit tests to ensure both
implementations agree.
"""
import chemicals as _chemicals
# Update default argmap with any user supplied values
argmap = default_argmap.copy()
for k, v in kwargs.items():
argmap[k] = v
args = _get_items_from_target(phase, f, argmap)
# f = getattr(_chemicals.numba_vectorized, f.__name__)
msg = f"Numba version failed for {f.__name__}, reverting to pure python"
if len(set(['xs', 'yz', 'zs']).intersection(args.keys())):
# Call function in for-loop for each pore since they are not vectorized
logger.info(msg)
vals = _np.zeros(phase.Np)
for pore in phase.Ps:
a = {}
for item in args.keys():
if item.endswith('s'):
try:
a[item] = [args[item][i][pore] for i in range(len(args[item]))]
except TypeError:
a[item] = args[item]
else:
a[item] = args[item][pore]
vals[pore] = f(*list(a.values()))
else:
try:
# Get the numba vectorized version of f, or else numpy arrays don't work
f = getattr(_chemicals.numba_vectorized, f.__name__)
vals = f(*args.values())
except AssertionError:
f = getattr(_chemicals, f.__name__)
vals = f(*args.values())
logger.warn(msg)
return vals
|
Wrapper function for calling models in the ``chemicals`` package
Parameters
----------
phase : dict
The OpenPNM Species object for which this model should calculate
values. This object should ideally have all the necessary chemical
properties in its ``params`` attribute, although this is optional as
discussed below in relation to ``kwargs``.
f : function
The handle of the function to apply, such as
``chemicals.viscosity.Letsou_Stiel``.
kwargs
By default this function will use
``openpnm.models.phase.default_argmap`` to determine which names on
``phase`` correspond to each argument required by ``f``. For
instance, ``default_argmap['Tc'] = 'param.critical_temperature'``
so any functions that need ``Tc`` will receive
``phase['param.critical_temperature']``. Some models only require
the normal thermodynamic parameters, like ``T``, ``Tc``, and ``Pc``,
so in many cases no additional arguments are needed beyond whats in the
default argument map. However, other models require values that are
themselves calcualted by another model, like ``Cvm``, or perhaps a
list of constants like ``a0``, ``a1``, etc. It is necessary to provide
these as keyword arguments, and they will be included in
``default_argmap`` as new entries or overwriting existing ones.
So ``mu='pore.blah'`` will pass ``phase['pore.blah']`` to the
``mu`` argument of ``f``. Any arguments ending with an ``s`` are
assumed to refer to the individual properties of pure components in a
mixture. So ``mus`` means fetch the viscosity of each component as a
list, like ``[1.3e-5, 1.9e-5]``. This function will trim the trailing
``s`` off any argument name before checking the ``default_argmap`` so
that the normal pure component values can be looked up.
Notes
-----
This wrapper works with both pure and mixture phases, but the mixture
models are very slow due to the way ``chemicals`` vectorizes code. For pure
species it allows the computation of values at many different conditions
in a vectorized way. The means that the conditions in each pore, such as
temperature, pressure, etc can be passed and iterpreted as a list of
conditions. For mixture models, however, the vectorization is done over
the compositions, at a *fixed* condition. This means that we must do a
pure-python for-loop (ie. slow) for each individual pore. As such, we
have re-implemented several of the most useful mixing models offered by
``chemicals`` in ``OpenPNM``, and include unit tests to ensure both
implementations agree.
|
chemicals_wrapper
|
python
|
PMEAL/OpenPNM
|
openpnm/models/phase/__init__.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/phase/__init__.py
|
MIT
|
def liquid_mixture_Vc_XXX(
phase,
Vcs='pore.critical_volume.*',
): # pragma: no cover
r"""
Calculates the critical volume of a liquid mixture using the correlation
in [1]_
Parameters
----------
%(phase)s
%(Vcs)s
Returns
-------
References
----------
.. [1] tbd
"""
raise NotImplementedError("This function is not ready yet")
xs = phase['pore.mole_fraction']
Vcs = phase.get_comp_vals(Vcs)
N = len(xs) # Number of components
Vm1 = np.sum([xs[i]*Vcs[i] for i in range(N)], axis=0)
Vm2 = np.sum([xs[i]*(Vcs[i])**(2/3) for i in range(N)], axis=0)
Vm3 = np.sum([xs[i]*(Vcs[i])**(1/3) for i in range(N)], axis=0)
Vm = 0.25*(Vm1 + 3*(Vm2*Vm3))
return Vm
|
Calculates the critical volume of a liquid mixture using the correlation
in [1]_
Parameters
----------
%(phase)s
%(Vcs)s
Returns
-------
References
----------
.. [1] tbd
|
liquid_mixture_Vc_XXX
|
python
|
PMEAL/OpenPNM
|
openpnm/models/phase/critical_props/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/phase/critical_props/_funcs.py
|
MIT
|
def liquid_mixture_Tc_XXX(
phase,
Vm='pore.molar_volume',
Vcs='pore.critical_volume.*',
Tcs='pore.critical_temperature.*',
): # pragma: no cover
r"""
Calculates the critical temperature of a liquid mixture using the
correlation in [1]_
Parameters
----------
%(phase)s
%(Vm)s
%(Vcs)s
%(Tcs)s
Returns
-------
References
----------
.. [1] tbd
"""
raise NotImplementedError("This function is not ready yet")
xs = phase['pore.mole_fraction']
Tcs = phase.get_comp_vals(Tcs)
Vcs = phase.get_comp_vals(Vcs)
Vm = phase[Vm]
N = len(xs) # Number of components
num = np.zeros_like(xs[0])
for i in range(N):
for j in range(N):
VT = (Vcs[i]*Tcs[i]*Vcs[j]*Tcs[j])**0.5
num += xs[i]*xs[j]*VT
Tcm = num/Vm
return Tcm
|
Calculates the critical temperature of a liquid mixture using the
correlation in [1]_
Parameters
----------
%(phase)s
%(Vm)s
%(Vcs)s
%(Tcs)s
Returns
-------
References
----------
.. [1] tbd
|
liquid_mixture_Tc_XXX
|
python
|
PMEAL/OpenPNM
|
openpnm/models/phase/critical_props/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/phase/critical_props/_funcs.py
|
MIT
|
def liquid_mixture_acentric_factor_XXX(
phase,
omegas='param.acentric_factor.*',
): # pragma: no cover
r"""
Calculates the accentric factor of a liquid mixture using the correlation
in [1]_
Parameters
----------
%(phase)s
%(omegas)s
Returns
-------
References
----------
.. [1] tbd
"""
raise NotImplementedError("This function is not ready yet")
xs = phase['pore.mole_fraction']
omegas = phase.get_comp_vals(omegas)
omega = np.sum([omegas[i]*xs[i] for i in range(len(xs))], axis=0)
return omega
|
Calculates the accentric factor of a liquid mixture using the correlation
in [1]_
Parameters
----------
%(phase)s
%(omegas)s
Returns
-------
References
----------
.. [1] tbd
|
liquid_mixture_acentric_factor_XXX
|
python
|
PMEAL/OpenPNM
|
openpnm/models/phase/critical_props/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/phase/critical_props/_funcs.py
|
MIT
|
def ideal_gas(
phase,
P='pore.pressure',
T='pore.temperature',
MW='param.molecular_weight',
):
r"""
Uses ideal gas law to calculate the mass density of an ideal gas
Parameters
----------
%(phase)s
%(T)s
%(P)s
%(MW)s
Returns
-------
"""
P = phase[P]
T = phase[T]
try:
# If phase is a pure species, it should have molecular weight in params
MW = phase[MW]
except KeyError:
# Otherwise, get the mole weighted average value
MW = phase.get_mix_vals(MW)
R = 8.314462618 # J/(mol.K)
value = P/(R*T)*(MW/1000) # Convert to kg/m3
return value
|
Uses ideal gas law to calculate the mass density of an ideal gas
Parameters
----------
%(phase)s
%(T)s
%(P)s
%(MW)s
Returns
-------
|
ideal_gas
|
python
|
PMEAL/OpenPNM
|
openpnm/models/phase/density/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/phase/density/_funcs.py
|
MIT
|
def water_correlation(
phase,
T='pore.temperature',
salinity='pore.salinity',
):
r"""
Calculates density of pure water or seawater at atmospheric pressure
using Eq. (8) given by Sharqawy et. al [1]. Values at temperature higher
than the normal boiling temperature are calculated at the saturation
pressure.
Parameters
----------
%(phase)s
%(T)s
%(salinity)s
Returns
-------
Notes
-----
``T`` must be in K, and ``salinity`` in g of salt per kg of phase, or
ppt (parts per thousand)
VALIDITY: 273 < T < 453 K; 0 < S < 160 g/kg;
ACCURACY: 0.1 pct
References
----------
[1] Sharqawy M. H., Lienhard J. H., and Zubair, S. M., Desalination and
Water Treatment, 2010.
"""
T = phase[T]
if salinity in phase.keys():
S = phase[salinity]
else:
S = 0
a1 = 9.9992293295E+02
a2 = 2.0341179217E-02
a3 = -6.1624591598E-03
a4 = 2.2614664708E-05
a5 = -4.6570659168E-08
b1 = 8.0200240891E-01
b2 = -2.0005183488E-03
b3 = 1.6771024982E-05
b4 = -3.0600536746E-08
b5 = -1.6132224742E-11
TC = T-273.15
rho_w = a1 + a2*TC + a3*TC**2 + a4*TC**3 + a5*TC**4
d_rho = b1*S + b2*S*TC + b3*S*(TC**2) + b4*S*(TC**3) + b5*(S**2)*(TC**2)
rho_sw = rho_w + d_rho
value = rho_sw
return value
|
Calculates density of pure water or seawater at atmospheric pressure
using Eq. (8) given by Sharqawy et. al [1]. Values at temperature higher
than the normal boiling temperature are calculated at the saturation
pressure.
Parameters
----------
%(phase)s
%(T)s
%(salinity)s
Returns
-------
Notes
-----
``T`` must be in K, and ``salinity`` in g of salt per kg of phase, or
ppt (parts per thousand)
VALIDITY: 273 < T < 453 K; 0 < S < 160 g/kg;
ACCURACY: 0.1 pct
References
----------
[1] Sharqawy M. H., Lienhard J. H., and Zubair, S. M., Desalination and
Water Treatment, 2010.
|
water_correlation
|
python
|
PMEAL/OpenPNM
|
openpnm/models/phase/density/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/phase/density/_funcs.py
|
MIT
|
def liquid_mixture_COSTALD(
phase,
T='pore.temperature',
MWs='param.molecular_weight.*',
Tcs='param.critical_temperature.*',
Vcs='param.critical_volume.*',
omegas='param.acentric_factor.*',
):
r"""
Computes the density of a liquid mixture using the COrrospoding STAtes
Liquid Density (COSTALD) method.
Parameters
----------
%(phase)s
%(T)s
%(MWs)s
%(Tcs)s
%(Vcs)s
%(omegas)s
Returns
-------
density : ndarray
The density of the liquid mixture in units of kg/m3. Note that
``chemicals.volume.COSTALD`` returns molar volume, so this function
converts it to density using the mole fraction weighted molecular
weight of the mixture: :math:`MW_{mix} = \Sigma x_i \cdot MW_i`.
Notes
-----
This is same approach used by ``chemicals.volume.COSTALD_mixture`` and
exact numerical correspondance is confirmed. Unlike the ``chemicals``
version, this function is vectorized over the conditions rather than
the compositions, since a typical simulation has millions of pores each
representing an independent conditions, but a mixture typically only has
a few components.
"""
# Fetch parameters for each pure component
Tcs = phase.get_comp_vals(Tcs)
Vcs = phase.get_comp_vals(Vcs)
omegas = phase.get_comp_vals(omegas)
Xs = phase['pore.mole_fraction']
# Compute mixture values
omegam = np.vstack([Xs[k]*omegas[k] for k in Xs.keys()]).sum(axis=0)
Vm1 = np.vstack([Xs[k]*Vcs[k] for k in Xs.keys()]).sum(axis=0)
Vm2 = np.vstack([Xs[k]*(Vcs[k])**(2/3) for k in Xs.keys()]).sum(axis=0)
Vm3 = np.vstack([Xs[k]*(Vcs[k])**(1/3) for k in Xs.keys()]).sum(axis=0)
Vm = 0.25*(Vm1 + 3*Vm2*Vm3)
Tcm = 0.0
for i, ki in enumerate(Xs.keys()):
inner = 0.0
for j, kj in enumerate(Xs.keys()):
inner += Xs[ki]*Xs[kj]*(Vcs[ki]*Tcs[ki]*Vcs[kj]*Tcs[kj])**0.5
Tcm += inner
Tcm = Tcm/Vm
# Convert molar volume to normal mass density
MWs = phase.get_comp_vals('param.molecular_weight')
MWm = np.vstack([Xs[k]*MWs[k] for k in Xs.keys()]).sum(axis=0)
T = phase[T]
rhoL = liquid_pure_COSTALD(
phase=phase,
T=T,
MW=MWm,
Tc=Tcm,
Vc=Vm,
omega=omegam,
)
return rhoL
|
Computes the density of a liquid mixture using the COrrospoding STAtes
Liquid Density (COSTALD) method.
Parameters
----------
%(phase)s
%(T)s
%(MWs)s
%(Tcs)s
%(Vcs)s
%(omegas)s
Returns
-------
density : ndarray
The density of the liquid mixture in units of kg/m3. Note that
``chemicals.volume.COSTALD`` returns molar volume, so this function
converts it to density using the mole fraction weighted molecular
weight of the mixture: :math:`MW_{mix} = \Sigma x_i \cdot MW_i`.
Notes
-----
This is same approach used by ``chemicals.volume.COSTALD_mixture`` and
exact numerical correspondance is confirmed. Unlike the ``chemicals``
version, this function is vectorized over the conditions rather than
the compositions, since a typical simulation has millions of pores each
representing an independent conditions, but a mixture typically only has
a few components.
|
liquid_mixture_COSTALD
|
python
|
PMEAL/OpenPNM
|
openpnm/models/phase/density/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/phase/density/_funcs.py
|
MIT
|
def liquid_pure_COSTALD(
phase,
T='pore.temperature',
Tc='param.critical_temperature',
Vc='param.critical_volume',
omega='param.acentric_factor',
MW='param.molecular_weight',
):
r"""
Computes the density of a pure liquid using the COrrospoding STAtes
Liquid Density (COSTALD) method.
Parameters
----------
%(phase)s
%(T)s
%(Tc)s
%(Vc)s
%(omega)s
%(MW)s
Returns
-------
"""
Vc = phase[Vc]
Tc = phase[Tc]
omega = phase[omega]
T = phase[T]
Tr = T/Tc
V0 = 1 - 1.52816*(1-Tr)**(1/3) + 1.43907*(1-Tr)**(2/3) - 0.81446*(1-Tr) + \
0.190454*(1-Tr)**(4/3)
V1 = (-0.296123 + 0.386914*Tr - 0.0427258*Tr**2 - 0.0480645*Tr**3)/(Tr - 1.00001)
Vs = Vc*V0*(1-omega*V1)
MW = phase[MW]
rhoL = 1e-3*MW/Vs
return rhoL
|
Computes the density of a pure liquid using the COrrospoding STAtes
Liquid Density (COSTALD) method.
Parameters
----------
%(phase)s
%(T)s
%(Tc)s
%(Vc)s
%(omega)s
%(MW)s
Returns
-------
|
liquid_pure_COSTALD
|
python
|
PMEAL/OpenPNM
|
openpnm/models/phase/density/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/phase/density/_funcs.py
|
MIT
|
def mass_to_molar(
phase,
MW='param.molecular_weight',
rho='pore.density',
):
r"""
Calculates the molar density from the molecular weight and mass density
Parameters
----------
%(phase)s
%(MW)s
%(rho)s
Returns
-------
value : ndarray
A numpy ndrray containing molar density values [mol/m3]
"""
MW = phase[MW]/1000
rho = phase[rho]
value = rho/MW
return value
|
Calculates the molar density from the molecular weight and mass density
Parameters
----------
%(phase)s
%(MW)s
%(rho)s
Returns
-------
value : ndarray
A numpy ndrray containing molar density values [mol/m3]
|
mass_to_molar
|
python
|
PMEAL/OpenPNM
|
openpnm/models/phase/density/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/phase/density/_funcs.py
|
MIT
|
def liquid_mixture_tc(
phase,
T='pore.temperature',
mu='pore.viscosity',
Vms_at_Tb='param.molar_volume_Tb.*',
sigmas_at_Tb='param.surface_tension_Tb.*',
):
r"""
Uses Tyn-Calus model to estimate diffusion coefficient in a dilute liquid
solution of A in B from first principles at conditions of interest
Parameters
----------
%(phase)s
%(T)s
%(mu)s
Vms_at_Tb : str or list of scalars
Molar volumes of each component at its boiling temperature (m3/mol).
Can either be a string to a parameter on each component of a list
of scalar values which are used directly
sigmas_at_Tb : float
Surface tension of component A at boiling temperature (N/m)
Returns
-------
"""
T = phase[T]
mu = phase[mu]
sigma_A, sigma_B = phase.get_comp_vals(sigmas_at_Tb).values()
VA, VB = phase.get_comp_vals(Vms_at_Tb).values()
A = 8.93e-8*(VB*1e6)**0.267/(VA*1e6)**0.433*T
B = (sigma_B/sigma_A)**0.15/(mu*1e3)
value = A*B*1e-4
return value
|
Uses Tyn-Calus model to estimate diffusion coefficient in a dilute liquid
solution of A in B from first principles at conditions of interest
Parameters
----------
%(phase)s
%(T)s
%(mu)s
Vms_at_Tb : str or list of scalars
Molar volumes of each component at its boiling temperature (m3/mol).
Can either be a string to a parameter on each component of a list
of scalar values which are used directly
sigmas_at_Tb : float
Surface tension of component A at boiling temperature (N/m)
Returns
-------
|
liquid_mixture_tc
|
python
|
PMEAL/OpenPNM
|
openpnm/models/phase/diffusivity/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/phase/diffusivity/_funcs.py
|
MIT
|
def gas_mixture_ce(
phase,
T='pore.temperature',
P='pore.pressure',
Tcs='param.critical_temperature.*',
Pcs='param.critical_pressure.*',
omegas='param.acentric_factor.*',
MWs='param.molecular_weight.*',
epsilons='param.LJ_energy.*',
sigmas='param.LJ_diameter.*',
):
r"""
Calculate gas phase diffusion coefficient using Chapman-Enskog equation.
Parameters
----------
%(phase)s
%(T)s
%(P)s
%(Tcs)s
%(Pcs)s
%(omegas)s
%(MWs)s
%(epsilons)s
%(sigmas)s
Returns
-------
"""
# Fetch values from components
T = phase[T]
P = phase[P]
try:
MA, MB = phase.get_comp_vals(MWs).values()
except ValueError:
raise Exception('This function only works on binary mixtures')
MWAB = 2/(1/MA + 1/MB)
omega = phase.get_comp_vals(omegas).values()
Tc = phase.get_comp_vals(Tcs).values()
Pc = phase.get_comp_vals(Pcs).values()
k = 1.380649e-23 # Boltzmann constant
try:
eA, eB = phase.get_comp_vals(epsilons).values()
except Exception:
# Use correlation of Tee, Gotoh, & Stewart
eA, eB = (0.7915 + 0.1693*omega)*Tc*k
eAB = (eA*eB)**0.5
# Compute collision integral using Neufeld's correlation (RPP Eq.(11-3.6))
A, B, C, D, E, F, G, H = (1.06036, 0.15610, 0.19300, 0.47635, 1.03587,
1.52996, 1.76474, 3.89411)
Tstar = k*T/eAB
Omega = Omega = A/(Tstar**B) + C/np.exp(D*Tstar) + E/np.exp(F*Tstar) \
+ G/np.exp(H*Tstar)
# Now apply RPP Eq.(11-3.2)
try:
sA, sB = phase.get_comp_vals(sigmas).values()
except Exception:
# Use correlation of Tee, Gotoh, & Stewart
sA, sB = (2.3551 - 0.08847*omega)*(Tc/Pc)**(1/3)
sAB = (sA + sB)/2
DAB = 0.00266 * (T**1.5) / (P/101325 * MWAB**0.5 * sAB**2 * Omega) * 1e-4
return DAB
|
Calculate gas phase diffusion coefficient using Chapman-Enskog equation.
Parameters
----------
%(phase)s
%(T)s
%(P)s
%(Tcs)s
%(Pcs)s
%(omegas)s
%(MWs)s
%(epsilons)s
%(sigmas)s
Returns
-------
|
gas_mixture_ce
|
python
|
PMEAL/OpenPNM
|
openpnm/models/phase/diffusivity/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/phase/diffusivity/_funcs.py
|
MIT
|
def gas_mixture_fesg(
phase,
T='pore.temperature',
P='pore.pressure',
MWs='param.molecular_weight.*',
Vdms='param.molar_diffusion_volume.*',
):
r"""
Estimates the diffusion coefficient of both species in a binary gas
mixture using the Fuller et al correlation [1]_, [2]_, [3]_.
Parameters
----------
%(phase)s
%(T)s
%(P)s
%(MWs)s
%(Vdms)s
Returns
-------
Dij : dict[ndarray]
The dict contains one array for each component, containing the
diffusion coefficient of that component at each location.
References
----------
.. [1] Fuller, E. N., and J. C. Giddings: J. Gas Chromatogr., 3: 222 (1965).
.. [2] Fuller, E. N., P. D. Schettler, and J. C. Giddings: Ind. Eng. Chem.,
58(5): 18 (1966).
.. [3] Fuller, E. N., K. Ensley, and J. C. Giddings: J. Phys. Chem.,
73: 3679 (1969).
"""
T = phase[T]
P = phase[P]
# The following is to accomodate proper mixtures AND normal Phase objects
try:
MA, MB = phase.get_comp_vals(MWs).values()
except AttributeError:
MA, MB = phase[MWs]
try:
vA, vB = phase.get_comp_vals(Vdms).values()
except AttributeError:
vA, vB = phase[Vdms]
MAB = 2/(1/MA + 1/MB)
P = P/101325
DAB = 0.00143*T**1.75/(P*(MAB**0.5)*(vA**(1./3) + vB**(1./3))**2)*1e-4
return DAB
|
Estimates the diffusion coefficient of both species in a binary gas
mixture using the Fuller et al correlation [1]_, [2]_, [3]_.
Parameters
----------
%(phase)s
%(T)s
%(P)s
%(MWs)s
%(Vdms)s
Returns
-------
Dij : dict[ndarray]
The dict contains one array for each component, containing the
diffusion coefficient of that component at each location.
References
----------
.. [1] Fuller, E. N., and J. C. Giddings: J. Gas Chromatogr., 3: 222 (1965).
.. [2] Fuller, E. N., P. D. Schettler, and J. C. Giddings: Ind. Eng. Chem.,
58(5): 18 (1966).
.. [3] Fuller, E. N., K. Ensley, and J. C. Giddings: J. Phys. Chem.,
73: 3679 (1969).
|
gas_mixture_fesg
|
python
|
PMEAL/OpenPNM
|
openpnm/models/phase/diffusivity/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/phase/diffusivity/_funcs.py
|
MIT
|
def gas_pure_TRC(
phase,
T='pore.temperature',
a=[],
):
r"""
Parameters
----------
%(phase)s
%(T)s
a : list
The coefficients to use (see notes for form of equation). If not
given the ``phase['param.CAS']`` is used to lookup the values from
``chemicals.heat_capacity.TRC_gas_data``
Returns
-------
"""
# TRCCp
from chemicals.heat_capacity import TRC_gas_data
T = phase[T]
if len(a) == 0:
c = TRC_gas_data.loc[phase.params['CAS']]
a = list(c[3:11])
R = 8.314462618
y = np.zeros_like(T)
temp = (T - a[7])/(T + a[6])
mask = T > a[7]
y[mask] = temp[mask]
Cp = R*(a[0] + (a[1]/(T**2))*np.exp(-a[1]/T) + a[3]*(y**2)
+ (a[4] - a[5]/((T - a[7])**2))*(y**8))
return Cp
|
Parameters
----------
%(phase)s
%(T)s
a : list
The coefficients to use (see notes for form of equation). If not
given the ``phase['param.CAS']`` is used to lookup the values from
``chemicals.heat_capacity.TRC_gas_data``
Returns
-------
|
gas_pure_TRC
|
python
|
PMEAL/OpenPNM
|
openpnm/models/phase/heat_capacity/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/phase/heat_capacity/_funcs.py
|
MIT
|
def gas_mixture_yweighted(
phase,
Cps='pore.heat_capacity.*',
):
r"""
Uses a linearly mole fraction weighted average
Parameters
----------
%(phase)s
%(Cps)s
Returns
-------
"""
Cpmix = mixing_rule(phase=phase, prop=Cps, mode='linear')
return Cpmix
|
Uses a linearly mole fraction weighted average
Parameters
----------
%(phase)s
%(Cps)s
Returns
-------
|
gas_mixture_yweighted
|
python
|
PMEAL/OpenPNM
|
openpnm/models/phase/heat_capacity/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/phase/heat_capacity/_funcs.py
|
MIT
|
def liquid_mixture_xweighted(
phase,
Cps='pore.heat_capacity.*',
):
r"""
Uses a linearly mole fraction weighted average
Parameters
----------
%(phase)s
%(Cps)s
Returns
-------
"""
Cpmix = mixing_rule(phase=phase, prop=Cps, mode='linear')
return Cpmix
|
Uses a linearly mole fraction weighted average
Parameters
----------
%(phase)s
%(Cps)s
Returns
-------
|
liquid_mixture_xweighted
|
python
|
PMEAL/OpenPNM
|
openpnm/models/phase/heat_capacity/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/phase/heat_capacity/_funcs.py
|
MIT
|
def mix_and_match(
phase,
prop,
phases,
occupancy,
):
r"""
Return the given property by looking it up from a list of given phases
based on occupancy.
Parameters
----------
%(phase)s
prop : str
The dictionary key to the array containing the pore/throat property to
be used in the calculation.
phases : list
List of Phases over which the given `prop` is to be
averaged out.
occupancy : str
The dictionary key to the array containing the occupancy associated
with each of the given ``phases``.
Returns
-------
weighted_average : ndarray
Weighted average of the given `prop` averaged over `phases`.
"""
# Hack for ModelsMixin to not complain (cyclic dep)
prop = prop.strip("_")
values = np.zeros_like(phases[0][prop])
for phase in phases:
mask = phase[occupancy]
values[mask] = phase[prop][mask]
return values
|
Return the given property by looking it up from a list of given phases
based on occupancy.
Parameters
----------
%(phase)s
prop : str
The dictionary key to the array containing the pore/throat property to
be used in the calculation.
phases : list
List of Phases over which the given `prop` is to be
averaged out.
occupancy : str
The dictionary key to the array containing the occupancy associated
with each of the given ``phases``.
Returns
-------
weighted_average : ndarray
Weighted average of the given `prop` averaged over `phases`.
|
mix_and_match
|
python
|
PMEAL/OpenPNM
|
openpnm/models/phase/misc/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/phase/misc/_funcs.py
|
MIT
|
def mole_to_mass_fraction(
phase,
MWs='param.molecular_weight.*',
):
r"""
Convert mole fraction to mass fraction
Parameters
----------
%(phase)s
%(MWs)s
Returns
-------
"""
MWs = phase.get_comp_vals(MWs)
xs = phase['pore.mole_fraction']
ms = {}
# Find the actual masses in each pore
for c in xs.keys():
ms[c] = xs[c]*MWs[c]
# Normalize component mass by total mass in each pore
denom = np.vstack(list(ms.values())).sum(axis=0)
for c in xs.keys():
ms[c] = ms[c]/denom
return ms
|
Convert mole fraction to mass fraction
Parameters
----------
%(phase)s
%(MWs)s
Returns
-------
|
mole_to_mass_fraction
|
python
|
PMEAL/OpenPNM
|
openpnm/models/phase/misc/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/phase/misc/_funcs.py
|
MIT
|
def salinity(
phase,
T='pore.temperature',
conc='pore.concentration',
):
r"""
Calculates the salinity in g salt per kg of solution from concentration
Parameters
----------
%(phase)s
%(T)s
%(conc)s
Returns
-------
salinity : ndarray
The salinity in g of solute per kg of solution.
Notes
-----
This model is useful for converting known concentration values (e.g.
calculated by a transport algorithm) into salinity values, which can then
be used for finding other physical properties of water which are available
as a function of salinity.
The salinity correlations are valid for salinity up to 160 g/kg, which
corresponds to a concentration of 0.05 mol/L (assuming NaCl is the only
solute)
"""
C = phase[conc]
T = phase[T]
a = 8.73220929e+00
b = 6.00389629e+01
c = -1.19083743e-01
d = -1.77796042e+00
e = 3.26987130e-04
f = -1.09636011e-01
g = -1.83933426e-07
S = a + b*C + c*T + d*C**2 + e*T**2 + f*C**3 + g*T**3
return S
|
Calculates the salinity in g salt per kg of solution from concentration
Parameters
----------
%(phase)s
%(T)s
%(conc)s
Returns
-------
salinity : ndarray
The salinity in g of solute per kg of solution.
Notes
-----
This model is useful for converting known concentration values (e.g.
calculated by a transport algorithm) into salinity values, which can then
be used for finding other physical properties of water which are available
as a function of salinity.
The salinity correlations are valid for salinity up to 160 g/kg, which
corresponds to a concentration of 0.05 mol/L (assuming NaCl is the only
solute)
|
salinity
|
python
|
PMEAL/OpenPNM
|
openpnm/models/phase/mixtures/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/phase/mixtures/_funcs.py
|
MIT
|
def mixing_rule(
phase,
prop,
mode='logarithmic',
power=1,
):
r"""
Computes the property of a mixture using the specified mixing rule
Parameters
----------
%(phase)s
prop : str
The dictionary key containing the property of interest on each
component
mode : str
The mixing rule to to use. Options are:
============== ========================================================
mode
============== ========================================================
'logarithmic' (default) Uses the natural logarithm of the property as:
:math:`ln(z) = \Sigma (x_i \cdot ln(\z_i))`
'linear' Basic mole fraction weighting of the form
:math:`z = \Sigma (x_i \cdot \z_i)`
'power Applies an exponent to the property as:
:math:`\z^{power} = \Sigma (x_i \cdot \z_i^{power})`
============== ========================================================
power : scalar
If ``mode='power'`` this indicates the value of the exponent,
otherwise this is ignored.
"""
xs = phase['pore.mole_fraction']
ys = phase.get_comp_vals(prop)
z = 0.0
if mode == 'logarithmic':
for i in xs.keys():
z += xs[i]*np.log(ys[i])
z = np.exp(z)
elif mode in ['linear', 'simple']:
for i in xs.keys():
z += xs[i]*ys[i]
elif mode == 'power':
for i in xs.keys():
z += xs[i]*ys[i]**power
z = z**(1/power)
return z
|
Computes the property of a mixture using the specified mixing rule
Parameters
----------
%(phase)s
prop : str
The dictionary key containing the property of interest on each
component
mode : str
The mixing rule to to use. Options are:
============== ========================================================
mode
============== ========================================================
'logarithmic' (default) Uses the natural logarithm of the property as:
:math:`ln(z) = \Sigma (x_i \cdot ln(\z_i))`
'linear' Basic mole fraction weighting of the form
:math:`z = \Sigma (x_i \cdot \z_i)`
'power Applies an exponent to the property as:
:math:`\z^{power} = \Sigma (x_i \cdot \z_i^{power})`
============== ========================================================
power : scalar
If ``mode='power'`` this indicates the value of the exponent,
otherwise this is ignored.
|
mixing_rule
|
python
|
PMEAL/OpenPNM
|
openpnm/models/phase/mixtures/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/phase/mixtures/_funcs.py
|
MIT
|
def mole_to_mass_fraction(
phase,
MWs='param.molecular_weight'
):
r"""
Computes the mass fraction in each pore
Parameters
----------
%(phase)s
%(MWs)s
Returns
-------
ws : ndarray
An ndarray containing the mass fraction in each pore computed from
the mole fractions of each component and their molecular weights.
"""
xs = phase['pore.mole_fraction']
MW = phase.get_comp_vals(MWs)
num = [xs[k]*MW[k] for k in xs.keys()]
denom = np.sum(num, axis=0)
ws = num/denom
comps = list(phase.components.keys())
d = {comps[i]: ws[i, :] for i in range(len(comps))}
return d
|
Computes the mass fraction in each pore
Parameters
----------
%(phase)s
%(MWs)s
Returns
-------
ws : ndarray
An ndarray containing the mass fraction in each pore computed from
the mole fractions of each component and their molecular weights.
|
mole_to_mass_fraction
|
python
|
PMEAL/OpenPNM
|
openpnm/models/phase/mixtures/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/phase/mixtures/_funcs.py
|
MIT
|
def mole_summation(phase):
r"""
Computes total mole fraction in each pore given component values
Parameters
----------
%(phase)s
Returns
-------
vals : ND-array
An ND-array containing the total mole fraction. Note that this is not
guaranteed to sum to 1.0.
"""
xs = [phase['pore.mole_fraction.' + c.name] for c in phase.components.values()]
if len(xs) > 0:
xs = np.sum(xs, axis=0)
else:
xs = np.nan
return xs
|
Computes total mole fraction in each pore given component values
Parameters
----------
%(phase)s
Returns
-------
vals : ND-array
An ND-array containing the total mole fraction. Note that this is not
guaranteed to sum to 1.0.
|
mole_summation
|
python
|
PMEAL/OpenPNM
|
openpnm/models/phase/mixtures/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/phase/mixtures/_funcs.py
|
MIT
|
def from_component(phase, prop, compname):
r"""
Fetches the given values from the specified object
Parameters
----------
%(phase)s
prop : str
The name of the array to retreive
compname : str
The name of the object possessing the desired data
Returns
-------
vals : ND-array
An ND-array containing the request data
"""
comp = phase.project[compname]
vals = comp[prop]
return vals
|
Fetches the given values from the specified object
Parameters
----------
%(phase)s
prop : str
The name of the array to retreive
compname : str
The name of the object possessing the desired data
Returns
-------
vals : ND-array
An ND-array containing the request data
|
from_component
|
python
|
PMEAL/OpenPNM
|
openpnm/models/phase/mixtures/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/phase/mixtures/_funcs.py
|
MIT
|
def gaseous_species_in_water(
phase,
T="throat.temperature",
):
r"""
Calculate Henry's law constant for gaseous species dissolved in water
Parameters
----------
%(phase)s
%(T)s
Returns
-------
H : ndarray
A numpy ndarray containing Henry's law constant (Kpx) [atm/mol-frac]
Notes
-----
The constant for the correlation a lookup using the chemical formula
stored in ``phase.params['formula']``.
References
----------
Yaws, Carl L., et al. "Solubility & Henry's Law constants for sulfur
compounds in water: unlike traditional methods, the new correlation and
data presented here are appropriate for very low concentrations."
Chemical Engineering 110.8 (2003): 60-65.
"""
import pandas as pd
fname = "gas_water_henry.csv"
path = Path(os.path.realpath(__file__), "../")
path = Path(path.resolve(), fname)
df = pd.read_csv(path)
row = df[df.Formula == phase.params['formula']]
A, B, C, D = row.iloc[0, 3:7].astype(float)
Tmin, Tmax = row.iloc[0, 7:9].astype(float)
T = phase[T]
if (T.min() < Tmin) or (T.max() > Tmax):
logger.critical("The correlation is only accurate for temperatures in the "
+ f"range of {Tmin:.1f}K and {Tmax:.1f}K!")
Hpx_log10 = A + B/T + C*np.log10(T) + D*T
return 10**Hpx_log10
|
Calculate Henry's law constant for gaseous species dissolved in water
Parameters
----------
%(phase)s
%(T)s
Returns
-------
H : ndarray
A numpy ndarray containing Henry's law constant (Kpx) [atm/mol-frac]
Notes
-----
The constant for the correlation a lookup using the chemical formula
stored in ``phase.params['formula']``.
References
----------
Yaws, Carl L., et al. "Solubility & Henry's Law constants for sulfur
compounds in water: unlike traditional methods, the new correlation and
data presented here are appropriate for very low concentrations."
Chemical Engineering 110.8 (2003): 60-65.
|
gaseous_species_in_water
|
python
|
PMEAL/OpenPNM
|
openpnm/models/phase/partition_coefficient/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/phase/partition_coefficient/_funcs.py
|
MIT
|
def water_correlation(
phase,
T='pore.temperature',
salinity='pore.salinity'
):
r"""
Calculates surface tension of pure water or seawater at atmospheric
pressure
This model uses Eq. (28) given by Sharqawy et al. [1]. Values at
temperature higher than the normal boiling temperature are calculated at
the saturation pressure.
Parameters
----------
%(phase)s
%(T)s
%(salinity)s
Returns
-------
value : ndarray
A numpy ndarray containing surface tension of seawater in [N/m]
Notes
-----
T must be in K, and S in g of salt per kg of phase, or ppt (parts per
thousand). The correlation is valid for 273 < T < 313 K and
0 < S < 40 g/kg within 0.2 percent accuracy.
References
----------
[1] Sharqawy M. H., Lienhard J. H., and Zubair, S. M., Desalination and
Water Treatment, 2010.
"""
T = phase[T]
if salinity in phase.keys():
S = phase[salinity]
else:
S = 0
sigma_w = 0.2358*((1-(T/647.096))**1.256)*(1-0.625*(1-(T/647.096)))
a1 = 2.2637334337E-04
a2 = 9.4579521377E-03
a3 = 3.3104954843E-02
TC = T-273.15
sigma_sw = sigma_w*(1+(a1*TC+a2)*np.log(1+a3*S))
value = sigma_sw
return value
|
Calculates surface tension of pure water or seawater at atmospheric
pressure
This model uses Eq. (28) given by Sharqawy et al. [1]. Values at
temperature higher than the normal boiling temperature are calculated at
the saturation pressure.
Parameters
----------
%(phase)s
%(T)s
%(salinity)s
Returns
-------
value : ndarray
A numpy ndarray containing surface tension of seawater in [N/m]
Notes
-----
T must be in K, and S in g of salt per kg of phase, or ppt (parts per
thousand). The correlation is valid for 273 < T < 313 K and
0 < S < 40 g/kg within 0.2 percent accuracy.
References
----------
[1] Sharqawy M. H., Lienhard J. H., and Zubair, S. M., Desalination and
Water Treatment, 2010.
|
water_correlation
|
python
|
PMEAL/OpenPNM
|
openpnm/models/phase/surface_tension/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/phase/surface_tension/_funcs.py
|
MIT
|
def liquid_pure_bb(
phase,
T='pore.temperature',
Tc='param.critical_temperature',
Tb='param.boiling_temperature',
Pc='param.critical_pressure',
):
r"""
Computes the surface tension of a pure liquid in its own vapor using the
correlation in [1]
Parameters
----------
%(phase)s
%(T)s
%(Tc)s
%(Tb)s
%(Pc)s
Returns
-------
value : ndarray
A numpy ndarray containing surface tension values scaled to the
temperature [N/m]
References
----------
[1] Brock and Bird
"""
T = phase[T]
Tc = phase[Tc]
Tr = T/Tc
Tb = phase[Tb]
Tbr = Tb/Tc
Pc = phase[Pc]/100000
Q = 0.1196*(1 + Tbr*np.log(Pc/1.01325)/(1-Tbr))-0.279
sigma = 1e-3 * Q * (Pc**(2/3)) * (Tc**(1/3)) * ((1-Tr)**(11/9))
return sigma
|
Computes the surface tension of a pure liquid in its own vapor using the
correlation in [1]
Parameters
----------
%(phase)s
%(T)s
%(Tc)s
%(Tb)s
%(Pc)s
Returns
-------
value : ndarray
A numpy ndarray containing surface tension values scaled to the
temperature [N/m]
References
----------
[1] Brock and Bird
|
liquid_pure_bb
|
python
|
PMEAL/OpenPNM
|
openpnm/models/phase/surface_tension/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/phase/surface_tension/_funcs.py
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.