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 liquid_mixture_wsd(
phase,
sigmas='pore.surface_tension.*',
rhos='pore.density.*',
MWs='param.molecular_weight.*',
):
r"""
Computes the surface tension of a liqiud mixture with its own vapor using
the correlation in [1]
Parameters
----------
%(phase)s
%(rhos)s
%(MWs)s
%(sigmas)s
Returns
-------
sigma : ndarray
A numpy ndarray containing surface tension values
References
----------
[1] Winterfeld, Scriven, and Davis
"""
sigmas = phase.get_comp_vals(sigmas)
xs = phase['pore.mole_fraction']
rhos = phase.get_comp_vals(rhos) # kg/m3
MWs = phase.get_comp_vals(MWs) # g/mol
rhoms = {k: rhos[k]/(MWs[k]/1000) for k in xs.keys()} # mol/m3
rhom_mix = np.vstack([rhoms[k]*xs[k] for k in xs.keys()]).sum(axis=0)
sigma = 0.0
for i, ki in enumerate(xs.keys()):
for j, kj in enumerate(xs.keys()):
num = xs[ki]*xs[kj]*(rhom_mix**2)*(sigmas[ki]*sigmas[kj])**0.5
denom = rhoms[ki]*rhoms[kj]
sigma += num/denom
return sigma
|
Computes the surface tension of a liqiud mixture with its own vapor using
the correlation in [1]
Parameters
----------
%(phase)s
%(rhos)s
%(MWs)s
%(sigmas)s
Returns
-------
sigma : ndarray
A numpy ndarray containing surface tension values
References
----------
[1] Winterfeld, Scriven, and Davis
|
liquid_mixture_wsd
|
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 water_correlation(
phase,
T="pore.temperature",
salinity="pore.salinity",
):
r"""
Calculates thermal conductivity of pure water or seawater at atmospheric
pressure using the correlation given [1].
Values at temperature higher the normal boiling temperature are calculated
at the saturation pressure.
Parameters
----------
%(phase)s
%(T)s
%(salinity)s
Returns
-------
value : ndarray
A numpy ndarray containing thermal conductivity of water/seawater in [W/m.K]
Notes
-----
T must be in K, and S in g of salt per kg of phase, or ppt (parts per
thousand). The correlation is valid for 273 < T < 453 K and
0 < S < 160 g/kg within 3 percent accuracy.
References
----------
[1] D. T. Jamieson, and J. S. Tudhope, Desalination, 8, 393-401, 1970.
"""
T = phase[T]
if salinity in phase.keys():
S = phase[salinity]
else:
S = 0
T68 = 1.00024 * T # convert from T_90 to T_68
SP = S / 1.00472 # convert from S to S_P
k_sw = 0.001 * (
10
** (
np.log10(240 + 0.0002 * SP)
+ 0.434
* (2.3 - (343.5 + 0.037 * SP) / T68)
* ((1 - T68 / (647.3 + 0.03 * SP))) ** (1 / 3)
)
)
value = k_sw
return value
|
Calculates thermal conductivity of pure water or seawater at atmospheric
pressure using the correlation given [1].
Values at temperature higher the normal boiling temperature are calculated
at the saturation pressure.
Parameters
----------
%(phase)s
%(T)s
%(salinity)s
Returns
-------
value : ndarray
A numpy ndarray containing thermal conductivity of water/seawater in [W/m.K]
Notes
-----
T must be in K, and S in g of salt per kg of phase, or ppt (parts per
thousand). The correlation is valid for 273 < T < 453 K and
0 < S < 160 g/kg within 3 percent accuracy.
References
----------
[1] D. T. Jamieson, and J. S. Tudhope, Desalination, 8, 393-401, 1970.
|
water_correlation
|
python
|
PMEAL/OpenPNM
|
openpnm/models/phase/thermal_conductivity/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/phase/thermal_conductivity/_funcs.py
|
MIT
|
def gas_pure_gismr(
phase,
T='pore.temperature',
MW='param.molecular_weight',
Tb='param.boiling_temperature',
Pc='param.critical_pressure',
omega='param.acentric_factor',
):
r"""
Calculate the thermal conductivty of a pure gas using the correlation in
[1]
Parameters
----------
%(phase)s
%(T)s
%(MW)s
%(Tb)s
%(Pc)s
%(omega)s
Returns
-------
References
----------
[1] gharagheizi method: doi:10.1002/aic.13938
"""
T = phase[T]
MW = phase[MW]
Tb = phase[Tb]
# The following correction suggested by chemicals package author
Pc = phase[Pc]/10000
omega = phase[omega]
B = (T + (2.0*omega + 2.0*T - 2.0*T*(2.0*omega + 3.2825)/Tb + 3.2825)
/ (2.0*omega + T - T*(2.0*omega + 3.2825)/Tb + 3.2825)
- T*(2.0*omega + 3.2825)/Tb)
A = (2*omega + T - (2*omega + 3.2825)*T/Tb + 3.2825)/(0.1*MW*Pc*T) \
* (3.9752*omega + 0.1*Pc + 1.9876*B + 6.5243)**2
k = 7.9505e-4 + 3.989e-5*T - 5.419e-5*MW + 3.989e-5*A
return k
|
Calculate the thermal conductivty of a pure gas using the correlation in
[1]
Parameters
----------
%(phase)s
%(T)s
%(MW)s
%(Tb)s
%(Pc)s
%(omega)s
Returns
-------
References
----------
[1] gharagheizi method: doi:10.1002/aic.13938
|
gas_pure_gismr
|
python
|
PMEAL/OpenPNM
|
openpnm/models/phase/thermal_conductivity/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/phase/thermal_conductivity/_funcs.py
|
MIT
|
def liquid_pure_gismr(
phase,
T='pore.temperature',
MW='param.molecular_weight',
Tb='param.boiling_temperature',
Pc='param.critical_pressure',
omega='param.acentric_factor',
):
r"""
Calculates the thermal conductivity of a pure liquid using the correlation
in [1]
Parameters
----------
%(phase)s
%(T)s
%(MW)s
%(Tb)s
%(Pc)s
%(omega)s
Returns
-------
References
----------
[1] gharagheizi method: doi:10.1002/aic.13938
"""
T = phase[T]
MW = phase[MW]
Tb = phase[Tb]
Pc = phase[Pc]/100000
omega = phase[omega]
B = 16.0407*MW + 2.0*Tb - 27.9074
A = 3.8588*(MW**8)*(1.0045*B + 6.5152*MW - 8.9756)
k = (1e-4)*(10*omega + 2*Pc - 2*T + 4 + 1.908*(Tb + 1.009*(B**2)/(MW**2))
+ 3.9287*(MW**4)/(B**4) + A/(B**8))
return k
|
Calculates the thermal conductivity of a pure liquid using the correlation
in [1]
Parameters
----------
%(phase)s
%(T)s
%(MW)s
%(Tb)s
%(Pc)s
%(omega)s
Returns
-------
References
----------
[1] gharagheizi method: doi:10.1002/aic.13938
|
liquid_pure_gismr
|
python
|
PMEAL/OpenPNM
|
openpnm/models/phase/thermal_conductivity/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/phase/thermal_conductivity/_funcs.py
|
MIT
|
def liquid_pure_sr(
phase,
T="pore.temperature",
Tc='param.critical_temperature',
MW='param.molecular_weight',
Tb='param.boiling_temperature',
):
r"""
Calculates the thermal conductivity of a pure liquid using the correlation
in [1]
Parameters
----------
%(phase)s
%(T)s
%(Tc)s
%(MW)s
%(Tb)s
Returns
-------
value : ndarray
A numpy ndarray containing thermal conductivity values in [W/m.K]
References
----------
[1] Sato et al
"""
T = phase[T]
Tc = phase[Tc]
MW = phase[MW]
Tbr = phase[Tb]/Tc
Tr = T / Tc
value = ((1.1053 / ((MW) ** 0.5)) * (3 + 20 * (1 - Tr) ** (2 / 3))
/ (3 + 20 * (1 - Tbr) ** (2 / 3)))
return value
|
Calculates the thermal conductivity of a pure liquid using the correlation
in [1]
Parameters
----------
%(phase)s
%(T)s
%(Tc)s
%(MW)s
%(Tb)s
Returns
-------
value : ndarray
A numpy ndarray containing thermal conductivity values in [W/m.K]
References
----------
[1] Sato et al
|
liquid_pure_sr
|
python
|
PMEAL/OpenPNM
|
openpnm/models/phase/thermal_conductivity/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/phase/thermal_conductivity/_funcs.py
|
MIT
|
def liquid_mixture_DIPPR9I(
phase,
rhos='pore.density.*',
ks='pore.thermal_conductivity.*',
MWs='param.molecular_weight.*',
):
r"""
Calculates the thermal conductivity of a liquid mixture using the
correlation in [1]
Parameters
----------
%(phase)s
%(rhos)s
%(ks)s
%(MWs)s
Returns
-------
References
----------
[1] DIPPR9I
"""
raise NotImplementedError("This function is not ready yet")
from chemicals import rho_to_Vm
xs = phase['pore.mole_fraction']
kLs = phase.get_comp_vals(ks)
# kL = numba_vectorized.DIPPR9I(xs, kLs) # Another one that doesn't work
Vm = [rho_to_Vm(c.get_comp_vals(rhos), c.get_comp_vals(MWs))
for c in phase.components.keys()]
denom = np.sum([xs[i]*Vm[i] for i in range(len(xs))], axis=0)
phis = np.array([xs[i]*Vm[i] for i in range(len(xs))])/denom
kij = 2/np.sum([1/kLs[i] for i in range(len(xs))], axis=0)
kmix = np.zeros_like(xs[0])
N = len(xs)
for i in range(N):
for j in range(N):
kmix += phis[i]*phis[j]*kij
return kmix
|
Calculates the thermal conductivity of a liquid mixture using the
correlation in [1]
Parameters
----------
%(phase)s
%(rhos)s
%(ks)s
%(MWs)s
Returns
-------
References
----------
[1] DIPPR9I
|
liquid_mixture_DIPPR9I
|
python
|
PMEAL/OpenPNM
|
openpnm/models/phase/thermal_conductivity/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/phase/thermal_conductivity/_funcs.py
|
MIT
|
def liquid_mixture_DIPPR9H(
phase,
ks='pore.thermal_conductivity.*',
MWs='param.molecular_weight.*',
):
r"""
Calculates the thermal conductivity of a liquid mixture using the
correlation in [1]
Parameters
----------
%(phase)s
%(ks)s
%(MWs)s
Returns
-------
References
----------
[1] DIPPR9H
"""
xs = phase['pore.mole_fraction']
MW = phase.get_comp_vals(MWs)
ks = phase.get_comp_vals(ks)
num = np.vstack([xs[k]*MW[k]/(ks[k]**2) for k in xs.keys()]).sum(axis=0)
denom = np.vstack([xs[k]*MW[k] for k in xs.keys()]).sum(axis=0)
temp = num/denom
kmix = (1/temp)**0.5
return kmix
|
Calculates the thermal conductivity of a liquid mixture using the
correlation in [1]
Parameters
----------
%(phase)s
%(ks)s
%(MWs)s
Returns
-------
References
----------
[1] DIPPR9H
|
liquid_mixture_DIPPR9H
|
python
|
PMEAL/OpenPNM
|
openpnm/models/phase/thermal_conductivity/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/phase/thermal_conductivity/_funcs.py
|
MIT
|
def gas_mixture_whz(
phase,
T='pore.temperature',
ks='pore.thermal_conductivity.*',
MWs='param.molecular_weight.*',
):
r"""
Calculates the viscosity of a gas mixture using the correlation in [1]
Parameters
----------
%(phase)s
%(T)s
%(ks)s
%(MWs)s
Returns
-------
References
----------
[1] Wassiljew, Herning & Zipperer
"""
T = phase[T]
ys = phase['pore.mole_fraction']
kGs = phase.get_comp_vals(ks)
MWs = phase.get_comp_vals(MWs)
kmix = np.zeros_like(T)
for i, ki in enumerate(ys.keys()):
num = ys[ki]*kGs[ki]
denom = 0.0
for j, kj in enumerate(ys.keys()):
A = np.sqrt(MWs[kj]/MWs[ki])
denom += ys[ki]*A
kmix += num/denom
return kmix
|
Calculates the viscosity of a gas mixture using the correlation in [1]
Parameters
----------
%(phase)s
%(T)s
%(ks)s
%(MWs)s
Returns
-------
References
----------
[1] Wassiljew, Herning & Zipperer
|
gas_mixture_whz
|
python
|
PMEAL/OpenPNM
|
openpnm/models/phase/thermal_conductivity/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/phase/thermal_conductivity/_funcs.py
|
MIT
|
def water_correlation(phase, T='pore.temperature', salinity='pore.salinity'):
r"""
Calculates vapor pressure of pure water or seawater given by [1] based on
Raoult's law. The pure water vapor pressure is given by [2]
Parameters
----------
%(phase)s
%(T)s
%(salinity)s
Returns
-------
Notes
-----
T must be in K, and S in g of salt per kg of phase, or ppt (parts per
thousand)
VALIDITY: 273 < T < 473 K; 0 < S < 240 g/kg;
ACCURACY: 0.5 percent
References
----------
[1] Sharqawy M. H., Lienhard J. H., and Zubair, S. M., Desalination and
Water Treatment, 2010.
[2] ASHRAE handbook: Fundamentals, ASHRAE; 2005.
"""
T = phase[T]
if salinity in phase.keys():
S = phase[salinity]
else:
S = 0
a1 = -5.8002206E+03
a2 = 1.3914993E+00
a3 = -4.8640239E-02
a4 = 4.1764768E-05
a5 = -1.4452093E-08
a6 = 6.5459673E+00
Pv_w = np.exp((a1/T) + a2 + a3*T + a4*T**2 + a5*T**3 + a6*np.log(T))
Pv_sw = Pv_w/(1+0.57357*(S/(1000-S)))
value = Pv_sw
return value
|
Calculates vapor pressure of pure water or seawater given by [1] based on
Raoult's law. The pure water vapor pressure is given by [2]
Parameters
----------
%(phase)s
%(T)s
%(salinity)s
Returns
-------
Notes
-----
T must be in K, and S in g of salt per kg of phase, or ppt (parts per
thousand)
VALIDITY: 273 < T < 473 K; 0 < S < 240 g/kg;
ACCURACY: 0.5 percent
References
----------
[1] Sharqawy M. H., Lienhard J. H., and Zubair, S. M., Desalination and
Water Treatment, 2010.
[2] ASHRAE handbook: Fundamentals, ASHRAE; 2005.
|
water_correlation
|
python
|
PMEAL/OpenPNM
|
openpnm/models/phase/vapor_pressure/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/phase/vapor_pressure/_funcs.py
|
MIT
|
def liquid_pure_lk(
phase,
T='pore.temperature',
Tc='param.critical_temperature',
Pc='param.critical_pressure',
omega='param.acentric_factor',
):
r"""
Calculate the vapor pressure of a pure liquid using the correlation in [1]
Parameters
----------
%(phase)s
%(T)s
%(Tc)s
%(Pc)s
%(omega)s
Returns
-------
References
----------
[1] Lee and Kesler
"""
T = phase[T]
Tc = phase[Tc]
Tr = T/Tc
Pc = phase[Pc]
omega = phase[omega]
f0 = 5.92714 - 6.09648/Tr - 1.28862*np.log(Tr) + 0.169347*(Tr**6)
f1 = 15.2518 - 15.6875/Tr - 13.4721*np.log(Tr) + 0.43577*(Tr**6)
Pr = np.exp(f0 + omega*f1)
Pvap = Pr*Pc
return Pvap
|
Calculate the vapor pressure of a pure liquid using the correlation in [1]
Parameters
----------
%(phase)s
%(T)s
%(Tc)s
%(Pc)s
%(omega)s
Returns
-------
References
----------
[1] Lee and Kesler
|
liquid_pure_lk
|
python
|
PMEAL/OpenPNM
|
openpnm/models/phase/vapor_pressure/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/phase/vapor_pressure/_funcs.py
|
MIT
|
def liquid_pure_antoine(
phase,
T='pore.temperature',
):
r"""
Calculates the vapor pressure of a pure liquid using Antoine's equation
Parameters
----------
%(phase)s
%(T)s
%(Tc)s
Returns
-------
References
----------
[1] RPP
Notes
-----
Coefficients are looked up from the ``chemicals`` package. If values for
"extended" version are not found then the normal 3-coefficient values are
sought.
"""
# either antoine or extended antoine using constants from RPP
CAS = phase.params['CAS']
T = phase[T]
from chemicals.vapor_pressure import Psat_data_AntoinePoling
coeffs = Psat_data_AntoinePoling.loc[CAS]
_, A, B, C, Tmin, Tmax = coeffs
Pvap = 10**(A - B/(T + C))
return Pvap
|
Calculates the vapor pressure of a pure liquid using Antoine's equation
Parameters
----------
%(phase)s
%(T)s
%(Tc)s
Returns
-------
References
----------
[1] RPP
Notes
-----
Coefficients are looked up from the ``chemicals`` package. If values for
"extended" version are not found then the normal 3-coefficient values are
sought.
|
liquid_pure_antoine
|
python
|
PMEAL/OpenPNM
|
openpnm/models/phase/vapor_pressure/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/phase/vapor_pressure/_funcs.py
|
MIT
|
def water_correlation(
phase,
T='pore.temperature',
salinity='pore.salinity'
):
r"""
Calculates viscosity of pure water or seawater at atmospheric pressure.
This correlation uses Eq. (22) 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
-------
mu : ndarray
Array containing viscosity of water or seawater in [kg/m.s] or [Pa.s]
Notes
-----
T must be in K, and S in g of salt per kg of phase, or ppt (parts per
thousand)
VALIDITY: 273 < T < 453 K; 0 < S < 150 g/kg;
ACCURACY: 1.5 percent
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
TC = T-273.15
S = S/1000
a1 = 1.5700386464E-01
a2 = 6.4992620050E+01
a3 = -9.1296496657E+01
a4 = 4.2844324477E-05
mu_w = a4 + 1/(a1*(TC+a2)**2+a3)
a5 = 1.5409136040E+00
a6 = 1.9981117208E-02
a7 = -9.5203865864E-05
a8 = 7.9739318223E+00
a9 = -7.5614568881E-02
a10 = 4.7237011074E-04
A = a5 + a6*T + a7*T**2
B = a8 + a9*T + a10*T**2
mu_sw = mu_w*(1 + A*S + B*S**2)
value = mu_sw
return value
|
Calculates viscosity of pure water or seawater at atmospheric pressure.
This correlation uses Eq. (22) 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
-------
mu : ndarray
Array containing viscosity of water or seawater in [kg/m.s] or [Pa.s]
Notes
-----
T must be in K, and S in g of salt per kg of phase, or ppt (parts per
thousand)
VALIDITY: 273 < T < 453 K; 0 < S < 150 g/kg;
ACCURACY: 1.5 percent
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/viscosity/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/phase/viscosity/_funcs.py
|
MIT
|
def air_correlation(
phase,
T='pore.temperature',
n_V='pore.molar_density',
):
r"""
Calculates the viscosity of air at given conditions
This model uses the correlation from [1].
Parameters
----------
%(phase)s
%(T)s
%(n_V)s
Returns
-------
References
----------
[1] I forget
"""
raise Exception("This function does not work yet")
# Get props from object
T = phase[T]
rho = phase[n_V]
# Declare given constants
MW = 28.9586 # g/mol
Tc = 132.6312 # K
rho_c = 10447.7 # mol/m3
sigma = 0.36 # nm
e_k = 103.3 # K
# Compute a few definitions
delta = rho/rho_c
T_star = T/e_k
tau = np.atleast_2d(Tc/T)
# Declare the summation variables
ind = np.atleast_2d([0, 1, 2, 3, 4]).T
N_i = np.atleast_2d([10.72, 1.122, 0.002019, -8.878, -0.02916]).T
t_i = np.atleast_2d([0.2, 0.05, 2.4, 0.6, 3.6]).T
d_i = np.atleast_2d([1, 4, 9, 1, 8]).T
b_i = np.atleast_2d([0.431, -0.4623, 0.08406, 0.005341, -0.00331]).T
gamma_i = np.atleast_2d([0, 0, 0, 1, 1]).T
# Start crunching numbers
omega = np.exp(np.sum(b_i*(np.atleast_2d(np.log(T_star))**(ind)), axis=0))
mu_o = 0.9266958*(MW*T)**0.5/((sigma**2) * omega)
temp = N_i * (tau**t_i) * (delta**d_i) * np.exp(-gamma_i*(delta**gamma_i))
mu_t = np.sum(temp, axis=0)
mu = mu_o + mu_t
return mu
|
Calculates the viscosity of air at given conditions
This model uses the correlation from [1].
Parameters
----------
%(phase)s
%(T)s
%(n_V)s
Returns
-------
References
----------
[1] I forget
|
air_correlation
|
python
|
PMEAL/OpenPNM
|
openpnm/models/phase/viscosity/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/phase/viscosity/_funcs.py
|
MIT
|
def gas_pure_st(
phase,
T='pore.temperature',
Tc='param.critical_temperature',
Pc='param.critical_pressure',
MW='param.molecular_weight',
):
r"""
Calculates the viscosity of a pure gas using the correlation in [1]
Parameters
----------
%(phase)s
%(T)s
%(Tc)s
%(Pc)s
%(MW)s
Returns
-------
References
----------
[1] Stiel and Thodos
"""
# stiel-thodos
T = phase[T]
Tc = phase[Tc]
Pc = phase[Pc]/101325
MW = phase[MW]
mu = np.zeros_like(T)
Tr = T/Tc
zeta = Tc**(1/6)/((MW**0.5)*(Pc**(2/3)))
mu_hi = (17.78e-5*(4.58*Tr - 1.67)**0.625)/zeta
mu_lo = (34e-5*Tr**0.94)/zeta
mask = Tr > 1.5
mu[mask] = mu_hi[mask]
mu[~mask] = mu_lo[~mask]
return mu/1000
|
Calculates the viscosity of a pure gas using the correlation in [1]
Parameters
----------
%(phase)s
%(T)s
%(Tc)s
%(Pc)s
%(MW)s
Returns
-------
References
----------
[1] Stiel and Thodos
|
gas_pure_st
|
python
|
PMEAL/OpenPNM
|
openpnm/models/phase/viscosity/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/phase/viscosity/_funcs.py
|
MIT
|
def gas_pure_gesmr(
phase,
T='pore.temperature',
Tc='param.critical_temperature',
Pc='param.critical_pressure',
MW='param.molecular_weight',
):
r"""
Calculates the viscosity of a pure gas using the correlation [1]
Parameters
----------
%(phase)s
%(T)s
%(Tc)s
%(Pc)s
%(MW)s
Returns
-------
References
----------
[1] Gharagheizi et al
"""
T = phase[T]
MW = phase[MW]
Pc = phase[Pc]
Tc = phase[Tc]
Tr = T/Tc
mu = (1e-5)*Pc*Tr + (0.091 - 0.477/MW)*T + \
MW*((1e-5)*Pc - 8.0*(MW**2)/(T**2))*(10.7639/Tc - 4.1929/T)
mu = mu*1e-7
mu = np.clip(mu, a_min=1e-7, a_max=np.inf)
return mu
|
Calculates the viscosity of a pure gas using the correlation [1]
Parameters
----------
%(phase)s
%(T)s
%(Tc)s
%(Pc)s
%(MW)s
Returns
-------
References
----------
[1] Gharagheizi et al
|
gas_pure_gesmr
|
python
|
PMEAL/OpenPNM
|
openpnm/models/phase/viscosity/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/phase/viscosity/_funcs.py
|
MIT
|
def gas_mixture_hz(
phase,
mus='pore.viscosity.*',
MWs='param.molecular_weight.*',
):
r"""
Computes the viscosity of a gas mixture using the correlation in [1]
Parameters
----------
%(phase)s
%(mus)s
%(MWs)s
Returns
-------
mu : ndarray
An ndarray of Np length containing the viscosity of the mixture in
each pore
References
----------
[1] Herning and Zipperer
"""
MWs = phase.get_comp_vals(MWs)
mus = phase.get_comp_vals(mus)
xs = phase['pore.mole_fraction']
num = 0.0
denom = 0.0
for k in xs.keys():
num += xs[k]*mus[k]*MWs[k]**0.5
denom += xs[k]*MWs[k]**0.5
mu = num/denom
return mu
|
Computes the viscosity of a gas mixture using the correlation in [1]
Parameters
----------
%(phase)s
%(mus)s
%(MWs)s
Returns
-------
mu : ndarray
An ndarray of Np length containing the viscosity of the mixture in
each pore
References
----------
[1] Herning and Zipperer
|
gas_mixture_hz
|
python
|
PMEAL/OpenPNM
|
openpnm/models/phase/viscosity/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/phase/viscosity/_funcs.py
|
MIT
|
def liquid_pure_ls(
phase,
T='pore.temperature',
MW='param.molecular_weight',
Tc='param.critical_temperature',
Pc='param.critical_pressure',
omega='param.acentric_factor',
):
r"""
Computes the viscosity of a pure liquid using the correlation in [1]
Parameters
----------
%(phase)s
%(T)s
%(MW)s
%(Tc)s
%(Pc)s
%(omega)s
Returns
-------
mu : ndarray
An ndarray of Np length containing the viscosity of the mixture in
each pore
References
----------
[1] Letsou and Stiel
"""
T = phase[T]
MW = phase[MW]
Tc = phase[Tc]
Pc = phase[Pc]
omega = phase[omega]
Tr = T/Tc
zeta = 2173.424 * (Tc**(1/6))/((MW**(0.5))*(Pc**(2/3)))
zeta0 = (1.5174 - 2.135*Tr + 0.75*(Tr**2))*1e-5
zeta1 = (4.2552 - 7.674*Tr + 3.4*(Tr**2))*1e-5
mu = (zeta0 + omega*zeta1)/zeta
return mu
|
Computes the viscosity of a pure liquid using the correlation in [1]
Parameters
----------
%(phase)s
%(T)s
%(MW)s
%(Tc)s
%(Pc)s
%(omega)s
Returns
-------
mu : ndarray
An ndarray of Np length containing the viscosity of the mixture in
each pore
References
----------
[1] Letsou and Stiel
|
liquid_pure_ls
|
python
|
PMEAL/OpenPNM
|
openpnm/models/phase/viscosity/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/phase/viscosity/_funcs.py
|
MIT
|
def _poisson_conductance(phase,
pore_conductivity=None,
throat_conductivity=None,
size_factors=None):
r"""
Calculates the conductance of the conduits in the network, where a
conduit is (1/2 pore - full throat - 1/2 pore). See the notes section.
Parameters
----------
phase : OpenPNM Phase
The object which this model is associated with. This controls the
length of the calculated array, and also provides access to other
necessary properties.
pore_conductivity : str
Dictionary key of the pore conductivity values
throat_conductivity : str
Dictionary key of the throat conductivity values
size_factors: str
Dictionary key of the conduit size factors' values.
Returns
-------
g : ndarray
Array containing conductance values for conduits in the
geometry attached to the given physics object.
Notes
-----
This function requires that all the necessary phase properties
already be calculated.
"""
network = phase.network
cn = network.conns
Dt = phase[throat_conductivity]
D1, D2 = phase[pore_conductivity][cn].T
# If individual size factors for conduit constiuents are known
SF = network[size_factors]
if SF.ndim == 2:
F1, Ft, F2 = SF.T
g1 = D1 * F1
gt = Dt * Ft
g2 = D2 * F2
return 1 / (1 / g1 + 1 / gt + 1 / g2)
else:
# Otherwise, i.e., the size factor for the entire conduit is only known
F = network[size_factors]
return Dt * F
|
Calculates the conductance of the conduits in the network, where a
conduit is (1/2 pore - full throat - 1/2 pore). See the notes section.
Parameters
----------
phase : OpenPNM Phase
The object which this model is associated with. This controls the
length of the calculated array, and also provides access to other
necessary properties.
pore_conductivity : str
Dictionary key of the pore conductivity values
throat_conductivity : str
Dictionary key of the throat conductivity values
size_factors: str
Dictionary key of the conduit size factors' values.
Returns
-------
g : ndarray
Array containing conductance values for conduits in the
geometry attached to the given physics object.
Notes
-----
This function requires that all the necessary phase properties
already be calculated.
|
_poisson_conductance
|
python
|
PMEAL/OpenPNM
|
openpnm/models/physics/_utils.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/physics/_utils.py
|
MIT
|
def _get_key_props(phase=None,
diameter="throat.diameter",
surface_tension="throat.surface_tension",
contact_angle="throat.contact_angle"):
"""
Returns desired properties in the correct format! See Notes.
Notes
-----
Many of the methods are generic to pores and throats. Some information may
be stored on either the pore or throat and needs to be interpolated.
This is a helper method to return the properties in the correct format.
TODO: Check for method to convert throat to pore data
"""
element = diameter.split(".")[0]
if element == "pore":
if "throat" in surface_tension:
sigma = phase.interpolate_data(propname=surface_tension)
else:
sigma = phase[surface_tension]
if "throat" in contact_angle:
theta = phase.interpolate_data(propname=contact_angle)
else:
theta = phase[contact_angle]
if element == "throat":
if "pore" in surface_tension:
sigma = phase.interpolate_data(propname=surface_tension)
else:
sigma = phase[surface_tension]
if "pore" in contact_angle:
theta = phase.interpolate_data(propname=contact_angle)
else:
theta = phase[contact_angle]
return element, sigma, theta
|
Returns desired properties in the correct format! See Notes.
Notes
-----
Many of the methods are generic to pores and throats. Some information may
be stored on either the pore or throat and needs to be interpolated.
This is a helper method to return the properties in the correct format.
TODO: Check for method to convert throat to pore data
|
_get_key_props
|
python
|
PMEAL/OpenPNM
|
openpnm/models/physics/_utils.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/physics/_utils.py
|
MIT
|
def ad_dif(
phase,
pore_pressure='pore.pressure',
throat_hydraulic_conductance='throat.hydraulic_conductance',
throat_diffusive_conductance='throat.diffusive_conductance',
s_scheme='powerlaw'
):
r"""
Calculates the advective-diffusive conductance of conduits in network.
Parameters
----------
%(phase)s
pore_pressure : str
%(dict_blurb)s pore pressure
throat_hydraulic_conductance : str
%(dict_blurb)s hydraulic conductance
throat_diffusive_conductance : str
%(dict_blurb)s throat diffusive conductance
s_scheme : str
Name of the space discretization scheme to use
Returns
-------
%(return_arr)s advection-diffuvsion conductance values
Notes
-----
This function calculates the specified property for the *entire*
network then extracts the values for the appropriate throats at the
end.
This function assumes cylindrical throats with constant cross-section
area. Corrections for different shapes and variable cross-section area
can be imposed by passing the proper conduit_shape_factors argument
when computing the diffusive and hydraulic conductances.
shape_factor depends on the physics of the problem, i.e.
diffusion-like processes and fluid flow need different shape factors.
"""
network = phase.project.network
cn = network['throat.conns']
# Find g for half of pore 1, throat, and half of pore 2
P = phase[pore_pressure]
gh = phase[throat_hydraulic_conductance]
gd = phase[throat_diffusive_conductance]
if gd.size == network.Nt:
gd = _np.tile(gd, 2)
# Special treatment when gd is not Nt by 1 (ex. mass partitioning)
elif gd.size == 2 * network.Nt:
gd = gd.reshape(network.Nt * 2, order='F')
else:
raise Exception(f"Shape of {throat_diffusive_conductance} must either"
r" be (Nt,1) or (Nt,2)")
Qij = -gh * _np.diff(P[cn], axis=1).squeeze()
Qij = _np.append(Qij, -Qij)
Peij = Qij / gd
Peij[(Peij < 1e-10) & (Peij >= 0)] = 1e-10
Peij[(Peij > -1e-10) & (Peij <= 0)] = -1e-10
# Correct the flow rate
Qij = Peij * gd
if s_scheme == 'upwind':
w = gd + _np.maximum(0, -Qij)
elif s_scheme == 'hybrid':
w = _np.maximum(0, _np.maximum(-Qij, gd - Qij / 2))
elif s_scheme == 'powerlaw':
w = gd * _np.maximum(0, (1 - 0.1 * _np.absolute(Peij))**5) + \
_np.maximum(0, -Qij)
elif s_scheme == 'exponential':
w = -Qij / (1 - _np.exp(Peij))
else:
raise Exception('Unrecognized discretization scheme: ' + s_scheme)
w = w.reshape(network.Nt, 2, order='F')
return w
|
Calculates the advective-diffusive conductance of conduits in network.
Parameters
----------
%(phase)s
pore_pressure : str
%(dict_blurb)s pore pressure
throat_hydraulic_conductance : str
%(dict_blurb)s hydraulic conductance
throat_diffusive_conductance : str
%(dict_blurb)s throat diffusive conductance
s_scheme : str
Name of the space discretization scheme to use
Returns
-------
%(return_arr)s advection-diffuvsion conductance values
Notes
-----
This function calculates the specified property for the *entire*
network then extracts the values for the appropriate throats at the
end.
This function assumes cylindrical throats with constant cross-section
area. Corrections for different shapes and variable cross-section area
can be imposed by passing the proper conduit_shape_factors argument
when computing the diffusive and hydraulic conductances.
shape_factor depends on the physics of the problem, i.e.
diffusion-like processes and fluid flow need different shape factors.
|
ad_dif
|
python
|
PMEAL/OpenPNM
|
openpnm/models/physics/ad_dif_conductance/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/physics/ad_dif_conductance/_funcs.py
|
MIT
|
def washburn(phase,
surface_tension="throat.surface_tension",
contact_angle="throat.contact_angle",
diameter="throat.diameter"):
r"""
Computes the capillary entry pressure assuming the throat in a
cylindrical tube.
Parameters
----------
%(phase)s
surface_tension : str
%(dict_blurb)s surface tension. If a pore property is given, it is
interpolated to a throat list.
contact_angle : str
%(dict_blurb)s contact angle. If a pore property is given, it is
interpolated to a throat list.
diameter : str
%(dict_blurb)s throat diameter
Returns
-------
%(return_arr)s capillary entry pressure
Notes
-----
The Washburn equation is:
.. math::
P_c = -\frac{2\sigma(cos(\theta))}{r}
This is the most basic approach to calculating entry pressure and is
suitable for highly non-wetting invading phases in most materials.
"""
network = phase.network
sigma = phase[surface_tension]
theta = phase[contact_angle]
r = network[diameter] / 2
value = -2 * sigma * _np.cos(_np.radians(theta)) / r
if diameter.split(".")[0] == "throat":
pass
else:
value = value[phase.pores()]
value[_np.absolute(value) == _np.inf] = 0
return value
|
Computes the capillary entry pressure assuming the throat in a
cylindrical tube.
Parameters
----------
%(phase)s
surface_tension : str
%(dict_blurb)s surface tension. If a pore property is given, it is
interpolated to a throat list.
contact_angle : str
%(dict_blurb)s contact angle. If a pore property is given, it is
interpolated to a throat list.
diameter : str
%(dict_blurb)s throat diameter
Returns
-------
%(return_arr)s capillary entry pressure
Notes
-----
The Washburn equation is:
.. math::
P_c = -\frac{2\sigma(cos(\theta))}{r}
This is the most basic approach to calculating entry pressure and is
suitable for highly non-wetting invading phases in most materials.
|
washburn
|
python
|
PMEAL/OpenPNM
|
openpnm/models/physics/capillary_pressure/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/physics/capillary_pressure/_funcs.py
|
MIT
|
def purcell(phase,
r_toroid,
surface_tension="throat.surface_tension",
contact_angle="throat.contact_angle",
diameter="throat.diameter"):
r"""
Computes the throat capillary entry pressure assuming the throat is a
toroid.
Parameters
----------
%(phase)s
r_toroid : float or array_like
The radius of the toroid surrounding the pore
surface_tension : str
%(dict_blurb)s surface tension.
contact_angle : str
%(dict_blurb)s contact angle.
diameter : str
%(dict_blurb)s throat diameter
Returns
-------
%(return_arr)s capillary entry pressure
Notes
-----
This approach accounts for the converging-diverging nature of many throat
types. Advancing the meniscus beyond the apex of the toroid requires an
increase in capillary pressure beyond that for a cylindical tube of the
same radius. The details of this equation are described by Mason and
Morrow [1]_, and explored by Gostick [2]_ in the context of a pore network
model.
References
----------
.. [1] G. Mason, N. R. Morrow, Effect of contact angle on capillary
displacement curvatures in pore throats formed by spheres. J.
Colloid Interface Sci. 168, 130 (1994).
.. [2] J. Gostick, Random pore network modeling of fibrous PEMFC gas
diffusion media using Voronoi and Delaunay tessellations. J.
Electrochem. Soc. 160, F731 (2013).
"""
network = phase.network
sigma = phase[surface_tension]
theta = phase[contact_angle]
r = network[diameter] / 2
R = r_toroid
alpha = (
theta - 180 + _np.rad2deg(_np.arcsin(_np.sin(_np.radians(theta)) / (1 + r / R)))
)
value = (-2 * sigma / r) * (
_np.cos(_np.radians(theta - alpha))
/ (1 + R / r * (1 - _np.cos(_np.radians(alpha))))
)
if diameter.split(".")[0] == "throat":
pass
else:
value = value[phase.pores()]
return value
|
Computes the throat capillary entry pressure assuming the throat is a
toroid.
Parameters
----------
%(phase)s
r_toroid : float or array_like
The radius of the toroid surrounding the pore
surface_tension : str
%(dict_blurb)s surface tension.
contact_angle : str
%(dict_blurb)s contact angle.
diameter : str
%(dict_blurb)s throat diameter
Returns
-------
%(return_arr)s capillary entry pressure
Notes
-----
This approach accounts for the converging-diverging nature of many throat
types. Advancing the meniscus beyond the apex of the toroid requires an
increase in capillary pressure beyond that for a cylindical tube of the
same radius. The details of this equation are described by Mason and
Morrow [1]_, and explored by Gostick [2]_ in the context of a pore network
model.
References
----------
.. [1] G. Mason, N. R. Morrow, Effect of contact angle on capillary
displacement curvatures in pore throats formed by spheres. J.
Colloid Interface Sci. 168, 130 (1994).
.. [2] J. Gostick, Random pore network modeling of fibrous PEMFC gas
diffusion media using Voronoi and Delaunay tessellations. J.
Electrochem. Soc. 160, F731 (2013).
|
purcell
|
python
|
PMEAL/OpenPNM
|
openpnm/models/physics/capillary_pressure/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/physics/capillary_pressure/_funcs.py
|
MIT
|
def generic_diffusive(phase,
pore_diffusivity="pore.diffusivity",
throat_diffusivity="throat.diffusivity",
size_factors="throat.diffusive_size_factors"):
r"""
Calculates the diffusive conductance of conduits in network.
Parameters
----------
%(phase)s
pore_diffusivity : str
%(dict_blurb)s pore diffusivity
throat_diffusivity : str
%(dict_blurb)s throat diffusivity
size_factors : str
%(dict_blurb)s conduit diffusive size factors
Returns
-------
%(return_arr)s diffusive conductance
"""
return _poisson_conductance(phase=phase,
pore_conductivity=pore_diffusivity,
throat_conductivity=throat_diffusivity,
size_factors=size_factors)
|
Calculates the diffusive conductance of conduits in network.
Parameters
----------
%(phase)s
pore_diffusivity : str
%(dict_blurb)s pore diffusivity
throat_diffusivity : str
%(dict_blurb)s throat diffusivity
size_factors : str
%(dict_blurb)s conduit diffusive size factors
Returns
-------
%(return_arr)s diffusive conductance
|
generic_diffusive
|
python
|
PMEAL/OpenPNM
|
openpnm/models/physics/diffusive_conductance/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/physics/diffusive_conductance/_funcs.py
|
MIT
|
def ordinary_diffusion(phase,
pore_diffusivity="pore.diffusivity",
throat_diffusivity="throat.diffusivity",
size_factors="throat.diffusive_size_factors"):
r"""
Calculates the diffusive conductance of conduits in network.
Parameters
----------
%(phase)s
pore_diffusivity : str
%(dict_blurb)s pore diffusivity
throat_diffusivity : str
%(dict_blurb)s throat diffusivity
size_factors: str
%(dict_blurb)s conduit diffusive size factors
Returns
-------
%(return_arr)s diffusive conductance
"""
return _poisson_conductance(phase=phase,
pore_conductivity=pore_diffusivity,
throat_conductivity=throat_diffusivity,
size_factors=size_factors)
|
Calculates the diffusive conductance of conduits in network.
Parameters
----------
%(phase)s
pore_diffusivity : str
%(dict_blurb)s pore diffusivity
throat_diffusivity : str
%(dict_blurb)s throat diffusivity
size_factors: str
%(dict_blurb)s conduit diffusive size factors
Returns
-------
%(return_arr)s diffusive conductance
|
ordinary_diffusion
|
python
|
PMEAL/OpenPNM
|
openpnm/models/physics/diffusive_conductance/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/physics/diffusive_conductance/_funcs.py
|
MIT
|
def mixed_diffusion(phase,
pore_diameter="pore.diameter",
throat_diameter="throat.diameter",
pore_diffusivity="pore.diffusivity",
throat_diffusivity="throat.diffusivity",
pore_temperature="pore.temperature",
throat_temperature="throat.temperature",
molecular_weight="pore.molecular_weight",
size_factors="throat.diffusive_size_factors"):
r"""
Calculates the diffusive conductance of conduits in network with
Knudsen correction.
Parameters
----------
%(phase)s
pore_diameter : str
%(dict_blurb)s pore diameter
throat_diameter : str
%(dict_blurb)s throat diameter
pore_diffusivity : str
%(dict_blurb)s pore diffusivity
throat_diffusivity : str
%(dict_blurb)s pore diffusivity
pore_temperature : str
%(dict_blurb)s pore temperature
molecular_weigth : str
%(dict_blurb)s pore molecular weight
size_factors : str
%(dict_blurb)s size factor
Returns
-------
%(return_arr)s diffusive conductance
"""
# Fetch model parameters
Dp = phase[pore_diffusivity]
Dt = phase[throat_diffusivity]
dp = phase.network[pore_diameter]
dt = phase.network[throat_diameter]
MWp = phase[molecular_weight]
MWt = phase.interpolate_data(propname='throat.'+molecular_weight.split('.', 1)[-1])
Tp = phase[pore_temperature]
Tt = phase[throat_temperature]
# Calculate Knudsen contribution
DKp = dp/3 * (8*_const.R*Tp / (_const.pi*MWp)) ** 0.5
DKt = dt/3 * (8*_const.R*Tt / (_const.pi*MWt)) ** 0.5
# Calculate mixed diffusivity
Dp_eff = (1/DKp + 1/Dp) ** -1
Dt_eff = (1/DKt + 1/Dt) ** -1
return _poisson_conductance(phase=phase,
pore_conductivity=Dp_eff,
throat_conductivity=Dt_eff,
size_factors=size_factors)
|
Calculates the diffusive conductance of conduits in network with
Knudsen correction.
Parameters
----------
%(phase)s
pore_diameter : str
%(dict_blurb)s pore diameter
throat_diameter : str
%(dict_blurb)s throat diameter
pore_diffusivity : str
%(dict_blurb)s pore diffusivity
throat_diffusivity : str
%(dict_blurb)s pore diffusivity
pore_temperature : str
%(dict_blurb)s pore temperature
molecular_weigth : str
%(dict_blurb)s pore molecular weight
size_factors : str
%(dict_blurb)s size factor
Returns
-------
%(return_arr)s diffusive conductance
|
mixed_diffusion
|
python
|
PMEAL/OpenPNM
|
openpnm/models/physics/diffusive_conductance/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/physics/diffusive_conductance/_funcs.py
|
MIT
|
def taylor_aris_diffusion(phase,
pore_area="pore.area",
throat_area="throat.cross_sectional_area",
pore_diffusivity="pore.diffusivity",
throat_diffusivity="throat.diffusivity",
pore_pressure="pore.pressure",
throat_hydraulic_conductance="throat.hydraulic_conductance",
size_factors="throat.diffusive_size_factors"):
r"""
Calculates the diffusive conductance of conduits in network
considering the Taylor-Aris effect (effect of flow on diffusion).
Parameters
----------
%(phase)s
pore_area : str
%(dict_blurb)s pore cross-sectional area
throat_area : str
%(dict_blurb)s throat cross-sectional area
pore_diffusivity : str
%(dict_blurb)s pore diffusivity
throat_diffusivity : str
%(dict_blurb)s pore diffusivity
pore_pressure : str
%(dict_blurb)s pore pressure
throat_hydraulic_conductance : str
%(dict_blurb)s throat hydraulic conductance
size_factors : str
%(dict_blurb)s conduit size factors
Returns
-------
%(return_arr)s diffusive conductance
"""
network = phase.network
cn = network['throat.conns']
F = network[size_factors]
# Fetch model parameters
A1, A2 = network[pore_area][cn].T
At = network[throat_area]
D1, D2 = phase[pore_diffusivity][cn].T
Dt = phase[throat_diffusivity]
P = phase[pore_pressure]
gh = phase[throat_hydraulic_conductance]
# Calculate Peclet number
Qt = -gh * _np.diff(P[cn], axis=1).squeeze()
u1, ut, u2 = [Qt/Ai for Ai in [A1, At, A2]]
Pe1 = u1 * ((4 * A1 / _np.pi) ** 0.5) / D1
Pe2 = u2 * ((4 * A2 / _np.pi) ** 0.5) / D2
Pet = ut * ((4 * At / _np.pi) ** 0.5) / Dt
if F.ndim > 1:
g1 = D1 * (1 + Pe1**2 / 192) * F[:, 0]
gt = Dt * (1 + Pet**2 / 192) * F[:, 1]
g2 = D2 * (1 + Pe2**2 / 192) * F[:, 2]
gtot = 1 / (1/g1 + 1/gt + 1/g2)
else:
gtot = Dt * (1 + Pet**2 / 192) * F
return gtot
|
Calculates the diffusive conductance of conduits in network
considering the Taylor-Aris effect (effect of flow on diffusion).
Parameters
----------
%(phase)s
pore_area : str
%(dict_blurb)s pore cross-sectional area
throat_area : str
%(dict_blurb)s throat cross-sectional area
pore_diffusivity : str
%(dict_blurb)s pore diffusivity
throat_diffusivity : str
%(dict_blurb)s pore diffusivity
pore_pressure : str
%(dict_blurb)s pore pressure
throat_hydraulic_conductance : str
%(dict_blurb)s throat hydraulic conductance
size_factors : str
%(dict_blurb)s conduit size factors
Returns
-------
%(return_arr)s diffusive conductance
|
taylor_aris_diffusion
|
python
|
PMEAL/OpenPNM
|
openpnm/models/physics/diffusive_conductance/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/physics/diffusive_conductance/_funcs.py
|
MIT
|
def generic_electrical(
phase,
pore_conductivity='pore.electrical_conductivity',
throat_conductivity='throat.electrical_conductivity',
size_factors='throat.diffusive_size_factors'
):
r"""
Calculate the electrical conductance of conduits in network, where a
conduit is ( 1/2 pore - full throat - 1/2 pore ). See the notes section.
Parameters
----------
%(phase)s
pore_conductivity : str
%(dict_blurb)s pore electrical conductivity
throat_conductivity : str
%(dict_blurb)s throat electrical conductivity
size_factors: str
%(dict_blurb)s conduit diffusive size factors
Returns
-------
%(return_arr)s electrical conductance
"""
return _poisson_conductance(phase=phase,
pore_conductivity=pore_conductivity,
throat_conductivity=throat_conductivity,
size_factors=size_factors)
|
Calculate the electrical conductance of conduits in network, where a
conduit is ( 1/2 pore - full throat - 1/2 pore ). See the notes section.
Parameters
----------
%(phase)s
pore_conductivity : str
%(dict_blurb)s pore electrical conductivity
throat_conductivity : str
%(dict_blurb)s throat electrical conductivity
size_factors: str
%(dict_blurb)s conduit diffusive size factors
Returns
-------
%(return_arr)s electrical conductance
|
generic_electrical
|
python
|
PMEAL/OpenPNM
|
openpnm/models/physics/electrical_conductance/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/physics/electrical_conductance/_funcs.py
|
MIT
|
def series_resistors(
phase,
pore_conductivity='pore.electrical_conductivity',
throat_conductivity='throat.electrical_conductivity',
size_factors='throat.diffusive_size_factors'
):
r"""
Calculate the electrical conductance of conduits in network, where a
conduit is ( 1/2 pore - full throat - 1/2 pore ). See the notes section.
Parameters
----------
%(phase)s
pore_conductivity : str
%(dict_blurb)s pore electrical conductivity
throat_conductivity : str
%(dict_blurb)s throat electrical conductivity
size_factors: str
%(dict_blurb)s conduit diffusive size factors
Returns
-------
%(return_arr)s electrical conductance
"""
return _poisson_conductance(phase=phase,
pore_conductivity=pore_conductivity,
throat_conductivity=throat_conductivity,
size_factors=size_factors)
|
Calculate the electrical conductance of conduits in network, where a
conduit is ( 1/2 pore - full throat - 1/2 pore ). See the notes section.
Parameters
----------
%(phase)s
pore_conductivity : str
%(dict_blurb)s pore electrical conductivity
throat_conductivity : str
%(dict_blurb)s throat electrical conductivity
size_factors: str
%(dict_blurb)s conduit diffusive size factors
Returns
-------
%(return_arr)s electrical conductance
|
series_resistors
|
python
|
PMEAL/OpenPNM
|
openpnm/models/physics/electrical_conductance/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/physics/electrical_conductance/_funcs.py
|
MIT
|
def generic_hydraulic(
phase,
pore_viscosity='pore.viscosity',
throat_viscosity='throat.viscosity',
size_factors='throat.hydraulic_size_factors'
):
r"""
Calculates the hydraulic conductance of conduits in network.
Parameters
----------
%(phase)s
pore_viscosity : str
%(dict_blurb)s pore viscosity
throat_viscosity : str
%(dict_blurb)s throat viscosity
size_factors : str
%(dict_blurb)s conduit hydraulic size factors
Returns
-------
%(return_arr)s hydraulic conductance
"""
network = phase.network
conns = network.conns
mu1, mu2 = phase[pore_viscosity][conns].T
mut = phase[throat_viscosity]
SF = network[size_factors]
if isinstance(SF, dict): # Legacy approach
F1, Ft, F2 = SF.values()
elif SF.ndim > 1: # Nt-by-3 array
F1, Ft, F2 = SF.T
else: # Nt array, like from network extraction predictions
F1, Ft, F2 = _np.inf, SF, _np.inf
g1 = F1 / mu1
gt = Ft / mut
g2 = F2 / mu2
return 1 / (1/g1 + 1/gt + 1/g2)
|
Calculates the hydraulic conductance of conduits in network.
Parameters
----------
%(phase)s
pore_viscosity : str
%(dict_blurb)s pore viscosity
throat_viscosity : str
%(dict_blurb)s throat viscosity
size_factors : str
%(dict_blurb)s conduit hydraulic size factors
Returns
-------
%(return_arr)s hydraulic conductance
|
generic_hydraulic
|
python
|
PMEAL/OpenPNM
|
openpnm/models/physics/hydraulic_conductance/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/physics/hydraulic_conductance/_funcs.py
|
MIT
|
def hagen_poiseuille(
phase,
pore_viscosity="pore.viscosity",
throat_viscosity="throat.viscosity",
size_factors="throat.hydraulic_size_factors"
):
r"""
Calculates the hydraulic conductance of conduits in network.
Parameters
----------
%(phase)s
pore_viscosity : str
%(dict_blurb)s pore viscosity
throat_viscosity : str
%(dict_blurb)s throat viscosity
size_factors : str
%(dict_blurb)s conduit hydraulic size factors
Returns
-------
%(return_arr)s hydraulic conductance
"""
return generic_hydraulic(phase=phase,
pore_viscosity=pore_viscosity,
throat_viscosity=throat_viscosity,
size_factors=size_factors)
|
Calculates the hydraulic conductance of conduits in network.
Parameters
----------
%(phase)s
pore_viscosity : str
%(dict_blurb)s pore viscosity
throat_viscosity : str
%(dict_blurb)s throat viscosity
size_factors : str
%(dict_blurb)s conduit hydraulic size factors
Returns
-------
%(return_arr)s hydraulic conductance
|
hagen_poiseuille
|
python
|
PMEAL/OpenPNM
|
openpnm/models/physics/hydraulic_conductance/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/physics/hydraulic_conductance/_funcs.py
|
MIT
|
def general_toroidal(
phase,
profile_equation='elliptical',
mode='max',
target_Pc=None,
num_points=1000,
throat_scale_a='throat.scale_a',
throat_scale_b='throat.scale_b',
throat_diameter='throat.diameter',
touch_length='throat.touch_length',
surface_tension='throat.surface_tension',
contact_angle='throat.contact_angle'
):
r"""
The general model for meniscus properties inside a toroidal throat
Parameters
----------
%(phase)s
profile_equation : str
Options are 'elliptical' (default), 'sinusoidal'.
mode : str
Determines what information to send back. Options are:
======== =========================================================
Mode Description
======== =========================================================
'max' (default) The maximum capillary pressure along the throat
axis
'touch' The maximum capillary pressure a meniscus can sustain
before touching a solid feature
======== =========================================================
target_Pc : float
The target capillary pressure to return data for when mode is 'men'
num_points : float
The number of divisions to make along the profile length to assess the
meniscus properties in order to find target pressures, touch lengths,
minima and maxima. The default is 1000.
throat_scale_a : str
%(dict_blurb)s scale factor for adjusting the profile along the
throat axis (x).
throat_scale_b : str
%(dict_blurb)s scale factor for adjusting the profile perpendicular
to the throat axis (y).
throat_diameter : str
%(dict_blurb)s throat diameter values to be used.
touch_length : str
%(dict_blurb)s maximum length that a meniscus can
protrude into the connecting pore before touching a solid feature and
therfore invading
surface_tension : str
%(dict_blurb)s surface tension values to be used. If a pore property
is given, it is interpolated to a throat list.
contact_angle : str
%(dict_blurb)s contact angle values to be used. If a pore property
is given, it is interpolated to a throat list.
Returns
-------
values : dict
A dictionary containing the following entries:
============ =========================================================
Item Description
============ =========================================================
'pos' xpos
'rx' rx(xpos, fa, fb, throatRad)
'alpha' fill_angle(xpos, fa, fb, throatRad)
'alpha_min' fill_angle(xmin, fa, fb, throatRad)
'alpha_max' fill_angle(xmax, fa, fb, throatRad)
'c2x' c2x(xpos, fa, fb, throatRad, contact)
'gamma' cap_angle(xpos, fa, fb, throatRad, contact)
'radius' rad_curve(xpos, fa, fb, throatRad, contact)
'center' (xpos - men_data['c2x'])
'men_max' ??
============ =========================================================
"""
from sympy import symbols, lambdify
from sympy import atan as sym_atan
from sympy import cos as sym_cos
from sympy import sin as sym_sin
from sympy import sqrt as sym_sqrt
from sympy import pi as sym_pi
# Get data from dictionary keys
network = phase.network
surface_tension = phase[surface_tension]
contact = phase[contact_angle]
# Contact Angle in radians
contact = np.deg2rad(contact)
# Network properties
throatRad = network[throat_diameter]/2
# Scaling parameters for throat profile
fa = phase[throat_scale_a]
fb = phase[throat_scale_b]
# Governing equations
x, a, b, rt, sigma, theta = symbols('x, a, b, rt, sigma, theta')
if profile_equation == 'elliptical':
y = sym_sqrt(1 - (x/a)**2)*b
elif profile_equation == 'sinusoidal':
y = (sym_cos((sym_pi/2)*(x/a)))*b
else:
logger.error('Profile equation is not valid, default to elliptical')
y = sym_sqrt(1 - (x/a)**2)*b
# Throat radius profile
r = rt + (b-y)
# Derivative of profile
rprime = r.diff(x)
# Filling angle
alpha = sym_atan(rprime)
# Angle between y axis and contact point to meniscus center
eta = sym_pi - alpha - theta
gamma = sym_pi/2 - eta
# Radius of curvature of meniscus
rm = r/sym_cos(eta)
# distance from center of curvature to meniscus contact point (Pythagoras)
d = rm*sym_sin(eta)
# angle between throat axis, meniscus center and meniscus contact point
# Capillary Pressure
p = 2*sigma/rm
# Callable functions
rx = lambdify((x, a, b, rt), r, 'numpy')
fill_angle = lambdify((x, a, b, rt), alpha, 'numpy')
rad_curve = lambdify((x, a, b, rt, theta), rm, 'numpy')
c2x = lambdify((x, a, b, rt, theta), d, 'numpy')
cap_angle = lambdify((x, a, b, rt, theta), gamma, 'numpy')
Pc = lambdify((x, a, b, rt, theta, sigma), p, 'numpy')
# All relative positions along throat
hp = int(num_points/2)
log_pos = np.logspace(-4, -1, hp+1)[:-1]
lin_pos = np.arange(0.1, 1.0, 1/hp)
half_pos = np.concatenate((log_pos, lin_pos))
pos = np.concatenate((-half_pos[::-1], half_pos))
# Now find the positions of the menisci along each throat axis
Y, X = np.meshgrid(throatRad, pos)
X *= fa
# throat Capillary Pressure
t_Pc = Pc(X, fa, fb, Y, contact, surface_tension)
# Values of minima and maxima
Pc_min = np.min(t_Pc, axis=0)
Pc_max = np.max(t_Pc, axis=0)
# Arguments of minima and maxima
a_min = np.argmin(t_Pc, axis=0)
a_max = np.argmax(t_Pc, axis=0)
if mode == 'max':
return Pc_max
elif mode == 'touch':
all_rad = rad_curve(X, fa, fb, Y, contact)
all_c2x = c2x(X, fa, fb, Y, contact)
all_cen = X - all_c2x
dist = all_cen + all_rad
# Only count lengths where meniscus bulges into pore
dist[all_rad < 0] = 0.0
touch_len = network[touch_length]
mask = dist > touch_len
arg_touch = np.argmax(mask, axis=0)
# Make sure we only count ones that happen before max pressure
# And above min pressure (which will be erroneous)
arg_in_range = (arg_touch < a_max) * (arg_touch > a_min)
arg_touch[~arg_in_range] = a_max[~arg_in_range]
x_touch = pos[arg_touch]*fa
# Return the pressure at which a touch happens
Pc_touch = Pc(x_touch, fa, fb, throatRad, contact, surface_tension)
return Pc_touch
elif (mode == 'men'):
if target_Pc is None:
logger.error(msg='Please supply a target capillary pressure'
+ ' when mode is "men", defaulting to 1.0e-6')
target_Pc = 1.0e-6
else:
raise Exception('Unrecognized mode')
if np.abs(target_Pc) < 1.0e-6:
logger.error(msg='Please supply a target capillary pressure'
+ ' with absolute value greater than 1.0e-6,'
+ ' default to 1.0e-6')
target_Pc = 1.0e-6
# Find the position in-between the minima and maxima corresponding to
# the target pressure
inds = np.indices(np.shape(t_Pc))
# Change values outside the range between minima and maxima to be those
# Values
mask = inds[0] < np.ones(len(pos))[:, np.newaxis]*a_min
t_Pc[mask] = (np.ones(len(pos))[:, np.newaxis]*Pc_min)[mask]
mask = inds[0] > np.ones(len(pos))[:, np.newaxis]*a_max
t_Pc[mask] = (np.ones(len(pos))[:, np.newaxis]*Pc_max)[mask]
# Find the argument at or above the target Pressure
mask = t_Pc >= target_Pc
arg_x = np.argmax(mask, axis=0)
# If outside range change to minima or maxima accordingly
arg_x[target_Pc < Pc_min] = a_min[target_Pc < Pc_min]
arg_x[target_Pc > Pc_max] = a_max[target_Pc > Pc_max]
xpos = pos[arg_x]*fa
xmin = pos[a_min]*fa
xmax = pos[a_max]*fa
# Output
men_data = {}
men_data['pos'] = xpos
men_data['rx'] = rx(xpos, fa, fb, throatRad)
men_data['alpha'] = fill_angle(xpos, fa, fb, throatRad)
men_data['alpha_min'] = fill_angle(xmin, fa, fb, throatRad)
men_data['alpha_max'] = fill_angle(xmax, fa, fb, throatRad)
men_data['c2x'] = c2x(xpos, fa, fb, throatRad, contact)
men_data['gamma'] = cap_angle(xpos, fa, fb, throatRad, contact)
men_data['radius'] = rad_curve(xpos, fa, fb, throatRad, contact)
# xpos is relative to the throat center
men_data['center'] = (xpos - men_data['c2x'])
men_data['men_max'] = men_data['center'] - men_data['radius']
logger.info(mode+' calculated for Pc: '+str(target_Pc))
return men_data
|
The general model for meniscus properties inside a toroidal throat
Parameters
----------
%(phase)s
profile_equation : str
Options are 'elliptical' (default), 'sinusoidal'.
mode : str
Determines what information to send back. Options are:
======== =========================================================
Mode Description
======== =========================================================
'max' (default) The maximum capillary pressure along the throat
axis
'touch' The maximum capillary pressure a meniscus can sustain
before touching a solid feature
======== =========================================================
target_Pc : float
The target capillary pressure to return data for when mode is 'men'
num_points : float
The number of divisions to make along the profile length to assess the
meniscus properties in order to find target pressures, touch lengths,
minima and maxima. The default is 1000.
throat_scale_a : str
%(dict_blurb)s scale factor for adjusting the profile along the
throat axis (x).
throat_scale_b : str
%(dict_blurb)s scale factor for adjusting the profile perpendicular
to the throat axis (y).
throat_diameter : str
%(dict_blurb)s throat diameter values to be used.
touch_length : str
%(dict_blurb)s maximum length that a meniscus can
protrude into the connecting pore before touching a solid feature and
therfore invading
surface_tension : str
%(dict_blurb)s surface tension values to be used. If a pore property
is given, it is interpolated to a throat list.
contact_angle : str
%(dict_blurb)s contact angle values to be used. If a pore property
is given, it is interpolated to a throat list.
Returns
-------
values : dict
A dictionary containing the following entries:
============ =========================================================
Item Description
============ =========================================================
'pos' xpos
'rx' rx(xpos, fa, fb, throatRad)
'alpha' fill_angle(xpos, fa, fb, throatRad)
'alpha_min' fill_angle(xmin, fa, fb, throatRad)
'alpha_max' fill_angle(xmax, fa, fb, throatRad)
'c2x' c2x(xpos, fa, fb, throatRad, contact)
'gamma' cap_angle(xpos, fa, fb, throatRad, contact)
'radius' rad_curve(xpos, fa, fb, throatRad, contact)
'center' (xpos - men_data['c2x'])
'men_max' ??
============ =========================================================
|
general_toroidal
|
python
|
PMEAL/OpenPNM
|
openpnm/models/physics/meniscus/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/physics/meniscus/_funcs.py
|
MIT
|
def sinusoidal(
phase,
mode='max',
target_Pc=None,
num_points=1e3,
r_toroid=5e-6,
throat_diameter='throat.diameter',
pore_diameter='pore.diameter',
touch_length='throat.touch_length',
surface_tension='throat.surface_tension',
contact_angle='throat.contact_angle'
):
r"""
Wrapper for the toroidal model to implement a sinusoidal profile.
The quarter-wavelength is equal to toroidal radius r_toroid.
The amplitude is equal to the toroidal radius multiplied by the ratio
of the throat radius and average connecting pore radius.
Notes
-----
The capillary pressure equation for a sinusoidal throat is extended
from the Washburn equation as [1]_:
.. math::
P_c = -\frac{2\sigma(cos(\alpha + \theta))}{r(x)}
where alpha is:
.. math::
\alpha = arctan(\frac{dr}{dx})
References
----------
.. [1] A. Forner-Cuenca et. al, Advanced Water Management in PEFCs:
Diffusion Layers with Patterned Wettability.
J. ECS. 163, 9, F1038-F1048 (2016).
"""
phase['throat.scale_a'] = r_toroid
phase['throat.scale_b'] = r_toroid
output = general_toroidal(phase=phase,
mode=mode,
profile_equation='sinusoidal',
target_Pc=target_Pc,
num_points=num_points,
throat_diameter=throat_diameter,
touch_length=touch_length,
surface_tension=surface_tension,
contact_angle=contact_angle)
return output
|
Wrapper for the toroidal model to implement a sinusoidal profile.
The quarter-wavelength is equal to toroidal radius r_toroid.
The amplitude is equal to the toroidal radius multiplied by the ratio
of the throat radius and average connecting pore radius.
Notes
-----
The capillary pressure equation for a sinusoidal throat is extended
from the Washburn equation as [1]_:
.. math::
P_c = -\frac{2\sigma(cos(\alpha + \theta))}{r(x)}
where alpha is:
.. math::
\alpha = arctan(\frac{dr}{dx})
References
----------
.. [1] A. Forner-Cuenca et. al, Advanced Water Management in PEFCs:
Diffusion Layers with Patterned Wettability.
J. ECS. 163, 9, F1038-F1048 (2016).
|
sinusoidal
|
python
|
PMEAL/OpenPNM
|
openpnm/models/physics/meniscus/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/physics/meniscus/_funcs.py
|
MIT
|
def purcell(
phase,
mode='max',
target_Pc=None,
num_points=1e3,
r_toroid=5e-6,
throat_diameter='throat.diameter',
touch_length='throat.touch_length',
surface_tension='throat.surface_tension',
contact_angle='throat.contact_angle'
):
r"""
Wrapper for the general toroidal model to implement the Purcell
equation for a torus with cylindrical profile and toroidal radius
r_toroid.
Notes
-----
This approach accounts for the converging-diverging nature of many
throat types. Advancing the meniscus beyond the apex of the toroid
requires an increase in capillary pressure beyond that for a
cylindical tube of the same radius. The details of this equation are
described by Mason and Morrow [1], and explored by Gostick [2] in the
context of a pore network model.
References
----------
[1] Missing reference
[2] Missing reference
"""
phase['throat.scale_a'] = r_toroid
phase['throat.scale_b'] = r_toroid
output = general_toroidal(phase=phase,
mode=mode,
profile_equation='elliptical',
target_Pc=target_Pc,
num_points=num_points,
throat_diameter=throat_diameter,
touch_length=touch_length,
surface_tension=surface_tension,
contact_angle=contact_angle)
return output
|
Wrapper for the general toroidal model to implement the Purcell
equation for a torus with cylindrical profile and toroidal radius
r_toroid.
Notes
-----
This approach accounts for the converging-diverging nature of many
throat types. Advancing the meniscus beyond the apex of the toroid
requires an increase in capillary pressure beyond that for a
cylindical tube of the same radius. The details of this equation are
described by Mason and Morrow [1], and explored by Gostick [2] in the
context of a pore network model.
References
----------
[1] Missing reference
[2] Missing reference
|
purcell
|
python
|
PMEAL/OpenPNM
|
openpnm/models/physics/meniscus/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/physics/meniscus/_funcs.py
|
MIT
|
def late_filling(phase, pressure='pore.pressure',
Pc_star='pore.pc_star',
Swp_star=0.2, eta=3):
r"""
Calculates the fraction of a pore or throat filled with invading fluid
based on the capillary pressure in the invading phase. The invading phase
volume is calculated from:
.. math::
S_{nwp} = 1 - S_{wp}^{*} (P^{*}/P_{c})^{\eta}
Parameters
----------
pressure : str
%(dict_blurb)s capillary pressure in the non-wetting phase (Pc > 0).
Pc_star : str
%(dict_blurb)s minimum pressure required to create an interface
within the pore body or throat. Typically this would be calculated
using the Washburn equation.
Swp_star : float
The residual wetting phase in an invaded pore or throat at a pressure
of ``pc_star``.
eta : float
Exponent controlling the rate at which wetting phase is displaced with
increasing pressure.
Returns
-------
%(return_arr)s fraction of each pore or throat that would be filled with
non-wetting phase at the given phase pressure. This does not account
for whether or not the element is actually invaded, which requires a
percolation algorithm of some sort.
"""
pc_star = phase[Pc_star]
Pc = phase[pressure]
# Remove any 0's from the Pc array to prevent numpy div by 0 warning
Pc = np.maximum(Pc, 1e-9)
Swp = Swp_star*((pc_star/Pc)**eta)
values = np.clip(1 - Swp, 0.0, 1.0)
return values
|
Calculates the fraction of a pore or throat filled with invading fluid
based on the capillary pressure in the invading phase. The invading phase
volume is calculated from:
.. math::
S_{nwp} = 1 - S_{wp}^{*} (P^{*}/P_{c})^{\eta}
Parameters
----------
pressure : str
%(dict_blurb)s capillary pressure in the non-wetting phase (Pc > 0).
Pc_star : str
%(dict_blurb)s minimum pressure required to create an interface
within the pore body or throat. Typically this would be calculated
using the Washburn equation.
Swp_star : float
The residual wetting phase in an invaded pore or throat at a pressure
of ``pc_star``.
eta : float
Exponent controlling the rate at which wetting phase is displaced with
increasing pressure.
Returns
-------
%(return_arr)s fraction of each pore or throat that would be filled with
non-wetting phase at the given phase pressure. This does not account
for whether or not the element is actually invaded, which requires a
percolation algorithm of some sort.
|
late_filling
|
python
|
PMEAL/OpenPNM
|
openpnm/models/physics/multiphase/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/physics/multiphase/_funcs.py
|
MIT
|
def standard_kinetics(phase, X, prefactor, exponent):
r"""
Calculates the rate, as well as slope and intercept of the following
function at the given value of ``X``:
.. math::
r = A X^b
Parameters
----------
%(phase)s
X : str
%(dict_blurb)s quantity of interest
prefactor : str
%(dict_blurb)s the prefactor to be used in the source term model
exponent : str
%(dict_blurb)s the exponent to be used in the source term model
Returns
-------
rate_info : dict
A dictionary containing the following three items:
======= ==============================================================
Item Description
======= ==============================================================
rate The value of the source term function at the given X.
S1 The slope of the source term function at the given X.
S2 The intercept of the source term function at the given X.
======= ==============================================================
Notes
-----
The slope and intercept provide a linearized source term equation about the
current value of X as follow:
.. math::
rate = S_{1} X + S_{2}
"""
X = phase[X]
A = phase[prefactor]
b = phase[exponent]
r = A*(X**b)
S1 = A*b*(X**(b - 1))
S2 = A*(1 - b)*(X**b)
values = {'S1': S1, 'S2': S2, 'rate': r}
return values
|
Calculates the rate, as well as slope and intercept of the following
function at the given value of ``X``:
.. math::
r = A X^b
Parameters
----------
%(phase)s
X : str
%(dict_blurb)s quantity of interest
prefactor : str
%(dict_blurb)s the prefactor to be used in the source term model
exponent : str
%(dict_blurb)s the exponent to be used in the source term model
Returns
-------
rate_info : dict
A dictionary containing the following three items:
======= ==============================================================
Item Description
======= ==============================================================
rate The value of the source term function at the given X.
S1 The slope of the source term function at the given X.
S2 The intercept of the source term function at the given X.
======= ==============================================================
Notes
-----
The slope and intercept provide a linearized source term equation about the
current value of X as follow:
.. math::
rate = S_{1} X + S_{2}
|
standard_kinetics
|
python
|
PMEAL/OpenPNM
|
openpnm/models/physics/source_terms/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/physics/source_terms/_funcs.py
|
MIT
|
def linear(phase, X, A1=0.0, A2=0.0):
r"""
Calculates the rate, as well as slope and intercept of the following
function at the given value of ``X``:
.. math::
r = A_{1} X + A_{2}
Parameters
----------
%(phase)s
X : str
The dictionary key on the phase object containing the the quantity
of interest
A1 -> A2 : str
The dictionary keys on the phase object containing the coefficients
values to be used in the source term model
Returns
-------
dict
A dictionary containing the following three items:
'rate'
The value of the source term function at the given X.
'S1'
The slope of the source term function at the given X.
'S2'
The intercept of the source term function at the given X.
Notes
-----
The slope and intercept provide a linearized source term equation about the
current value of X as follow:
.. math::
rate = S_{1} X + S_{2}
"""
r = phase[A1] * phase[X] + phase[A2]
S1 = phase[A1]
S2 = phase[A2]
values = {'S1': S1, 'S2': S2, 'rate': r}
return values
|
Calculates the rate, as well as slope and intercept of the following
function at the given value of ``X``:
.. math::
r = A_{1} X + A_{2}
Parameters
----------
%(phase)s
X : str
The dictionary key on the phase object containing the the quantity
of interest
A1 -> A2 : str
The dictionary keys on the phase object containing the coefficients
values to be used in the source term model
Returns
-------
dict
A dictionary containing the following three items:
'rate'
The value of the source term function at the given X.
'S1'
The slope of the source term function at the given X.
'S2'
The intercept of the source term function at the given X.
Notes
-----
The slope and intercept provide a linearized source term equation about the
current value of X as follow:
.. math::
rate = S_{1} X + S_{2}
|
linear
|
python
|
PMEAL/OpenPNM
|
openpnm/models/physics/source_terms/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/physics/source_terms/_funcs.py
|
MIT
|
def power_law(phase, X, A1=0.0, A2=0.0, A3=0.0):
r"""
Calculates the rate, as well as slope and intercept of the following
function at the given value of *X*:
.. math::
r = A_{1} x^{A_{2}} + A_{3}
Parameters
----------
%(phase)s
X : str
The dictionary key on the phase object containing the the quantity
of interest
A1 -> A3 : str
The dictionary keys on the phase object containing the coefficients
values to be used in the source term model
Returns
-------
dict
A dictionary containing the following three items:
'rate'
The value of the source term function at the given X.
'S1'
The slope of the source term function at the given X.
'S2'
The intercept of the source term function at the given X.
Notes
-----
The slope and intercept provide a linearized source term equation about the
current value of X as follow:
.. math::
rate = S_{1} X + S_{2}
"""
A = phase[A1]
B = phase[A2]
C = phase[A3]
X = phase[X]
r = A * X ** B + C
S1 = A * B * X ** (B - 1)
S2 = A * X ** B * (1 - B) + C
values = {'S1': S1, 'S2': S2, 'rate': r}
return values
|
Calculates the rate, as well as slope and intercept of the following
function at the given value of *X*:
.. math::
r = A_{1} x^{A_{2}} + A_{3}
Parameters
----------
%(phase)s
X : str
The dictionary key on the phase object containing the the quantity
of interest
A1 -> A3 : str
The dictionary keys on the phase object containing the coefficients
values to be used in the source term model
Returns
-------
dict
A dictionary containing the following three items:
'rate'
The value of the source term function at the given X.
'S1'
The slope of the source term function at the given X.
'S2'
The intercept of the source term function at the given X.
Notes
-----
The slope and intercept provide a linearized source term equation about the
current value of X as follow:
.. math::
rate = S_{1} X + S_{2}
|
power_law
|
python
|
PMEAL/OpenPNM
|
openpnm/models/physics/source_terms/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/physics/source_terms/_funcs.py
|
MIT
|
def exponential(phase, X, A1=0.0, A2=1.0, A3=1.0, A4=1.0, A5=0.0, A6=0.0):
r"""
Calculates the rate, as well as slope and intercept of the following
function at the given value of `X`:
.. math::
r = A_{1} A_{2}^{( A_{3} x^{ A_{4} } + A_{5})} + A_{6}
Parameters
----------
%(phase)s
X : str
The dictionary key on the phase object containing the the quantity
of interest
A1 -> A6 : str
The dictionary keys on the phase object containing the coefficients
values to be used in the source term model
Returns
-------
dict
A dictionary containing the following three items:
'rate'
The value of the source term function at the given X.
'S1'
The slope of the source term function at the given X.
'S2'
The intercept of the source term function at the given X.
Notes
-----
The slope and intercept provide a linearized source term equation about the
current value of X as follow:
.. math::
rate = S_{1} X + S_{2}
"""
A = phase[A1]
B = phase[A2]
C = phase[A3]
D = phase[A4]
E = phase[A5]
F = phase[A6]
X = phase[X]
r = A * B ** (C * X ** D + E) + F
S1 = A * C * D * X ** (D - 1) * _np.log(B) * B ** (C * X ** D + E)
S2 = A * B ** (C * X ** D + E) * (1 - C * D * _np.log(B) * X ** D) + F
values = {'S1': S1, 'S2': S2, 'rate': r}
return values
|
Calculates the rate, as well as slope and intercept of the following
function at the given value of `X`:
.. math::
r = A_{1} A_{2}^{( A_{3} x^{ A_{4} } + A_{5})} + A_{6}
Parameters
----------
%(phase)s
X : str
The dictionary key on the phase object containing the the quantity
of interest
A1 -> A6 : str
The dictionary keys on the phase object containing the coefficients
values to be used in the source term model
Returns
-------
dict
A dictionary containing the following three items:
'rate'
The value of the source term function at the given X.
'S1'
The slope of the source term function at the given X.
'S2'
The intercept of the source term function at the given X.
Notes
-----
The slope and intercept provide a linearized source term equation about the
current value of X as follow:
.. math::
rate = S_{1} X + S_{2}
|
exponential
|
python
|
PMEAL/OpenPNM
|
openpnm/models/physics/source_terms/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/physics/source_terms/_funcs.py
|
MIT
|
def natural_exponential(phase, X, A1=0.0, A2=0.0, A3=0.0, A4=0.0, A5=0.0):
r"""
Calculates the rate, as well as slope and intercept of the following
function at the given value of `X`:
.. math::
r = A_{1} exp( A_{2} x^{ A_{3} } + A_{4} )+ A_{5}
Parameters
----------
%(phase)s
X : str
The dictionary key on the phase object containing the the quantity
of interest
A1 -> A5 : str
The dictionary keys on the phase object containing the coefficients
values to be used in the source term model
Returns
-------
dict
A dictionary containing the following three items:
'rate'
The value of the source term function at the given X.
'S1'
The slope of the source term function at the given X.
'S2'
The intercept of the source term function at the given X.
Notes
-----
The slope and intercept provide a linearized source term equation about the
current value of X as follow:
.. math::
rate = S_{1} X + S_{2}
"""
A = phase[A1]
B = phase[A2]
C = phase[A3]
D = phase[A4]
E = phase[A5]
X = phase[X]
r = A * _np.exp(B * X ** C + D) + E
S1 = A * B * C * X ** (C - 1) * _np.exp(B * X ** C + D)
S2 = A * (1 - B * C * X ** C) * _np.exp(B * X ** C + D) + E
values = {'pore.S1': S1, 'pore.S2': S2, 'pore.rate': r}
return values
|
Calculates the rate, as well as slope and intercept of the following
function at the given value of `X`:
.. math::
r = A_{1} exp( A_{2} x^{ A_{3} } + A_{4} )+ A_{5}
Parameters
----------
%(phase)s
X : str
The dictionary key on the phase object containing the the quantity
of interest
A1 -> A5 : str
The dictionary keys on the phase object containing the coefficients
values to be used in the source term model
Returns
-------
dict
A dictionary containing the following three items:
'rate'
The value of the source term function at the given X.
'S1'
The slope of the source term function at the given X.
'S2'
The intercept of the source term function at the given X.
Notes
-----
The slope and intercept provide a linearized source term equation about the
current value of X as follow:
.. math::
rate = S_{1} X + S_{2}
|
natural_exponential
|
python
|
PMEAL/OpenPNM
|
openpnm/models/physics/source_terms/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/physics/source_terms/_funcs.py
|
MIT
|
def logarithm(phase, X, A1=0.0, A2=10.0, A3=1.0, A4=1.0, A5=0.0, A6=0.0):
r"""
Calculates the rate, as well as slope and intercept of the following
function at the given value of `X`:
.. math::
r = A_{1} Log_{ A_{2} }( A_{3} x^{ A_{4} }+ A_{5})+ A_{6}
Parameters
----------
%(phase)s
X : str
The dictionary key on the phase object containing the the quantity
of interest
A1 -> A6 : str
The dictionary keys on the phase object containing the coefficients
values to be used in the source term model
Returns
-------
dict
A dictionary containing the following three items:
'rate'
The value of the source term function at the given X.
'S1'
The slope of the source term function at the given X.
'S2'
The intercept of the source term function at the given X.
Notes
-----
The slope and intercept provide a linearized source term equation about the
current value of X as follow:
.. math::
rate = S_{1} X + S_{2}
"""
A = phase[A1]
B = phase[A2]
C = phase[A3]
D = phase[A4]
E = phase[A5]
F = phase[A6]
X = phase[X]
r = (A * _np.log(C * X ** D + E)/_np.log(B) + F)
S1 = A * C * D * X ** (D - 1) / (_np.log(B) * (C * X ** D + E))
S2 = A * _np.log(C * X ** D + E) / _np.log(B) + F - A * C * D * X ** D / \
(_np.log(B) * (C * X ** D + E))
values = {'S1': S1, 'S2': S2, 'rate': r}
return values
|
Calculates the rate, as well as slope and intercept of the following
function at the given value of `X`:
.. math::
r = A_{1} Log_{ A_{2} }( A_{3} x^{ A_{4} }+ A_{5})+ A_{6}
Parameters
----------
%(phase)s
X : str
The dictionary key on the phase object containing the the quantity
of interest
A1 -> A6 : str
The dictionary keys on the phase object containing the coefficients
values to be used in the source term model
Returns
-------
dict
A dictionary containing the following three items:
'rate'
The value of the source term function at the given X.
'S1'
The slope of the source term function at the given X.
'S2'
The intercept of the source term function at the given X.
Notes
-----
The slope and intercept provide a linearized source term equation about the
current value of X as follow:
.. math::
rate = S_{1} X + S_{2}
|
logarithm
|
python
|
PMEAL/OpenPNM
|
openpnm/models/physics/source_terms/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/physics/source_terms/_funcs.py
|
MIT
|
def natural_logarithm(phase, X, A1=0.0, A2=1.0, A3=1.0, A4=0.0, A5=0.0):
r"""
Calculates the rate, as well as slope and intercept of the following
function at the given value of `X`:
.. math::
r = A_{1} Ln( A_{2} x^{ A_{3} }+ A_{4})+ A_{5}
Parameters
----------
%(phase)s
X : str
The dictionary key on the phase object containing the the quantity
of interest
A1 -> A5 : str
The dictionary keys on the phase object containing the coefficients
values to be used in the source term model
Returns
-------
dict
A dictionary containing the following three items:
'rate'
The value of the source term function at the given X.
'S1'
The slope of the source term function at the given X.
'S2'
The intercept of the source term function at the given X.
Notes
-----
The slope and intercept provide a linearized source term equation about the
current value of X as follow:
.. math::
rate = S_{1} X + S_{2}
"""
A = phase[A1]
B = phase[A2]
C = phase[A3]
D = phase[A4]
E = phase[A5]
X = phase[X]
r = A*_np.log(B*X**C + D) + E
S1 = A*B*C*X**(C - 1) / (B * X ** C + D)
S2 = A*_np.log(B*X**C + D) + E - A*B*C*X**C / (B*X**C + D)
values = {'pore.S1': S1, 'pore.S2': S2, 'pore.rate': r}
return values
|
Calculates the rate, as well as slope and intercept of the following
function at the given value of `X`:
.. math::
r = A_{1} Ln( A_{2} x^{ A_{3} }+ A_{4})+ A_{5}
Parameters
----------
%(phase)s
X : str
The dictionary key on the phase object containing the the quantity
of interest
A1 -> A5 : str
The dictionary keys on the phase object containing the coefficients
values to be used in the source term model
Returns
-------
dict
A dictionary containing the following three items:
'rate'
The value of the source term function at the given X.
'S1'
The slope of the source term function at the given X.
'S2'
The intercept of the source term function at the given X.
Notes
-----
The slope and intercept provide a linearized source term equation about the
current value of X as follow:
.. math::
rate = S_{1} X + S_{2}
|
natural_logarithm
|
python
|
PMEAL/OpenPNM
|
openpnm/models/physics/source_terms/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/physics/source_terms/_funcs.py
|
MIT
|
def _build_func(eq, **args):
r"""
Take a symbolic equation and return the lambdified version plus the
linearization of form S1 * x + S2
"""
from sympy import lambdify
eq_prime = eq.diff(args['x'])
s1 = eq_prime
s2 = eq - eq_prime*args['x']
EQ = lambdify(args.values(), expr=eq, modules='numpy')
S1 = lambdify(args.values(), expr=s1, modules='numpy')
S2 = lambdify(args.values(), expr=s2, modules='numpy')
return EQ, S1, S2
|
Take a symbolic equation and return the lambdified version plus the
linearization of form S1 * x + S2
|
_build_func
|
python
|
PMEAL/OpenPNM
|
openpnm/models/physics/source_terms/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/physics/source_terms/_funcs.py
|
MIT
|
def general_symbolic(phase, eqn, x, **kwargs):
r"""
A general function to interpret a sympy equation and evaluate the linear
components of the source term.
Parameters
----------
%(phase)s
eqn : str
The str representation of the equation to use. This will be
passed to sympy's ``sympify`` function to make a *live* sympy object.
x : str
The dictionary key of the independent variable
kwargs
All additional keyword arguments are converted to sympy variables
using the ``symbols`` function. Note that IF the arguments are
strs, it is assumed they are dictionary keys pointing to arrays
on the ``phase`` object. If they are numerical values they are
used 'as is'. Numpy arrays are not accepted. These must be stored
in the ``phase`` dictionary and referenced by key.
Examples
--------
>>> import openpnm as op
>>> from openpnm.models.physics import source_terms as st
>>> import numpy as np
>>> import sympy
>>> pn = op.network.Cubic(shape=[5, 5, 5], spacing=0.0001)
>>> water = op.phase.Water(network=pn)
>>> water['pore.a'] = 1
>>> water['pore.b'] = 2
>>> water['pore.c'] = 3
>>> water['pore.x'] = np.random.random(water.Np)
>>> y = 'a*x**b + c'
>>> arg_map = {'a':'pore.a', 'b':'pore.b', 'c':'pore.c'}
>>> water.add_model(propname='pore.general',
... model=st.general_symbolic,
... eqn=y, x='pore.x', **arg_map)
"""
from sympy import symbols, sympify
eqn = sympify(eqn)
# Get the data
data = {'x': phase[x]}
args = {'x': symbols('x')}
for key in kwargs.keys():
if isinstance(kwargs[key], str):
data[key] = phase[kwargs[key]]
else:
data[key] = kwargs[key]
args[key] = symbols(key)
r, s1, s2 = _build_func(eqn, **args)
r_val = r(*data.values())
s1_val = s1(*data.values())
s2_val = s2(*data.values())
values = {'S1': s1_val, 'S2': s2_val, 'rate': r_val}
return values
|
A general function to interpret a sympy equation and evaluate the linear
components of the source term.
Parameters
----------
%(phase)s
eqn : str
The str representation of the equation to use. This will be
passed to sympy's ``sympify`` function to make a *live* sympy object.
x : str
The dictionary key of the independent variable
kwargs
All additional keyword arguments are converted to sympy variables
using the ``symbols`` function. Note that IF the arguments are
strs, it is assumed they are dictionary keys pointing to arrays
on the ``phase`` object. If they are numerical values they are
used 'as is'. Numpy arrays are not accepted. These must be stored
in the ``phase`` dictionary and referenced by key.
Examples
--------
>>> import openpnm as op
>>> from openpnm.models.physics import source_terms as st
>>> import numpy as np
>>> import sympy
>>> pn = op.network.Cubic(shape=[5, 5, 5], spacing=0.0001)
>>> water = op.phase.Water(network=pn)
>>> water['pore.a'] = 1
>>> water['pore.b'] = 2
>>> water['pore.c'] = 3
>>> water['pore.x'] = np.random.random(water.Np)
>>> y = 'a*x**b + c'
>>> arg_map = {'a':'pore.a', 'b':'pore.b', 'c':'pore.c'}
>>> water.add_model(propname='pore.general',
... model=st.general_symbolic,
... eqn=y, x='pore.x', **arg_map)
|
general_symbolic
|
python
|
PMEAL/OpenPNM
|
openpnm/models/physics/source_terms/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/physics/source_terms/_funcs.py
|
MIT
|
def butler_volmer_conc(
phase, X, n, i0_ref, c_ref, beta,
gamma=1,
temperature="pore.temperature",
reaction_area="pore.reaction_area",
solid_voltage="pore.solid_voltage",
electrolyte_voltage="pore.electrolyte_voltage",
open_circuit_voltage="pore.open_circuit_voltage",
):
r"""
Calculates the rate, slope and intercept of the Butler-Volmer kinetic
model based on **concentration** to be used in mass transfer
algorithms.
Parameters
----------
%(phase)s
X : str
The dictionary key of the quantity of interest (i.e. main variable
to be solved; in this case, concentration).
n : float
Number of electrons transferred in the redox reaction.
i0_ref : float
Exchange current density for some conveniently selected value of
c_ref [A/m^2].
c_ref : float
Reference concentration [mol/m^3].
beta : float
Symmetry factor. The value of beta represents the
fraction of the applied potential that promotes the
cathodic reaction. Frequently, beta is assummed to be
0.5, although the theoretical justification for this
is not completely rigorous. This kinetic parameter must be determined
to agree with experimental data.
gamma : float
The exponent of the concentration term
solid_voltage : str
The dictionary key of solid phase voltages [V].
electrolyte_voltage : str
The dictionary key of electrolyte phase voltages [V].
open_circuit_voltage : str
The dictionary key of equilibrium potential values [V].
reaction_area : str
The dictionary key of reaction area values [m^2].
temperature : str
The dictionary key of temperature values [K].
Returns
-------
dict
Dictionary containing the following key/value pairs:
- rate : The value of the source term function at the given X.
- S1 : The slope of the source term function at the given X.
- S2 : The intercept of the source term function at the given X.
Notes
-----
The difference between butler_volmer_conc and butler_volmer_voltage is
that the former is linearized with respect to the electrolyte
concentration whereas the latter is linearized with respect to the
electrolyte voltage.
Consequently, while the S1 and S2 produced by these model shouldn't be
identical, they should both produce the same **rate** with the only
difference that the rate generated by butler_volmer_conc has the units
[mol/s] whereas that generated by butler_volmer_voltage has the units
[C/s]. Therefore, the two rates will differ by n * F, where n is the
number of electrons transferred and F is the Faraday's constant. The
Butler-Volmer equation used in this function is based on Eq. 8.24
of the Electrochemical Systems reference book cited here.
.. math::
r_{mass} = \frac{ i A }{ n F }=
i_{0ref} A_{rxn} (\frac{ 1 }{ n F })(\frac{ X }{ c_{ref} }) ^ {\gamma}
\Big(
\exp( \frac{(1-\beta) n F}{RT} \eta_s )
- \exp( -\frac{\beta n F}{RT} \eta_s )
\Big)
where:
.. math::
\eta_s = \phi_{met} - \phi_{soln} - U_{eq}
where :math:`{\phi_{met}}` is the electrostatic potential of the electrode,
:math:`{\phi_{soln}}` is the electrostatic potential of the electrolyte
solution, and :math:`{U_{eq}}` is the equilibrium potential, which is
the potential at which the net rate of reaction is zero. Here, we
assume U_{eq} is equal to the open-circuit voltage and is constant.
Alternatively, the dependency of the U_{eq} to the consentration
of species can be defined as a function and assigned to the
phase['pore.open_circuit_voltage'] (e.g. Eq.8.20 of
the reference book (Electrochemical Systems).
The slope and intercept provide a linearized source term equation
about the current value of X as follow:
.. math::
rate = S_{1} X + S_{2}
Reference: John Newman, Karen E. Thomas-Alyea, Electrochemical Systems,
John Wiley & Sons, third edition, 2004.
For more details read Chapter8:Electrode kinetics (e.g. Eqs: 8.6,8.10,8.24).
"""
# Fetch model variables
X = phase[X]
T = phase[temperature]
phi_met = phase[solid_voltage]
phi_soln = phase[electrolyte_voltage]
U_eq = phase[open_circuit_voltage]
A_rxn = phase.network[reaction_area]
F = _sp.constants.physical_constants["Faraday constant"][0]
R = _sp.constants.R
# Linearize with respect to X (electrolyte concentration)
eta_s = phi_met - phi_soln - U_eq
cte = i0_ref * A_rxn / (n * F)
m1 = (1-beta) * n * F / (R * T)
m2 = beta * n * F / (R * T)
fV = _np.exp(m1 * eta_s) - _np.exp(-m2 * eta_s)
fC = (X / c_ref)**gamma
r = cte * fC * fV
drdC = cte * (X / c_ref)**(gamma - 1) * (1 / c_ref) * fV
S1 = drdC
S2 = r - drdC * X
values = {"S1": S1, "S2": S2, "rate": r}
return values
|
Calculates the rate, slope and intercept of the Butler-Volmer kinetic
model based on **concentration** to be used in mass transfer
algorithms.
Parameters
----------
%(phase)s
X : str
The dictionary key of the quantity of interest (i.e. main variable
to be solved; in this case, concentration).
n : float
Number of electrons transferred in the redox reaction.
i0_ref : float
Exchange current density for some conveniently selected value of
c_ref [A/m^2].
c_ref : float
Reference concentration [mol/m^3].
beta : float
Symmetry factor. The value of beta represents the
fraction of the applied potential that promotes the
cathodic reaction. Frequently, beta is assummed to be
0.5, although the theoretical justification for this
is not completely rigorous. This kinetic parameter must be determined
to agree with experimental data.
gamma : float
The exponent of the concentration term
solid_voltage : str
The dictionary key of solid phase voltages [V].
electrolyte_voltage : str
The dictionary key of electrolyte phase voltages [V].
open_circuit_voltage : str
The dictionary key of equilibrium potential values [V].
reaction_area : str
The dictionary key of reaction area values [m^2].
temperature : str
The dictionary key of temperature values [K].
Returns
-------
dict
Dictionary containing the following key/value pairs:
- rate : The value of the source term function at the given X.
- S1 : The slope of the source term function at the given X.
- S2 : The intercept of the source term function at the given X.
Notes
-----
The difference between butler_volmer_conc and butler_volmer_voltage is
that the former is linearized with respect to the electrolyte
concentration whereas the latter is linearized with respect to the
electrolyte voltage.
Consequently, while the S1 and S2 produced by these model shouldn't be
identical, they should both produce the same **rate** with the only
difference that the rate generated by butler_volmer_conc has the units
[mol/s] whereas that generated by butler_volmer_voltage has the units
[C/s]. Therefore, the two rates will differ by n * F, where n is the
number of electrons transferred and F is the Faraday's constant. The
Butler-Volmer equation used in this function is based on Eq. 8.24
of the Electrochemical Systems reference book cited here.
.. math::
r_{mass} = \frac{ i A }{ n F }=
i_{0ref} A_{rxn} (\frac{ 1 }{ n F })(\frac{ X }{ c_{ref} }) ^ {\gamma}
\Big(
\exp( \frac{(1-\beta) n F}{RT} \eta_s )
- \exp( -\frac{\beta n F}{RT} \eta_s )
\Big)
where:
.. math::
\eta_s = \phi_{met} - \phi_{soln} - U_{eq}
where :math:`{\phi_{met}}` is the electrostatic potential of the electrode,
:math:`{\phi_{soln}}` is the electrostatic potential of the electrolyte
solution, and :math:`{U_{eq}}` is the equilibrium potential, which is
the potential at which the net rate of reaction is zero. Here, we
assume U_{eq} is equal to the open-circuit voltage and is constant.
Alternatively, the dependency of the U_{eq} to the consentration
of species can be defined as a function and assigned to the
phase['pore.open_circuit_voltage'] (e.g. Eq.8.20 of
the reference book (Electrochemical Systems).
The slope and intercept provide a linearized source term equation
about the current value of X as follow:
.. math::
rate = S_{1} X + S_{2}
Reference: John Newman, Karen E. Thomas-Alyea, Electrochemical Systems,
John Wiley & Sons, third edition, 2004.
For more details read Chapter8:Electrode kinetics (e.g. Eqs: 8.6,8.10,8.24).
|
butler_volmer_conc
|
python
|
PMEAL/OpenPNM
|
openpnm/models/physics/source_terms/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/physics/source_terms/_funcs.py
|
MIT
|
def butler_volmer_voltage(
phase, X, n, i0_ref, c_ref, beta,
gamma=1,
temperature="pore.temperature",
reaction_area="pore.reaction_area",
solid_voltage="pore.solid_voltage",
open_circuit_voltage="pore.open_circuit_voltage",
electrolyte_concentration="pore.electrolyte_concentration",
):
r"""
Calculates the rate, slope and intercept of the Butler-Volmer kinetic model
based on **voltage** to be used in electron conduction algorithms.
Parameters
----------
%(phase)s
X : str
The dictionary key of the quantity of interest (i.e. main variable
to be solved; in this case, electrolyte voltage).
n : float
Number of electrons transferred in the redox reaction.
i0_ref : float
Exchange current density for some conveniently selected value of
c_ref [A/m^2].
c_ref : float
Reference concentration [mol/m^3].
beta : float
Symmetry factor. The value of beta represents the
fraction of the applied potential that promotes the
cathodic reaction. Frequently, beta is assummed to be
0.5, although the theoretical justification for this
is not completely rigorous. This kinetic parameter must be determined
to agree with experimental data.
gamma : float
The exponent of the concentration term
electrolyte_concentration : str
The dictionary key of the electrolyte concentrations [mol/m^3].
solid_voltage : str
The dictionary key of solid phase voltages [V].
electrolyte_voltage : str
The dictionary key of electrolyte phase voltages [V].
open_circuit_voltage : str
The dictionary key of equilibrium potential values [V].
reaction_area : str
The dictionary key of reaction area values [m^2].
temperature : str
The dictionary key of temperature values [K].
Returns
-------
rate_info : dict
Dictionary containing the following key/value pairs:
- rate : The value of the source term function at the given X.
- S1 : The slope of the source term function at the given X.
- S2 : The intercept of the source term function at the given X.
Notes
-----
The difference between butler_volmer_conc and butler_volmer_voltage is
that the former is linearized with respect to the electrolyte
concentration whereas the latter is linearized with respect to the
electrolyte voltage.
Consequently, while the S1 and S2 produced by these model shouldn't be
identical, they should both produce the same **rate** with the only
difference that the rate generated by butler_volmer_conc has the units
[mol/s] whereas that generated by butler_volmer_voltage has the units
[C/s]. Therefore, the two rates will differ by n * F, where n is the
number of electrons transferred and F is the Faraday's constant. The
Butler-Volmer equation used in this function is based on Eq. 8.24
of the Electrochemical Systems reference book cited here.
.. math::
r_{charge}=i A = i_{0ref} A_{rxn} (\frac{ c }{ c_{ref} }) ^ {\gamma}
\Big(
\exp( \frac{(1-\beta) n F}{RT} \eta_s )
- \exp( -\frac{\beta n F}{RT} \eta_s )
\Big)
where:
.. math::
\eta_s = \phi_{met} - \phi_{soln} - U_{eq}
where :math:`{\phi_{met}}` is the electrostatic potential of the electrode,
:math:`{\phi_{soln}}` is the electrostatic potential of the electrolyte
solution, and :math:`{U_{eq}}` is the equilibrium potential, which is
the potential at which the net rate of reaction is zero. Here, we
assume U_{eq} is equal to the open-circuit voltage and is constant.
Alternatively, the dependency of the U_{eq} to the consentration
of species can be defined as a function and assigned to the
phase['pore.open_circuit_voltage'] (e.g. Eq.8.20 of
the reference book (Electrochemical Systems).
The slope and intercept provide a linearized source term equation
about the current value of X as follow:
.. math::
rate = S_{1} X + S_{2}
Reference: John Newman, Karen E. Thomas-Alyea, Electrochemical Systems,
John Wiley & Sons, third edition, 2004.
For more details read Chapter8:Electrode kinetics (e.g. Eqs: 8.6,8.10,8.24).
"""
# Fetch model variables
A_rxn = phase.network[reaction_area]
phi_met = phase[solid_voltage]
U_eq = phase[open_circuit_voltage]
c = phase[electrolyte_concentration]
T = phase[temperature]
X = phase[X]
F = _sp.constants.physical_constants["Faraday constant"][0]
R = _sp.constants.R
# Linearize with respect to X (electrolyte voltage)
eta_s = phi_met - X - U_eq
cte = i0_ref * A_rxn
m1 = (1-beta) * n * F / (R * T)
m2 = beta * n * F / (R * T)
fV = _np.exp(m1 * eta_s) - _np.exp(-m2 * eta_s)
dfVdV = -(m1 * _np.exp(m1 * eta_s) + m2 * _np.exp(-m2 * eta_s))
fC = (c / c_ref)**gamma
r = cte * fC * fV
drdV = cte * fC * dfVdV
S1 = drdV
S2 = r - drdV * X
values = {"S1": S1, "S2": S2, "rate": r}
return values
|
Calculates the rate, slope and intercept of the Butler-Volmer kinetic model
based on **voltage** to be used in electron conduction algorithms.
Parameters
----------
%(phase)s
X : str
The dictionary key of the quantity of interest (i.e. main variable
to be solved; in this case, electrolyte voltage).
n : float
Number of electrons transferred in the redox reaction.
i0_ref : float
Exchange current density for some conveniently selected value of
c_ref [A/m^2].
c_ref : float
Reference concentration [mol/m^3].
beta : float
Symmetry factor. The value of beta represents the
fraction of the applied potential that promotes the
cathodic reaction. Frequently, beta is assummed to be
0.5, although the theoretical justification for this
is not completely rigorous. This kinetic parameter must be determined
to agree with experimental data.
gamma : float
The exponent of the concentration term
electrolyte_concentration : str
The dictionary key of the electrolyte concentrations [mol/m^3].
solid_voltage : str
The dictionary key of solid phase voltages [V].
electrolyte_voltage : str
The dictionary key of electrolyte phase voltages [V].
open_circuit_voltage : str
The dictionary key of equilibrium potential values [V].
reaction_area : str
The dictionary key of reaction area values [m^2].
temperature : str
The dictionary key of temperature values [K].
Returns
-------
rate_info : dict
Dictionary containing the following key/value pairs:
- rate : The value of the source term function at the given X.
- S1 : The slope of the source term function at the given X.
- S2 : The intercept of the source term function at the given X.
Notes
-----
The difference between butler_volmer_conc and butler_volmer_voltage is
that the former is linearized with respect to the electrolyte
concentration whereas the latter is linearized with respect to the
electrolyte voltage.
Consequently, while the S1 and S2 produced by these model shouldn't be
identical, they should both produce the same **rate** with the only
difference that the rate generated by butler_volmer_conc has the units
[mol/s] whereas that generated by butler_volmer_voltage has the units
[C/s]. Therefore, the two rates will differ by n * F, where n is the
number of electrons transferred and F is the Faraday's constant. The
Butler-Volmer equation used in this function is based on Eq. 8.24
of the Electrochemical Systems reference book cited here.
.. math::
r_{charge}=i A = i_{0ref} A_{rxn} (\frac{ c }{ c_{ref} }) ^ {\gamma}
\Big(
\exp( \frac{(1-\beta) n F}{RT} \eta_s )
- \exp( -\frac{\beta n F}{RT} \eta_s )
\Big)
where:
.. math::
\eta_s = \phi_{met} - \phi_{soln} - U_{eq}
where :math:`{\phi_{met}}` is the electrostatic potential of the electrode,
:math:`{\phi_{soln}}` is the electrostatic potential of the electrolyte
solution, and :math:`{U_{eq}}` is the equilibrium potential, which is
the potential at which the net rate of reaction is zero. Here, we
assume U_{eq} is equal to the open-circuit voltage and is constant.
Alternatively, the dependency of the U_{eq} to the consentration
of species can be defined as a function and assigned to the
phase['pore.open_circuit_voltage'] (e.g. Eq.8.20 of
the reference book (Electrochemical Systems).
The slope and intercept provide a linearized source term equation
about the current value of X as follow:
.. math::
rate = S_{1} X + S_{2}
Reference: John Newman, Karen E. Thomas-Alyea, Electrochemical Systems,
John Wiley & Sons, third edition, 2004.
For more details read Chapter8:Electrode kinetics (e.g. Eqs: 8.6,8.10,8.24).
|
butler_volmer_voltage
|
python
|
PMEAL/OpenPNM
|
openpnm/models/physics/source_terms/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/physics/source_terms/_funcs.py
|
MIT
|
def generic_thermal(phase,
pore_conductivity='pore.thermal_conductivity',
throat_conductivity='throat.thermal_conductivity',
size_factors='throat.diffusive_size_factors'):
r"""
Calculate the thermal conductance of conduits in network.
Parameters
----------
%(phase)s
pore_conductivity : str
%(dict_blurb)s thermal conductivity
throat_conductivity : str
%(dict_blurb)s throat thermal conductivity
size_factors : str
%(dict_blurb)s conduit diffusive size factors
Returns
-------
%(return_arr)s thermal conductance
"""
return _poisson_conductance(phase=phase,
pore_conductivity=pore_conductivity,
throat_conductivity=throat_conductivity,
size_factors=size_factors)
|
Calculate the thermal conductance of conduits in network.
Parameters
----------
%(phase)s
pore_conductivity : str
%(dict_blurb)s thermal conductivity
throat_conductivity : str
%(dict_blurb)s throat thermal conductivity
size_factors : str
%(dict_blurb)s conduit diffusive size factors
Returns
-------
%(return_arr)s thermal conductance
|
generic_thermal
|
python
|
PMEAL/OpenPNM
|
openpnm/models/physics/thermal_conductance/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/physics/thermal_conductance/_funcs.py
|
MIT
|
def series_resistors(
phase,
pore_thermal_conductivity='pore.thermal_conductivity',
throat_thermal_conductivity='throat.thermal_conductivity',
size_factors='throat.diffusive_size_factors'
):
r"""
Calculate the thermal conductance of conduits in network.
Parameters
----------
%(phase)s
pore_conductivity : str
%(dict_blurb)s thermal conductivity
throat_conductivity : str
%(dict_blurb)s throat thermal conductivity
size_factors : str
%(dict_blurb)s conduit diffusive size factors
Returns
-------
%(return_arr)s thermal conductance
"""
return _poisson_conductance(phase=phase,
pore_conductivity=pore_thermal_conductivity,
throat_conductivity=throat_thermal_conductivity,
size_factors=size_factors)
|
Calculate the thermal conductance of conduits in network.
Parameters
----------
%(phase)s
pore_conductivity : str
%(dict_blurb)s thermal conductivity
throat_conductivity : str
%(dict_blurb)s throat thermal conductivity
size_factors : str
%(dict_blurb)s conduit diffusive size factors
Returns
-------
%(return_arr)s thermal conductance
|
series_resistors
|
python
|
PMEAL/OpenPNM
|
openpnm/models/physics/thermal_conductance/_funcs.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/models/physics/thermal_conductance/_funcs.py
|
MIT
|
def add_boundary_pores(self, labels, spacing):
r"""
Add boundary pores to the specified faces of the network
Pores are offset from the faces by 1/2 of the given ``spacing``,
such that they lie directly on the boundaries.
Parameters
----------
labels : str or list[str]
The labels indicating the pores defining each face where
boundary pores are to be added (e.g. 'left' or
['left', 'right'])
spacing : scalar or array_like
The spacing of the network (e.g. [1, 1, 1]). This must be
given since it can be quite difficult to infer from the
network, for instance if boundary pores have already added
to other faces.
"""
spacing = np.array(spacing)
if spacing.size == 1:
spacing = np.ones(3)*spacing
for item in labels:
Ps = self.pores(item)
coords = np.absolute(self['pore.coords'][Ps])
axis = np.count_nonzero(np.diff(coords, axis=0), axis=0) == 0
offset = np.array(axis, dtype=int)/2
if np.amin(coords) == np.amin(coords[:, np.where(axis)[0]]):
offset = -1*offset
topotools.add_boundary_pores(network=self, pores=Ps, offset=offset,
apply_label=item + '_boundary')
|
Add boundary pores to the specified faces of the network
Pores are offset from the faces by 1/2 of the given ``spacing``,
such that they lie directly on the boundaries.
Parameters
----------
labels : str or list[str]
The labels indicating the pores defining each face where
boundary pores are to be added (e.g. 'left' or
['left', 'right'])
spacing : scalar or array_like
The spacing of the network (e.g. [1, 1, 1]). This must be
given since it can be quite difficult to infer from the
network, for instance if boundary pores have already added
to other faces.
|
add_boundary_pores
|
python
|
PMEAL/OpenPNM
|
openpnm/network/_bcc.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/network/_bcc.py
|
MIT
|
def add_boundary_pores(self, labels=["top", "bottom", "front",
"back", "left", "right"],
spacing=None):
r"""
Add pores to the faces of the network for use as boundary pores.
Pores are offset from the faces by 1/2 a lattice spacing such that
they lie directly on the boundaries.
Parameters
----------
labels : str or list[str]
The labels indicating the pores defining each face where
boundary pores are to be added (e.g. 'left' or
['left', 'right'])
spacing : scalar or array_like
The spacing of the network (e.g. [1, 1, 1]). This should be
given since it can be quite difficult to infer from the
network, for instance if boundary pores have already added to
other faces.
"""
if isinstance(labels, str):
labels = [labels]
x, y, z = self["pore.coords"].T
if spacing is None:
spacing = skgr.tools.get_cubic_spacing(self)
else:
spacing = np.array(spacing)
if spacing.size == 1:
spacing = np.ones(3) * spacing
Lcx, Lcy, Lcz = spacing
offset = {}
shape = skgr.tools.get_cubic_shape(self)
offset["front"] = offset["left"] = offset["bottom"] = [0, 0, 0]
offset["right"] = [Lcx * shape[0], 0, 0]
offset["back"] = [0, Lcy * shape[1], 0]
offset["top"] = [0, 0, Lcz * shape[2]]
scale = {}
scale["left"] = scale["right"] = [0, 1, 1]
scale["front"] = scale["back"] = [1, 0, 1]
scale["bottom"] = scale["top"] = [1, 1, 0]
for label in labels:
try:
Ps = self.pores(label)
topotools.clone_pores(network=self, pores=Ps,
labels=f"{label}_boundary",
mode='parents')
# Translate cloned pores
ind = self.pores(label + "_boundary")
coords = self["pore.coords"][ind]
coords = coords * scale[label] + offset[label]
self["pore.coords"][ind] = coords
except KeyError:
msg = f"No pores labelled {label} found, skipping boundary addition"
logger.warning(msg)
|
Add pores to the faces of the network for use as boundary pores.
Pores are offset from the faces by 1/2 a lattice spacing such that
they lie directly on the boundaries.
Parameters
----------
labels : str or list[str]
The labels indicating the pores defining each face where
boundary pores are to be added (e.g. 'left' or
['left', 'right'])
spacing : scalar or array_like
The spacing of the network (e.g. [1, 1, 1]). This should be
given since it can be quite difficult to infer from the
network, for instance if boundary pores have already added to
other faces.
|
add_boundary_pores
|
python
|
PMEAL/OpenPNM
|
openpnm/network/_cubic.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/network/_cubic.py
|
MIT
|
def find_throat_facets(self, throats=None):
r"""
Finds the indicies of the Voronoi nodes that define the facet or
ridge between the Delaunay nodes connected by the given throat.
Parameters
----------
throats : array_like
The throats whose facets are sought. The given throats should be
from the 'delaunay' network. If no throats are specified, all
'delaunay' throats are assumed.
Notes
-----
The method is not well optimized as it scans through each given throat
inside a for-loop, so it could be slow for large networks.
"""
if throats is None:
throats = self.throats('delaunay')
temp = []
tvals = self['throat.interconnect'].astype(int)
am = self.create_adjacency_matrix(weights=tvals, fmt='lil',
drop_zeros=True)
for t in throats:
P12 = self['throat.conns'][t]
Ps = list(set(am.rows[P12][0]).intersection(am.rows[P12][1]))
temp.append(Ps)
return np.array(temp, dtype=object)
|
Finds the indicies of the Voronoi nodes that define the facet or
ridge between the Delaunay nodes connected by the given throat.
Parameters
----------
throats : array_like
The throats whose facets are sought. The given throats should be
from the 'delaunay' network. If no throats are specified, all
'delaunay' throats are assumed.
Notes
-----
The method is not well optimized as it scans through each given throat
inside a for-loop, so it could be slow for large networks.
|
find_throat_facets
|
python
|
PMEAL/OpenPNM
|
openpnm/network/_delaunay_voronoi_dual.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/network/_delaunay_voronoi_dual.py
|
MIT
|
def find_pore_hulls(self, pores=None):
r"""
Finds the indices of the Voronoi nodes that define the convex hull
around the given Delaunay nodes.
Parameters
----------
pores : array_like
The pores whose convex hull are sought. The given pores should be
from the 'delaunay' network. If no pores are given, then the hull
is found for all 'delaunay' pores.
Notes
-----
This metod is not fully optimized as it scans through each pore in a
for-loop, so could be slow for large networks.
"""
if pores is None:
pores = self.pores('delaunay')
temp = []
tvals = self['throat.interconnect'].astype(int)
am = self.create_adjacency_matrix(weights=tvals, fmt='lil',
drop_zeros=True)
for p in pores:
Ps = am.rows[p]
temp.append(Ps)
return np.array(temp, dtype=object)
|
Finds the indices of the Voronoi nodes that define the convex hull
around the given Delaunay nodes.
Parameters
----------
pores : array_like
The pores whose convex hull are sought. The given pores should be
from the 'delaunay' network. If no pores are given, then the hull
is found for all 'delaunay' pores.
Notes
-----
This metod is not fully optimized as it scans through each pore in a
for-loop, so could be slow for large networks.
|
find_pore_hulls
|
python
|
PMEAL/OpenPNM
|
openpnm/network/_delaunay_voronoi_dual.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/network/_delaunay_voronoi_dual.py
|
MIT
|
def add_boundary_pores(self, labels, spacing):
r"""
Add boundary pores to the specified faces of the network
Pores are offset from the faces by 1/2 of the given ``spacing``,
such that they lie directly on the boundaries.
Parameters
----------
labels : str or list[str]
The labels indicating the pores defining each face where
boundary pores are to be added (e.g. 'left' or
['left', 'right'])
spacing : scalar or array_like
The spacing of the network (e.g. [1, 1, 1]). This must be
given since it can be quite difficult to infer from the
network, for instance if boundary pores have already added
to other faces.
"""
spacing = np.array(spacing)
if spacing.size == 1:
spacing = np.ones(3)*spacing
for item in labels:
Ps = self.pores(item)
coords = np.absolute(self['pore.coords'][Ps])
axis = np.count_nonzero(np.diff(coords, axis=0), axis=0) == 0
offset = np.array(axis, dtype=int)/2
if np.amin(coords) == np.amin(coords[:, np.where(axis)[0]]):
offset = -1*offset
topotools.add_boundary_pores(network=self, pores=Ps, offset=offset,
apply_label=item + '_boundary')
|
Add boundary pores to the specified faces of the network
Pores are offset from the faces by 1/2 of the given ``spacing``,
such that they lie directly on the boundaries.
Parameters
----------
labels : str or list[str]
The labels indicating the pores defining each face where
boundary pores are to be added (e.g. 'left' or
['left', 'right'])
spacing : scalar or array_like
The spacing of the network (e.g. [1, 1, 1]). This must be
given since it can be quite difficult to infer from the
network, for instance if boundary pores have already added
to other faces.
|
add_boundary_pores
|
python
|
PMEAL/OpenPNM
|
openpnm/network/_fcc.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/network/_fcc.py
|
MIT
|
def get_adjacency_matrix(self, fmt='coo'):
r"""
Adjacency matrix in the specified sparse format, with throat IDs
indicating the non-zero values.
Parameters
----------
fmt : str, default is 'coo'
The sparse storage format to return. Options are:
**'coo'** : This is the native format of OpenPNM's data
**'lil'** : Enables row-wise slice of the matrix
**'csr'** : Favored by most linear algebra routines
**'dok'** : Enables subscript access of locations
Notes
-----
This method will only create the requested matrix in the specified
format if one is not already saved on the object. If not present,
this method will create and return the matrix, as well as store it
for future use.
To obtain a matrix with weights other than throat IDs at each
non-zero location use ``create_adjacency_matrix``.
To obtain the non-directed graph, with only upper-triangular
entries, use ``sp.sparse.triu(am, k=1)``.
"""
# Retrieve existing matrix if available
if fmt in self._am.keys():
am = self._am[fmt]
else:
am = self.create_adjacency_matrix(weights=self.Ts, fmt=fmt)
self._am[fmt] = am
return am
|
Adjacency matrix in the specified sparse format, with throat IDs
indicating the non-zero values.
Parameters
----------
fmt : str, default is 'coo'
The sparse storage format to return. Options are:
**'coo'** : This is the native format of OpenPNM's data
**'lil'** : Enables row-wise slice of the matrix
**'csr'** : Favored by most linear algebra routines
**'dok'** : Enables subscript access of locations
Notes
-----
This method will only create the requested matrix in the specified
format if one is not already saved on the object. If not present,
this method will create and return the matrix, as well as store it
for future use.
To obtain a matrix with weights other than throat IDs at each
non-zero location use ``create_adjacency_matrix``.
To obtain the non-directed graph, with only upper-triangular
entries, use ``sp.sparse.triu(am, k=1)``.
|
get_adjacency_matrix
|
python
|
PMEAL/OpenPNM
|
openpnm/network/_network.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/network/_network.py
|
MIT
|
def get_incidence_matrix(self, fmt='coo'):
r"""
Incidence matrix in the specified sparse format, with pore IDs
indicating the non-zero values.
Parameters
----------
fmt : str, default is 'coo'
The sparse storage format to return. Options are:
**'coo'** : This is the native format of OpenPNM's data
**'lil'** : Enables row-wise slice of the matrix
**'csr'** : Favored by most linear algebra routines
**'dok'** : Enables subscript access of locations
Notes
-----
This method will only create the requested matrix in the specified
format if one is not already saved on the object. If not present,
this method will create and return the matrix, as well as store it
for future use.
To obtain a matrix with weights other than pore IDs at each
non-zero location use ``create_incidence_matrix``.
"""
if fmt in self._im.keys():
im = self._im[fmt]
elif self._im.keys():
im = self._im[list(self._im.keys())[0]]
tofmt = getattr(im, f"to{fmt}")
im = tofmt()
self._im[fmt] = im
else:
im = self.create_incidence_matrix(weights=self.Ts, fmt=fmt)
self._im[fmt] = im
return im
|
Incidence matrix in the specified sparse format, with pore IDs
indicating the non-zero values.
Parameters
----------
fmt : str, default is 'coo'
The sparse storage format to return. Options are:
**'coo'** : This is the native format of OpenPNM's data
**'lil'** : Enables row-wise slice of the matrix
**'csr'** : Favored by most linear algebra routines
**'dok'** : Enables subscript access of locations
Notes
-----
This method will only create the requested matrix in the specified
format if one is not already saved on the object. If not present,
this method will create and return the matrix, as well as store it
for future use.
To obtain a matrix with weights other than pore IDs at each
non-zero location use ``create_incidence_matrix``.
|
get_incidence_matrix
|
python
|
PMEAL/OpenPNM
|
openpnm/network/_network.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/network/_network.py
|
MIT
|
def find_connected_pores(self, throats=[], flatten=False, mode='or'):
r"""
Return a list of pores connected to the given list of throats
Parameters
----------
throats : array_like
List of throats numbers
flatten : bool, optional
If ``True`` (default) a 1D array of unique pore numbers is
returned. If ``False`` each location in the the returned
array contains a sub-arras of neighboring pores for each input
throat, in the order they were sent.
mode : str
Specifies logic to filter the resulting list. Options are:
=========== =====================================================
mode meaning
=========== =====================================================
'or' All neighbors of the input pores. Also accepts 'any'
and 'union'.
'xor' Only neighbors of one and only one input pore. This
is useful for counting the pores that are not shared
by any of the input pores. Also accepts
'exclusive_or'.
'xnor' Neighbors that are shared by two or more input pores.
This is equivalent to counting all neighbors
with 'or', minus those found with 'xor', and is
useful for finding neighbors that the inputs have
in common.
'and' Only neighbors shared by all input pores. Also
accepts 'intersection' and 'all'
=========== =====================================================
Returns
-------
1D array (if ``flatten`` is ``True``) or ndarray of arrays (if
``flatten`` is ``False``)
Examples
--------
>>> import openpnm as op
>>> pn = op.network.Cubic(shape=[5, 5, 5])
>>> Ps = pn.find_connected_pores(throats=[0, 1])
>>> print(Ps)
[[0 1]
[1 2]]
>>> Ps = pn.find_connected_pores(throats=[0, 1], flatten=True)
>>> print(Ps)
[0 1 2]
"""
Ts = self._parse_indices(throats)
pores = topotools.find_connected_sites(bonds=Ts, network=self,
flatten=flatten, logic=mode)
return pores
|
Return a list of pores connected to the given list of throats
Parameters
----------
throats : array_like
List of throats numbers
flatten : bool, optional
If ``True`` (default) a 1D array of unique pore numbers is
returned. If ``False`` each location in the the returned
array contains a sub-arras of neighboring pores for each input
throat, in the order they were sent.
mode : str
Specifies logic to filter the resulting list. Options are:
=========== =====================================================
mode meaning
=========== =====================================================
'or' All neighbors of the input pores. Also accepts 'any'
and 'union'.
'xor' Only neighbors of one and only one input pore. This
is useful for counting the pores that are not shared
by any of the input pores. Also accepts
'exclusive_or'.
'xnor' Neighbors that are shared by two or more input pores.
This is equivalent to counting all neighbors
with 'or', minus those found with 'xor', and is
useful for finding neighbors that the inputs have
in common.
'and' Only neighbors shared by all input pores. Also
accepts 'intersection' and 'all'
=========== =====================================================
Returns
-------
1D array (if ``flatten`` is ``True``) or ndarray of arrays (if
``flatten`` is ``False``)
Examples
--------
>>> import openpnm as op
>>> pn = op.network.Cubic(shape=[5, 5, 5])
>>> Ps = pn.find_connected_pores(throats=[0, 1])
>>> print(Ps)
[[0 1]
[1 2]]
>>> Ps = pn.find_connected_pores(throats=[0, 1], flatten=True)
>>> print(Ps)
[0 1 2]
|
find_connected_pores
|
python
|
PMEAL/OpenPNM
|
openpnm/network/_network.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/network/_network.py
|
MIT
|
def find_connecting_throat(self, P1, P2):
r"""
Return the throat index connecting pairs of pores.
Parameters
----------
P1 : array_like
The indices of the pores whose throats are sought. These can
be vectors of indices, but must be the same length
P2 : array_like
The indices of the pores whose throats are sought. These can
be vectors of indices, but must be the same length
Returns
-------
list
Returns a list the same length as P1 (and P2) with the each
element containing the throat index that connects the
corresponding pores, or `None`` if pores are not connected.
Notes
-----
The returned list can be converted to an ndarray, which will
convert the ``None`` values to ``nan``. These can then be found
using ``numpy.isnan``.
Examples
--------
>>> import openpnm as op
>>> pn = op.network.Cubic(shape=[5, 5, 5])
>>> Ts = pn.find_connecting_throat([0, 1, 2], [2, 2, 2])
>>> print(Ts)
[nan 1. nan]
"""
sites = np.vstack((P1, P2)).T
Ts = topotools.find_connecting_bonds(sites=sites, network=self)
return Ts
|
Return the throat index connecting pairs of pores.
Parameters
----------
P1 : array_like
The indices of the pores whose throats are sought. These can
be vectors of indices, but must be the same length
P2 : array_like
The indices of the pores whose throats are sought. These can
be vectors of indices, but must be the same length
Returns
-------
list
Returns a list the same length as P1 (and P2) with the each
element containing the throat index that connects the
corresponding pores, or `None`` if pores are not connected.
Notes
-----
The returned list can be converted to an ndarray, which will
convert the ``None`` values to ``nan``. These can then be found
using ``numpy.isnan``.
Examples
--------
>>> import openpnm as op
>>> pn = op.network.Cubic(shape=[5, 5, 5])
>>> Ts = pn.find_connecting_throat([0, 1, 2], [2, 2, 2])
>>> print(Ts)
[nan 1. nan]
|
find_connecting_throat
|
python
|
PMEAL/OpenPNM
|
openpnm/network/_network.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/network/_network.py
|
MIT
|
def find_neighbor_pores(self, pores, mode='or', flatten=True,
include_input=False, asmask=False):
r"""
Returns a list of pores that are direct neighbors to the given pore(s)
Parameters
----------
pores : array_like
Indices of the pores whose neighbors are sought
flatten : bool
If ``True`` (default) the returned result is a compressed
array of all neighbors. If ``False``, a list of lists with
each sub-list containing the neighbors for each input site.
Note that an *unflattened* list might be slow to generate
since it is a Python ``list`` rather than a Numpy ``array``.
include_input : bool
If ``False`` (default) then the input pores are not included
in the returned list(s). Note that since pores are not
neighbors of themselves, the neighbors of pore N will not
include N, even if this flag is ``True``.
mode : str
Specifies logic to filter the resulting list. Options are:
=========== =====================================================
mode meaning
=========== =====================================================
'or' All neighbors of the input pores. Also accepts 'any'
and 'union'.
'xor' Only neighbors of one and only one input pore. This
is useful for counting the pores that are not shared
by any of the input pores. Also accepts
'exclusive_or'.
'xnor' Neighbors that are shared by two or more input pores.
This is equivalent to counting all neighbors
with 'or', minus those found with 'xor', and is
useful for finding neighbors that the inputs have
in common.
'and' Only neighbors shared by all input pores. Also
accepts 'intersection' and 'all'
=========== =====================================================
asmask : boolean
If ``False`` (default), the returned result is a list of the
neighboring pores as indices. If ``True``, the returned result is a
boolean mask. (Useful for labelling)
Returns
-------
If ``flatten`` is ``True``, returns a 1D array of pore indices
filtered according to the specified mode. If ``flatten`` is
``False``, returns a list of lists, where each list contains the
neighbors of the corresponding input pores.
Notes
-----
The ``logic`` options are applied to neighboring pores only, thus
it is not possible to obtain pores that are part of the global set
but not neighbors. This is because (a) the list of global pores
might be very large, and (b) it is not possible to return a list
of neighbors for each input pores if global pores are considered.
Examples
--------
>>> import openpnm as op
>>> pn = op.network.Cubic(shape=[5, 5, 5])
>>> Ps = pn.find_neighbor_pores(pores=[0, 2])
>>> print(Ps)
[ 1 3 5 7 25 27]
>>> Ps = pn.find_neighbor_pores(pores=[0, 1])
>>> print(Ps)
[ 2 5 6 25 26]
>>> Ps = pn.find_neighbor_pores(pores=[0, 1], mode='or',
... include_input=True)
>>> print(Ps)
[ 0 1 2 5 6 25 26]
>>> Ps = pn.find_neighbor_pores(pores=[0, 2], flatten=False)
>>> print(Ps[0])
[ 1 5 25]
>>> print(Ps[1])
[ 1 3 7 27]
>>> Ps = pn.find_neighbor_pores(pores=[0, 2], mode='xnor')
>>> print(Ps)
[1]
>>> Ps = pn.find_neighbor_pores(pores=[0, 2], mode='xor')
>>> print(Ps)
[ 3 5 7 25 27]
"""
pores = self._parse_indices(pores)
if np.size(pores) == 0:
return np.array([], ndmin=1, dtype=int)
neighbors = topotools.find_neighbor_sites(sites=pores, logic=mode,
network=self,
flatten=flatten,
include_input=include_input)
if asmask is False:
return neighbors
elif flatten is True:
neighbors = self._tomask(element='pore', indices=neighbors)
return neighbors
else:
raise Exception('Cannot create mask on an unflattened output')
|
Returns a list of pores that are direct neighbors to the given pore(s)
Parameters
----------
pores : array_like
Indices of the pores whose neighbors are sought
flatten : bool
If ``True`` (default) the returned result is a compressed
array of all neighbors. If ``False``, a list of lists with
each sub-list containing the neighbors for each input site.
Note that an *unflattened* list might be slow to generate
since it is a Python ``list`` rather than a Numpy ``array``.
include_input : bool
If ``False`` (default) then the input pores are not included
in the returned list(s). Note that since pores are not
neighbors of themselves, the neighbors of pore N will not
include N, even if this flag is ``True``.
mode : str
Specifies logic to filter the resulting list. Options are:
=========== =====================================================
mode meaning
=========== =====================================================
'or' All neighbors of the input pores. Also accepts 'any'
and 'union'.
'xor' Only neighbors of one and only one input pore. This
is useful for counting the pores that are not shared
by any of the input pores. Also accepts
'exclusive_or'.
'xnor' Neighbors that are shared by two or more input pores.
This is equivalent to counting all neighbors
with 'or', minus those found with 'xor', and is
useful for finding neighbors that the inputs have
in common.
'and' Only neighbors shared by all input pores. Also
accepts 'intersection' and 'all'
=========== =====================================================
asmask : boolean
If ``False`` (default), the returned result is a list of the
neighboring pores as indices. If ``True``, the returned result is a
boolean mask. (Useful for labelling)
Returns
-------
If ``flatten`` is ``True``, returns a 1D array of pore indices
filtered according to the specified mode. If ``flatten`` is
``False``, returns a list of lists, where each list contains the
neighbors of the corresponding input pores.
Notes
-----
The ``logic`` options are applied to neighboring pores only, thus
it is not possible to obtain pores that are part of the global set
but not neighbors. This is because (a) the list of global pores
might be very large, and (b) it is not possible to return a list
of neighbors for each input pores if global pores are considered.
Examples
--------
>>> import openpnm as op
>>> pn = op.network.Cubic(shape=[5, 5, 5])
>>> Ps = pn.find_neighbor_pores(pores=[0, 2])
>>> print(Ps)
[ 1 3 5 7 25 27]
>>> Ps = pn.find_neighbor_pores(pores=[0, 1])
>>> print(Ps)
[ 2 5 6 25 26]
>>> Ps = pn.find_neighbor_pores(pores=[0, 1], mode='or',
... include_input=True)
>>> print(Ps)
[ 0 1 2 5 6 25 26]
>>> Ps = pn.find_neighbor_pores(pores=[0, 2], flatten=False)
>>> print(Ps[0])
[ 1 5 25]
>>> print(Ps[1])
[ 1 3 7 27]
>>> Ps = pn.find_neighbor_pores(pores=[0, 2], mode='xnor')
>>> print(Ps)
[1]
>>> Ps = pn.find_neighbor_pores(pores=[0, 2], mode='xor')
>>> print(Ps)
[ 3 5 7 25 27]
|
find_neighbor_pores
|
python
|
PMEAL/OpenPNM
|
openpnm/network/_network.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/network/_network.py
|
MIT
|
def find_neighbor_throats(self, pores, mode='or', flatten=True,
asmask=False):
r"""
Returns a list of throats neighboring the given pore(s)
Parameters
----------
pores : array_like
Indices of pores whose neighbors are sought
flatten : bool, optional
If ``True`` (default) a 1D array of unique throat indices is
returned. If ``False`` the returned array contains arrays of
neighboring throat indices for each input pore, in the order
they were sent.
mode : str
Specifies logic to filter the resulting list. Options are:
=========== =====================================================
mode meaning
=========== =====================================================
'or' (default) All neighbors of the input throats. Also
accepts 'any' and 'union'.
'xor' Only neighbors of one and only one input throats. This
is useful for counting the pores that are not shared
by any of the input pores. Also accepts
'exclusive_or'.
'xnor' Neighbors that are shared by two or more input
throats. This is equivalent to counting all neighbors
with 'or', minus those found with 'xor', and is
useful for finding neighbors that the inputs have
in common.
'and' Only neighbors shared by all input throats. Also
accepts 'intersection' and 'all'
=========== =====================================================
asmask : boolean
If ``False`` (default), the returned result is a list of the
neighboring throats as indices. If ``True``, the returned result is a
boolean mask. (Useful for labelling)
Returns
-------
If ``flatten`` is ``True``, returns a 1D array of throat indices
filtered according to the specified mode. If ``flatten`` is
``False``, returns a list of lists, where each list contains the
neighbors of the corresponding input pores.
Notes
-----
The ``logic`` options are applied to neighboring bonds only, thus
it is not possible to obtain bonds that are part of the global set
but not neighbors. This is because (a) the list of global bonds
might be very large, and (b) it is not possible to return a list
of neighbors for each input site if global sites are considered.
Examples
--------
>>> import openpnm as op
>>> pn = op.network.Cubic(shape=[5, 5, 5])
>>> Ts = pn.find_neighbor_throats(pores=[0, 1])
>>> print(Ts)
[ 0 1 100 101 200 201]
>>> Ts = pn.find_neighbor_throats(pores=[0, 1], flatten=False)
>>> print(Ts[0])
[ 0 100 200]
>>> print(Ts[1])
[ 0 1 101 201]
"""
pores = self._parse_indices(pores)
if np.size(pores) == 0:
return np.array([], ndmin=1, dtype=int)
if flatten is False:
neighbors = topotools.find_neighbor_bonds(sites=pores, logic=mode,
network=self,
flatten=flatten)
else:
neighbors = topotools.find_neighbor_bonds(sites=pores, logic=mode,
network=self, flatten=True)
if asmask is False:
return neighbors
elif flatten is True:
neighbors = self._tomask(element='throat', indices=neighbors)
return neighbors
else:
raise Exception('Cannot create mask on an unflattened output')
|
Returns a list of throats neighboring the given pore(s)
Parameters
----------
pores : array_like
Indices of pores whose neighbors are sought
flatten : bool, optional
If ``True`` (default) a 1D array of unique throat indices is
returned. If ``False`` the returned array contains arrays of
neighboring throat indices for each input pore, in the order
they were sent.
mode : str
Specifies logic to filter the resulting list. Options are:
=========== =====================================================
mode meaning
=========== =====================================================
'or' (default) All neighbors of the input throats. Also
accepts 'any' and 'union'.
'xor' Only neighbors of one and only one input throats. This
is useful for counting the pores that are not shared
by any of the input pores. Also accepts
'exclusive_or'.
'xnor' Neighbors that are shared by two or more input
throats. This is equivalent to counting all neighbors
with 'or', minus those found with 'xor', and is
useful for finding neighbors that the inputs have
in common.
'and' Only neighbors shared by all input throats. Also
accepts 'intersection' and 'all'
=========== =====================================================
asmask : boolean
If ``False`` (default), the returned result is a list of the
neighboring throats as indices. If ``True``, the returned result is a
boolean mask. (Useful for labelling)
Returns
-------
If ``flatten`` is ``True``, returns a 1D array of throat indices
filtered according to the specified mode. If ``flatten`` is
``False``, returns a list of lists, where each list contains the
neighbors of the corresponding input pores.
Notes
-----
The ``logic`` options are applied to neighboring bonds only, thus
it is not possible to obtain bonds that are part of the global set
but not neighbors. This is because (a) the list of global bonds
might be very large, and (b) it is not possible to return a list
of neighbors for each input site if global sites are considered.
Examples
--------
>>> import openpnm as op
>>> pn = op.network.Cubic(shape=[5, 5, 5])
>>> Ts = pn.find_neighbor_throats(pores=[0, 1])
>>> print(Ts)
[ 0 1 100 101 200 201]
>>> Ts = pn.find_neighbor_throats(pores=[0, 1], flatten=False)
>>> print(Ts[0])
[ 0 100 200]
>>> print(Ts[1])
[ 0 1 101 201]
|
find_neighbor_throats
|
python
|
PMEAL/OpenPNM
|
openpnm/network/_network.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/network/_network.py
|
MIT
|
def num_neighbors(self, pores, mode='or', flatten=False):
r"""
Returns the number of neigbhoring pores for each given input pore
Parameters
----------
pores : array_like
Pores whose neighbors are to be counted
flatten : bool, optional
If ``False`` (default) the number of pores neighboring each
input pore as an array the same length as ``pores``. If
``True`` the sum total number of is counted.
mode : str
The logic to apply to the returned count of pores:
=========== =====================================================
mode meaning
=========== =====================================================
'or' (default) All neighbors of the input pores. Also
accepts 'any' and 'union'.
'xor' Only neighbors of one and only one input pore. This
is useful for counting the pores that are not shared
by any of the input pores. Also accepts
'exclusive_or'.
'xnor' Neighbors that are shared by two or more input pores.
This is equivalent to counting all neighbors
with 'or', minus those found with 'xor', and is
useful for finding neighbors that the inputs have
in common.
'and' Only neighbors shared by all input pores. Also
accepts 'intersection' and 'all'
=========== =====================================================
Returns
-------
If ``flatten`` is False, a 1D array with number of neighbors in each
element, otherwise a scalar value of the number of neighbors.
Notes
-----
This method literally just counts the number of elements in the array
returned by ``find_neighbor_pores`` using the same logic. Explore
those methods if uncertain about the meaning of the ``mode`` argument
here.
See Also
--------
find_neighbor_pores
find_neighbor_throats
Examples
--------
>>> import openpnm as op
>>> pn = op.network.Cubic(shape=[5, 5, 5])
>>> Np = pn.num_neighbors(pores=[0, 1], flatten=False)
>>> print(Np)
[3 4]
>>> Np = pn.num_neighbors(pores=[0, 2], flatten=True)
>>> print(Np)
6
>>> Np = pn.num_neighbors(pores=[0, 2], mode='and', flatten=True)
>>> print(Np)
1
"""
pores = self._parse_indices(pores)
if flatten:
# Count number of neighbors
num = self.find_neighbor_pores(pores, flatten=flatten,
mode=mode, include_input=True)
num = np.size(num)
else: # Could be done much faster if flatten == False
am = self.create_adjacency_matrix(fmt="csr")
num = am[pores].sum(axis=1).A1
return num
|
Returns the number of neigbhoring pores for each given input pore
Parameters
----------
pores : array_like
Pores whose neighbors are to be counted
flatten : bool, optional
If ``False`` (default) the number of pores neighboring each
input pore as an array the same length as ``pores``. If
``True`` the sum total number of is counted.
mode : str
The logic to apply to the returned count of pores:
=========== =====================================================
mode meaning
=========== =====================================================
'or' (default) All neighbors of the input pores. Also
accepts 'any' and 'union'.
'xor' Only neighbors of one and only one input pore. This
is useful for counting the pores that are not shared
by any of the input pores. Also accepts
'exclusive_or'.
'xnor' Neighbors that are shared by two or more input pores.
This is equivalent to counting all neighbors
with 'or', minus those found with 'xor', and is
useful for finding neighbors that the inputs have
in common.
'and' Only neighbors shared by all input pores. Also
accepts 'intersection' and 'all'
=========== =====================================================
Returns
-------
If ``flatten`` is False, a 1D array with number of neighbors in each
element, otherwise a scalar value of the number of neighbors.
Notes
-----
This method literally just counts the number of elements in the array
returned by ``find_neighbor_pores`` using the same logic. Explore
those methods if uncertain about the meaning of the ``mode`` argument
here.
See Also
--------
find_neighbor_pores
find_neighbor_throats
Examples
--------
>>> import openpnm as op
>>> pn = op.network.Cubic(shape=[5, 5, 5])
>>> Np = pn.num_neighbors(pores=[0, 1], flatten=False)
>>> print(Np)
[3 4]
>>> Np = pn.num_neighbors(pores=[0, 2], flatten=True)
>>> print(Np)
6
>>> Np = pn.num_neighbors(pores=[0, 2], mode='and', flatten=True)
>>> print(Np)
1
|
num_neighbors
|
python
|
PMEAL/OpenPNM
|
openpnm/network/_network.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/network/_network.py
|
MIT
|
def find_nearby_pores(self, pores, r, flatten=False, include_input=False):
r"""
Find all pores within a given radial distance of the input pore(s)
regardless of whether or not they are toplogically connected.
Parameters
----------
pores : array_like
The list of pores for whom nearby neighbors are to be found
r : scalar
The maximum radius within which the search should be performed
include_input : bool
Controls whether the input pores should be included in the
list of pores nearby the *other pores* in the input list.
So if ``pores=[1, 2]`` and 1 and 2 are within ``r`` of each
other, then 1 will be included in the returned for pores
near 2, and vice-versa *if* this argument is ``True``.
The default is ``False``.
flatten : bool
If ``True`` returns a single list of all pores that match the
criteria, otherwise returns an array containing a sub-array for
each input pore, where each sub-array contains the pores that
are nearby to each given input pore. The default is False.
Returns
-------
A list of pores which are within the given spatial distance.
If a list of N pores is supplied, then a an N-long list of
such lists is returned. The returned lists each contain the
pore for which the neighbors were sought.
Examples
--------
>>> import openpnm as op
>>> pn = op.network.Cubic(shape=[3, 3, 3])
>>> Ps = pn.find_nearby_pores(pores=[0, 1], r=1)
>>> print(Ps[0])
[3 9]
>>> print(Ps[1])
[ 2 4 10]
>>> Ps = pn.find_nearby_pores(pores=[0, 1], r=0.5)
>>> print(Ps)
[array([], dtype=int64), array([], dtype=int64)]
>>> Ps = pn.find_nearby_pores(pores=[0, 1], r=1, flatten=True)
>>> print(Ps)
[ 2 3 4 9 10]
"""
pores = self._parse_indices(pores)
# Handle an empty array if given
if np.size(pores) == 0:
return np.array([], dtype=np.int64)
if r <= 0:
raise Exception('Provided distances should be greater than 0')
# Create kdTree objects
kd = sptl.cKDTree(self['pore.coords'])
kd_pores = sptl.cKDTree(self['pore.coords'][pores])
# Perform search
Ps_within_r = kd_pores.query_ball_tree(kd, r=r)
# Remove self from each list
for i, P in enumerate(Ps_within_r):
Ps_within_r[i].remove(pores[i])
# Convert to flattened list by default
temp = np.concatenate((Ps_within_r))
Pn = np.unique(temp).astype(np.int64)
# Remove inputs if necessary
if include_input is False:
Pn = Pn[~np.in1d(Pn, pores)]
# Convert list of lists to a list of ndarrays
if flatten is False:
if len(Pn) == 0: # Deal with no nearby neighbors
Pn = [np.array([], dtype=np.int64) for i in pores]
else:
mask = np.zeros(shape=np.amax((Pn.max(), pores.max())) + 1, dtype=bool)
mask[Pn] = True
temp = []
for item in Ps_within_r:
temp.append(np.array(item, dtype=np.int64)[mask[item]])
Pn = temp
return Pn
|
Find all pores within a given radial distance of the input pore(s)
regardless of whether or not they are toplogically connected.
Parameters
----------
pores : array_like
The list of pores for whom nearby neighbors are to be found
r : scalar
The maximum radius within which the search should be performed
include_input : bool
Controls whether the input pores should be included in the
list of pores nearby the *other pores* in the input list.
So if ``pores=[1, 2]`` and 1 and 2 are within ``r`` of each
other, then 1 will be included in the returned for pores
near 2, and vice-versa *if* this argument is ``True``.
The default is ``False``.
flatten : bool
If ``True`` returns a single list of all pores that match the
criteria, otherwise returns an array containing a sub-array for
each input pore, where each sub-array contains the pores that
are nearby to each given input pore. The default is False.
Returns
-------
A list of pores which are within the given spatial distance.
If a list of N pores is supplied, then a an N-long list of
such lists is returned. The returned lists each contain the
pore for which the neighbors were sought.
Examples
--------
>>> import openpnm as op
>>> pn = op.network.Cubic(shape=[3, 3, 3])
>>> Ps = pn.find_nearby_pores(pores=[0, 1], r=1)
>>> print(Ps[0])
[3 9]
>>> print(Ps[1])
[ 2 4 10]
>>> Ps = pn.find_nearby_pores(pores=[0, 1], r=0.5)
>>> print(Ps)
[array([], dtype=int64), array([], dtype=int64)]
>>> Ps = pn.find_nearby_pores(pores=[0, 1], r=1, flatten=True)
>>> print(Ps)
[ 2 3 4 9 10]
|
find_nearby_pores
|
python
|
PMEAL/OpenPNM
|
openpnm/network/_network.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/network/_network.py
|
MIT
|
def get_comp_vals(self, propname):
r"""
Get a dictionary of the requested values from each component in the
mixture
Parameters
----------
propname : str
The property to fetch, such as ``'pore.viscosity'``.
Returns
-------
vals : dict
A dictionary with each component name as the key and the requested
property as the value.
"""
if not isinstance(propname, str):
return propname
if propname.endswith('*'):
try:
return self[propname]
except KeyError:
pass
try:
vals = {}
for comp in self.components.values():
vals[comp.name] = comp[propname]
return vals
except KeyError:
msg = f'{propname} not found on at least one component'
raise Exception(msg)
|
Get a dictionary of the requested values from each component in the
mixture
Parameters
----------
propname : str
The property to fetch, such as ``'pore.viscosity'``.
Returns
-------
vals : dict
A dictionary with each component name as the key and the requested
property as the value.
|
get_comp_vals
|
python
|
PMEAL/OpenPNM
|
openpnm/phase/_mixture.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/phase/_mixture.py
|
MIT
|
def get_mix_vals(self, propname, mode='linear', power=1):
r"""
Get the mole fraction weighted value of a given property for the mixture
Parameters
----------
propname : str
The property to fetch, such as ``'pore.viscosity'``.
mode : str
The type of weighting to use. Options are:
============== ====================================================
mode
============== ====================================================
'linear' (default) Basic mole fraction weighting of the form:
:math:`z = \Sigma (x_i \cdot \z_i)`
'logarithmic' Uses the natural logarithm of the property as:
:math:`ln(z) = \Sigma (x_i \cdot ln(\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.
Returns
-------
vals : ndarray
An ndarray with the requested values obtained using the specified
weigthing.
"""
Xs = self['pore.mole_fraction']
ys = self.get_comp_vals(propname)
if mode == 'linear':
z = np.vstack([Xs[k]*ys[k] for k in Xs.keys()]).sum(axis=0)
elif mode == 'logarithmic':
z = np.vstack([Xs[k]*np.log(ys[k]) for k in Xs.keys()]).sum(axis=0)
z = np.exp(z)
elif mode == 'power':
z = np.vstack([Xs[k]*(ys[k])**power for k in Xs.keys()]).sum(axis=0)
z = z**(1/power)
return z
|
Get the mole fraction weighted value of a given property for the mixture
Parameters
----------
propname : str
The property to fetch, such as ``'pore.viscosity'``.
mode : str
The type of weighting to use. Options are:
============== ====================================================
mode
============== ====================================================
'linear' (default) Basic mole fraction weighting of the form:
:math:`z = \Sigma (x_i \cdot \z_i)`
'logarithmic' Uses the natural logarithm of the property as:
:math:`ln(z) = \Sigma (x_i \cdot ln(\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.
Returns
-------
vals : ndarray
An ndarray with the requested values obtained using the specified
weigthing.
|
get_mix_vals
|
python
|
PMEAL/OpenPNM
|
openpnm/phase/_mixture.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/phase/_mixture.py
|
MIT
|
def remove_comp(self, component):
r"""
Helper method to remove a component from the mixture
Parameters
----------
component : Species object or str name
The `Species` to remove from the mixture. Can either be a handle to
the object, or the object's `name`.
Notes
-----
This method just calls
`del mixture['pore.mole_fraction.<component.name>']` to remove the
given component.
"""
if hasattr(component, 'name'):
component = component.name
try:
del self['pore.mole_fraction.' + component]
except KeyError:
pass
|
Helper method to remove a component from the mixture
Parameters
----------
component : Species object or str name
The `Species` to remove from the mixture. Can either be a handle to
the object, or the object's `name`.
Notes
-----
This method just calls
`del mixture['pore.mole_fraction.<component.name>']` to remove the
given component.
|
remove_comp
|
python
|
PMEAL/OpenPNM
|
openpnm/phase/_mixture.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/phase/_mixture.py
|
MIT
|
def check_mixture_health(self):
r"""
Checks the state of health of the mixture
Calculates the mole fraction of all species in each pore and returns
an list of where values are too low or too high,
Returns
-------
health : dict
A HealthDict object containing lists of locations where the mole
fractions are not unity. One value indicates locations that are
too high, and another where they are too low. This `dict` evaluates
to `True` if all items are healthy.
"""
h = HealthDict()
h['mole_fraction_too_low'] = []
h['mole_fraction_too_high'] = []
conc = mole_summation(phase=self)
lo = np.where(conc < 1.0)[0]
hi = np.where(conc > 1.0)[0]
if len(lo) > 0:
h['mole_fraction_too_low'] = lo
if len(hi) > 0:
h['mole_fraction_too_high'] = hi
return h
|
Checks the state of health of the mixture
Calculates the mole fraction of all species in each pore and returns
an list of where values are too low or too high,
Returns
-------
health : dict
A HealthDict object containing lists of locations where the mole
fractions are not unity. One value indicates locations that are
too high, and another where they are too low. This `dict` evaluates
to `True` if all items are healthy.
|
check_mixture_health
|
python
|
PMEAL/OpenPNM
|
openpnm/phase/_mixture.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/phase/_mixture.py
|
MIT
|
def x(self, compname=None, x=None):
r"""
Helper method for getting and setting mole fractions of a component
Parameters
----------
compname : str, optional
The name of the component, i.e. ``obj.name``. If ``x`` is not
provided this will *return* the mole fraction of the requested
component. If ``x`` is provided this will *set* the mole fraction
of the specified component to ``x``.
x : scalar or ndarray, optional
The mole fraction of the given species in the mixture. If not
provided this method works as a *getter* and will return the
mole fraction of the requested component. If ``compname`` is not
provided then the mole fractions of all components will be returned
as a dictionary with the components names as keys.
Notes
-----
This method is equivalent to
``mixture['pore.mole_fraction.<compname>'] = x``
"""
if hasattr(compname, 'name'):
compname = compname.name
if x is None:
if compname is None:
return self['pore.mole_fraction']
else:
self['pore.mole_fraction' + '.' + compname]
else:
self['pore.mole_fraction.' + compname] = x
|
Helper method for getting and setting mole fractions of a component
Parameters
----------
compname : str, optional
The name of the component, i.e. ``obj.name``. If ``x`` is not
provided this will *return* the mole fraction of the requested
component. If ``x`` is provided this will *set* the mole fraction
of the specified component to ``x``.
x : scalar or ndarray, optional
The mole fraction of the given species in the mixture. If not
provided this method works as a *getter* and will return the
mole fraction of the requested component. If ``compname`` is not
provided then the mole fractions of all components will be returned
as a dictionary with the components names as keys.
Notes
-----
This method is equivalent to
``mixture['pore.mole_fraction.<compname>'] = x``
|
x
|
python
|
PMEAL/OpenPNM
|
openpnm/phase/_mixture.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/phase/_mixture.py
|
MIT
|
def y(self, compname=None, y=None):
r"""
Helper method for getting and setting mole fractions of a component
Parameters
----------
compname : str, optional
The name of the component i.e. ``obj.name``. If ``y`` is not
provided this will *return* the mole fraction of the requested
component. If ``y`` is provided this will *set* the mole fraction
of the specified component to ``y``.
y : scalar or ndarray, optional
The mole fraction of the given species in the mixture. If not
provided this method works as a *getter* and will return the
mole fraction of the requested component. If ``compname`` is also
not provided then the mole fractions of all components will be
returned as a dictionary with the components names as keys.
Notes
-----
This method is equivalent to
``mixture['pore.mole_fraction.<compname>'] = y``
"""
if hasattr(compname, 'name'):
compname = compname.name
if y is None:
if compname is None:
return self['pore.mole_fraction']
else:
return self['pore.mole_fraction' + '.' + compname]
else:
self['pore.mole_fraction.' + compname] = y
|
Helper method for getting and setting mole fractions of a component
Parameters
----------
compname : str, optional
The name of the component i.e. ``obj.name``. If ``y`` is not
provided this will *return* the mole fraction of the requested
component. If ``y`` is provided this will *set* the mole fraction
of the specified component to ``y``.
y : scalar or ndarray, optional
The mole fraction of the given species in the mixture. If not
provided this method works as a *getter* and will return the
mole fraction of the requested component. If ``compname`` is also
not provided then the mole fractions of all components will be
returned as a dictionary with the components names as keys.
Notes
-----
This method is equivalent to
``mixture['pore.mole_fraction.<compname>'] = y``
|
y
|
python
|
PMEAL/OpenPNM
|
openpnm/phase/_mixture.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/phase/_mixture.py
|
MIT
|
def _get_rtol(self, A, b, x0):
r"""
Returns the relative tolerance ``rtol`` that corresponds to the
the given tolerance ``tol``.
Notes
-----
``rtol`` is defined based on the following formula:
``rtol = residual(@x_final) / residual(@x0)``
"""
res0 = self._get_residual(A, b, x0)
atol = self._get_atol(b)
rtol = atol / res0
return rtol
|
Returns the relative tolerance ``rtol`` that corresponds to the
the given tolerance ``tol``.
Notes
-----
``rtol`` is defined based on the following formula:
``rtol = residual(@x_final) / residual(@x0)``
|
_get_rtol
|
python
|
PMEAL/OpenPNM
|
openpnm/solvers/_base.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/solvers/_base.py
|
MIT
|
def solve(self, A, b, **kwargs):
"""Solves the given linear system of equations Ax=b."""
from pypardiso import spsolve
if not isinstance(A, (csr_matrix, csc_matrix)):
A = A.tocsr()
return (spsolve(A, b), 0)
|
Solves the given linear system of equations Ax=b.
|
solve
|
python
|
PMEAL/OpenPNM
|
openpnm/solvers/_pardiso.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/solvers/_pardiso.py
|
MIT
|
def _create_solver(self):
r"""
This method creates the petsc sparse linear solver.
"""
# https://petsc.org/release/docs/manualpages/KSP/KSPType.html
iterative = [
'richardson', 'chebyshev', 'cg', 'groppcg', 'pipecg', 'pipecgrr',
'cgne', 'nash', 'stcg', 'gltr', 'fcg', 'pipefcg', 'gmres',
'pipefgmres', 'fgmres', 'lgmres', 'dgmres', 'pgmres', 'tcqmr',
'bcgs', 'ibcgs', 'fbcgs', 'fbcgsr', 'bcgsl', 'pipebcgs', 'cgs',
'tfqmr', 'cr', 'pipecr', 'lsqr', 'preonly', 'qcg', 'bicg',
'minres', 'symmlq', 'lcd', 'python', 'gcr', 'pipegcr', 'tsirm',
'cgls', 'fetidp']
# https://petsc.org/release/docs/manualpages/PC/PCType.html
preconditioners = [
'none', 'jacobi', 'sor', 'lu', 'shell', 'bjacobi', 'mg',
'eisenstat', 'ilu', 'icc', 'asm', 'gasm', 'ksp', 'composite',
'redundant', 'spai', 'nn', 'cholesky', 'pbjacobi', 'mat', 'hypre',
'parms', 'fieldsplit', 'tfs', 'ml', 'galerkin', 'exotic', 'cp',
'bfbt', 'lsc', 'python', 'pfmg', 'syspfmg', 'redistribute', 'svd',
'gamg', 'sacusp', 'sacusppoly', 'bicgstabcusp', 'ainvcusp',
'chowiluviennacl', 'rowscalingviennacl', 'saviennacl', 'bddc',
'kaczmarz', 'telescope']
direct_lu = ['mumps', 'superlu_dist', 'umfpack', 'klu']
direct_cholesky = ['mumps', 'cholmod']
valid_solvers = iterative + direct_lu + direct_cholesky
solver = self.solver_type
preconditioner = self.preconditioner
if solver not in valid_solvers:
raise Exception(f"{solver} solver not availabe, choose another solver")
if preconditioner not in preconditioners:
raise Exception(f"{preconditioner} not found, choose another preconditioner")
self.ksp = PETSc.KSP()
self.ksp.create(PETSc.COMM_WORLD)
if solver in direct_lu:
self.ksp.getPC().setType('lu')
self.ksp.getPC().setFactorSolverType(solver)
self.ksp.setType('preonly')
elif solver in direct_cholesky:
self.ksp.getPC().setType('cholesky')
self.ksp.getPC().setFactorSolverType(solver)
self.ksp.setType('preonly')
elif solver in preconditioners:
self.ksp.getPC().setType(solver)
self.ksp.setType('preonly')
elif solver in iterative:
self.ksp.getPC().setType(preconditioner)
self.ksp.setType(solver)
|
This method creates the petsc sparse linear solver.
|
_create_solver
|
python
|
PMEAL/OpenPNM
|
openpnm/solvers/_petsc.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/solvers/_petsc.py
|
MIT
|
def _set_tolerances(self, atol=None, rtol=None, maxiter=None):
r"""
Set absolute and relative tolerances, and maximum number of iterations.
"""
atol = self.atol if atol is None else atol
rtol = self.rtol if rtol is None else rtol
maxiter = self.maxiter if maxiter is None else maxiter
# BUG: PETSc misses rtol requirement by ~10-20X -> Report to petsc4py
self.ksp.setTolerances(atol=None, rtol=rtol/50, max_it=maxiter)
|
Set absolute and relative tolerances, and maximum number of iterations.
|
_set_tolerances
|
python
|
PMEAL/OpenPNM
|
openpnm/solvers/_petsc.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/solvers/_petsc.py
|
MIT
|
def _assemble_A(self):
r"""
This method creates the petsc sparse coefficients matrix from the
OpenPNM scipy one. The method also equally decomposes the matrix at
certain rows into different blocks (each block contains all the
columns) and distributes them over the pre-assigned cores for parallel
computing. The method can be used in serial.
"""
# Create a petsc sparse matrix
self.petsc_A = PETSc.Mat()
self.petsc_A.create(PETSc.COMM_WORLD)
self.petsc_A.setSizes([self.m, self.n])
self.petsc_A.setType('aij') # sparse
self.petsc_A.setUp()
# Loop over owned block of rows on this processor
# and insert entry values (for parallel computing).
self.Istart, self.Iend = self.petsc_A.getOwnershipRange()
# Assign values to the coefficients matrix from the scipy sparse csr
size_tmp = self.A.shape
# Row indices
csr1 = self.A.indptr[self.Istart:self.Iend+1] - self.A.indptr[self.Istart]
ind1 = self.A.indptr[self.Istart]
ind2 = self.A.indptr[self.Iend]
csr2 = self.A.indices[ind1:ind2] # column indices
csr3 = self.A.data[ind1:ind2] # data
self.petsc_A = PETSc.Mat().createAIJ(size=size_tmp,
csr=(csr1, csr2, csr3))
# Communicate off-processor values and setup internal data structures
# for performing parallel operations
self.petsc_A.assemblyBegin()
self.petsc_A.assemblyEnd()
|
This method creates the petsc sparse coefficients matrix from the
OpenPNM scipy one. The method also equally decomposes the matrix at
certain rows into different blocks (each block contains all the
columns) and distributes them over the pre-assigned cores for parallel
computing. The method can be used in serial.
|
_assemble_A
|
python
|
PMEAL/OpenPNM
|
openpnm/solvers/_petsc.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/solvers/_petsc.py
|
MIT
|
def _assemble_b_and_x(self):
r"""
Initialize the solution vector (self.petsc_x), which is a dense
matrix (1D vector) and defines the rhs vector (self.petsc_b) from
the existing data.
"""
# Get vector(s) compatible with the matrix (same parallel layout)
# passing same communicator as the A matrix
# Global solution vector (all the local solutions will return to it)
self.petsc_s = PETSc.Vec()
self.petsc_s.create(PETSc.COMM_WORLD)
self.petsc_s.setSizes(self.m)
self.petsc_s.setFromOptions()
self.Istart, self.Iend = self.petsc_s.getOwnershipRange()
self.petsc_x = (self.petsc_s).duplicate()
self.petsc_b = (self.petsc_s).duplicate()
# Set the solution vector to zeros or the given initial guess (if any)
PETSc.Vec.setArray(self.petsc_x, self.x0[self.Istart: self.Iend])
# Define the petsc rhs vector from the numpy one
PETSc.Vec.setArray(self.petsc_b, self.b[self.Istart: self.Iend])
|
Initialize the solution vector (self.petsc_x), which is a dense
matrix (1D vector) and defines the rhs vector (self.petsc_b) from
the existing data.
|
_assemble_b_and_x
|
python
|
PMEAL/OpenPNM
|
openpnm/solvers/_petsc.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/solvers/_petsc.py
|
MIT
|
def solve(self, A, b, x0=None, solver_type='cg', precondioner='jacobi',
maxiter=None, atol=None, rtol=None):
r"""
Solves and returns the solution to the linear system, Ax = b.
This method converts the solution vector from a PETSc.Vec
instance to a numpy array, and finally destroys all the PETSc
objects to free memory.
Parameters
----------
A : csr_matrix
Coefficients matrix in Ax = b
b : ndarray
Right-hand-side vector in Ax = b
solver_type : str, optional
Default is the iterative solver 'cg' based on the
Conjugate Gradient method.
preconditioner: str, optional
Default is the 'jacobi' preconditioner, i.e., diagonal
scaling preconditioning. The preconditioner is used with
iterative solvers. When a direct solver is used, this
parameter is ignored.
factorization_type : str, optional
The factorization type used with the direct solver.
Default is 'lu'. This parameter is ignored when an
iterative solver is used.
Returns
-------
ndarray
The solution to Ax = b
Notes
-----
Certain combinations of iterative solvers and precondioners
or direct solvers and factorization types are not supported.
The summary table of the different possibilities
can be found
`here <https://petsc.org/main/overview/linear_solve_table>`_
"""
self.b = b
self.A = sp.sparse.csr_matrix(A)
self.m, self.n = self.A.shape
self.x0 = np.zeros_like(self.b) if x0 is None else x0
self.solver_type = solver_type
self.preconditioner = precondioner
self.atol = self._get_atol(self.b)
self.rtol = self._get_rtol(self.x0)
self._assemble_b_and_x()
self._assemble_A()
self._create_solver()
self._set_tolerances(atol=atol, rtol=rtol, maxiter=maxiter)
self.ksp.setOperators(self.petsc_A)
self.ksp.setFromOptions()
# Solve the linear system
self.ksp.solve(self.petsc_b, self.petsc_x)
# Gather the solution to all processors
gather_to_0, self.petsc_s = PETSc.Scatter().toAll(self.petsc_x)
gather_to_0.scatter(self.petsc_x, self.petsc_s,
PETSc.InsertMode.INSERT, PETSc.ScatterMode.FORWARD)
# Convert solution vector from PETSc.Vec instance to a numpy array
self.solution = PETSc.Vec.getArray(self.petsc_s)
# Destroy petsc solver, coefficients matrix, rhs, and solution vectors
PETSc.KSP.destroy(self.ksp)
PETSc.Mat.destroy(self.petsc_A)
PETSc.Vec.destroy(self.petsc_b)
PETSc.Vec.destroy(self.petsc_x)
PETSc.Vec.destroy(self.petsc_s)
# FIXME: fetch exit_code somehow from petsc
exit_code = 0
return self.solution, exit_code
|
Solves and returns the solution to the linear system, Ax = b.
This method converts the solution vector from a PETSc.Vec
instance to a numpy array, and finally destroys all the PETSc
objects to free memory.
Parameters
----------
A : csr_matrix
Coefficients matrix in Ax = b
b : ndarray
Right-hand-side vector in Ax = b
solver_type : str, optional
Default is the iterative solver 'cg' based on the
Conjugate Gradient method.
preconditioner: str, optional
Default is the 'jacobi' preconditioner, i.e., diagonal
scaling preconditioning. The preconditioner is used with
iterative solvers. When a direct solver is used, this
parameter is ignored.
factorization_type : str, optional
The factorization type used with the direct solver.
Default is 'lu'. This parameter is ignored when an
iterative solver is used.
Returns
-------
ndarray
The solution to Ax = b
Notes
-----
Certain combinations of iterative solvers and precondioners
or direct solvers and factorization types are not supported.
The summary table of the different possibilities
can be found
`here <https://petsc.org/main/overview/linear_solve_table>`_
|
solve
|
python
|
PMEAL/OpenPNM
|
openpnm/solvers/_petsc.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/solvers/_petsc.py
|
MIT
|
def solve(self, A, b, **kwargs):
"""Solves the given linear system of equations Ax=b."""
if not isinstance(A, (csr_matrix, csc_matrix)):
A = A.tocsr()
return (spsolve(A, b), 0)
|
Solves the given linear system of equations Ax=b.
|
solve
|
python
|
PMEAL/OpenPNM
|
openpnm/solvers/_scipy.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/solvers/_scipy.py
|
MIT
|
def solve(self, A, b, **kwargs):
"""Solves the given linear system of equations Ax=b."""
if not isinstance(A, (csr_matrix, csc_matrix)):
A = A.tocsr()
atol = self._get_atol(b)
try:
return cg(A, b, tol=self.tol, atol=atol, **kwargs)
except TypeError:
return cg(A, b, rtol=self.tol, atol=atol, **kwargs)
|
Solves the given linear system of equations Ax=b.
|
solve
|
python
|
PMEAL/OpenPNM
|
openpnm/solvers/_scipy.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/solvers/_scipy.py
|
MIT
|
def find_isolated_clusters(network, mask, inlets):
r"""
Identifies pores and throats that are invaded but not connected to the inlets
Parameters
----------
network : dict
The OpenPNM Network
mask : ndarray
A boolean mask of either Nt or Np length with ``True`` values
indicating invaded bonds or sites. If this array is Nt-long then
then bond percolation is used to identify clusters, whereas site
percolation is used if it is Np-long.
inlets : ndarray
A array containing indices of the pores which define the inlets. Any
clusters not connected to these sites are considered isolated.
Returns
-------
sites : ndarray
An ndarray containing the indices of invaded pores which are not
connected to the given ``inlets``.
"""
labels = find_clusters(network=network, mask=mask)
isolated = np.in1d(labels.pore_labels, labels.pore_labels[inlets], invert=True)
isolated = np.where(isolated)[0]
return isolated
|
Identifies pores and throats that are invaded but not connected to the inlets
Parameters
----------
network : dict
The OpenPNM Network
mask : ndarray
A boolean mask of either Nt or Np length with ``True`` values
indicating invaded bonds or sites. If this array is Nt-long then
then bond percolation is used to identify clusters, whereas site
percolation is used if it is Np-long.
inlets : ndarray
A array containing indices of the pores which define the inlets. Any
clusters not connected to these sites are considered isolated.
Returns
-------
sites : ndarray
An ndarray containing the indices of invaded pores which are not
connected to the given ``inlets``.
|
find_isolated_clusters
|
python
|
PMEAL/OpenPNM
|
openpnm/topotools/_perctools.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/topotools/_perctools.py
|
MIT
|
def find_clusters(network, mask=[]):
r"""
Identify connected clusters of pores and throats in the network.
Either site and bond percolation can be considered, see description of
``mask`` argument for details.
Parameters
----------
network : Network
The network
mask : array_like, boolean
A list of open bonds or sites (throats or pores). If the mask is
Np-long, then the method will perform a site percolation to identify
clusters, and if the mask is Nt-long bond percolation will be
performed.
Returns
-------
p_labels, t_labels : tuple of ndarrays
A tuple containing an Np-long array of pore cluster labels, and an
Nt-long array of throat cluster labels. The label numbers correspond
such that pores and throats with the same label are part of the same
cluster. Uninvaded locations are set to -1.
"""
# Parse the input arguments
mask = np.array(mask, ndmin=1)
if mask.dtype != bool:
raise Exception('Mask must be a boolean array of Np or Nt length')
# If pore mask was given perform site percolation
if np.size(mask) == network.Np:
(p_clusters, t_clusters) = \
simulations.site_percolation(network.conns, mask)
# If pore mask was given perform bond percolation
elif np.size(mask) == network.Nt:
(p_clusters, t_clusters) = \
simulations.bond_percolation(network.conns, mask)
else:
raise Exception('Mask received was neither Nt nor Np long')
result = namedtuple('result', ('pore_labels', 'throat_labels'))
result.pore_labels = p_clusters
result.throat_labels = t_clusters
return result
|
Identify connected clusters of pores and throats in the network.
Either site and bond percolation can be considered, see description of
``mask`` argument for details.
Parameters
----------
network : Network
The network
mask : array_like, boolean
A list of open bonds or sites (throats or pores). If the mask is
Np-long, then the method will perform a site percolation to identify
clusters, and if the mask is Nt-long bond percolation will be
performed.
Returns
-------
p_labels, t_labels : tuple of ndarrays
A tuple containing an Np-long array of pore cluster labels, and an
Nt-long array of throat cluster labels. The label numbers correspond
such that pores and throats with the same label are part of the same
cluster. Uninvaded locations are set to -1.
|
find_clusters
|
python
|
PMEAL/OpenPNM
|
openpnm/topotools/_perctools.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/topotools/_perctools.py
|
MIT
|
def trim(network, pores=[], throats=[]):
"""
Remove pores or throats from the network
Parameters
----------
network : Network
The Network from which pores or throats should be removed
pores (or throats) : array_like
The indices of the of the pores or throats to be removed from the
network.
"""
pores = network._parse_indices(pores)
throats = network._parse_indices(throats)
Pkeep = np.copy(network['pore.all'])
Tkeep = np.copy(network['throat.all'])
if np.size(pores) > 0:
Pkeep[pores] = False
if not np.any(Pkeep):
raise Exception('Cannot delete ALL pores')
# # Performing customized find_neighbor_throats which is much faster,
# # but not general for other types of queries
# temp = np.in1d(network['throat.conns'].flatten(), pores)
# temp = np.reshape(temp, (network.Nt, 2))
# Ts = np.any(temp, axis=1)
# Ts = network.Ts[Ts]
Ts = network.find_neighbor_throats(pores=~Pkeep, mode='union')
if len(Ts) > 0:
Tkeep[Ts] = False
if np.size(throats) > 0:
Tkeep[throats] = False
# The following IF catches the special case of deleting ALL throats
# It removes all throat props, adds 'all', and skips rest of function
if not np.any(Tkeep):
logger.info('Removing ALL throats from network')
for item in list(network.keys()):
if item.split('.', 1)[0] == 'throat':
del network[item]
network['throat.all'] = np.array([], ndmin=1)
return
# Temporarily store throat conns and pore map for processing later
Np_old = network.Np
Nt_old = network.Nt
Pkeep_inds = np.where(Pkeep)[0]
Tkeep_inds = np.where(Tkeep)[0]
Pmap = np.ones((network.Np,), dtype=int)*-1
tpore1 = network['throat.conns'][:, 0]
tpore2 = network['throat.conns'][:, 1]
# Delete specified pores and throats from all objects
for obj in network.project:
if (obj.Np == Np_old) and (obj.Nt == Nt_old):
Ps = Pkeep_inds
Ts = Tkeep_inds
for key in list(obj.keys()):
temp = obj.pop(key)
if key.split('.', 1)[0] == 'throat':
obj.update({key: temp[Ts]})
if key.split('.', 1)[0] == 'pore':
obj.update({key: temp[Ps]})
# Remap throat connections
Pmap[Pkeep] = np.arange(0, np.sum(Pkeep))
Tnew1 = Pmap[tpore1[Tkeep]]
Tnew2 = Pmap[tpore2[Tkeep]]
network.update({'throat.conns': np.vstack((Tnew1, Tnew2)).T})
# Clear adjacency and incidence matrices which will be out of date now
network._am.clear()
network._im.clear()
|
Remove pores or throats from the network
Parameters
----------
network : Network
The Network from which pores or throats should be removed
pores (or throats) : array_like
The indices of the of the pores or throats to be removed from the
network.
|
trim
|
python
|
PMEAL/OpenPNM
|
openpnm/topotools/_topotools.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/topotools/_topotools.py
|
MIT
|
def extend(network, coords=[], conns=[], labels=[], **kwargs):
r"""
Add pores or throats to the network from a list of coords or conns.
Parameters
----------
network : Network
The network to which pores or throats should be added
coords : array_like
The coordinates of the pores to add. These will be appended to the
'pore.coords' array so should be of shape N-by-3, where N is the
number of pores in the list.
conns : array_like
The throat connections to add. These will be appended to the
'throat.conns' array so should be of shape N-by-2. Note that the
numbering must point to existing pores.
labels : str, or list[str], optional
A list of labels to apply to the new pores and throats
"""
if 'throat_conns' in kwargs.keys():
conns = kwargs['throat_conns']
if 'pore_coords' in kwargs.keys():
coords = kwargs['pore_coords']
coords = np.array(coords)
conns = np.array(conns)
Np_old = network.num_pores()
Nt_old = network.num_throats()
Np = Np_old + coords.shape[0]
Nt = Nt_old + conns.shape[0]
if np.any(conns > Np):
raise Exception('Some throat conns point to non-existent pores')
network.update({'pore.all': np.ones([Np, ], dtype=bool),
'throat.all': np.ones([Nt, ], dtype=bool)})
# Add coords and conns
if np.size(coords) > 0:
coords = np.vstack((network['pore.coords'], coords))
network['pore.coords'] = coords
if np.size(conns) > 0:
conns = np.vstack((network['throat.conns'], conns))
network['throat.conns'] = conns
# Increase size of any prop or label arrays already on network and phases
objs = list(network.project.phases)
objs.append(network)
for obj in objs:
obj.update({'pore.all': np.ones([Np, ], dtype=bool),
'throat.all': np.ones([Nt, ], dtype=bool)})
for item in list(obj.keys()):
N = obj._count(element=item.split('.', 1)[0])
if obj[item].shape[0] < N:
arr = obj.pop(item)
s = arr.shape
if arr.dtype == bool:
obj[item] = np.zeros(shape=(N, *s[1:]), dtype=bool)
else:
obj[item] = np.ones(shape=(N, *s[1:]), dtype=float)*np.nan
obj[item][:arr.shape[0]] = arr
# Regenerate models on all objects to fill new elements
for obj in network.project.phases:
if hasattr(obj, 'models'):
obj.regenerate_models()
# Apply labels, if supplied
if labels != []:
# Convert labels to list if necessary
if isinstance(labels, str):
labels = [labels]
for label in labels:
# Remove pore or throat from label, if present
label = label.split('.', 1)[-1]
if np.size(coords) > 0:
Ps = np.r_[Np_old:Np]
if 'pore.'+label not in network.labels():
network['pore.'+label] = False
network['pore.'+label][Ps] = True
if np.size(conns) > 0:
Ts = np.r_[Nt_old:Nt]
if 'throat.'+label not in network.labels():
network['throat.'+label] = False
network['throat.'+label][Ts] = True
# Clear adjacency and incidence matrices which will be out of date now
network._am.clear()
network._im.clear()
|
Add pores or throats to the network from a list of coords or conns.
Parameters
----------
network : Network
The network to which pores or throats should be added
coords : array_like
The coordinates of the pores to add. These will be appended to the
'pore.coords' array so should be of shape N-by-3, where N is the
number of pores in the list.
conns : array_like
The throat connections to add. These will be appended to the
'throat.conns' array so should be of shape N-by-2. Note that the
numbering must point to existing pores.
labels : str, or list[str], optional
A list of labels to apply to the new pores and throats
|
extend
|
python
|
PMEAL/OpenPNM
|
openpnm/topotools/_topotools.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/topotools/_topotools.py
|
MIT
|
def label_faces(network, tol=0.0, label='surface'):
r"""
Finds pores on the surface of the network and labels them according to
whether they are on the *top*, *bottom*, etc.
This function assumes the network is cubic in shape
Parameters
----------
network : Network
The network to apply the labels
tol : scalar
The tolerance for defining what counts as a surface pore, which is
specifically meant for random networks. All pores with ``tol`` of
the maximum or minimum along each axis are counts as pores. The
default is 0.
label : str
An identifying label to isolate the pores on the faces of the network.
The default is 'surface'. Surface pores can be found using
``find_surface_pores``.
"""
if label is not None:
label = label.split('.', 1)[-1]
if 'pore.'+label not in network.labels():
find_surface_pores(network, label=label)
Psurf = network['pore.'+label]
else:
Psurf = True # So it will "do nothing" below
crds = network['pore.coords']
xmin, xmax = np.amin(crds[:, 0]), np.amax(crds[:, 0])
xspan = xmax - xmin
ymin, ymax = np.amin(crds[:, 1]), np.amax(crds[:, 1])
yspan = ymax - ymin
zmin, zmax = np.amin(crds[:, 2]), np.amax(crds[:, 2])
zspan = zmax - zmin
dims = dimensionality(network)
if dims[0]:
network['pore.left'] = (crds[:, 0] <= (xmin + tol*xspan)) * Psurf
network['pore.xmin'] = np.copy(network['pore.left'])
network['pore.right'] = (crds[:, 0] >= (xmax - tol*xspan)) * Psurf
network['pore.xmax'] = np.copy(network['pore.right'])
if dims[1]:
network['pore.front'] = (crds[:, 1] <= (ymin + tol*yspan)) * Psurf
network['pore.ymin'] = np.copy(network['pore.front'])
network['pore.back'] = (crds[:, 1] >= (ymax - tol*yspan)) * Psurf
network['pore.ymax'] = np.copy(network['pore.back'])
if dims[2]:
network['pore.bottom'] = (crds[:, 2] <= (zmin + tol*zspan)) * Psurf
network['pore.zmin'] = np.copy(network['pore.bottom'])
network['pore.top'] = (crds[:, 2] >= (zmax - tol*zspan)) * Psurf
network['pore.zmax'] = np.copy(network['pore.top'])
|
Finds pores on the surface of the network and labels them according to
whether they are on the *top*, *bottom*, etc.
This function assumes the network is cubic in shape
Parameters
----------
network : Network
The network to apply the labels
tol : scalar
The tolerance for defining what counts as a surface pore, which is
specifically meant for random networks. All pores with ``tol`` of
the maximum or minimum along each axis are counts as pores. The
default is 0.
label : str
An identifying label to isolate the pores on the faces of the network.
The default is 'surface'. Surface pores can be found using
``find_surface_pores``.
|
label_faces
|
python
|
PMEAL/OpenPNM
|
openpnm/topotools/_topotools.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/topotools/_topotools.py
|
MIT
|
def find_surface_pores(network, markers=None, label='surface'):
r"""
Find the pores on the surface of the domain by performing a Delaunay
triangulation between the network pores and some external ``markers``. All
pores connected to these external marker points are considered surface
pores.
Parameters
----------
network: Network
The network for which the surface pores are to be found
markers: array_like
3 x N array of the marker coordinates to use in the triangulation. The
labeling is performed in one step, so all points are added, and then
any pores connected to at least one marker is given the provided label.
By default, this function will automatically generate 6 points outside
each axis of the network domain. Users may wish to specify a single
external marker point and provide an appropriate label in order to
identify specific faces. For instance, the marker may be *above* the
domain, and the label might be 'top_surface'.
label : str
The label to apply to the pores. The default is 'surface'.
Notes
-----
This function does not check whether the given markers actually lie outside
the domain, allowing the labeling of *internal* sufaces.
If this method fails to mark some surface pores, consider sending more
markers on each face.
"""
import scipy.spatial as sptl
dims = dimensionality(network)
coords = network['pore.coords'][:, dims]
if markers is None:
# normalize coords to a 1 unit cube centered on origin
coords -= np.amin(coords, axis=0)
coords /= np.amax(coords, axis=0)
coords -= 0.5
npts = max((network.Np/10, 100))
if sum(dims) == 1:
network['pore.'+label] = True
return
if sum(dims) == 2:
r = 0.75
theta = np.linspace(0, 2*np.pi, int(npts), dtype=float)
x = r*np.cos(theta)
y = r*np.sin(theta)
markers = np.vstack((x, y)).T
if sum(dims) == 3:
r = 1.00
indices = np.arange(0, int(npts), dtype=float) + 0.5
phi = np.arccos(1 - 2*indices/npts)
theta = np.pi * (1 + 5**0.5) * indices
x = r*np.cos(theta) * np.sin(phi)
y = r*np.sin(theta) * np.sin(phi)
z = r*np.cos(phi)
markers = np.vstack((x, y, z)).T
else:
if sum(dims) == 1:
pass
if sum(dims) == 2:
markers = np.atleast_2d(markers)
if markers.shape[1] != 2:
raise Exception('Network appears planar, so markers must be 2D')
if sum(dims) == 3:
markers = np.atleast_2d(markers)
if markers.shape[1] != 3:
raise Exception('Markers must be 3D for this network')
pts = np.vstack((coords, markers))
tri = sptl.Delaunay(pts, incremental=False)
(indices, indptr) = tri.vertex_neighbor_vertices
for k in range(network.Np, tri.npoints):
neighbors = indptr[indices[k]:indices[k+1]]
inds = np.where(neighbors < network.Np)
neighbors = neighbors[inds]
if 'pore.'+label not in network.keys():
network['pore.'+label] = False
network['pore.'+label][neighbors] = True
|
Find the pores on the surface of the domain by performing a Delaunay
triangulation between the network pores and some external ``markers``. All
pores connected to these external marker points are considered surface
pores.
Parameters
----------
network: Network
The network for which the surface pores are to be found
markers: array_like
3 x N array of the marker coordinates to use in the triangulation. The
labeling is performed in one step, so all points are added, and then
any pores connected to at least one marker is given the provided label.
By default, this function will automatically generate 6 points outside
each axis of the network domain. Users may wish to specify a single
external marker point and provide an appropriate label in order to
identify specific faces. For instance, the marker may be *above* the
domain, and the label might be 'top_surface'.
label : str
The label to apply to the pores. The default is 'surface'.
Notes
-----
This function does not check whether the given markers actually lie outside
the domain, allowing the labeling of *internal* sufaces.
If this method fails to mark some surface pores, consider sending more
markers on each face.
|
find_surface_pores
|
python
|
PMEAL/OpenPNM
|
openpnm/topotools/_topotools.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/topotools/_topotools.py
|
MIT
|
def clone_pores(network, pores, labels=['clone'], mode='parents'):
r"""
Clones the specified pores and adds them to the network
Parameters
----------
network : Network
The Network object to which the new pores are to be added
pores : array_like
List of pores to clone
labels : str, or list[str]
The labels to apply to the clones, default is 'clone'
mode : str
Controls the connections between parents and clones. Options are:
=========== ==========================================================
mode description
=========== ==========================================================
'parents' Each clone is connected only to its parent.(Default)
'siblings' Clones are only connected to each other in the same
manner as parents were connected.
'isolated' No connections between parents or siblings
=========== ==========================================================
"""
if isinstance(labels, str):
labels = [labels]
network._parse_indices(pores)
Np = network.Np
Nt = network.Nt
# Clone pores
parents = np.array(pores, ndmin=1)
pcurrent = network['pore.coords']
pclone = pcurrent[pores, :]
pnew = np.concatenate((pcurrent, pclone), axis=0)
Npnew = np.shape(pnew)[0]
clones = np.arange(Np, Npnew)
# Create cloned pores first
extend(network=network, pore_coords=pclone)
# Apply provided labels to cloned pores
for item in labels:
network.set_label(label=item, pores=range(Np, Npnew))
# Add connections between parents and clones
if mode == 'parents':
tclone = np.vstack((parents, clones)).T
extend(network=network, conns=tclone)
elif mode == 'siblings':
ts = network.find_neighbor_throats(pores=pores, mode='xnor')
mapping = np.zeros([network.Np, ], dtype=int)
mapping[pores] = np.arange(Np, network.Np)
tclone = mapping[network['throat.conns'][ts]]
extend(network=network, throat_conns=tclone)
elif mode == 'isolated':
pass
Ntnew = network.Nt
for item in labels:
network.set_label(label=item, throats=range(Nt, Ntnew))
# Clear adjacency and incidence matrices which will be out of date now
network._am.clear()
network._im.clear()
|
Clones the specified pores and adds them to the network
Parameters
----------
network : Network
The Network object to which the new pores are to be added
pores : array_like
List of pores to clone
labels : str, or list[str]
The labels to apply to the clones, default is 'clone'
mode : str
Controls the connections between parents and clones. Options are:
=========== ==========================================================
mode description
=========== ==========================================================
'parents' Each clone is connected only to its parent.(Default)
'siblings' Clones are only connected to each other in the same
manner as parents were connected.
'isolated' No connections between parents or siblings
=========== ==========================================================
|
clone_pores
|
python
|
PMEAL/OpenPNM
|
openpnm/topotools/_topotools.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/topotools/_topotools.py
|
MIT
|
def merge_networks(network, donor=[]):
r"""
Combine multiple networks into one without making any topological
connections
Parameters
----------
network : Network
The network to which all the other networks should be added.
donor : Network or list of Objects
The network object(s) to add to the given network
See Also
--------
extend
trim
stitch
"""
if isinstance(donor, list):
donors = donor
else:
donors = [donor]
for donor in donors:
network['throat.conns'] = np.vstack((network['throat.conns'],
donor['throat.conns']
+ network.Np))
network['pore.coords'] = np.vstack((network['pore.coords'],
donor['pore.coords']))
p_all = np.ones((np.shape(network['pore.coords'])[0],), dtype=bool)
t_all = np.ones((np.shape(network['throat.conns'])[0],), dtype=bool)
network.update({'pore.all': p_all})
network.update({'throat.all': t_all})
for key in set(network.keys()).union(set(donor.keys())):
if key.split('.')[1] not in ['conns', 'coords', '_id', 'all']:
if key in network.keys():
pop_flag = False
# If key not on donor add it first with dummy values to
# simplify merging later
if key not in donor.keys():
logger.debug('Adding ' + key + ' to donor')
if network[key].dtype == bool: # Deal with labels
donor[key] = False
else: # Deal with numerical data
element = key.split('.', 1)[0]
shape = list(network[key].shape)
N = donor._count(element)
shape[0] = N
donor[key] = np.empty(shape=shape)*np.nan
pop_flag = True
# Then merge it with existing array on network
if len(network[key].shape) == 1:
temp = np.hstack((network[key], donor[key]))
else:
temp = np.vstack((network[key], donor[key]))
network[key] = temp
if pop_flag:
donor.pop(key, None)
else:
# If key not on network add it first
logger.debug('Adding ' + key + ' to network')
if donor[key].dtype == bool:
network[key] = False
else:
data_shape = list(donor[key].shape)
pore_prop = True if key.split(".")[0] == "pore" else False
data_shape[0] = network.Np if pore_prop else network.Nt
network[key] = np.empty(data_shape) * np.nan
# Then append donor values to network
s = np.shape(donor[key])[0]
network[key][-s:] = donor[key]
# Clear adjacency and incidence matrices which will be out of date now
network._am.clear()
network._im.clear()
|
Combine multiple networks into one without making any topological
connections
Parameters
----------
network : Network
The network to which all the other networks should be added.
donor : Network or list of Objects
The network object(s) to add to the given network
See Also
--------
extend
trim
stitch
|
merge_networks
|
python
|
PMEAL/OpenPNM
|
openpnm/topotools/_topotools.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/topotools/_topotools.py
|
MIT
|
def stitch_pores(network, pores1, pores2, mode='gabriel'):
r"""
Stitches together pores in a network with disconnected clusters
Parameters
----------
network : OpenPNM Network
The network to operate upon
pores1 and pores2: array_like
The pore indices of the disconnected clusters to be joined
mode : str
Dictates which tesselation method is used to identify which pores to
stitch together. Options are:
=========== ==========================================================
mode meaning
=========== ==========================================================
'delaunay' Uses the delaunay tesselation method
=========== ==========================================================
Returns
-------
None
The network is operated on 'in-place' so nothing is returned.
"""
raise NotImplementedError()
from openpnm.network import Delaunay
pores1 = network._parse_indices(pores1)
pores2 = network._parse_indices(pores2)
C1 = network.coords[pores1, :]
C2 = network.coords[pores2, :]
crds = np.vstack((C1, C2))
if mode == 'delaunay':
shape = get_shape(network) * dimensionality(network)
net = Delaunay(points=crds, shape=shape)
else:
raise Exception('Unsupported mode')
net.set_label(pores=range(len(pores1)), label='pore.one')
net.set_label(pores=range(len(pores2)), label='pore.two')
Ts = net.find_neighbor_throats(pores=net.pores('one'), mode='xor')
conns = net.conns[Ts]
mapped_conns = np.vstack((pores1[conns[:, 0]],
pores2[conns[:, 1] - len(pores1)])).T
mapped_conns = np.sort(mapped_conns, axis=1)
extend(network=network, conns=mapped_conns, labels='stitched')
|
Stitches together pores in a network with disconnected clusters
Parameters
----------
network : OpenPNM Network
The network to operate upon
pores1 and pores2: array_like
The pore indices of the disconnected clusters to be joined
mode : str
Dictates which tesselation method is used to identify which pores to
stitch together. Options are:
=========== ==========================================================
mode meaning
=========== ==========================================================
'delaunay' Uses the delaunay tesselation method
=========== ==========================================================
Returns
-------
None
The network is operated on 'in-place' so nothing is returned.
|
stitch_pores
|
python
|
PMEAL/OpenPNM
|
openpnm/topotools/_topotools.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/topotools/_topotools.py
|
MIT
|
def connect_pores(network, pores1, pores2, labels=['new_conns']):
r"""
Returns the possible connections between two groups of pores
Parameters
----------
network : Network
The network to which the pores should be added
pores1 : array_like
The first group of pores on the network
pores2 : array_like
The second group of pores on the network
labels : list of strings
The labels to apply to the new throats. The default is ``'new_conns'``.
Notes
-----
The method also works if ``pores1`` and ``pores2`` are list of lists,
in which case it consecutively connects corresponding members of the two
lists in a 1-to-1 fashion. Example: pores1 = [[0, 1], [2, 3]] and
pores2 = [[5], [7, 9]] leads to creation of the following connections:
::
0 --> 5 2 --> 7 3 --> 7
1 --> 5 2 --> 9 3 --> 9
If you want to use the batch functionality, make sure that each element
within ``pores1`` and ``pores2`` are of type list or ndarray.
"""
# Assert that `pores1` and `pores2` are list of lists
try:
len(pores1[0])
except (TypeError, IndexError):
pores1 = [pores1]
try:
len(pores2[0])
except (TypeError, IndexError):
pores2 = [pores2]
if len(pores1) != len(pores2):
raise Exception('Running in batch mode! pores1 and pores2 must be'
+ ' of the same length.')
arr1, arr2 = [], []
for ps1, ps2 in zip(pores1, pores2):
size1 = np.size(ps1)
size2 = np.size(ps2)
arr1.append(np.repeat(ps1, size2))
arr2.append(np.tile(ps2, size1))
conns = np.vstack([np.concatenate(arr1), np.concatenate(arr2)]).T
extend(network=network, throat_conns=conns, labels=labels)
|
Returns the possible connections between two groups of pores
Parameters
----------
network : Network
The network to which the pores should be added
pores1 : array_like
The first group of pores on the network
pores2 : array_like
The second group of pores on the network
labels : list of strings
The labels to apply to the new throats. The default is ``'new_conns'``.
Notes
-----
The method also works if ``pores1`` and ``pores2`` are list of lists,
in which case it consecutively connects corresponding members of the two
lists in a 1-to-1 fashion. Example: pores1 = [[0, 1], [2, 3]] and
pores2 = [[5], [7, 9]] leads to creation of the following connections:
::
0 --> 5 2 --> 7 3 --> 7
1 --> 5 2 --> 9 3 --> 9
If you want to use the batch functionality, make sure that each element
within ``pores1`` and ``pores2`` are of type list or ndarray.
|
connect_pores
|
python
|
PMEAL/OpenPNM
|
openpnm/topotools/_topotools.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/topotools/_topotools.py
|
MIT
|
def merge_pores(network, pores, labels=['merged'], include_neighbors=True):
r"""
Combines a selection of pores into a new single pore located at the
centroid of the selected pores (and optionally their neighbors)
and connected to all of their neighbors.
Parameters
----------
network : Network
pores : array_like
The list of pores which are to be combined into a new single pore
labels : str or list[str]
The labels to apply to the new pore and new throat connections
Notes
-----
(1) The method also works if a list of lists is passed, in which case
it consecutively merges the given selections of pores.
(2) The selection of pores should be chosen carefully, preferrable so that
they all form a continuous cluster. For instance, it is recommended
to use the ``find_nearby_pores`` method to find all pores within a
certain distance of a given pore, and these can then be merged without
causing any abnormal connections.
"""
# Assert that `pores` is list of lists
try:
len(pores[0])
except (TypeError, IndexError):
pores = [pores]
N = len(pores)
NBs, XYZs = [], []
for Ps in pores:
temp = network.find_neighbor_pores(pores=Ps,
mode='union',
flatten=True,
include_input=False)
NBs.append(temp)
if len(Ps) == 2:
XYZs.append(np.mean(network["pore.coords"][Ps], axis=0))
else:
if include_neighbors:
points = np.concatenate((temp, Ps))
else:
points = Ps
XYZs.append(hull_centroid(network["pore.coords"][points]))
extend(network, pore_coords=XYZs, labels=labels)
Pnew = network.Ps[-N::]
# Possible throats between new pores: This only happens when running in
# batch mode, i.e. multiple groups of pores are to be merged. In case
# some of these groups share elements, possible throats between the
# intersecting elements is not captured and must be added manually.
pores_set = [set(items) for items in pores]
NBs_set = [set(items) for items in NBs]
ps1, ps2 = [], []
from itertools import combinations
for i, j in combinations(range(N), 2):
if not NBs_set[i].isdisjoint(pores_set[j]):
ps1.append([network.Ps[-N+i]])
ps2.append([network.Ps[-N+j]])
# Add (possible) connections between the new pores
connect_pores(network, pores1=ps1, pores2=ps2, labels=labels)
# Add connections between the new pores and the rest of the network
connect_pores(network, pores2=np.split(Pnew, N), pores1=NBs, labels=labels)
# Trim merged pores from the network
trim(network=network, pores=np.concatenate(pores))
|
Combines a selection of pores into a new single pore located at the
centroid of the selected pores (and optionally their neighbors)
and connected to all of their neighbors.
Parameters
----------
network : Network
pores : array_like
The list of pores which are to be combined into a new single pore
labels : str or list[str]
The labels to apply to the new pore and new throat connections
Notes
-----
(1) The method also works if a list of lists is passed, in which case
it consecutively merges the given selections of pores.
(2) The selection of pores should be chosen carefully, preferrable so that
they all form a continuous cluster. For instance, it is recommended
to use the ``find_nearby_pores`` method to find all pores within a
certain distance of a given pore, and these can then be merged without
causing any abnormal connections.
|
merge_pores
|
python
|
PMEAL/OpenPNM
|
openpnm/topotools/_topotools.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/topotools/_topotools.py
|
MIT
|
def hull_centroid(points):
r"""
Computes centroid of the convex hull enclosing the given coordinates.
Parameters
----------
points : Np by 3 ndarray
Coordinates (xyz)
Returns
-------
centroid : array
A 3 by 1 Numpy array containing coordinates of the centroid.
"""
dim = [np.unique(points[:, i]).size != 1 for i in range(3)]
hull = ConvexHull(points[:, dim])
centroid = points.mean(axis=0)
centroid[dim] = hull.points[hull.vertices].mean(axis=0)
return centroid
|
Computes centroid of the convex hull enclosing the given coordinates.
Parameters
----------
points : Np by 3 ndarray
Coordinates (xyz)
Returns
-------
centroid : array
A 3 by 1 Numpy array containing coordinates of the centroid.
|
hull_centroid
|
python
|
PMEAL/OpenPNM
|
openpnm/topotools/_topotools.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/topotools/_topotools.py
|
MIT
|
def add_boundary_pores(network, pores, offset=None, move_to=None,
apply_label='boundary'):
r"""
This method uses ``clone_pores`` to clone the input pores, then shifts
them the specified amount and direction, then applies the given label.
Parameters
----------
pores : array_like
List of pores to offset. If no pores are specified, then it
assumes that all surface pores are to be cloned.
offset : 3 x 1 array
The distance in vector form which the cloned boundary pores should
be offset. Either this, or ``move_to`` must be specified.
move_to : 3 x 1 array
The location to move the boundary pores to. A value of ``None``
indicates that no translation should be applied in that axis. For
instance, ``[None, None, 0]`` indicates that the boundary pores should
moved along the z-axis to the specified location. Either this or
``offset`` must be specified.
apply_label : str
This label is applied to the boundary pores. Default is
'boundary'.
"""
# Parse the input pores
Ps = np.array(pores, ndmin=1)
if Ps.dtype is bool:
Ps = network.to_indices(Ps)
if np.size(pores) == 0: # Handle an empty array if given
return np.array([], dtype=np.int64)
# Clone the specifed pores
clone_pores(network=network, pores=Ps)
newPs = network.pores('pore.clone')
del network['pore.clone']
newTs = network.throats('clone')
del network['throat.clone']
if offset is not None: # Offset the cloned pores
network['pore.coords'][newPs] += offset
if move_to is not None: # Move the cloned pores
for i, d in enumerate(move_to):
if d is not None:
temp = network['pore.coords'][newPs]
temp[:, i] = d
network['pore.coords'][newPs] = temp
# Apply labels to boundary pores (trim leading 'pores' if present)
label = apply_label.split('.', 1)[-1]
plabel = 'pore.' + label
tlabel = 'throat.' + label
network[plabel] = False
network[plabel][newPs] = True
network[tlabel] = False
network[tlabel][newTs] = True
|
This method uses ``clone_pores`` to clone the input pores, then shifts
them the specified amount and direction, then applies the given label.
Parameters
----------
pores : array_like
List of pores to offset. If no pores are specified, then it
assumes that all surface pores are to be cloned.
offset : 3 x 1 array
The distance in vector form which the cloned boundary pores should
be offset. Either this, or ``move_to`` must be specified.
move_to : 3 x 1 array
The location to move the boundary pores to. A value of ``None``
indicates that no translation should be applied in that axis. For
instance, ``[None, None, 0]`` indicates that the boundary pores should
moved along the z-axis to the specified location. Either this or
``offset`` must be specified.
apply_label : str
This label is applied to the boundary pores. Default is
'boundary'.
|
add_boundary_pores
|
python
|
PMEAL/OpenPNM
|
openpnm/topotools/_topotools.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/topotools/_topotools.py
|
MIT
|
def iscoplanar(coords):
r"""
Determines if given pores are coplanar with each other
Parameters
----------
coords : array_like
List of pore coords to check for coplanarity. At least 3 pores are
required.
Returns
-------
results : bool
A boolean value of whether given points are coplanar (``True``) or
not (``False``)
"""
coords = np.array(coords, ndmin=1)
if np.shape(coords)[0] < 3:
raise Exception('At least 3 input pores are required')
Px = coords[:, 0]
Py = coords[:, 1]
Pz = coords[:, 2]
# Do easy check first, for common coordinate
if np.shape(np.unique(Px))[0] == 1:
return True
if np.shape(np.unique(Py))[0] == 1:
return True
if np.shape(np.unique(Pz))[0] == 1:
return True
# Perform rigorous check using vector algebra
# Grab first basis vector from list of coords
n1 = np.array((Px[1] - Px[0], Py[1] - Py[0], Pz[1] - Pz[0])).T
n = np.array([0.0, 0.0, 0.0])
i = 1
while n.sum() == 0:
if i >= (np.size(Px) - 1):
logger.warning('No valid basis vectors found')
return False
# Chose a secon basis vector
n2 = np.array((Px[i+1] - Px[i], Py[i+1] - Py[i], Pz[i+1] - Pz[i])).T
# Find their cross product
n = np.cross(n1, n2)
i += 1
# Create vectors between all other pairs of points
r = np.array((Px[1:-1] - Px[0], Py[1:-1] - Py[0], Pz[1:-1] - Pz[0]))
# Ensure they all lie on the same plane
n_dot = np.dot(n, r)
return bool(np.sum(np.absolute(n_dot)) == 0)
|
Determines if given pores are coplanar with each other
Parameters
----------
coords : array_like
List of pore coords to check for coplanarity. At least 3 pores are
required.
Returns
-------
results : bool
A boolean value of whether given points are coplanar (``True``) or
not (``False``)
|
iscoplanar
|
python
|
PMEAL/OpenPNM
|
openpnm/topotools/_topotools.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/topotools/_topotools.py
|
MIT
|
def is_fully_connected(network, pores_BC=None):
r"""
Checks whether network is fully connected, i.e. not clustered.
Parameters
----------
network : Network
The network whose connectivity to check.
pores_BC : array_like (optional)
The pore indices of boundary conditions (inlets/outlets).
Returns
-------
bool
If ``pores_BC`` is not specified, then returns ``True`` only if
the entire network is connected to the same cluster. If
``pores_BC`` is given, then returns ``True`` only if all clusters
are connected to the given boundary condition pores.
"""
am = network.get_adjacency_matrix(fmt='lil').copy()
temp = csgraph.connected_components(am, directed=False)[1]
is_connected = np.unique(temp).size == 1
# Ensure all clusters are part of pores, if given
if not is_connected and pores_BC is not None:
am.resize(network.Np + 1, network.Np + 1)
pores_BC = network._parse_indices(pores_BC)
am.rows[-1] = pores_BC.tolist()
am.data[-1] = np.arange(network.Nt, network.Nt + len(pores_BC)).tolist()
temp = csgraph.connected_components(am, directed=False)[1]
is_connected = np.unique(temp).size == 1
return is_connected
|
Checks whether network is fully connected, i.e. not clustered.
Parameters
----------
network : Network
The network whose connectivity to check.
pores_BC : array_like (optional)
The pore indices of boundary conditions (inlets/outlets).
Returns
-------
bool
If ``pores_BC`` is not specified, then returns ``True`` only if
the entire network is connected to the same cluster. If
``pores_BC`` is given, then returns ``True`` only if all clusters
are connected to the given boundary condition pores.
|
is_fully_connected
|
python
|
PMEAL/OpenPNM
|
openpnm/topotools/_topotools.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/topotools/_topotools.py
|
MIT
|
def get_domain_area(network, inlets=None, outlets=None):
r"""
Determine the cross sectional area relative to the inlets/outlets.
Parameters
----------
network : Network
The network object containing the pore coordinates
inlets : array_like
The pore indices of the inlets.
outlets : array_Like
The pore indices of the outlets.
Returns
-------
area : scalar
The cross sectional area relative to the inlets/outlets.
"""
logger.warning('Attempting to estimate inlet area...will be low')
if dimensionality(network).sum() != 3:
raise Exception('The network is not 3D, specify area manually')
inlets = network.coords[inlets]
outlets = network.coords[outlets]
if not iscoplanar(inlets):
logger.error('Detected inlet pores are not coplanar')
if not iscoplanar(outlets):
logger.error('Detected outlet pores are not coplanar')
Nin = np.ptp(inlets, axis=0) > 0
if Nin.all():
logger.warning('Detected inlets are not oriented along a principle axis')
Nout = np.ptp(outlets, axis=0) > 0
if Nout.all():
logger.warning('Detected outlets are not oriented along a principle axis')
hull_in = ConvexHull(points=inlets[:, Nin])
hull_out = ConvexHull(points=outlets[:, Nout])
if hull_in.volume != hull_out.volume:
logger.error('Inlet and outlet faces are different area')
area = hull_in.volume # In 2D: volume=area, area=perimeter
return area
|
Determine the cross sectional area relative to the inlets/outlets.
Parameters
----------
network : Network
The network object containing the pore coordinates
inlets : array_like
The pore indices of the inlets.
outlets : array_Like
The pore indices of the outlets.
Returns
-------
area : scalar
The cross sectional area relative to the inlets/outlets.
|
get_domain_area
|
python
|
PMEAL/OpenPNM
|
openpnm/topotools/_topotools.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/topotools/_topotools.py
|
MIT
|
def get_domain_length(network, inlets=None, outlets=None):
r"""
Determine the domain length relative to the inlets/outlets.
Parameters
----------
network : Network
The network object containing the pore coordinates
inlets : array_like
The pore indices of the inlets.
outlets : array_Like
The pore indices of the outlets.
Returns
-------
area : scalar
The domain length relative to the inlets/outlets.
"""
msg = ('Attempting to estimate domain length...could be low if'
' boundary pores were not added')
logger.warning(msg)
inlets = network.coords[inlets]
outlets = network.coords[outlets]
if not iscoplanar(inlets):
logger.error('Detected inlet pores are not coplanar')
if not iscoplanar(outlets):
logger.error('Detected inlet pores are not coplanar')
tree = cKDTree(data=inlets)
Ls = np.unique(np.float64(tree.query(x=outlets)[0]))
if not np.allclose(Ls, Ls[0]):
logger.error('A unique value of length could not be found')
length = Ls[0]
return length
|
Determine the domain length relative to the inlets/outlets.
Parameters
----------
network : Network
The network object containing the pore coordinates
inlets : array_like
The pore indices of the inlets.
outlets : array_Like
The pore indices of the outlets.
Returns
-------
area : scalar
The domain length relative to the inlets/outlets.
|
get_domain_length
|
python
|
PMEAL/OpenPNM
|
openpnm/topotools/_topotools.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/topotools/_topotools.py
|
MIT
|
def reduce_coordination(network, z):
r"""
Deletes throats on network to match specified average coordination number
Parameters
----------
target : Network
The network whose throats are to be trimmed
z : scalar
The desired average coordination number. It is not possible to specify
the distribution of the coordination, only the mean value.
Returns
-------
trim : ndarray
A boolean array with ``True`` values indicating which pores to trim
(using ``op.topotools.trim``) to obtain the desired average
coordination number.
Notes
-----
This method first finds the minimum spanning tree of the network using
random weights on each throat, then assures that these throats are *not*
deleted, in order to maintain network connectivity. The list of throats
to trim is generated randomly from the throats *not* on the spanning tree.
"""
# Find minimum spanning tree using random weights
am = network.create_adjacency_matrix(weights=np.random.rand(network.Nt),
triu=False)
mst = csgraph.minimum_spanning_tree(am, overwrite=True)
mst = mst.tocoo()
# Label throats on spanning tree to avoid deleting them
Ts = network.find_connecting_throat(mst.row, mst.col)
Ts = np.hstack(Ts)
network['throat.mst'] = False
network['throat.mst'][Ts] = True
# Trim throats not on the spanning tree to acheive desired coordination
Ts = np.random.permutation(network.throats('mst', mode='nor'))
del network['throat.mst']
Ts = Ts[:int(network.Nt - network.Np*(z/2))]
Ts = network.to_mask(throats=Ts)
return Ts
|
Deletes throats on network to match specified average coordination number
Parameters
----------
target : Network
The network whose throats are to be trimmed
z : scalar
The desired average coordination number. It is not possible to specify
the distribution of the coordination, only the mean value.
Returns
-------
trim : ndarray
A boolean array with ``True`` values indicating which pores to trim
(using ``op.topotools.trim``) to obtain the desired average
coordination number.
Notes
-----
This method first finds the minimum spanning tree of the network using
random weights on each throat, then assures that these throats are *not*
deleted, in order to maintain network connectivity. The list of throats
to trim is generated randomly from the throats *not* on the spanning tree.
|
reduce_coordination
|
python
|
PMEAL/OpenPNM
|
openpnm/topotools/_topotools.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/topotools/_topotools.py
|
MIT
|
def add_reservoir_pore(cls, network, pores, offset=0.1):
r"""
Adds a single pore connected to all ``pores`` to act as a reservoir
This function is mostly needed to make network compatible with the
Statoil file format, which requires reservoir pores on the inlet and
outlet faces.
Parameters
----------
network : Network
The network to which the reservoir pore should be added
pores : array_like
The pores to which the reservoir pore should be connected to
offset : scalar
Controls the distance which the reservoir is offset from the given
``pores``. The total displacement is found from the network
dimension normal to given ``pores``, multiplied by ``offset``.
Returns
-------
project : list
An OpenPNM project object with a new geometry object added to
represent the newly added pore and throats.
"""
import openpnm.models.geometry as mods
# Check if a label was given and fetch actual indices
if isinstance(pores, str):
# Convert 'face' into 'pore.face' if necessary
if not pores.startswith('pore.'):
pores = 'pore.' + pores
pores = network.pores(pores)
# Find coordinates of pores on given face
coords = network['pore.coords'][pores]
# Normalize the coordinates based on full network size
c_norm = coords/network['pore.coords'].max(axis=0)
# Identify axis of face by looking for dim with smallest delta
diffs = np.amax(c_norm - np.average(c_norm, axis=0), axis=0)
ax = np.where(diffs == diffs.min())[0][0]
# Add new pore at center of domain
new_coord = network['pore.coords'].mean(axis=0)
domain_half_length = np.ptp(network['pore.coords'][:, ax])/2
if coords[:, ax].mean() < network['pore.coords'][:, ax].mean():
new_coord[ax] = new_coord[ax] - domain_half_length*(1 + offset)
if coords[:, ax].mean() > network['pore.coords'][:, ax].mean():
new_coord[ax] = new_coord[ax] + domain_half_length*(1 + offset)
# Ps = np.arange(network.Np, network.Np + 1)
extend(network=network, coords=[new_coord], labels=['reservoir'])
conns = [[P, network.Np-1] for P in pores]
# Ts = np.arange(network.Nt, network.Nt + len(conns))
extend(network=network, conns=conns, labels=['reservoir'])
# Compute the geometrical properties of the reservoir pore and throats
# Confirm if network has any geometry props on it
props = {'throat.length', 'pore.diameter', 'throat.volume'}
if len(set(network.keys()).intersection(props)) > 0:
raise Exception('Geometrical properties should be moved to a '
+ 'geometry object first')
# or just do this?: geo = Imported(network=network)
network.add_model(propname='pore.diameter',
model=mods.geometry.pore_size.largest_sphere)
network.add_model(propname='throat.diameter_temp',
model=mods.geometry.throat_size.from_neighbor_pores,
mode='min')
network.add_model(propname='throat.diameter',
model=mods.misc.scaled,
prop='throat.diameter_temp', factor=0.5)
network.add_model(propname='throat.volume',
model=mods.geometry.throat_volume.cylinder)
return network.project
|
Adds a single pore connected to all ``pores`` to act as a reservoir
This function is mostly needed to make network compatible with the
Statoil file format, which requires reservoir pores on the inlet and
outlet faces.
Parameters
----------
network : Network
The network to which the reservoir pore should be added
pores : array_like
The pores to which the reservoir pore should be connected to
offset : scalar
Controls the distance which the reservoir is offset from the given
``pores``. The total displacement is found from the network
dimension normal to given ``pores``, multiplied by ``offset``.
Returns
-------
project : list
An OpenPNM project object with a new geometry object added to
represent the newly added pore and throats.
|
add_reservoir_pore
|
python
|
PMEAL/OpenPNM
|
openpnm/topotools/_topotools.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/topotools/_topotools.py
|
MIT
|
def check_data_health(obj):
r"""
Checks the health of pore and throat data arrays.
Parameters
----------
obj : Base
A handle of the object to be checked
Returns
-------
health : dict
Returns a HealthDict object which is a basic dictionary with an
added ``health`` attribute that is ``True`` is all entries in the
dict are deemed healthy (empty lists), or ``False`` otherwise.
"""
health = HealthDict()
for item in obj.props():
health[item] = []
if obj[item].dtype == 'O':
health[item] = 'No checks on object'
elif np.sum(np.isnan(obj[item])) > 0:
health[item] = 'Has NaNs'
elif np.shape(obj[item])[0] != obj._count(item.split('.', 1)[0]):
health[item] = 'Wrong Length'
return health
|
Checks the health of pore and throat data arrays.
Parameters
----------
obj : Base
A handle of the object to be checked
Returns
-------
health : dict
Returns a HealthDict object which is a basic dictionary with an
added ``health`` attribute that is ``True`` is all entries in the
dict are deemed healthy (empty lists), or ``False`` otherwise.
|
check_data_health
|
python
|
PMEAL/OpenPNM
|
openpnm/utils/_health.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/utils/_health.py
|
MIT
|
def check_network_health(network):
r"""
This method checks the topological health of the network
The following aspects are checked for:
(1) Isolated pores
(2) Disconnected clusters of pores
(3) Duplicate throats
(4) Headless throats
(5) Bidirectional throats
Returns
-------
health : dict
A dictionary containing the offending pores or throat numbers
under each named key.
Notes
-----
It also returns a list of which pores and throats should be trimmed
from the network to restore health. This list is a suggestion only,
and is based on keeping the largest cluster and trimming the others.
- Does not yet check for duplicate pores
- Does not yet suggest which throats to remove
- This is just a 'check' and does not 'fix' the problems it finds
"""
import openpnm.models.network as mods
health = HealthDict()
# Check for headless throats
headless = mods.headless_throats(network)
health['headless_throats'] = np.where(headless)[0].tolist()
# Check for throats that loop back onto the same pore
looped = mods.looped_throats(network)
health['looped_throats'] = np.where(looped)[0].tolist()
# Check for individual isolated pores
isolated = mods.isolated_pores(network)
health['isolated_pores'] = np.where(isolated)[0].tolist()
# Check for separated clusters of pores
size = mods.cluster_size(network)
mx = np.max(size)
health['disconnected_pores'] = np.where(size < mx)[0].tolist()
# Check for duplicate throats
dupes = mods.duplicate_throats(network)
health['duplicate_throats'] = np.where(dupes)[0].tolist()
# Check for bidirectional throats
bidir = mods.bidirectional_throats(network)
health['bidirectional_throats'] = np.where(bidir)[0].tolist()
return health
|
This method checks the topological health of the network
The following aspects are checked for:
(1) Isolated pores
(2) Disconnected clusters of pores
(3) Duplicate throats
(4) Headless throats
(5) Bidirectional throats
Returns
-------
health : dict
A dictionary containing the offending pores or throat numbers
under each named key.
Notes
-----
It also returns a list of which pores and throats should be trimmed
from the network to restore health. This list is a suggestion only,
and is based on keeping the largest cluster and trimming the others.
- Does not yet check for duplicate pores
- Does not yet suggest which throats to remove
- This is just a 'check' and does not 'fix' the problems it finds
|
check_network_health
|
python
|
PMEAL/OpenPNM
|
openpnm/utils/_health.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/utils/_health.py
|
MIT
|
def flat_list(input_list):
r"""
Given a list of nested lists of arbitrary depth, returns a single
level or 'flat' list.
"""
def _flatten(l):
for el in l:
if isinstance(el, Iterable) and not isinstance(el, (str, bytes)):
yield from _flatten(el)
else:
yield el
return list(_flatten(input_list))
|
Given a list of nested lists of arbitrary depth, returns a single
level or 'flat' list.
|
flat_list
|
python
|
PMEAL/OpenPNM
|
openpnm/utils/_misc.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/utils/_misc.py
|
MIT
|
def sanitize_dict(input_dict):
r"""
Given a nested dictionary, ensures that all nested dicts are normal
Python dicts. This is necessary for pickling, or just converting
an 'auto-vivifying' dict to something that acts normal.
"""
plain_dict = dict()
for key in input_dict.keys():
value = input_dict[key]
if hasattr(value, "keys"):
plain_dict[key] = sanitize_dict(value)
else:
plain_dict[key] = value
return plain_dict
|
Given a nested dictionary, ensures that all nested dicts are normal
Python dicts. This is necessary for pickling, or just converting
an 'auto-vivifying' dict to something that acts normal.
|
sanitize_dict
|
python
|
PMEAL/OpenPNM
|
openpnm/utils/_misc.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/utils/_misc.py
|
MIT
|
def methods_to_table(obj):
r"""
Converts a methods on an object to a ReST compatible table
Parameters
----------
obj : Base
Any object that has a methods
params : bool
Indicates whether or not to include a list of parameter
values in the table. Set to False for just a list of models, and
True for a more verbose table with all parameter values.
"""
parent = obj.__class__.__mro__[1]
temp = inspect.getmembers(parent, predicate=inspect.isroutine)
parent_funcs = [i[0] for i in temp if not i[0].startswith("_")]
temp = inspect.getmembers(obj.__class__, predicate=inspect.isroutine)
obj_funcs = [i[0] for i in temp if not i[0].startswith("_")]
funcs = set(obj_funcs).difference(set(parent_funcs))
row = "+" + "-" * 22 + "+" + "-" * 49 + "+"
fmt = "{0:1s} {1:20s} {2:1s} {3:47s} {4:1s}"
lines = []
lines.append(row)
lines.append(fmt.format("|", "Method", "|", "Description", "|"))
lines.append(row.replace("-", "="))
for i, item in enumerate(funcs):
try:
s = getattr(obj, item).__doc__.strip()
end = s.find("\n")
if end > 47:
s = s[:44] + "..."
lines.append(fmt.format("|", item, "|", s[:end], "|"))
lines.append(row)
except AttributeError:
pass
return "\n".join(lines)
|
Converts a methods on an object to a ReST compatible table
Parameters
----------
obj : Base
Any object that has a methods
params : bool
Indicates whether or not to include a list of parameter
values in the table. Set to False for just a list of models, and
True for a more verbose table with all parameter values.
|
methods_to_table
|
python
|
PMEAL/OpenPNM
|
openpnm/utils/_misc.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/utils/_misc.py
|
MIT
|
def models_to_table(obj, params=True):
r"""
Converts a all the models on an object to a ReST compatible table
Parameters
----------
obj : Base
Any object that has a ``models`` attribute
params : bool
Indicates whether or not to include a list of parameter
values in the table. Set to False for just a list of models, and
True for a more verbose table with all parameter values.
"""
if not hasattr(obj, "models"):
raise Exception("Received object does not have any models")
row = "+" + "-" * 4 + "+" + "-" * 22 + "+" + "-" * 18 + "+" + "-" * 26 + "+"
fmt = "{0:1s} {1:2s} {2:1s} {3:20s} {4:1s} {5:16s} {6:1s} {7:24s} {8:1s}"
lines = []
lines.append(row)
lines.append(
fmt.format("|", "#", "|", "Property Name", "|", "Parameter", "|", "Value", "|")
)
lines.append(row.replace("-", "="))
for i, item in enumerate(obj.models.keys()):
prop = item
if len(prop) > 20:
prop = item[:17] + "..."
temp = obj.models[item].copy()
model = str(temp.pop("model")).split(" ")[1]
lines.append(
fmt.format("|", str(i + 1), "|", prop, "|", "model:", "|", model, "|")
)
lines.append(row)
if params:
for param in temp.keys():
p1 = param
if len(p1) > 16:
p1 = p1[:13] + "..."
p2 = str(temp[param])
if len(p2) > 24:
p2 = p2[:21] + "..."
lines.append(fmt.format("|", "", "|", "", "|", p1, "|", p2, "|"))
lines.append(row)
return "\n".join(lines)
|
Converts a all the models on an object to a ReST compatible table
Parameters
----------
obj : Base
Any object that has a ``models`` attribute
params : bool
Indicates whether or not to include a list of parameter
values in the table. Set to False for just a list of models, and
True for a more verbose table with all parameter values.
|
models_to_table
|
python
|
PMEAL/OpenPNM
|
openpnm/utils/_misc.py
|
https://github.com/PMEAL/OpenPNM/blob/master/openpnm/utils/_misc.py
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.