repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
CalebBell/fluids | fluids/core.py | Peclet_heat | def Peclet_heat(V, L, rho=None, Cp=None, k=None, alpha=None):
r'''Calculates heat transfer Peclet number or `Pe` for a specified velocity
`V`, characteristic length `L`, and specified properties for the given
fluid.
.. math::
Pe = \frac{VL\rho C_p}{k} = \frac{LV}{\alpha}
Inputs either of any of the following sets:
* V, L, density `rho`, heat capacity `Cp`, and thermal conductivity `k`
* V, L, and thermal diffusivity `alpha`
Parameters
----------
V : float
Velocity [m/s]
L : float
Characteristic length [m]
rho : float, optional
Density, [kg/m^3]
Cp : float, optional
Heat capacity, [J/kg/K]
k : float, optional
Thermal conductivity, [W/m/K]
alpha : float, optional
Thermal diffusivity, [m^2/s]
Returns
-------
Pe : float
Peclet number (heat) []
Notes
-----
.. math::
Pe = \frac{\text{Bulk heat transfer}}{\text{Conduction heat transfer}}
An error is raised if none of the required input sets are provided.
Examples
--------
>>> Peclet_heat(1.5, 2, 1000., 4000., 0.6)
20000000.0
>>> Peclet_heat(1.5, 2, alpha=1E-7)
30000000.0
References
----------
.. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,
Eighth Edition. McGraw-Hill Professional, 2007.
.. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and
Applications. Boston: McGraw Hill Higher Education, 2006.
'''
if rho and Cp and k:
alpha = k/(rho*Cp)
elif not alpha:
raise Exception('Either heat capacity and thermal conductivity and\
density, or thermal diffusivity is needed')
return V*L/alpha | python | def Peclet_heat(V, L, rho=None, Cp=None, k=None, alpha=None):
r'''Calculates heat transfer Peclet number or `Pe` for a specified velocity
`V`, characteristic length `L`, and specified properties for the given
fluid.
.. math::
Pe = \frac{VL\rho C_p}{k} = \frac{LV}{\alpha}
Inputs either of any of the following sets:
* V, L, density `rho`, heat capacity `Cp`, and thermal conductivity `k`
* V, L, and thermal diffusivity `alpha`
Parameters
----------
V : float
Velocity [m/s]
L : float
Characteristic length [m]
rho : float, optional
Density, [kg/m^3]
Cp : float, optional
Heat capacity, [J/kg/K]
k : float, optional
Thermal conductivity, [W/m/K]
alpha : float, optional
Thermal diffusivity, [m^2/s]
Returns
-------
Pe : float
Peclet number (heat) []
Notes
-----
.. math::
Pe = \frac{\text{Bulk heat transfer}}{\text{Conduction heat transfer}}
An error is raised if none of the required input sets are provided.
Examples
--------
>>> Peclet_heat(1.5, 2, 1000., 4000., 0.6)
20000000.0
>>> Peclet_heat(1.5, 2, alpha=1E-7)
30000000.0
References
----------
.. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,
Eighth Edition. McGraw-Hill Professional, 2007.
.. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and
Applications. Boston: McGraw Hill Higher Education, 2006.
'''
if rho and Cp and k:
alpha = k/(rho*Cp)
elif not alpha:
raise Exception('Either heat capacity and thermal conductivity and\
density, or thermal diffusivity is needed')
return V*L/alpha | [
"def",
"Peclet_heat",
"(",
"V",
",",
"L",
",",
"rho",
"=",
"None",
",",
"Cp",
"=",
"None",
",",
"k",
"=",
"None",
",",
"alpha",
"=",
"None",
")",
":",
"if",
"rho",
"and",
"Cp",
"and",
"k",
":",
"alpha",
"=",
"k",
"/",
"(",
"rho",
"*",
"Cp",
")",
"elif",
"not",
"alpha",
":",
"raise",
"Exception",
"(",
"'Either heat capacity and thermal conductivity and\\\n density, or thermal diffusivity is needed'",
")",
"return",
"V",
"*",
"L",
"/",
"alpha"
]
| r'''Calculates heat transfer Peclet number or `Pe` for a specified velocity
`V`, characteristic length `L`, and specified properties for the given
fluid.
.. math::
Pe = \frac{VL\rho C_p}{k} = \frac{LV}{\alpha}
Inputs either of any of the following sets:
* V, L, density `rho`, heat capacity `Cp`, and thermal conductivity `k`
* V, L, and thermal diffusivity `alpha`
Parameters
----------
V : float
Velocity [m/s]
L : float
Characteristic length [m]
rho : float, optional
Density, [kg/m^3]
Cp : float, optional
Heat capacity, [J/kg/K]
k : float, optional
Thermal conductivity, [W/m/K]
alpha : float, optional
Thermal diffusivity, [m^2/s]
Returns
-------
Pe : float
Peclet number (heat) []
Notes
-----
.. math::
Pe = \frac{\text{Bulk heat transfer}}{\text{Conduction heat transfer}}
An error is raised if none of the required input sets are provided.
Examples
--------
>>> Peclet_heat(1.5, 2, 1000., 4000., 0.6)
20000000.0
>>> Peclet_heat(1.5, 2, alpha=1E-7)
30000000.0
References
----------
.. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,
Eighth Edition. McGraw-Hill Professional, 2007.
.. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and
Applications. Boston: McGraw Hill Higher Education, 2006. | [
"r",
"Calculates",
"heat",
"transfer",
"Peclet",
"number",
"or",
"Pe",
"for",
"a",
"specified",
"velocity",
"V",
"characteristic",
"length",
"L",
"and",
"specified",
"properties",
"for",
"the",
"given",
"fluid",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/core.py#L187-L246 | train |
CalebBell/fluids | fluids/core.py | Fourier_heat | def Fourier_heat(t, L, rho=None, Cp=None, k=None, alpha=None):
r'''Calculates heat transfer Fourier number or `Fo` for a specified time
`t`, characteristic length `L`, and specified properties for the given
fluid.
.. math::
Fo = \frac{k t}{C_p \rho L^2} = \frac{\alpha t}{L^2}
Inputs either of any of the following sets:
* t, L, density `rho`, heat capacity `Cp`, and thermal conductivity `k`
* t, L, and thermal diffusivity `alpha`
Parameters
----------
t : float
time [s]
L : float
Characteristic length [m]
rho : float, optional
Density, [kg/m^3]
Cp : float, optional
Heat capacity, [J/kg/K]
k : float, optional
Thermal conductivity, [W/m/K]
alpha : float, optional
Thermal diffusivity, [m^2/s]
Returns
-------
Fo : float
Fourier number (heat) []
Notes
-----
.. math::
Fo = \frac{\text{Heat conduction rate}}
{\text{Rate of thermal energy storage in a solid}}
An error is raised if none of the required input sets are provided.
Examples
--------
>>> Fourier_heat(t=1.5, L=2, rho=1000., Cp=4000., k=0.6)
5.625e-08
>>> Fourier_heat(1.5, 2, alpha=1E-7)
3.75e-08
References
----------
.. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,
Eighth Edition. McGraw-Hill Professional, 2007.
.. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and
Applications. Boston: McGraw Hill Higher Education, 2006.
'''
if rho and Cp and k:
alpha = k/(rho*Cp)
elif not alpha:
raise Exception('Either heat capacity and thermal conductivity and \
density, or thermal diffusivity is needed')
return t*alpha/L**2 | python | def Fourier_heat(t, L, rho=None, Cp=None, k=None, alpha=None):
r'''Calculates heat transfer Fourier number or `Fo` for a specified time
`t`, characteristic length `L`, and specified properties for the given
fluid.
.. math::
Fo = \frac{k t}{C_p \rho L^2} = \frac{\alpha t}{L^2}
Inputs either of any of the following sets:
* t, L, density `rho`, heat capacity `Cp`, and thermal conductivity `k`
* t, L, and thermal diffusivity `alpha`
Parameters
----------
t : float
time [s]
L : float
Characteristic length [m]
rho : float, optional
Density, [kg/m^3]
Cp : float, optional
Heat capacity, [J/kg/K]
k : float, optional
Thermal conductivity, [W/m/K]
alpha : float, optional
Thermal diffusivity, [m^2/s]
Returns
-------
Fo : float
Fourier number (heat) []
Notes
-----
.. math::
Fo = \frac{\text{Heat conduction rate}}
{\text{Rate of thermal energy storage in a solid}}
An error is raised if none of the required input sets are provided.
Examples
--------
>>> Fourier_heat(t=1.5, L=2, rho=1000., Cp=4000., k=0.6)
5.625e-08
>>> Fourier_heat(1.5, 2, alpha=1E-7)
3.75e-08
References
----------
.. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,
Eighth Edition. McGraw-Hill Professional, 2007.
.. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and
Applications. Boston: McGraw Hill Higher Education, 2006.
'''
if rho and Cp and k:
alpha = k/(rho*Cp)
elif not alpha:
raise Exception('Either heat capacity and thermal conductivity and \
density, or thermal diffusivity is needed')
return t*alpha/L**2 | [
"def",
"Fourier_heat",
"(",
"t",
",",
"L",
",",
"rho",
"=",
"None",
",",
"Cp",
"=",
"None",
",",
"k",
"=",
"None",
",",
"alpha",
"=",
"None",
")",
":",
"if",
"rho",
"and",
"Cp",
"and",
"k",
":",
"alpha",
"=",
"k",
"/",
"(",
"rho",
"*",
"Cp",
")",
"elif",
"not",
"alpha",
":",
"raise",
"Exception",
"(",
"'Either heat capacity and thermal conductivity and \\\ndensity, or thermal diffusivity is needed'",
")",
"return",
"t",
"*",
"alpha",
"/",
"L",
"**",
"2"
]
| r'''Calculates heat transfer Fourier number or `Fo` for a specified time
`t`, characteristic length `L`, and specified properties for the given
fluid.
.. math::
Fo = \frac{k t}{C_p \rho L^2} = \frac{\alpha t}{L^2}
Inputs either of any of the following sets:
* t, L, density `rho`, heat capacity `Cp`, and thermal conductivity `k`
* t, L, and thermal diffusivity `alpha`
Parameters
----------
t : float
time [s]
L : float
Characteristic length [m]
rho : float, optional
Density, [kg/m^3]
Cp : float, optional
Heat capacity, [J/kg/K]
k : float, optional
Thermal conductivity, [W/m/K]
alpha : float, optional
Thermal diffusivity, [m^2/s]
Returns
-------
Fo : float
Fourier number (heat) []
Notes
-----
.. math::
Fo = \frac{\text{Heat conduction rate}}
{\text{Rate of thermal energy storage in a solid}}
An error is raised if none of the required input sets are provided.
Examples
--------
>>> Fourier_heat(t=1.5, L=2, rho=1000., Cp=4000., k=0.6)
5.625e-08
>>> Fourier_heat(1.5, 2, alpha=1E-7)
3.75e-08
References
----------
.. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,
Eighth Edition. McGraw-Hill Professional, 2007.
.. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and
Applications. Boston: McGraw Hill Higher Education, 2006. | [
"r",
"Calculates",
"heat",
"transfer",
"Fourier",
"number",
"or",
"Fo",
"for",
"a",
"specified",
"time",
"t",
"characteristic",
"length",
"L",
"and",
"specified",
"properties",
"for",
"the",
"given",
"fluid",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/core.py#L288-L348 | train |
CalebBell/fluids | fluids/core.py | Graetz_heat | def Graetz_heat(V, D, x, rho=None, Cp=None, k=None, alpha=None):
r'''Calculates Graetz number or `Gz` for a specified velocity
`V`, diameter `D`, axial distance `x`, and specified properties for the
given fluid.
.. math::
Gz = \frac{VD^2\cdot C_p \rho}{x\cdot k} = \frac{VD^2}{x \alpha}
Inputs either of any of the following sets:
* V, D, x, density `rho`, heat capacity `Cp`, and thermal conductivity `k`
* V, D, x, and thermal diffusivity `alpha`
Parameters
----------
V : float
Velocity, [m/s]
D : float
Diameter [m]
x : float
Axial distance [m]
rho : float, optional
Density, [kg/m^3]
Cp : float, optional
Heat capacity, [J/kg/K]
k : float, optional
Thermal conductivity, [W/m/K]
alpha : float, optional
Thermal diffusivity, [m^2/s]
Returns
-------
Gz : float
Graetz number []
Notes
-----
.. math::
Gz = \frac{\text{Time for radial heat diffusion in a fluid by conduction}}
{\text{Time taken by fluid to reach distance x}}
.. math::
Gz = \frac{D}{x}RePr
An error is raised if none of the required input sets are provided.
Examples
--------
>>> Graetz_heat(1.5, 0.25, 5, 800., 2200., 0.6)
55000.0
>>> Graetz_heat(1.5, 0.25, 5, alpha=1E-7)
187500.0
References
----------
.. [1] Bergman, Theodore L., Adrienne S. Lavine, Frank P. Incropera, and
David P. DeWitt. Introduction to Heat Transfer. 6E. Hoboken, NJ:
Wiley, 2011.
'''
if rho and Cp and k:
alpha = k/(rho*Cp)
elif not alpha:
raise Exception('Either heat capacity and thermal conductivity and\
density, or thermal diffusivity is needed')
return V*D**2/(x*alpha) | python | def Graetz_heat(V, D, x, rho=None, Cp=None, k=None, alpha=None):
r'''Calculates Graetz number or `Gz` for a specified velocity
`V`, diameter `D`, axial distance `x`, and specified properties for the
given fluid.
.. math::
Gz = \frac{VD^2\cdot C_p \rho}{x\cdot k} = \frac{VD^2}{x \alpha}
Inputs either of any of the following sets:
* V, D, x, density `rho`, heat capacity `Cp`, and thermal conductivity `k`
* V, D, x, and thermal diffusivity `alpha`
Parameters
----------
V : float
Velocity, [m/s]
D : float
Diameter [m]
x : float
Axial distance [m]
rho : float, optional
Density, [kg/m^3]
Cp : float, optional
Heat capacity, [J/kg/K]
k : float, optional
Thermal conductivity, [W/m/K]
alpha : float, optional
Thermal diffusivity, [m^2/s]
Returns
-------
Gz : float
Graetz number []
Notes
-----
.. math::
Gz = \frac{\text{Time for radial heat diffusion in a fluid by conduction}}
{\text{Time taken by fluid to reach distance x}}
.. math::
Gz = \frac{D}{x}RePr
An error is raised if none of the required input sets are provided.
Examples
--------
>>> Graetz_heat(1.5, 0.25, 5, 800., 2200., 0.6)
55000.0
>>> Graetz_heat(1.5, 0.25, 5, alpha=1E-7)
187500.0
References
----------
.. [1] Bergman, Theodore L., Adrienne S. Lavine, Frank P. Incropera, and
David P. DeWitt. Introduction to Heat Transfer. 6E. Hoboken, NJ:
Wiley, 2011.
'''
if rho and Cp and k:
alpha = k/(rho*Cp)
elif not alpha:
raise Exception('Either heat capacity and thermal conductivity and\
density, or thermal diffusivity is needed')
return V*D**2/(x*alpha) | [
"def",
"Graetz_heat",
"(",
"V",
",",
"D",
",",
"x",
",",
"rho",
"=",
"None",
",",
"Cp",
"=",
"None",
",",
"k",
"=",
"None",
",",
"alpha",
"=",
"None",
")",
":",
"if",
"rho",
"and",
"Cp",
"and",
"k",
":",
"alpha",
"=",
"k",
"/",
"(",
"rho",
"*",
"Cp",
")",
"elif",
"not",
"alpha",
":",
"raise",
"Exception",
"(",
"'Either heat capacity and thermal conductivity and\\\n density, or thermal diffusivity is needed'",
")",
"return",
"V",
"*",
"D",
"**",
"2",
"/",
"(",
"x",
"*",
"alpha",
")"
]
| r'''Calculates Graetz number or `Gz` for a specified velocity
`V`, diameter `D`, axial distance `x`, and specified properties for the
given fluid.
.. math::
Gz = \frac{VD^2\cdot C_p \rho}{x\cdot k} = \frac{VD^2}{x \alpha}
Inputs either of any of the following sets:
* V, D, x, density `rho`, heat capacity `Cp`, and thermal conductivity `k`
* V, D, x, and thermal diffusivity `alpha`
Parameters
----------
V : float
Velocity, [m/s]
D : float
Diameter [m]
x : float
Axial distance [m]
rho : float, optional
Density, [kg/m^3]
Cp : float, optional
Heat capacity, [J/kg/K]
k : float, optional
Thermal conductivity, [W/m/K]
alpha : float, optional
Thermal diffusivity, [m^2/s]
Returns
-------
Gz : float
Graetz number []
Notes
-----
.. math::
Gz = \frac{\text{Time for radial heat diffusion in a fluid by conduction}}
{\text{Time taken by fluid to reach distance x}}
.. math::
Gz = \frac{D}{x}RePr
An error is raised if none of the required input sets are provided.
Examples
--------
>>> Graetz_heat(1.5, 0.25, 5, 800., 2200., 0.6)
55000.0
>>> Graetz_heat(1.5, 0.25, 5, alpha=1E-7)
187500.0
References
----------
.. [1] Bergman, Theodore L., Adrienne S. Lavine, Frank P. Incropera, and
David P. DeWitt. Introduction to Heat Transfer. 6E. Hoboken, NJ:
Wiley, 2011. | [
"r",
"Calculates",
"Graetz",
"number",
"or",
"Gz",
"for",
"a",
"specified",
"velocity",
"V",
"diameter",
"D",
"axial",
"distance",
"x",
"and",
"specified",
"properties",
"for",
"the",
"given",
"fluid",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/core.py#L390-L454 | train |
CalebBell/fluids | fluids/core.py | Schmidt | def Schmidt(D, mu=None, nu=None, rho=None):
r'''Calculates Schmidt number or `Sc` for a fluid with the given
parameters.
.. math::
Sc = \frac{\mu}{D\rho} = \frac{\nu}{D}
Inputs can be any of the following sets:
* Diffusivity, dynamic viscosity, and density
* Diffusivity and kinematic viscosity
Parameters
----------
D : float
Diffusivity of a species, [m^2/s]
mu : float, optional
Dynamic viscosity, [Pa*s]
nu : float, optional
Kinematic viscosity, [m^2/s]
rho : float, optional
Density, [kg/m^3]
Returns
-------
Sc : float
Schmidt number []
Notes
-----
.. math::
Sc =\frac{\text{kinematic viscosity}}{\text{molecular diffusivity}}
= \frac{\text{viscous diffusivity}}{\text{species diffusivity}}
An error is raised if none of the required input sets are provided.
Examples
--------
>>> Schmidt(D=2E-6, mu=4.61E-6, rho=800)
0.00288125
>>> Schmidt(D=1E-9, nu=6E-7)
599.9999999999999
References
----------
.. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,
Eighth Edition. McGraw-Hill Professional, 2007.
.. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and
Applications. Boston: McGraw Hill Higher Education, 2006.
'''
if rho and mu:
return mu/(rho*D)
elif nu:
return nu/D
else:
raise Exception('Insufficient information provided for Schmidt number calculation') | python | def Schmidt(D, mu=None, nu=None, rho=None):
r'''Calculates Schmidt number or `Sc` for a fluid with the given
parameters.
.. math::
Sc = \frac{\mu}{D\rho} = \frac{\nu}{D}
Inputs can be any of the following sets:
* Diffusivity, dynamic viscosity, and density
* Diffusivity and kinematic viscosity
Parameters
----------
D : float
Diffusivity of a species, [m^2/s]
mu : float, optional
Dynamic viscosity, [Pa*s]
nu : float, optional
Kinematic viscosity, [m^2/s]
rho : float, optional
Density, [kg/m^3]
Returns
-------
Sc : float
Schmidt number []
Notes
-----
.. math::
Sc =\frac{\text{kinematic viscosity}}{\text{molecular diffusivity}}
= \frac{\text{viscous diffusivity}}{\text{species diffusivity}}
An error is raised if none of the required input sets are provided.
Examples
--------
>>> Schmidt(D=2E-6, mu=4.61E-6, rho=800)
0.00288125
>>> Schmidt(D=1E-9, nu=6E-7)
599.9999999999999
References
----------
.. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,
Eighth Edition. McGraw-Hill Professional, 2007.
.. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and
Applications. Boston: McGraw Hill Higher Education, 2006.
'''
if rho and mu:
return mu/(rho*D)
elif nu:
return nu/D
else:
raise Exception('Insufficient information provided for Schmidt number calculation') | [
"def",
"Schmidt",
"(",
"D",
",",
"mu",
"=",
"None",
",",
"nu",
"=",
"None",
",",
"rho",
"=",
"None",
")",
":",
"if",
"rho",
"and",
"mu",
":",
"return",
"mu",
"/",
"(",
"rho",
"*",
"D",
")",
"elif",
"nu",
":",
"return",
"nu",
"/",
"D",
"else",
":",
"raise",
"Exception",
"(",
"'Insufficient information provided for Schmidt number calculation'",
")"
]
| r'''Calculates Schmidt number or `Sc` for a fluid with the given
parameters.
.. math::
Sc = \frac{\mu}{D\rho} = \frac{\nu}{D}
Inputs can be any of the following sets:
* Diffusivity, dynamic viscosity, and density
* Diffusivity and kinematic viscosity
Parameters
----------
D : float
Diffusivity of a species, [m^2/s]
mu : float, optional
Dynamic viscosity, [Pa*s]
nu : float, optional
Kinematic viscosity, [m^2/s]
rho : float, optional
Density, [kg/m^3]
Returns
-------
Sc : float
Schmidt number []
Notes
-----
.. math::
Sc =\frac{\text{kinematic viscosity}}{\text{molecular diffusivity}}
= \frac{\text{viscous diffusivity}}{\text{species diffusivity}}
An error is raised if none of the required input sets are provided.
Examples
--------
>>> Schmidt(D=2E-6, mu=4.61E-6, rho=800)
0.00288125
>>> Schmidt(D=1E-9, nu=6E-7)
599.9999999999999
References
----------
.. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,
Eighth Edition. McGraw-Hill Professional, 2007.
.. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and
Applications. Boston: McGraw Hill Higher Education, 2006. | [
"r",
"Calculates",
"Schmidt",
"number",
"or",
"Sc",
"for",
"a",
"fluid",
"with",
"the",
"given",
"parameters",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/core.py#L457-L512 | train |
CalebBell/fluids | fluids/core.py | Lewis | def Lewis(D=None, alpha=None, Cp=None, k=None, rho=None):
r'''Calculates Lewis number or `Le` for a fluid with the given parameters.
.. math::
Le = \frac{k}{\rho C_p D} = \frac{\alpha}{D}
Inputs can be either of the following sets:
* Diffusivity and Thermal diffusivity
* Diffusivity, heat capacity, thermal conductivity, and density
Parameters
----------
D : float
Diffusivity of a species, [m^2/s]
alpha : float, optional
Thermal diffusivity, [m^2/s]
Cp : float, optional
Heat capacity, [J/kg/K]
k : float, optional
Thermal conductivity, [W/m/K]
rho : float, optional
Density, [kg/m^3]
Returns
-------
Le : float
Lewis number []
Notes
-----
.. math::
Le=\frac{\text{Thermal diffusivity}}{\text{Mass diffusivity}} =
\frac{Sc}{Pr}
An error is raised if none of the required input sets are provided.
Examples
--------
>>> Lewis(D=22.6E-6, alpha=19.1E-6)
0.8451327433628318
>>> Lewis(D=22.6E-6, rho=800., k=.2, Cp=2200)
0.00502815768302494
References
----------
.. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,
Eighth Edition. McGraw-Hill Professional, 2007.
.. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and
Applications. Boston: McGraw Hill Higher Education, 2006.
.. [3] Gesellschaft, V. D. I., ed. VDI Heat Atlas. 2nd edition.
Berlin; New York:: Springer, 2010.
'''
if k and Cp and rho:
alpha = k/(rho*Cp)
elif alpha:
pass
else:
raise Exception('Insufficient information provided for Le calculation')
return alpha/D | python | def Lewis(D=None, alpha=None, Cp=None, k=None, rho=None):
r'''Calculates Lewis number or `Le` for a fluid with the given parameters.
.. math::
Le = \frac{k}{\rho C_p D} = \frac{\alpha}{D}
Inputs can be either of the following sets:
* Diffusivity and Thermal diffusivity
* Diffusivity, heat capacity, thermal conductivity, and density
Parameters
----------
D : float
Diffusivity of a species, [m^2/s]
alpha : float, optional
Thermal diffusivity, [m^2/s]
Cp : float, optional
Heat capacity, [J/kg/K]
k : float, optional
Thermal conductivity, [W/m/K]
rho : float, optional
Density, [kg/m^3]
Returns
-------
Le : float
Lewis number []
Notes
-----
.. math::
Le=\frac{\text{Thermal diffusivity}}{\text{Mass diffusivity}} =
\frac{Sc}{Pr}
An error is raised if none of the required input sets are provided.
Examples
--------
>>> Lewis(D=22.6E-6, alpha=19.1E-6)
0.8451327433628318
>>> Lewis(D=22.6E-6, rho=800., k=.2, Cp=2200)
0.00502815768302494
References
----------
.. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,
Eighth Edition. McGraw-Hill Professional, 2007.
.. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and
Applications. Boston: McGraw Hill Higher Education, 2006.
.. [3] Gesellschaft, V. D. I., ed. VDI Heat Atlas. 2nd edition.
Berlin; New York:: Springer, 2010.
'''
if k and Cp and rho:
alpha = k/(rho*Cp)
elif alpha:
pass
else:
raise Exception('Insufficient information provided for Le calculation')
return alpha/D | [
"def",
"Lewis",
"(",
"D",
"=",
"None",
",",
"alpha",
"=",
"None",
",",
"Cp",
"=",
"None",
",",
"k",
"=",
"None",
",",
"rho",
"=",
"None",
")",
":",
"if",
"k",
"and",
"Cp",
"and",
"rho",
":",
"alpha",
"=",
"k",
"/",
"(",
"rho",
"*",
"Cp",
")",
"elif",
"alpha",
":",
"pass",
"else",
":",
"raise",
"Exception",
"(",
"'Insufficient information provided for Le calculation'",
")",
"return",
"alpha",
"/",
"D"
]
| r'''Calculates Lewis number or `Le` for a fluid with the given parameters.
.. math::
Le = \frac{k}{\rho C_p D} = \frac{\alpha}{D}
Inputs can be either of the following sets:
* Diffusivity and Thermal diffusivity
* Diffusivity, heat capacity, thermal conductivity, and density
Parameters
----------
D : float
Diffusivity of a species, [m^2/s]
alpha : float, optional
Thermal diffusivity, [m^2/s]
Cp : float, optional
Heat capacity, [J/kg/K]
k : float, optional
Thermal conductivity, [W/m/K]
rho : float, optional
Density, [kg/m^3]
Returns
-------
Le : float
Lewis number []
Notes
-----
.. math::
Le=\frac{\text{Thermal diffusivity}}{\text{Mass diffusivity}} =
\frac{Sc}{Pr}
An error is raised if none of the required input sets are provided.
Examples
--------
>>> Lewis(D=22.6E-6, alpha=19.1E-6)
0.8451327433628318
>>> Lewis(D=22.6E-6, rho=800., k=.2, Cp=2200)
0.00502815768302494
References
----------
.. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,
Eighth Edition. McGraw-Hill Professional, 2007.
.. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and
Applications. Boston: McGraw Hill Higher Education, 2006.
.. [3] Gesellschaft, V. D. I., ed. VDI Heat Atlas. 2nd edition.
Berlin; New York:: Springer, 2010. | [
"r",
"Calculates",
"Lewis",
"number",
"or",
"Le",
"for",
"a",
"fluid",
"with",
"the",
"given",
"parameters",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/core.py#L515-L574 | train |
CalebBell/fluids | fluids/core.py | Confinement | def Confinement(D, rhol, rhog, sigma, g=g):
r'''Calculates Confinement number or `Co` for a fluid in a channel of
diameter `D` with liquid and gas densities `rhol` and `rhog` and surface
tension `sigma`, under the influence of gravitational force `g`.
.. math::
\text{Co}=\frac{\left[\frac{\sigma}{g(\rho_l-\rho_g)}\right]^{0.5}}{D}
Parameters
----------
D : float
Diameter of channel, [m]
rhol : float
Density of liquid phase, [kg/m^3]
rhog : float
Density of gas phase, [kg/m^3]
sigma : float
Surface tension between liquid-gas phase, [N/m]
g : float, optional
Acceleration due to gravity, [m/s^2]
Returns
-------
Co : float
Confinement number [-]
Notes
-----
Used in two-phase pressure drop and heat transfer correlations. First used
in [1]_ according to [3]_.
.. math::
\text{Co} = \frac{\frac{\text{surface tension force}}
{\text{buoyancy force}}}{\text{Channel area}}
Examples
--------
>>> Confinement(0.001, 1077, 76.5, 4.27E-3)
0.6596978265315191
References
----------
.. [1] Cornwell, Keith, and Peter A. Kew. "Boiling in Small Parallel
Channels." In Energy Efficiency in Process Technology, edited by Dr P.
A. Pilavachi, 624-638. Springer Netherlands, 1993.
doi:10.1007/978-94-011-1454-7_56.
.. [2] Kandlikar, Satish G. Heat Transfer and Fluid Flow in Minichannels
and Microchannels. Elsevier, 2006.
.. [3] Tran, T. N, M. -C Chyu, M. W Wambsganss, and D. M France. Two-Phase
Pressure Drop of Refrigerants during Flow Boiling in Small Channels: An
Experimental Investigation and Correlation Development." International
Journal of Multiphase Flow 26, no. 11 (November 1, 2000): 1739-54.
doi:10.1016/S0301-9322(99)00119-6.
'''
return (sigma/(g*(rhol-rhog)))**0.5/D | python | def Confinement(D, rhol, rhog, sigma, g=g):
r'''Calculates Confinement number or `Co` for a fluid in a channel of
diameter `D` with liquid and gas densities `rhol` and `rhog` and surface
tension `sigma`, under the influence of gravitational force `g`.
.. math::
\text{Co}=\frac{\left[\frac{\sigma}{g(\rho_l-\rho_g)}\right]^{0.5}}{D}
Parameters
----------
D : float
Diameter of channel, [m]
rhol : float
Density of liquid phase, [kg/m^3]
rhog : float
Density of gas phase, [kg/m^3]
sigma : float
Surface tension between liquid-gas phase, [N/m]
g : float, optional
Acceleration due to gravity, [m/s^2]
Returns
-------
Co : float
Confinement number [-]
Notes
-----
Used in two-phase pressure drop and heat transfer correlations. First used
in [1]_ according to [3]_.
.. math::
\text{Co} = \frac{\frac{\text{surface tension force}}
{\text{buoyancy force}}}{\text{Channel area}}
Examples
--------
>>> Confinement(0.001, 1077, 76.5, 4.27E-3)
0.6596978265315191
References
----------
.. [1] Cornwell, Keith, and Peter A. Kew. "Boiling in Small Parallel
Channels." In Energy Efficiency in Process Technology, edited by Dr P.
A. Pilavachi, 624-638. Springer Netherlands, 1993.
doi:10.1007/978-94-011-1454-7_56.
.. [2] Kandlikar, Satish G. Heat Transfer and Fluid Flow in Minichannels
and Microchannels. Elsevier, 2006.
.. [3] Tran, T. N, M. -C Chyu, M. W Wambsganss, and D. M France. Two-Phase
Pressure Drop of Refrigerants during Flow Boiling in Small Channels: An
Experimental Investigation and Correlation Development." International
Journal of Multiphase Flow 26, no. 11 (November 1, 2000): 1739-54.
doi:10.1016/S0301-9322(99)00119-6.
'''
return (sigma/(g*(rhol-rhog)))**0.5/D | [
"def",
"Confinement",
"(",
"D",
",",
"rhol",
",",
"rhog",
",",
"sigma",
",",
"g",
"=",
"g",
")",
":",
"return",
"(",
"sigma",
"/",
"(",
"g",
"*",
"(",
"rhol",
"-",
"rhog",
")",
")",
")",
"**",
"0.5",
"/",
"D"
]
| r'''Calculates Confinement number or `Co` for a fluid in a channel of
diameter `D` with liquid and gas densities `rhol` and `rhog` and surface
tension `sigma`, under the influence of gravitational force `g`.
.. math::
\text{Co}=\frac{\left[\frac{\sigma}{g(\rho_l-\rho_g)}\right]^{0.5}}{D}
Parameters
----------
D : float
Diameter of channel, [m]
rhol : float
Density of liquid phase, [kg/m^3]
rhog : float
Density of gas phase, [kg/m^3]
sigma : float
Surface tension between liquid-gas phase, [N/m]
g : float, optional
Acceleration due to gravity, [m/s^2]
Returns
-------
Co : float
Confinement number [-]
Notes
-----
Used in two-phase pressure drop and heat transfer correlations. First used
in [1]_ according to [3]_.
.. math::
\text{Co} = \frac{\frac{\text{surface tension force}}
{\text{buoyancy force}}}{\text{Channel area}}
Examples
--------
>>> Confinement(0.001, 1077, 76.5, 4.27E-3)
0.6596978265315191
References
----------
.. [1] Cornwell, Keith, and Peter A. Kew. "Boiling in Small Parallel
Channels." In Energy Efficiency in Process Technology, edited by Dr P.
A. Pilavachi, 624-638. Springer Netherlands, 1993.
doi:10.1007/978-94-011-1454-7_56.
.. [2] Kandlikar, Satish G. Heat Transfer and Fluid Flow in Minichannels
and Microchannels. Elsevier, 2006.
.. [3] Tran, T. N, M. -C Chyu, M. W Wambsganss, and D. M France. Two-Phase
Pressure Drop of Refrigerants during Flow Boiling in Small Channels: An
Experimental Investigation and Correlation Development." International
Journal of Multiphase Flow 26, no. 11 (November 1, 2000): 1739-54.
doi:10.1016/S0301-9322(99)00119-6. | [
"r",
"Calculates",
"Confinement",
"number",
"or",
"Co",
"for",
"a",
"fluid",
"in",
"a",
"channel",
"of",
"diameter",
"D",
"with",
"liquid",
"and",
"gas",
"densities",
"rhol",
"and",
"rhog",
"and",
"surface",
"tension",
"sigma",
"under",
"the",
"influence",
"of",
"gravitational",
"force",
"g",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/core.py#L666-L720 | train |
CalebBell/fluids | fluids/core.py | Morton | def Morton(rhol, rhog, mul, sigma, g=g):
r'''Calculates Morton number or `Mo` for a liquid and vapor with the
specified properties, under the influence of gravitational force `g`.
.. math::
Mo = \frac{g \mu_l^4(\rho_l - \rho_g)}{\rho_l^2 \sigma^3}
Parameters
----------
rhol : float
Density of liquid phase, [kg/m^3]
rhog : float
Density of gas phase, [kg/m^3]
mul : float
Viscosity of liquid phase, [Pa*s]
sigma : float
Surface tension between liquid-gas phase, [N/m]
g : float, optional
Acceleration due to gravity, [m/s^2]
Returns
-------
Mo : float
Morton number, [-]
Notes
-----
Used in modeling bubbles in liquid.
Examples
--------
>>> Morton(1077.0, 76.5, 4.27E-3, 0.023)
2.311183104430743e-07
References
----------
.. [1] Kunes, Josef. Dimensionless Physical Quantities in Science and
Engineering. Elsevier, 2012.
.. [2] Yan, Xiaokang, Kaixin Zheng, Yan Jia, Zhenyong Miao, Lijun Wang,
Yijun Cao, and Jiongtian Liu. “Drag Coefficient Prediction of a Single
Bubble Rising in Liquids.” Industrial & Engineering Chemistry Research,
April 2, 2018. https://doi.org/10.1021/acs.iecr.7b04743.
'''
mul2 = mul*mul
return g*mul2*mul2*(rhol - rhog)/(rhol*rhol*sigma*sigma*sigma) | python | def Morton(rhol, rhog, mul, sigma, g=g):
r'''Calculates Morton number or `Mo` for a liquid and vapor with the
specified properties, under the influence of gravitational force `g`.
.. math::
Mo = \frac{g \mu_l^4(\rho_l - \rho_g)}{\rho_l^2 \sigma^3}
Parameters
----------
rhol : float
Density of liquid phase, [kg/m^3]
rhog : float
Density of gas phase, [kg/m^3]
mul : float
Viscosity of liquid phase, [Pa*s]
sigma : float
Surface tension between liquid-gas phase, [N/m]
g : float, optional
Acceleration due to gravity, [m/s^2]
Returns
-------
Mo : float
Morton number, [-]
Notes
-----
Used in modeling bubbles in liquid.
Examples
--------
>>> Morton(1077.0, 76.5, 4.27E-3, 0.023)
2.311183104430743e-07
References
----------
.. [1] Kunes, Josef. Dimensionless Physical Quantities in Science and
Engineering. Elsevier, 2012.
.. [2] Yan, Xiaokang, Kaixin Zheng, Yan Jia, Zhenyong Miao, Lijun Wang,
Yijun Cao, and Jiongtian Liu. “Drag Coefficient Prediction of a Single
Bubble Rising in Liquids.” Industrial & Engineering Chemistry Research,
April 2, 2018. https://doi.org/10.1021/acs.iecr.7b04743.
'''
mul2 = mul*mul
return g*mul2*mul2*(rhol - rhog)/(rhol*rhol*sigma*sigma*sigma) | [
"def",
"Morton",
"(",
"rhol",
",",
"rhog",
",",
"mul",
",",
"sigma",
",",
"g",
"=",
"g",
")",
":",
"mul2",
"=",
"mul",
"*",
"mul",
"return",
"g",
"*",
"mul2",
"*",
"mul2",
"*",
"(",
"rhol",
"-",
"rhog",
")",
"/",
"(",
"rhol",
"*",
"rhol",
"*",
"sigma",
"*",
"sigma",
"*",
"sigma",
")"
]
| r'''Calculates Morton number or `Mo` for a liquid and vapor with the
specified properties, under the influence of gravitational force `g`.
.. math::
Mo = \frac{g \mu_l^4(\rho_l - \rho_g)}{\rho_l^2 \sigma^3}
Parameters
----------
rhol : float
Density of liquid phase, [kg/m^3]
rhog : float
Density of gas phase, [kg/m^3]
mul : float
Viscosity of liquid phase, [Pa*s]
sigma : float
Surface tension between liquid-gas phase, [N/m]
g : float, optional
Acceleration due to gravity, [m/s^2]
Returns
-------
Mo : float
Morton number, [-]
Notes
-----
Used in modeling bubbles in liquid.
Examples
--------
>>> Morton(1077.0, 76.5, 4.27E-3, 0.023)
2.311183104430743e-07
References
----------
.. [1] Kunes, Josef. Dimensionless Physical Quantities in Science and
Engineering. Elsevier, 2012.
.. [2] Yan, Xiaokang, Kaixin Zheng, Yan Jia, Zhenyong Miao, Lijun Wang,
Yijun Cao, and Jiongtian Liu. “Drag Coefficient Prediction of a Single
Bubble Rising in Liquids.” Industrial & Engineering Chemistry Research,
April 2, 2018. https://doi.org/10.1021/acs.iecr.7b04743. | [
"r",
"Calculates",
"Morton",
"number",
"or",
"Mo",
"for",
"a",
"liquid",
"and",
"vapor",
"with",
"the",
"specified",
"properties",
"under",
"the",
"influence",
"of",
"gravitational",
"force",
"g",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/core.py#L723-L767 | train |
CalebBell/fluids | fluids/core.py | Prandtl | def Prandtl(Cp=None, k=None, mu=None, nu=None, rho=None, alpha=None):
r'''Calculates Prandtl number or `Pr` for a fluid with the given
parameters.
.. math::
Pr = \frac{C_p \mu}{k} = \frac{\nu}{\alpha} = \frac{C_p \rho \nu}{k}
Inputs can be any of the following sets:
* Heat capacity, dynamic viscosity, and thermal conductivity
* Thermal diffusivity and kinematic viscosity
* Heat capacity, kinematic viscosity, thermal conductivity, and density
Parameters
----------
Cp : float
Heat capacity, [J/kg/K]
k : float
Thermal conductivity, [W/m/K]
mu : float, optional
Dynamic viscosity, [Pa*s]
nu : float, optional
Kinematic viscosity, [m^2/s]
rho : float
Density, [kg/m^3]
alpha : float
Thermal diffusivity, [m^2/s]
Returns
-------
Pr : float
Prandtl number []
Notes
-----
.. math::
Pr=\frac{\text{kinematic viscosity}}{\text{thermal diffusivity}} = \frac{\text{momentum diffusivity}}{\text{thermal diffusivity}}
An error is raised if none of the required input sets are provided.
Examples
--------
>>> Prandtl(Cp=1637., k=0.010, mu=4.61E-6)
0.754657
>>> Prandtl(Cp=1637., k=0.010, nu=6.4E-7, rho=7.1)
0.7438528
>>> Prandtl(nu=6.3E-7, alpha=9E-7)
0.7000000000000001
References
----------
.. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,
Eighth Edition. McGraw-Hill Professional, 2007.
.. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and
Applications. Boston: McGraw Hill Higher Education, 2006.
.. [3] Gesellschaft, V. D. I., ed. VDI Heat Atlas. 2nd edition.
Berlin; New York:: Springer, 2010.
'''
if k and Cp and mu:
return Cp*mu/k
elif nu and rho and Cp and k:
return nu*rho*Cp/k
elif nu and alpha:
return nu/alpha
else:
raise Exception('Insufficient information provided for Pr calculation') | python | def Prandtl(Cp=None, k=None, mu=None, nu=None, rho=None, alpha=None):
r'''Calculates Prandtl number or `Pr` for a fluid with the given
parameters.
.. math::
Pr = \frac{C_p \mu}{k} = \frac{\nu}{\alpha} = \frac{C_p \rho \nu}{k}
Inputs can be any of the following sets:
* Heat capacity, dynamic viscosity, and thermal conductivity
* Thermal diffusivity and kinematic viscosity
* Heat capacity, kinematic viscosity, thermal conductivity, and density
Parameters
----------
Cp : float
Heat capacity, [J/kg/K]
k : float
Thermal conductivity, [W/m/K]
mu : float, optional
Dynamic viscosity, [Pa*s]
nu : float, optional
Kinematic viscosity, [m^2/s]
rho : float
Density, [kg/m^3]
alpha : float
Thermal diffusivity, [m^2/s]
Returns
-------
Pr : float
Prandtl number []
Notes
-----
.. math::
Pr=\frac{\text{kinematic viscosity}}{\text{thermal diffusivity}} = \frac{\text{momentum diffusivity}}{\text{thermal diffusivity}}
An error is raised if none of the required input sets are provided.
Examples
--------
>>> Prandtl(Cp=1637., k=0.010, mu=4.61E-6)
0.754657
>>> Prandtl(Cp=1637., k=0.010, nu=6.4E-7, rho=7.1)
0.7438528
>>> Prandtl(nu=6.3E-7, alpha=9E-7)
0.7000000000000001
References
----------
.. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,
Eighth Edition. McGraw-Hill Professional, 2007.
.. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and
Applications. Boston: McGraw Hill Higher Education, 2006.
.. [3] Gesellschaft, V. D. I., ed. VDI Heat Atlas. 2nd edition.
Berlin; New York:: Springer, 2010.
'''
if k and Cp and mu:
return Cp*mu/k
elif nu and rho and Cp and k:
return nu*rho*Cp/k
elif nu and alpha:
return nu/alpha
else:
raise Exception('Insufficient information provided for Pr calculation') | [
"def",
"Prandtl",
"(",
"Cp",
"=",
"None",
",",
"k",
"=",
"None",
",",
"mu",
"=",
"None",
",",
"nu",
"=",
"None",
",",
"rho",
"=",
"None",
",",
"alpha",
"=",
"None",
")",
":",
"if",
"k",
"and",
"Cp",
"and",
"mu",
":",
"return",
"Cp",
"*",
"mu",
"/",
"k",
"elif",
"nu",
"and",
"rho",
"and",
"Cp",
"and",
"k",
":",
"return",
"nu",
"*",
"rho",
"*",
"Cp",
"/",
"k",
"elif",
"nu",
"and",
"alpha",
":",
"return",
"nu",
"/",
"alpha",
"else",
":",
"raise",
"Exception",
"(",
"'Insufficient information provided for Pr calculation'",
")"
]
| r'''Calculates Prandtl number or `Pr` for a fluid with the given
parameters.
.. math::
Pr = \frac{C_p \mu}{k} = \frac{\nu}{\alpha} = \frac{C_p \rho \nu}{k}
Inputs can be any of the following sets:
* Heat capacity, dynamic viscosity, and thermal conductivity
* Thermal diffusivity and kinematic viscosity
* Heat capacity, kinematic viscosity, thermal conductivity, and density
Parameters
----------
Cp : float
Heat capacity, [J/kg/K]
k : float
Thermal conductivity, [W/m/K]
mu : float, optional
Dynamic viscosity, [Pa*s]
nu : float, optional
Kinematic viscosity, [m^2/s]
rho : float
Density, [kg/m^3]
alpha : float
Thermal diffusivity, [m^2/s]
Returns
-------
Pr : float
Prandtl number []
Notes
-----
.. math::
Pr=\frac{\text{kinematic viscosity}}{\text{thermal diffusivity}} = \frac{\text{momentum diffusivity}}{\text{thermal diffusivity}}
An error is raised if none of the required input sets are provided.
Examples
--------
>>> Prandtl(Cp=1637., k=0.010, mu=4.61E-6)
0.754657
>>> Prandtl(Cp=1637., k=0.010, nu=6.4E-7, rho=7.1)
0.7438528
>>> Prandtl(nu=6.3E-7, alpha=9E-7)
0.7000000000000001
References
----------
.. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,
Eighth Edition. McGraw-Hill Professional, 2007.
.. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and
Applications. Boston: McGraw Hill Higher Education, 2006.
.. [3] Gesellschaft, V. D. I., ed. VDI Heat Atlas. 2nd edition.
Berlin; New York:: Springer, 2010. | [
"r",
"Calculates",
"Prandtl",
"number",
"or",
"Pr",
"for",
"a",
"fluid",
"with",
"the",
"given",
"parameters",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/core.py#L811-L876 | train |
CalebBell/fluids | fluids/core.py | Grashof | def Grashof(L, beta, T1, T2=0, rho=None, mu=None, nu=None, g=g):
r'''Calculates Grashof number or `Gr` for a fluid with the given
properties, temperature difference, and characteristic length.
.. math::
Gr = \frac{g\beta (T_s-T_\infty)L^3}{\nu^2}
= \frac{g\beta (T_s-T_\infty)L^3\rho^2}{\mu^2}
Inputs either of any of the following sets:
* L, beta, T1 and T2, and density `rho` and kinematic viscosity `mu`
* L, beta, T1 and T2, and dynamic viscosity `nu`
Parameters
----------
L : float
Characteristic length [m]
beta : float
Volumetric thermal expansion coefficient [1/K]
T1 : float
Temperature 1, usually a film temperature [K]
T2 : float, optional
Temperature 2, usually a bulk temperature (or 0 if only a difference
is provided to the function) [K]
rho : float, optional
Density, [kg/m^3]
mu : float, optional
Dynamic viscosity, [Pa*s]
nu : float, optional
Kinematic viscosity, [m^2/s]
g : float, optional
Acceleration due to gravity, [m/s^2]
Returns
-------
Gr : float
Grashof number []
Notes
-----
.. math::
Gr = \frac{\text{Buoyancy forces}}{\text{Viscous forces}}
An error is raised if none of the required input sets are provided.
Used in free convection problems only.
Examples
--------
Example 4 of [1]_, p. 1-21 (matches):
>>> Grashof(L=0.9144, beta=0.000933, T1=178.2, rho=1.1613, mu=1.9E-5)
4656936556.178915
>>> Grashof(L=0.9144, beta=0.000933, T1=378.2, T2=200, nu=1.636e-05)
4657491516.530312
References
----------
.. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,
Eighth Edition. McGraw-Hill Professional, 2007.
.. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and
Applications. Boston: McGraw Hill Higher Education, 2006.
'''
if rho and mu:
nu = mu/rho
elif not nu:
raise Exception('Either density and viscosity, or dynamic viscosity, \
is needed')
return g*beta*abs(T2-T1)*L**3/nu**2 | python | def Grashof(L, beta, T1, T2=0, rho=None, mu=None, nu=None, g=g):
r'''Calculates Grashof number or `Gr` for a fluid with the given
properties, temperature difference, and characteristic length.
.. math::
Gr = \frac{g\beta (T_s-T_\infty)L^3}{\nu^2}
= \frac{g\beta (T_s-T_\infty)L^3\rho^2}{\mu^2}
Inputs either of any of the following sets:
* L, beta, T1 and T2, and density `rho` and kinematic viscosity `mu`
* L, beta, T1 and T2, and dynamic viscosity `nu`
Parameters
----------
L : float
Characteristic length [m]
beta : float
Volumetric thermal expansion coefficient [1/K]
T1 : float
Temperature 1, usually a film temperature [K]
T2 : float, optional
Temperature 2, usually a bulk temperature (or 0 if only a difference
is provided to the function) [K]
rho : float, optional
Density, [kg/m^3]
mu : float, optional
Dynamic viscosity, [Pa*s]
nu : float, optional
Kinematic viscosity, [m^2/s]
g : float, optional
Acceleration due to gravity, [m/s^2]
Returns
-------
Gr : float
Grashof number []
Notes
-----
.. math::
Gr = \frac{\text{Buoyancy forces}}{\text{Viscous forces}}
An error is raised if none of the required input sets are provided.
Used in free convection problems only.
Examples
--------
Example 4 of [1]_, p. 1-21 (matches):
>>> Grashof(L=0.9144, beta=0.000933, T1=178.2, rho=1.1613, mu=1.9E-5)
4656936556.178915
>>> Grashof(L=0.9144, beta=0.000933, T1=378.2, T2=200, nu=1.636e-05)
4657491516.530312
References
----------
.. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,
Eighth Edition. McGraw-Hill Professional, 2007.
.. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and
Applications. Boston: McGraw Hill Higher Education, 2006.
'''
if rho and mu:
nu = mu/rho
elif not nu:
raise Exception('Either density and viscosity, or dynamic viscosity, \
is needed')
return g*beta*abs(T2-T1)*L**3/nu**2 | [
"def",
"Grashof",
"(",
"L",
",",
"beta",
",",
"T1",
",",
"T2",
"=",
"0",
",",
"rho",
"=",
"None",
",",
"mu",
"=",
"None",
",",
"nu",
"=",
"None",
",",
"g",
"=",
"g",
")",
":",
"if",
"rho",
"and",
"mu",
":",
"nu",
"=",
"mu",
"/",
"rho",
"elif",
"not",
"nu",
":",
"raise",
"Exception",
"(",
"'Either density and viscosity, or dynamic viscosity, \\\n is needed'",
")",
"return",
"g",
"*",
"beta",
"*",
"abs",
"(",
"T2",
"-",
"T1",
")",
"*",
"L",
"**",
"3",
"/",
"nu",
"**",
"2"
]
| r'''Calculates Grashof number or `Gr` for a fluid with the given
properties, temperature difference, and characteristic length.
.. math::
Gr = \frac{g\beta (T_s-T_\infty)L^3}{\nu^2}
= \frac{g\beta (T_s-T_\infty)L^3\rho^2}{\mu^2}
Inputs either of any of the following sets:
* L, beta, T1 and T2, and density `rho` and kinematic viscosity `mu`
* L, beta, T1 and T2, and dynamic viscosity `nu`
Parameters
----------
L : float
Characteristic length [m]
beta : float
Volumetric thermal expansion coefficient [1/K]
T1 : float
Temperature 1, usually a film temperature [K]
T2 : float, optional
Temperature 2, usually a bulk temperature (or 0 if only a difference
is provided to the function) [K]
rho : float, optional
Density, [kg/m^3]
mu : float, optional
Dynamic viscosity, [Pa*s]
nu : float, optional
Kinematic viscosity, [m^2/s]
g : float, optional
Acceleration due to gravity, [m/s^2]
Returns
-------
Gr : float
Grashof number []
Notes
-----
.. math::
Gr = \frac{\text{Buoyancy forces}}{\text{Viscous forces}}
An error is raised if none of the required input sets are provided.
Used in free convection problems only.
Examples
--------
Example 4 of [1]_, p. 1-21 (matches):
>>> Grashof(L=0.9144, beta=0.000933, T1=178.2, rho=1.1613, mu=1.9E-5)
4656936556.178915
>>> Grashof(L=0.9144, beta=0.000933, T1=378.2, T2=200, nu=1.636e-05)
4657491516.530312
References
----------
.. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,
Eighth Edition. McGraw-Hill Professional, 2007.
.. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and
Applications. Boston: McGraw Hill Higher Education, 2006. | [
"r",
"Calculates",
"Grashof",
"number",
"or",
"Gr",
"for",
"a",
"fluid",
"with",
"the",
"given",
"properties",
"temperature",
"difference",
"and",
"characteristic",
"length",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/core.py#L879-L946 | train |
CalebBell/fluids | fluids/core.py | Froude | def Froude(V, L, g=g, squared=False):
r'''Calculates Froude number `Fr` for velocity `V` and geometric length
`L`. If desired, gravity can be specified as well. Normally the function
returns the result of the equation below; Froude number is also often
said to be defined as the square of the equation below.
.. math::
Fr = \frac{V}{\sqrt{gL}}
Parameters
----------
V : float
Velocity of the particle or fluid, [m/s]
L : float
Characteristic length, no typical definition [m]
g : float, optional
Acceleration due to gravity, [m/s^2]
squared : bool, optional
Whether to return the squared form of Froude number
Returns
-------
Fr : float
Froude number, [-]
Notes
-----
Many alternate definitions including density ratios have been used.
.. math::
Fr = \frac{\text{Inertial Force}}{\text{Gravity Force}}
Examples
--------
>>> Froude(1.83, L=2., g=1.63)
1.0135432593877318
>>> Froude(1.83, L=2., squared=True)
0.17074638128208924
References
----------
.. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,
Eighth Edition. McGraw-Hill Professional, 2007.
.. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and
Applications. Boston: McGraw Hill Higher Education, 2006.
'''
Fr = V/(L*g)**0.5
if squared:
Fr *= Fr
return Fr | python | def Froude(V, L, g=g, squared=False):
r'''Calculates Froude number `Fr` for velocity `V` and geometric length
`L`. If desired, gravity can be specified as well. Normally the function
returns the result of the equation below; Froude number is also often
said to be defined as the square of the equation below.
.. math::
Fr = \frac{V}{\sqrt{gL}}
Parameters
----------
V : float
Velocity of the particle or fluid, [m/s]
L : float
Characteristic length, no typical definition [m]
g : float, optional
Acceleration due to gravity, [m/s^2]
squared : bool, optional
Whether to return the squared form of Froude number
Returns
-------
Fr : float
Froude number, [-]
Notes
-----
Many alternate definitions including density ratios have been used.
.. math::
Fr = \frac{\text{Inertial Force}}{\text{Gravity Force}}
Examples
--------
>>> Froude(1.83, L=2., g=1.63)
1.0135432593877318
>>> Froude(1.83, L=2., squared=True)
0.17074638128208924
References
----------
.. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,
Eighth Edition. McGraw-Hill Professional, 2007.
.. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and
Applications. Boston: McGraw Hill Higher Education, 2006.
'''
Fr = V/(L*g)**0.5
if squared:
Fr *= Fr
return Fr | [
"def",
"Froude",
"(",
"V",
",",
"L",
",",
"g",
"=",
"g",
",",
"squared",
"=",
"False",
")",
":",
"Fr",
"=",
"V",
"/",
"(",
"L",
"*",
"g",
")",
"**",
"0.5",
"if",
"squared",
":",
"Fr",
"*=",
"Fr",
"return",
"Fr"
]
| r'''Calculates Froude number `Fr` for velocity `V` and geometric length
`L`. If desired, gravity can be specified as well. Normally the function
returns the result of the equation below; Froude number is also often
said to be defined as the square of the equation below.
.. math::
Fr = \frac{V}{\sqrt{gL}}
Parameters
----------
V : float
Velocity of the particle or fluid, [m/s]
L : float
Characteristic length, no typical definition [m]
g : float, optional
Acceleration due to gravity, [m/s^2]
squared : bool, optional
Whether to return the squared form of Froude number
Returns
-------
Fr : float
Froude number, [-]
Notes
-----
Many alternate definitions including density ratios have been used.
.. math::
Fr = \frac{\text{Inertial Force}}{\text{Gravity Force}}
Examples
--------
>>> Froude(1.83, L=2., g=1.63)
1.0135432593877318
>>> Froude(1.83, L=2., squared=True)
0.17074638128208924
References
----------
.. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,
Eighth Edition. McGraw-Hill Professional, 2007.
.. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and
Applications. Boston: McGraw Hill Higher Education, 2006. | [
"r",
"Calculates",
"Froude",
"number",
"Fr",
"for",
"velocity",
"V",
"and",
"geometric",
"length",
"L",
".",
"If",
"desired",
"gravity",
"can",
"be",
"specified",
"as",
"well",
".",
"Normally",
"the",
"function",
"returns",
"the",
"result",
"of",
"the",
"equation",
"below",
";",
"Froude",
"number",
"is",
"also",
"often",
"said",
"to",
"be",
"defined",
"as",
"the",
"square",
"of",
"the",
"equation",
"below",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/core.py#L1028-L1077 | train |
CalebBell/fluids | fluids/core.py | Stokes_number | def Stokes_number(V, Dp, D, rhop, mu):
r'''Calculates Stokes Number for a given characteristic velocity `V`,
particle diameter `Dp`, characteristic diameter `D`, particle density
`rhop`, and fluid viscosity `mu`.
.. math::
\text{Stk} = \frac{\rho_p V D_p^2}{18\mu_f D}
Parameters
----------
V : float
Characteristic velocity (often superficial), [m/s]
Dp : float
Particle diameter, [m]
D : float
Characteristic diameter (ex demister wire diameter or cyclone
diameter), [m]
rhop : float
Particle density, [kg/m^3]
mu : float
Fluid viscosity, [Pa*s]
Returns
-------
Stk : float
Stokes numer, [-]
Notes
-----
Used in droplet impaction or collection studies.
Examples
--------
>>> Stokes_number(V=0.9, Dp=1E-5, D=1E-3, rhop=1000, mu=1E-5)
0.5
References
----------
.. [1] Rhodes, Martin J. Introduction to Particle Technology. Wiley, 2013.
.. [2] Al-Dughaither, Abdullah S., Ahmed A. Ibrahim, and Waheed A.
Al-Masry. "Investigating Droplet Separation Efficiency in Wire-Mesh Mist
Eliminators in Bubble Column." Journal of Saudi Chemical Society 14, no.
4 (October 1, 2010): 331-39. https://doi.org/10.1016/j.jscs.2010.04.001.
'''
return rhop*V*(Dp*Dp)/(18.0*mu*D) | python | def Stokes_number(V, Dp, D, rhop, mu):
r'''Calculates Stokes Number for a given characteristic velocity `V`,
particle diameter `Dp`, characteristic diameter `D`, particle density
`rhop`, and fluid viscosity `mu`.
.. math::
\text{Stk} = \frac{\rho_p V D_p^2}{18\mu_f D}
Parameters
----------
V : float
Characteristic velocity (often superficial), [m/s]
Dp : float
Particle diameter, [m]
D : float
Characteristic diameter (ex demister wire diameter or cyclone
diameter), [m]
rhop : float
Particle density, [kg/m^3]
mu : float
Fluid viscosity, [Pa*s]
Returns
-------
Stk : float
Stokes numer, [-]
Notes
-----
Used in droplet impaction or collection studies.
Examples
--------
>>> Stokes_number(V=0.9, Dp=1E-5, D=1E-3, rhop=1000, mu=1E-5)
0.5
References
----------
.. [1] Rhodes, Martin J. Introduction to Particle Technology. Wiley, 2013.
.. [2] Al-Dughaither, Abdullah S., Ahmed A. Ibrahim, and Waheed A.
Al-Masry. "Investigating Droplet Separation Efficiency in Wire-Mesh Mist
Eliminators in Bubble Column." Journal of Saudi Chemical Society 14, no.
4 (October 1, 2010): 331-39. https://doi.org/10.1016/j.jscs.2010.04.001.
'''
return rhop*V*(Dp*Dp)/(18.0*mu*D) | [
"def",
"Stokes_number",
"(",
"V",
",",
"Dp",
",",
"D",
",",
"rhop",
",",
"mu",
")",
":",
"return",
"rhop",
"*",
"V",
"*",
"(",
"Dp",
"*",
"Dp",
")",
"/",
"(",
"18.0",
"*",
"mu",
"*",
"D",
")"
]
| r'''Calculates Stokes Number for a given characteristic velocity `V`,
particle diameter `Dp`, characteristic diameter `D`, particle density
`rhop`, and fluid viscosity `mu`.
.. math::
\text{Stk} = \frac{\rho_p V D_p^2}{18\mu_f D}
Parameters
----------
V : float
Characteristic velocity (often superficial), [m/s]
Dp : float
Particle diameter, [m]
D : float
Characteristic diameter (ex demister wire diameter or cyclone
diameter), [m]
rhop : float
Particle density, [kg/m^3]
mu : float
Fluid viscosity, [Pa*s]
Returns
-------
Stk : float
Stokes numer, [-]
Notes
-----
Used in droplet impaction or collection studies.
Examples
--------
>>> Stokes_number(V=0.9, Dp=1E-5, D=1E-3, rhop=1000, mu=1E-5)
0.5
References
----------
.. [1] Rhodes, Martin J. Introduction to Particle Technology. Wiley, 2013.
.. [2] Al-Dughaither, Abdullah S., Ahmed A. Ibrahim, and Waheed A.
Al-Masry. "Investigating Droplet Separation Efficiency in Wire-Mesh Mist
Eliminators in Bubble Column." Journal of Saudi Chemical Society 14, no.
4 (October 1, 2010): 331-39. https://doi.org/10.1016/j.jscs.2010.04.001. | [
"r",
"Calculates",
"Stokes",
"Number",
"for",
"a",
"given",
"characteristic",
"velocity",
"V",
"particle",
"diameter",
"Dp",
"characteristic",
"diameter",
"D",
"particle",
"density",
"rhop",
"and",
"fluid",
"viscosity",
"mu",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/core.py#L1644-L1688 | train |
CalebBell/fluids | fluids/core.py | Suratman | def Suratman(L, rho, mu, sigma):
r'''Calculates Suratman number, `Su`, for a fluid with the given
characteristic length, density, viscosity, and surface tension.
.. math::
\text{Su} = \frac{\rho\sigma L}{\mu^2}
Parameters
----------
L : float
Characteristic length [m]
rho : float
Density of fluid, [kg/m^3]
mu : float
Viscosity of fluid, [Pa*s]
sigma : float
Surface tension, [N/m]
Returns
-------
Su : float
Suratman number []
Notes
-----
Also known as Laplace number. Used in two-phase flow, especially the
bubbly-slug regime. No confusion regarding the definition of this group
has been observed.
.. math::
\text{Su} = \frac{\text{Re}^2}{\text{We}} =\frac{\text{Inertia}\cdot
\text{Surface tension} }{\text{(viscous forces)}^2}
The oldest reference to this group found by the author is in 1963, from
[2]_.
Examples
--------
>>> Suratman(1E-4, 1000., 1E-3, 1E-1)
10000.0
References
----------
.. [1] Sen, Nilava. "Suratman Number in Bubble-to-Slug Flow Pattern
Transition under Microgravity." Acta Astronautica 65, no. 3-4 (August
2009): 423-28. doi:10.1016/j.actaastro.2009.02.013.
.. [2] Catchpole, John P., and George. Fulford. "DIMENSIONLESS GROUPS."
Industrial & Engineering Chemistry 58, no. 3 (March 1, 1966): 46-60.
doi:10.1021/ie50675a012.
'''
return rho*sigma*L/(mu*mu) | python | def Suratman(L, rho, mu, sigma):
r'''Calculates Suratman number, `Su`, for a fluid with the given
characteristic length, density, viscosity, and surface tension.
.. math::
\text{Su} = \frac{\rho\sigma L}{\mu^2}
Parameters
----------
L : float
Characteristic length [m]
rho : float
Density of fluid, [kg/m^3]
mu : float
Viscosity of fluid, [Pa*s]
sigma : float
Surface tension, [N/m]
Returns
-------
Su : float
Suratman number []
Notes
-----
Also known as Laplace number. Used in two-phase flow, especially the
bubbly-slug regime. No confusion regarding the definition of this group
has been observed.
.. math::
\text{Su} = \frac{\text{Re}^2}{\text{We}} =\frac{\text{Inertia}\cdot
\text{Surface tension} }{\text{(viscous forces)}^2}
The oldest reference to this group found by the author is in 1963, from
[2]_.
Examples
--------
>>> Suratman(1E-4, 1000., 1E-3, 1E-1)
10000.0
References
----------
.. [1] Sen, Nilava. "Suratman Number in Bubble-to-Slug Flow Pattern
Transition under Microgravity." Acta Astronautica 65, no. 3-4 (August
2009): 423-28. doi:10.1016/j.actaastro.2009.02.013.
.. [2] Catchpole, John P., and George. Fulford. "DIMENSIONLESS GROUPS."
Industrial & Engineering Chemistry 58, no. 3 (March 1, 1966): 46-60.
doi:10.1021/ie50675a012.
'''
return rho*sigma*L/(mu*mu) | [
"def",
"Suratman",
"(",
"L",
",",
"rho",
",",
"mu",
",",
"sigma",
")",
":",
"return",
"rho",
"*",
"sigma",
"*",
"L",
"/",
"(",
"mu",
"*",
"mu",
")"
]
| r'''Calculates Suratman number, `Su`, for a fluid with the given
characteristic length, density, viscosity, and surface tension.
.. math::
\text{Su} = \frac{\rho\sigma L}{\mu^2}
Parameters
----------
L : float
Characteristic length [m]
rho : float
Density of fluid, [kg/m^3]
mu : float
Viscosity of fluid, [Pa*s]
sigma : float
Surface tension, [N/m]
Returns
-------
Su : float
Suratman number []
Notes
-----
Also known as Laplace number. Used in two-phase flow, especially the
bubbly-slug regime. No confusion regarding the definition of this group
has been observed.
.. math::
\text{Su} = \frac{\text{Re}^2}{\text{We}} =\frac{\text{Inertia}\cdot
\text{Surface tension} }{\text{(viscous forces)}^2}
The oldest reference to this group found by the author is in 1963, from
[2]_.
Examples
--------
>>> Suratman(1E-4, 1000., 1E-3, 1E-1)
10000.0
References
----------
.. [1] Sen, Nilava. "Suratman Number in Bubble-to-Slug Flow Pattern
Transition under Microgravity." Acta Astronautica 65, no. 3-4 (August
2009): 423-28. doi:10.1016/j.actaastro.2009.02.013.
.. [2] Catchpole, John P., and George. Fulford. "DIMENSIONLESS GROUPS."
Industrial & Engineering Chemistry 58, no. 3 (March 1, 1966): 46-60.
doi:10.1021/ie50675a012. | [
"r",
"Calculates",
"Suratman",
"number",
"Su",
"for",
"a",
"fluid",
"with",
"the",
"given",
"characteristic",
"length",
"density",
"viscosity",
"and",
"surface",
"tension",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/core.py#L1828-L1878 | train |
CalebBell/fluids | fluids/core.py | nu_mu_converter | def nu_mu_converter(rho, mu=None, nu=None):
r'''Calculates either kinematic or dynamic viscosity, depending on inputs.
Used when one type of viscosity is known as well as density, to obtain
the other type. Raises an error if both types of viscosity or neither type
of viscosity is provided.
.. math::
\nu = \frac{\mu}{\rho}
.. math::
\mu = \nu\rho
Parameters
----------
rho : float
Density, [kg/m^3]
mu : float, optional
Dynamic viscosity, [Pa*s]
nu : float, optional
Kinematic viscosity, [m^2/s]
Returns
-------
mu or nu : float
Dynamic viscosity, Pa*s or Kinematic viscosity, m^2/s
Examples
--------
>>> nu_mu_converter(998., nu=1.0E-6)
0.000998
References
----------
.. [1] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and
Applications. Boston: McGraw Hill Higher Education, 2006.
'''
if (nu and mu) or not rho or (not nu and not mu):
raise Exception('Inputs must be rho and one of mu and nu.')
if mu:
return mu/rho
elif nu:
return nu*rho | python | def nu_mu_converter(rho, mu=None, nu=None):
r'''Calculates either kinematic or dynamic viscosity, depending on inputs.
Used when one type of viscosity is known as well as density, to obtain
the other type. Raises an error if both types of viscosity or neither type
of viscosity is provided.
.. math::
\nu = \frac{\mu}{\rho}
.. math::
\mu = \nu\rho
Parameters
----------
rho : float
Density, [kg/m^3]
mu : float, optional
Dynamic viscosity, [Pa*s]
nu : float, optional
Kinematic viscosity, [m^2/s]
Returns
-------
mu or nu : float
Dynamic viscosity, Pa*s or Kinematic viscosity, m^2/s
Examples
--------
>>> nu_mu_converter(998., nu=1.0E-6)
0.000998
References
----------
.. [1] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and
Applications. Boston: McGraw Hill Higher Education, 2006.
'''
if (nu and mu) or not rho or (not nu and not mu):
raise Exception('Inputs must be rho and one of mu and nu.')
if mu:
return mu/rho
elif nu:
return nu*rho | [
"def",
"nu_mu_converter",
"(",
"rho",
",",
"mu",
"=",
"None",
",",
"nu",
"=",
"None",
")",
":",
"if",
"(",
"nu",
"and",
"mu",
")",
"or",
"not",
"rho",
"or",
"(",
"not",
"nu",
"and",
"not",
"mu",
")",
":",
"raise",
"Exception",
"(",
"'Inputs must be rho and one of mu and nu.'",
")",
"if",
"mu",
":",
"return",
"mu",
"/",
"rho",
"elif",
"nu",
":",
"return",
"nu",
"*",
"rho"
]
| r'''Calculates either kinematic or dynamic viscosity, depending on inputs.
Used when one type of viscosity is known as well as density, to obtain
the other type. Raises an error if both types of viscosity or neither type
of viscosity is provided.
.. math::
\nu = \frac{\mu}{\rho}
.. math::
\mu = \nu\rho
Parameters
----------
rho : float
Density, [kg/m^3]
mu : float, optional
Dynamic viscosity, [Pa*s]
nu : float, optional
Kinematic viscosity, [m^2/s]
Returns
-------
mu or nu : float
Dynamic viscosity, Pa*s or Kinematic viscosity, m^2/s
Examples
--------
>>> nu_mu_converter(998., nu=1.0E-6)
0.000998
References
----------
.. [1] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and
Applications. Boston: McGraw Hill Higher Education, 2006. | [
"r",
"Calculates",
"either",
"kinematic",
"or",
"dynamic",
"viscosity",
"depending",
"on",
"inputs",
".",
"Used",
"when",
"one",
"type",
"of",
"viscosity",
"is",
"known",
"as",
"well",
"as",
"density",
"to",
"obtain",
"the",
"other",
"type",
".",
"Raises",
"an",
"error",
"if",
"both",
"types",
"of",
"viscosity",
"or",
"neither",
"type",
"of",
"viscosity",
"is",
"provided",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/core.py#L2158-L2199 | train |
CalebBell/fluids | fluids/core.py | Engauge_2d_parser | def Engauge_2d_parser(lines, flat=False):
'''Not exposed function to read a 2D file generated by engauge-digitizer;
for curve fitting.
'''
z_values = []
x_lists = []
y_lists = []
working_xs = []
working_ys = []
new_curve = True
for line in lines:
if line.strip() == '':
new_curve = True
elif new_curve:
z = float(line.split(',')[1])
z_values.append(z)
if working_xs and working_ys:
x_lists.append(working_xs)
y_lists.append(working_ys)
working_xs = []
working_ys = []
new_curve = False
else:
x, y = [float(i) for i in line.strip().split(',')]
working_xs.append(x)
working_ys.append(y)
x_lists.append(working_xs)
y_lists.append(working_ys)
if flat:
all_zs = []
all_xs = []
all_ys = []
for z, xs, ys in zip(z_values, x_lists, y_lists):
for x, y in zip(xs, ys):
all_zs.append(z)
all_xs.append(x)
all_ys.append(y)
return all_zs, all_xs, all_ys
return z_values, x_lists, y_lists | python | def Engauge_2d_parser(lines, flat=False):
'''Not exposed function to read a 2D file generated by engauge-digitizer;
for curve fitting.
'''
z_values = []
x_lists = []
y_lists = []
working_xs = []
working_ys = []
new_curve = True
for line in lines:
if line.strip() == '':
new_curve = True
elif new_curve:
z = float(line.split(',')[1])
z_values.append(z)
if working_xs and working_ys:
x_lists.append(working_xs)
y_lists.append(working_ys)
working_xs = []
working_ys = []
new_curve = False
else:
x, y = [float(i) for i in line.strip().split(',')]
working_xs.append(x)
working_ys.append(y)
x_lists.append(working_xs)
y_lists.append(working_ys)
if flat:
all_zs = []
all_xs = []
all_ys = []
for z, xs, ys in zip(z_values, x_lists, y_lists):
for x, y in zip(xs, ys):
all_zs.append(z)
all_xs.append(x)
all_ys.append(y)
return all_zs, all_xs, all_ys
return z_values, x_lists, y_lists | [
"def",
"Engauge_2d_parser",
"(",
"lines",
",",
"flat",
"=",
"False",
")",
":",
"z_values",
"=",
"[",
"]",
"x_lists",
"=",
"[",
"]",
"y_lists",
"=",
"[",
"]",
"working_xs",
"=",
"[",
"]",
"working_ys",
"=",
"[",
"]",
"new_curve",
"=",
"True",
"for",
"line",
"in",
"lines",
":",
"if",
"line",
".",
"strip",
"(",
")",
"==",
"''",
":",
"new_curve",
"=",
"True",
"elif",
"new_curve",
":",
"z",
"=",
"float",
"(",
"line",
".",
"split",
"(",
"','",
")",
"[",
"1",
"]",
")",
"z_values",
".",
"append",
"(",
"z",
")",
"if",
"working_xs",
"and",
"working_ys",
":",
"x_lists",
".",
"append",
"(",
"working_xs",
")",
"y_lists",
".",
"append",
"(",
"working_ys",
")",
"working_xs",
"=",
"[",
"]",
"working_ys",
"=",
"[",
"]",
"new_curve",
"=",
"False",
"else",
":",
"x",
",",
"y",
"=",
"[",
"float",
"(",
"i",
")",
"for",
"i",
"in",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
"','",
")",
"]",
"working_xs",
".",
"append",
"(",
"x",
")",
"working_ys",
".",
"append",
"(",
"y",
")",
"x_lists",
".",
"append",
"(",
"working_xs",
")",
"y_lists",
".",
"append",
"(",
"working_ys",
")",
"if",
"flat",
":",
"all_zs",
"=",
"[",
"]",
"all_xs",
"=",
"[",
"]",
"all_ys",
"=",
"[",
"]",
"for",
"z",
",",
"xs",
",",
"ys",
"in",
"zip",
"(",
"z_values",
",",
"x_lists",
",",
"y_lists",
")",
":",
"for",
"x",
",",
"y",
"in",
"zip",
"(",
"xs",
",",
"ys",
")",
":",
"all_zs",
".",
"append",
"(",
"z",
")",
"all_xs",
".",
"append",
"(",
"x",
")",
"all_ys",
".",
"append",
"(",
"y",
")",
"return",
"all_zs",
",",
"all_xs",
",",
"all_ys",
"return",
"z_values",
",",
"x_lists",
",",
"y_lists"
]
| Not exposed function to read a 2D file generated by engauge-digitizer;
for curve fitting. | [
"Not",
"exposed",
"function",
"to",
"read",
"a",
"2D",
"file",
"generated",
"by",
"engauge",
"-",
"digitizer",
";",
"for",
"curve",
"fitting",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/core.py#L2869-L2910 | train |
CalebBell/fluids | fluids/compressible.py | isothermal_work_compression | def isothermal_work_compression(P1, P2, T, Z=1):
r'''Calculates the work of compression or expansion of a gas going through
an isothermal process.
.. math::
W = zRT\ln\left(\frac{P_2}{P_1}\right)
Parameters
----------
P1 : float
Inlet pressure, [Pa]
P2 : float
Outlet pressure, [Pa]
T : float
Temperature of the gas going through an isothermal process, [K]
Z : float
Constant compressibility factor of the gas, [-]
Returns
-------
W : float
Work performed per mole of gas compressed/expanded [J/mol]
Notes
-----
The full derivation with all forms is as follows:
.. math::
W = \int_{P_1}^{P_2} V dP = zRT\int_{P_1}^{P_2} \frac{1}{P} dP
.. math::
W = zRT\ln\left(\frac{P_2}{P_1}\right) = P_1 V_1 \ln\left(\frac{P_2}
{P_1}\right) = P_2 V_2 \ln\left(\frac{P_2}{P_1}\right)
The substitutions are according to the ideal gas law with compressibility:
.. math:
PV = ZRT
The work of compression/expansion is the change in enthalpy of the gas.
Returns negative values for expansion and positive values for compression.
An average compressibility factor can be used where Z changes. For further
accuracy, this expression can be used repeatedly with small changes in
pressure and the work from each step summed.
This is the best possible case for compression; all actual compresssors
require more work to do the compression.
By making the compression take a large number of stages and cooling the gas
between stages, this can be approached reasonable closely. Integrally
geared compressors are often used for this purpose.
Examples
--------
>>> isothermal_work_compression(1E5, 1E6, 300)
5743.427304244769
References
----------
.. [1] Couper, James R., W. Roy Penney, and James R. Fair. Chemical Process
Equipment: Selection and Design. 2nd ed. Amsterdam ; Boston: Gulf
Professional Publishing, 2009.
'''
return Z*R*T*log(P2/P1) | python | def isothermal_work_compression(P1, P2, T, Z=1):
r'''Calculates the work of compression or expansion of a gas going through
an isothermal process.
.. math::
W = zRT\ln\left(\frac{P_2}{P_1}\right)
Parameters
----------
P1 : float
Inlet pressure, [Pa]
P2 : float
Outlet pressure, [Pa]
T : float
Temperature of the gas going through an isothermal process, [K]
Z : float
Constant compressibility factor of the gas, [-]
Returns
-------
W : float
Work performed per mole of gas compressed/expanded [J/mol]
Notes
-----
The full derivation with all forms is as follows:
.. math::
W = \int_{P_1}^{P_2} V dP = zRT\int_{P_1}^{P_2} \frac{1}{P} dP
.. math::
W = zRT\ln\left(\frac{P_2}{P_1}\right) = P_1 V_1 \ln\left(\frac{P_2}
{P_1}\right) = P_2 V_2 \ln\left(\frac{P_2}{P_1}\right)
The substitutions are according to the ideal gas law with compressibility:
.. math:
PV = ZRT
The work of compression/expansion is the change in enthalpy of the gas.
Returns negative values for expansion and positive values for compression.
An average compressibility factor can be used where Z changes. For further
accuracy, this expression can be used repeatedly with small changes in
pressure and the work from each step summed.
This is the best possible case for compression; all actual compresssors
require more work to do the compression.
By making the compression take a large number of stages and cooling the gas
between stages, this can be approached reasonable closely. Integrally
geared compressors are often used for this purpose.
Examples
--------
>>> isothermal_work_compression(1E5, 1E6, 300)
5743.427304244769
References
----------
.. [1] Couper, James R., W. Roy Penney, and James R. Fair. Chemical Process
Equipment: Selection and Design. 2nd ed. Amsterdam ; Boston: Gulf
Professional Publishing, 2009.
'''
return Z*R*T*log(P2/P1) | [
"def",
"isothermal_work_compression",
"(",
"P1",
",",
"P2",
",",
"T",
",",
"Z",
"=",
"1",
")",
":",
"return",
"Z",
"*",
"R",
"*",
"T",
"*",
"log",
"(",
"P2",
"/",
"P1",
")"
]
| r'''Calculates the work of compression or expansion of a gas going through
an isothermal process.
.. math::
W = zRT\ln\left(\frac{P_2}{P_1}\right)
Parameters
----------
P1 : float
Inlet pressure, [Pa]
P2 : float
Outlet pressure, [Pa]
T : float
Temperature of the gas going through an isothermal process, [K]
Z : float
Constant compressibility factor of the gas, [-]
Returns
-------
W : float
Work performed per mole of gas compressed/expanded [J/mol]
Notes
-----
The full derivation with all forms is as follows:
.. math::
W = \int_{P_1}^{P_2} V dP = zRT\int_{P_1}^{P_2} \frac{1}{P} dP
.. math::
W = zRT\ln\left(\frac{P_2}{P_1}\right) = P_1 V_1 \ln\left(\frac{P_2}
{P_1}\right) = P_2 V_2 \ln\left(\frac{P_2}{P_1}\right)
The substitutions are according to the ideal gas law with compressibility:
.. math:
PV = ZRT
The work of compression/expansion is the change in enthalpy of the gas.
Returns negative values for expansion and positive values for compression.
An average compressibility factor can be used where Z changes. For further
accuracy, this expression can be used repeatedly with small changes in
pressure and the work from each step summed.
This is the best possible case for compression; all actual compresssors
require more work to do the compression.
By making the compression take a large number of stages and cooling the gas
between stages, this can be approached reasonable closely. Integrally
geared compressors are often used for this purpose.
Examples
--------
>>> isothermal_work_compression(1E5, 1E6, 300)
5743.427304244769
References
----------
.. [1] Couper, James R., W. Roy Penney, and James R. Fair. Chemical Process
Equipment: Selection and Design. 2nd ed. Amsterdam ; Boston: Gulf
Professional Publishing, 2009. | [
"r",
"Calculates",
"the",
"work",
"of",
"compression",
"or",
"expansion",
"of",
"a",
"gas",
"going",
"through",
"an",
"isothermal",
"process",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/compressible.py#L38-L102 | train |
CalebBell/fluids | fluids/compressible.py | isentropic_T_rise_compression | def isentropic_T_rise_compression(T1, P1, P2, k, eta=1):
r'''Calculates the increase in temperature of a fluid which is compressed
or expanded under isentropic, adiabatic conditions assuming constant
Cp and Cv. The polytropic model is the same equation; just provide `n`
instead of `k` and use a polytropic efficienty for `eta` instead of a
isentropic efficiency.
.. math::
T_2 = T_1 + \frac{\Delta T_s}{\eta_s} = T_1 \left\{1 + \frac{1}
{\eta_s}\left[\left(\frac{P_2}{P_1}\right)^{(k-1)/k}-1\right]\right\}
Parameters
----------
T1 : float
Initial temperature of gas [K]
P1 : float
Initial pressure of gas [Pa]
P2 : float
Final pressure of gas [Pa]
k : float
Isentropic exponent of the gas (Cp/Cv) or polytropic exponent `n` to
use this as a polytropic model instead [-]
eta : float
Isentropic efficiency of the process or polytropic efficiency of the
process to use this as a polytropic model instead [-]
Returns
-------
T2 : float
Final temperature of gas [K]
Notes
-----
For the ideal case (`eta`=1), the model simplifies to:
.. math::
\frac{T_2}{T_1} = \left(\frac{P_2}{P_1}\right)^{(k-1)/k}
Examples
--------
>>> isentropic_T_rise_compression(286.8, 54050, 432400, 1.4)
519.5230938217768
References
----------
.. [1] Couper, James R., W. Roy Penney, and James R. Fair. Chemical Process
Equipment: Selection and Design. 2nd ed. Amsterdam ; Boston: Gulf
Professional Publishing, 2009.
.. [2] GPSA. GPSA Engineering Data Book. 13th edition. Gas Processors
Suppliers Association, Tulsa, OK, 2012.
'''
dT = T1*((P2/P1)**((k - 1.0)/k) - 1.0)/eta
return T1 + dT | python | def isentropic_T_rise_compression(T1, P1, P2, k, eta=1):
r'''Calculates the increase in temperature of a fluid which is compressed
or expanded under isentropic, adiabatic conditions assuming constant
Cp and Cv. The polytropic model is the same equation; just provide `n`
instead of `k` and use a polytropic efficienty for `eta` instead of a
isentropic efficiency.
.. math::
T_2 = T_1 + \frac{\Delta T_s}{\eta_s} = T_1 \left\{1 + \frac{1}
{\eta_s}\left[\left(\frac{P_2}{P_1}\right)^{(k-1)/k}-1\right]\right\}
Parameters
----------
T1 : float
Initial temperature of gas [K]
P1 : float
Initial pressure of gas [Pa]
P2 : float
Final pressure of gas [Pa]
k : float
Isentropic exponent of the gas (Cp/Cv) or polytropic exponent `n` to
use this as a polytropic model instead [-]
eta : float
Isentropic efficiency of the process or polytropic efficiency of the
process to use this as a polytropic model instead [-]
Returns
-------
T2 : float
Final temperature of gas [K]
Notes
-----
For the ideal case (`eta`=1), the model simplifies to:
.. math::
\frac{T_2}{T_1} = \left(\frac{P_2}{P_1}\right)^{(k-1)/k}
Examples
--------
>>> isentropic_T_rise_compression(286.8, 54050, 432400, 1.4)
519.5230938217768
References
----------
.. [1] Couper, James R., W. Roy Penney, and James R. Fair. Chemical Process
Equipment: Selection and Design. 2nd ed. Amsterdam ; Boston: Gulf
Professional Publishing, 2009.
.. [2] GPSA. GPSA Engineering Data Book. 13th edition. Gas Processors
Suppliers Association, Tulsa, OK, 2012.
'''
dT = T1*((P2/P1)**((k - 1.0)/k) - 1.0)/eta
return T1 + dT | [
"def",
"isentropic_T_rise_compression",
"(",
"T1",
",",
"P1",
",",
"P2",
",",
"k",
",",
"eta",
"=",
"1",
")",
":",
"dT",
"=",
"T1",
"*",
"(",
"(",
"P2",
"/",
"P1",
")",
"**",
"(",
"(",
"k",
"-",
"1.0",
")",
"/",
"k",
")",
"-",
"1.0",
")",
"/",
"eta",
"return",
"T1",
"+",
"dT"
]
| r'''Calculates the increase in temperature of a fluid which is compressed
or expanded under isentropic, adiabatic conditions assuming constant
Cp and Cv. The polytropic model is the same equation; just provide `n`
instead of `k` and use a polytropic efficienty for `eta` instead of a
isentropic efficiency.
.. math::
T_2 = T_1 + \frac{\Delta T_s}{\eta_s} = T_1 \left\{1 + \frac{1}
{\eta_s}\left[\left(\frac{P_2}{P_1}\right)^{(k-1)/k}-1\right]\right\}
Parameters
----------
T1 : float
Initial temperature of gas [K]
P1 : float
Initial pressure of gas [Pa]
P2 : float
Final pressure of gas [Pa]
k : float
Isentropic exponent of the gas (Cp/Cv) or polytropic exponent `n` to
use this as a polytropic model instead [-]
eta : float
Isentropic efficiency of the process or polytropic efficiency of the
process to use this as a polytropic model instead [-]
Returns
-------
T2 : float
Final temperature of gas [K]
Notes
-----
For the ideal case (`eta`=1), the model simplifies to:
.. math::
\frac{T_2}{T_1} = \left(\frac{P_2}{P_1}\right)^{(k-1)/k}
Examples
--------
>>> isentropic_T_rise_compression(286.8, 54050, 432400, 1.4)
519.5230938217768
References
----------
.. [1] Couper, James R., W. Roy Penney, and James R. Fair. Chemical Process
Equipment: Selection and Design. 2nd ed. Amsterdam ; Boston: Gulf
Professional Publishing, 2009.
.. [2] GPSA. GPSA Engineering Data Book. 13th edition. Gas Processors
Suppliers Association, Tulsa, OK, 2012. | [
"r",
"Calculates",
"the",
"increase",
"in",
"temperature",
"of",
"a",
"fluid",
"which",
"is",
"compressed",
"or",
"expanded",
"under",
"isentropic",
"adiabatic",
"conditions",
"assuming",
"constant",
"Cp",
"and",
"Cv",
".",
"The",
"polytropic",
"model",
"is",
"the",
"same",
"equation",
";",
"just",
"provide",
"n",
"instead",
"of",
"k",
"and",
"use",
"a",
"polytropic",
"efficienty",
"for",
"eta",
"instead",
"of",
"a",
"isentropic",
"efficiency",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/compressible.py#L212-L264 | train |
CalebBell/fluids | fluids/compressible.py | isentropic_efficiency | def isentropic_efficiency(P1, P2, k, eta_s=None, eta_p=None):
r'''Calculates either isentropic or polytropic efficiency from the other
type of efficiency.
.. math::
\eta_s = \frac{(P_2/P_1)^{(k-1)/k}-1}
{(P_2/P_1)^{\frac{k-1}{k\eta_p}}-1}
.. math::
\eta_p = \frac{\left(k - 1\right) \log{\left (\frac{P_{2}}{P_{1}}
\right )}}{k \log{\left (\frac{1}{\eta_{s}} \left(\eta_{s}
+ \left(\frac{P_{2}}{P_{1}}\right)^{\frac{1}{k} \left(k - 1\right)}
- 1\right) \right )}}
Parameters
----------
P1 : float
Initial pressure of gas [Pa]
P2 : float
Final pressure of gas [Pa]
k : float
Isentropic exponent of the gas (Cp/Cv) [-]
eta_s : float, optional
Isentropic (adiabatic) efficiency of the process, [-]
eta_p : float, optional
Polytropic efficiency of the process, [-]
Returns
-------
eta_s or eta_p : float
Isentropic or polytropic efficiency, depending on input, [-]
Notes
-----
The form for obtained `eta_p` from `eta_s` was derived with SymPy.
Examples
--------
>>> isentropic_efficiency(1E5, 1E6, 1.4, eta_p=0.78)
0.7027614191263858
References
----------
.. [1] Couper, James R., W. Roy Penney, and James R. Fair. Chemical Process
Equipment: Selection and Design. 2nd ed. Amsterdam ; Boston: Gulf
Professional Publishing, 2009.
'''
if eta_s is None and eta_p:
return ((P2/P1)**((k-1.0)/k)-1.0)/((P2/P1)**((k-1.0)/(k*eta_p))-1.0)
elif eta_p is None and eta_s:
return (k - 1.0)*log(P2/P1)/(k*log(
(eta_s + (P2/P1)**((k - 1.0)/k) - 1.0)/eta_s))
else:
raise Exception('Either eta_s or eta_p is required') | python | def isentropic_efficiency(P1, P2, k, eta_s=None, eta_p=None):
r'''Calculates either isentropic or polytropic efficiency from the other
type of efficiency.
.. math::
\eta_s = \frac{(P_2/P_1)^{(k-1)/k}-1}
{(P_2/P_1)^{\frac{k-1}{k\eta_p}}-1}
.. math::
\eta_p = \frac{\left(k - 1\right) \log{\left (\frac{P_{2}}{P_{1}}
\right )}}{k \log{\left (\frac{1}{\eta_{s}} \left(\eta_{s}
+ \left(\frac{P_{2}}{P_{1}}\right)^{\frac{1}{k} \left(k - 1\right)}
- 1\right) \right )}}
Parameters
----------
P1 : float
Initial pressure of gas [Pa]
P2 : float
Final pressure of gas [Pa]
k : float
Isentropic exponent of the gas (Cp/Cv) [-]
eta_s : float, optional
Isentropic (adiabatic) efficiency of the process, [-]
eta_p : float, optional
Polytropic efficiency of the process, [-]
Returns
-------
eta_s or eta_p : float
Isentropic or polytropic efficiency, depending on input, [-]
Notes
-----
The form for obtained `eta_p` from `eta_s` was derived with SymPy.
Examples
--------
>>> isentropic_efficiency(1E5, 1E6, 1.4, eta_p=0.78)
0.7027614191263858
References
----------
.. [1] Couper, James R., W. Roy Penney, and James R. Fair. Chemical Process
Equipment: Selection and Design. 2nd ed. Amsterdam ; Boston: Gulf
Professional Publishing, 2009.
'''
if eta_s is None and eta_p:
return ((P2/P1)**((k-1.0)/k)-1.0)/((P2/P1)**((k-1.0)/(k*eta_p))-1.0)
elif eta_p is None and eta_s:
return (k - 1.0)*log(P2/P1)/(k*log(
(eta_s + (P2/P1)**((k - 1.0)/k) - 1.0)/eta_s))
else:
raise Exception('Either eta_s or eta_p is required') | [
"def",
"isentropic_efficiency",
"(",
"P1",
",",
"P2",
",",
"k",
",",
"eta_s",
"=",
"None",
",",
"eta_p",
"=",
"None",
")",
":",
"if",
"eta_s",
"is",
"None",
"and",
"eta_p",
":",
"return",
"(",
"(",
"P2",
"/",
"P1",
")",
"**",
"(",
"(",
"k",
"-",
"1.0",
")",
"/",
"k",
")",
"-",
"1.0",
")",
"/",
"(",
"(",
"P2",
"/",
"P1",
")",
"**",
"(",
"(",
"k",
"-",
"1.0",
")",
"/",
"(",
"k",
"*",
"eta_p",
")",
")",
"-",
"1.0",
")",
"elif",
"eta_p",
"is",
"None",
"and",
"eta_s",
":",
"return",
"(",
"k",
"-",
"1.0",
")",
"*",
"log",
"(",
"P2",
"/",
"P1",
")",
"/",
"(",
"k",
"*",
"log",
"(",
"(",
"eta_s",
"+",
"(",
"P2",
"/",
"P1",
")",
"**",
"(",
"(",
"k",
"-",
"1.0",
")",
"/",
"k",
")",
"-",
"1.0",
")",
"/",
"eta_s",
")",
")",
"else",
":",
"raise",
"Exception",
"(",
"'Either eta_s or eta_p is required'",
")"
]
| r'''Calculates either isentropic or polytropic efficiency from the other
type of efficiency.
.. math::
\eta_s = \frac{(P_2/P_1)^{(k-1)/k}-1}
{(P_2/P_1)^{\frac{k-1}{k\eta_p}}-1}
.. math::
\eta_p = \frac{\left(k - 1\right) \log{\left (\frac{P_{2}}{P_{1}}
\right )}}{k \log{\left (\frac{1}{\eta_{s}} \left(\eta_{s}
+ \left(\frac{P_{2}}{P_{1}}\right)^{\frac{1}{k} \left(k - 1\right)}
- 1\right) \right )}}
Parameters
----------
P1 : float
Initial pressure of gas [Pa]
P2 : float
Final pressure of gas [Pa]
k : float
Isentropic exponent of the gas (Cp/Cv) [-]
eta_s : float, optional
Isentropic (adiabatic) efficiency of the process, [-]
eta_p : float, optional
Polytropic efficiency of the process, [-]
Returns
-------
eta_s or eta_p : float
Isentropic or polytropic efficiency, depending on input, [-]
Notes
-----
The form for obtained `eta_p` from `eta_s` was derived with SymPy.
Examples
--------
>>> isentropic_efficiency(1E5, 1E6, 1.4, eta_p=0.78)
0.7027614191263858
References
----------
.. [1] Couper, James R., W. Roy Penney, and James R. Fair. Chemical Process
Equipment: Selection and Design. 2nd ed. Amsterdam ; Boston: Gulf
Professional Publishing, 2009. | [
"r",
"Calculates",
"either",
"isentropic",
"or",
"polytropic",
"efficiency",
"from",
"the",
"other",
"type",
"of",
"efficiency",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/compressible.py#L267-L320 | train |
CalebBell/fluids | fluids/compressible.py | P_isothermal_critical_flow | def P_isothermal_critical_flow(P, fd, D, L):
r'''Calculates critical flow pressure `Pcf` for a fluid flowing
isothermally and suffering pressure drop caused by a pipe's friction factor.
.. math::
P_2 = P_{1} e^{\frac{1}{2 D} \left(D \left(\operatorname{LambertW}
{\left (- e^{\frac{1}{D} \left(- D - L f_d\right)} \right )} + 1\right)
+ L f_d\right)}
Parameters
----------
P : float
Inlet pressure [Pa]
fd : float
Darcy friction factor for flow in pipe [-]
D : float
Diameter of pipe, [m]
L : float
Length of pipe, [m]
Returns
-------
Pcf : float
Critical flow pressure of a compressible gas flowing from `P1` to `Pcf`
in a tube of length L and friction factor `fd` [Pa]
Notes
-----
Assumes isothermal flow. Developed based on the `isothermal_gas` model,
using SymPy.
The isothermal gas model is solved for maximum mass flow rate; any pressure
drop under it is impossible due to the formation of a shock wave.
Examples
--------
>>> P_isothermal_critical_flow(P=1E6, fd=0.00185, L=1000., D=0.5)
389699.7317645518
References
----------
.. [1] Wilkes, James O. Fluid Mechanics for Chemical Engineers with
Microfluidics and CFD. 2 edition. Upper Saddle River, NJ: Prentice Hall,
2005.
'''
# Correct branch of lambertw found by trial and error
lambert_term = float(lambertw(-exp((-D - L*fd)/D), -1).real)
return P*exp((D*(lambert_term + 1.0) + L*fd)/(2.0*D)) | python | def P_isothermal_critical_flow(P, fd, D, L):
r'''Calculates critical flow pressure `Pcf` for a fluid flowing
isothermally and suffering pressure drop caused by a pipe's friction factor.
.. math::
P_2 = P_{1} e^{\frac{1}{2 D} \left(D \left(\operatorname{LambertW}
{\left (- e^{\frac{1}{D} \left(- D - L f_d\right)} \right )} + 1\right)
+ L f_d\right)}
Parameters
----------
P : float
Inlet pressure [Pa]
fd : float
Darcy friction factor for flow in pipe [-]
D : float
Diameter of pipe, [m]
L : float
Length of pipe, [m]
Returns
-------
Pcf : float
Critical flow pressure of a compressible gas flowing from `P1` to `Pcf`
in a tube of length L and friction factor `fd` [Pa]
Notes
-----
Assumes isothermal flow. Developed based on the `isothermal_gas` model,
using SymPy.
The isothermal gas model is solved for maximum mass flow rate; any pressure
drop under it is impossible due to the formation of a shock wave.
Examples
--------
>>> P_isothermal_critical_flow(P=1E6, fd=0.00185, L=1000., D=0.5)
389699.7317645518
References
----------
.. [1] Wilkes, James O. Fluid Mechanics for Chemical Engineers with
Microfluidics and CFD. 2 edition. Upper Saddle River, NJ: Prentice Hall,
2005.
'''
# Correct branch of lambertw found by trial and error
lambert_term = float(lambertw(-exp((-D - L*fd)/D), -1).real)
return P*exp((D*(lambert_term + 1.0) + L*fd)/(2.0*D)) | [
"def",
"P_isothermal_critical_flow",
"(",
"P",
",",
"fd",
",",
"D",
",",
"L",
")",
":",
"# Correct branch of lambertw found by trial and error",
"lambert_term",
"=",
"float",
"(",
"lambertw",
"(",
"-",
"exp",
"(",
"(",
"-",
"D",
"-",
"L",
"*",
"fd",
")",
"/",
"D",
")",
",",
"-",
"1",
")",
".",
"real",
")",
"return",
"P",
"*",
"exp",
"(",
"(",
"D",
"*",
"(",
"lambert_term",
"+",
"1.0",
")",
"+",
"L",
"*",
"fd",
")",
"/",
"(",
"2.0",
"*",
"D",
")",
")"
]
| r'''Calculates critical flow pressure `Pcf` for a fluid flowing
isothermally and suffering pressure drop caused by a pipe's friction factor.
.. math::
P_2 = P_{1} e^{\frac{1}{2 D} \left(D \left(\operatorname{LambertW}
{\left (- e^{\frac{1}{D} \left(- D - L f_d\right)} \right )} + 1\right)
+ L f_d\right)}
Parameters
----------
P : float
Inlet pressure [Pa]
fd : float
Darcy friction factor for flow in pipe [-]
D : float
Diameter of pipe, [m]
L : float
Length of pipe, [m]
Returns
-------
Pcf : float
Critical flow pressure of a compressible gas flowing from `P1` to `Pcf`
in a tube of length L and friction factor `fd` [Pa]
Notes
-----
Assumes isothermal flow. Developed based on the `isothermal_gas` model,
using SymPy.
The isothermal gas model is solved for maximum mass flow rate; any pressure
drop under it is impossible due to the formation of a shock wave.
Examples
--------
>>> P_isothermal_critical_flow(P=1E6, fd=0.00185, L=1000., D=0.5)
389699.7317645518
References
----------
.. [1] Wilkes, James O. Fluid Mechanics for Chemical Engineers with
Microfluidics and CFD. 2 edition. Upper Saddle River, NJ: Prentice Hall,
2005. | [
"r",
"Calculates",
"critical",
"flow",
"pressure",
"Pcf",
"for",
"a",
"fluid",
"flowing",
"isothermally",
"and",
"suffering",
"pressure",
"drop",
"caused",
"by",
"a",
"pipe",
"s",
"friction",
"factor",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/compressible.py#L452-L499 | train |
CalebBell/fluids | fluids/compressible.py | P_upstream_isothermal_critical_flow | def P_upstream_isothermal_critical_flow(P, fd, D, L):
'''Not part of the public API. Reverses `P_isothermal_critical_flow`.
Examples
--------
>>> P_upstream_isothermal_critical_flow(P=389699.7317645518, fd=0.00185,
... L=1000., D=0.5)
1000000.0000000001
'''
lambertw_term = float(lambertw(-exp(-(fd*L+D)/D), -1).real)
return exp(-0.5*(D*lambertw_term+fd*L+D)/D)*P | python | def P_upstream_isothermal_critical_flow(P, fd, D, L):
'''Not part of the public API. Reverses `P_isothermal_critical_flow`.
Examples
--------
>>> P_upstream_isothermal_critical_flow(P=389699.7317645518, fd=0.00185,
... L=1000., D=0.5)
1000000.0000000001
'''
lambertw_term = float(lambertw(-exp(-(fd*L+D)/D), -1).real)
return exp(-0.5*(D*lambertw_term+fd*L+D)/D)*P | [
"def",
"P_upstream_isothermal_critical_flow",
"(",
"P",
",",
"fd",
",",
"D",
",",
"L",
")",
":",
"lambertw_term",
"=",
"float",
"(",
"lambertw",
"(",
"-",
"exp",
"(",
"-",
"(",
"fd",
"*",
"L",
"+",
"D",
")",
"/",
"D",
")",
",",
"-",
"1",
")",
".",
"real",
")",
"return",
"exp",
"(",
"-",
"0.5",
"*",
"(",
"D",
"*",
"lambertw_term",
"+",
"fd",
"*",
"L",
"+",
"D",
")",
"/",
"D",
")",
"*",
"P"
]
| Not part of the public API. Reverses `P_isothermal_critical_flow`.
Examples
--------
>>> P_upstream_isothermal_critical_flow(P=389699.7317645518, fd=0.00185,
... L=1000., D=0.5)
1000000.0000000001 | [
"Not",
"part",
"of",
"the",
"public",
"API",
".",
"Reverses",
"P_isothermal_critical_flow",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/compressible.py#L502-L512 | train |
CalebBell/fluids | fluids/compressible.py | is_critical_flow | def is_critical_flow(P1, P2, k):
r'''Determines if a flow of a fluid driven by pressure gradient
P1 - P2 is critical, for a fluid with the given isentropic coefficient.
This function calculates critical flow pressure, and checks if this is
larger than P2. If so, the flow is critical and choked.
Parameters
----------
P1 : float
Higher, source pressure [Pa]
P2 : float
Lower, downstream pressure [Pa]
k : float
Isentropic coefficient []
Returns
-------
flowtype : bool
True if the flow is choked; otherwise False
Notes
-----
Assumes isentropic flow. Uses P_critical_flow function.
Examples
--------
Examples 1-2 from API 520.
>>> is_critical_flow(670E3, 532E3, 1.11)
False
>>> is_critical_flow(670E3, 101E3, 1.11)
True
References
----------
.. [1] API. 2014. API 520 - Part 1 Sizing, Selection, and Installation of
Pressure-relieving Devices, Part I - Sizing and Selection, 9E.
'''
Pcf = P_critical_flow(P1, k)
return Pcf > P2 | python | def is_critical_flow(P1, P2, k):
r'''Determines if a flow of a fluid driven by pressure gradient
P1 - P2 is critical, for a fluid with the given isentropic coefficient.
This function calculates critical flow pressure, and checks if this is
larger than P2. If so, the flow is critical and choked.
Parameters
----------
P1 : float
Higher, source pressure [Pa]
P2 : float
Lower, downstream pressure [Pa]
k : float
Isentropic coefficient []
Returns
-------
flowtype : bool
True if the flow is choked; otherwise False
Notes
-----
Assumes isentropic flow. Uses P_critical_flow function.
Examples
--------
Examples 1-2 from API 520.
>>> is_critical_flow(670E3, 532E3, 1.11)
False
>>> is_critical_flow(670E3, 101E3, 1.11)
True
References
----------
.. [1] API. 2014. API 520 - Part 1 Sizing, Selection, and Installation of
Pressure-relieving Devices, Part I - Sizing and Selection, 9E.
'''
Pcf = P_critical_flow(P1, k)
return Pcf > P2 | [
"def",
"is_critical_flow",
"(",
"P1",
",",
"P2",
",",
"k",
")",
":",
"Pcf",
"=",
"P_critical_flow",
"(",
"P1",
",",
"k",
")",
"return",
"Pcf",
">",
"P2"
]
| r'''Determines if a flow of a fluid driven by pressure gradient
P1 - P2 is critical, for a fluid with the given isentropic coefficient.
This function calculates critical flow pressure, and checks if this is
larger than P2. If so, the flow is critical and choked.
Parameters
----------
P1 : float
Higher, source pressure [Pa]
P2 : float
Lower, downstream pressure [Pa]
k : float
Isentropic coefficient []
Returns
-------
flowtype : bool
True if the flow is choked; otherwise False
Notes
-----
Assumes isentropic flow. Uses P_critical_flow function.
Examples
--------
Examples 1-2 from API 520.
>>> is_critical_flow(670E3, 532E3, 1.11)
False
>>> is_critical_flow(670E3, 101E3, 1.11)
True
References
----------
.. [1] API. 2014. API 520 - Part 1 Sizing, Selection, and Installation of
Pressure-relieving Devices, Part I - Sizing and Selection, 9E. | [
"r",
"Determines",
"if",
"a",
"flow",
"of",
"a",
"fluid",
"driven",
"by",
"pressure",
"gradient",
"P1",
"-",
"P2",
"is",
"critical",
"for",
"a",
"fluid",
"with",
"the",
"given",
"isentropic",
"coefficient",
".",
"This",
"function",
"calculates",
"critical",
"flow",
"pressure",
"and",
"checks",
"if",
"this",
"is",
"larger",
"than",
"P2",
".",
"If",
"so",
"the",
"flow",
"is",
"critical",
"and",
"choked",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/compressible.py#L515-L554 | train |
CalebBell/fluids | fluids/friction.py | one_phase_dP | def one_phase_dP(m, rho, mu, D, roughness=0, L=1, Method=None):
r'''Calculates single-phase pressure drop. This is a wrapper
around other methods.
Parameters
----------
m : float
Mass flow rate of fluid, [kg/s]
rho : float
Density of fluid, [kg/m^3]
mu : float
Viscosity of fluid, [Pa*s]
D : float
Diameter of pipe, [m]
roughness : float, optional
Roughness of pipe for use in calculating friction factor, [m]
L : float, optional
Length of pipe, [m]
Method : string, optional
A string of the function name to use
Returns
-------
dP : float
Pressure drop of the single-phase flow, [Pa]
Notes
-----
Examples
--------
>>> one_phase_dP(10.0, 1000, 1E-5, .1, L=1)
63.43447321097365
References
----------
.. [1] Crane Co. Flow of Fluids Through Valves, Fittings, and Pipe. Crane,
2009.
'''
D2 = D*D
V = m/(0.25*pi*D2*rho)
Re = Reynolds(V=V, rho=rho, mu=mu, D=D)
fd = friction_factor(Re=Re, eD=roughness/D, Method=Method)
dP = fd*L/D*(0.5*rho*V*V)
return dP | python | def one_phase_dP(m, rho, mu, D, roughness=0, L=1, Method=None):
r'''Calculates single-phase pressure drop. This is a wrapper
around other methods.
Parameters
----------
m : float
Mass flow rate of fluid, [kg/s]
rho : float
Density of fluid, [kg/m^3]
mu : float
Viscosity of fluid, [Pa*s]
D : float
Diameter of pipe, [m]
roughness : float, optional
Roughness of pipe for use in calculating friction factor, [m]
L : float, optional
Length of pipe, [m]
Method : string, optional
A string of the function name to use
Returns
-------
dP : float
Pressure drop of the single-phase flow, [Pa]
Notes
-----
Examples
--------
>>> one_phase_dP(10.0, 1000, 1E-5, .1, L=1)
63.43447321097365
References
----------
.. [1] Crane Co. Flow of Fluids Through Valves, Fittings, and Pipe. Crane,
2009.
'''
D2 = D*D
V = m/(0.25*pi*D2*rho)
Re = Reynolds(V=V, rho=rho, mu=mu, D=D)
fd = friction_factor(Re=Re, eD=roughness/D, Method=Method)
dP = fd*L/D*(0.5*rho*V*V)
return dP | [
"def",
"one_phase_dP",
"(",
"m",
",",
"rho",
",",
"mu",
",",
"D",
",",
"roughness",
"=",
"0",
",",
"L",
"=",
"1",
",",
"Method",
"=",
"None",
")",
":",
"D2",
"=",
"D",
"*",
"D",
"V",
"=",
"m",
"/",
"(",
"0.25",
"*",
"pi",
"*",
"D2",
"*",
"rho",
")",
"Re",
"=",
"Reynolds",
"(",
"V",
"=",
"V",
",",
"rho",
"=",
"rho",
",",
"mu",
"=",
"mu",
",",
"D",
"=",
"D",
")",
"fd",
"=",
"friction_factor",
"(",
"Re",
"=",
"Re",
",",
"eD",
"=",
"roughness",
"/",
"D",
",",
"Method",
"=",
"Method",
")",
"dP",
"=",
"fd",
"*",
"L",
"/",
"D",
"*",
"(",
"0.5",
"*",
"rho",
"*",
"V",
"*",
"V",
")",
"return",
"dP"
]
| r'''Calculates single-phase pressure drop. This is a wrapper
around other methods.
Parameters
----------
m : float
Mass flow rate of fluid, [kg/s]
rho : float
Density of fluid, [kg/m^3]
mu : float
Viscosity of fluid, [Pa*s]
D : float
Diameter of pipe, [m]
roughness : float, optional
Roughness of pipe for use in calculating friction factor, [m]
L : float, optional
Length of pipe, [m]
Method : string, optional
A string of the function name to use
Returns
-------
dP : float
Pressure drop of the single-phase flow, [Pa]
Notes
-----
Examples
--------
>>> one_phase_dP(10.0, 1000, 1E-5, .1, L=1)
63.43447321097365
References
----------
.. [1] Crane Co. Flow of Fluids Through Valves, Fittings, and Pipe. Crane,
2009. | [
"r",
"Calculates",
"single",
"-",
"phase",
"pressure",
"drop",
".",
"This",
"is",
"a",
"wrapper",
"around",
"other",
"methods",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/friction.py#L3874-L3918 | train |
CalebBell/fluids | fluids/flow_meter.py | discharge_coefficient_to_K | def discharge_coefficient_to_K(D, Do, C):
r'''Converts a discharge coefficient to a standard loss coefficient,
for use in computation of the actual pressure drop of an orifice or other
device.
.. math::
K = \left[\frac{\sqrt{1-\beta^4(1-C^2)}}{C\beta^2} - 1\right]^2
Parameters
----------
D : float
Upstream internal pipe diameter, [m]
Do : float
Diameter of orifice at flow conditions, [m]
C : float
Coefficient of discharge of the orifice, [-]
Returns
-------
K : float
Loss coefficient with respect to the velocity and density of the fluid
just upstream of the orifice, [-]
Notes
-----
If expansibility is used in the orifice calculation, the result will not
match with the specified pressure drop formula in [1]_; it can almost
be matched by dividing the calculated mass flow by the expansibility factor
and using that mass flow with the loss coefficient.
Examples
--------
>>> discharge_coefficient_to_K(D=0.07366, Do=0.05, C=0.61512)
5.2314291729754
References
----------
.. [1] American Society of Mechanical Engineers. Mfc-3M-2004 Measurement
Of Fluid Flow In Pipes Using Orifice, Nozzle, And Venturi. ASME, 2001.
.. [2] ISO 5167-2:2003 - Measurement of Fluid Flow by Means of Pressure
Differential Devices Inserted in Circular Cross-Section Conduits Running
Full -- Part 2: Orifice Plates.
'''
beta = Do/D
beta2 = beta*beta
beta4 = beta2*beta2
return ((1.0 - beta4*(1.0 - C*C))**0.5/(C*beta2) - 1.0)**2 | python | def discharge_coefficient_to_K(D, Do, C):
r'''Converts a discharge coefficient to a standard loss coefficient,
for use in computation of the actual pressure drop of an orifice or other
device.
.. math::
K = \left[\frac{\sqrt{1-\beta^4(1-C^2)}}{C\beta^2} - 1\right]^2
Parameters
----------
D : float
Upstream internal pipe diameter, [m]
Do : float
Diameter of orifice at flow conditions, [m]
C : float
Coefficient of discharge of the orifice, [-]
Returns
-------
K : float
Loss coefficient with respect to the velocity and density of the fluid
just upstream of the orifice, [-]
Notes
-----
If expansibility is used in the orifice calculation, the result will not
match with the specified pressure drop formula in [1]_; it can almost
be matched by dividing the calculated mass flow by the expansibility factor
and using that mass flow with the loss coefficient.
Examples
--------
>>> discharge_coefficient_to_K(D=0.07366, Do=0.05, C=0.61512)
5.2314291729754
References
----------
.. [1] American Society of Mechanical Engineers. Mfc-3M-2004 Measurement
Of Fluid Flow In Pipes Using Orifice, Nozzle, And Venturi. ASME, 2001.
.. [2] ISO 5167-2:2003 - Measurement of Fluid Flow by Means of Pressure
Differential Devices Inserted in Circular Cross-Section Conduits Running
Full -- Part 2: Orifice Plates.
'''
beta = Do/D
beta2 = beta*beta
beta4 = beta2*beta2
return ((1.0 - beta4*(1.0 - C*C))**0.5/(C*beta2) - 1.0)**2 | [
"def",
"discharge_coefficient_to_K",
"(",
"D",
",",
"Do",
",",
"C",
")",
":",
"beta",
"=",
"Do",
"/",
"D",
"beta2",
"=",
"beta",
"*",
"beta",
"beta4",
"=",
"beta2",
"*",
"beta2",
"return",
"(",
"(",
"1.0",
"-",
"beta4",
"*",
"(",
"1.0",
"-",
"C",
"*",
"C",
")",
")",
"**",
"0.5",
"/",
"(",
"C",
"*",
"beta2",
")",
"-",
"1.0",
")",
"**",
"2"
]
| r'''Converts a discharge coefficient to a standard loss coefficient,
for use in computation of the actual pressure drop of an orifice or other
device.
.. math::
K = \left[\frac{\sqrt{1-\beta^4(1-C^2)}}{C\beta^2} - 1\right]^2
Parameters
----------
D : float
Upstream internal pipe diameter, [m]
Do : float
Diameter of orifice at flow conditions, [m]
C : float
Coefficient of discharge of the orifice, [-]
Returns
-------
K : float
Loss coefficient with respect to the velocity and density of the fluid
just upstream of the orifice, [-]
Notes
-----
If expansibility is used in the orifice calculation, the result will not
match with the specified pressure drop formula in [1]_; it can almost
be matched by dividing the calculated mass flow by the expansibility factor
and using that mass flow with the loss coefficient.
Examples
--------
>>> discharge_coefficient_to_K(D=0.07366, Do=0.05, C=0.61512)
5.2314291729754
References
----------
.. [1] American Society of Mechanical Engineers. Mfc-3M-2004 Measurement
Of Fluid Flow In Pipes Using Orifice, Nozzle, And Venturi. ASME, 2001.
.. [2] ISO 5167-2:2003 - Measurement of Fluid Flow by Means of Pressure
Differential Devices Inserted in Circular Cross-Section Conduits Running
Full -- Part 2: Orifice Plates. | [
"r",
"Converts",
"a",
"discharge",
"coefficient",
"to",
"a",
"standard",
"loss",
"coefficient",
"for",
"use",
"in",
"computation",
"of",
"the",
"actual",
"pressure",
"drop",
"of",
"an",
"orifice",
"or",
"other",
"device",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/flow_meter.py#L438-L484 | train |
CalebBell/fluids | fluids/particle_size_distribution.py | ParticleSizeDistributionContinuous.dn | def dn(self, fraction, n=None):
r'''Computes the diameter at which a specified `fraction` of the
distribution falls under. Utilizes a bounded solver to search for the
desired diameter.
Parameters
----------
fraction : float
Fraction of the distribution which should be under the calculated
diameter, [-]
n : int, optional
None (for the `order` specified when the distribution was created),
0 (number), 1 (length), 2 (area), 3 (volume/mass),
or any integer, [-]
Returns
-------
d : float
Particle size diameter, [m]
Examples
--------
>>> psd = PSDLognormal(s=0.5, d_characteristic=5E-6, order=3)
>>> psd.dn(.5)
5e-06
>>> psd.dn(1)
0.00029474365335233776
>>> psd.dn(0)
0.0
'''
if fraction == 1.0:
# Avoid returning the maximum value of the search interval
fraction = 1.0 - epsilon
if fraction < 0:
raise ValueError('Fraction must be more than 0')
elif fraction == 0: # pragma: no cover
if self.truncated:
return self.d_min
return 0.0
# Solve to float prevision limit - works well, but is there a real
# point when with mpmath it would never happen?
# dist.cdf(dist.dn(0)-1e-35) == 0
# dist.cdf(dist.dn(0)-1e-36) == input
# dn(0) == 1.9663615597466143e-20
# def err(d):
# cdf = self.cdf(d, n=n)
# if cdf == 0:
# cdf = -1
# return cdf
# return brenth(err, self.d_minimum, self.d_excessive, maxiter=1000, xtol=1E-200)
elif fraction > 1:
raise ValueError('Fraction less than 1')
# As the dn may be incredibly small, it is required for the absolute
# tolerance to not be happy - it needs to continue iterating as long
# as necessary to pin down the answer
return brenth(lambda d:self.cdf(d, n=n) -fraction,
self.d_minimum, self.d_excessive, maxiter=1000, xtol=1E-200) | python | def dn(self, fraction, n=None):
r'''Computes the diameter at which a specified `fraction` of the
distribution falls under. Utilizes a bounded solver to search for the
desired diameter.
Parameters
----------
fraction : float
Fraction of the distribution which should be under the calculated
diameter, [-]
n : int, optional
None (for the `order` specified when the distribution was created),
0 (number), 1 (length), 2 (area), 3 (volume/mass),
or any integer, [-]
Returns
-------
d : float
Particle size diameter, [m]
Examples
--------
>>> psd = PSDLognormal(s=0.5, d_characteristic=5E-6, order=3)
>>> psd.dn(.5)
5e-06
>>> psd.dn(1)
0.00029474365335233776
>>> psd.dn(0)
0.0
'''
if fraction == 1.0:
# Avoid returning the maximum value of the search interval
fraction = 1.0 - epsilon
if fraction < 0:
raise ValueError('Fraction must be more than 0')
elif fraction == 0: # pragma: no cover
if self.truncated:
return self.d_min
return 0.0
# Solve to float prevision limit - works well, but is there a real
# point when with mpmath it would never happen?
# dist.cdf(dist.dn(0)-1e-35) == 0
# dist.cdf(dist.dn(0)-1e-36) == input
# dn(0) == 1.9663615597466143e-20
# def err(d):
# cdf = self.cdf(d, n=n)
# if cdf == 0:
# cdf = -1
# return cdf
# return brenth(err, self.d_minimum, self.d_excessive, maxiter=1000, xtol=1E-200)
elif fraction > 1:
raise ValueError('Fraction less than 1')
# As the dn may be incredibly small, it is required for the absolute
# tolerance to not be happy - it needs to continue iterating as long
# as necessary to pin down the answer
return brenth(lambda d:self.cdf(d, n=n) -fraction,
self.d_minimum, self.d_excessive, maxiter=1000, xtol=1E-200) | [
"def",
"dn",
"(",
"self",
",",
"fraction",
",",
"n",
"=",
"None",
")",
":",
"if",
"fraction",
"==",
"1.0",
":",
"# Avoid returning the maximum value of the search interval",
"fraction",
"=",
"1.0",
"-",
"epsilon",
"if",
"fraction",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"'Fraction must be more than 0'",
")",
"elif",
"fraction",
"==",
"0",
":",
"# pragma: no cover",
"if",
"self",
".",
"truncated",
":",
"return",
"self",
".",
"d_min",
"return",
"0.0",
"# Solve to float prevision limit - works well, but is there a real",
"# point when with mpmath it would never happen?",
"# dist.cdf(dist.dn(0)-1e-35) == 0",
"# dist.cdf(dist.dn(0)-1e-36) == input",
"# dn(0) == 1.9663615597466143e-20",
"# def err(d): ",
"# cdf = self.cdf(d, n=n)",
"# if cdf == 0:",
"# cdf = -1",
"# return cdf",
"# return brenth(err, self.d_minimum, self.d_excessive, maxiter=1000, xtol=1E-200)",
"elif",
"fraction",
">",
"1",
":",
"raise",
"ValueError",
"(",
"'Fraction less than 1'",
")",
"# As the dn may be incredibly small, it is required for the absolute ",
"# tolerance to not be happy - it needs to continue iterating as long",
"# as necessary to pin down the answer",
"return",
"brenth",
"(",
"lambda",
"d",
":",
"self",
".",
"cdf",
"(",
"d",
",",
"n",
"=",
"n",
")",
"-",
"fraction",
",",
"self",
".",
"d_minimum",
",",
"self",
".",
"d_excessive",
",",
"maxiter",
"=",
"1000",
",",
"xtol",
"=",
"1E-200",
")"
]
| r'''Computes the diameter at which a specified `fraction` of the
distribution falls under. Utilizes a bounded solver to search for the
desired diameter.
Parameters
----------
fraction : float
Fraction of the distribution which should be under the calculated
diameter, [-]
n : int, optional
None (for the `order` specified when the distribution was created),
0 (number), 1 (length), 2 (area), 3 (volume/mass),
or any integer, [-]
Returns
-------
d : float
Particle size diameter, [m]
Examples
--------
>>> psd = PSDLognormal(s=0.5, d_characteristic=5E-6, order=3)
>>> psd.dn(.5)
5e-06
>>> psd.dn(1)
0.00029474365335233776
>>> psd.dn(0)
0.0 | [
"r",
"Computes",
"the",
"diameter",
"at",
"which",
"a",
"specified",
"fraction",
"of",
"the",
"distribution",
"falls",
"under",
".",
"Utilizes",
"a",
"bounded",
"solver",
"to",
"search",
"for",
"the",
"desired",
"diameter",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/particle_size_distribution.py#L1360-L1417 | train |
CalebBell/fluids | fluids/particle_size_distribution.py | ParticleSizeDistribution.fit | def fit(self, x0=None, distribution='lognormal', n=None, **kwargs):
'''Incomplete method to fit experimental values to a curve. It is very
hard to get good initial guesses, which are really required for this.
Differential evolution is promissing. This API is likely to change in
the future.
'''
dist = {'lognormal': PSDLognormal,
'GGS': PSDGatesGaudinSchuhman,
'RR': PSDRosinRammler}[distribution]
if distribution == 'lognormal':
if x0 is None:
d_characteristic = sum([fi*di for fi, di in zip(self.fractions, self.Dis)])
s = 0.4
x0 = [d_characteristic, s]
elif distribution == 'GGS':
if x0 is None:
d_characteristic = sum([fi*di for fi, di in zip(self.fractions, self.Dis)])
m = 1.5
x0 = [d_characteristic, m]
elif distribution == 'RR':
if x0 is None:
x0 = [5E-6, 1e-2]
from scipy.optimize import minimize
return minimize(self._fit_obj_function, x0, args=(dist, n), **kwargs) | python | def fit(self, x0=None, distribution='lognormal', n=None, **kwargs):
'''Incomplete method to fit experimental values to a curve. It is very
hard to get good initial guesses, which are really required for this.
Differential evolution is promissing. This API is likely to change in
the future.
'''
dist = {'lognormal': PSDLognormal,
'GGS': PSDGatesGaudinSchuhman,
'RR': PSDRosinRammler}[distribution]
if distribution == 'lognormal':
if x0 is None:
d_characteristic = sum([fi*di for fi, di in zip(self.fractions, self.Dis)])
s = 0.4
x0 = [d_characteristic, s]
elif distribution == 'GGS':
if x0 is None:
d_characteristic = sum([fi*di for fi, di in zip(self.fractions, self.Dis)])
m = 1.5
x0 = [d_characteristic, m]
elif distribution == 'RR':
if x0 is None:
x0 = [5E-6, 1e-2]
from scipy.optimize import minimize
return minimize(self._fit_obj_function, x0, args=(dist, n), **kwargs) | [
"def",
"fit",
"(",
"self",
",",
"x0",
"=",
"None",
",",
"distribution",
"=",
"'lognormal'",
",",
"n",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"dist",
"=",
"{",
"'lognormal'",
":",
"PSDLognormal",
",",
"'GGS'",
":",
"PSDGatesGaudinSchuhman",
",",
"'RR'",
":",
"PSDRosinRammler",
"}",
"[",
"distribution",
"]",
"if",
"distribution",
"==",
"'lognormal'",
":",
"if",
"x0",
"is",
"None",
":",
"d_characteristic",
"=",
"sum",
"(",
"[",
"fi",
"*",
"di",
"for",
"fi",
",",
"di",
"in",
"zip",
"(",
"self",
".",
"fractions",
",",
"self",
".",
"Dis",
")",
"]",
")",
"s",
"=",
"0.4",
"x0",
"=",
"[",
"d_characteristic",
",",
"s",
"]",
"elif",
"distribution",
"==",
"'GGS'",
":",
"if",
"x0",
"is",
"None",
":",
"d_characteristic",
"=",
"sum",
"(",
"[",
"fi",
"*",
"di",
"for",
"fi",
",",
"di",
"in",
"zip",
"(",
"self",
".",
"fractions",
",",
"self",
".",
"Dis",
")",
"]",
")",
"m",
"=",
"1.5",
"x0",
"=",
"[",
"d_characteristic",
",",
"m",
"]",
"elif",
"distribution",
"==",
"'RR'",
":",
"if",
"x0",
"is",
"None",
":",
"x0",
"=",
"[",
"5E-6",
",",
"1e-2",
"]",
"from",
"scipy",
".",
"optimize",
"import",
"minimize",
"return",
"minimize",
"(",
"self",
".",
"_fit_obj_function",
",",
"x0",
",",
"args",
"=",
"(",
"dist",
",",
"n",
")",
",",
"*",
"*",
"kwargs",
")"
]
| Incomplete method to fit experimental values to a curve. It is very
hard to get good initial guesses, which are really required for this.
Differential evolution is promissing. This API is likely to change in
the future. | [
"Incomplete",
"method",
"to",
"fit",
"experimental",
"values",
"to",
"a",
"curve",
".",
"It",
"is",
"very",
"hard",
"to",
"get",
"good",
"initial",
"guesses",
"which",
"are",
"really",
"required",
"for",
"this",
".",
"Differential",
"evolution",
"is",
"promissing",
".",
"This",
"API",
"is",
"likely",
"to",
"change",
"in",
"the",
"future",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/particle_size_distribution.py#L1881-L1905 | train |
CalebBell/fluids | fluids/particle_size_distribution.py | ParticleSizeDistribution.Dis | def Dis(self):
'''Representative diameters of each bin.
'''
return [self.di_power(i, power=1) for i in range(self.N)] | python | def Dis(self):
'''Representative diameters of each bin.
'''
return [self.di_power(i, power=1) for i in range(self.N)] | [
"def",
"Dis",
"(",
"self",
")",
":",
"return",
"[",
"self",
".",
"di_power",
"(",
"i",
",",
"power",
"=",
"1",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"N",
")",
"]"
]
| Representative diameters of each bin. | [
"Representative",
"diameters",
"of",
"each",
"bin",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/particle_size_distribution.py#L1908-L1911 | train |
CalebBell/fluids | fluids/geometry.py | SA_tank | def SA_tank(D, L, sideA=None, sideB=None, sideA_a=0,
sideB_a=0, sideA_f=None, sideA_k=None, sideB_f=None, sideB_k=None,
full_output=False):
r'''Calculates the surface are of a cylindrical tank with optional heads.
In the degenerate case of being provided with only `D` and `L`, provides
the surface area of a cylinder.
Parameters
----------
D : float
Diameter of the cylindrical section of the tank, [m]
L : float
Length of the main cylindrical section of the tank, [m]
sideA : string, optional
The left (or bottom for vertical) head of the tank's type; one of
[None, 'conical', 'ellipsoidal', 'torispherical', 'guppy', 'spherical'].
sideB : string, optional
The right (or top for vertical) head of the tank's type; one of
[None, 'conical', 'ellipsoidal', 'torispherical', 'guppy', 'spherical'].
sideA_a : float, optional
The distance the head as specified by sideA extends down or to the left
from the main cylindrical section, [m]
sideB_a : float, optional
The distance the head as specified by sideB extends up or to the right
from the main cylindrical section, [m]
sideA_f : float, optional
Dish-radius parameter for side A; fD = dish radius [1/m]
sideA_k : float, optional
knuckle-radius parameter for side A; kD = knuckle radius [1/m]
sideB_f : float, optional
Dish-radius parameter for side B; fD = dish radius [1/m]
sideB_k : float, optional
knuckle-radius parameter for side B; kD = knuckle radius [1/m]
Returns
-------
SA : float
Surface area of the tank [m^2]
areas : tuple, only returned if full_output == True
(sideA_SA, sideB_SA, lateral_SA)
Other Parameters
----------------
full_output : bool, optional
Returns a tuple of (sideA_SA, sideB_SA, lateral_SA) if True
Examples
--------
Cylinder, Spheroid, Long Cones, and spheres. All checked.
>>> SA_tank(D=2, L=2)
18.84955592153876
>>> SA_tank(D=1., L=0, sideA='ellipsoidal', sideA_a=2, sideB='ellipsoidal',
... sideB_a=2)
28.480278854014387
>>> SA_tank(D=1., L=5, sideA='conical', sideA_a=2, sideB='conical',
... sideB_a=2)
22.18452243965656
>>> SA_tank(D=1., L=5, sideA='spherical', sideA_a=0.5, sideB='spherical',
... sideB_a=0.5)
18.84955592153876
'''
# Side A
if sideA == 'conical':
sideA_SA = SA_conical_head(D=D, a=sideA_a)
elif sideA == 'ellipsoidal':
sideA_SA = SA_ellipsoidal_head(D=D, a=sideA_a)
elif sideA == 'guppy':
sideA_SA = SA_guppy_head(D=D, a=sideA_a)
elif sideA == 'spherical':
sideA_SA = SA_partial_sphere(D=D, h=sideA_a)
elif sideA == 'torispherical':
sideA_SA = SA_torispheroidal(D=D, fd=sideA_f, fk=sideA_k)
else:
sideA_SA = pi/4*D**2 # Circle
# Side B
if sideB == 'conical':
sideB_SA = SA_conical_head(D=D, a=sideB_a)
elif sideB == 'ellipsoidal':
sideB_SA = SA_ellipsoidal_head(D=D, a=sideB_a)
elif sideB == 'guppy':
sideB_SA = SA_guppy_head(D=D, a=sideB_a)
elif sideB == 'spherical':
sideB_SA = SA_partial_sphere(D=D, h=sideB_a)
elif sideB == 'torispherical':
sideB_SA = SA_torispheroidal(D=D, fd=sideB_f, fk=sideB_k)
else:
sideB_SA = pi/4*D**2 # Circle
lateral_SA = pi*D*L
SA = sideA_SA + sideB_SA + lateral_SA
if full_output:
return SA, (sideA_SA, sideB_SA, lateral_SA)
else:
return SA | python | def SA_tank(D, L, sideA=None, sideB=None, sideA_a=0,
sideB_a=0, sideA_f=None, sideA_k=None, sideB_f=None, sideB_k=None,
full_output=False):
r'''Calculates the surface are of a cylindrical tank with optional heads.
In the degenerate case of being provided with only `D` and `L`, provides
the surface area of a cylinder.
Parameters
----------
D : float
Diameter of the cylindrical section of the tank, [m]
L : float
Length of the main cylindrical section of the tank, [m]
sideA : string, optional
The left (or bottom for vertical) head of the tank's type; one of
[None, 'conical', 'ellipsoidal', 'torispherical', 'guppy', 'spherical'].
sideB : string, optional
The right (or top for vertical) head of the tank's type; one of
[None, 'conical', 'ellipsoidal', 'torispherical', 'guppy', 'spherical'].
sideA_a : float, optional
The distance the head as specified by sideA extends down or to the left
from the main cylindrical section, [m]
sideB_a : float, optional
The distance the head as specified by sideB extends up or to the right
from the main cylindrical section, [m]
sideA_f : float, optional
Dish-radius parameter for side A; fD = dish radius [1/m]
sideA_k : float, optional
knuckle-radius parameter for side A; kD = knuckle radius [1/m]
sideB_f : float, optional
Dish-radius parameter for side B; fD = dish radius [1/m]
sideB_k : float, optional
knuckle-radius parameter for side B; kD = knuckle radius [1/m]
Returns
-------
SA : float
Surface area of the tank [m^2]
areas : tuple, only returned if full_output == True
(sideA_SA, sideB_SA, lateral_SA)
Other Parameters
----------------
full_output : bool, optional
Returns a tuple of (sideA_SA, sideB_SA, lateral_SA) if True
Examples
--------
Cylinder, Spheroid, Long Cones, and spheres. All checked.
>>> SA_tank(D=2, L=2)
18.84955592153876
>>> SA_tank(D=1., L=0, sideA='ellipsoidal', sideA_a=2, sideB='ellipsoidal',
... sideB_a=2)
28.480278854014387
>>> SA_tank(D=1., L=5, sideA='conical', sideA_a=2, sideB='conical',
... sideB_a=2)
22.18452243965656
>>> SA_tank(D=1., L=5, sideA='spherical', sideA_a=0.5, sideB='spherical',
... sideB_a=0.5)
18.84955592153876
'''
# Side A
if sideA == 'conical':
sideA_SA = SA_conical_head(D=D, a=sideA_a)
elif sideA == 'ellipsoidal':
sideA_SA = SA_ellipsoidal_head(D=D, a=sideA_a)
elif sideA == 'guppy':
sideA_SA = SA_guppy_head(D=D, a=sideA_a)
elif sideA == 'spherical':
sideA_SA = SA_partial_sphere(D=D, h=sideA_a)
elif sideA == 'torispherical':
sideA_SA = SA_torispheroidal(D=D, fd=sideA_f, fk=sideA_k)
else:
sideA_SA = pi/4*D**2 # Circle
# Side B
if sideB == 'conical':
sideB_SA = SA_conical_head(D=D, a=sideB_a)
elif sideB == 'ellipsoidal':
sideB_SA = SA_ellipsoidal_head(D=D, a=sideB_a)
elif sideB == 'guppy':
sideB_SA = SA_guppy_head(D=D, a=sideB_a)
elif sideB == 'spherical':
sideB_SA = SA_partial_sphere(D=D, h=sideB_a)
elif sideB == 'torispherical':
sideB_SA = SA_torispheroidal(D=D, fd=sideB_f, fk=sideB_k)
else:
sideB_SA = pi/4*D**2 # Circle
lateral_SA = pi*D*L
SA = sideA_SA + sideB_SA + lateral_SA
if full_output:
return SA, (sideA_SA, sideB_SA, lateral_SA)
else:
return SA | [
"def",
"SA_tank",
"(",
"D",
",",
"L",
",",
"sideA",
"=",
"None",
",",
"sideB",
"=",
"None",
",",
"sideA_a",
"=",
"0",
",",
"sideB_a",
"=",
"0",
",",
"sideA_f",
"=",
"None",
",",
"sideA_k",
"=",
"None",
",",
"sideB_f",
"=",
"None",
",",
"sideB_k",
"=",
"None",
",",
"full_output",
"=",
"False",
")",
":",
"# Side A",
"if",
"sideA",
"==",
"'conical'",
":",
"sideA_SA",
"=",
"SA_conical_head",
"(",
"D",
"=",
"D",
",",
"a",
"=",
"sideA_a",
")",
"elif",
"sideA",
"==",
"'ellipsoidal'",
":",
"sideA_SA",
"=",
"SA_ellipsoidal_head",
"(",
"D",
"=",
"D",
",",
"a",
"=",
"sideA_a",
")",
"elif",
"sideA",
"==",
"'guppy'",
":",
"sideA_SA",
"=",
"SA_guppy_head",
"(",
"D",
"=",
"D",
",",
"a",
"=",
"sideA_a",
")",
"elif",
"sideA",
"==",
"'spherical'",
":",
"sideA_SA",
"=",
"SA_partial_sphere",
"(",
"D",
"=",
"D",
",",
"h",
"=",
"sideA_a",
")",
"elif",
"sideA",
"==",
"'torispherical'",
":",
"sideA_SA",
"=",
"SA_torispheroidal",
"(",
"D",
"=",
"D",
",",
"fd",
"=",
"sideA_f",
",",
"fk",
"=",
"sideA_k",
")",
"else",
":",
"sideA_SA",
"=",
"pi",
"/",
"4",
"*",
"D",
"**",
"2",
"# Circle",
"# Side B",
"if",
"sideB",
"==",
"'conical'",
":",
"sideB_SA",
"=",
"SA_conical_head",
"(",
"D",
"=",
"D",
",",
"a",
"=",
"sideB_a",
")",
"elif",
"sideB",
"==",
"'ellipsoidal'",
":",
"sideB_SA",
"=",
"SA_ellipsoidal_head",
"(",
"D",
"=",
"D",
",",
"a",
"=",
"sideB_a",
")",
"elif",
"sideB",
"==",
"'guppy'",
":",
"sideB_SA",
"=",
"SA_guppy_head",
"(",
"D",
"=",
"D",
",",
"a",
"=",
"sideB_a",
")",
"elif",
"sideB",
"==",
"'spherical'",
":",
"sideB_SA",
"=",
"SA_partial_sphere",
"(",
"D",
"=",
"D",
",",
"h",
"=",
"sideB_a",
")",
"elif",
"sideB",
"==",
"'torispherical'",
":",
"sideB_SA",
"=",
"SA_torispheroidal",
"(",
"D",
"=",
"D",
",",
"fd",
"=",
"sideB_f",
",",
"fk",
"=",
"sideB_k",
")",
"else",
":",
"sideB_SA",
"=",
"pi",
"/",
"4",
"*",
"D",
"**",
"2",
"# Circle",
"lateral_SA",
"=",
"pi",
"*",
"D",
"*",
"L",
"SA",
"=",
"sideA_SA",
"+",
"sideB_SA",
"+",
"lateral_SA",
"if",
"full_output",
":",
"return",
"SA",
",",
"(",
"sideA_SA",
",",
"sideB_SA",
",",
"lateral_SA",
")",
"else",
":",
"return",
"SA"
]
| r'''Calculates the surface are of a cylindrical tank with optional heads.
In the degenerate case of being provided with only `D` and `L`, provides
the surface area of a cylinder.
Parameters
----------
D : float
Diameter of the cylindrical section of the tank, [m]
L : float
Length of the main cylindrical section of the tank, [m]
sideA : string, optional
The left (or bottom for vertical) head of the tank's type; one of
[None, 'conical', 'ellipsoidal', 'torispherical', 'guppy', 'spherical'].
sideB : string, optional
The right (or top for vertical) head of the tank's type; one of
[None, 'conical', 'ellipsoidal', 'torispherical', 'guppy', 'spherical'].
sideA_a : float, optional
The distance the head as specified by sideA extends down or to the left
from the main cylindrical section, [m]
sideB_a : float, optional
The distance the head as specified by sideB extends up or to the right
from the main cylindrical section, [m]
sideA_f : float, optional
Dish-radius parameter for side A; fD = dish radius [1/m]
sideA_k : float, optional
knuckle-radius parameter for side A; kD = knuckle radius [1/m]
sideB_f : float, optional
Dish-radius parameter for side B; fD = dish radius [1/m]
sideB_k : float, optional
knuckle-radius parameter for side B; kD = knuckle radius [1/m]
Returns
-------
SA : float
Surface area of the tank [m^2]
areas : tuple, only returned if full_output == True
(sideA_SA, sideB_SA, lateral_SA)
Other Parameters
----------------
full_output : bool, optional
Returns a tuple of (sideA_SA, sideB_SA, lateral_SA) if True
Examples
--------
Cylinder, Spheroid, Long Cones, and spheres. All checked.
>>> SA_tank(D=2, L=2)
18.84955592153876
>>> SA_tank(D=1., L=0, sideA='ellipsoidal', sideA_a=2, sideB='ellipsoidal',
... sideB_a=2)
28.480278854014387
>>> SA_tank(D=1., L=5, sideA='conical', sideA_a=2, sideB='conical',
... sideB_a=2)
22.18452243965656
>>> SA_tank(D=1., L=5, sideA='spherical', sideA_a=0.5, sideB='spherical',
... sideB_a=0.5)
18.84955592153876 | [
"r",
"Calculates",
"the",
"surface",
"are",
"of",
"a",
"cylindrical",
"tank",
"with",
"optional",
"heads",
".",
"In",
"the",
"degenerate",
"case",
"of",
"being",
"provided",
"with",
"only",
"D",
"and",
"L",
"provides",
"the",
"surface",
"area",
"of",
"a",
"cylinder",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/geometry.py#L1192-L1287 | train |
CalebBell/fluids | fluids/geometry.py | pitch_angle_solver | def pitch_angle_solver(angle=None, pitch=None, pitch_parallel=None,
pitch_normal=None):
r'''Utility to take any two of `angle`, `pitch`, `pitch_parallel`, and
`pitch_normal` and calculate the other two. This is useful for applications
with tube banks, as in shell and tube heat exchangers or air coolers and
allows for a wider range of user input.
.. math::
\text{pitch normal} = \text{pitch} \cdot \sin(\text{angle})
.. math::
\text{pitch parallel} = \text{pitch} \cdot \cos(\text{angle})
Parameters
----------
angle : float, optional
The angle of the tube layout, [degrees]
pitch : float, optional
The shortest distance between tube centers; defined in relation to the
flow direction only, [m]
pitch_parallel : float, optional
The distance between tube center along a line parallel to the flow;
has been called `longitudinal` pitch, `pp`, `s2`, `SL`, and `p2`, [m]
pitch_normal : float, optional
The distance between tube centers in a line 90° to the line of flow;
has been called the `transverse` pitch, `pn`, `s1`, `ST`, and `p1`, [m]
Returns
-------
angle : float
The angle of the tube layout, [degrees]
pitch : float
The shortest distance between tube centers; defined in relation to the
flow direction only, [m]
pitch_parallel : float
The distance between tube center along a line parallel to the flow;
has been called `longitudinal` pitch, `pp`, `s2`, `SL`, and `p2`, [m]
pitch_normal : float
The distance between tube centers in a line 90° to the line of flow;
has been called the `transverse` pitch, `pn`, `s1`, `ST`, and `p1`, [m]
Notes
-----
For the 90 and 0 degree case, the normal or parallel pitches can be zero;
given the angle and the zero value, obviously is it not possible to
calculate the pitch and a math error will be raised.
No exception will be raised if three or four inputs are provided; the other
two will simply be calculated according to the list of if statements used.
An exception will be raised if only one input is provided.
Examples
--------
>>> pitch_angle_solver(pitch=1, angle=30)
(30, 1, 0.8660254037844387, 0.49999999999999994)
References
----------
.. [1] Schlunder, Ernst U, and International Center for Heat and Mass
Transfer. Heat Exchanger Design Handbook. Washington:
Hemisphere Pub. Corp., 1983.
'''
if angle is not None and pitch is not None:
pitch_normal = pitch*sin(radians(angle))
pitch_parallel = pitch*cos(radians(angle))
elif angle is not None and pitch_normal is not None:
pitch = pitch_normal/sin(radians(angle))
pitch_parallel = pitch*cos(radians(angle))
elif angle is not None and pitch_parallel is not None:
pitch = pitch_parallel/cos(radians(angle))
pitch_normal = pitch*sin(radians(angle))
elif pitch_normal is not None and pitch is not None:
angle = degrees(asin(pitch_normal/pitch))
pitch_parallel = pitch*cos(radians(angle))
elif pitch_parallel is not None and pitch is not None:
angle = degrees(acos(pitch_parallel/pitch))
pitch_normal = pitch*sin(radians(angle))
elif pitch_parallel is not None and pitch_normal is not None:
angle = degrees(asin(pitch_normal/(pitch_normal**2 + pitch_parallel**2)**0.5))
pitch = (pitch_normal**2 + pitch_parallel**2)**0.5
else:
raise Exception('Two of the arguments are required')
return angle, pitch, pitch_parallel, pitch_normal | python | def pitch_angle_solver(angle=None, pitch=None, pitch_parallel=None,
pitch_normal=None):
r'''Utility to take any two of `angle`, `pitch`, `pitch_parallel`, and
`pitch_normal` and calculate the other two. This is useful for applications
with tube banks, as in shell and tube heat exchangers or air coolers and
allows for a wider range of user input.
.. math::
\text{pitch normal} = \text{pitch} \cdot \sin(\text{angle})
.. math::
\text{pitch parallel} = \text{pitch} \cdot \cos(\text{angle})
Parameters
----------
angle : float, optional
The angle of the tube layout, [degrees]
pitch : float, optional
The shortest distance between tube centers; defined in relation to the
flow direction only, [m]
pitch_parallel : float, optional
The distance between tube center along a line parallel to the flow;
has been called `longitudinal` pitch, `pp`, `s2`, `SL`, and `p2`, [m]
pitch_normal : float, optional
The distance between tube centers in a line 90° to the line of flow;
has been called the `transverse` pitch, `pn`, `s1`, `ST`, and `p1`, [m]
Returns
-------
angle : float
The angle of the tube layout, [degrees]
pitch : float
The shortest distance between tube centers; defined in relation to the
flow direction only, [m]
pitch_parallel : float
The distance between tube center along a line parallel to the flow;
has been called `longitudinal` pitch, `pp`, `s2`, `SL`, and `p2`, [m]
pitch_normal : float
The distance between tube centers in a line 90° to the line of flow;
has been called the `transverse` pitch, `pn`, `s1`, `ST`, and `p1`, [m]
Notes
-----
For the 90 and 0 degree case, the normal or parallel pitches can be zero;
given the angle and the zero value, obviously is it not possible to
calculate the pitch and a math error will be raised.
No exception will be raised if three or four inputs are provided; the other
two will simply be calculated according to the list of if statements used.
An exception will be raised if only one input is provided.
Examples
--------
>>> pitch_angle_solver(pitch=1, angle=30)
(30, 1, 0.8660254037844387, 0.49999999999999994)
References
----------
.. [1] Schlunder, Ernst U, and International Center for Heat and Mass
Transfer. Heat Exchanger Design Handbook. Washington:
Hemisphere Pub. Corp., 1983.
'''
if angle is not None and pitch is not None:
pitch_normal = pitch*sin(radians(angle))
pitch_parallel = pitch*cos(radians(angle))
elif angle is not None and pitch_normal is not None:
pitch = pitch_normal/sin(radians(angle))
pitch_parallel = pitch*cos(radians(angle))
elif angle is not None and pitch_parallel is not None:
pitch = pitch_parallel/cos(radians(angle))
pitch_normal = pitch*sin(radians(angle))
elif pitch_normal is not None and pitch is not None:
angle = degrees(asin(pitch_normal/pitch))
pitch_parallel = pitch*cos(radians(angle))
elif pitch_parallel is not None and pitch is not None:
angle = degrees(acos(pitch_parallel/pitch))
pitch_normal = pitch*sin(radians(angle))
elif pitch_parallel is not None and pitch_normal is not None:
angle = degrees(asin(pitch_normal/(pitch_normal**2 + pitch_parallel**2)**0.5))
pitch = (pitch_normal**2 + pitch_parallel**2)**0.5
else:
raise Exception('Two of the arguments are required')
return angle, pitch, pitch_parallel, pitch_normal | [
"def",
"pitch_angle_solver",
"(",
"angle",
"=",
"None",
",",
"pitch",
"=",
"None",
",",
"pitch_parallel",
"=",
"None",
",",
"pitch_normal",
"=",
"None",
")",
":",
"if",
"angle",
"is",
"not",
"None",
"and",
"pitch",
"is",
"not",
"None",
":",
"pitch_normal",
"=",
"pitch",
"*",
"sin",
"(",
"radians",
"(",
"angle",
")",
")",
"pitch_parallel",
"=",
"pitch",
"*",
"cos",
"(",
"radians",
"(",
"angle",
")",
")",
"elif",
"angle",
"is",
"not",
"None",
"and",
"pitch_normal",
"is",
"not",
"None",
":",
"pitch",
"=",
"pitch_normal",
"/",
"sin",
"(",
"radians",
"(",
"angle",
")",
")",
"pitch_parallel",
"=",
"pitch",
"*",
"cos",
"(",
"radians",
"(",
"angle",
")",
")",
"elif",
"angle",
"is",
"not",
"None",
"and",
"pitch_parallel",
"is",
"not",
"None",
":",
"pitch",
"=",
"pitch_parallel",
"/",
"cos",
"(",
"radians",
"(",
"angle",
")",
")",
"pitch_normal",
"=",
"pitch",
"*",
"sin",
"(",
"radians",
"(",
"angle",
")",
")",
"elif",
"pitch_normal",
"is",
"not",
"None",
"and",
"pitch",
"is",
"not",
"None",
":",
"angle",
"=",
"degrees",
"(",
"asin",
"(",
"pitch_normal",
"/",
"pitch",
")",
")",
"pitch_parallel",
"=",
"pitch",
"*",
"cos",
"(",
"radians",
"(",
"angle",
")",
")",
"elif",
"pitch_parallel",
"is",
"not",
"None",
"and",
"pitch",
"is",
"not",
"None",
":",
"angle",
"=",
"degrees",
"(",
"acos",
"(",
"pitch_parallel",
"/",
"pitch",
")",
")",
"pitch_normal",
"=",
"pitch",
"*",
"sin",
"(",
"radians",
"(",
"angle",
")",
")",
"elif",
"pitch_parallel",
"is",
"not",
"None",
"and",
"pitch_normal",
"is",
"not",
"None",
":",
"angle",
"=",
"degrees",
"(",
"asin",
"(",
"pitch_normal",
"/",
"(",
"pitch_normal",
"**",
"2",
"+",
"pitch_parallel",
"**",
"2",
")",
"**",
"0.5",
")",
")",
"pitch",
"=",
"(",
"pitch_normal",
"**",
"2",
"+",
"pitch_parallel",
"**",
"2",
")",
"**",
"0.5",
"else",
":",
"raise",
"Exception",
"(",
"'Two of the arguments are required'",
")",
"return",
"angle",
",",
"pitch",
",",
"pitch_parallel",
",",
"pitch_normal"
]
| r'''Utility to take any two of `angle`, `pitch`, `pitch_parallel`, and
`pitch_normal` and calculate the other two. This is useful for applications
with tube banks, as in shell and tube heat exchangers or air coolers and
allows for a wider range of user input.
.. math::
\text{pitch normal} = \text{pitch} \cdot \sin(\text{angle})
.. math::
\text{pitch parallel} = \text{pitch} \cdot \cos(\text{angle})
Parameters
----------
angle : float, optional
The angle of the tube layout, [degrees]
pitch : float, optional
The shortest distance between tube centers; defined in relation to the
flow direction only, [m]
pitch_parallel : float, optional
The distance between tube center along a line parallel to the flow;
has been called `longitudinal` pitch, `pp`, `s2`, `SL`, and `p2`, [m]
pitch_normal : float, optional
The distance between tube centers in a line 90° to the line of flow;
has been called the `transverse` pitch, `pn`, `s1`, `ST`, and `p1`, [m]
Returns
-------
angle : float
The angle of the tube layout, [degrees]
pitch : float
The shortest distance between tube centers; defined in relation to the
flow direction only, [m]
pitch_parallel : float
The distance between tube center along a line parallel to the flow;
has been called `longitudinal` pitch, `pp`, `s2`, `SL`, and `p2`, [m]
pitch_normal : float
The distance between tube centers in a line 90° to the line of flow;
has been called the `transverse` pitch, `pn`, `s1`, `ST`, and `p1`, [m]
Notes
-----
For the 90 and 0 degree case, the normal or parallel pitches can be zero;
given the angle and the zero value, obviously is it not possible to
calculate the pitch and a math error will be raised.
No exception will be raised if three or four inputs are provided; the other
two will simply be calculated according to the list of if statements used.
An exception will be raised if only one input is provided.
Examples
--------
>>> pitch_angle_solver(pitch=1, angle=30)
(30, 1, 0.8660254037844387, 0.49999999999999994)
References
----------
.. [1] Schlunder, Ernst U, and International Center for Heat and Mass
Transfer. Heat Exchanger Design Handbook. Washington:
Hemisphere Pub. Corp., 1983. | [
"r",
"Utility",
"to",
"take",
"any",
"two",
"of",
"angle",
"pitch",
"pitch_parallel",
"and",
"pitch_normal",
"and",
"calculate",
"the",
"other",
"two",
".",
"This",
"is",
"useful",
"for",
"applications",
"with",
"tube",
"banks",
"as",
"in",
"shell",
"and",
"tube",
"heat",
"exchangers",
"or",
"air",
"coolers",
"and",
"allows",
"for",
"a",
"wider",
"range",
"of",
"user",
"input",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/geometry.py#L3030-L3113 | train |
CalebBell/fluids | fluids/geometry.py | A_hollow_cylinder | def A_hollow_cylinder(Di, Do, L):
r'''Returns the surface area of a hollow cylinder.
.. math::
A = \pi D_o L + \pi D_i L + 2\cdot \frac{\pi D_o^2}{4}
- 2\cdot \frac{\pi D_i^2}{4}
Parameters
----------
Di : float
Diameter of the hollow in the cylinder, [m]
Do : float
Diameter of the exterior of the cylinder, [m]
L : float
Length of the cylinder, [m]
Returns
-------
A : float
Surface area [m^2]
Examples
--------
>>> A_hollow_cylinder(0.005, 0.01, 0.1)
0.004830198704894308
'''
side_o = pi*Do*L
side_i = pi*Di*L
cap_circle = pi*Do**2/4*2
cap_removed = pi*Di**2/4*2
return side_o + side_i + cap_circle - cap_removed | python | def A_hollow_cylinder(Di, Do, L):
r'''Returns the surface area of a hollow cylinder.
.. math::
A = \pi D_o L + \pi D_i L + 2\cdot \frac{\pi D_o^2}{4}
- 2\cdot \frac{\pi D_i^2}{4}
Parameters
----------
Di : float
Diameter of the hollow in the cylinder, [m]
Do : float
Diameter of the exterior of the cylinder, [m]
L : float
Length of the cylinder, [m]
Returns
-------
A : float
Surface area [m^2]
Examples
--------
>>> A_hollow_cylinder(0.005, 0.01, 0.1)
0.004830198704894308
'''
side_o = pi*Do*L
side_i = pi*Di*L
cap_circle = pi*Do**2/4*2
cap_removed = pi*Di**2/4*2
return side_o + side_i + cap_circle - cap_removed | [
"def",
"A_hollow_cylinder",
"(",
"Di",
",",
"Do",
",",
"L",
")",
":",
"side_o",
"=",
"pi",
"*",
"Do",
"*",
"L",
"side_i",
"=",
"pi",
"*",
"Di",
"*",
"L",
"cap_circle",
"=",
"pi",
"*",
"Do",
"**",
"2",
"/",
"4",
"*",
"2",
"cap_removed",
"=",
"pi",
"*",
"Di",
"**",
"2",
"/",
"4",
"*",
"2",
"return",
"side_o",
"+",
"side_i",
"+",
"cap_circle",
"-",
"cap_removed"
]
| r'''Returns the surface area of a hollow cylinder.
.. math::
A = \pi D_o L + \pi D_i L + 2\cdot \frac{\pi D_o^2}{4}
- 2\cdot \frac{\pi D_i^2}{4}
Parameters
----------
Di : float
Diameter of the hollow in the cylinder, [m]
Do : float
Diameter of the exterior of the cylinder, [m]
L : float
Length of the cylinder, [m]
Returns
-------
A : float
Surface area [m^2]
Examples
--------
>>> A_hollow_cylinder(0.005, 0.01, 0.1)
0.004830198704894308 | [
"r",
"Returns",
"the",
"surface",
"area",
"of",
"a",
"hollow",
"cylinder",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/geometry.py#L3285-L3315 | train |
CalebBell/fluids | fluids/geometry.py | A_multiple_hole_cylinder | def A_multiple_hole_cylinder(Do, L, holes):
r'''Returns the surface area of a cylinder with multiple holes.
Calculation will naively return a negative value or other impossible
result if the number of cylinders added is physically impossible.
Holes may be of different shapes, but must be perpendicular to the
axis of the cylinder.
.. math::
A = \pi D_o L + 2\cdot \frac{\pi D_o^2}{4} +
\sum_{i}^n \left( \pi D_i L - 2\cdot \frac{\pi D_i^2}{4}\right)
Parameters
----------
Do : float
Diameter of the exterior of the cylinder, [m]
L : float
Length of the cylinder, [m]
holes : list
List of tuples containing (diameter, count) pairs of descriptions for
each of the holes sizes.
Returns
-------
A : float
Surface area [m^2]
Examples
--------
>>> A_multiple_hole_cylinder(0.01, 0.1, [(0.005, 1)])
0.004830198704894308
'''
side_o = pi*Do*L
cap_circle = pi*Do**2/4*2
A = cap_circle + side_o
for Di, n in holes:
side_i = pi*Di*L
cap_removed = pi*Di**2/4*2
A = A + side_i*n - cap_removed*n
return A | python | def A_multiple_hole_cylinder(Do, L, holes):
r'''Returns the surface area of a cylinder with multiple holes.
Calculation will naively return a negative value or other impossible
result if the number of cylinders added is physically impossible.
Holes may be of different shapes, but must be perpendicular to the
axis of the cylinder.
.. math::
A = \pi D_o L + 2\cdot \frac{\pi D_o^2}{4} +
\sum_{i}^n \left( \pi D_i L - 2\cdot \frac{\pi D_i^2}{4}\right)
Parameters
----------
Do : float
Diameter of the exterior of the cylinder, [m]
L : float
Length of the cylinder, [m]
holes : list
List of tuples containing (diameter, count) pairs of descriptions for
each of the holes sizes.
Returns
-------
A : float
Surface area [m^2]
Examples
--------
>>> A_multiple_hole_cylinder(0.01, 0.1, [(0.005, 1)])
0.004830198704894308
'''
side_o = pi*Do*L
cap_circle = pi*Do**2/4*2
A = cap_circle + side_o
for Di, n in holes:
side_i = pi*Di*L
cap_removed = pi*Di**2/4*2
A = A + side_i*n - cap_removed*n
return A | [
"def",
"A_multiple_hole_cylinder",
"(",
"Do",
",",
"L",
",",
"holes",
")",
":",
"side_o",
"=",
"pi",
"*",
"Do",
"*",
"L",
"cap_circle",
"=",
"pi",
"*",
"Do",
"**",
"2",
"/",
"4",
"*",
"2",
"A",
"=",
"cap_circle",
"+",
"side_o",
"for",
"Di",
",",
"n",
"in",
"holes",
":",
"side_i",
"=",
"pi",
"*",
"Di",
"*",
"L",
"cap_removed",
"=",
"pi",
"*",
"Di",
"**",
"2",
"/",
"4",
"*",
"2",
"A",
"=",
"A",
"+",
"side_i",
"*",
"n",
"-",
"cap_removed",
"*",
"n",
"return",
"A"
]
| r'''Returns the surface area of a cylinder with multiple holes.
Calculation will naively return a negative value or other impossible
result if the number of cylinders added is physically impossible.
Holes may be of different shapes, but must be perpendicular to the
axis of the cylinder.
.. math::
A = \pi D_o L + 2\cdot \frac{\pi D_o^2}{4} +
\sum_{i}^n \left( \pi D_i L - 2\cdot \frac{\pi D_i^2}{4}\right)
Parameters
----------
Do : float
Diameter of the exterior of the cylinder, [m]
L : float
Length of the cylinder, [m]
holes : list
List of tuples containing (diameter, count) pairs of descriptions for
each of the holes sizes.
Returns
-------
A : float
Surface area [m^2]
Examples
--------
>>> A_multiple_hole_cylinder(0.01, 0.1, [(0.005, 1)])
0.004830198704894308 | [
"r",
"Returns",
"the",
"surface",
"area",
"of",
"a",
"cylinder",
"with",
"multiple",
"holes",
".",
"Calculation",
"will",
"naively",
"return",
"a",
"negative",
"value",
"or",
"other",
"impossible",
"result",
"if",
"the",
"number",
"of",
"cylinders",
"added",
"is",
"physically",
"impossible",
".",
"Holes",
"may",
"be",
"of",
"different",
"shapes",
"but",
"must",
"be",
"perpendicular",
"to",
"the",
"axis",
"of",
"the",
"cylinder",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/geometry.py#L3346-L3384 | train |
CalebBell/fluids | fluids/geometry.py | TANK.V_from_h | def V_from_h(self, h, method='full'):
r'''Method to calculate the volume of liquid in a fully defined tank
given a specified height `h`. `h` must be under the maximum height.
If the method is 'chebyshev', and the coefficients have not yet been
calculated, they are created by calling `set_chebyshev_approximators`.
Parameters
----------
h : float
Height specified, [m]
method : str
One of 'full' (calculated rigorously) or 'chebyshev'
Returns
-------
V : float
Volume of liquid in the tank up to the specified height, [m^3]
Notes
-----
'''
if method == 'full':
return V_from_h(h, self.D, self.L, self.horizontal, self.sideA,
self.sideB, self.sideA_a, self.sideB_a,
self.sideA_f, self.sideA_k, self.sideB_f,
self.sideB_k)
elif method == 'chebyshev':
if not self.chebyshev:
self.set_chebyshev_approximators()
return self.V_from_h_cheb(h)
else:
raise Exception("Allowable methods are 'full' or 'chebyshev'.") | python | def V_from_h(self, h, method='full'):
r'''Method to calculate the volume of liquid in a fully defined tank
given a specified height `h`. `h` must be under the maximum height.
If the method is 'chebyshev', and the coefficients have not yet been
calculated, they are created by calling `set_chebyshev_approximators`.
Parameters
----------
h : float
Height specified, [m]
method : str
One of 'full' (calculated rigorously) or 'chebyshev'
Returns
-------
V : float
Volume of liquid in the tank up to the specified height, [m^3]
Notes
-----
'''
if method == 'full':
return V_from_h(h, self.D, self.L, self.horizontal, self.sideA,
self.sideB, self.sideA_a, self.sideB_a,
self.sideA_f, self.sideA_k, self.sideB_f,
self.sideB_k)
elif method == 'chebyshev':
if not self.chebyshev:
self.set_chebyshev_approximators()
return self.V_from_h_cheb(h)
else:
raise Exception("Allowable methods are 'full' or 'chebyshev'.") | [
"def",
"V_from_h",
"(",
"self",
",",
"h",
",",
"method",
"=",
"'full'",
")",
":",
"if",
"method",
"==",
"'full'",
":",
"return",
"V_from_h",
"(",
"h",
",",
"self",
".",
"D",
",",
"self",
".",
"L",
",",
"self",
".",
"horizontal",
",",
"self",
".",
"sideA",
",",
"self",
".",
"sideB",
",",
"self",
".",
"sideA_a",
",",
"self",
".",
"sideB_a",
",",
"self",
".",
"sideA_f",
",",
"self",
".",
"sideA_k",
",",
"self",
".",
"sideB_f",
",",
"self",
".",
"sideB_k",
")",
"elif",
"method",
"==",
"'chebyshev'",
":",
"if",
"not",
"self",
".",
"chebyshev",
":",
"self",
".",
"set_chebyshev_approximators",
"(",
")",
"return",
"self",
".",
"V_from_h_cheb",
"(",
"h",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"Allowable methods are 'full' or 'chebyshev'.\"",
")"
]
| r'''Method to calculate the volume of liquid in a fully defined tank
given a specified height `h`. `h` must be under the maximum height.
If the method is 'chebyshev', and the coefficients have not yet been
calculated, they are created by calling `set_chebyshev_approximators`.
Parameters
----------
h : float
Height specified, [m]
method : str
One of 'full' (calculated rigorously) or 'chebyshev'
Returns
-------
V : float
Volume of liquid in the tank up to the specified height, [m^3]
Notes
----- | [
"r",
"Method",
"to",
"calculate",
"the",
"volume",
"of",
"liquid",
"in",
"a",
"fully",
"defined",
"tank",
"given",
"a",
"specified",
"height",
"h",
".",
"h",
"must",
"be",
"under",
"the",
"maximum",
"height",
".",
"If",
"the",
"method",
"is",
"chebyshev",
"and",
"the",
"coefficients",
"have",
"not",
"yet",
"been",
"calculated",
"they",
"are",
"created",
"by",
"calling",
"set_chebyshev_approximators",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/geometry.py#L1713-L1744 | train |
CalebBell/fluids | fluids/geometry.py | TANK.h_from_V | def h_from_V(self, V, method='spline'):
r'''Method to calculate the height of liquid in a fully defined tank
given a specified volume of liquid in it `V`. `V` must be under the
maximum volume. If the method is 'spline', and the interpolation table
is not yet defined, creates it by calling the method set_table. If the
method is 'chebyshev', and the coefficients have not yet been
calculated, they are created by calling `set_chebyshev_approximators`.
Parameters
----------
V : float
Volume of liquid in the tank up to the desired height, [m^3]
method : str
One of 'spline', 'chebyshev', or 'brenth'
Returns
-------
h : float
Height of liquid at which the volume is as desired, [m]
'''
if method == 'spline':
if not self.table:
self.set_table()
return float(self.interp_h_from_V(V))
elif method == 'chebyshev':
if not self.chebyshev:
self.set_chebyshev_approximators()
return self.h_from_V_cheb(V)
elif method == 'brenth':
to_solve = lambda h : self.V_from_h(h, method='full') - V
return brenth(to_solve, self.h_max, 0)
else:
raise Exception("Allowable methods are 'full' or 'chebyshev', "
"or 'brenth'.") | python | def h_from_V(self, V, method='spline'):
r'''Method to calculate the height of liquid in a fully defined tank
given a specified volume of liquid in it `V`. `V` must be under the
maximum volume. If the method is 'spline', and the interpolation table
is not yet defined, creates it by calling the method set_table. If the
method is 'chebyshev', and the coefficients have not yet been
calculated, they are created by calling `set_chebyshev_approximators`.
Parameters
----------
V : float
Volume of liquid in the tank up to the desired height, [m^3]
method : str
One of 'spline', 'chebyshev', or 'brenth'
Returns
-------
h : float
Height of liquid at which the volume is as desired, [m]
'''
if method == 'spline':
if not self.table:
self.set_table()
return float(self.interp_h_from_V(V))
elif method == 'chebyshev':
if not self.chebyshev:
self.set_chebyshev_approximators()
return self.h_from_V_cheb(V)
elif method == 'brenth':
to_solve = lambda h : self.V_from_h(h, method='full') - V
return brenth(to_solve, self.h_max, 0)
else:
raise Exception("Allowable methods are 'full' or 'chebyshev', "
"or 'brenth'.") | [
"def",
"h_from_V",
"(",
"self",
",",
"V",
",",
"method",
"=",
"'spline'",
")",
":",
"if",
"method",
"==",
"'spline'",
":",
"if",
"not",
"self",
".",
"table",
":",
"self",
".",
"set_table",
"(",
")",
"return",
"float",
"(",
"self",
".",
"interp_h_from_V",
"(",
"V",
")",
")",
"elif",
"method",
"==",
"'chebyshev'",
":",
"if",
"not",
"self",
".",
"chebyshev",
":",
"self",
".",
"set_chebyshev_approximators",
"(",
")",
"return",
"self",
".",
"h_from_V_cheb",
"(",
"V",
")",
"elif",
"method",
"==",
"'brenth'",
":",
"to_solve",
"=",
"lambda",
"h",
":",
"self",
".",
"V_from_h",
"(",
"h",
",",
"method",
"=",
"'full'",
")",
"-",
"V",
"return",
"brenth",
"(",
"to_solve",
",",
"self",
".",
"h_max",
",",
"0",
")",
"else",
":",
"raise",
"Exception",
"(",
"\"Allowable methods are 'full' or 'chebyshev', \"",
"\"or 'brenth'.\"",
")"
]
| r'''Method to calculate the height of liquid in a fully defined tank
given a specified volume of liquid in it `V`. `V` must be under the
maximum volume. If the method is 'spline', and the interpolation table
is not yet defined, creates it by calling the method set_table. If the
method is 'chebyshev', and the coefficients have not yet been
calculated, they are created by calling `set_chebyshev_approximators`.
Parameters
----------
V : float
Volume of liquid in the tank up to the desired height, [m^3]
method : str
One of 'spline', 'chebyshev', or 'brenth'
Returns
-------
h : float
Height of liquid at which the volume is as desired, [m] | [
"r",
"Method",
"to",
"calculate",
"the",
"height",
"of",
"liquid",
"in",
"a",
"fully",
"defined",
"tank",
"given",
"a",
"specified",
"volume",
"of",
"liquid",
"in",
"it",
"V",
".",
"V",
"must",
"be",
"under",
"the",
"maximum",
"volume",
".",
"If",
"the",
"method",
"is",
"spline",
"and",
"the",
"interpolation",
"table",
"is",
"not",
"yet",
"defined",
"creates",
"it",
"by",
"calling",
"the",
"method",
"set_table",
".",
"If",
"the",
"method",
"is",
"chebyshev",
"and",
"the",
"coefficients",
"have",
"not",
"yet",
"been",
"calculated",
"they",
"are",
"created",
"by",
"calling",
"set_chebyshev_approximators",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/geometry.py#L1746-L1779 | train |
CalebBell/fluids | fluids/geometry.py | TANK.set_table | def set_table(self, n=100, dx=None):
r'''Method to set an interpolation table of liquids levels versus
volumes in the tank, for a fully defined tank. Normally run by the
h_from_V method, this may be run prior to its use with a custom
specification. Either the number of points on the table, or the
vertical distance between steps may be specified.
Parameters
----------
n : float, optional
Number of points in the interpolation table, [-]
dx : float, optional
Vertical distance between steps in the interpolation table, [m]
'''
if dx:
self.heights = np.linspace(0, self.h_max, int(self.h_max/dx)+1)
else:
self.heights = np.linspace(0, self.h_max, n)
self.volumes = [self.V_from_h(h) for h in self.heights]
from scipy.interpolate import UnivariateSpline
self.interp_h_from_V = UnivariateSpline(self.volumes, self.heights, ext=3, s=0.0)
self.table = True | python | def set_table(self, n=100, dx=None):
r'''Method to set an interpolation table of liquids levels versus
volumes in the tank, for a fully defined tank. Normally run by the
h_from_V method, this may be run prior to its use with a custom
specification. Either the number of points on the table, or the
vertical distance between steps may be specified.
Parameters
----------
n : float, optional
Number of points in the interpolation table, [-]
dx : float, optional
Vertical distance between steps in the interpolation table, [m]
'''
if dx:
self.heights = np.linspace(0, self.h_max, int(self.h_max/dx)+1)
else:
self.heights = np.linspace(0, self.h_max, n)
self.volumes = [self.V_from_h(h) for h in self.heights]
from scipy.interpolate import UnivariateSpline
self.interp_h_from_V = UnivariateSpline(self.volumes, self.heights, ext=3, s=0.0)
self.table = True | [
"def",
"set_table",
"(",
"self",
",",
"n",
"=",
"100",
",",
"dx",
"=",
"None",
")",
":",
"if",
"dx",
":",
"self",
".",
"heights",
"=",
"np",
".",
"linspace",
"(",
"0",
",",
"self",
".",
"h_max",
",",
"int",
"(",
"self",
".",
"h_max",
"/",
"dx",
")",
"+",
"1",
")",
"else",
":",
"self",
".",
"heights",
"=",
"np",
".",
"linspace",
"(",
"0",
",",
"self",
".",
"h_max",
",",
"n",
")",
"self",
".",
"volumes",
"=",
"[",
"self",
".",
"V_from_h",
"(",
"h",
")",
"for",
"h",
"in",
"self",
".",
"heights",
"]",
"from",
"scipy",
".",
"interpolate",
"import",
"UnivariateSpline",
"self",
".",
"interp_h_from_V",
"=",
"UnivariateSpline",
"(",
"self",
".",
"volumes",
",",
"self",
".",
"heights",
",",
"ext",
"=",
"3",
",",
"s",
"=",
"0.0",
")",
"self",
".",
"table",
"=",
"True"
]
| r'''Method to set an interpolation table of liquids levels versus
volumes in the tank, for a fully defined tank. Normally run by the
h_from_V method, this may be run prior to its use with a custom
specification. Either the number of points on the table, or the
vertical distance between steps may be specified.
Parameters
----------
n : float, optional
Number of points in the interpolation table, [-]
dx : float, optional
Vertical distance between steps in the interpolation table, [m] | [
"r",
"Method",
"to",
"set",
"an",
"interpolation",
"table",
"of",
"liquids",
"levels",
"versus",
"volumes",
"in",
"the",
"tank",
"for",
"a",
"fully",
"defined",
"tank",
".",
"Normally",
"run",
"by",
"the",
"h_from_V",
"method",
"this",
"may",
"be",
"run",
"prior",
"to",
"its",
"use",
"with",
"a",
"custom",
"specification",
".",
"Either",
"the",
"number",
"of",
"points",
"on",
"the",
"table",
"or",
"the",
"vertical",
"distance",
"between",
"steps",
"may",
"be",
"specified",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/geometry.py#L1781-L1802 | train |
CalebBell/fluids | fluids/geometry.py | TANK._V_solver_error | def _V_solver_error(self, Vtarget, D, L, horizontal, sideA, sideB, sideA_a,
sideB_a, sideA_f, sideA_k, sideB_f, sideB_k,
sideA_a_ratio, sideB_a_ratio):
'''Function which uses only the variables given, and the TANK
class itself, to determine how far from the desired volume, Vtarget,
the volume produced by the specified parameters in a new TANK instance
is. Should only be used by solve_tank_for_V method.
'''
a = TANK(D=float(D), L=float(L), horizontal=horizontal, sideA=sideA, sideB=sideB,
sideA_a=sideA_a, sideB_a=sideB_a, sideA_f=sideA_f,
sideA_k=sideA_k, sideB_f=sideB_f, sideB_k=sideB_k,
sideA_a_ratio=sideA_a_ratio, sideB_a_ratio=sideB_a_ratio)
error = abs(Vtarget - a.V_total)
return error | python | def _V_solver_error(self, Vtarget, D, L, horizontal, sideA, sideB, sideA_a,
sideB_a, sideA_f, sideA_k, sideB_f, sideB_k,
sideA_a_ratio, sideB_a_ratio):
'''Function which uses only the variables given, and the TANK
class itself, to determine how far from the desired volume, Vtarget,
the volume produced by the specified parameters in a new TANK instance
is. Should only be used by solve_tank_for_V method.
'''
a = TANK(D=float(D), L=float(L), horizontal=horizontal, sideA=sideA, sideB=sideB,
sideA_a=sideA_a, sideB_a=sideB_a, sideA_f=sideA_f,
sideA_k=sideA_k, sideB_f=sideB_f, sideB_k=sideB_k,
sideA_a_ratio=sideA_a_ratio, sideB_a_ratio=sideB_a_ratio)
error = abs(Vtarget - a.V_total)
return error | [
"def",
"_V_solver_error",
"(",
"self",
",",
"Vtarget",
",",
"D",
",",
"L",
",",
"horizontal",
",",
"sideA",
",",
"sideB",
",",
"sideA_a",
",",
"sideB_a",
",",
"sideA_f",
",",
"sideA_k",
",",
"sideB_f",
",",
"sideB_k",
",",
"sideA_a_ratio",
",",
"sideB_a_ratio",
")",
":",
"a",
"=",
"TANK",
"(",
"D",
"=",
"float",
"(",
"D",
")",
",",
"L",
"=",
"float",
"(",
"L",
")",
",",
"horizontal",
"=",
"horizontal",
",",
"sideA",
"=",
"sideA",
",",
"sideB",
"=",
"sideB",
",",
"sideA_a",
"=",
"sideA_a",
",",
"sideB_a",
"=",
"sideB_a",
",",
"sideA_f",
"=",
"sideA_f",
",",
"sideA_k",
"=",
"sideA_k",
",",
"sideB_f",
"=",
"sideB_f",
",",
"sideB_k",
"=",
"sideB_k",
",",
"sideA_a_ratio",
"=",
"sideA_a_ratio",
",",
"sideB_a_ratio",
"=",
"sideB_a_ratio",
")",
"error",
"=",
"abs",
"(",
"Vtarget",
"-",
"a",
".",
"V_total",
")",
"return",
"error"
]
| Function which uses only the variables given, and the TANK
class itself, to determine how far from the desired volume, Vtarget,
the volume produced by the specified parameters in a new TANK instance
is. Should only be used by solve_tank_for_V method. | [
"Function",
"which",
"uses",
"only",
"the",
"variables",
"given",
"and",
"the",
"TANK",
"class",
"itself",
"to",
"determine",
"how",
"far",
"from",
"the",
"desired",
"volume",
"Vtarget",
"the",
"volume",
"produced",
"by",
"the",
"specified",
"parameters",
"in",
"a",
"new",
"TANK",
"instance",
"is",
".",
"Should",
"only",
"be",
"used",
"by",
"solve_tank_for_V",
"method",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/geometry.py#L1843-L1856 | train |
CalebBell/fluids | fluids/geometry.py | PlateExchanger.plate_exchanger_identifier | def plate_exchanger_identifier(self):
'''Method to create an identifying string in format 'L' + wavelength +
'A' + amplitude + 'B' + chevron angle-chevron angle. Wavelength and
amplitude are specified in units of mm and rounded to two decimal places.
'''
s = ('L' + str(round(self.wavelength*1000, 2))
+ 'A' + str(round(self.amplitude*1000, 2))
+ 'B' + '-'.join([str(i) for i in self.chevron_angles]))
return s | python | def plate_exchanger_identifier(self):
'''Method to create an identifying string in format 'L' + wavelength +
'A' + amplitude + 'B' + chevron angle-chevron angle. Wavelength and
amplitude are specified in units of mm and rounded to two decimal places.
'''
s = ('L' + str(round(self.wavelength*1000, 2))
+ 'A' + str(round(self.amplitude*1000, 2))
+ 'B' + '-'.join([str(i) for i in self.chevron_angles]))
return s | [
"def",
"plate_exchanger_identifier",
"(",
"self",
")",
":",
"s",
"=",
"(",
"'L'",
"+",
"str",
"(",
"round",
"(",
"self",
".",
"wavelength",
"*",
"1000",
",",
"2",
")",
")",
"+",
"'A'",
"+",
"str",
"(",
"round",
"(",
"self",
".",
"amplitude",
"*",
"1000",
",",
"2",
")",
")",
"+",
"'B'",
"+",
"'-'",
".",
"join",
"(",
"[",
"str",
"(",
"i",
")",
"for",
"i",
"in",
"self",
".",
"chevron_angles",
"]",
")",
")",
"return",
"s"
]
| Method to create an identifying string in format 'L' + wavelength +
'A' + amplitude + 'B' + chevron angle-chevron angle. Wavelength and
amplitude are specified in units of mm and rounded to two decimal places. | [
"Method",
"to",
"create",
"an",
"identifying",
"string",
"in",
"format",
"L",
"+",
"wavelength",
"+",
"A",
"+",
"amplitude",
"+",
"B",
"+",
"chevron",
"angle",
"-",
"chevron",
"angle",
".",
"Wavelength",
"and",
"amplitude",
"are",
"specified",
"in",
"units",
"of",
"mm",
"and",
"rounded",
"to",
"two",
"decimal",
"places",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/geometry.py#L2163-L2171 | train |
CalebBell/fluids | fluids/numerics/__init__.py | linspace | def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None):
'''Port of numpy's linspace to pure python. Does not support dtype, and
returns lists of floats.
'''
num = int(num)
start = start * 1.
stop = stop * 1.
if num <= 0:
return []
if endpoint:
if num == 1:
return [start]
step = (stop-start)/float((num-1))
if num == 1:
step = nan
y = [start]
for _ in range(num-2):
y.append(y[-1] + step)
y.append(stop)
else:
step = (stop-start)/float(num)
if num == 1:
step = nan
y = [start]
for _ in range(num-1):
y.append(y[-1] + step)
if retstep:
return y, step
else:
return y | python | def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None):
'''Port of numpy's linspace to pure python. Does not support dtype, and
returns lists of floats.
'''
num = int(num)
start = start * 1.
stop = stop * 1.
if num <= 0:
return []
if endpoint:
if num == 1:
return [start]
step = (stop-start)/float((num-1))
if num == 1:
step = nan
y = [start]
for _ in range(num-2):
y.append(y[-1] + step)
y.append(stop)
else:
step = (stop-start)/float(num)
if num == 1:
step = nan
y = [start]
for _ in range(num-1):
y.append(y[-1] + step)
if retstep:
return y, step
else:
return y | [
"def",
"linspace",
"(",
"start",
",",
"stop",
",",
"num",
"=",
"50",
",",
"endpoint",
"=",
"True",
",",
"retstep",
"=",
"False",
",",
"dtype",
"=",
"None",
")",
":",
"num",
"=",
"int",
"(",
"num",
")",
"start",
"=",
"start",
"*",
"1.",
"stop",
"=",
"stop",
"*",
"1.",
"if",
"num",
"<=",
"0",
":",
"return",
"[",
"]",
"if",
"endpoint",
":",
"if",
"num",
"==",
"1",
":",
"return",
"[",
"start",
"]",
"step",
"=",
"(",
"stop",
"-",
"start",
")",
"/",
"float",
"(",
"(",
"num",
"-",
"1",
")",
")",
"if",
"num",
"==",
"1",
":",
"step",
"=",
"nan",
"y",
"=",
"[",
"start",
"]",
"for",
"_",
"in",
"range",
"(",
"num",
"-",
"2",
")",
":",
"y",
".",
"append",
"(",
"y",
"[",
"-",
"1",
"]",
"+",
"step",
")",
"y",
".",
"append",
"(",
"stop",
")",
"else",
":",
"step",
"=",
"(",
"stop",
"-",
"start",
")",
"/",
"float",
"(",
"num",
")",
"if",
"num",
"==",
"1",
":",
"step",
"=",
"nan",
"y",
"=",
"[",
"start",
"]",
"for",
"_",
"in",
"range",
"(",
"num",
"-",
"1",
")",
":",
"y",
".",
"append",
"(",
"y",
"[",
"-",
"1",
"]",
"+",
"step",
")",
"if",
"retstep",
":",
"return",
"y",
",",
"step",
"else",
":",
"return",
"y"
]
| Port of numpy's linspace to pure python. Does not support dtype, and
returns lists of floats. | [
"Port",
"of",
"numpy",
"s",
"linspace",
"to",
"pure",
"python",
".",
"Does",
"not",
"support",
"dtype",
"and",
"returns",
"lists",
"of",
"floats",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/numerics/__init__.py#L361-L392 | train |
CalebBell/fluids | fluids/numerics/__init__.py | derivative | def derivative(func, x0, dx=1.0, n=1, args=(), order=3):
'''Reimplementation of SciPy's derivative function, with more cached
coefficients and without using numpy. If new coefficients not cached are
needed, they are only calculated once and are remembered.
'''
if order < n + 1:
raise ValueError
if order % 2 == 0:
raise ValueError
weights = central_diff_weights(order, n)
tot = 0.0
ho = order >> 1
for k in range(order):
tot += weights[k]*func(x0 + (k - ho)*dx, *args)
return tot/product([dx]*n) | python | def derivative(func, x0, dx=1.0, n=1, args=(), order=3):
'''Reimplementation of SciPy's derivative function, with more cached
coefficients and without using numpy. If new coefficients not cached are
needed, they are only calculated once and are remembered.
'''
if order < n + 1:
raise ValueError
if order % 2 == 0:
raise ValueError
weights = central_diff_weights(order, n)
tot = 0.0
ho = order >> 1
for k in range(order):
tot += weights[k]*func(x0 + (k - ho)*dx, *args)
return tot/product([dx]*n) | [
"def",
"derivative",
"(",
"func",
",",
"x0",
",",
"dx",
"=",
"1.0",
",",
"n",
"=",
"1",
",",
"args",
"=",
"(",
")",
",",
"order",
"=",
"3",
")",
":",
"if",
"order",
"<",
"n",
"+",
"1",
":",
"raise",
"ValueError",
"if",
"order",
"%",
"2",
"==",
"0",
":",
"raise",
"ValueError",
"weights",
"=",
"central_diff_weights",
"(",
"order",
",",
"n",
")",
"tot",
"=",
"0.0",
"ho",
"=",
"order",
">>",
"1",
"for",
"k",
"in",
"range",
"(",
"order",
")",
":",
"tot",
"+=",
"weights",
"[",
"k",
"]",
"*",
"func",
"(",
"x0",
"+",
"(",
"k",
"-",
"ho",
")",
"*",
"dx",
",",
"*",
"args",
")",
"return",
"tot",
"/",
"product",
"(",
"[",
"dx",
"]",
"*",
"n",
")"
]
| Reimplementation of SciPy's derivative function, with more cached
coefficients and without using numpy. If new coefficients not cached are
needed, they are only calculated once and are remembered. | [
"Reimplementation",
"of",
"SciPy",
"s",
"derivative",
"function",
"with",
"more",
"cached",
"coefficients",
"and",
"without",
"using",
"numpy",
".",
"If",
"new",
"coefficients",
"not",
"cached",
"are",
"needed",
"they",
"are",
"only",
"calculated",
"once",
"and",
"are",
"remembered",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/numerics/__init__.py#L547-L561 | train |
CalebBell/fluids | fluids/numerics/__init__.py | polyder | def polyder(c, m=1, scl=1, axis=0):
'''not quite a copy of numpy's version because this was faster to implement.
'''
c = list(c)
cnt = int(m)
if cnt == 0:
return c
n = len(c)
if cnt >= n:
c = c[:1]*0
else:
for i in range(cnt):
n = n - 1
c *= scl
der = [0.0 for _ in range(n)]
for j in range(n, 0, -1):
der[j - 1] = j*c[j]
c = der
return c | python | def polyder(c, m=1, scl=1, axis=0):
'''not quite a copy of numpy's version because this was faster to implement.
'''
c = list(c)
cnt = int(m)
if cnt == 0:
return c
n = len(c)
if cnt >= n:
c = c[:1]*0
else:
for i in range(cnt):
n = n - 1
c *= scl
der = [0.0 for _ in range(n)]
for j in range(n, 0, -1):
der[j - 1] = j*c[j]
c = der
return c | [
"def",
"polyder",
"(",
"c",
",",
"m",
"=",
"1",
",",
"scl",
"=",
"1",
",",
"axis",
"=",
"0",
")",
":",
"c",
"=",
"list",
"(",
"c",
")",
"cnt",
"=",
"int",
"(",
"m",
")",
"if",
"cnt",
"==",
"0",
":",
"return",
"c",
"n",
"=",
"len",
"(",
"c",
")",
"if",
"cnt",
">=",
"n",
":",
"c",
"=",
"c",
"[",
":",
"1",
"]",
"*",
"0",
"else",
":",
"for",
"i",
"in",
"range",
"(",
"cnt",
")",
":",
"n",
"=",
"n",
"-",
"1",
"c",
"*=",
"scl",
"der",
"=",
"[",
"0.0",
"for",
"_",
"in",
"range",
"(",
"n",
")",
"]",
"for",
"j",
"in",
"range",
"(",
"n",
",",
"0",
",",
"-",
"1",
")",
":",
"der",
"[",
"j",
"-",
"1",
"]",
"=",
"j",
"*",
"c",
"[",
"j",
"]",
"c",
"=",
"der",
"return",
"c"
]
| not quite a copy of numpy's version because this was faster to implement. | [
"not",
"quite",
"a",
"copy",
"of",
"numpy",
"s",
"version",
"because",
"this",
"was",
"faster",
"to",
"implement",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/numerics/__init__.py#L620-L640 | train |
CalebBell/fluids | fluids/numerics/__init__.py | horner_log | def horner_log(coeffs, log_coeff, x):
'''Technically possible to save one addition of the last term of
coeffs is removed but benchmarks said nothing was saved'''
tot = 0.0
for c in coeffs:
tot = tot*x + c
return tot + log_coeff*log(x) | python | def horner_log(coeffs, log_coeff, x):
'''Technically possible to save one addition of the last term of
coeffs is removed but benchmarks said nothing was saved'''
tot = 0.0
for c in coeffs:
tot = tot*x + c
return tot + log_coeff*log(x) | [
"def",
"horner_log",
"(",
"coeffs",
",",
"log_coeff",
",",
"x",
")",
":",
"tot",
"=",
"0.0",
"for",
"c",
"in",
"coeffs",
":",
"tot",
"=",
"tot",
"*",
"x",
"+",
"c",
"return",
"tot",
"+",
"log_coeff",
"*",
"log",
"(",
"x",
")"
]
| Technically possible to save one addition of the last term of
coeffs is removed but benchmarks said nothing was saved | [
"Technically",
"possible",
"to",
"save",
"one",
"addition",
"of",
"the",
"last",
"term",
"of",
"coeffs",
"is",
"removed",
"but",
"benchmarks",
"said",
"nothing",
"was",
"saved"
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/numerics/__init__.py#L679-L685 | train |
CalebBell/fluids | fluids/numerics/__init__.py | implementation_optimize_tck | def implementation_optimize_tck(tck):
'''Converts 1-d or 2-d splines calculated with SciPy's `splrep` or
`bisplrep` to a format for fastest computation - lists in PyPy, and numpy
arrays otherwise.
Only implemented for 3 and 5 length `tck`s.
'''
if IS_PYPY:
return tck
else:
if len(tck) == 3:
tck[0] = np.array(tck[0])
tck[1] = np.array(tck[1])
elif len(tck) == 5:
tck[0] = np.array(tck[0])
tck[1] = np.array(tck[1])
tck[2] = np.array(tck[2])
else:
raise NotImplementedError
return tck | python | def implementation_optimize_tck(tck):
'''Converts 1-d or 2-d splines calculated with SciPy's `splrep` or
`bisplrep` to a format for fastest computation - lists in PyPy, and numpy
arrays otherwise.
Only implemented for 3 and 5 length `tck`s.
'''
if IS_PYPY:
return tck
else:
if len(tck) == 3:
tck[0] = np.array(tck[0])
tck[1] = np.array(tck[1])
elif len(tck) == 5:
tck[0] = np.array(tck[0])
tck[1] = np.array(tck[1])
tck[2] = np.array(tck[2])
else:
raise NotImplementedError
return tck | [
"def",
"implementation_optimize_tck",
"(",
"tck",
")",
":",
"if",
"IS_PYPY",
":",
"return",
"tck",
"else",
":",
"if",
"len",
"(",
"tck",
")",
"==",
"3",
":",
"tck",
"[",
"0",
"]",
"=",
"np",
".",
"array",
"(",
"tck",
"[",
"0",
"]",
")",
"tck",
"[",
"1",
"]",
"=",
"np",
".",
"array",
"(",
"tck",
"[",
"1",
"]",
")",
"elif",
"len",
"(",
"tck",
")",
"==",
"5",
":",
"tck",
"[",
"0",
"]",
"=",
"np",
".",
"array",
"(",
"tck",
"[",
"0",
"]",
")",
"tck",
"[",
"1",
"]",
"=",
"np",
".",
"array",
"(",
"tck",
"[",
"1",
"]",
")",
"tck",
"[",
"2",
"]",
"=",
"np",
".",
"array",
"(",
"tck",
"[",
"2",
"]",
")",
"else",
":",
"raise",
"NotImplementedError",
"return",
"tck"
]
| Converts 1-d or 2-d splines calculated with SciPy's `splrep` or
`bisplrep` to a format for fastest computation - lists in PyPy, and numpy
arrays otherwise.
Only implemented for 3 and 5 length `tck`s. | [
"Converts",
"1",
"-",
"d",
"or",
"2",
"-",
"d",
"splines",
"calculated",
"with",
"SciPy",
"s",
"splrep",
"or",
"bisplrep",
"to",
"a",
"format",
"for",
"fastest",
"computation",
"-",
"lists",
"in",
"PyPy",
"and",
"numpy",
"arrays",
"otherwise",
".",
"Only",
"implemented",
"for",
"3",
"and",
"5",
"length",
"tck",
"s",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/numerics/__init__.py#L870-L889 | train |
CalebBell/fluids | fluids/numerics/__init__.py | py_bisect | def py_bisect(f, a, b, args=(), xtol=_xtol, rtol=_rtol, maxiter=_iter,
ytol=None, full_output=False, disp=True):
'''Port of SciPy's C bisect routine.
'''
fa = f(a, *args)
fb = f(b, *args)
if fa*fb > 0.0:
raise ValueError("f(a) and f(b) must have different signs")
elif fa == 0.0:
return a
elif fb == 0.0:
return b
dm = b - a
iterations = 0.0
for i in range(maxiter):
dm *= 0.5
xm = a + dm
fm = f(xm, *args)
if fm*fa >= 0.0:
a = xm
abs_dm = fabs(dm)
if fm == 0.0:
return xm
elif ytol is not None:
if (abs_dm < xtol + rtol*abs_dm) and abs(fm) < ytol:
return xm
elif (abs_dm < xtol + rtol*abs_dm):
return xm
raise UnconvergedError("Failed to converge after %d iterations" %maxiter) | python | def py_bisect(f, a, b, args=(), xtol=_xtol, rtol=_rtol, maxiter=_iter,
ytol=None, full_output=False, disp=True):
'''Port of SciPy's C bisect routine.
'''
fa = f(a, *args)
fb = f(b, *args)
if fa*fb > 0.0:
raise ValueError("f(a) and f(b) must have different signs")
elif fa == 0.0:
return a
elif fb == 0.0:
return b
dm = b - a
iterations = 0.0
for i in range(maxiter):
dm *= 0.5
xm = a + dm
fm = f(xm, *args)
if fm*fa >= 0.0:
a = xm
abs_dm = fabs(dm)
if fm == 0.0:
return xm
elif ytol is not None:
if (abs_dm < xtol + rtol*abs_dm) and abs(fm) < ytol:
return xm
elif (abs_dm < xtol + rtol*abs_dm):
return xm
raise UnconvergedError("Failed to converge after %d iterations" %maxiter) | [
"def",
"py_bisect",
"(",
"f",
",",
"a",
",",
"b",
",",
"args",
"=",
"(",
")",
",",
"xtol",
"=",
"_xtol",
",",
"rtol",
"=",
"_rtol",
",",
"maxiter",
"=",
"_iter",
",",
"ytol",
"=",
"None",
",",
"full_output",
"=",
"False",
",",
"disp",
"=",
"True",
")",
":",
"fa",
"=",
"f",
"(",
"a",
",",
"*",
"args",
")",
"fb",
"=",
"f",
"(",
"b",
",",
"*",
"args",
")",
"if",
"fa",
"*",
"fb",
">",
"0.0",
":",
"raise",
"ValueError",
"(",
"\"f(a) and f(b) must have different signs\"",
")",
"elif",
"fa",
"==",
"0.0",
":",
"return",
"a",
"elif",
"fb",
"==",
"0.0",
":",
"return",
"b",
"dm",
"=",
"b",
"-",
"a",
"iterations",
"=",
"0.0",
"for",
"i",
"in",
"range",
"(",
"maxiter",
")",
":",
"dm",
"*=",
"0.5",
"xm",
"=",
"a",
"+",
"dm",
"fm",
"=",
"f",
"(",
"xm",
",",
"*",
"args",
")",
"if",
"fm",
"*",
"fa",
">=",
"0.0",
":",
"a",
"=",
"xm",
"abs_dm",
"=",
"fabs",
"(",
"dm",
")",
"if",
"fm",
"==",
"0.0",
":",
"return",
"xm",
"elif",
"ytol",
"is",
"not",
"None",
":",
"if",
"(",
"abs_dm",
"<",
"xtol",
"+",
"rtol",
"*",
"abs_dm",
")",
"and",
"abs",
"(",
"fm",
")",
"<",
"ytol",
":",
"return",
"xm",
"elif",
"(",
"abs_dm",
"<",
"xtol",
"+",
"rtol",
"*",
"abs_dm",
")",
":",
"return",
"xm",
"raise",
"UnconvergedError",
"(",
"\"Failed to converge after %d iterations\"",
"%",
"maxiter",
")"
]
| Port of SciPy's C bisect routine. | [
"Port",
"of",
"SciPy",
"s",
"C",
"bisect",
"routine",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/numerics/__init__.py#L1058-L1089 | train |
CalebBell/fluids | fluids/control_valve.py | is_choked_turbulent_l | def is_choked_turbulent_l(dP, P1, Psat, FF, FL=None, FLP=None, FP=None):
r'''Calculates if a liquid flow in IEC 60534 calculations is critical or
not, for use in IEC 60534 liquid valve sizing calculations.
Either FL may be provided or FLP and FP, depending on the calculation
process.
.. math::
\Delta P > F_L^2(P_1 - F_F P_{sat})
.. math::
\Delta P >= \left(\frac{F_{LP}}{F_P}\right)^2(P_1 - F_F P_{sat})
Parameters
----------
dP : float
Differential pressure across the valve, with reducer/expanders [Pa]
P1 : float
Pressure of the fluid before the valve and reducers/expanders [Pa]
Psat : float
Saturation pressure of the fluid at inlet temperature [Pa]
FF : float
Liquid critical pressure ratio factor [-]
FL : float, optional
Liquid pressure recovery factor of a control valve without attached fittings [-]
FLP : float, optional
Combined liquid pressure recovery factor with piping geometry factor,
for a control valve with attached fittings [-]
FP : float, optional
Piping geometry factor [-]
Returns
-------
choked : bool
Whether or not the flow is choked [-]
Examples
--------
>>> is_choked_turbulent_l(460.0, 680.0, 70.1, 0.94, 0.9)
False
>>> is_choked_turbulent_l(460.0, 680.0, 70.1, 0.94, 0.6)
True
References
----------
.. [1] IEC 60534-2-1 / ISA-75.01.01-2007
'''
if FLP and FP:
return dP >= (FLP/FP)**2*(P1-FF*Psat)
elif FL:
return dP >= FL**2*(P1-FF*Psat)
else:
raise Exception('Either (FLP and FP) or FL is needed') | python | def is_choked_turbulent_l(dP, P1, Psat, FF, FL=None, FLP=None, FP=None):
r'''Calculates if a liquid flow in IEC 60534 calculations is critical or
not, for use in IEC 60534 liquid valve sizing calculations.
Either FL may be provided or FLP and FP, depending on the calculation
process.
.. math::
\Delta P > F_L^2(P_1 - F_F P_{sat})
.. math::
\Delta P >= \left(\frac{F_{LP}}{F_P}\right)^2(P_1 - F_F P_{sat})
Parameters
----------
dP : float
Differential pressure across the valve, with reducer/expanders [Pa]
P1 : float
Pressure of the fluid before the valve and reducers/expanders [Pa]
Psat : float
Saturation pressure of the fluid at inlet temperature [Pa]
FF : float
Liquid critical pressure ratio factor [-]
FL : float, optional
Liquid pressure recovery factor of a control valve without attached fittings [-]
FLP : float, optional
Combined liquid pressure recovery factor with piping geometry factor,
for a control valve with attached fittings [-]
FP : float, optional
Piping geometry factor [-]
Returns
-------
choked : bool
Whether or not the flow is choked [-]
Examples
--------
>>> is_choked_turbulent_l(460.0, 680.0, 70.1, 0.94, 0.9)
False
>>> is_choked_turbulent_l(460.0, 680.0, 70.1, 0.94, 0.6)
True
References
----------
.. [1] IEC 60534-2-1 / ISA-75.01.01-2007
'''
if FLP and FP:
return dP >= (FLP/FP)**2*(P1-FF*Psat)
elif FL:
return dP >= FL**2*(P1-FF*Psat)
else:
raise Exception('Either (FLP and FP) or FL is needed') | [
"def",
"is_choked_turbulent_l",
"(",
"dP",
",",
"P1",
",",
"Psat",
",",
"FF",
",",
"FL",
"=",
"None",
",",
"FLP",
"=",
"None",
",",
"FP",
"=",
"None",
")",
":",
"if",
"FLP",
"and",
"FP",
":",
"return",
"dP",
">=",
"(",
"FLP",
"/",
"FP",
")",
"**",
"2",
"*",
"(",
"P1",
"-",
"FF",
"*",
"Psat",
")",
"elif",
"FL",
":",
"return",
"dP",
">=",
"FL",
"**",
"2",
"*",
"(",
"P1",
"-",
"FF",
"*",
"Psat",
")",
"else",
":",
"raise",
"Exception",
"(",
"'Either (FLP and FP) or FL is needed'",
")"
]
| r'''Calculates if a liquid flow in IEC 60534 calculations is critical or
not, for use in IEC 60534 liquid valve sizing calculations.
Either FL may be provided or FLP and FP, depending on the calculation
process.
.. math::
\Delta P > F_L^2(P_1 - F_F P_{sat})
.. math::
\Delta P >= \left(\frac{F_{LP}}{F_P}\right)^2(P_1 - F_F P_{sat})
Parameters
----------
dP : float
Differential pressure across the valve, with reducer/expanders [Pa]
P1 : float
Pressure of the fluid before the valve and reducers/expanders [Pa]
Psat : float
Saturation pressure of the fluid at inlet temperature [Pa]
FF : float
Liquid critical pressure ratio factor [-]
FL : float, optional
Liquid pressure recovery factor of a control valve without attached fittings [-]
FLP : float, optional
Combined liquid pressure recovery factor with piping geometry factor,
for a control valve with attached fittings [-]
FP : float, optional
Piping geometry factor [-]
Returns
-------
choked : bool
Whether or not the flow is choked [-]
Examples
--------
>>> is_choked_turbulent_l(460.0, 680.0, 70.1, 0.94, 0.9)
False
>>> is_choked_turbulent_l(460.0, 680.0, 70.1, 0.94, 0.6)
True
References
----------
.. [1] IEC 60534-2-1 / ISA-75.01.01-2007 | [
"r",
"Calculates",
"if",
"a",
"liquid",
"flow",
"in",
"IEC",
"60534",
"calculations",
"is",
"critical",
"or",
"not",
"for",
"use",
"in",
"IEC",
"60534",
"liquid",
"valve",
"sizing",
"calculations",
".",
"Either",
"FL",
"may",
"be",
"provided",
"or",
"FLP",
"and",
"FP",
"depending",
"on",
"the",
"calculation",
"process",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/control_valve.py#L259-L310 | train |
CalebBell/fluids | fluids/control_valve.py | is_choked_turbulent_g | def is_choked_turbulent_g(x, Fgamma, xT=None, xTP=None):
r'''Calculates if a gas flow in IEC 60534 calculations is critical or
not, for use in IEC 60534 gas valve sizing calculations.
Either xT or xTP must be provided, depending on the calculation process.
.. math::
x \ge F_\gamma x_T
.. math::
x \ge F_\gamma x_{TP}
Parameters
----------
x : float
Differential pressure over inlet pressure, [-]
Fgamma : float
Specific heat ratio factor [-]
xT : float, optional
Pressure difference ratio factor of a valve without fittings at choked
flow [-]
xTP : float
Pressure difference ratio factor of a valve with fittings at choked
flow [-]
Returns
-------
choked : bool
Whether or not the flow is choked [-]
Examples
--------
Example 3, compressible flow, non-choked with attached fittings:
>>> is_choked_turbulent_g(0.544, 0.929, 0.6)
False
>>> is_choked_turbulent_g(0.544, 0.929, xTP=0.625)
False
References
----------
.. [1] IEC 60534-2-1 / ISA-75.01.01-2007
'''
if xT:
return x >= Fgamma*xT
elif xTP:
return x >= Fgamma*xTP
else:
raise Exception('Either xT or xTP is needed') | python | def is_choked_turbulent_g(x, Fgamma, xT=None, xTP=None):
r'''Calculates if a gas flow in IEC 60534 calculations is critical or
not, for use in IEC 60534 gas valve sizing calculations.
Either xT or xTP must be provided, depending on the calculation process.
.. math::
x \ge F_\gamma x_T
.. math::
x \ge F_\gamma x_{TP}
Parameters
----------
x : float
Differential pressure over inlet pressure, [-]
Fgamma : float
Specific heat ratio factor [-]
xT : float, optional
Pressure difference ratio factor of a valve without fittings at choked
flow [-]
xTP : float
Pressure difference ratio factor of a valve with fittings at choked
flow [-]
Returns
-------
choked : bool
Whether or not the flow is choked [-]
Examples
--------
Example 3, compressible flow, non-choked with attached fittings:
>>> is_choked_turbulent_g(0.544, 0.929, 0.6)
False
>>> is_choked_turbulent_g(0.544, 0.929, xTP=0.625)
False
References
----------
.. [1] IEC 60534-2-1 / ISA-75.01.01-2007
'''
if xT:
return x >= Fgamma*xT
elif xTP:
return x >= Fgamma*xTP
else:
raise Exception('Either xT or xTP is needed') | [
"def",
"is_choked_turbulent_g",
"(",
"x",
",",
"Fgamma",
",",
"xT",
"=",
"None",
",",
"xTP",
"=",
"None",
")",
":",
"if",
"xT",
":",
"return",
"x",
">=",
"Fgamma",
"*",
"xT",
"elif",
"xTP",
":",
"return",
"x",
">=",
"Fgamma",
"*",
"xTP",
"else",
":",
"raise",
"Exception",
"(",
"'Either xT or xTP is needed'",
")"
]
| r'''Calculates if a gas flow in IEC 60534 calculations is critical or
not, for use in IEC 60534 gas valve sizing calculations.
Either xT or xTP must be provided, depending on the calculation process.
.. math::
x \ge F_\gamma x_T
.. math::
x \ge F_\gamma x_{TP}
Parameters
----------
x : float
Differential pressure over inlet pressure, [-]
Fgamma : float
Specific heat ratio factor [-]
xT : float, optional
Pressure difference ratio factor of a valve without fittings at choked
flow [-]
xTP : float
Pressure difference ratio factor of a valve with fittings at choked
flow [-]
Returns
-------
choked : bool
Whether or not the flow is choked [-]
Examples
--------
Example 3, compressible flow, non-choked with attached fittings:
>>> is_choked_turbulent_g(0.544, 0.929, 0.6)
False
>>> is_choked_turbulent_g(0.544, 0.929, xTP=0.625)
False
References
----------
.. [1] IEC 60534-2-1 / ISA-75.01.01-2007 | [
"r",
"Calculates",
"if",
"a",
"gas",
"flow",
"in",
"IEC",
"60534",
"calculations",
"is",
"critical",
"or",
"not",
"for",
"use",
"in",
"IEC",
"60534",
"gas",
"valve",
"sizing",
"calculations",
".",
"Either",
"xT",
"or",
"xTP",
"must",
"be",
"provided",
"depending",
"on",
"the",
"calculation",
"process",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/control_valve.py#L313-L360 | train |
CalebBell/fluids | fluids/control_valve.py | Reynolds_valve | def Reynolds_valve(nu, Q, D1, FL, Fd, C):
r'''Calculates Reynolds number of a control valve for a liquid or gas
flowing through it at a specified Q, for a specified D1, FL, Fd, C, and
with kinematic viscosity `nu` according to IEC 60534 calculations.
.. math::
Re_v = \frac{N_4 F_d Q}{\nu \sqrt{C F_L}}\left(\frac{F_L^2 C^2}
{N_2D^4} +1\right)^{1/4}
Parameters
----------
nu : float
Kinematic viscosity, [m^2/s]
Q : float
Volumetric flow rate of the fluid [m^3/s]
D1 : float
Diameter of the pipe before the valve [m]
FL : float, optional
Liquid pressure recovery factor of a control valve without attached
fittings []
Fd : float
Valve style modifier [-]
C : float
Metric Kv valve flow coefficient (flow rate of water at a pressure drop
of 1 bar) [m^3/hr]
Returns
-------
Rev : float
Valve reynolds number [-]
Examples
--------
>>> Reynolds_valve(3.26e-07, 360, 150.0, 0.9, 0.46, 165)
2966984.7525455453
References
----------
.. [1] IEC 60534-2-1 / ISA-75.01.01-2007
'''
return N4*Fd*Q/nu/(C*FL)**0.5*(FL**2*C**2/(N2*D1**4) + 1)**0.25 | python | def Reynolds_valve(nu, Q, D1, FL, Fd, C):
r'''Calculates Reynolds number of a control valve for a liquid or gas
flowing through it at a specified Q, for a specified D1, FL, Fd, C, and
with kinematic viscosity `nu` according to IEC 60534 calculations.
.. math::
Re_v = \frac{N_4 F_d Q}{\nu \sqrt{C F_L}}\left(\frac{F_L^2 C^2}
{N_2D^4} +1\right)^{1/4}
Parameters
----------
nu : float
Kinematic viscosity, [m^2/s]
Q : float
Volumetric flow rate of the fluid [m^3/s]
D1 : float
Diameter of the pipe before the valve [m]
FL : float, optional
Liquid pressure recovery factor of a control valve without attached
fittings []
Fd : float
Valve style modifier [-]
C : float
Metric Kv valve flow coefficient (flow rate of water at a pressure drop
of 1 bar) [m^3/hr]
Returns
-------
Rev : float
Valve reynolds number [-]
Examples
--------
>>> Reynolds_valve(3.26e-07, 360, 150.0, 0.9, 0.46, 165)
2966984.7525455453
References
----------
.. [1] IEC 60534-2-1 / ISA-75.01.01-2007
'''
return N4*Fd*Q/nu/(C*FL)**0.5*(FL**2*C**2/(N2*D1**4) + 1)**0.25 | [
"def",
"Reynolds_valve",
"(",
"nu",
",",
"Q",
",",
"D1",
",",
"FL",
",",
"Fd",
",",
"C",
")",
":",
"return",
"N4",
"*",
"Fd",
"*",
"Q",
"/",
"nu",
"/",
"(",
"C",
"*",
"FL",
")",
"**",
"0.5",
"*",
"(",
"FL",
"**",
"2",
"*",
"C",
"**",
"2",
"/",
"(",
"N2",
"*",
"D1",
"**",
"4",
")",
"+",
"1",
")",
"**",
"0.25"
]
| r'''Calculates Reynolds number of a control valve for a liquid or gas
flowing through it at a specified Q, for a specified D1, FL, Fd, C, and
with kinematic viscosity `nu` according to IEC 60534 calculations.
.. math::
Re_v = \frac{N_4 F_d Q}{\nu \sqrt{C F_L}}\left(\frac{F_L^2 C^2}
{N_2D^4} +1\right)^{1/4}
Parameters
----------
nu : float
Kinematic viscosity, [m^2/s]
Q : float
Volumetric flow rate of the fluid [m^3/s]
D1 : float
Diameter of the pipe before the valve [m]
FL : float, optional
Liquid pressure recovery factor of a control valve without attached
fittings []
Fd : float
Valve style modifier [-]
C : float
Metric Kv valve flow coefficient (flow rate of water at a pressure drop
of 1 bar) [m^3/hr]
Returns
-------
Rev : float
Valve reynolds number [-]
Examples
--------
>>> Reynolds_valve(3.26e-07, 360, 150.0, 0.9, 0.46, 165)
2966984.7525455453
References
----------
.. [1] IEC 60534-2-1 / ISA-75.01.01-2007 | [
"r",
"Calculates",
"Reynolds",
"number",
"of",
"a",
"control",
"valve",
"for",
"a",
"liquid",
"or",
"gas",
"flowing",
"through",
"it",
"at",
"a",
"specified",
"Q",
"for",
"a",
"specified",
"D1",
"FL",
"Fd",
"C",
"and",
"with",
"kinematic",
"viscosity",
"nu",
"according",
"to",
"IEC",
"60534",
"calculations",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/control_valve.py#L363-L403 | train |
CalebBell/fluids | fluids/control_valve.py | Reynolds_factor | def Reynolds_factor(FL, C, d, Rev, full_trim=True):
r'''Calculates the Reynolds number factor `FR` for a valve with a Reynolds
number `Rev`, diameter `d`, flow coefficient `C`, liquid pressure recovery
factor `FL`, and with either full or reduced trim, all according to
IEC 60534 calculations.
If full trim:
.. math::
F_{R,1a} = 1 + \left(\frac{0.33F_L^{0.5}}{n_1^{0.25}}\right)\log_{10}
\left(\frac{Re_v}{10000}\right)
.. math::
F_{R,2} = \min(\frac{0.026}{F_L}\sqrt{n_1 Re_v},\; 1)
.. math::
n_1 = \frac{N_2}{\left(\frac{C}{d^2}\right)^2}
.. math::
F_R = F_{R,2} \text{ if Rev < 10 else } \min(F_{R,1a}, F_{R,2})
Otherwise :
.. math::
F_{R,3a} = 1 + \left(\frac{0.33F_L^{0.5}}{n_2^{0.25}}\right)\log_{10}
\left(\frac{Re_v}{10000}\right)
.. math::
F_{R,4} = \frac{0.026}{F_L}\sqrt{n_2 Re_v}
.. math::
n_2 = 1 + N_{32}\left(\frac{C}{d}\right)^{2/3}
.. math::
F_R = F_{R,4} \text{ if Rev < 10 else } \min(F_{R,3a}, F_{R,4})
Parameters
----------
FL : float
Liquid pressure recovery factor of a control valve without attached
fittings []
C : float
Metric Kv valve flow coefficient (flow rate of water at a pressure drop
of 1 bar) [m^3/hr]
d : float
Diameter of the valve [m]
Rev : float
Valve reynolds number [-]
full_trim : bool
Whether or not the valve has full trim
Returns
-------
FR : float
Reynolds number factor for laminar or transitional flow []
Examples
--------
In Example 4, compressible flow with small flow trim sized for gas flow
(Cv in the problem was converted to Kv here to make FR match with N32, N2):
>>> Reynolds_factor(FL=0.98, C=0.015483, d=15., Rev=1202., full_trim=False)
0.7148753122302025
References
----------
.. [1] IEC 60534-2-1 / ISA-75.01.01-2007
'''
if full_trim:
n1 = N2/(min(C/d**2, 0.04))**2 # C/d**2 must not exceed 0.04
FR_1a = 1 + (0.33*FL**0.5)/n1**0.25*log10(Rev/10000.)
FR_2 = 0.026/FL*(n1*Rev)**0.5
if Rev < 10:
FR = FR_2
else:
FR = min(FR_2, FR_1a)
else:
n2 = 1 + N32*(C/d**2)**(2/3.)
FR_3a = 1 + (0.33*FL**0.5)/n2**0.25*log10(Rev/10000.)
FR_4 = min(0.026/FL*(n2*Rev)**0.5, 1)
if Rev < 10:
FR = FR_4
else:
FR = min(FR_3a, FR_4)
return FR | python | def Reynolds_factor(FL, C, d, Rev, full_trim=True):
r'''Calculates the Reynolds number factor `FR` for a valve with a Reynolds
number `Rev`, diameter `d`, flow coefficient `C`, liquid pressure recovery
factor `FL`, and with either full or reduced trim, all according to
IEC 60534 calculations.
If full trim:
.. math::
F_{R,1a} = 1 + \left(\frac{0.33F_L^{0.5}}{n_1^{0.25}}\right)\log_{10}
\left(\frac{Re_v}{10000}\right)
.. math::
F_{R,2} = \min(\frac{0.026}{F_L}\sqrt{n_1 Re_v},\; 1)
.. math::
n_1 = \frac{N_2}{\left(\frac{C}{d^2}\right)^2}
.. math::
F_R = F_{R,2} \text{ if Rev < 10 else } \min(F_{R,1a}, F_{R,2})
Otherwise :
.. math::
F_{R,3a} = 1 + \left(\frac{0.33F_L^{0.5}}{n_2^{0.25}}\right)\log_{10}
\left(\frac{Re_v}{10000}\right)
.. math::
F_{R,4} = \frac{0.026}{F_L}\sqrt{n_2 Re_v}
.. math::
n_2 = 1 + N_{32}\left(\frac{C}{d}\right)^{2/3}
.. math::
F_R = F_{R,4} \text{ if Rev < 10 else } \min(F_{R,3a}, F_{R,4})
Parameters
----------
FL : float
Liquid pressure recovery factor of a control valve without attached
fittings []
C : float
Metric Kv valve flow coefficient (flow rate of water at a pressure drop
of 1 bar) [m^3/hr]
d : float
Diameter of the valve [m]
Rev : float
Valve reynolds number [-]
full_trim : bool
Whether or not the valve has full trim
Returns
-------
FR : float
Reynolds number factor for laminar or transitional flow []
Examples
--------
In Example 4, compressible flow with small flow trim sized for gas flow
(Cv in the problem was converted to Kv here to make FR match with N32, N2):
>>> Reynolds_factor(FL=0.98, C=0.015483, d=15., Rev=1202., full_trim=False)
0.7148753122302025
References
----------
.. [1] IEC 60534-2-1 / ISA-75.01.01-2007
'''
if full_trim:
n1 = N2/(min(C/d**2, 0.04))**2 # C/d**2 must not exceed 0.04
FR_1a = 1 + (0.33*FL**0.5)/n1**0.25*log10(Rev/10000.)
FR_2 = 0.026/FL*(n1*Rev)**0.5
if Rev < 10:
FR = FR_2
else:
FR = min(FR_2, FR_1a)
else:
n2 = 1 + N32*(C/d**2)**(2/3.)
FR_3a = 1 + (0.33*FL**0.5)/n2**0.25*log10(Rev/10000.)
FR_4 = min(0.026/FL*(n2*Rev)**0.5, 1)
if Rev < 10:
FR = FR_4
else:
FR = min(FR_3a, FR_4)
return FR | [
"def",
"Reynolds_factor",
"(",
"FL",
",",
"C",
",",
"d",
",",
"Rev",
",",
"full_trim",
"=",
"True",
")",
":",
"if",
"full_trim",
":",
"n1",
"=",
"N2",
"/",
"(",
"min",
"(",
"C",
"/",
"d",
"**",
"2",
",",
"0.04",
")",
")",
"**",
"2",
"# C/d**2 must not exceed 0.04",
"FR_1a",
"=",
"1",
"+",
"(",
"0.33",
"*",
"FL",
"**",
"0.5",
")",
"/",
"n1",
"**",
"0.25",
"*",
"log10",
"(",
"Rev",
"/",
"10000.",
")",
"FR_2",
"=",
"0.026",
"/",
"FL",
"*",
"(",
"n1",
"*",
"Rev",
")",
"**",
"0.5",
"if",
"Rev",
"<",
"10",
":",
"FR",
"=",
"FR_2",
"else",
":",
"FR",
"=",
"min",
"(",
"FR_2",
",",
"FR_1a",
")",
"else",
":",
"n2",
"=",
"1",
"+",
"N32",
"*",
"(",
"C",
"/",
"d",
"**",
"2",
")",
"**",
"(",
"2",
"/",
"3.",
")",
"FR_3a",
"=",
"1",
"+",
"(",
"0.33",
"*",
"FL",
"**",
"0.5",
")",
"/",
"n2",
"**",
"0.25",
"*",
"log10",
"(",
"Rev",
"/",
"10000.",
")",
"FR_4",
"=",
"min",
"(",
"0.026",
"/",
"FL",
"*",
"(",
"n2",
"*",
"Rev",
")",
"**",
"0.5",
",",
"1",
")",
"if",
"Rev",
"<",
"10",
":",
"FR",
"=",
"FR_4",
"else",
":",
"FR",
"=",
"min",
"(",
"FR_3a",
",",
"FR_4",
")",
"return",
"FR"
]
| r'''Calculates the Reynolds number factor `FR` for a valve with a Reynolds
number `Rev`, diameter `d`, flow coefficient `C`, liquid pressure recovery
factor `FL`, and with either full or reduced trim, all according to
IEC 60534 calculations.
If full trim:
.. math::
F_{R,1a} = 1 + \left(\frac{0.33F_L^{0.5}}{n_1^{0.25}}\right)\log_{10}
\left(\frac{Re_v}{10000}\right)
.. math::
F_{R,2} = \min(\frac{0.026}{F_L}\sqrt{n_1 Re_v},\; 1)
.. math::
n_1 = \frac{N_2}{\left(\frac{C}{d^2}\right)^2}
.. math::
F_R = F_{R,2} \text{ if Rev < 10 else } \min(F_{R,1a}, F_{R,2})
Otherwise :
.. math::
F_{R,3a} = 1 + \left(\frac{0.33F_L^{0.5}}{n_2^{0.25}}\right)\log_{10}
\left(\frac{Re_v}{10000}\right)
.. math::
F_{R,4} = \frac{0.026}{F_L}\sqrt{n_2 Re_v}
.. math::
n_2 = 1 + N_{32}\left(\frac{C}{d}\right)^{2/3}
.. math::
F_R = F_{R,4} \text{ if Rev < 10 else } \min(F_{R,3a}, F_{R,4})
Parameters
----------
FL : float
Liquid pressure recovery factor of a control valve without attached
fittings []
C : float
Metric Kv valve flow coefficient (flow rate of water at a pressure drop
of 1 bar) [m^3/hr]
d : float
Diameter of the valve [m]
Rev : float
Valve reynolds number [-]
full_trim : bool
Whether or not the valve has full trim
Returns
-------
FR : float
Reynolds number factor for laminar or transitional flow []
Examples
--------
In Example 4, compressible flow with small flow trim sized for gas flow
(Cv in the problem was converted to Kv here to make FR match with N32, N2):
>>> Reynolds_factor(FL=0.98, C=0.015483, d=15., Rev=1202., full_trim=False)
0.7148753122302025
References
----------
.. [1] IEC 60534-2-1 / ISA-75.01.01-2007 | [
"r",
"Calculates",
"the",
"Reynolds",
"number",
"factor",
"FR",
"for",
"a",
"valve",
"with",
"a",
"Reynolds",
"number",
"Rev",
"diameter",
"d",
"flow",
"coefficient",
"C",
"liquid",
"pressure",
"recovery",
"factor",
"FL",
"and",
"with",
"either",
"full",
"or",
"reduced",
"trim",
"all",
"according",
"to",
"IEC",
"60534",
"calculations",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/control_valve.py#L461-L547 | train |
CalebBell/fluids | fluids/units.py | func_args | def func_args(func):
'''Basic function which returns a tuple of arguments of a function or
method.
'''
try:
return tuple(inspect.signature(func).parameters)
except:
return tuple(inspect.getargspec(func).args) | python | def func_args(func):
'''Basic function which returns a tuple of arguments of a function or
method.
'''
try:
return tuple(inspect.signature(func).parameters)
except:
return tuple(inspect.getargspec(func).args) | [
"def",
"func_args",
"(",
"func",
")",
":",
"try",
":",
"return",
"tuple",
"(",
"inspect",
".",
"signature",
"(",
"func",
")",
".",
"parameters",
")",
"except",
":",
"return",
"tuple",
"(",
"inspect",
".",
"getargspec",
"(",
"func",
")",
".",
"args",
")"
]
| Basic function which returns a tuple of arguments of a function or
method. | [
"Basic",
"function",
"which",
"returns",
"a",
"tuple",
"of",
"arguments",
"of",
"a",
"function",
"or",
"method",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/units.py#L51-L58 | train |
CalebBell/fluids | fluids/optional/pychebfun.py | cast_scalar | def cast_scalar(method):
"""
Cast scalars to constant interpolating objects
"""
@wraps(method)
def new_method(self, other):
if np.isscalar(other):
other = type(self)([other],self.domain())
return method(self, other)
return new_method | python | def cast_scalar(method):
"""
Cast scalars to constant interpolating objects
"""
@wraps(method)
def new_method(self, other):
if np.isscalar(other):
other = type(self)([other],self.domain())
return method(self, other)
return new_method | [
"def",
"cast_scalar",
"(",
"method",
")",
":",
"@",
"wraps",
"(",
"method",
")",
"def",
"new_method",
"(",
"self",
",",
"other",
")",
":",
"if",
"np",
".",
"isscalar",
"(",
"other",
")",
":",
"other",
"=",
"type",
"(",
"self",
")",
"(",
"[",
"other",
"]",
",",
"self",
".",
"domain",
"(",
")",
")",
"return",
"method",
"(",
"self",
",",
"other",
")",
"return",
"new_method"
]
| Cast scalars to constant interpolating objects | [
"Cast",
"scalars",
"to",
"constant",
"interpolating",
"objects"
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/optional/pychebfun.py#L75-L84 | train |
CalebBell/fluids | fluids/optional/pychebfun.py | dct | def dct(data):
"""
Compute DCT using FFT
"""
N = len(data)//2
fftdata = fftpack.fft(data, axis=0)[:N+1]
fftdata /= N
fftdata[0] /= 2.
fftdata[-1] /= 2.
if np.isrealobj(data):
data = np.real(fftdata)
else:
data = fftdata
return data | python | def dct(data):
"""
Compute DCT using FFT
"""
N = len(data)//2
fftdata = fftpack.fft(data, axis=0)[:N+1]
fftdata /= N
fftdata[0] /= 2.
fftdata[-1] /= 2.
if np.isrealobj(data):
data = np.real(fftdata)
else:
data = fftdata
return data | [
"def",
"dct",
"(",
"data",
")",
":",
"N",
"=",
"len",
"(",
"data",
")",
"//",
"2",
"fftdata",
"=",
"fftpack",
".",
"fft",
"(",
"data",
",",
"axis",
"=",
"0",
")",
"[",
":",
"N",
"+",
"1",
"]",
"fftdata",
"/=",
"N",
"fftdata",
"[",
"0",
"]",
"/=",
"2.",
"fftdata",
"[",
"-",
"1",
"]",
"/=",
"2.",
"if",
"np",
".",
"isrealobj",
"(",
"data",
")",
":",
"data",
"=",
"np",
".",
"real",
"(",
"fftdata",
")",
"else",
":",
"data",
"=",
"fftdata",
"return",
"data"
]
| Compute DCT using FFT | [
"Compute",
"DCT",
"using",
"FFT"
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/optional/pychebfun.py#L637-L650 | train |
CalebBell/fluids | fluids/optional/pychebfun.py | Polyfun._cutoff | def _cutoff(self, coeffs, vscale):
"""
Compute cutoff index after which the coefficients are deemed negligible.
"""
bnd = self._threshold(vscale)
inds = np.nonzero(abs(coeffs) >= bnd)
if len(inds[0]):
N = inds[0][-1]
else:
N = 0
return N+1 | python | def _cutoff(self, coeffs, vscale):
"""
Compute cutoff index after which the coefficients are deemed negligible.
"""
bnd = self._threshold(vscale)
inds = np.nonzero(abs(coeffs) >= bnd)
if len(inds[0]):
N = inds[0][-1]
else:
N = 0
return N+1 | [
"def",
"_cutoff",
"(",
"self",
",",
"coeffs",
",",
"vscale",
")",
":",
"bnd",
"=",
"self",
".",
"_threshold",
"(",
"vscale",
")",
"inds",
"=",
"np",
".",
"nonzero",
"(",
"abs",
"(",
"coeffs",
")",
">=",
"bnd",
")",
"if",
"len",
"(",
"inds",
"[",
"0",
"]",
")",
":",
"N",
"=",
"inds",
"[",
"0",
"]",
"[",
"-",
"1",
"]",
"else",
":",
"N",
"=",
"0",
"return",
"N",
"+",
"1"
]
| Compute cutoff index after which the coefficients are deemed negligible. | [
"Compute",
"cutoff",
"index",
"after",
"which",
"the",
"coefficients",
"are",
"deemed",
"negligible",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/optional/pychebfun.py#L203-L213 | train |
CalebBell/fluids | fluids/optional/pychebfun.py | Polyfun.same_domain | def same_domain(self, fun2):
"""
Returns True if the domains of two objects are the same.
"""
return np.allclose(self.domain(), fun2.domain(), rtol=1e-14, atol=1e-14) | python | def same_domain(self, fun2):
"""
Returns True if the domains of two objects are the same.
"""
return np.allclose(self.domain(), fun2.domain(), rtol=1e-14, atol=1e-14) | [
"def",
"same_domain",
"(",
"self",
",",
"fun2",
")",
":",
"return",
"np",
".",
"allclose",
"(",
"self",
".",
"domain",
"(",
")",
",",
"fun2",
".",
"domain",
"(",
")",
",",
"rtol",
"=",
"1e-14",
",",
"atol",
"=",
"1e-14",
")"
]
| Returns True if the domains of two objects are the same. | [
"Returns",
"True",
"if",
"the",
"domains",
"of",
"two",
"objects",
"are",
"the",
"same",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/optional/pychebfun.py#L241-L245 | train |
CalebBell/fluids | fluids/optional/pychebfun.py | Polyfun.restrict | def restrict(self,subinterval):
"""
Return a Polyfun that matches self on subinterval.
"""
if (subinterval[0] < self._domain[0]) or (subinterval[1] > self._domain[1]):
raise ValueError("Can only restrict to subinterval")
return self.from_function(self, subinterval) | python | def restrict(self,subinterval):
"""
Return a Polyfun that matches self on subinterval.
"""
if (subinterval[0] < self._domain[0]) or (subinterval[1] > self._domain[1]):
raise ValueError("Can only restrict to subinterval")
return self.from_function(self, subinterval) | [
"def",
"restrict",
"(",
"self",
",",
"subinterval",
")",
":",
"if",
"(",
"subinterval",
"[",
"0",
"]",
"<",
"self",
".",
"_domain",
"[",
"0",
"]",
")",
"or",
"(",
"subinterval",
"[",
"1",
"]",
">",
"self",
".",
"_domain",
"[",
"1",
"]",
")",
":",
"raise",
"ValueError",
"(",
"\"Can only restrict to subinterval\"",
")",
"return",
"self",
".",
"from_function",
"(",
"self",
",",
"subinterval",
")"
]
| Return a Polyfun that matches self on subinterval. | [
"Return",
"a",
"Polyfun",
"that",
"matches",
"self",
"on",
"subinterval",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/optional/pychebfun.py#L395-L401 | train |
CalebBell/fluids | fluids/optional/pychebfun.py | Chebfun.basis | def basis(self, n):
"""
Chebyshev basis functions T_n.
"""
if n == 0:
return self(np.array([1.]))
vals = np.ones(n+1)
vals[1::2] = -1
return self(vals) | python | def basis(self, n):
"""
Chebyshev basis functions T_n.
"""
if n == 0:
return self(np.array([1.]))
vals = np.ones(n+1)
vals[1::2] = -1
return self(vals) | [
"def",
"basis",
"(",
"self",
",",
"n",
")",
":",
"if",
"n",
"==",
"0",
":",
"return",
"self",
"(",
"np",
".",
"array",
"(",
"[",
"1.",
"]",
")",
")",
"vals",
"=",
"np",
".",
"ones",
"(",
"n",
"+",
"1",
")",
"vals",
"[",
"1",
":",
":",
"2",
"]",
"=",
"-",
"1",
"return",
"self",
"(",
"vals",
")"
]
| Chebyshev basis functions T_n. | [
"Chebyshev",
"basis",
"functions",
"T_n",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/optional/pychebfun.py#L435-L443 | train |
CalebBell/fluids | fluids/optional/pychebfun.py | Chebfun.sum | def sum(self):
"""
Evaluate the integral over the given interval using
Clenshaw-Curtis quadrature.
"""
ak = self.coefficients()
ak2 = ak[::2]
n = len(ak2)
Tints = 2/(1-(2*np.arange(n))**2)
val = np.sum((Tints*ak2.T).T, axis=0)
a_, b_ = self.domain()
return 0.5*(b_-a_)*val | python | def sum(self):
"""
Evaluate the integral over the given interval using
Clenshaw-Curtis quadrature.
"""
ak = self.coefficients()
ak2 = ak[::2]
n = len(ak2)
Tints = 2/(1-(2*np.arange(n))**2)
val = np.sum((Tints*ak2.T).T, axis=0)
a_, b_ = self.domain()
return 0.5*(b_-a_)*val | [
"def",
"sum",
"(",
"self",
")",
":",
"ak",
"=",
"self",
".",
"coefficients",
"(",
")",
"ak2",
"=",
"ak",
"[",
":",
":",
"2",
"]",
"n",
"=",
"len",
"(",
"ak2",
")",
"Tints",
"=",
"2",
"/",
"(",
"1",
"-",
"(",
"2",
"*",
"np",
".",
"arange",
"(",
"n",
")",
")",
"**",
"2",
")",
"val",
"=",
"np",
".",
"sum",
"(",
"(",
"Tints",
"*",
"ak2",
".",
"T",
")",
".",
"T",
",",
"axis",
"=",
"0",
")",
"a_",
",",
"b_",
"=",
"self",
".",
"domain",
"(",
")",
"return",
"0.5",
"*",
"(",
"b_",
"-",
"a_",
")",
"*",
"val"
]
| Evaluate the integral over the given interval using
Clenshaw-Curtis quadrature. | [
"Evaluate",
"the",
"integral",
"over",
"the",
"given",
"interval",
"using",
"Clenshaw",
"-",
"Curtis",
"quadrature",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/optional/pychebfun.py#L449-L460 | train |
CalebBell/fluids | fluids/optional/pychebfun.py | Chebfun.integrate | def integrate(self):
"""
Return the object representing the primitive of self over the domain. The
output starts at zero on the left-hand side of the domain.
"""
coeffs = self.coefficients()
a,b = self.domain()
int_coeffs = 0.5*(b-a)*poly.chebyshev.chebint(coeffs)
antiderivative = self.from_coeff(int_coeffs, domain=self.domain())
return antiderivative - antiderivative(a) | python | def integrate(self):
"""
Return the object representing the primitive of self over the domain. The
output starts at zero on the left-hand side of the domain.
"""
coeffs = self.coefficients()
a,b = self.domain()
int_coeffs = 0.5*(b-a)*poly.chebyshev.chebint(coeffs)
antiderivative = self.from_coeff(int_coeffs, domain=self.domain())
return antiderivative - antiderivative(a) | [
"def",
"integrate",
"(",
"self",
")",
":",
"coeffs",
"=",
"self",
".",
"coefficients",
"(",
")",
"a",
",",
"b",
"=",
"self",
".",
"domain",
"(",
")",
"int_coeffs",
"=",
"0.5",
"*",
"(",
"b",
"-",
"a",
")",
"*",
"poly",
".",
"chebyshev",
".",
"chebint",
"(",
"coeffs",
")",
"antiderivative",
"=",
"self",
".",
"from_coeff",
"(",
"int_coeffs",
",",
"domain",
"=",
"self",
".",
"domain",
"(",
")",
")",
"return",
"antiderivative",
"-",
"antiderivative",
"(",
"a",
")"
]
| Return the object representing the primitive of self over the domain. The
output starts at zero on the left-hand side of the domain. | [
"Return",
"the",
"object",
"representing",
"the",
"primitive",
"of",
"self",
"over",
"the",
"domain",
".",
"The",
"output",
"starts",
"at",
"zero",
"on",
"the",
"left",
"-",
"hand",
"side",
"of",
"the",
"domain",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/optional/pychebfun.py#L462-L471 | train |
CalebBell/fluids | fluids/optional/pychebfun.py | Chebfun.differentiate | def differentiate(self, n=1):
"""
n-th derivative, default 1.
"""
ak = self.coefficients()
a_, b_ = self.domain()
for _ in range(n):
ak = self.differentiator(ak)
return self.from_coeff((2./(b_-a_))**n*ak, domain=self.domain()) | python | def differentiate(self, n=1):
"""
n-th derivative, default 1.
"""
ak = self.coefficients()
a_, b_ = self.domain()
for _ in range(n):
ak = self.differentiator(ak)
return self.from_coeff((2./(b_-a_))**n*ak, domain=self.domain()) | [
"def",
"differentiate",
"(",
"self",
",",
"n",
"=",
"1",
")",
":",
"ak",
"=",
"self",
".",
"coefficients",
"(",
")",
"a_",
",",
"b_",
"=",
"self",
".",
"domain",
"(",
")",
"for",
"_",
"in",
"range",
"(",
"n",
")",
":",
"ak",
"=",
"self",
".",
"differentiator",
"(",
"ak",
")",
"return",
"self",
".",
"from_coeff",
"(",
"(",
"2.",
"/",
"(",
"b_",
"-",
"a_",
")",
")",
"**",
"n",
"*",
"ak",
",",
"domain",
"=",
"self",
".",
"domain",
"(",
")",
")"
]
| n-th derivative, default 1. | [
"n",
"-",
"th",
"derivative",
"default",
"1",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/optional/pychebfun.py#L473-L481 | train |
CalebBell/fluids | fluids/optional/pychebfun.py | Chebfun.sample_function | def sample_function(self, f, N):
"""
Sample a function on N+1 Chebyshev points.
"""
x = self.interpolation_points(N+1)
return f(x) | python | def sample_function(self, f, N):
"""
Sample a function on N+1 Chebyshev points.
"""
x = self.interpolation_points(N+1)
return f(x) | [
"def",
"sample_function",
"(",
"self",
",",
"f",
",",
"N",
")",
":",
"x",
"=",
"self",
".",
"interpolation_points",
"(",
"N",
"+",
"1",
")",
"return",
"f",
"(",
"x",
")"
]
| Sample a function on N+1 Chebyshev points. | [
"Sample",
"a",
"function",
"on",
"N",
"+",
"1",
"Chebyshev",
"points",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/optional/pychebfun.py#L538-L543 | train |
CalebBell/fluids | fluids/optional/pychebfun.py | Chebfun.interpolator | def interpolator(self, x, values):
"""
Returns a polynomial with vector coefficients which interpolates the values at the Chebyshev points x
"""
# hacking the barycentric interpolator by computing the weights in advance
p = Bary([0.])
N = len(values)
weights = np.ones(N)
weights[0] = .5
weights[1::2] = -1
weights[-1] *= .5
p.wi = weights
p.xi = x
p.set_yi(values)
return p | python | def interpolator(self, x, values):
"""
Returns a polynomial with vector coefficients which interpolates the values at the Chebyshev points x
"""
# hacking the barycentric interpolator by computing the weights in advance
p = Bary([0.])
N = len(values)
weights = np.ones(N)
weights[0] = .5
weights[1::2] = -1
weights[-1] *= .5
p.wi = weights
p.xi = x
p.set_yi(values)
return p | [
"def",
"interpolator",
"(",
"self",
",",
"x",
",",
"values",
")",
":",
"# hacking the barycentric interpolator by computing the weights in advance",
"p",
"=",
"Bary",
"(",
"[",
"0.",
"]",
")",
"N",
"=",
"len",
"(",
"values",
")",
"weights",
"=",
"np",
".",
"ones",
"(",
"N",
")",
"weights",
"[",
"0",
"]",
"=",
".5",
"weights",
"[",
"1",
":",
":",
"2",
"]",
"=",
"-",
"1",
"weights",
"[",
"-",
"1",
"]",
"*=",
".5",
"p",
".",
"wi",
"=",
"weights",
"p",
".",
"xi",
"=",
"x",
"p",
".",
"set_yi",
"(",
"values",
")",
"return",
"p"
]
| Returns a polynomial with vector coefficients which interpolates the values at the Chebyshev points x | [
"Returns",
"a",
"polynomial",
"with",
"vector",
"coefficients",
"which",
"interpolates",
"the",
"values",
"at",
"the",
"Chebyshev",
"points",
"x"
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/optional/pychebfun.py#L582-L596 | train |
CalebBell/fluids | fluids/drag.py | drag_sphere | def drag_sphere(Re, Method=None, AvailableMethods=False):
r'''This function handles calculation of drag coefficient on spheres.
Twenty methods are available, all requiring only the Reynolds number of the
sphere. Most methods are valid from Re=0 to Re=200,000. A correlation will
be automatically selected if none is specified. The full list of correlations
valid for a given Reynolds number can be obtained with the `AvailableMethods`
flag.
If no correlation is selected, the following rules are used:
* If Re < 0.01, use Stoke's solution.
* If 0.01 <= Re < 0.1, linearly combine 'Barati' with Stokes's solution
such that at Re = 0.1 the solution is 'Barati', and at Re = 0.01 the
solution is 'Stokes'.
* If 0.1 <= Re <= ~212963, use the 'Barati' solution.
* If ~212963 < Re <= 1E6, use the 'Barati_high' solution.
* For Re > 1E6, raises an exception; no valid results have been found.
Examples
--------
>>> drag_sphere(200)
0.7682237950389874
Parameters
----------
Re : float
Particle Reynolds number of the sphere using the surrounding fluid
density and viscosity, [-]
Returns
-------
Cd : float
Drag coefficient [-]
methods : list, only returned if AvailableMethods == True
List of methods which can be used to calculate `Cd` with the given `Re`
Other Parameters
----------------
Method : string, optional
A string of the function name to use, as in the dictionary
drag_sphere_correlations
AvailableMethods : bool, optional
If True, function will consider which methods which can be used to
calculate `Cd` with the given `Re`
'''
def list_methods():
methods = []
for key, (func, Re_min, Re_max) in drag_sphere_correlations.items():
if (Re_min is None or Re > Re_min) and (Re_max is None or Re < Re_max):
methods.append(key)
return methods
if AvailableMethods:
return list_methods()
if not Method:
if Re > 0.1:
# Smooth transition point between the two models
if Re <= 212963.26847812787:
return Barati(Re)
elif Re <= 1E6:
return Barati_high(Re)
else:
raise ValueError('No models implement a solution for Re > 1E6')
elif Re >= 0.01:
# Re from 0.01 to 0.1
ratio = (Re - 0.01)/(0.1 - 0.01)
# Ensure a smooth transition by linearly switching to Stokes' law
return ratio*Barati(Re) + (1-ratio)*Stokes(Re)
else:
return Stokes(Re)
if Method in drag_sphere_correlations:
return drag_sphere_correlations[Method][0](Re)
else:
raise Exception('Failure in in function') | python | def drag_sphere(Re, Method=None, AvailableMethods=False):
r'''This function handles calculation of drag coefficient on spheres.
Twenty methods are available, all requiring only the Reynolds number of the
sphere. Most methods are valid from Re=0 to Re=200,000. A correlation will
be automatically selected if none is specified. The full list of correlations
valid for a given Reynolds number can be obtained with the `AvailableMethods`
flag.
If no correlation is selected, the following rules are used:
* If Re < 0.01, use Stoke's solution.
* If 0.01 <= Re < 0.1, linearly combine 'Barati' with Stokes's solution
such that at Re = 0.1 the solution is 'Barati', and at Re = 0.01 the
solution is 'Stokes'.
* If 0.1 <= Re <= ~212963, use the 'Barati' solution.
* If ~212963 < Re <= 1E6, use the 'Barati_high' solution.
* For Re > 1E6, raises an exception; no valid results have been found.
Examples
--------
>>> drag_sphere(200)
0.7682237950389874
Parameters
----------
Re : float
Particle Reynolds number of the sphere using the surrounding fluid
density and viscosity, [-]
Returns
-------
Cd : float
Drag coefficient [-]
methods : list, only returned if AvailableMethods == True
List of methods which can be used to calculate `Cd` with the given `Re`
Other Parameters
----------------
Method : string, optional
A string of the function name to use, as in the dictionary
drag_sphere_correlations
AvailableMethods : bool, optional
If True, function will consider which methods which can be used to
calculate `Cd` with the given `Re`
'''
def list_methods():
methods = []
for key, (func, Re_min, Re_max) in drag_sphere_correlations.items():
if (Re_min is None or Re > Re_min) and (Re_max is None or Re < Re_max):
methods.append(key)
return methods
if AvailableMethods:
return list_methods()
if not Method:
if Re > 0.1:
# Smooth transition point between the two models
if Re <= 212963.26847812787:
return Barati(Re)
elif Re <= 1E6:
return Barati_high(Re)
else:
raise ValueError('No models implement a solution for Re > 1E6')
elif Re >= 0.01:
# Re from 0.01 to 0.1
ratio = (Re - 0.01)/(0.1 - 0.01)
# Ensure a smooth transition by linearly switching to Stokes' law
return ratio*Barati(Re) + (1-ratio)*Stokes(Re)
else:
return Stokes(Re)
if Method in drag_sphere_correlations:
return drag_sphere_correlations[Method][0](Re)
else:
raise Exception('Failure in in function') | [
"def",
"drag_sphere",
"(",
"Re",
",",
"Method",
"=",
"None",
",",
"AvailableMethods",
"=",
"False",
")",
":",
"def",
"list_methods",
"(",
")",
":",
"methods",
"=",
"[",
"]",
"for",
"key",
",",
"(",
"func",
",",
"Re_min",
",",
"Re_max",
")",
"in",
"drag_sphere_correlations",
".",
"items",
"(",
")",
":",
"if",
"(",
"Re_min",
"is",
"None",
"or",
"Re",
">",
"Re_min",
")",
"and",
"(",
"Re_max",
"is",
"None",
"or",
"Re",
"<",
"Re_max",
")",
":",
"methods",
".",
"append",
"(",
"key",
")",
"return",
"methods",
"if",
"AvailableMethods",
":",
"return",
"list_methods",
"(",
")",
"if",
"not",
"Method",
":",
"if",
"Re",
">",
"0.1",
":",
"# Smooth transition point between the two models",
"if",
"Re",
"<=",
"212963.26847812787",
":",
"return",
"Barati",
"(",
"Re",
")",
"elif",
"Re",
"<=",
"1E6",
":",
"return",
"Barati_high",
"(",
"Re",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'No models implement a solution for Re > 1E6'",
")",
"elif",
"Re",
">=",
"0.01",
":",
"# Re from 0.01 to 0.1",
"ratio",
"=",
"(",
"Re",
"-",
"0.01",
")",
"/",
"(",
"0.1",
"-",
"0.01",
")",
"# Ensure a smooth transition by linearly switching to Stokes' law",
"return",
"ratio",
"*",
"Barati",
"(",
"Re",
")",
"+",
"(",
"1",
"-",
"ratio",
")",
"*",
"Stokes",
"(",
"Re",
")",
"else",
":",
"return",
"Stokes",
"(",
"Re",
")",
"if",
"Method",
"in",
"drag_sphere_correlations",
":",
"return",
"drag_sphere_correlations",
"[",
"Method",
"]",
"[",
"0",
"]",
"(",
"Re",
")",
"else",
":",
"raise",
"Exception",
"(",
"'Failure in in function'",
")"
]
| r'''This function handles calculation of drag coefficient on spheres.
Twenty methods are available, all requiring only the Reynolds number of the
sphere. Most methods are valid from Re=0 to Re=200,000. A correlation will
be automatically selected if none is specified. The full list of correlations
valid for a given Reynolds number can be obtained with the `AvailableMethods`
flag.
If no correlation is selected, the following rules are used:
* If Re < 0.01, use Stoke's solution.
* If 0.01 <= Re < 0.1, linearly combine 'Barati' with Stokes's solution
such that at Re = 0.1 the solution is 'Barati', and at Re = 0.01 the
solution is 'Stokes'.
* If 0.1 <= Re <= ~212963, use the 'Barati' solution.
* If ~212963 < Re <= 1E6, use the 'Barati_high' solution.
* For Re > 1E6, raises an exception; no valid results have been found.
Examples
--------
>>> drag_sphere(200)
0.7682237950389874
Parameters
----------
Re : float
Particle Reynolds number of the sphere using the surrounding fluid
density and viscosity, [-]
Returns
-------
Cd : float
Drag coefficient [-]
methods : list, only returned if AvailableMethods == True
List of methods which can be used to calculate `Cd` with the given `Re`
Other Parameters
----------------
Method : string, optional
A string of the function name to use, as in the dictionary
drag_sphere_correlations
AvailableMethods : bool, optional
If True, function will consider which methods which can be used to
calculate `Cd` with the given `Re` | [
"r",
"This",
"function",
"handles",
"calculation",
"of",
"drag",
"coefficient",
"on",
"spheres",
".",
"Twenty",
"methods",
"are",
"available",
"all",
"requiring",
"only",
"the",
"Reynolds",
"number",
"of",
"the",
"sphere",
".",
"Most",
"methods",
"are",
"valid",
"from",
"Re",
"=",
"0",
"to",
"Re",
"=",
"200",
"000",
".",
"A",
"correlation",
"will",
"be",
"automatically",
"selected",
"if",
"none",
"is",
"specified",
".",
"The",
"full",
"list",
"of",
"correlations",
"valid",
"for",
"a",
"given",
"Reynolds",
"number",
"can",
"be",
"obtained",
"with",
"the",
"AvailableMethods",
"flag",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/drag.py#L1028-L1101 | train |
CalebBell/fluids | fluids/drag.py | v_terminal | def v_terminal(D, rhop, rho, mu, Method=None):
r'''Calculates terminal velocity of a falling sphere using any drag
coefficient method supported by `drag_sphere`. The laminar solution for
Re < 0.01 is first tried; if the resulting terminal velocity does not
put it in the laminar regime, a numerical solution is used.
.. math::
v_t = \sqrt{\frac{4 g d_p (\rho_p-\rho_f)}{3 C_D \rho_f }}
Parameters
----------
D : float
Diameter of the sphere, [m]
rhop : float
Particle density, [kg/m^3]
rho : float
Density of the surrounding fluid, [kg/m^3]
mu : float
Viscosity of the surrounding fluid [Pa*s]
Method : string, optional
A string of the function name to use, as in the dictionary
drag_sphere_correlations
Returns
-------
v_t : float
Terminal velocity of falling sphere [m/s]
Notes
-----
As there are no correlations implemented for Re > 1E6, an error will be
raised if the numerical solver seeks a solution above that limit.
The laminar solution is given in [1]_ and is:
.. math::
v_t = \frac{g d_p^2 (\rho_p - \rho_f)}{18 \mu_f}
Examples
--------
>>> v_terminal(D=70E-6, rhop=2600., rho=1000., mu=1E-3)
0.004142497244531304
Example 7-1 in GPSA handbook, 13th edition:
>>> from scipy.constants import *
>>> v_terminal(D=150E-6, rhop=31.2*lb/foot**3, rho=2.07*lb/foot**3, mu=1.2e-05)/foot
0.4491992020345101
The answer reported there is 0.46 ft/sec.
References
----------
.. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,
Eighth Edition. McGraw-Hill Professional, 2007.
.. [2] Rushton, Albert, Anthony S. Ward, and Richard G. Holdich.
Solid-Liquid Filtration and Separation Technology. 1st edition. Weinheim ;
New York: Wiley-VCH, 1996.
'''
'''The following would be the ideal implementation. The actual function is
optimized for speed, not readability
def err(V):
Re = rho*V*D/mu
Cd = Barati_high(Re)
V2 = (4/3.*g*D*(rhop-rho)/rho/Cd)**0.5
return (V-V2)
return fsolve(err, 1.)'''
v_lam = g*D*D*(rhop-rho)/(18*mu)
Re_lam = Reynolds(V=v_lam, D=D, rho=rho, mu=mu)
if Re_lam < 0.01 or Method == 'Stokes':
return v_lam
Re_almost = rho*D/mu
main = 4/3.*g*D*(rhop-rho)/rho
V_max = 1E6/rho/D*mu # where the correlation breaks down, Re=1E6
def err(V):
Cd = drag_sphere(Re_almost*V, Method=Method)
return V - (main/Cd)**0.5
# Begin the solver with 1/100 th the velocity possible at the maximum
# Reynolds number the correlation is good for
return float(newton(err, V_max/100, tol=1E-12)) | python | def v_terminal(D, rhop, rho, mu, Method=None):
r'''Calculates terminal velocity of a falling sphere using any drag
coefficient method supported by `drag_sphere`. The laminar solution for
Re < 0.01 is first tried; if the resulting terminal velocity does not
put it in the laminar regime, a numerical solution is used.
.. math::
v_t = \sqrt{\frac{4 g d_p (\rho_p-\rho_f)}{3 C_D \rho_f }}
Parameters
----------
D : float
Diameter of the sphere, [m]
rhop : float
Particle density, [kg/m^3]
rho : float
Density of the surrounding fluid, [kg/m^3]
mu : float
Viscosity of the surrounding fluid [Pa*s]
Method : string, optional
A string of the function name to use, as in the dictionary
drag_sphere_correlations
Returns
-------
v_t : float
Terminal velocity of falling sphere [m/s]
Notes
-----
As there are no correlations implemented for Re > 1E6, an error will be
raised if the numerical solver seeks a solution above that limit.
The laminar solution is given in [1]_ and is:
.. math::
v_t = \frac{g d_p^2 (\rho_p - \rho_f)}{18 \mu_f}
Examples
--------
>>> v_terminal(D=70E-6, rhop=2600., rho=1000., mu=1E-3)
0.004142497244531304
Example 7-1 in GPSA handbook, 13th edition:
>>> from scipy.constants import *
>>> v_terminal(D=150E-6, rhop=31.2*lb/foot**3, rho=2.07*lb/foot**3, mu=1.2e-05)/foot
0.4491992020345101
The answer reported there is 0.46 ft/sec.
References
----------
.. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,
Eighth Edition. McGraw-Hill Professional, 2007.
.. [2] Rushton, Albert, Anthony S. Ward, and Richard G. Holdich.
Solid-Liquid Filtration and Separation Technology. 1st edition. Weinheim ;
New York: Wiley-VCH, 1996.
'''
'''The following would be the ideal implementation. The actual function is
optimized for speed, not readability
def err(V):
Re = rho*V*D/mu
Cd = Barati_high(Re)
V2 = (4/3.*g*D*(rhop-rho)/rho/Cd)**0.5
return (V-V2)
return fsolve(err, 1.)'''
v_lam = g*D*D*(rhop-rho)/(18*mu)
Re_lam = Reynolds(V=v_lam, D=D, rho=rho, mu=mu)
if Re_lam < 0.01 or Method == 'Stokes':
return v_lam
Re_almost = rho*D/mu
main = 4/3.*g*D*(rhop-rho)/rho
V_max = 1E6/rho/D*mu # where the correlation breaks down, Re=1E6
def err(V):
Cd = drag_sphere(Re_almost*V, Method=Method)
return V - (main/Cd)**0.5
# Begin the solver with 1/100 th the velocity possible at the maximum
# Reynolds number the correlation is good for
return float(newton(err, V_max/100, tol=1E-12)) | [
"def",
"v_terminal",
"(",
"D",
",",
"rhop",
",",
"rho",
",",
"mu",
",",
"Method",
"=",
"None",
")",
":",
"'''The following would be the ideal implementation. The actual function is\n optimized for speed, not readability\n def err(V):\n Re = rho*V*D/mu\n Cd = Barati_high(Re)\n V2 = (4/3.*g*D*(rhop-rho)/rho/Cd)**0.5\n return (V-V2)\n return fsolve(err, 1.)'''",
"v_lam",
"=",
"g",
"*",
"D",
"*",
"D",
"*",
"(",
"rhop",
"-",
"rho",
")",
"/",
"(",
"18",
"*",
"mu",
")",
"Re_lam",
"=",
"Reynolds",
"(",
"V",
"=",
"v_lam",
",",
"D",
"=",
"D",
",",
"rho",
"=",
"rho",
",",
"mu",
"=",
"mu",
")",
"if",
"Re_lam",
"<",
"0.01",
"or",
"Method",
"==",
"'Stokes'",
":",
"return",
"v_lam",
"Re_almost",
"=",
"rho",
"*",
"D",
"/",
"mu",
"main",
"=",
"4",
"/",
"3.",
"*",
"g",
"*",
"D",
"*",
"(",
"rhop",
"-",
"rho",
")",
"/",
"rho",
"V_max",
"=",
"1E6",
"/",
"rho",
"/",
"D",
"*",
"mu",
"# where the correlation breaks down, Re=1E6",
"def",
"err",
"(",
"V",
")",
":",
"Cd",
"=",
"drag_sphere",
"(",
"Re_almost",
"*",
"V",
",",
"Method",
"=",
"Method",
")",
"return",
"V",
"-",
"(",
"main",
"/",
"Cd",
")",
"**",
"0.5",
"# Begin the solver with 1/100 th the velocity possible at the maximum",
"# Reynolds number the correlation is good for",
"return",
"float",
"(",
"newton",
"(",
"err",
",",
"V_max",
"/",
"100",
",",
"tol",
"=",
"1E-12",
")",
")"
]
| r'''Calculates terminal velocity of a falling sphere using any drag
coefficient method supported by `drag_sphere`. The laminar solution for
Re < 0.01 is first tried; if the resulting terminal velocity does not
put it in the laminar regime, a numerical solution is used.
.. math::
v_t = \sqrt{\frac{4 g d_p (\rho_p-\rho_f)}{3 C_D \rho_f }}
Parameters
----------
D : float
Diameter of the sphere, [m]
rhop : float
Particle density, [kg/m^3]
rho : float
Density of the surrounding fluid, [kg/m^3]
mu : float
Viscosity of the surrounding fluid [Pa*s]
Method : string, optional
A string of the function name to use, as in the dictionary
drag_sphere_correlations
Returns
-------
v_t : float
Terminal velocity of falling sphere [m/s]
Notes
-----
As there are no correlations implemented for Re > 1E6, an error will be
raised if the numerical solver seeks a solution above that limit.
The laminar solution is given in [1]_ and is:
.. math::
v_t = \frac{g d_p^2 (\rho_p - \rho_f)}{18 \mu_f}
Examples
--------
>>> v_terminal(D=70E-6, rhop=2600., rho=1000., mu=1E-3)
0.004142497244531304
Example 7-1 in GPSA handbook, 13th edition:
>>> from scipy.constants import *
>>> v_terminal(D=150E-6, rhop=31.2*lb/foot**3, rho=2.07*lb/foot**3, mu=1.2e-05)/foot
0.4491992020345101
The answer reported there is 0.46 ft/sec.
References
----------
.. [1] Green, Don, and Robert Perry. Perry's Chemical Engineers' Handbook,
Eighth Edition. McGraw-Hill Professional, 2007.
.. [2] Rushton, Albert, Anthony S. Ward, and Richard G. Holdich.
Solid-Liquid Filtration and Separation Technology. 1st edition. Weinheim ;
New York: Wiley-VCH, 1996. | [
"r",
"Calculates",
"terminal",
"velocity",
"of",
"a",
"falling",
"sphere",
"using",
"any",
"drag",
"coefficient",
"method",
"supported",
"by",
"drag_sphere",
".",
"The",
"laminar",
"solution",
"for",
"Re",
"<",
"0",
".",
"01",
"is",
"first",
"tried",
";",
"if",
"the",
"resulting",
"terminal",
"velocity",
"does",
"not",
"put",
"it",
"in",
"the",
"laminar",
"regime",
"a",
"numerical",
"solution",
"is",
"used",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/drag.py#L1104-L1185 | train |
CalebBell/fluids | fluids/drag.py | integrate_drag_sphere | def integrate_drag_sphere(D, rhop, rho, mu, t, V=0, Method=None,
distance=False):
r'''Integrates the velocity and distance traveled by a particle moving
at a speed which will converge to its terminal velocity.
Performs an integration of the following expression for acceleration:
.. math::
a = \frac{g(\rho_p-\rho_f)}{\rho_p} - \frac{3C_D \rho_f u^2}{4D \rho_p}
Parameters
----------
D : float
Diameter of the sphere, [m]
rhop : float
Particle density, [kg/m^3]
rho : float
Density of the surrounding fluid, [kg/m^3]
mu : float
Viscosity of the surrounding fluid [Pa*s]
t : float
Time to integrate the particle to, [s]
V : float
Initial velocity of the particle, [m/s]
Method : string, optional
A string of the function name to use, as in the dictionary
drag_sphere_correlations
distance : bool, optional
Whether or not to calculate the distance traveled and return it as
well
Returns
-------
v : float
Velocity of falling sphere after time `t` [m/s]
x : float, returned only if `distance` == True
Distance traveled by the falling sphere in time `t`, [m]
Notes
-----
This can be relatively slow as drag correlations can be complex.
There are analytical solutions available for the Stokes law regime (Re <
0.3). They were obtained from Wolfram Alpha. [1]_ was not used in the
derivation, but also describes the derivation fully.
.. math::
V(t) = \frac{\exp(-at) (V_0 a + b(\exp(at) - 1))}{a}
.. math::
x(t) = \frac{\exp(-a t)\left[V_0 a(\exp(a t) - 1) + b\exp(a t)(a t-1)
+ b\right]}{a^2}
.. math::
a = \frac{18\mu_f}{D^2\rho_p}
.. math::
b = \frac{g(\rho_p-\rho_f)}{\rho_p}
The analytical solution will automatically be used if the initial and
terminal velocity is show the particle's behavior to be laminar. Note
that this behavior requires that the terminal velocity of the particle be
solved for - this adds slight (1%) overhead for the cases where particles
are not laminar.
Examples
--------
>>> integrate_drag_sphere(D=0.001, rhop=2200., rho=1.2, mu=1.78E-5, t=0.5,
... V=30, distance=True)
(9.686465044053476, 7.8294546436299175)
References
----------
.. [1] Timmerman, Peter, and Jacobus P. van der Weele. "On the Rise and
Fall of a Ball with Linear or Quadratic Drag." American Journal of
Physics 67, no. 6 (June 1999): 538-46. https://doi.org/10.1119/1.19320.
'''
laminar_initial = Reynolds(V=V, rho=rho, D=D, mu=mu) < 0.01
v_laminar_end_assumed = v_terminal(D=D, rhop=rhop, rho=rho, mu=mu, Method=Method)
laminar_end = Reynolds(V=v_laminar_end_assumed, rho=rho, D=D, mu=mu) < 0.01
if Method == 'Stokes' or (laminar_initial and laminar_end and Method is None):
try:
t1 = 18.0*mu/(D*D*rhop)
t2 = g*(rhop-rho)/rhop
V_end = exp(-t1*t)*(t1*V + t2*(exp(t1*t) - 1.0))/t1
x_end = exp(-t1*t)*(V*t1*(exp(t1*t) - 1.0) + t2*exp(t1*t)*(t1*t - 1.0) + t2)/(t1*t1)
if distance:
return V_end, x_end
else:
return V_end
except OverflowError:
# It is only necessary to integrate to terminal velocity
t_to_terminal = time_v_terminal_Stokes(D, rhop, rho, mu, V0=V, tol=1e-9)
if t_to_terminal > t:
raise Exception('Should never happen')
V_end, x_end = integrate_drag_sphere(D=D, rhop=rhop, rho=rho, mu=mu, t=t_to_terminal, V=V, Method='Stokes', distance=True)
# terminal velocity has been reached - V does not change, but x does
# No reason to believe this isn't working even though it isn't
# matching the ode solver
if distance:
return V_end, x_end + V_end*(t - t_to_terminal)
else:
return V_end
# This is a serious problem for small diameters
# It would be possible to step slowly, using smaller increments
# of time to avlid overflows. However, this unfortunately quickly
# gets much, exponentially, slower than just using odeint because
# for example solving 10000 seconds might require steps of .0001
# seconds at a diameter of 1e-7 meters.
# x = 0.0
# subdivisions = 10
# dt = t/subdivisions
# for i in range(subdivisions):
# V, dx = integrate_drag_sphere(D=D, rhop=rhop, rho=rho, mu=mu,
# t=dt, V=V, distance=True,
# Method=Method)
# x += dx
# if distance:
# return V, x
# else:
# return V
Re_ish = rho*D/mu
c1 = g*(rhop-rho)/rhop
c2 = -0.75*rho/(D*rhop)
def dv_dt(V, t):
if V == 0:
# 64/Re goes to infinity, but gets multiplied by 0 squared.
t2 = 0.0
else:
# t2 = c2*V*V*Stokes(Re_ish*V)
t2 = c2*V*V*drag_sphere(Re_ish*V, Method=Method)
return c1 + t2
# Number of intervals for the solution to be solved for; the integrator
# doesn't care what we give it, but a large number of intervals are needed
# For an accurate integration of the particle's distance traveled
pts = 1000 if distance else 2
ts = np.linspace(0, t, pts)
# Delayed import of necessaray functions
from scipy.integrate import odeint, cumtrapz
# Perform the integration
Vs = odeint(dv_dt, [V], ts)
#
V_end = float(Vs[-1])
if distance:
# Calculate the distance traveled
x = float(cumtrapz(np.ravel(Vs), ts)[-1])
return V_end, x
else:
return V_end | python | def integrate_drag_sphere(D, rhop, rho, mu, t, V=0, Method=None,
distance=False):
r'''Integrates the velocity and distance traveled by a particle moving
at a speed which will converge to its terminal velocity.
Performs an integration of the following expression for acceleration:
.. math::
a = \frac{g(\rho_p-\rho_f)}{\rho_p} - \frac{3C_D \rho_f u^2}{4D \rho_p}
Parameters
----------
D : float
Diameter of the sphere, [m]
rhop : float
Particle density, [kg/m^3]
rho : float
Density of the surrounding fluid, [kg/m^3]
mu : float
Viscosity of the surrounding fluid [Pa*s]
t : float
Time to integrate the particle to, [s]
V : float
Initial velocity of the particle, [m/s]
Method : string, optional
A string of the function name to use, as in the dictionary
drag_sphere_correlations
distance : bool, optional
Whether or not to calculate the distance traveled and return it as
well
Returns
-------
v : float
Velocity of falling sphere after time `t` [m/s]
x : float, returned only if `distance` == True
Distance traveled by the falling sphere in time `t`, [m]
Notes
-----
This can be relatively slow as drag correlations can be complex.
There are analytical solutions available for the Stokes law regime (Re <
0.3). They were obtained from Wolfram Alpha. [1]_ was not used in the
derivation, but also describes the derivation fully.
.. math::
V(t) = \frac{\exp(-at) (V_0 a + b(\exp(at) - 1))}{a}
.. math::
x(t) = \frac{\exp(-a t)\left[V_0 a(\exp(a t) - 1) + b\exp(a t)(a t-1)
+ b\right]}{a^2}
.. math::
a = \frac{18\mu_f}{D^2\rho_p}
.. math::
b = \frac{g(\rho_p-\rho_f)}{\rho_p}
The analytical solution will automatically be used if the initial and
terminal velocity is show the particle's behavior to be laminar. Note
that this behavior requires that the terminal velocity of the particle be
solved for - this adds slight (1%) overhead for the cases where particles
are not laminar.
Examples
--------
>>> integrate_drag_sphere(D=0.001, rhop=2200., rho=1.2, mu=1.78E-5, t=0.5,
... V=30, distance=True)
(9.686465044053476, 7.8294546436299175)
References
----------
.. [1] Timmerman, Peter, and Jacobus P. van der Weele. "On the Rise and
Fall of a Ball with Linear or Quadratic Drag." American Journal of
Physics 67, no. 6 (June 1999): 538-46. https://doi.org/10.1119/1.19320.
'''
laminar_initial = Reynolds(V=V, rho=rho, D=D, mu=mu) < 0.01
v_laminar_end_assumed = v_terminal(D=D, rhop=rhop, rho=rho, mu=mu, Method=Method)
laminar_end = Reynolds(V=v_laminar_end_assumed, rho=rho, D=D, mu=mu) < 0.01
if Method == 'Stokes' or (laminar_initial and laminar_end and Method is None):
try:
t1 = 18.0*mu/(D*D*rhop)
t2 = g*(rhop-rho)/rhop
V_end = exp(-t1*t)*(t1*V + t2*(exp(t1*t) - 1.0))/t1
x_end = exp(-t1*t)*(V*t1*(exp(t1*t) - 1.0) + t2*exp(t1*t)*(t1*t - 1.0) + t2)/(t1*t1)
if distance:
return V_end, x_end
else:
return V_end
except OverflowError:
# It is only necessary to integrate to terminal velocity
t_to_terminal = time_v_terminal_Stokes(D, rhop, rho, mu, V0=V, tol=1e-9)
if t_to_terminal > t:
raise Exception('Should never happen')
V_end, x_end = integrate_drag_sphere(D=D, rhop=rhop, rho=rho, mu=mu, t=t_to_terminal, V=V, Method='Stokes', distance=True)
# terminal velocity has been reached - V does not change, but x does
# No reason to believe this isn't working even though it isn't
# matching the ode solver
if distance:
return V_end, x_end + V_end*(t - t_to_terminal)
else:
return V_end
# This is a serious problem for small diameters
# It would be possible to step slowly, using smaller increments
# of time to avlid overflows. However, this unfortunately quickly
# gets much, exponentially, slower than just using odeint because
# for example solving 10000 seconds might require steps of .0001
# seconds at a diameter of 1e-7 meters.
# x = 0.0
# subdivisions = 10
# dt = t/subdivisions
# for i in range(subdivisions):
# V, dx = integrate_drag_sphere(D=D, rhop=rhop, rho=rho, mu=mu,
# t=dt, V=V, distance=True,
# Method=Method)
# x += dx
# if distance:
# return V, x
# else:
# return V
Re_ish = rho*D/mu
c1 = g*(rhop-rho)/rhop
c2 = -0.75*rho/(D*rhop)
def dv_dt(V, t):
if V == 0:
# 64/Re goes to infinity, but gets multiplied by 0 squared.
t2 = 0.0
else:
# t2 = c2*V*V*Stokes(Re_ish*V)
t2 = c2*V*V*drag_sphere(Re_ish*V, Method=Method)
return c1 + t2
# Number of intervals for the solution to be solved for; the integrator
# doesn't care what we give it, but a large number of intervals are needed
# For an accurate integration of the particle's distance traveled
pts = 1000 if distance else 2
ts = np.linspace(0, t, pts)
# Delayed import of necessaray functions
from scipy.integrate import odeint, cumtrapz
# Perform the integration
Vs = odeint(dv_dt, [V], ts)
#
V_end = float(Vs[-1])
if distance:
# Calculate the distance traveled
x = float(cumtrapz(np.ravel(Vs), ts)[-1])
return V_end, x
else:
return V_end | [
"def",
"integrate_drag_sphere",
"(",
"D",
",",
"rhop",
",",
"rho",
",",
"mu",
",",
"t",
",",
"V",
"=",
"0",
",",
"Method",
"=",
"None",
",",
"distance",
"=",
"False",
")",
":",
"laminar_initial",
"=",
"Reynolds",
"(",
"V",
"=",
"V",
",",
"rho",
"=",
"rho",
",",
"D",
"=",
"D",
",",
"mu",
"=",
"mu",
")",
"<",
"0.01",
"v_laminar_end_assumed",
"=",
"v_terminal",
"(",
"D",
"=",
"D",
",",
"rhop",
"=",
"rhop",
",",
"rho",
"=",
"rho",
",",
"mu",
"=",
"mu",
",",
"Method",
"=",
"Method",
")",
"laminar_end",
"=",
"Reynolds",
"(",
"V",
"=",
"v_laminar_end_assumed",
",",
"rho",
"=",
"rho",
",",
"D",
"=",
"D",
",",
"mu",
"=",
"mu",
")",
"<",
"0.01",
"if",
"Method",
"==",
"'Stokes'",
"or",
"(",
"laminar_initial",
"and",
"laminar_end",
"and",
"Method",
"is",
"None",
")",
":",
"try",
":",
"t1",
"=",
"18.0",
"*",
"mu",
"/",
"(",
"D",
"*",
"D",
"*",
"rhop",
")",
"t2",
"=",
"g",
"*",
"(",
"rhop",
"-",
"rho",
")",
"/",
"rhop",
"V_end",
"=",
"exp",
"(",
"-",
"t1",
"*",
"t",
")",
"*",
"(",
"t1",
"*",
"V",
"+",
"t2",
"*",
"(",
"exp",
"(",
"t1",
"*",
"t",
")",
"-",
"1.0",
")",
")",
"/",
"t1",
"x_end",
"=",
"exp",
"(",
"-",
"t1",
"*",
"t",
")",
"*",
"(",
"V",
"*",
"t1",
"*",
"(",
"exp",
"(",
"t1",
"*",
"t",
")",
"-",
"1.0",
")",
"+",
"t2",
"*",
"exp",
"(",
"t1",
"*",
"t",
")",
"*",
"(",
"t1",
"*",
"t",
"-",
"1.0",
")",
"+",
"t2",
")",
"/",
"(",
"t1",
"*",
"t1",
")",
"if",
"distance",
":",
"return",
"V_end",
",",
"x_end",
"else",
":",
"return",
"V_end",
"except",
"OverflowError",
":",
"# It is only necessary to integrate to terminal velocity",
"t_to_terminal",
"=",
"time_v_terminal_Stokes",
"(",
"D",
",",
"rhop",
",",
"rho",
",",
"mu",
",",
"V0",
"=",
"V",
",",
"tol",
"=",
"1e-9",
")",
"if",
"t_to_terminal",
">",
"t",
":",
"raise",
"Exception",
"(",
"'Should never happen'",
")",
"V_end",
",",
"x_end",
"=",
"integrate_drag_sphere",
"(",
"D",
"=",
"D",
",",
"rhop",
"=",
"rhop",
",",
"rho",
"=",
"rho",
",",
"mu",
"=",
"mu",
",",
"t",
"=",
"t_to_terminal",
",",
"V",
"=",
"V",
",",
"Method",
"=",
"'Stokes'",
",",
"distance",
"=",
"True",
")",
"# terminal velocity has been reached - V does not change, but x does",
"# No reason to believe this isn't working even though it isn't",
"# matching the ode solver",
"if",
"distance",
":",
"return",
"V_end",
",",
"x_end",
"+",
"V_end",
"*",
"(",
"t",
"-",
"t_to_terminal",
")",
"else",
":",
"return",
"V_end",
"# This is a serious problem for small diameters",
"# It would be possible to step slowly, using smaller increments",
"# of time to avlid overflows. However, this unfortunately quickly",
"# gets much, exponentially, slower than just using odeint because",
"# for example solving 10000 seconds might require steps of .0001",
"# seconds at a diameter of 1e-7 meters.",
"# x = 0.0",
"# subdivisions = 10",
"# dt = t/subdivisions",
"# for i in range(subdivisions):",
"# V, dx = integrate_drag_sphere(D=D, rhop=rhop, rho=rho, mu=mu,",
"# t=dt, V=V, distance=True,",
"# Method=Method)",
"# x += dx",
"# if distance:",
"# return V, x",
"# else:",
"# return V",
"Re_ish",
"=",
"rho",
"*",
"D",
"/",
"mu",
"c1",
"=",
"g",
"*",
"(",
"rhop",
"-",
"rho",
")",
"/",
"rhop",
"c2",
"=",
"-",
"0.75",
"*",
"rho",
"/",
"(",
"D",
"*",
"rhop",
")",
"def",
"dv_dt",
"(",
"V",
",",
"t",
")",
":",
"if",
"V",
"==",
"0",
":",
"# 64/Re goes to infinity, but gets multiplied by 0 squared.",
"t2",
"=",
"0.0",
"else",
":",
"# t2 = c2*V*V*Stokes(Re_ish*V)",
"t2",
"=",
"c2",
"*",
"V",
"*",
"V",
"*",
"drag_sphere",
"(",
"Re_ish",
"*",
"V",
",",
"Method",
"=",
"Method",
")",
"return",
"c1",
"+",
"t2",
"# Number of intervals for the solution to be solved for; the integrator",
"# doesn't care what we give it, but a large number of intervals are needed",
"# For an accurate integration of the particle's distance traveled",
"pts",
"=",
"1000",
"if",
"distance",
"else",
"2",
"ts",
"=",
"np",
".",
"linspace",
"(",
"0",
",",
"t",
",",
"pts",
")",
"# Delayed import of necessaray functions",
"from",
"scipy",
".",
"integrate",
"import",
"odeint",
",",
"cumtrapz",
"# Perform the integration",
"Vs",
"=",
"odeint",
"(",
"dv_dt",
",",
"[",
"V",
"]",
",",
"ts",
")",
"#",
"V_end",
"=",
"float",
"(",
"Vs",
"[",
"-",
"1",
"]",
")",
"if",
"distance",
":",
"# Calculate the distance traveled",
"x",
"=",
"float",
"(",
"cumtrapz",
"(",
"np",
".",
"ravel",
"(",
"Vs",
")",
",",
"ts",
")",
"[",
"-",
"1",
"]",
")",
"return",
"V_end",
",",
"x",
"else",
":",
"return",
"V_end"
]
| r'''Integrates the velocity and distance traveled by a particle moving
at a speed which will converge to its terminal velocity.
Performs an integration of the following expression for acceleration:
.. math::
a = \frac{g(\rho_p-\rho_f)}{\rho_p} - \frac{3C_D \rho_f u^2}{4D \rho_p}
Parameters
----------
D : float
Diameter of the sphere, [m]
rhop : float
Particle density, [kg/m^3]
rho : float
Density of the surrounding fluid, [kg/m^3]
mu : float
Viscosity of the surrounding fluid [Pa*s]
t : float
Time to integrate the particle to, [s]
V : float
Initial velocity of the particle, [m/s]
Method : string, optional
A string of the function name to use, as in the dictionary
drag_sphere_correlations
distance : bool, optional
Whether or not to calculate the distance traveled and return it as
well
Returns
-------
v : float
Velocity of falling sphere after time `t` [m/s]
x : float, returned only if `distance` == True
Distance traveled by the falling sphere in time `t`, [m]
Notes
-----
This can be relatively slow as drag correlations can be complex.
There are analytical solutions available for the Stokes law regime (Re <
0.3). They were obtained from Wolfram Alpha. [1]_ was not used in the
derivation, but also describes the derivation fully.
.. math::
V(t) = \frac{\exp(-at) (V_0 a + b(\exp(at) - 1))}{a}
.. math::
x(t) = \frac{\exp(-a t)\left[V_0 a(\exp(a t) - 1) + b\exp(a t)(a t-1)
+ b\right]}{a^2}
.. math::
a = \frac{18\mu_f}{D^2\rho_p}
.. math::
b = \frac{g(\rho_p-\rho_f)}{\rho_p}
The analytical solution will automatically be used if the initial and
terminal velocity is show the particle's behavior to be laminar. Note
that this behavior requires that the terminal velocity of the particle be
solved for - this adds slight (1%) overhead for the cases where particles
are not laminar.
Examples
--------
>>> integrate_drag_sphere(D=0.001, rhop=2200., rho=1.2, mu=1.78E-5, t=0.5,
... V=30, distance=True)
(9.686465044053476, 7.8294546436299175)
References
----------
.. [1] Timmerman, Peter, and Jacobus P. van der Weele. "On the Rise and
Fall of a Ball with Linear or Quadratic Drag." American Journal of
Physics 67, no. 6 (June 1999): 538-46. https://doi.org/10.1119/1.19320. | [
"r",
"Integrates",
"the",
"velocity",
"and",
"distance",
"traveled",
"by",
"a",
"particle",
"moving",
"at",
"a",
"speed",
"which",
"will",
"converge",
"to",
"its",
"terminal",
"velocity",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/drag.py#L1260-L1414 | train |
CalebBell/fluids | fluids/fittings.py | bend_rounded_Ito | def bend_rounded_Ito(Di, angle, Re, rc=None, bend_diameters=None,
roughness=0.0):
'''Ito method as shown in Blevins. Curved friction factor as given in
Blevins, with minor tweaks to be more accurate to the original methods.
'''
if not rc:
if bend_diameters is None:
bend_diameters = 5.0
rc = Di*bend_diameters
radius_ratio = rc/Di
angle_rad = radians(angle)
De2 = Re*(Di/rc)**2.0
if rc > 50.0*Di:
alpha = 1.0
else:
# Alpha is up to 6, as ratio gets higher, can go down to 1
alpha_45 = 1.0 + 5.13*(Di/rc)**1.47
alpha_90 = 0.95 + 4.42*(Di/rc)**1.96 if rc/Di < 9.85 else 1.0
alpha_180 = 1.0 + 5.06*(Di/rc)**4.52
alpha = interp(angle, _Ito_angles, [alpha_45, alpha_90, alpha_180])
if De2 <= 360.0:
fc = friction_factor_curved(Re=Re, Di=Di, Dc=2.0*rc,
roughness=roughness,
Rec_method='Srinivasan',
laminar_method='White',
turbulent_method='Srinivasan turbulent')
K = 0.0175*alpha*fc*angle*rc/Di
else:
K = 0.00431*alpha*angle*Re**-0.17*(rc/Di)**0.84
return K | python | def bend_rounded_Ito(Di, angle, Re, rc=None, bend_diameters=None,
roughness=0.0):
'''Ito method as shown in Blevins. Curved friction factor as given in
Blevins, with minor tweaks to be more accurate to the original methods.
'''
if not rc:
if bend_diameters is None:
bend_diameters = 5.0
rc = Di*bend_diameters
radius_ratio = rc/Di
angle_rad = radians(angle)
De2 = Re*(Di/rc)**2.0
if rc > 50.0*Di:
alpha = 1.0
else:
# Alpha is up to 6, as ratio gets higher, can go down to 1
alpha_45 = 1.0 + 5.13*(Di/rc)**1.47
alpha_90 = 0.95 + 4.42*(Di/rc)**1.96 if rc/Di < 9.85 else 1.0
alpha_180 = 1.0 + 5.06*(Di/rc)**4.52
alpha = interp(angle, _Ito_angles, [alpha_45, alpha_90, alpha_180])
if De2 <= 360.0:
fc = friction_factor_curved(Re=Re, Di=Di, Dc=2.0*rc,
roughness=roughness,
Rec_method='Srinivasan',
laminar_method='White',
turbulent_method='Srinivasan turbulent')
K = 0.0175*alpha*fc*angle*rc/Di
else:
K = 0.00431*alpha*angle*Re**-0.17*(rc/Di)**0.84
return K | [
"def",
"bend_rounded_Ito",
"(",
"Di",
",",
"angle",
",",
"Re",
",",
"rc",
"=",
"None",
",",
"bend_diameters",
"=",
"None",
",",
"roughness",
"=",
"0.0",
")",
":",
"if",
"not",
"rc",
":",
"if",
"bend_diameters",
"is",
"None",
":",
"bend_diameters",
"=",
"5.0",
"rc",
"=",
"Di",
"*",
"bend_diameters",
"radius_ratio",
"=",
"rc",
"/",
"Di",
"angle_rad",
"=",
"radians",
"(",
"angle",
")",
"De2",
"=",
"Re",
"*",
"(",
"Di",
"/",
"rc",
")",
"**",
"2.0",
"if",
"rc",
">",
"50.0",
"*",
"Di",
":",
"alpha",
"=",
"1.0",
"else",
":",
"# Alpha is up to 6, as ratio gets higher, can go down to 1",
"alpha_45",
"=",
"1.0",
"+",
"5.13",
"*",
"(",
"Di",
"/",
"rc",
")",
"**",
"1.47",
"alpha_90",
"=",
"0.95",
"+",
"4.42",
"*",
"(",
"Di",
"/",
"rc",
")",
"**",
"1.96",
"if",
"rc",
"/",
"Di",
"<",
"9.85",
"else",
"1.0",
"alpha_180",
"=",
"1.0",
"+",
"5.06",
"*",
"(",
"Di",
"/",
"rc",
")",
"**",
"4.52",
"alpha",
"=",
"interp",
"(",
"angle",
",",
"_Ito_angles",
",",
"[",
"alpha_45",
",",
"alpha_90",
",",
"alpha_180",
"]",
")",
"if",
"De2",
"<=",
"360.0",
":",
"fc",
"=",
"friction_factor_curved",
"(",
"Re",
"=",
"Re",
",",
"Di",
"=",
"Di",
",",
"Dc",
"=",
"2.0",
"*",
"rc",
",",
"roughness",
"=",
"roughness",
",",
"Rec_method",
"=",
"'Srinivasan'",
",",
"laminar_method",
"=",
"'White'",
",",
"turbulent_method",
"=",
"'Srinivasan turbulent'",
")",
"K",
"=",
"0.0175",
"*",
"alpha",
"*",
"fc",
"*",
"angle",
"*",
"rc",
"/",
"Di",
"else",
":",
"K",
"=",
"0.00431",
"*",
"alpha",
"*",
"angle",
"*",
"Re",
"**",
"-",
"0.17",
"*",
"(",
"rc",
"/",
"Di",
")",
"**",
"0.84",
"return",
"K"
]
| Ito method as shown in Blevins. Curved friction factor as given in
Blevins, with minor tweaks to be more accurate to the original methods. | [
"Ito",
"method",
"as",
"shown",
"in",
"Blevins",
".",
"Curved",
"friction",
"factor",
"as",
"given",
"in",
"Blevins",
"with",
"minor",
"tweaks",
"to",
"be",
"more",
"accurate",
"to",
"the",
"original",
"methods",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/fittings.py#L1193-L1224 | train |
CalebBell/fluids | fluids/design_climate.py | geopy_geolocator | def geopy_geolocator():
'''Lazy loader for geocoder from geopy. This currently loads the
`Nominatim` geocode and returns an instance of it, taking ~2 us.
'''
global geolocator
if geolocator is None:
try:
from geopy.geocoders import Nominatim
except ImportError:
return None
geolocator = Nominatim(user_agent=geolocator_user_agent)
return geolocator
return geolocator | python | def geopy_geolocator():
'''Lazy loader for geocoder from geopy. This currently loads the
`Nominatim` geocode and returns an instance of it, taking ~2 us.
'''
global geolocator
if geolocator is None:
try:
from geopy.geocoders import Nominatim
except ImportError:
return None
geolocator = Nominatim(user_agent=geolocator_user_agent)
return geolocator
return geolocator | [
"def",
"geopy_geolocator",
"(",
")",
":",
"global",
"geolocator",
"if",
"geolocator",
"is",
"None",
":",
"try",
":",
"from",
"geopy",
".",
"geocoders",
"import",
"Nominatim",
"except",
"ImportError",
":",
"return",
"None",
"geolocator",
"=",
"Nominatim",
"(",
"user_agent",
"=",
"geolocator_user_agent",
")",
"return",
"geolocator",
"return",
"geolocator"
]
| Lazy loader for geocoder from geopy. This currently loads the
`Nominatim` geocode and returns an instance of it, taking ~2 us. | [
"Lazy",
"loader",
"for",
"geocoder",
"from",
"geopy",
".",
"This",
"currently",
"loads",
"the",
"Nominatim",
"geocode",
"and",
"returns",
"an",
"instance",
"of",
"it",
"taking",
"~2",
"us",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/design_climate.py#L86-L98 | train |
CalebBell/fluids | fluids/design_climate.py | heating_degree_days | def heating_degree_days(T, T_base=F2K(65), truncate=True):
r'''Calculates the heating degree days for a period of time.
.. math::
\text{heating degree days} = max(T - T_{base}, 0)
Parameters
----------
T : float
Measured temperature; sometimes an average over a length of time is used,
other times the average of the lowest and highest temperature in a
period are used, [K]
T_base : float, optional
Reference temperature for the degree day calculation, defaults
to 65 °F (18.33 °C, 291.483 K), the value most used in the US, [K]
truncate : bool
If truncate is True, no negative values will be returned; if negative,
the value is truncated to 0, [-]
Returns
-------
heating_degree_days : float
Degree above the base temperature multiplied by the length of time of
the measurement, normally days [day*K]
Notes
-----
Some common base temperatures are 18 °C (Canada), 15.5 °C (EU),
17 °C (Denmark, Finland), 12 °C Switzerland. The base temperature
should always be presented with the results.
The time unit does not have to be days; it can be any time unit, and the
calculation behaves the same.
Examples
--------
>>> heating_degree_days(303.8)
12.31666666666672
>>> heating_degree_days(273)
0.0
>>> heating_degree_days(322, T_base=300)
22
References
----------
.. [1] "Heating Degree Day." Wikipedia, January 24, 2018.
https://en.wikipedia.org/w/index.php?title=Heating_degree_day&oldid=822187764.
'''
dd = T - T_base
if truncate and dd < 0.0:
dd = 0.0
return dd | python | def heating_degree_days(T, T_base=F2K(65), truncate=True):
r'''Calculates the heating degree days for a period of time.
.. math::
\text{heating degree days} = max(T - T_{base}, 0)
Parameters
----------
T : float
Measured temperature; sometimes an average over a length of time is used,
other times the average of the lowest and highest temperature in a
period are used, [K]
T_base : float, optional
Reference temperature for the degree day calculation, defaults
to 65 °F (18.33 °C, 291.483 K), the value most used in the US, [K]
truncate : bool
If truncate is True, no negative values will be returned; if negative,
the value is truncated to 0, [-]
Returns
-------
heating_degree_days : float
Degree above the base temperature multiplied by the length of time of
the measurement, normally days [day*K]
Notes
-----
Some common base temperatures are 18 °C (Canada), 15.5 °C (EU),
17 °C (Denmark, Finland), 12 °C Switzerland. The base temperature
should always be presented with the results.
The time unit does not have to be days; it can be any time unit, and the
calculation behaves the same.
Examples
--------
>>> heating_degree_days(303.8)
12.31666666666672
>>> heating_degree_days(273)
0.0
>>> heating_degree_days(322, T_base=300)
22
References
----------
.. [1] "Heating Degree Day." Wikipedia, January 24, 2018.
https://en.wikipedia.org/w/index.php?title=Heating_degree_day&oldid=822187764.
'''
dd = T - T_base
if truncate and dd < 0.0:
dd = 0.0
return dd | [
"def",
"heating_degree_days",
"(",
"T",
",",
"T_base",
"=",
"F2K",
"(",
"65",
")",
",",
"truncate",
"=",
"True",
")",
":",
"dd",
"=",
"T",
"-",
"T_base",
"if",
"truncate",
"and",
"dd",
"<",
"0.0",
":",
"dd",
"=",
"0.0",
"return",
"dd"
]
| r'''Calculates the heating degree days for a period of time.
.. math::
\text{heating degree days} = max(T - T_{base}, 0)
Parameters
----------
T : float
Measured temperature; sometimes an average over a length of time is used,
other times the average of the lowest and highest temperature in a
period are used, [K]
T_base : float, optional
Reference temperature for the degree day calculation, defaults
to 65 °F (18.33 °C, 291.483 K), the value most used in the US, [K]
truncate : bool
If truncate is True, no negative values will be returned; if negative,
the value is truncated to 0, [-]
Returns
-------
heating_degree_days : float
Degree above the base temperature multiplied by the length of time of
the measurement, normally days [day*K]
Notes
-----
Some common base temperatures are 18 °C (Canada), 15.5 °C (EU),
17 °C (Denmark, Finland), 12 °C Switzerland. The base temperature
should always be presented with the results.
The time unit does not have to be days; it can be any time unit, and the
calculation behaves the same.
Examples
--------
>>> heating_degree_days(303.8)
12.31666666666672
>>> heating_degree_days(273)
0.0
>>> heating_degree_days(322, T_base=300)
22
References
----------
.. [1] "Heating Degree Day." Wikipedia, January 24, 2018.
https://en.wikipedia.org/w/index.php?title=Heating_degree_day&oldid=822187764. | [
"r",
"Calculates",
"the",
"heating",
"degree",
"days",
"for",
"a",
"period",
"of",
"time",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/design_climate.py#L193-L246 | train |
CalebBell/fluids | fluids/design_climate.py | cooling_degree_days | def cooling_degree_days(T, T_base=283.15, truncate=True):
r'''Calculates the cooling degree days for a period of time.
.. math::
\text{cooling degree days} = max(T_{base} - T, 0)
Parameters
----------
T : float
Measured temperature; sometimes an average over a length of time is used,
other times the average of the lowest and highest temperature in a
period are used, [K]
T_base : float, optional
Reference temperature for the degree day calculation, defaults
to 10 °C, 283.15 K, a common value, [K]
truncate : bool
If truncate is True, no negative values will be returned; if negative,
the value is truncated to 0, [-]
Returns
-------
cooling_degree_days : float
Degree below the base temperature multiplied by the length of time of
the measurement, normally days [day*K]
Notes
-----
The base temperature should always be presented with the results.
The time unit does not have to be days; it can be time unit, and the
calculation behaves the same.
Examples
--------
>>> cooling_degree_days(250)
33.14999999999998
>>> cooling_degree_days(300)
0.0
>>> cooling_degree_days(250, T_base=300)
50
References
----------
.. [1] "Heating Degree Day." Wikipedia, January 24, 2018.
https://en.wikipedia.org/w/index.php?title=Heating_degree_day&oldid=822187764.
'''
dd = T_base - T
if truncate and dd < 0.0:
dd = 0.0
return dd | python | def cooling_degree_days(T, T_base=283.15, truncate=True):
r'''Calculates the cooling degree days for a period of time.
.. math::
\text{cooling degree days} = max(T_{base} - T, 0)
Parameters
----------
T : float
Measured temperature; sometimes an average over a length of time is used,
other times the average of the lowest and highest temperature in a
period are used, [K]
T_base : float, optional
Reference temperature for the degree day calculation, defaults
to 10 °C, 283.15 K, a common value, [K]
truncate : bool
If truncate is True, no negative values will be returned; if negative,
the value is truncated to 0, [-]
Returns
-------
cooling_degree_days : float
Degree below the base temperature multiplied by the length of time of
the measurement, normally days [day*K]
Notes
-----
The base temperature should always be presented with the results.
The time unit does not have to be days; it can be time unit, and the
calculation behaves the same.
Examples
--------
>>> cooling_degree_days(250)
33.14999999999998
>>> cooling_degree_days(300)
0.0
>>> cooling_degree_days(250, T_base=300)
50
References
----------
.. [1] "Heating Degree Day." Wikipedia, January 24, 2018.
https://en.wikipedia.org/w/index.php?title=Heating_degree_day&oldid=822187764.
'''
dd = T_base - T
if truncate and dd < 0.0:
dd = 0.0
return dd | [
"def",
"cooling_degree_days",
"(",
"T",
",",
"T_base",
"=",
"283.15",
",",
"truncate",
"=",
"True",
")",
":",
"dd",
"=",
"T_base",
"-",
"T",
"if",
"truncate",
"and",
"dd",
"<",
"0.0",
":",
"dd",
"=",
"0.0",
"return",
"dd"
]
| r'''Calculates the cooling degree days for a period of time.
.. math::
\text{cooling degree days} = max(T_{base} - T, 0)
Parameters
----------
T : float
Measured temperature; sometimes an average over a length of time is used,
other times the average of the lowest and highest temperature in a
period are used, [K]
T_base : float, optional
Reference temperature for the degree day calculation, defaults
to 10 °C, 283.15 K, a common value, [K]
truncate : bool
If truncate is True, no negative values will be returned; if negative,
the value is truncated to 0, [-]
Returns
-------
cooling_degree_days : float
Degree below the base temperature multiplied by the length of time of
the measurement, normally days [day*K]
Notes
-----
The base temperature should always be presented with the results.
The time unit does not have to be days; it can be time unit, and the
calculation behaves the same.
Examples
--------
>>> cooling_degree_days(250)
33.14999999999998
>>> cooling_degree_days(300)
0.0
>>> cooling_degree_days(250, T_base=300)
50
References
----------
.. [1] "Heating Degree Day." Wikipedia, January 24, 2018.
https://en.wikipedia.org/w/index.php?title=Heating_degree_day&oldid=822187764. | [
"r",
"Calculates",
"the",
"cooling",
"degree",
"days",
"for",
"a",
"period",
"of",
"time",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/design_climate.py#L249-L300 | train |
CalebBell/fluids | fluids/design_climate.py | get_station_year_text | def get_station_year_text(WMO, WBAN, year):
'''Basic method to download data from the GSOD database, given a
station identifier and year.
Parameters
----------
WMO : int or None
World Meteorological Organization (WMO) identifiers, [-]
WBAN : int or None
Weather Bureau Army Navy (WBAN) weather station identifier, [-]
year : int
Year data should be retrieved from, [year]
Returns
-------
data : str
Downloaded data file
'''
if WMO is None:
WMO = 999999
if WBAN is None:
WBAN = 99999
station = str(int(WMO)) + '-' + str(int(WBAN))
gsod_year_dir = os.path.join(data_dir, 'gsod', str(year))
path = os.path.join(gsod_year_dir, station + '.op')
if os.path.exists(path):
data = open(path).read()
if data and data != 'Exception':
return data
else:
raise Exception(data)
toget = ('ftp://ftp.ncdc.noaa.gov/pub/data/gsod/' + str(year) + '/'
+ station + '-' + str(year) +'.op.gz')
try:
data = urlopen(toget, timeout=5)
except Exception as e:
if not os.path.exists(gsod_year_dir):
os.makedirs(gsod_year_dir)
open(path, 'w').write('Exception')
raise Exception('Could not obtain desired data; check '
'if the year has data published for the '
'specified station and the station was specified '
'in the correct form. The full error is %s' %(e))
data = data.read()
data_thing = StringIO(data)
f = gzip.GzipFile(fileobj=data_thing, mode="r")
year_station_data = f.read()
try:
year_station_data = year_station_data.decode('utf-8')
except:
pass
# Cache the data for future use
if not os.path.exists(gsod_year_dir):
os.makedirs(gsod_year_dir)
open(path, 'w').write(year_station_data)
return year_station_data | python | def get_station_year_text(WMO, WBAN, year):
'''Basic method to download data from the GSOD database, given a
station identifier and year.
Parameters
----------
WMO : int or None
World Meteorological Organization (WMO) identifiers, [-]
WBAN : int or None
Weather Bureau Army Navy (WBAN) weather station identifier, [-]
year : int
Year data should be retrieved from, [year]
Returns
-------
data : str
Downloaded data file
'''
if WMO is None:
WMO = 999999
if WBAN is None:
WBAN = 99999
station = str(int(WMO)) + '-' + str(int(WBAN))
gsod_year_dir = os.path.join(data_dir, 'gsod', str(year))
path = os.path.join(gsod_year_dir, station + '.op')
if os.path.exists(path):
data = open(path).read()
if data and data != 'Exception':
return data
else:
raise Exception(data)
toget = ('ftp://ftp.ncdc.noaa.gov/pub/data/gsod/' + str(year) + '/'
+ station + '-' + str(year) +'.op.gz')
try:
data = urlopen(toget, timeout=5)
except Exception as e:
if not os.path.exists(gsod_year_dir):
os.makedirs(gsod_year_dir)
open(path, 'w').write('Exception')
raise Exception('Could not obtain desired data; check '
'if the year has data published for the '
'specified station and the station was specified '
'in the correct form. The full error is %s' %(e))
data = data.read()
data_thing = StringIO(data)
f = gzip.GzipFile(fileobj=data_thing, mode="r")
year_station_data = f.read()
try:
year_station_data = year_station_data.decode('utf-8')
except:
pass
# Cache the data for future use
if not os.path.exists(gsod_year_dir):
os.makedirs(gsod_year_dir)
open(path, 'w').write(year_station_data)
return year_station_data | [
"def",
"get_station_year_text",
"(",
"WMO",
",",
"WBAN",
",",
"year",
")",
":",
"if",
"WMO",
"is",
"None",
":",
"WMO",
"=",
"999999",
"if",
"WBAN",
"is",
"None",
":",
"WBAN",
"=",
"99999",
"station",
"=",
"str",
"(",
"int",
"(",
"WMO",
")",
")",
"+",
"'-'",
"+",
"str",
"(",
"int",
"(",
"WBAN",
")",
")",
"gsod_year_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"data_dir",
",",
"'gsod'",
",",
"str",
"(",
"year",
")",
")",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"gsod_year_dir",
",",
"station",
"+",
"'.op'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"data",
"=",
"open",
"(",
"path",
")",
".",
"read",
"(",
")",
"if",
"data",
"and",
"data",
"!=",
"'Exception'",
":",
"return",
"data",
"else",
":",
"raise",
"Exception",
"(",
"data",
")",
"toget",
"=",
"(",
"'ftp://ftp.ncdc.noaa.gov/pub/data/gsod/'",
"+",
"str",
"(",
"year",
")",
"+",
"'/'",
"+",
"station",
"+",
"'-'",
"+",
"str",
"(",
"year",
")",
"+",
"'.op.gz'",
")",
"try",
":",
"data",
"=",
"urlopen",
"(",
"toget",
",",
"timeout",
"=",
"5",
")",
"except",
"Exception",
"as",
"e",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"gsod_year_dir",
")",
":",
"os",
".",
"makedirs",
"(",
"gsod_year_dir",
")",
"open",
"(",
"path",
",",
"'w'",
")",
".",
"write",
"(",
"'Exception'",
")",
"raise",
"Exception",
"(",
"'Could not obtain desired data; check '",
"'if the year has data published for the '",
"'specified station and the station was specified '",
"'in the correct form. The full error is %s'",
"%",
"(",
"e",
")",
")",
"data",
"=",
"data",
".",
"read",
"(",
")",
"data_thing",
"=",
"StringIO",
"(",
"data",
")",
"f",
"=",
"gzip",
".",
"GzipFile",
"(",
"fileobj",
"=",
"data_thing",
",",
"mode",
"=",
"\"r\"",
")",
"year_station_data",
"=",
"f",
".",
"read",
"(",
")",
"try",
":",
"year_station_data",
"=",
"year_station_data",
".",
"decode",
"(",
"'utf-8'",
")",
"except",
":",
"pass",
"# Cache the data for future use",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"gsod_year_dir",
")",
":",
"os",
".",
"makedirs",
"(",
"gsod_year_dir",
")",
"open",
"(",
"path",
",",
"'w'",
")",
".",
"write",
"(",
"year_station_data",
")",
"return",
"year_station_data"
]
| Basic method to download data from the GSOD database, given a
station identifier and year.
Parameters
----------
WMO : int or None
World Meteorological Organization (WMO) identifiers, [-]
WBAN : int or None
Weather Bureau Army Navy (WBAN) weather station identifier, [-]
year : int
Year data should be retrieved from, [year]
Returns
-------
data : str
Downloaded data file | [
"Basic",
"method",
"to",
"download",
"data",
"from",
"the",
"GSOD",
"database",
"given",
"a",
"station",
"identifier",
"and",
"year",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/design_climate.py#L699-L760 | train |
CalebBell/fluids | fluids/packed_tower.py | _Stichlmair_flood_f | def _Stichlmair_flood_f(inputs, Vl, rhog, rhol, mug, voidage, specific_area,
C1, C2, C3, H):
'''Internal function which calculates the errors of the two Stichlmair
objective functions, and their jacobian.
'''
Vg, dP_irr = float(inputs[0]), float(inputs[1])
dp = 6.0*(1.0 - voidage)/specific_area
Re = Vg*rhog*dp/mug
f0 = C1/Re + C2/Re**0.5 + C3
dP_dry = 0.75*f0*(1.0 - voidage)/voidage**4.65*rhog*H/dp*Vg*Vg
c = (-C1/Re - 0.5*C2*Re**-0.5)/f0
Frl = Vl*Vl*specific_area/(g*voidage**4.65)
h0 = 0.555*Frl**(1/3.)
hT = h0*(1.0 + 20.0*(dP_irr/H/rhol/g)**2)
err1 = dP_dry/H*((1.0 - voidage + hT)/(1.0 - voidage))**((2.0 + c)/3.)*(voidage/(voidage-hT))**4.65 - dP_irr/H
term = (dP_irr/(rhol*g*H))**2
err2 = (1./term - 40.0*((2.0+c)/3.)*h0/(1.0 - voidage + h0*(1.0 + 20.0*term))
- 186.0*h0/(voidage - h0*(1.0 + 20.0*term)))
return err1, err2 | python | def _Stichlmair_flood_f(inputs, Vl, rhog, rhol, mug, voidage, specific_area,
C1, C2, C3, H):
'''Internal function which calculates the errors of the two Stichlmair
objective functions, and their jacobian.
'''
Vg, dP_irr = float(inputs[0]), float(inputs[1])
dp = 6.0*(1.0 - voidage)/specific_area
Re = Vg*rhog*dp/mug
f0 = C1/Re + C2/Re**0.5 + C3
dP_dry = 0.75*f0*(1.0 - voidage)/voidage**4.65*rhog*H/dp*Vg*Vg
c = (-C1/Re - 0.5*C2*Re**-0.5)/f0
Frl = Vl*Vl*specific_area/(g*voidage**4.65)
h0 = 0.555*Frl**(1/3.)
hT = h0*(1.0 + 20.0*(dP_irr/H/rhol/g)**2)
err1 = dP_dry/H*((1.0 - voidage + hT)/(1.0 - voidage))**((2.0 + c)/3.)*(voidage/(voidage-hT))**4.65 - dP_irr/H
term = (dP_irr/(rhol*g*H))**2
err2 = (1./term - 40.0*((2.0+c)/3.)*h0/(1.0 - voidage + h0*(1.0 + 20.0*term))
- 186.0*h0/(voidage - h0*(1.0 + 20.0*term)))
return err1, err2 | [
"def",
"_Stichlmair_flood_f",
"(",
"inputs",
",",
"Vl",
",",
"rhog",
",",
"rhol",
",",
"mug",
",",
"voidage",
",",
"specific_area",
",",
"C1",
",",
"C2",
",",
"C3",
",",
"H",
")",
":",
"Vg",
",",
"dP_irr",
"=",
"float",
"(",
"inputs",
"[",
"0",
"]",
")",
",",
"float",
"(",
"inputs",
"[",
"1",
"]",
")",
"dp",
"=",
"6.0",
"*",
"(",
"1.0",
"-",
"voidage",
")",
"/",
"specific_area",
"Re",
"=",
"Vg",
"*",
"rhog",
"*",
"dp",
"/",
"mug",
"f0",
"=",
"C1",
"/",
"Re",
"+",
"C2",
"/",
"Re",
"**",
"0.5",
"+",
"C3",
"dP_dry",
"=",
"0.75",
"*",
"f0",
"*",
"(",
"1.0",
"-",
"voidage",
")",
"/",
"voidage",
"**",
"4.65",
"*",
"rhog",
"*",
"H",
"/",
"dp",
"*",
"Vg",
"*",
"Vg",
"c",
"=",
"(",
"-",
"C1",
"/",
"Re",
"-",
"0.5",
"*",
"C2",
"*",
"Re",
"**",
"-",
"0.5",
")",
"/",
"f0",
"Frl",
"=",
"Vl",
"*",
"Vl",
"*",
"specific_area",
"/",
"(",
"g",
"*",
"voidage",
"**",
"4.65",
")",
"h0",
"=",
"0.555",
"*",
"Frl",
"**",
"(",
"1",
"/",
"3.",
")",
"hT",
"=",
"h0",
"*",
"(",
"1.0",
"+",
"20.0",
"*",
"(",
"dP_irr",
"/",
"H",
"/",
"rhol",
"/",
"g",
")",
"**",
"2",
")",
"err1",
"=",
"dP_dry",
"/",
"H",
"*",
"(",
"(",
"1.0",
"-",
"voidage",
"+",
"hT",
")",
"/",
"(",
"1.0",
"-",
"voidage",
")",
")",
"**",
"(",
"(",
"2.0",
"+",
"c",
")",
"/",
"3.",
")",
"*",
"(",
"voidage",
"/",
"(",
"voidage",
"-",
"hT",
")",
")",
"**",
"4.65",
"-",
"dP_irr",
"/",
"H",
"term",
"=",
"(",
"dP_irr",
"/",
"(",
"rhol",
"*",
"g",
"*",
"H",
")",
")",
"**",
"2",
"err2",
"=",
"(",
"1.",
"/",
"term",
"-",
"40.0",
"*",
"(",
"(",
"2.0",
"+",
"c",
")",
"/",
"3.",
")",
"*",
"h0",
"/",
"(",
"1.0",
"-",
"voidage",
"+",
"h0",
"*",
"(",
"1.0",
"+",
"20.0",
"*",
"term",
")",
")",
"-",
"186.0",
"*",
"h0",
"/",
"(",
"voidage",
"-",
"h0",
"*",
"(",
"1.0",
"+",
"20.0",
"*",
"term",
")",
")",
")",
"return",
"err1",
",",
"err2"
]
| Internal function which calculates the errors of the two Stichlmair
objective functions, and their jacobian. | [
"Internal",
"function",
"which",
"calculates",
"the",
"errors",
"of",
"the",
"two",
"Stichlmair",
"objective",
"functions",
"and",
"their",
"jacobian",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/packed_tower.py#L568-L586 | train |
CalebBell/fluids | fluids/packed_tower.py | Robbins | def Robbins(L, G, rhol, rhog, mul, H=1.0, Fpd=24.0):
r'''Calculates pressure drop across a packed column, using the Robbins
equation.
Pressure drop is given by:
.. math::
\Delta P = C_3 G_f^2 10^{C_4L_f}+0.4[L_f/20000]^{0.1}[C_3G_f^210^{C_4L_f}]^4
.. math::
G_f=G[0.075/\rho_g]^{0.5}[F_{pd}/20]^{0.5}=986F_s[F_{pd}/20]^{0.5}
.. math::
L_f=L[62.4/\rho_L][F_{pd}/20]^{0.5}\mu^{0.1}
.. math::
F_s=V_s\rho_g^{0.5}
Parameters
----------
L : float
Specific liquid mass flow rate [kg/s/m^2]
G : float
Specific gas mass flow rate [kg/s/m^2]
rhol : float
Density of liquid [kg/m^3]
rhog : float
Density of gas [kg/m^3]
mul : float
Viscosity of liquid [Pa*s]
H : float
Height of packing [m]
Fpd : float
Robbins packing factor (tabulated for packings) [1/ft]
Returns
-------
dP : float
Pressure drop across packing [Pa]
Notes
-----
Perry's displayed equation has a typo in a superscript.
This model is based on the example in Perry's.
Examples
--------
>>> Robbins(L=12.2, G=2.03, rhol=1000., rhog=1.1853, mul=0.001, H=2.0, Fpd=24.0)
619.6624593438102
References
----------
.. [1] Robbins [Chem. Eng. Progr., p. 87 (May 1991) Improved Pressure Drop
Prediction with a New Correlation.
'''
# Convert SI units to imperial for use in correlation
L = L*737.33812 # kg/s/m^2 to lb/hr/ft^2
G = G*737.33812 # kg/s/m^2 to lb/hr/ft^2
rhol = rhol*0.062427961 # kg/m^3 to lb/ft^3
rhog = rhog*0.062427961 # kg/m^3 to lb/ft^3
mul = mul*1000.0 # Pa*s to cP
C3 = 7.4E-8
C4 = 2.7E-5
Fpd_root_term = (.05*Fpd)**0.5
Lf = L*(62.4/rhol)*Fpd_root_term*mul**0.1
Gf = G*(0.075/rhog)**0.5*Fpd_root_term
Gf2 = Gf*Gf
C4LF_10_GF2_C3 = C3*Gf2*10.0**(C4*Lf)
C4LF_10_GF2_C3_2 = C4LF_10_GF2_C3*C4LF_10_GF2_C3
dP = C4LF_10_GF2_C3 + 0.4*(5e-5*Lf)**0.1*(C4LF_10_GF2_C3_2*C4LF_10_GF2_C3_2)
return dP*817.22083*H | python | def Robbins(L, G, rhol, rhog, mul, H=1.0, Fpd=24.0):
r'''Calculates pressure drop across a packed column, using the Robbins
equation.
Pressure drop is given by:
.. math::
\Delta P = C_3 G_f^2 10^{C_4L_f}+0.4[L_f/20000]^{0.1}[C_3G_f^210^{C_4L_f}]^4
.. math::
G_f=G[0.075/\rho_g]^{0.5}[F_{pd}/20]^{0.5}=986F_s[F_{pd}/20]^{0.5}
.. math::
L_f=L[62.4/\rho_L][F_{pd}/20]^{0.5}\mu^{0.1}
.. math::
F_s=V_s\rho_g^{0.5}
Parameters
----------
L : float
Specific liquid mass flow rate [kg/s/m^2]
G : float
Specific gas mass flow rate [kg/s/m^2]
rhol : float
Density of liquid [kg/m^3]
rhog : float
Density of gas [kg/m^3]
mul : float
Viscosity of liquid [Pa*s]
H : float
Height of packing [m]
Fpd : float
Robbins packing factor (tabulated for packings) [1/ft]
Returns
-------
dP : float
Pressure drop across packing [Pa]
Notes
-----
Perry's displayed equation has a typo in a superscript.
This model is based on the example in Perry's.
Examples
--------
>>> Robbins(L=12.2, G=2.03, rhol=1000., rhog=1.1853, mul=0.001, H=2.0, Fpd=24.0)
619.6624593438102
References
----------
.. [1] Robbins [Chem. Eng. Progr., p. 87 (May 1991) Improved Pressure Drop
Prediction with a New Correlation.
'''
# Convert SI units to imperial for use in correlation
L = L*737.33812 # kg/s/m^2 to lb/hr/ft^2
G = G*737.33812 # kg/s/m^2 to lb/hr/ft^2
rhol = rhol*0.062427961 # kg/m^3 to lb/ft^3
rhog = rhog*0.062427961 # kg/m^3 to lb/ft^3
mul = mul*1000.0 # Pa*s to cP
C3 = 7.4E-8
C4 = 2.7E-5
Fpd_root_term = (.05*Fpd)**0.5
Lf = L*(62.4/rhol)*Fpd_root_term*mul**0.1
Gf = G*(0.075/rhog)**0.5*Fpd_root_term
Gf2 = Gf*Gf
C4LF_10_GF2_C3 = C3*Gf2*10.0**(C4*Lf)
C4LF_10_GF2_C3_2 = C4LF_10_GF2_C3*C4LF_10_GF2_C3
dP = C4LF_10_GF2_C3 + 0.4*(5e-5*Lf)**0.1*(C4LF_10_GF2_C3_2*C4LF_10_GF2_C3_2)
return dP*817.22083*H | [
"def",
"Robbins",
"(",
"L",
",",
"G",
",",
"rhol",
",",
"rhog",
",",
"mul",
",",
"H",
"=",
"1.0",
",",
"Fpd",
"=",
"24.0",
")",
":",
"# Convert SI units to imperial for use in correlation",
"L",
"=",
"L",
"*",
"737.33812",
"# kg/s/m^2 to lb/hr/ft^2",
"G",
"=",
"G",
"*",
"737.33812",
"# kg/s/m^2 to lb/hr/ft^2",
"rhol",
"=",
"rhol",
"*",
"0.062427961",
"# kg/m^3 to lb/ft^3",
"rhog",
"=",
"rhog",
"*",
"0.062427961",
"# kg/m^3 to lb/ft^3",
"mul",
"=",
"mul",
"*",
"1000.0",
"# Pa*s to cP",
"C3",
"=",
"7.4E-8",
"C4",
"=",
"2.7E-5",
"Fpd_root_term",
"=",
"(",
".05",
"*",
"Fpd",
")",
"**",
"0.5",
"Lf",
"=",
"L",
"*",
"(",
"62.4",
"/",
"rhol",
")",
"*",
"Fpd_root_term",
"*",
"mul",
"**",
"0.1",
"Gf",
"=",
"G",
"*",
"(",
"0.075",
"/",
"rhog",
")",
"**",
"0.5",
"*",
"Fpd_root_term",
"Gf2",
"=",
"Gf",
"*",
"Gf",
"C4LF_10_GF2_C3",
"=",
"C3",
"*",
"Gf2",
"*",
"10.0",
"**",
"(",
"C4",
"*",
"Lf",
")",
"C4LF_10_GF2_C3_2",
"=",
"C4LF_10_GF2_C3",
"*",
"C4LF_10_GF2_C3",
"dP",
"=",
"C4LF_10_GF2_C3",
"+",
"0.4",
"*",
"(",
"5e-5",
"*",
"Lf",
")",
"**",
"0.1",
"*",
"(",
"C4LF_10_GF2_C3_2",
"*",
"C4LF_10_GF2_C3_2",
")",
"return",
"dP",
"*",
"817.22083",
"*",
"H"
]
| r'''Calculates pressure drop across a packed column, using the Robbins
equation.
Pressure drop is given by:
.. math::
\Delta P = C_3 G_f^2 10^{C_4L_f}+0.4[L_f/20000]^{0.1}[C_3G_f^210^{C_4L_f}]^4
.. math::
G_f=G[0.075/\rho_g]^{0.5}[F_{pd}/20]^{0.5}=986F_s[F_{pd}/20]^{0.5}
.. math::
L_f=L[62.4/\rho_L][F_{pd}/20]^{0.5}\mu^{0.1}
.. math::
F_s=V_s\rho_g^{0.5}
Parameters
----------
L : float
Specific liquid mass flow rate [kg/s/m^2]
G : float
Specific gas mass flow rate [kg/s/m^2]
rhol : float
Density of liquid [kg/m^3]
rhog : float
Density of gas [kg/m^3]
mul : float
Viscosity of liquid [Pa*s]
H : float
Height of packing [m]
Fpd : float
Robbins packing factor (tabulated for packings) [1/ft]
Returns
-------
dP : float
Pressure drop across packing [Pa]
Notes
-----
Perry's displayed equation has a typo in a superscript.
This model is based on the example in Perry's.
Examples
--------
>>> Robbins(L=12.2, G=2.03, rhol=1000., rhog=1.1853, mul=0.001, H=2.0, Fpd=24.0)
619.6624593438102
References
----------
.. [1] Robbins [Chem. Eng. Progr., p. 87 (May 1991) Improved Pressure Drop
Prediction with a New Correlation. | [
"r",
"Calculates",
"pressure",
"drop",
"across",
"a",
"packed",
"column",
"using",
"the",
"Robbins",
"equation",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/packed_tower.py#L741-L812 | train |
CalebBell/fluids | fluids/packed_bed.py | dP_packed_bed | def dP_packed_bed(dp, voidage, vs, rho, mu, L=1, Dt=None, sphericity=None,
Method=None, AvailableMethods=False):
r'''This function handles choosing which pressure drop in a packed bed
correlation is used. Automatically select which correlation
to use if none is provided. Returns None if insufficient information is
provided.
Preferred correlations are 'Erdim, Akgiray & Demir' when tube
diameter is not provided, and 'Harrison, Brunner & Hecker' when tube
diameter is provided. If you are using a particles in a narrow tube
between 2 and 3 particle diameters, expect higher than normal voidages
(0.4-0.5) and used the method 'Guo, Sun, Zhang, Ding & Liu'.
Examples
--------
>>> dP_packed_bed(dp=8E-4, voidage=0.4, vs=1E-3, rho=1E3, mu=1E-3)
1438.2826958844414
>>> dP_packed_bed(dp=8E-4, voidage=0.4, vs=1E-3, rho=1E3, mu=1E-3, Dt=0.01)
1255.1625662548427
>>> dP_packed_bed(dp=0.05, voidage=0.492, vs=0.1, rho=1E3, mu=1E-3, Dt=0.015, Method='Guo, Sun, Zhang, Ding & Liu')
18782.499710673364
Parameters
----------
dp : float
Particle diameter of spheres [m]
voidage : float
Void fraction of bed packing [-]
vs : float
Superficial velocity of the fluid (volumetric flow rate/cross-sectional
area) [m/s]
rho : float
Density of the fluid [kg/m^3]
mu : float
Viscosity of the fluid, [Pa*s]
L : float, optional
Length the fluid flows in the packed bed [m]
Dt : float, optional
Diameter of the tube, [m]
sphericity : float, optional
Sphericity of the particles [-]
Returns
-------
dP : float
Pressure drop across the bed [Pa]
methods : list, only returned if AvailableMethods == True
List of methods which can be used to calculate `dP` with the given inputs
Other Parameters
----------------
Method : string, optional
A string of the function name to use, as in the dictionary
packed_beds_correlations
AvailableMethods : bool, optional
If True, function will consider which methods which can be used to
calculate `dP` with the given inputs and return them as a list
'''
def list_methods():
methods = []
if all((dp, voidage, vs, rho, mu, L)):
for key, values in packed_beds_correlations.items():
if Dt or not values[1]:
methods.append(key)
if 'Harrison, Brunner & Hecker' in methods:
methods.remove('Harrison, Brunner & Hecker')
methods.insert(0, 'Harrison, Brunner & Hecker')
elif 'Erdim, Akgiray & Demir' in methods:
methods.remove('Erdim, Akgiray & Demir')
methods.insert(0, 'Erdim, Akgiray & Demir')
return methods
if AvailableMethods:
return list_methods()
if not Method:
Method = list_methods()[0]
if dp and sphericity:
dp = dp*sphericity
if Method in packed_beds_correlations:
if packed_beds_correlations[Method][1]:
return packed_beds_correlations[Method][0](dp=dp, voidage=voidage, vs=vs, rho=rho, mu=mu, L=L, Dt=Dt)
else:
return packed_beds_correlations[Method][0](dp=dp, voidage=voidage, vs=vs, rho=rho, mu=mu, L=L)
else:
raise Exception('Failure in in function') | python | def dP_packed_bed(dp, voidage, vs, rho, mu, L=1, Dt=None, sphericity=None,
Method=None, AvailableMethods=False):
r'''This function handles choosing which pressure drop in a packed bed
correlation is used. Automatically select which correlation
to use if none is provided. Returns None if insufficient information is
provided.
Preferred correlations are 'Erdim, Akgiray & Demir' when tube
diameter is not provided, and 'Harrison, Brunner & Hecker' when tube
diameter is provided. If you are using a particles in a narrow tube
between 2 and 3 particle diameters, expect higher than normal voidages
(0.4-0.5) and used the method 'Guo, Sun, Zhang, Ding & Liu'.
Examples
--------
>>> dP_packed_bed(dp=8E-4, voidage=0.4, vs=1E-3, rho=1E3, mu=1E-3)
1438.2826958844414
>>> dP_packed_bed(dp=8E-4, voidage=0.4, vs=1E-3, rho=1E3, mu=1E-3, Dt=0.01)
1255.1625662548427
>>> dP_packed_bed(dp=0.05, voidage=0.492, vs=0.1, rho=1E3, mu=1E-3, Dt=0.015, Method='Guo, Sun, Zhang, Ding & Liu')
18782.499710673364
Parameters
----------
dp : float
Particle diameter of spheres [m]
voidage : float
Void fraction of bed packing [-]
vs : float
Superficial velocity of the fluid (volumetric flow rate/cross-sectional
area) [m/s]
rho : float
Density of the fluid [kg/m^3]
mu : float
Viscosity of the fluid, [Pa*s]
L : float, optional
Length the fluid flows in the packed bed [m]
Dt : float, optional
Diameter of the tube, [m]
sphericity : float, optional
Sphericity of the particles [-]
Returns
-------
dP : float
Pressure drop across the bed [Pa]
methods : list, only returned if AvailableMethods == True
List of methods which can be used to calculate `dP` with the given inputs
Other Parameters
----------------
Method : string, optional
A string of the function name to use, as in the dictionary
packed_beds_correlations
AvailableMethods : bool, optional
If True, function will consider which methods which can be used to
calculate `dP` with the given inputs and return them as a list
'''
def list_methods():
methods = []
if all((dp, voidage, vs, rho, mu, L)):
for key, values in packed_beds_correlations.items():
if Dt or not values[1]:
methods.append(key)
if 'Harrison, Brunner & Hecker' in methods:
methods.remove('Harrison, Brunner & Hecker')
methods.insert(0, 'Harrison, Brunner & Hecker')
elif 'Erdim, Akgiray & Demir' in methods:
methods.remove('Erdim, Akgiray & Demir')
methods.insert(0, 'Erdim, Akgiray & Demir')
return methods
if AvailableMethods:
return list_methods()
if not Method:
Method = list_methods()[0]
if dp and sphericity:
dp = dp*sphericity
if Method in packed_beds_correlations:
if packed_beds_correlations[Method][1]:
return packed_beds_correlations[Method][0](dp=dp, voidage=voidage, vs=vs, rho=rho, mu=mu, L=L, Dt=Dt)
else:
return packed_beds_correlations[Method][0](dp=dp, voidage=voidage, vs=vs, rho=rho, mu=mu, L=L)
else:
raise Exception('Failure in in function') | [
"def",
"dP_packed_bed",
"(",
"dp",
",",
"voidage",
",",
"vs",
",",
"rho",
",",
"mu",
",",
"L",
"=",
"1",
",",
"Dt",
"=",
"None",
",",
"sphericity",
"=",
"None",
",",
"Method",
"=",
"None",
",",
"AvailableMethods",
"=",
"False",
")",
":",
"def",
"list_methods",
"(",
")",
":",
"methods",
"=",
"[",
"]",
"if",
"all",
"(",
"(",
"dp",
",",
"voidage",
",",
"vs",
",",
"rho",
",",
"mu",
",",
"L",
")",
")",
":",
"for",
"key",
",",
"values",
"in",
"packed_beds_correlations",
".",
"items",
"(",
")",
":",
"if",
"Dt",
"or",
"not",
"values",
"[",
"1",
"]",
":",
"methods",
".",
"append",
"(",
"key",
")",
"if",
"'Harrison, Brunner & Hecker'",
"in",
"methods",
":",
"methods",
".",
"remove",
"(",
"'Harrison, Brunner & Hecker'",
")",
"methods",
".",
"insert",
"(",
"0",
",",
"'Harrison, Brunner & Hecker'",
")",
"elif",
"'Erdim, Akgiray & Demir'",
"in",
"methods",
":",
"methods",
".",
"remove",
"(",
"'Erdim, Akgiray & Demir'",
")",
"methods",
".",
"insert",
"(",
"0",
",",
"'Erdim, Akgiray & Demir'",
")",
"return",
"methods",
"if",
"AvailableMethods",
":",
"return",
"list_methods",
"(",
")",
"if",
"not",
"Method",
":",
"Method",
"=",
"list_methods",
"(",
")",
"[",
"0",
"]",
"if",
"dp",
"and",
"sphericity",
":",
"dp",
"=",
"dp",
"*",
"sphericity",
"if",
"Method",
"in",
"packed_beds_correlations",
":",
"if",
"packed_beds_correlations",
"[",
"Method",
"]",
"[",
"1",
"]",
":",
"return",
"packed_beds_correlations",
"[",
"Method",
"]",
"[",
"0",
"]",
"(",
"dp",
"=",
"dp",
",",
"voidage",
"=",
"voidage",
",",
"vs",
"=",
"vs",
",",
"rho",
"=",
"rho",
",",
"mu",
"=",
"mu",
",",
"L",
"=",
"L",
",",
"Dt",
"=",
"Dt",
")",
"else",
":",
"return",
"packed_beds_correlations",
"[",
"Method",
"]",
"[",
"0",
"]",
"(",
"dp",
"=",
"dp",
",",
"voidage",
"=",
"voidage",
",",
"vs",
"=",
"vs",
",",
"rho",
"=",
"rho",
",",
"mu",
"=",
"mu",
",",
"L",
"=",
"L",
")",
"else",
":",
"raise",
"Exception",
"(",
"'Failure in in function'",
")"
]
| r'''This function handles choosing which pressure drop in a packed bed
correlation is used. Automatically select which correlation
to use if none is provided. Returns None if insufficient information is
provided.
Preferred correlations are 'Erdim, Akgiray & Demir' when tube
diameter is not provided, and 'Harrison, Brunner & Hecker' when tube
diameter is provided. If you are using a particles in a narrow tube
between 2 and 3 particle diameters, expect higher than normal voidages
(0.4-0.5) and used the method 'Guo, Sun, Zhang, Ding & Liu'.
Examples
--------
>>> dP_packed_bed(dp=8E-4, voidage=0.4, vs=1E-3, rho=1E3, mu=1E-3)
1438.2826958844414
>>> dP_packed_bed(dp=8E-4, voidage=0.4, vs=1E-3, rho=1E3, mu=1E-3, Dt=0.01)
1255.1625662548427
>>> dP_packed_bed(dp=0.05, voidage=0.492, vs=0.1, rho=1E3, mu=1E-3, Dt=0.015, Method='Guo, Sun, Zhang, Ding & Liu')
18782.499710673364
Parameters
----------
dp : float
Particle diameter of spheres [m]
voidage : float
Void fraction of bed packing [-]
vs : float
Superficial velocity of the fluid (volumetric flow rate/cross-sectional
area) [m/s]
rho : float
Density of the fluid [kg/m^3]
mu : float
Viscosity of the fluid, [Pa*s]
L : float, optional
Length the fluid flows in the packed bed [m]
Dt : float, optional
Diameter of the tube, [m]
sphericity : float, optional
Sphericity of the particles [-]
Returns
-------
dP : float
Pressure drop across the bed [Pa]
methods : list, only returned if AvailableMethods == True
List of methods which can be used to calculate `dP` with the given inputs
Other Parameters
----------------
Method : string, optional
A string of the function name to use, as in the dictionary
packed_beds_correlations
AvailableMethods : bool, optional
If True, function will consider which methods which can be used to
calculate `dP` with the given inputs and return them as a list | [
"r",
"This",
"function",
"handles",
"choosing",
"which",
"pressure",
"drop",
"in",
"a",
"packed",
"bed",
"correlation",
"is",
"used",
".",
"Automatically",
"select",
"which",
"correlation",
"to",
"use",
"if",
"none",
"is",
"provided",
".",
"Returns",
"None",
"if",
"insufficient",
"information",
"is",
"provided",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/packed_bed.py#L994-L1079 | train |
CalebBell/fluids | fluids/two_phase.py | Friedel | def Friedel(m, x, rhol, rhog, mul, mug, sigma, D, roughness=0, L=1):
r'''Calculates two-phase pressure drop with the Friedel correlation.
.. math::
\Delta P_{friction} = \Delta P_{lo} \phi_{lo}^2
.. math::
\phi_{lo}^2 = E + \frac{3.24FH}{Fr^{0.0454} We^{0.035}}
.. math::
H = \left(\frac{\rho_l}{\rho_g}\right)^{0.91}\left(\frac{\mu_g}{\mu_l}
\right)^{0.19}\left(1 - \frac{\mu_g}{\mu_l}\right)^{0.7}
.. math::
F = x^{0.78}(1 - x)^{0.224}
.. math::
E = (1-x)^2 + x^2\left(\frac{\rho_l f_{d,go}}{\rho_g f_{d,lo}}\right)
.. math::
Fr = \frac{G_{tp}^2}{gD\rho_H^2}
.. math::
We = \frac{G_{tp}^2 D}{\sigma \rho_H}
.. math::
\rho_H = \left(\frac{x}{\rho_g} + \frac{1-x}{\rho_l}\right)^{-1}
Parameters
----------
m : float
Mass flow rate of fluid, [kg/s]
x : float
Quality of fluid, [-]
rhol : float
Liquid density, [kg/m^3]
rhog : float
Gas density, [kg/m^3]
mul : float
Viscosity of liquid, [Pa*s]
mug : float
Viscosity of gas, [Pa*s]
sigma : float
Surface tension, [N/m]
D : float
Diameter of pipe, [m]
roughness : float, optional
Roughness of pipe for use in calculating friction factor, [m]
L : float, optional
Length of pipe, [m]
Returns
-------
dP : float
Pressure drop of the two-phase flow, [Pa]
Notes
-----
Applicable to vertical upflow and horizontal flow. Known to work poorly
when mul/mug > 1000. Gives mean errors on the order of 40%. Tested on data
with diameters as small as 4 mm.
The power of 0.0454 is given as 0.045 in [2]_, [3]_, [4]_, and [5]_; [6]_
and [2]_ give 0.0454 and [2]_ also gives a similar correlation said to be
presented in [1]_, so it is believed this 0.0454 was the original power.
[6]_ also gives an expression for friction factor claimed to be presented
in [1]_; it is not used here.
Examples
--------
Example 4 in [6]_:
>>> Friedel(m=0.6, x=0.1, rhol=915., rhog=2.67, mul=180E-6, mug=14E-6,
... sigma=0.0487, D=0.05, roughness=0, L=1)
738.6500525002245
References
----------
.. [1] Friedel, L. "Improved Friction Pressure Drop Correlations for
Horizontal and Vertical Two-Phase Pipe Flow." , in: Proceedings,
European Two Phase Flow Group Meeting, Ispra, Italy, 1979: 485-481.
.. [2] Whalley, P. B. Boiling, Condensation, and Gas-Liquid Flow. Oxford:
Oxford University Press, 1987.
.. [3] Triplett, K. A., S. M. Ghiaasiaan, S. I. Abdel-Khalik, A. LeMouel,
and B. N. McCord. "Gas-liquid Two-Phase Flow in Microchannels: Part II:
Void Fraction and Pressure Drop.” International Journal of Multiphase
Flow 25, no. 3 (April 1999): 395-410. doi:10.1016/S0301-9322(98)00055-X.
.. [4] Mekisso, Henock Mateos. "Comparison of Frictional Pressure Drop
Correlations for Isothermal Two-Phase Horizontal Flow." Thesis, Oklahoma
State University, 2013. https://shareok.org/handle/11244/11109.
.. [5] Thome, John R. "Engineering Data Book III." Wolverine Tube Inc
(2004). http://www.wlv.com/heat-transfer-databook/
.. [6] Ghiaasiaan, S. Mostafa. Two-Phase Flow, Boiling, and Condensation:
In Conventional and Miniature Systems. Cambridge University Press, 2007.
'''
# Liquid-only properties, for calculation of E, dP_lo
v_lo = m/rhol/(pi/4*D**2)
Re_lo = Reynolds(V=v_lo, rho=rhol, mu=mul, D=D)
fd_lo = friction_factor(Re=Re_lo, eD=roughness/D)
dP_lo = fd_lo*L/D*(0.5*rhol*v_lo**2)
# Gas-only properties, for calculation of E
v_go = m/rhog/(pi/4*D**2)
Re_go = Reynolds(V=v_go, rho=rhog, mu=mug, D=D)
fd_go = friction_factor(Re=Re_go, eD=roughness/D)
F = x**0.78*(1-x)**0.224
H = (rhol/rhog)**0.91*(mug/mul)**0.19*(1 - mug/mul)**0.7
E = (1-x)**2 + x**2*(rhol*fd_go/(rhog*fd_lo))
# Homogeneous properties, for Froude/Weber numbers
voidage_h = homogeneous(x, rhol, rhog)
rho_h = rhol*(1-voidage_h) + rhog*voidage_h
Q_h = m/rho_h
v_h = Q_h/(pi/4*D**2)
Fr = Froude(V=v_h, L=D, squared=True) # checked with (m/(pi/4*D**2))**2/g/D/rho_h**2
We = Weber(V=v_h, L=D, rho=rho_h, sigma=sigma) # checked with (m/(pi/4*D**2))**2*D/sigma/rho_h
phi_lo2 = E + 3.24*F*H/(Fr**0.0454*We**0.035)
return phi_lo2*dP_lo | python | def Friedel(m, x, rhol, rhog, mul, mug, sigma, D, roughness=0, L=1):
r'''Calculates two-phase pressure drop with the Friedel correlation.
.. math::
\Delta P_{friction} = \Delta P_{lo} \phi_{lo}^2
.. math::
\phi_{lo}^2 = E + \frac{3.24FH}{Fr^{0.0454} We^{0.035}}
.. math::
H = \left(\frac{\rho_l}{\rho_g}\right)^{0.91}\left(\frac{\mu_g}{\mu_l}
\right)^{0.19}\left(1 - \frac{\mu_g}{\mu_l}\right)^{0.7}
.. math::
F = x^{0.78}(1 - x)^{0.224}
.. math::
E = (1-x)^2 + x^2\left(\frac{\rho_l f_{d,go}}{\rho_g f_{d,lo}}\right)
.. math::
Fr = \frac{G_{tp}^2}{gD\rho_H^2}
.. math::
We = \frac{G_{tp}^2 D}{\sigma \rho_H}
.. math::
\rho_H = \left(\frac{x}{\rho_g} + \frac{1-x}{\rho_l}\right)^{-1}
Parameters
----------
m : float
Mass flow rate of fluid, [kg/s]
x : float
Quality of fluid, [-]
rhol : float
Liquid density, [kg/m^3]
rhog : float
Gas density, [kg/m^3]
mul : float
Viscosity of liquid, [Pa*s]
mug : float
Viscosity of gas, [Pa*s]
sigma : float
Surface tension, [N/m]
D : float
Diameter of pipe, [m]
roughness : float, optional
Roughness of pipe for use in calculating friction factor, [m]
L : float, optional
Length of pipe, [m]
Returns
-------
dP : float
Pressure drop of the two-phase flow, [Pa]
Notes
-----
Applicable to vertical upflow and horizontal flow. Known to work poorly
when mul/mug > 1000. Gives mean errors on the order of 40%. Tested on data
with diameters as small as 4 mm.
The power of 0.0454 is given as 0.045 in [2]_, [3]_, [4]_, and [5]_; [6]_
and [2]_ give 0.0454 and [2]_ also gives a similar correlation said to be
presented in [1]_, so it is believed this 0.0454 was the original power.
[6]_ also gives an expression for friction factor claimed to be presented
in [1]_; it is not used here.
Examples
--------
Example 4 in [6]_:
>>> Friedel(m=0.6, x=0.1, rhol=915., rhog=2.67, mul=180E-6, mug=14E-6,
... sigma=0.0487, D=0.05, roughness=0, L=1)
738.6500525002245
References
----------
.. [1] Friedel, L. "Improved Friction Pressure Drop Correlations for
Horizontal and Vertical Two-Phase Pipe Flow." , in: Proceedings,
European Two Phase Flow Group Meeting, Ispra, Italy, 1979: 485-481.
.. [2] Whalley, P. B. Boiling, Condensation, and Gas-Liquid Flow. Oxford:
Oxford University Press, 1987.
.. [3] Triplett, K. A., S. M. Ghiaasiaan, S. I. Abdel-Khalik, A. LeMouel,
and B. N. McCord. "Gas-liquid Two-Phase Flow in Microchannels: Part II:
Void Fraction and Pressure Drop.” International Journal of Multiphase
Flow 25, no. 3 (April 1999): 395-410. doi:10.1016/S0301-9322(98)00055-X.
.. [4] Mekisso, Henock Mateos. "Comparison of Frictional Pressure Drop
Correlations for Isothermal Two-Phase Horizontal Flow." Thesis, Oklahoma
State University, 2013. https://shareok.org/handle/11244/11109.
.. [5] Thome, John R. "Engineering Data Book III." Wolverine Tube Inc
(2004). http://www.wlv.com/heat-transfer-databook/
.. [6] Ghiaasiaan, S. Mostafa. Two-Phase Flow, Boiling, and Condensation:
In Conventional and Miniature Systems. Cambridge University Press, 2007.
'''
# Liquid-only properties, for calculation of E, dP_lo
v_lo = m/rhol/(pi/4*D**2)
Re_lo = Reynolds(V=v_lo, rho=rhol, mu=mul, D=D)
fd_lo = friction_factor(Re=Re_lo, eD=roughness/D)
dP_lo = fd_lo*L/D*(0.5*rhol*v_lo**2)
# Gas-only properties, for calculation of E
v_go = m/rhog/(pi/4*D**2)
Re_go = Reynolds(V=v_go, rho=rhog, mu=mug, D=D)
fd_go = friction_factor(Re=Re_go, eD=roughness/D)
F = x**0.78*(1-x)**0.224
H = (rhol/rhog)**0.91*(mug/mul)**0.19*(1 - mug/mul)**0.7
E = (1-x)**2 + x**2*(rhol*fd_go/(rhog*fd_lo))
# Homogeneous properties, for Froude/Weber numbers
voidage_h = homogeneous(x, rhol, rhog)
rho_h = rhol*(1-voidage_h) + rhog*voidage_h
Q_h = m/rho_h
v_h = Q_h/(pi/4*D**2)
Fr = Froude(V=v_h, L=D, squared=True) # checked with (m/(pi/4*D**2))**2/g/D/rho_h**2
We = Weber(V=v_h, L=D, rho=rho_h, sigma=sigma) # checked with (m/(pi/4*D**2))**2*D/sigma/rho_h
phi_lo2 = E + 3.24*F*H/(Fr**0.0454*We**0.035)
return phi_lo2*dP_lo | [
"def",
"Friedel",
"(",
"m",
",",
"x",
",",
"rhol",
",",
"rhog",
",",
"mul",
",",
"mug",
",",
"sigma",
",",
"D",
",",
"roughness",
"=",
"0",
",",
"L",
"=",
"1",
")",
":",
"# Liquid-only properties, for calculation of E, dP_lo",
"v_lo",
"=",
"m",
"/",
"rhol",
"/",
"(",
"pi",
"/",
"4",
"*",
"D",
"**",
"2",
")",
"Re_lo",
"=",
"Reynolds",
"(",
"V",
"=",
"v_lo",
",",
"rho",
"=",
"rhol",
",",
"mu",
"=",
"mul",
",",
"D",
"=",
"D",
")",
"fd_lo",
"=",
"friction_factor",
"(",
"Re",
"=",
"Re_lo",
",",
"eD",
"=",
"roughness",
"/",
"D",
")",
"dP_lo",
"=",
"fd_lo",
"*",
"L",
"/",
"D",
"*",
"(",
"0.5",
"*",
"rhol",
"*",
"v_lo",
"**",
"2",
")",
"# Gas-only properties, for calculation of E",
"v_go",
"=",
"m",
"/",
"rhog",
"/",
"(",
"pi",
"/",
"4",
"*",
"D",
"**",
"2",
")",
"Re_go",
"=",
"Reynolds",
"(",
"V",
"=",
"v_go",
",",
"rho",
"=",
"rhog",
",",
"mu",
"=",
"mug",
",",
"D",
"=",
"D",
")",
"fd_go",
"=",
"friction_factor",
"(",
"Re",
"=",
"Re_go",
",",
"eD",
"=",
"roughness",
"/",
"D",
")",
"F",
"=",
"x",
"**",
"0.78",
"*",
"(",
"1",
"-",
"x",
")",
"**",
"0.224",
"H",
"=",
"(",
"rhol",
"/",
"rhog",
")",
"**",
"0.91",
"*",
"(",
"mug",
"/",
"mul",
")",
"**",
"0.19",
"*",
"(",
"1",
"-",
"mug",
"/",
"mul",
")",
"**",
"0.7",
"E",
"=",
"(",
"1",
"-",
"x",
")",
"**",
"2",
"+",
"x",
"**",
"2",
"*",
"(",
"rhol",
"*",
"fd_go",
"/",
"(",
"rhog",
"*",
"fd_lo",
")",
")",
"# Homogeneous properties, for Froude/Weber numbers",
"voidage_h",
"=",
"homogeneous",
"(",
"x",
",",
"rhol",
",",
"rhog",
")",
"rho_h",
"=",
"rhol",
"*",
"(",
"1",
"-",
"voidage_h",
")",
"+",
"rhog",
"*",
"voidage_h",
"Q_h",
"=",
"m",
"/",
"rho_h",
"v_h",
"=",
"Q_h",
"/",
"(",
"pi",
"/",
"4",
"*",
"D",
"**",
"2",
")",
"Fr",
"=",
"Froude",
"(",
"V",
"=",
"v_h",
",",
"L",
"=",
"D",
",",
"squared",
"=",
"True",
")",
"# checked with (m/(pi/4*D**2))**2/g/D/rho_h**2",
"We",
"=",
"Weber",
"(",
"V",
"=",
"v_h",
",",
"L",
"=",
"D",
",",
"rho",
"=",
"rho_h",
",",
"sigma",
"=",
"sigma",
")",
"# checked with (m/(pi/4*D**2))**2*D/sigma/rho_h",
"phi_lo2",
"=",
"E",
"+",
"3.24",
"*",
"F",
"*",
"H",
"/",
"(",
"Fr",
"**",
"0.0454",
"*",
"We",
"**",
"0.035",
")",
"return",
"phi_lo2",
"*",
"dP_lo"
]
| r'''Calculates two-phase pressure drop with the Friedel correlation.
.. math::
\Delta P_{friction} = \Delta P_{lo} \phi_{lo}^2
.. math::
\phi_{lo}^2 = E + \frac{3.24FH}{Fr^{0.0454} We^{0.035}}
.. math::
H = \left(\frac{\rho_l}{\rho_g}\right)^{0.91}\left(\frac{\mu_g}{\mu_l}
\right)^{0.19}\left(1 - \frac{\mu_g}{\mu_l}\right)^{0.7}
.. math::
F = x^{0.78}(1 - x)^{0.224}
.. math::
E = (1-x)^2 + x^2\left(\frac{\rho_l f_{d,go}}{\rho_g f_{d,lo}}\right)
.. math::
Fr = \frac{G_{tp}^2}{gD\rho_H^2}
.. math::
We = \frac{G_{tp}^2 D}{\sigma \rho_H}
.. math::
\rho_H = \left(\frac{x}{\rho_g} + \frac{1-x}{\rho_l}\right)^{-1}
Parameters
----------
m : float
Mass flow rate of fluid, [kg/s]
x : float
Quality of fluid, [-]
rhol : float
Liquid density, [kg/m^3]
rhog : float
Gas density, [kg/m^3]
mul : float
Viscosity of liquid, [Pa*s]
mug : float
Viscosity of gas, [Pa*s]
sigma : float
Surface tension, [N/m]
D : float
Diameter of pipe, [m]
roughness : float, optional
Roughness of pipe for use in calculating friction factor, [m]
L : float, optional
Length of pipe, [m]
Returns
-------
dP : float
Pressure drop of the two-phase flow, [Pa]
Notes
-----
Applicable to vertical upflow and horizontal flow. Known to work poorly
when mul/mug > 1000. Gives mean errors on the order of 40%. Tested on data
with diameters as small as 4 mm.
The power of 0.0454 is given as 0.045 in [2]_, [3]_, [4]_, and [5]_; [6]_
and [2]_ give 0.0454 and [2]_ also gives a similar correlation said to be
presented in [1]_, so it is believed this 0.0454 was the original power.
[6]_ also gives an expression for friction factor claimed to be presented
in [1]_; it is not used here.
Examples
--------
Example 4 in [6]_:
>>> Friedel(m=0.6, x=0.1, rhol=915., rhog=2.67, mul=180E-6, mug=14E-6,
... sigma=0.0487, D=0.05, roughness=0, L=1)
738.6500525002245
References
----------
.. [1] Friedel, L. "Improved Friction Pressure Drop Correlations for
Horizontal and Vertical Two-Phase Pipe Flow." , in: Proceedings,
European Two Phase Flow Group Meeting, Ispra, Italy, 1979: 485-481.
.. [2] Whalley, P. B. Boiling, Condensation, and Gas-Liquid Flow. Oxford:
Oxford University Press, 1987.
.. [3] Triplett, K. A., S. M. Ghiaasiaan, S. I. Abdel-Khalik, A. LeMouel,
and B. N. McCord. "Gas-liquid Two-Phase Flow in Microchannels: Part II:
Void Fraction and Pressure Drop.” International Journal of Multiphase
Flow 25, no. 3 (April 1999): 395-410. doi:10.1016/S0301-9322(98)00055-X.
.. [4] Mekisso, Henock Mateos. "Comparison of Frictional Pressure Drop
Correlations for Isothermal Two-Phase Horizontal Flow." Thesis, Oklahoma
State University, 2013. https://shareok.org/handle/11244/11109.
.. [5] Thome, John R. "Engineering Data Book III." Wolverine Tube Inc
(2004). http://www.wlv.com/heat-transfer-databook/
.. [6] Ghiaasiaan, S. Mostafa. Two-Phase Flow, Boiling, and Condensation:
In Conventional and Miniature Systems. Cambridge University Press, 2007. | [
"r",
"Calculates",
"two",
"-",
"phase",
"pressure",
"drop",
"with",
"the",
"Friedel",
"correlation",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/two_phase.py#L204-L324 | train |
CalebBell/fluids | fluids/atmosphere.py | airmass | def airmass(func, angle, H_max=86400.0, R_planet=6.371229E6, RI=1.000276):
r'''Calculates mass of air per square meter in the atmosphere using a
provided atmospheric model. The lowest air mass is calculated straight up;
as the angle is lowered to nearer and nearer the horizon, the air mass
increases, and can approach 40x or more the minimum airmass.
.. math::
m(\gamma) = \int_0^\infty \rho \left\{1 - \left[1 + 2(\text{RI}-1)
(1-\rho/\rho_0)\right]
\left[\frac{\cos \gamma}{(1+h/R)}\right]^2\right\}^{-1/2} dH
Parameters
----------
func : float
Function which returns the density of the atmosphere as a function of
elevation
angle : float
Degrees above the horizon (90 = straight up), [degrees]
H_max : float, optional
Maximum height to compute the integration up to before the contribution
of density becomes negligible, [m]
R_planet : float, optional
The radius of the planet for which the integration is being performed,
[m]
RI : float, optional
The refractive index of the atmosphere (air on earth at 0.7 um as
default) assumed a constant, [-]
Returns
-------
m : float
Mass of air per square meter in the atmosphere, [kg/m^2]
Notes
-----
Numerical integration via SciPy's `quad` is used to perform the
calculation.
Examples
--------
>>> airmass(lambda Z : ATMOSPHERE_1976(Z).rho, 90)
10356.127665863998
References
----------
.. [1] Kasten, Fritz, and Andrew T. Young. "Revised Optical Air Mass Tables
and Approximation Formula." Applied Optics 28, no. 22 (November 15,
1989): 4735-38. https://doi.org/10.1364/AO.28.004735.
'''
delta0 = RI - 1.0
rho0 = func(0.0)
angle_term = cos(radians(angle))
def to_int(Z):
rho = func(Z)
t1 = (1.0 + 2.0*delta0*(1.0 - rho/rho0))
t2 = (angle_term/(1.0 + Z/R_planet))**2
t3 = (1.0 - t1*t2)**-0.5
return rho*t3
from scipy.integrate import quad
return float(quad(to_int, 0, 86400.0)[0]) | python | def airmass(func, angle, H_max=86400.0, R_planet=6.371229E6, RI=1.000276):
r'''Calculates mass of air per square meter in the atmosphere using a
provided atmospheric model. The lowest air mass is calculated straight up;
as the angle is lowered to nearer and nearer the horizon, the air mass
increases, and can approach 40x or more the minimum airmass.
.. math::
m(\gamma) = \int_0^\infty \rho \left\{1 - \left[1 + 2(\text{RI}-1)
(1-\rho/\rho_0)\right]
\left[\frac{\cos \gamma}{(1+h/R)}\right]^2\right\}^{-1/2} dH
Parameters
----------
func : float
Function which returns the density of the atmosphere as a function of
elevation
angle : float
Degrees above the horizon (90 = straight up), [degrees]
H_max : float, optional
Maximum height to compute the integration up to before the contribution
of density becomes negligible, [m]
R_planet : float, optional
The radius of the planet for which the integration is being performed,
[m]
RI : float, optional
The refractive index of the atmosphere (air on earth at 0.7 um as
default) assumed a constant, [-]
Returns
-------
m : float
Mass of air per square meter in the atmosphere, [kg/m^2]
Notes
-----
Numerical integration via SciPy's `quad` is used to perform the
calculation.
Examples
--------
>>> airmass(lambda Z : ATMOSPHERE_1976(Z).rho, 90)
10356.127665863998
References
----------
.. [1] Kasten, Fritz, and Andrew T. Young. "Revised Optical Air Mass Tables
and Approximation Formula." Applied Optics 28, no. 22 (November 15,
1989): 4735-38. https://doi.org/10.1364/AO.28.004735.
'''
delta0 = RI - 1.0
rho0 = func(0.0)
angle_term = cos(radians(angle))
def to_int(Z):
rho = func(Z)
t1 = (1.0 + 2.0*delta0*(1.0 - rho/rho0))
t2 = (angle_term/(1.0 + Z/R_planet))**2
t3 = (1.0 - t1*t2)**-0.5
return rho*t3
from scipy.integrate import quad
return float(quad(to_int, 0, 86400.0)[0]) | [
"def",
"airmass",
"(",
"func",
",",
"angle",
",",
"H_max",
"=",
"86400.0",
",",
"R_planet",
"=",
"6.371229E6",
",",
"RI",
"=",
"1.000276",
")",
":",
"delta0",
"=",
"RI",
"-",
"1.0",
"rho0",
"=",
"func",
"(",
"0.0",
")",
"angle_term",
"=",
"cos",
"(",
"radians",
"(",
"angle",
")",
")",
"def",
"to_int",
"(",
"Z",
")",
":",
"rho",
"=",
"func",
"(",
"Z",
")",
"t1",
"=",
"(",
"1.0",
"+",
"2.0",
"*",
"delta0",
"*",
"(",
"1.0",
"-",
"rho",
"/",
"rho0",
")",
")",
"t2",
"=",
"(",
"angle_term",
"/",
"(",
"1.0",
"+",
"Z",
"/",
"R_planet",
")",
")",
"**",
"2",
"t3",
"=",
"(",
"1.0",
"-",
"t1",
"*",
"t2",
")",
"**",
"-",
"0.5",
"return",
"rho",
"*",
"t3",
"from",
"scipy",
".",
"integrate",
"import",
"quad",
"return",
"float",
"(",
"quad",
"(",
"to_int",
",",
"0",
",",
"86400.0",
")",
"[",
"0",
"]",
")"
]
| r'''Calculates mass of air per square meter in the atmosphere using a
provided atmospheric model. The lowest air mass is calculated straight up;
as the angle is lowered to nearer and nearer the horizon, the air mass
increases, and can approach 40x or more the minimum airmass.
.. math::
m(\gamma) = \int_0^\infty \rho \left\{1 - \left[1 + 2(\text{RI}-1)
(1-\rho/\rho_0)\right]
\left[\frac{\cos \gamma}{(1+h/R)}\right]^2\right\}^{-1/2} dH
Parameters
----------
func : float
Function which returns the density of the atmosphere as a function of
elevation
angle : float
Degrees above the horizon (90 = straight up), [degrees]
H_max : float, optional
Maximum height to compute the integration up to before the contribution
of density becomes negligible, [m]
R_planet : float, optional
The radius of the planet for which the integration is being performed,
[m]
RI : float, optional
The refractive index of the atmosphere (air on earth at 0.7 um as
default) assumed a constant, [-]
Returns
-------
m : float
Mass of air per square meter in the atmosphere, [kg/m^2]
Notes
-----
Numerical integration via SciPy's `quad` is used to perform the
calculation.
Examples
--------
>>> airmass(lambda Z : ATMOSPHERE_1976(Z).rho, 90)
10356.127665863998
References
----------
.. [1] Kasten, Fritz, and Andrew T. Young. "Revised Optical Air Mass Tables
and Approximation Formula." Applied Optics 28, no. 22 (November 15,
1989): 4735-38. https://doi.org/10.1364/AO.28.004735. | [
"r",
"Calculates",
"mass",
"of",
"air",
"per",
"square",
"meter",
"in",
"the",
"atmosphere",
"using",
"a",
"provided",
"atmospheric",
"model",
".",
"The",
"lowest",
"air",
"mass",
"is",
"calculated",
"straight",
"up",
";",
"as",
"the",
"angle",
"is",
"lowered",
"to",
"nearer",
"and",
"nearer",
"the",
"horizon",
"the",
"air",
"mass",
"increases",
"and",
"can",
"approach",
"40x",
"or",
"more",
"the",
"minimum",
"airmass",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/atmosphere.py#L689-L750 | train |
CalebBell/fluids | fluids/atmosphere.py | ATMOSPHERE_1976._get_ind_from_H | def _get_ind_from_H(H):
r'''Method defined in the US Standard Atmosphere 1976 for determining
the index of the layer a specified elevation is above. Levels are
0, 11E3, 20E3, 32E3, 47E3, 51E3, 71E3, 84852 meters respectively.
'''
if H <= 0:
return 0
for ind, Hi in enumerate(H_std):
if Hi >= H :
return ind-1
return 7 | python | def _get_ind_from_H(H):
r'''Method defined in the US Standard Atmosphere 1976 for determining
the index of the layer a specified elevation is above. Levels are
0, 11E3, 20E3, 32E3, 47E3, 51E3, 71E3, 84852 meters respectively.
'''
if H <= 0:
return 0
for ind, Hi in enumerate(H_std):
if Hi >= H :
return ind-1
return 7 | [
"def",
"_get_ind_from_H",
"(",
"H",
")",
":",
"if",
"H",
"<=",
"0",
":",
"return",
"0",
"for",
"ind",
",",
"Hi",
"in",
"enumerate",
"(",
"H_std",
")",
":",
"if",
"Hi",
">=",
"H",
":",
"return",
"ind",
"-",
"1",
"return",
"7"
]
| r'''Method defined in the US Standard Atmosphere 1976 for determining
the index of the layer a specified elevation is above. Levels are
0, 11E3, 20E3, 32E3, 47E3, 51E3, 71E3, 84852 meters respectively. | [
"r",
"Method",
"defined",
"in",
"the",
"US",
"Standard",
"Atmosphere",
"1976",
"for",
"determining",
"the",
"index",
"of",
"the",
"layer",
"a",
"specified",
"elevation",
"is",
"above",
".",
"Levels",
"are",
"0",
"11E3",
"20E3",
"32E3",
"47E3",
"51E3",
"71E3",
"84852",
"meters",
"respectively",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/atmosphere.py#L154-L164 | train |
CalebBell/fluids | fluids/piping.py | gauge_from_t | def gauge_from_t(t, SI=True, schedule='BWG'):
r'''Looks up the gauge of a given wire thickness of given schedule.
Values are all non-linear, and tabulated internally.
Parameters
----------
t : float
Thickness, [m]
SI : bool, optional
If False, requires that the thickness is given in inches not meters
schedule : str
Gauge schedule, one of 'BWG', 'AWG', 'SWG', 'MWG', 'BSWG', or 'SSWG'
Returns
-------
gauge : float-like
Wire Gauge, [-]
Notes
-----
An internal variable, tol, is used in the selection of the wire gauge. If
the next smaller wire gauge is within 10% of the difference between it and
the previous wire gauge, the smaller wire gauge is selected. Accordingly,
this function can return a gauge with a thickness smaller than desired
in some circumstances.
* Birmingham Wire Gauge (BWG) ranges from 0.2 (0.5 inch) to 36 (0.004 inch).
* American Wire Gauge (AWG) ranges from 0.167 (0.58 inch) to 51 (0.00099
inch). These are used for electrical wires.
* Steel Wire Gauge (SWG) ranges from 0.143 (0.49 inch) to 51 (0.0044 inch).
Also called Washburn & Moen wire gauge, American Steel gauge, Wire Co.
gauge, and Roebling wire gauge.
* Music Wire Gauge (MWG) ranges from 0.167 (0.004 inch) to 46 (0.18
inch). Also called Piano Wire Gauge.
* British Standard Wire Gage (BSWG) ranges from 0.143 (0.5 inch) to
51 (0.001 inch). Also called Imperial Wire Gage (IWG).
* Stub's Steel Wire Gage (SSWG) ranges from 1 (0.227 inch) to 80 (0.013 inch)
Examples
--------
>>> gauge_from_t(.5, SI=False, schedule='BWG')
0.2
References
----------
.. [1] Oberg, Erik, Franklin D. Jones, and Henry H. Ryffel. Machinery's
Handbook. Industrial Press, Incorporated, 2012.
'''
tol = 0.1
# Handle units
if SI:
t_inch = round(t/inch, 9) # all schedules are in inches
else:
t_inch = t
# Get the schedule
try:
sch_integers, sch_inch, sch_SI, decreasing = wire_schedules[schedule]
except:
raise ValueError('Wire gauge schedule not found')
# Check if outside limits
sch_max, sch_min = sch_inch[0], sch_inch[-1]
if t_inch > sch_max:
raise ValueError('Input thickness is above the largest in the selected schedule')
# If given thickness is exactly in the index, be happy
if t_inch in sch_inch:
gauge = sch_integers[sch_inch.index(t_inch)]
else:
for i in range(len(sch_inch)):
if sch_inch[i] >= t_inch:
larger = sch_inch[i]
else:
break
if larger == sch_min:
gauge = sch_min # If t is under the lowest schedule, be happy
else:
smaller = sch_inch[i]
if (t_inch - smaller) <= tol*(larger - smaller):
gauge = sch_integers[i]
else:
gauge = sch_integers[i-1]
return gauge | python | def gauge_from_t(t, SI=True, schedule='BWG'):
r'''Looks up the gauge of a given wire thickness of given schedule.
Values are all non-linear, and tabulated internally.
Parameters
----------
t : float
Thickness, [m]
SI : bool, optional
If False, requires that the thickness is given in inches not meters
schedule : str
Gauge schedule, one of 'BWG', 'AWG', 'SWG', 'MWG', 'BSWG', or 'SSWG'
Returns
-------
gauge : float-like
Wire Gauge, [-]
Notes
-----
An internal variable, tol, is used in the selection of the wire gauge. If
the next smaller wire gauge is within 10% of the difference between it and
the previous wire gauge, the smaller wire gauge is selected. Accordingly,
this function can return a gauge with a thickness smaller than desired
in some circumstances.
* Birmingham Wire Gauge (BWG) ranges from 0.2 (0.5 inch) to 36 (0.004 inch).
* American Wire Gauge (AWG) ranges from 0.167 (0.58 inch) to 51 (0.00099
inch). These are used for electrical wires.
* Steel Wire Gauge (SWG) ranges from 0.143 (0.49 inch) to 51 (0.0044 inch).
Also called Washburn & Moen wire gauge, American Steel gauge, Wire Co.
gauge, and Roebling wire gauge.
* Music Wire Gauge (MWG) ranges from 0.167 (0.004 inch) to 46 (0.18
inch). Also called Piano Wire Gauge.
* British Standard Wire Gage (BSWG) ranges from 0.143 (0.5 inch) to
51 (0.001 inch). Also called Imperial Wire Gage (IWG).
* Stub's Steel Wire Gage (SSWG) ranges from 1 (0.227 inch) to 80 (0.013 inch)
Examples
--------
>>> gauge_from_t(.5, SI=False, schedule='BWG')
0.2
References
----------
.. [1] Oberg, Erik, Franklin D. Jones, and Henry H. Ryffel. Machinery's
Handbook. Industrial Press, Incorporated, 2012.
'''
tol = 0.1
# Handle units
if SI:
t_inch = round(t/inch, 9) # all schedules are in inches
else:
t_inch = t
# Get the schedule
try:
sch_integers, sch_inch, sch_SI, decreasing = wire_schedules[schedule]
except:
raise ValueError('Wire gauge schedule not found')
# Check if outside limits
sch_max, sch_min = sch_inch[0], sch_inch[-1]
if t_inch > sch_max:
raise ValueError('Input thickness is above the largest in the selected schedule')
# If given thickness is exactly in the index, be happy
if t_inch in sch_inch:
gauge = sch_integers[sch_inch.index(t_inch)]
else:
for i in range(len(sch_inch)):
if sch_inch[i] >= t_inch:
larger = sch_inch[i]
else:
break
if larger == sch_min:
gauge = sch_min # If t is under the lowest schedule, be happy
else:
smaller = sch_inch[i]
if (t_inch - smaller) <= tol*(larger - smaller):
gauge = sch_integers[i]
else:
gauge = sch_integers[i-1]
return gauge | [
"def",
"gauge_from_t",
"(",
"t",
",",
"SI",
"=",
"True",
",",
"schedule",
"=",
"'BWG'",
")",
":",
"tol",
"=",
"0.1",
"# Handle units",
"if",
"SI",
":",
"t_inch",
"=",
"round",
"(",
"t",
"/",
"inch",
",",
"9",
")",
"# all schedules are in inches",
"else",
":",
"t_inch",
"=",
"t",
"# Get the schedule",
"try",
":",
"sch_integers",
",",
"sch_inch",
",",
"sch_SI",
",",
"decreasing",
"=",
"wire_schedules",
"[",
"schedule",
"]",
"except",
":",
"raise",
"ValueError",
"(",
"'Wire gauge schedule not found'",
")",
"# Check if outside limits",
"sch_max",
",",
"sch_min",
"=",
"sch_inch",
"[",
"0",
"]",
",",
"sch_inch",
"[",
"-",
"1",
"]",
"if",
"t_inch",
">",
"sch_max",
":",
"raise",
"ValueError",
"(",
"'Input thickness is above the largest in the selected schedule'",
")",
"# If given thickness is exactly in the index, be happy",
"if",
"t_inch",
"in",
"sch_inch",
":",
"gauge",
"=",
"sch_integers",
"[",
"sch_inch",
".",
"index",
"(",
"t_inch",
")",
"]",
"else",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"sch_inch",
")",
")",
":",
"if",
"sch_inch",
"[",
"i",
"]",
">=",
"t_inch",
":",
"larger",
"=",
"sch_inch",
"[",
"i",
"]",
"else",
":",
"break",
"if",
"larger",
"==",
"sch_min",
":",
"gauge",
"=",
"sch_min",
"# If t is under the lowest schedule, be happy",
"else",
":",
"smaller",
"=",
"sch_inch",
"[",
"i",
"]",
"if",
"(",
"t_inch",
"-",
"smaller",
")",
"<=",
"tol",
"*",
"(",
"larger",
"-",
"smaller",
")",
":",
"gauge",
"=",
"sch_integers",
"[",
"i",
"]",
"else",
":",
"gauge",
"=",
"sch_integers",
"[",
"i",
"-",
"1",
"]",
"return",
"gauge"
]
| r'''Looks up the gauge of a given wire thickness of given schedule.
Values are all non-linear, and tabulated internally.
Parameters
----------
t : float
Thickness, [m]
SI : bool, optional
If False, requires that the thickness is given in inches not meters
schedule : str
Gauge schedule, one of 'BWG', 'AWG', 'SWG', 'MWG', 'BSWG', or 'SSWG'
Returns
-------
gauge : float-like
Wire Gauge, [-]
Notes
-----
An internal variable, tol, is used in the selection of the wire gauge. If
the next smaller wire gauge is within 10% of the difference between it and
the previous wire gauge, the smaller wire gauge is selected. Accordingly,
this function can return a gauge with a thickness smaller than desired
in some circumstances.
* Birmingham Wire Gauge (BWG) ranges from 0.2 (0.5 inch) to 36 (0.004 inch).
* American Wire Gauge (AWG) ranges from 0.167 (0.58 inch) to 51 (0.00099
inch). These are used for electrical wires.
* Steel Wire Gauge (SWG) ranges from 0.143 (0.49 inch) to 51 (0.0044 inch).
Also called Washburn & Moen wire gauge, American Steel gauge, Wire Co.
gauge, and Roebling wire gauge.
* Music Wire Gauge (MWG) ranges from 0.167 (0.004 inch) to 46 (0.18
inch). Also called Piano Wire Gauge.
* British Standard Wire Gage (BSWG) ranges from 0.143 (0.5 inch) to
51 (0.001 inch). Also called Imperial Wire Gage (IWG).
* Stub's Steel Wire Gage (SSWG) ranges from 1 (0.227 inch) to 80 (0.013 inch)
Examples
--------
>>> gauge_from_t(.5, SI=False, schedule='BWG')
0.2
References
----------
.. [1] Oberg, Erik, Franklin D. Jones, and Henry H. Ryffel. Machinery's
Handbook. Industrial Press, Incorporated, 2012. | [
"r",
"Looks",
"up",
"the",
"gauge",
"of",
"a",
"given",
"wire",
"thickness",
"of",
"given",
"schedule",
".",
"Values",
"are",
"all",
"non",
"-",
"linear",
"and",
"tabulated",
"internally",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/piping.py#L349-L434 | train |
CalebBell/fluids | fluids/piping.py | t_from_gauge | def t_from_gauge(gauge, SI=True, schedule='BWG'):
r'''Looks up the thickness of a given wire gauge of given schedule.
Values are all non-linear, and tabulated internally.
Parameters
----------
gauge : float-like
Wire Gauge, []
SI : bool, optional
If False, will return a thickness in inches not meters
schedule : str
Gauge schedule, one of 'BWG', 'AWG', 'SWG', 'MWG', 'BSWG', or 'SSWG'
Returns
-------
t : float
Thickness, [m]
Notes
-----
* Birmingham Wire Gauge (BWG) ranges from 0.2 (0.5 inch) to 36 (0.004 inch).
* American Wire Gauge (AWG) ranges from 0.167 (0.58 inch) to 51 (0.00099
inch). These are used for electrical wires.
* Steel Wire Gauge (SWG) ranges from 0.143 (0.49 inch) to 51 (0.0044 inch).
Also called Washburn & Moen wire gauge, American Steel gauge, Wire Co.
gauge, and Roebling wire gauge.
* Music Wire Gauge (MWG) ranges from 0.167 (0.004 inch) to 46 (0.18
inch). Also called Piano Wire Gauge.
* British Standard Wire Gage (BSWG) ranges from 0.143 (0.5 inch) to
51 (0.001 inch). Also called Imperial Wire Gage (IWG).
* Stub's Steel Wire Gage (SSWG) ranges from 1 (0.227 inch) to 80 (0.013 inch)
Examples
--------
>>> t_from_gauge(.2, False, 'BWG')
0.5
References
----------
.. [1] Oberg, Erik, Franklin D. Jones, and Henry H. Ryffel. Machinery's
Handbook. Industrial Press, Incorporated, 2012.
'''
try:
sch_integers, sch_inch, sch_SI, decreasing = wire_schedules[schedule]
except:
raise ValueError("Wire gauge schedule not found; supported gauges are \
'BWG', 'AWG', 'SWG', 'MWG', 'BSWG', and 'SSWG'.")
try:
i = sch_integers.index(gauge)
except:
raise ValueError('Input gauge not found in selected schedule')
if SI:
return sch_SI[i] # returns thickness in m
else:
return sch_inch[i] | python | def t_from_gauge(gauge, SI=True, schedule='BWG'):
r'''Looks up the thickness of a given wire gauge of given schedule.
Values are all non-linear, and tabulated internally.
Parameters
----------
gauge : float-like
Wire Gauge, []
SI : bool, optional
If False, will return a thickness in inches not meters
schedule : str
Gauge schedule, one of 'BWG', 'AWG', 'SWG', 'MWG', 'BSWG', or 'SSWG'
Returns
-------
t : float
Thickness, [m]
Notes
-----
* Birmingham Wire Gauge (BWG) ranges from 0.2 (0.5 inch) to 36 (0.004 inch).
* American Wire Gauge (AWG) ranges from 0.167 (0.58 inch) to 51 (0.00099
inch). These are used for electrical wires.
* Steel Wire Gauge (SWG) ranges from 0.143 (0.49 inch) to 51 (0.0044 inch).
Also called Washburn & Moen wire gauge, American Steel gauge, Wire Co.
gauge, and Roebling wire gauge.
* Music Wire Gauge (MWG) ranges from 0.167 (0.004 inch) to 46 (0.18
inch). Also called Piano Wire Gauge.
* British Standard Wire Gage (BSWG) ranges from 0.143 (0.5 inch) to
51 (0.001 inch). Also called Imperial Wire Gage (IWG).
* Stub's Steel Wire Gage (SSWG) ranges from 1 (0.227 inch) to 80 (0.013 inch)
Examples
--------
>>> t_from_gauge(.2, False, 'BWG')
0.5
References
----------
.. [1] Oberg, Erik, Franklin D. Jones, and Henry H. Ryffel. Machinery's
Handbook. Industrial Press, Incorporated, 2012.
'''
try:
sch_integers, sch_inch, sch_SI, decreasing = wire_schedules[schedule]
except:
raise ValueError("Wire gauge schedule not found; supported gauges are \
'BWG', 'AWG', 'SWG', 'MWG', 'BSWG', and 'SSWG'.")
try:
i = sch_integers.index(gauge)
except:
raise ValueError('Input gauge not found in selected schedule')
if SI:
return sch_SI[i] # returns thickness in m
else:
return sch_inch[i] | [
"def",
"t_from_gauge",
"(",
"gauge",
",",
"SI",
"=",
"True",
",",
"schedule",
"=",
"'BWG'",
")",
":",
"try",
":",
"sch_integers",
",",
"sch_inch",
",",
"sch_SI",
",",
"decreasing",
"=",
"wire_schedules",
"[",
"schedule",
"]",
"except",
":",
"raise",
"ValueError",
"(",
"\"Wire gauge schedule not found; supported gauges are \\\n'BWG', 'AWG', 'SWG', 'MWG', 'BSWG', and 'SSWG'.\"",
")",
"try",
":",
"i",
"=",
"sch_integers",
".",
"index",
"(",
"gauge",
")",
"except",
":",
"raise",
"ValueError",
"(",
"'Input gauge not found in selected schedule'",
")",
"if",
"SI",
":",
"return",
"sch_SI",
"[",
"i",
"]",
"# returns thickness in m",
"else",
":",
"return",
"sch_inch",
"[",
"i",
"]"
]
| r'''Looks up the thickness of a given wire gauge of given schedule.
Values are all non-linear, and tabulated internally.
Parameters
----------
gauge : float-like
Wire Gauge, []
SI : bool, optional
If False, will return a thickness in inches not meters
schedule : str
Gauge schedule, one of 'BWG', 'AWG', 'SWG', 'MWG', 'BSWG', or 'SSWG'
Returns
-------
t : float
Thickness, [m]
Notes
-----
* Birmingham Wire Gauge (BWG) ranges from 0.2 (0.5 inch) to 36 (0.004 inch).
* American Wire Gauge (AWG) ranges from 0.167 (0.58 inch) to 51 (0.00099
inch). These are used for electrical wires.
* Steel Wire Gauge (SWG) ranges from 0.143 (0.49 inch) to 51 (0.0044 inch).
Also called Washburn & Moen wire gauge, American Steel gauge, Wire Co.
gauge, and Roebling wire gauge.
* Music Wire Gauge (MWG) ranges from 0.167 (0.004 inch) to 46 (0.18
inch). Also called Piano Wire Gauge.
* British Standard Wire Gage (BSWG) ranges from 0.143 (0.5 inch) to
51 (0.001 inch). Also called Imperial Wire Gage (IWG).
* Stub's Steel Wire Gage (SSWG) ranges from 1 (0.227 inch) to 80 (0.013 inch)
Examples
--------
>>> t_from_gauge(.2, False, 'BWG')
0.5
References
----------
.. [1] Oberg, Erik, Franklin D. Jones, and Henry H. Ryffel. Machinery's
Handbook. Industrial Press, Incorporated, 2012. | [
"r",
"Looks",
"up",
"the",
"thickness",
"of",
"a",
"given",
"wire",
"gauge",
"of",
"given",
"schedule",
".",
"Values",
"are",
"all",
"non",
"-",
"linear",
"and",
"tabulated",
"internally",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/piping.py#L437-L493 | train |
CalebBell/fluids | fluids/safety_valve.py | API520_F2 | def API520_F2(k, P1, P2):
r'''Calculates coefficient F2 for subcritical flow for use in API 520
subcritical flow relief valve sizing.
.. math::
F_2 = \sqrt{\left(\frac{k}{k-1}\right)r^\frac{2}{k}
\left[\frac{1-r^\frac{k-1}{k}}{1-r}\right]}
.. math::
r = \frac{P_2}{P_1}
Parameters
----------
k : float
Isentropic coefficient or ideal gas heat capacity ratio [-]
P1 : float
Upstream relieving pressure; the set pressure plus the allowable
overpressure, plus atmospheric pressure, [Pa]
P2 : float
Built-up backpressure; the increase in pressure during flow at the
outlet of a pressure-relief device after it opens, [Pa]
Returns
-------
F2 : float
Subcritical flow coefficient `F2` [-]
Notes
-----
F2 is completely dimensionless.
Examples
--------
From [1]_ example 2, matches.
>>> API520_F2(1.8, 1E6, 7E5)
0.8600724121105563
References
----------
.. [1] API Standard 520, Part 1 - Sizing and Selection.
'''
r = P2/P1
return ( k/(k-1)*r**(2./k) * ((1-r**((k-1.)/k))/(1.-r)) )**0.5 | python | def API520_F2(k, P1, P2):
r'''Calculates coefficient F2 for subcritical flow for use in API 520
subcritical flow relief valve sizing.
.. math::
F_2 = \sqrt{\left(\frac{k}{k-1}\right)r^\frac{2}{k}
\left[\frac{1-r^\frac{k-1}{k}}{1-r}\right]}
.. math::
r = \frac{P_2}{P_1}
Parameters
----------
k : float
Isentropic coefficient or ideal gas heat capacity ratio [-]
P1 : float
Upstream relieving pressure; the set pressure plus the allowable
overpressure, plus atmospheric pressure, [Pa]
P2 : float
Built-up backpressure; the increase in pressure during flow at the
outlet of a pressure-relief device after it opens, [Pa]
Returns
-------
F2 : float
Subcritical flow coefficient `F2` [-]
Notes
-----
F2 is completely dimensionless.
Examples
--------
From [1]_ example 2, matches.
>>> API520_F2(1.8, 1E6, 7E5)
0.8600724121105563
References
----------
.. [1] API Standard 520, Part 1 - Sizing and Selection.
'''
r = P2/P1
return ( k/(k-1)*r**(2./k) * ((1-r**((k-1.)/k))/(1.-r)) )**0.5 | [
"def",
"API520_F2",
"(",
"k",
",",
"P1",
",",
"P2",
")",
":",
"r",
"=",
"P2",
"/",
"P1",
"return",
"(",
"k",
"/",
"(",
"k",
"-",
"1",
")",
"*",
"r",
"**",
"(",
"2.",
"/",
"k",
")",
"*",
"(",
"(",
"1",
"-",
"r",
"**",
"(",
"(",
"k",
"-",
"1.",
")",
"/",
"k",
")",
")",
"/",
"(",
"1.",
"-",
"r",
")",
")",
")",
"**",
"0.5"
]
| r'''Calculates coefficient F2 for subcritical flow for use in API 520
subcritical flow relief valve sizing.
.. math::
F_2 = \sqrt{\left(\frac{k}{k-1}\right)r^\frac{2}{k}
\left[\frac{1-r^\frac{k-1}{k}}{1-r}\right]}
.. math::
r = \frac{P_2}{P_1}
Parameters
----------
k : float
Isentropic coefficient or ideal gas heat capacity ratio [-]
P1 : float
Upstream relieving pressure; the set pressure plus the allowable
overpressure, plus atmospheric pressure, [Pa]
P2 : float
Built-up backpressure; the increase in pressure during flow at the
outlet of a pressure-relief device after it opens, [Pa]
Returns
-------
F2 : float
Subcritical flow coefficient `F2` [-]
Notes
-----
F2 is completely dimensionless.
Examples
--------
From [1]_ example 2, matches.
>>> API520_F2(1.8, 1E6, 7E5)
0.8600724121105563
References
----------
.. [1] API Standard 520, Part 1 - Sizing and Selection. | [
"r",
"Calculates",
"coefficient",
"F2",
"for",
"subcritical",
"flow",
"for",
"use",
"in",
"API",
"520",
"subcritical",
"flow",
"relief",
"valve",
"sizing",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/safety_valve.py#L130-L173 | train |
CalebBell/fluids | fluids/safety_valve.py | API520_SH | def API520_SH(T1, P1):
r'''Calculates correction due to steam superheat for steam flow for use in
API 520 relief valve sizing. 2D interpolation among a table with 28
pressures and 10 temperatures is performed.
Parameters
----------
T1 : float
Temperature of the fluid entering the valve [K]
P1 : float
Upstream relieving pressure; the set pressure plus the allowable
overpressure, plus atmospheric pressure, [Pa]
Returns
-------
KSH : float
Correction due to steam superheat [-]
Notes
-----
For P above 20679 kPag, use the critical flow model.
Superheat cannot be above 649 degrees Celsius.
If T1 is above 149 degrees Celsius, returns 1.
Examples
--------
Custom example from table 9:
>>> API520_SH(593+273.15, 1066.325E3)
0.7201800000000002
References
----------
.. [1] API Standard 520, Part 1 - Sizing and Selection.
'''
if P1 > 20780325.0: # 20679E3+atm
raise Exception('For P above 20679 kPag, use the critical flow model')
if T1 > 922.15:
raise Exception('Superheat cannot be above 649 degrees Celcius')
if T1 < 422.15:
return 1. # No superheat under 15 psig
return float(bisplev(T1, P1, API520_KSH_tck)) | python | def API520_SH(T1, P1):
r'''Calculates correction due to steam superheat for steam flow for use in
API 520 relief valve sizing. 2D interpolation among a table with 28
pressures and 10 temperatures is performed.
Parameters
----------
T1 : float
Temperature of the fluid entering the valve [K]
P1 : float
Upstream relieving pressure; the set pressure plus the allowable
overpressure, plus atmospheric pressure, [Pa]
Returns
-------
KSH : float
Correction due to steam superheat [-]
Notes
-----
For P above 20679 kPag, use the critical flow model.
Superheat cannot be above 649 degrees Celsius.
If T1 is above 149 degrees Celsius, returns 1.
Examples
--------
Custom example from table 9:
>>> API520_SH(593+273.15, 1066.325E3)
0.7201800000000002
References
----------
.. [1] API Standard 520, Part 1 - Sizing and Selection.
'''
if P1 > 20780325.0: # 20679E3+atm
raise Exception('For P above 20679 kPag, use the critical flow model')
if T1 > 922.15:
raise Exception('Superheat cannot be above 649 degrees Celcius')
if T1 < 422.15:
return 1. # No superheat under 15 psig
return float(bisplev(T1, P1, API520_KSH_tck)) | [
"def",
"API520_SH",
"(",
"T1",
",",
"P1",
")",
":",
"if",
"P1",
">",
"20780325.0",
":",
"# 20679E3+atm",
"raise",
"Exception",
"(",
"'For P above 20679 kPag, use the critical flow model'",
")",
"if",
"T1",
">",
"922.15",
":",
"raise",
"Exception",
"(",
"'Superheat cannot be above 649 degrees Celcius'",
")",
"if",
"T1",
"<",
"422.15",
":",
"return",
"1.",
"# No superheat under 15 psig",
"return",
"float",
"(",
"bisplev",
"(",
"T1",
",",
"P1",
",",
"API520_KSH_tck",
")",
")"
]
| r'''Calculates correction due to steam superheat for steam flow for use in
API 520 relief valve sizing. 2D interpolation among a table with 28
pressures and 10 temperatures is performed.
Parameters
----------
T1 : float
Temperature of the fluid entering the valve [K]
P1 : float
Upstream relieving pressure; the set pressure plus the allowable
overpressure, plus atmospheric pressure, [Pa]
Returns
-------
KSH : float
Correction due to steam superheat [-]
Notes
-----
For P above 20679 kPag, use the critical flow model.
Superheat cannot be above 649 degrees Celsius.
If T1 is above 149 degrees Celsius, returns 1.
Examples
--------
Custom example from table 9:
>>> API520_SH(593+273.15, 1066.325E3)
0.7201800000000002
References
----------
.. [1] API Standard 520, Part 1 - Sizing and Selection. | [
"r",
"Calculates",
"correction",
"due",
"to",
"steam",
"superheat",
"for",
"steam",
"flow",
"for",
"use",
"in",
"API",
"520",
"relief",
"valve",
"sizing",
".",
"2D",
"interpolation",
"among",
"a",
"table",
"with",
"28",
"pressures",
"and",
"10",
"temperatures",
"is",
"performed",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/safety_valve.py#L319-L361 | train |
CalebBell/fluids | fluids/safety_valve.py | API520_W | def API520_W(Pset, Pback):
r'''Calculates capacity correction due to backpressure on balanced
spring-loaded PRVs in liquid service. For pilot operated valves,
this is always 1. Applicable up to 50% of the percent gauge backpressure,
For use in API 520 relief valve sizing. 1D interpolation among a table with
53 backpressures is performed.
Parameters
----------
Pset : float
Set pressure for relief [Pa]
Pback : float
Backpressure, [Pa]
Returns
-------
KW : float
Correction due to liquid backpressure [-]
Notes
-----
If the calculated gauge backpressure is less than 15%, a value of 1 is
returned.
Examples
--------
Custom example from figure 31:
>>> API520_W(1E6, 3E5) # 22% overpressure
0.9511471848008564
References
----------
.. [1] API Standard 520, Part 1 - Sizing and Selection.
'''
gauge_backpressure = (Pback-atm)/(Pset-atm)*100.0 # in percent
if gauge_backpressure < 15.0:
return 1.0
return interp(gauge_backpressure, Kw_x, Kw_y) | python | def API520_W(Pset, Pback):
r'''Calculates capacity correction due to backpressure on balanced
spring-loaded PRVs in liquid service. For pilot operated valves,
this is always 1. Applicable up to 50% of the percent gauge backpressure,
For use in API 520 relief valve sizing. 1D interpolation among a table with
53 backpressures is performed.
Parameters
----------
Pset : float
Set pressure for relief [Pa]
Pback : float
Backpressure, [Pa]
Returns
-------
KW : float
Correction due to liquid backpressure [-]
Notes
-----
If the calculated gauge backpressure is less than 15%, a value of 1 is
returned.
Examples
--------
Custom example from figure 31:
>>> API520_W(1E6, 3E5) # 22% overpressure
0.9511471848008564
References
----------
.. [1] API Standard 520, Part 1 - Sizing and Selection.
'''
gauge_backpressure = (Pback-atm)/(Pset-atm)*100.0 # in percent
if gauge_backpressure < 15.0:
return 1.0
return interp(gauge_backpressure, Kw_x, Kw_y) | [
"def",
"API520_W",
"(",
"Pset",
",",
"Pback",
")",
":",
"gauge_backpressure",
"=",
"(",
"Pback",
"-",
"atm",
")",
"/",
"(",
"Pset",
"-",
"atm",
")",
"*",
"100.0",
"# in percent",
"if",
"gauge_backpressure",
"<",
"15.0",
":",
"return",
"1.0",
"return",
"interp",
"(",
"gauge_backpressure",
",",
"Kw_x",
",",
"Kw_y",
")"
]
| r'''Calculates capacity correction due to backpressure on balanced
spring-loaded PRVs in liquid service. For pilot operated valves,
this is always 1. Applicable up to 50% of the percent gauge backpressure,
For use in API 520 relief valve sizing. 1D interpolation among a table with
53 backpressures is performed.
Parameters
----------
Pset : float
Set pressure for relief [Pa]
Pback : float
Backpressure, [Pa]
Returns
-------
KW : float
Correction due to liquid backpressure [-]
Notes
-----
If the calculated gauge backpressure is less than 15%, a value of 1 is
returned.
Examples
--------
Custom example from figure 31:
>>> API520_W(1E6, 3E5) # 22% overpressure
0.9511471848008564
References
----------
.. [1] API Standard 520, Part 1 - Sizing and Selection. | [
"r",
"Calculates",
"capacity",
"correction",
"due",
"to",
"backpressure",
"on",
"balanced",
"spring",
"-",
"loaded",
"PRVs",
"in",
"liquid",
"service",
".",
"For",
"pilot",
"operated",
"valves",
"this",
"is",
"always",
"1",
".",
"Applicable",
"up",
"to",
"50%",
"of",
"the",
"percent",
"gauge",
"backpressure",
"For",
"use",
"in",
"API",
"520",
"relief",
"valve",
"sizing",
".",
"1D",
"interpolation",
"among",
"a",
"table",
"with",
"53",
"backpressures",
"is",
"performed",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/safety_valve.py#L383-L421 | train |
CalebBell/fluids | fluids/safety_valve.py | API520_B | def API520_B(Pset, Pback, overpressure=0.1):
r'''Calculates capacity correction due to backpressure on balanced
spring-loaded PRVs in vapor service. For pilot operated valves,
this is always 1. Applicable up to 50% of the percent gauge backpressure,
For use in API 520 relief valve sizing. 1D interpolation among a table with
53 backpressures is performed.
Parameters
----------
Pset : float
Set pressure for relief [Pa]
Pback : float
Backpressure, [Pa]
overpressure : float, optional
The maximum fraction overpressure; one of 0.1, 0.16, or 0.21, []
Returns
-------
Kb : float
Correction due to vapor backpressure [-]
Notes
-----
If the calculated gauge backpressure is less than 30%, 38%, or 50% for
overpressures of 0.1, 0.16, or 0.21, a value of 1 is returned.
Percent gauge backpressure must be under 50%.
Examples
--------
Custom examples from figure 30:
>>> API520_B(1E6, 5E5)
0.7929945420944432
References
----------
.. [1] API Standard 520, Part 1 - Sizing and Selection.
'''
gauge_backpressure = (Pback-atm)/(Pset-atm)*100 # in percent
if overpressure not in [0.1, 0.16, 0.21]:
raise Exception('Only overpressure of 10%, 16%, or 21% are permitted')
if (overpressure == 0.1 and gauge_backpressure < 30) or (
overpressure == 0.16 and gauge_backpressure < 38) or (
overpressure == 0.21 and gauge_backpressure < 50):
return 1
elif gauge_backpressure > 50:
raise Exception('Gauge pressure must be < 50%')
if overpressure == 0.16:
Kb = interp(gauge_backpressure, Kb_16_over_x, Kb_16_over_y)
elif overpressure == 0.1:
Kb = interp(gauge_backpressure, Kb_10_over_x, Kb_10_over_y)
return Kb | python | def API520_B(Pset, Pback, overpressure=0.1):
r'''Calculates capacity correction due to backpressure on balanced
spring-loaded PRVs in vapor service. For pilot operated valves,
this is always 1. Applicable up to 50% of the percent gauge backpressure,
For use in API 520 relief valve sizing. 1D interpolation among a table with
53 backpressures is performed.
Parameters
----------
Pset : float
Set pressure for relief [Pa]
Pback : float
Backpressure, [Pa]
overpressure : float, optional
The maximum fraction overpressure; one of 0.1, 0.16, or 0.21, []
Returns
-------
Kb : float
Correction due to vapor backpressure [-]
Notes
-----
If the calculated gauge backpressure is less than 30%, 38%, or 50% for
overpressures of 0.1, 0.16, or 0.21, a value of 1 is returned.
Percent gauge backpressure must be under 50%.
Examples
--------
Custom examples from figure 30:
>>> API520_B(1E6, 5E5)
0.7929945420944432
References
----------
.. [1] API Standard 520, Part 1 - Sizing and Selection.
'''
gauge_backpressure = (Pback-atm)/(Pset-atm)*100 # in percent
if overpressure not in [0.1, 0.16, 0.21]:
raise Exception('Only overpressure of 10%, 16%, or 21% are permitted')
if (overpressure == 0.1 and gauge_backpressure < 30) or (
overpressure == 0.16 and gauge_backpressure < 38) or (
overpressure == 0.21 and gauge_backpressure < 50):
return 1
elif gauge_backpressure > 50:
raise Exception('Gauge pressure must be < 50%')
if overpressure == 0.16:
Kb = interp(gauge_backpressure, Kb_16_over_x, Kb_16_over_y)
elif overpressure == 0.1:
Kb = interp(gauge_backpressure, Kb_10_over_x, Kb_10_over_y)
return Kb | [
"def",
"API520_B",
"(",
"Pset",
",",
"Pback",
",",
"overpressure",
"=",
"0.1",
")",
":",
"gauge_backpressure",
"=",
"(",
"Pback",
"-",
"atm",
")",
"/",
"(",
"Pset",
"-",
"atm",
")",
"*",
"100",
"# in percent",
"if",
"overpressure",
"not",
"in",
"[",
"0.1",
",",
"0.16",
",",
"0.21",
"]",
":",
"raise",
"Exception",
"(",
"'Only overpressure of 10%, 16%, or 21% are permitted'",
")",
"if",
"(",
"overpressure",
"==",
"0.1",
"and",
"gauge_backpressure",
"<",
"30",
")",
"or",
"(",
"overpressure",
"==",
"0.16",
"and",
"gauge_backpressure",
"<",
"38",
")",
"or",
"(",
"overpressure",
"==",
"0.21",
"and",
"gauge_backpressure",
"<",
"50",
")",
":",
"return",
"1",
"elif",
"gauge_backpressure",
">",
"50",
":",
"raise",
"Exception",
"(",
"'Gauge pressure must be < 50%'",
")",
"if",
"overpressure",
"==",
"0.16",
":",
"Kb",
"=",
"interp",
"(",
"gauge_backpressure",
",",
"Kb_16_over_x",
",",
"Kb_16_over_y",
")",
"elif",
"overpressure",
"==",
"0.1",
":",
"Kb",
"=",
"interp",
"(",
"gauge_backpressure",
",",
"Kb_10_over_x",
",",
"Kb_10_over_y",
")",
"return",
"Kb"
]
| r'''Calculates capacity correction due to backpressure on balanced
spring-loaded PRVs in vapor service. For pilot operated valves,
this is always 1. Applicable up to 50% of the percent gauge backpressure,
For use in API 520 relief valve sizing. 1D interpolation among a table with
53 backpressures is performed.
Parameters
----------
Pset : float
Set pressure for relief [Pa]
Pback : float
Backpressure, [Pa]
overpressure : float, optional
The maximum fraction overpressure; one of 0.1, 0.16, or 0.21, []
Returns
-------
Kb : float
Correction due to vapor backpressure [-]
Notes
-----
If the calculated gauge backpressure is less than 30%, 38%, or 50% for
overpressures of 0.1, 0.16, or 0.21, a value of 1 is returned.
Percent gauge backpressure must be under 50%.
Examples
--------
Custom examples from figure 30:
>>> API520_B(1E6, 5E5)
0.7929945420944432
References
----------
.. [1] API Standard 520, Part 1 - Sizing and Selection. | [
"r",
"Calculates",
"capacity",
"correction",
"due",
"to",
"backpressure",
"on",
"balanced",
"spring",
"-",
"loaded",
"PRVs",
"in",
"vapor",
"service",
".",
"For",
"pilot",
"operated",
"valves",
"this",
"is",
"always",
"1",
".",
"Applicable",
"up",
"to",
"50%",
"of",
"the",
"percent",
"gauge",
"backpressure",
"For",
"use",
"in",
"API",
"520",
"relief",
"valve",
"sizing",
".",
"1D",
"interpolation",
"among",
"a",
"table",
"with",
"53",
"backpressures",
"is",
"performed",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/safety_valve.py#L452-L504 | train |
CalebBell/fluids | fluids/safety_valve.py | API520_A_g | def API520_A_g(m, T, Z, MW, k, P1, P2=101325, Kd=0.975, Kb=1, Kc=1):
r'''Calculates required relief valve area for an API 520 valve passing
a gas or a vapor, at either critical or sub-critical flow.
For critical flow:
.. math::
A = \frac{m}{CK_dP_1K_bK_c}\sqrt{\frac{TZ}{M}}
For sub-critical flow:
.. math::
A = \frac{17.9m}{F_2K_dK_c}\sqrt{\frac{TZ}{MP_1(P_1-P_2)}}
Parameters
----------
m : float
Mass flow rate of vapor through the valve, [kg/s]
T : float
Temperature of vapor entering the valve, [K]
Z : float
Compressibility factor of the vapor, [-]
MW : float
Molecular weight of the vapor, [g/mol]
k : float
Isentropic coefficient or ideal gas heat capacity ratio [-]
P1 : float
Upstream relieving pressure; the set pressure plus the allowable
overpressure, plus atmospheric pressure, [Pa]
P2 : float, optional
Built-up backpressure; the increase in pressure during flow at the
outlet of a pressure-relief device after it opens, [Pa]
Kd : float, optional
The effective coefficient of discharge, from the manufacturer or for
preliminary sizing, using 0.975 normally or 0.62 when used with a
rupture disc as described in [1]_, []
Kb : float, optional
Correction due to vapor backpressure [-]
Kc : float, optional
Combination correction factor for installation with a ruture disk
upstream of the PRV, []
Returns
-------
A : float
Minimum area for relief valve according to [1]_, [m^2]
Notes
-----
Units are interlally kg/hr, kPa, and mm^2 to match [1]_.
Examples
--------
Example 1 from [1]_ for critical flow, matches:
>>> API520_A_g(m=24270/3600., T=348., Z=0.90, MW=51., k=1.11, P1=670E3, Kb=1, Kc=1)
0.0036990460646834414
Example 2 from [1]_ for sub-critical flow, matches:
>>> API520_A_g(m=24270/3600., T=348., Z=0.90, MW=51., k=1.11, P1=670E3, P2=532E3, Kd=0.975, Kb=1, Kc=1)
0.004248358775943481
References
----------
.. [1] API Standard 520, Part 1 - Sizing and Selection.
'''
P1, P2 = P1/1000., P2/1000. # Pa to Kpa in the standard
m = m*3600. # kg/s to kg/hr
if is_critical_flow(P1, P2, k):
C = API520_C(k)
A = m/(C*Kd*Kb*Kc*P1)*(T*Z/MW)**0.5
else:
F2 = API520_F2(k, P1, P2)
A = 17.9*m/(F2*Kd*Kc)*(T*Z/(MW*P1*(P1-P2)))**0.5
return A*0.001**2 | python | def API520_A_g(m, T, Z, MW, k, P1, P2=101325, Kd=0.975, Kb=1, Kc=1):
r'''Calculates required relief valve area for an API 520 valve passing
a gas or a vapor, at either critical or sub-critical flow.
For critical flow:
.. math::
A = \frac{m}{CK_dP_1K_bK_c}\sqrt{\frac{TZ}{M}}
For sub-critical flow:
.. math::
A = \frac{17.9m}{F_2K_dK_c}\sqrt{\frac{TZ}{MP_1(P_1-P_2)}}
Parameters
----------
m : float
Mass flow rate of vapor through the valve, [kg/s]
T : float
Temperature of vapor entering the valve, [K]
Z : float
Compressibility factor of the vapor, [-]
MW : float
Molecular weight of the vapor, [g/mol]
k : float
Isentropic coefficient or ideal gas heat capacity ratio [-]
P1 : float
Upstream relieving pressure; the set pressure plus the allowable
overpressure, plus atmospheric pressure, [Pa]
P2 : float, optional
Built-up backpressure; the increase in pressure during flow at the
outlet of a pressure-relief device after it opens, [Pa]
Kd : float, optional
The effective coefficient of discharge, from the manufacturer or for
preliminary sizing, using 0.975 normally or 0.62 when used with a
rupture disc as described in [1]_, []
Kb : float, optional
Correction due to vapor backpressure [-]
Kc : float, optional
Combination correction factor for installation with a ruture disk
upstream of the PRV, []
Returns
-------
A : float
Minimum area for relief valve according to [1]_, [m^2]
Notes
-----
Units are interlally kg/hr, kPa, and mm^2 to match [1]_.
Examples
--------
Example 1 from [1]_ for critical flow, matches:
>>> API520_A_g(m=24270/3600., T=348., Z=0.90, MW=51., k=1.11, P1=670E3, Kb=1, Kc=1)
0.0036990460646834414
Example 2 from [1]_ for sub-critical flow, matches:
>>> API520_A_g(m=24270/3600., T=348., Z=0.90, MW=51., k=1.11, P1=670E3, P2=532E3, Kd=0.975, Kb=1, Kc=1)
0.004248358775943481
References
----------
.. [1] API Standard 520, Part 1 - Sizing and Selection.
'''
P1, P2 = P1/1000., P2/1000. # Pa to Kpa in the standard
m = m*3600. # kg/s to kg/hr
if is_critical_flow(P1, P2, k):
C = API520_C(k)
A = m/(C*Kd*Kb*Kc*P1)*(T*Z/MW)**0.5
else:
F2 = API520_F2(k, P1, P2)
A = 17.9*m/(F2*Kd*Kc)*(T*Z/(MW*P1*(P1-P2)))**0.5
return A*0.001**2 | [
"def",
"API520_A_g",
"(",
"m",
",",
"T",
",",
"Z",
",",
"MW",
",",
"k",
",",
"P1",
",",
"P2",
"=",
"101325",
",",
"Kd",
"=",
"0.975",
",",
"Kb",
"=",
"1",
",",
"Kc",
"=",
"1",
")",
":",
"P1",
",",
"P2",
"=",
"P1",
"/",
"1000.",
",",
"P2",
"/",
"1000.",
"# Pa to Kpa in the standard",
"m",
"=",
"m",
"*",
"3600.",
"# kg/s to kg/hr",
"if",
"is_critical_flow",
"(",
"P1",
",",
"P2",
",",
"k",
")",
":",
"C",
"=",
"API520_C",
"(",
"k",
")",
"A",
"=",
"m",
"/",
"(",
"C",
"*",
"Kd",
"*",
"Kb",
"*",
"Kc",
"*",
"P1",
")",
"*",
"(",
"T",
"*",
"Z",
"/",
"MW",
")",
"**",
"0.5",
"else",
":",
"F2",
"=",
"API520_F2",
"(",
"k",
",",
"P1",
",",
"P2",
")",
"A",
"=",
"17.9",
"*",
"m",
"/",
"(",
"F2",
"*",
"Kd",
"*",
"Kc",
")",
"*",
"(",
"T",
"*",
"Z",
"/",
"(",
"MW",
"*",
"P1",
"*",
"(",
"P1",
"-",
"P2",
")",
")",
")",
"**",
"0.5",
"return",
"A",
"*",
"0.001",
"**",
"2"
]
| r'''Calculates required relief valve area for an API 520 valve passing
a gas or a vapor, at either critical or sub-critical flow.
For critical flow:
.. math::
A = \frac{m}{CK_dP_1K_bK_c}\sqrt{\frac{TZ}{M}}
For sub-critical flow:
.. math::
A = \frac{17.9m}{F_2K_dK_c}\sqrt{\frac{TZ}{MP_1(P_1-P_2)}}
Parameters
----------
m : float
Mass flow rate of vapor through the valve, [kg/s]
T : float
Temperature of vapor entering the valve, [K]
Z : float
Compressibility factor of the vapor, [-]
MW : float
Molecular weight of the vapor, [g/mol]
k : float
Isentropic coefficient or ideal gas heat capacity ratio [-]
P1 : float
Upstream relieving pressure; the set pressure plus the allowable
overpressure, plus atmospheric pressure, [Pa]
P2 : float, optional
Built-up backpressure; the increase in pressure during flow at the
outlet of a pressure-relief device after it opens, [Pa]
Kd : float, optional
The effective coefficient of discharge, from the manufacturer or for
preliminary sizing, using 0.975 normally or 0.62 when used with a
rupture disc as described in [1]_, []
Kb : float, optional
Correction due to vapor backpressure [-]
Kc : float, optional
Combination correction factor for installation with a ruture disk
upstream of the PRV, []
Returns
-------
A : float
Minimum area for relief valve according to [1]_, [m^2]
Notes
-----
Units are interlally kg/hr, kPa, and mm^2 to match [1]_.
Examples
--------
Example 1 from [1]_ for critical flow, matches:
>>> API520_A_g(m=24270/3600., T=348., Z=0.90, MW=51., k=1.11, P1=670E3, Kb=1, Kc=1)
0.0036990460646834414
Example 2 from [1]_ for sub-critical flow, matches:
>>> API520_A_g(m=24270/3600., T=348., Z=0.90, MW=51., k=1.11, P1=670E3, P2=532E3, Kd=0.975, Kb=1, Kc=1)
0.004248358775943481
References
----------
.. [1] API Standard 520, Part 1 - Sizing and Selection. | [
"r",
"Calculates",
"required",
"relief",
"valve",
"area",
"for",
"an",
"API",
"520",
"valve",
"passing",
"a",
"gas",
"or",
"a",
"vapor",
"at",
"either",
"critical",
"or",
"sub",
"-",
"critical",
"flow",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/safety_valve.py#L507-L582 | train |
CalebBell/fluids | fluids/safety_valve.py | API520_A_steam | def API520_A_steam(m, T, P1, Kd=0.975, Kb=1, Kc=1):
r'''Calculates required relief valve area for an API 520 valve passing
a steam, at either saturation or superheat but not partially condensed.
.. math::
A = \frac{190.5m}{P_1 K_d K_b K_c K_N K_{SH}}
Parameters
----------
m : float
Mass flow rate of steam through the valve, [kg/s]
T : float
Temperature of steam entering the valve, [K]
P1 : float
Upstream relieving pressure; the set pressure plus the allowable
overpressure, plus atmospheric pressure, [Pa]
Kd : float, optional
The effective coefficient of discharge, from the manufacturer or for
preliminary sizing, using 0.975 normally or 0.62 when used with a
rupture disc as described in [1]_, []
Kb : float, optional
Correction due to vapor backpressure [-]
Kc : float, optional
Combination correction factor for installation with a rupture disk
upstream of the PRV, []
Returns
-------
A : float
Minimum area for relief valve according to [1]_, [m^2]
Notes
-----
Units are interlally kg/hr, kPa, and mm^2 to match [1]_.
With the provided temperature and pressure, the KN coefficient is
calculated with the function API520_N; as is the superheat correction KSH,
with the function API520_SH.
Examples
--------
Example 4 from [1]_, matches:
>>> API520_A_steam(m=69615/3600., T=592.5, P1=12236E3, Kd=0.975, Kb=1, Kc=1)
0.0011034712423692733
References
----------
.. [1] API Standard 520, Part 1 - Sizing and Selection.
'''
KN = API520_N(P1)
KSH = API520_SH(T, P1)
P1 = P1/1000. # Pa to kPa
m = m*3600. # kg/s to kg/hr
A = 190.5*m/(P1*Kd*Kb*Kc*KN*KSH)
return A*0.001**2 | python | def API520_A_steam(m, T, P1, Kd=0.975, Kb=1, Kc=1):
r'''Calculates required relief valve area for an API 520 valve passing
a steam, at either saturation or superheat but not partially condensed.
.. math::
A = \frac{190.5m}{P_1 K_d K_b K_c K_N K_{SH}}
Parameters
----------
m : float
Mass flow rate of steam through the valve, [kg/s]
T : float
Temperature of steam entering the valve, [K]
P1 : float
Upstream relieving pressure; the set pressure plus the allowable
overpressure, plus atmospheric pressure, [Pa]
Kd : float, optional
The effective coefficient of discharge, from the manufacturer or for
preliminary sizing, using 0.975 normally or 0.62 when used with a
rupture disc as described in [1]_, []
Kb : float, optional
Correction due to vapor backpressure [-]
Kc : float, optional
Combination correction factor for installation with a rupture disk
upstream of the PRV, []
Returns
-------
A : float
Minimum area for relief valve according to [1]_, [m^2]
Notes
-----
Units are interlally kg/hr, kPa, and mm^2 to match [1]_.
With the provided temperature and pressure, the KN coefficient is
calculated with the function API520_N; as is the superheat correction KSH,
with the function API520_SH.
Examples
--------
Example 4 from [1]_, matches:
>>> API520_A_steam(m=69615/3600., T=592.5, P1=12236E3, Kd=0.975, Kb=1, Kc=1)
0.0011034712423692733
References
----------
.. [1] API Standard 520, Part 1 - Sizing and Selection.
'''
KN = API520_N(P1)
KSH = API520_SH(T, P1)
P1 = P1/1000. # Pa to kPa
m = m*3600. # kg/s to kg/hr
A = 190.5*m/(P1*Kd*Kb*Kc*KN*KSH)
return A*0.001**2 | [
"def",
"API520_A_steam",
"(",
"m",
",",
"T",
",",
"P1",
",",
"Kd",
"=",
"0.975",
",",
"Kb",
"=",
"1",
",",
"Kc",
"=",
"1",
")",
":",
"KN",
"=",
"API520_N",
"(",
"P1",
")",
"KSH",
"=",
"API520_SH",
"(",
"T",
",",
"P1",
")",
"P1",
"=",
"P1",
"/",
"1000.",
"# Pa to kPa",
"m",
"=",
"m",
"*",
"3600.",
"# kg/s to kg/hr",
"A",
"=",
"190.5",
"*",
"m",
"/",
"(",
"P1",
"*",
"Kd",
"*",
"Kb",
"*",
"Kc",
"*",
"KN",
"*",
"KSH",
")",
"return",
"A",
"*",
"0.001",
"**",
"2"
]
| r'''Calculates required relief valve area for an API 520 valve passing
a steam, at either saturation or superheat but not partially condensed.
.. math::
A = \frac{190.5m}{P_1 K_d K_b K_c K_N K_{SH}}
Parameters
----------
m : float
Mass flow rate of steam through the valve, [kg/s]
T : float
Temperature of steam entering the valve, [K]
P1 : float
Upstream relieving pressure; the set pressure plus the allowable
overpressure, plus atmospheric pressure, [Pa]
Kd : float, optional
The effective coefficient of discharge, from the manufacturer or for
preliminary sizing, using 0.975 normally or 0.62 when used with a
rupture disc as described in [1]_, []
Kb : float, optional
Correction due to vapor backpressure [-]
Kc : float, optional
Combination correction factor for installation with a rupture disk
upstream of the PRV, []
Returns
-------
A : float
Minimum area for relief valve according to [1]_, [m^2]
Notes
-----
Units are interlally kg/hr, kPa, and mm^2 to match [1]_.
With the provided temperature and pressure, the KN coefficient is
calculated with the function API520_N; as is the superheat correction KSH,
with the function API520_SH.
Examples
--------
Example 4 from [1]_, matches:
>>> API520_A_steam(m=69615/3600., T=592.5, P1=12236E3, Kd=0.975, Kb=1, Kc=1)
0.0011034712423692733
References
----------
.. [1] API Standard 520, Part 1 - Sizing and Selection. | [
"r",
"Calculates",
"required",
"relief",
"valve",
"area",
"for",
"an",
"API",
"520",
"valve",
"passing",
"a",
"steam",
"at",
"either",
"saturation",
"or",
"superheat",
"but",
"not",
"partially",
"condensed",
"."
]
| 57f556752e039f1d3e5a822f408c184783db2828 | https://github.com/CalebBell/fluids/blob/57f556752e039f1d3e5a822f408c184783db2828/fluids/safety_valve.py#L585-L639 | train |
xhtml2pdf/xhtml2pdf | xhtml2pdf/context.py | pisaContext.getFile | def getFile(self, name, relative=None):
"""
Returns a file name or None
"""
if self.pathCallback is not None:
return getFile(self._getFileDeprecated(name, relative))
return getFile(name, relative or self.pathDirectory) | python | def getFile(self, name, relative=None):
"""
Returns a file name or None
"""
if self.pathCallback is not None:
return getFile(self._getFileDeprecated(name, relative))
return getFile(name, relative or self.pathDirectory) | [
"def",
"getFile",
"(",
"self",
",",
"name",
",",
"relative",
"=",
"None",
")",
":",
"if",
"self",
".",
"pathCallback",
"is",
"not",
"None",
":",
"return",
"getFile",
"(",
"self",
".",
"_getFileDeprecated",
"(",
"name",
",",
"relative",
")",
")",
"return",
"getFile",
"(",
"name",
",",
"relative",
"or",
"self",
".",
"pathDirectory",
")"
]
| Returns a file name or None | [
"Returns",
"a",
"file",
"name",
"or",
"None"
]
| 230357a392f48816532d3c2fa082a680b80ece48 | https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/context.py#L812-L818 | train |
xhtml2pdf/xhtml2pdf | xhtml2pdf/context.py | pisaContext.getFontName | def getFontName(self, names, default="helvetica"):
"""
Name of a font
"""
# print names, self.fontList
if type(names) is not ListType:
if type(names) not in six.string_types:
names = str(names)
names = names.strip().split(",")
for name in names:
if type(name) not in six.string_types:
name = str(name)
font = self.fontList.get(name.strip().lower(), None)
if font is not None:
return font
return self.fontList.get(default, None) | python | def getFontName(self, names, default="helvetica"):
"""
Name of a font
"""
# print names, self.fontList
if type(names) is not ListType:
if type(names) not in six.string_types:
names = str(names)
names = names.strip().split(",")
for name in names:
if type(name) not in six.string_types:
name = str(name)
font = self.fontList.get(name.strip().lower(), None)
if font is not None:
return font
return self.fontList.get(default, None) | [
"def",
"getFontName",
"(",
"self",
",",
"names",
",",
"default",
"=",
"\"helvetica\"",
")",
":",
"# print names, self.fontList",
"if",
"type",
"(",
"names",
")",
"is",
"not",
"ListType",
":",
"if",
"type",
"(",
"names",
")",
"not",
"in",
"six",
".",
"string_types",
":",
"names",
"=",
"str",
"(",
"names",
")",
"names",
"=",
"names",
".",
"strip",
"(",
")",
".",
"split",
"(",
"\",\"",
")",
"for",
"name",
"in",
"names",
":",
"if",
"type",
"(",
"name",
")",
"not",
"in",
"six",
".",
"string_types",
":",
"name",
"=",
"str",
"(",
"name",
")",
"font",
"=",
"self",
".",
"fontList",
".",
"get",
"(",
"name",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
",",
"None",
")",
"if",
"font",
"is",
"not",
"None",
":",
"return",
"font",
"return",
"self",
".",
"fontList",
".",
"get",
"(",
"default",
",",
"None",
")"
]
| Name of a font | [
"Name",
"of",
"a",
"font"
]
| 230357a392f48816532d3c2fa082a680b80ece48 | https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/context.py#L820-L835 | train |
xhtml2pdf/xhtml2pdf | xhtml2pdf/parser.py | pisaPreLoop | def pisaPreLoop(node, context, collect=False):
"""
Collect all CSS definitions
"""
data = u""
if node.nodeType == Node.TEXT_NODE and collect:
data = node.data
elif node.nodeType == Node.ELEMENT_NODE:
name = node.tagName.lower()
if name in ("style", "link"):
attr = pisaGetAttributes(context, name, node.attributes)
media = [x.strip()
for x in attr.media.lower().split(",") if x.strip()]
if attr.get("type", "").lower() in ("", "text/css") and \
(not media or "all" in media or "print" in media or "pdf" in media):
if name == "style":
for node in node.childNodes:
data += pisaPreLoop(node, context, collect=True)
context.addCSS(data)
return u""
if name == "link" and attr.href and attr.rel.lower() == "stylesheet":
# print "CSS LINK", attr
context.addCSS('\n@import "%s" %s;' %
(attr.href, ",".join(media)))
for node in node.childNodes:
result = pisaPreLoop(node, context, collect=collect)
if collect:
data += result
return data | python | def pisaPreLoop(node, context, collect=False):
"""
Collect all CSS definitions
"""
data = u""
if node.nodeType == Node.TEXT_NODE and collect:
data = node.data
elif node.nodeType == Node.ELEMENT_NODE:
name = node.tagName.lower()
if name in ("style", "link"):
attr = pisaGetAttributes(context, name, node.attributes)
media = [x.strip()
for x in attr.media.lower().split(",") if x.strip()]
if attr.get("type", "").lower() in ("", "text/css") and \
(not media or "all" in media or "print" in media or "pdf" in media):
if name == "style":
for node in node.childNodes:
data += pisaPreLoop(node, context, collect=True)
context.addCSS(data)
return u""
if name == "link" and attr.href and attr.rel.lower() == "stylesheet":
# print "CSS LINK", attr
context.addCSS('\n@import "%s" %s;' %
(attr.href, ",".join(media)))
for node in node.childNodes:
result = pisaPreLoop(node, context, collect=collect)
if collect:
data += result
return data | [
"def",
"pisaPreLoop",
"(",
"node",
",",
"context",
",",
"collect",
"=",
"False",
")",
":",
"data",
"=",
"u\"\"",
"if",
"node",
".",
"nodeType",
"==",
"Node",
".",
"TEXT_NODE",
"and",
"collect",
":",
"data",
"=",
"node",
".",
"data",
"elif",
"node",
".",
"nodeType",
"==",
"Node",
".",
"ELEMENT_NODE",
":",
"name",
"=",
"node",
".",
"tagName",
".",
"lower",
"(",
")",
"if",
"name",
"in",
"(",
"\"style\"",
",",
"\"link\"",
")",
":",
"attr",
"=",
"pisaGetAttributes",
"(",
"context",
",",
"name",
",",
"node",
".",
"attributes",
")",
"media",
"=",
"[",
"x",
".",
"strip",
"(",
")",
"for",
"x",
"in",
"attr",
".",
"media",
".",
"lower",
"(",
")",
".",
"split",
"(",
"\",\"",
")",
"if",
"x",
".",
"strip",
"(",
")",
"]",
"if",
"attr",
".",
"get",
"(",
"\"type\"",
",",
"\"\"",
")",
".",
"lower",
"(",
")",
"in",
"(",
"\"\"",
",",
"\"text/css\"",
")",
"and",
"(",
"not",
"media",
"or",
"\"all\"",
"in",
"media",
"or",
"\"print\"",
"in",
"media",
"or",
"\"pdf\"",
"in",
"media",
")",
":",
"if",
"name",
"==",
"\"style\"",
":",
"for",
"node",
"in",
"node",
".",
"childNodes",
":",
"data",
"+=",
"pisaPreLoop",
"(",
"node",
",",
"context",
",",
"collect",
"=",
"True",
")",
"context",
".",
"addCSS",
"(",
"data",
")",
"return",
"u\"\"",
"if",
"name",
"==",
"\"link\"",
"and",
"attr",
".",
"href",
"and",
"attr",
".",
"rel",
".",
"lower",
"(",
")",
"==",
"\"stylesheet\"",
":",
"# print \"CSS LINK\", attr",
"context",
".",
"addCSS",
"(",
"'\\n@import \"%s\" %s;'",
"%",
"(",
"attr",
".",
"href",
",",
"\",\"",
".",
"join",
"(",
"media",
")",
")",
")",
"for",
"node",
"in",
"node",
".",
"childNodes",
":",
"result",
"=",
"pisaPreLoop",
"(",
"node",
",",
"context",
",",
"collect",
"=",
"collect",
")",
"if",
"collect",
":",
"data",
"+=",
"result",
"return",
"data"
]
| Collect all CSS definitions | [
"Collect",
"all",
"CSS",
"definitions"
]
| 230357a392f48816532d3c2fa082a680b80ece48 | https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/parser.py#L440-L476 | train |
xhtml2pdf/xhtml2pdf | xhtml2pdf/parser.py | pisaParser | def pisaParser(src, context, default_css="", xhtml=False, encoding=None, xml_output=None):
"""
- Parse HTML and get miniDOM
- Extract CSS informations, add default CSS, parse CSS
- Handle the document DOM itself and build reportlab story
- Return Context object
"""
global CSSAttrCache
CSSAttrCache = {}
if xhtml:
# TODO: XHTMLParser doesn't see to exist...
parser = html5lib.XHTMLParser(tree=treebuilders.getTreeBuilder("dom"))
else:
parser = html5lib.HTMLParser(tree=treebuilders.getTreeBuilder("dom"))
if isinstance(src, six.text_type):
# If an encoding was provided, do not change it.
if not encoding:
encoding = "utf-8"
src = src.encode(encoding)
src = pisaTempFile(src, capacity=context.capacity)
# # Test for the restrictions of html5lib
# if encoding:
# # Workaround for html5lib<0.11.1
# if hasattr(inputstream, "isValidEncoding"):
# if encoding.strip().lower() == "utf8":
# encoding = "utf-8"
# if not inputstream.isValidEncoding(encoding):
# log.error("%r is not a valid encoding e.g. 'utf8' is not valid but 'utf-8' is!", encoding)
# else:
# if inputstream.codecName(encoding) is None:
# log.error("%r is not a valid encoding", encoding)
document = parser.parse(
src,
) # encoding=encoding)
if xml_output:
if encoding:
xml_output.write(document.toprettyxml(encoding=encoding))
else:
xml_output.write(document.toprettyxml(encoding="utf8"))
if default_css:
context.addDefaultCSS(default_css)
pisaPreLoop(document, context)
# try:
context.parseCSS()
# except:
# context.cssText = DEFAULT_CSS
# context.parseCSS()
# context.debug(9, pprint.pformat(context.css))
pisaLoop(document, context)
return context | python | def pisaParser(src, context, default_css="", xhtml=False, encoding=None, xml_output=None):
"""
- Parse HTML and get miniDOM
- Extract CSS informations, add default CSS, parse CSS
- Handle the document DOM itself and build reportlab story
- Return Context object
"""
global CSSAttrCache
CSSAttrCache = {}
if xhtml:
# TODO: XHTMLParser doesn't see to exist...
parser = html5lib.XHTMLParser(tree=treebuilders.getTreeBuilder("dom"))
else:
parser = html5lib.HTMLParser(tree=treebuilders.getTreeBuilder("dom"))
if isinstance(src, six.text_type):
# If an encoding was provided, do not change it.
if not encoding:
encoding = "utf-8"
src = src.encode(encoding)
src = pisaTempFile(src, capacity=context.capacity)
# # Test for the restrictions of html5lib
# if encoding:
# # Workaround for html5lib<0.11.1
# if hasattr(inputstream, "isValidEncoding"):
# if encoding.strip().lower() == "utf8":
# encoding = "utf-8"
# if not inputstream.isValidEncoding(encoding):
# log.error("%r is not a valid encoding e.g. 'utf8' is not valid but 'utf-8' is!", encoding)
# else:
# if inputstream.codecName(encoding) is None:
# log.error("%r is not a valid encoding", encoding)
document = parser.parse(
src,
) # encoding=encoding)
if xml_output:
if encoding:
xml_output.write(document.toprettyxml(encoding=encoding))
else:
xml_output.write(document.toprettyxml(encoding="utf8"))
if default_css:
context.addDefaultCSS(default_css)
pisaPreLoop(document, context)
# try:
context.parseCSS()
# except:
# context.cssText = DEFAULT_CSS
# context.parseCSS()
# context.debug(9, pprint.pformat(context.css))
pisaLoop(document, context)
return context | [
"def",
"pisaParser",
"(",
"src",
",",
"context",
",",
"default_css",
"=",
"\"\"",
",",
"xhtml",
"=",
"False",
",",
"encoding",
"=",
"None",
",",
"xml_output",
"=",
"None",
")",
":",
"global",
"CSSAttrCache",
"CSSAttrCache",
"=",
"{",
"}",
"if",
"xhtml",
":",
"# TODO: XHTMLParser doesn't see to exist...",
"parser",
"=",
"html5lib",
".",
"XHTMLParser",
"(",
"tree",
"=",
"treebuilders",
".",
"getTreeBuilder",
"(",
"\"dom\"",
")",
")",
"else",
":",
"parser",
"=",
"html5lib",
".",
"HTMLParser",
"(",
"tree",
"=",
"treebuilders",
".",
"getTreeBuilder",
"(",
"\"dom\"",
")",
")",
"if",
"isinstance",
"(",
"src",
",",
"six",
".",
"text_type",
")",
":",
"# If an encoding was provided, do not change it.",
"if",
"not",
"encoding",
":",
"encoding",
"=",
"\"utf-8\"",
"src",
"=",
"src",
".",
"encode",
"(",
"encoding",
")",
"src",
"=",
"pisaTempFile",
"(",
"src",
",",
"capacity",
"=",
"context",
".",
"capacity",
")",
"# # Test for the restrictions of html5lib",
"# if encoding:",
"# # Workaround for html5lib<0.11.1",
"# if hasattr(inputstream, \"isValidEncoding\"):",
"# if encoding.strip().lower() == \"utf8\":",
"# encoding = \"utf-8\"",
"# if not inputstream.isValidEncoding(encoding):",
"# log.error(\"%r is not a valid encoding e.g. 'utf8' is not valid but 'utf-8' is!\", encoding)",
"# else:",
"# if inputstream.codecName(encoding) is None:",
"# log.error(\"%r is not a valid encoding\", encoding)",
"document",
"=",
"parser",
".",
"parse",
"(",
"src",
",",
")",
"# encoding=encoding)",
"if",
"xml_output",
":",
"if",
"encoding",
":",
"xml_output",
".",
"write",
"(",
"document",
".",
"toprettyxml",
"(",
"encoding",
"=",
"encoding",
")",
")",
"else",
":",
"xml_output",
".",
"write",
"(",
"document",
".",
"toprettyxml",
"(",
"encoding",
"=",
"\"utf8\"",
")",
")",
"if",
"default_css",
":",
"context",
".",
"addDefaultCSS",
"(",
"default_css",
")",
"pisaPreLoop",
"(",
"document",
",",
"context",
")",
"# try:",
"context",
".",
"parseCSS",
"(",
")",
"# except:",
"# context.cssText = DEFAULT_CSS",
"# context.parseCSS()",
"# context.debug(9, pprint.pformat(context.css))",
"pisaLoop",
"(",
"document",
",",
"context",
")",
"return",
"context"
]
| - Parse HTML and get miniDOM
- Extract CSS informations, add default CSS, parse CSS
- Handle the document DOM itself and build reportlab story
- Return Context object | [
"-",
"Parse",
"HTML",
"and",
"get",
"miniDOM",
"-",
"Extract",
"CSS",
"informations",
"add",
"default",
"CSS",
"parse",
"CSS",
"-",
"Handle",
"the",
"document",
"DOM",
"itself",
"and",
"build",
"reportlab",
"story",
"-",
"Return",
"Context",
"object"
]
| 230357a392f48816532d3c2fa082a680b80ece48 | https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/parser.py#L703-L760 | train |
xhtml2pdf/xhtml2pdf | xhtml2pdf/paragraph.py | Line.doLayout | def doLayout(self, width):
"""
Align words in previous line.
"""
# Calculate dimensions
self.width = width
font_sizes = [0] + [frag.get("fontSize", 0) for frag in self]
self.fontSize = max(font_sizes)
self.height = self.lineHeight = max(frag * self.LINEHEIGHT for frag in font_sizes)
# Apply line height
y = (self.lineHeight - self.fontSize) # / 2
for frag in self:
frag["y"] = y
return self.height | python | def doLayout(self, width):
"""
Align words in previous line.
"""
# Calculate dimensions
self.width = width
font_sizes = [0] + [frag.get("fontSize", 0) for frag in self]
self.fontSize = max(font_sizes)
self.height = self.lineHeight = max(frag * self.LINEHEIGHT for frag in font_sizes)
# Apply line height
y = (self.lineHeight - self.fontSize) # / 2
for frag in self:
frag["y"] = y
return self.height | [
"def",
"doLayout",
"(",
"self",
",",
"width",
")",
":",
"# Calculate dimensions",
"self",
".",
"width",
"=",
"width",
"font_sizes",
"=",
"[",
"0",
"]",
"+",
"[",
"frag",
".",
"get",
"(",
"\"fontSize\"",
",",
"0",
")",
"for",
"frag",
"in",
"self",
"]",
"self",
".",
"fontSize",
"=",
"max",
"(",
"font_sizes",
")",
"self",
".",
"height",
"=",
"self",
".",
"lineHeight",
"=",
"max",
"(",
"frag",
"*",
"self",
".",
"LINEHEIGHT",
"for",
"frag",
"in",
"font_sizes",
")",
"# Apply line height",
"y",
"=",
"(",
"self",
".",
"lineHeight",
"-",
"self",
".",
"fontSize",
")",
"# / 2",
"for",
"frag",
"in",
"self",
":",
"frag",
"[",
"\"y\"",
"]",
"=",
"y",
"return",
"self",
".",
"height"
]
| Align words in previous line. | [
"Align",
"words",
"in",
"previous",
"line",
"."
]
| 230357a392f48816532d3c2fa082a680b80ece48 | https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/paragraph.py#L276-L293 | train |
xhtml2pdf/xhtml2pdf | xhtml2pdf/paragraph.py | Text.splitIntoLines | def splitIntoLines(self, maxWidth, maxHeight, splitted=False):
"""
Split text into lines and calculate X positions. If we need more
space in height than available we return the rest of the text
"""
self.lines = []
self.height = 0
self.maxWidth = self.width = maxWidth
self.maxHeight = maxHeight
boxStack = []
style = self.style
x = 0
# Start with indent in first line of text
if not splitted:
x = style["textIndent"]
lenText = len(self)
pos = 0
while pos < lenText:
# Reset values for new line
posBegin = pos
line = Line(style)
# Update boxes for next line
for box in copy.copy(boxStack):
box["x"] = 0
line.append(BoxBegin(box))
while pos < lenText:
# Get fragment, its width and set X
frag = self[pos]
fragWidth = frag["width"]
frag["x"] = x
pos += 1
# Keep in mind boxes for next lines
if isinstance(frag, BoxBegin):
boxStack.append(frag)
elif isinstance(frag, BoxEnd):
boxStack.pop()
# If space or linebreak handle special way
if frag.isSoft:
if frag.isLF:
line.append(frag)
break
# First element of line should not be a space
if x == 0:
continue
# Keep in mind last possible line break
# The elements exceed the current line
elif fragWidth + x > maxWidth:
break
# Add fragment to line and update x
x += fragWidth
line.append(frag)
# Remove trailing white spaces
while line and line[-1].name in ("space", "br"):
line.pop()
# Add line to list
line.dumpFragments()
# if line:
self.height += line.doLayout(self.width)
self.lines.append(line)
# If not enough space for current line force to split
if self.height > maxHeight:
return posBegin
# Reset variables
x = 0
# Apply alignment
self.lines[- 1].isLast = True
for line in self.lines:
line.doAlignment(maxWidth, style["textAlign"])
return None | python | def splitIntoLines(self, maxWidth, maxHeight, splitted=False):
"""
Split text into lines and calculate X positions. If we need more
space in height than available we return the rest of the text
"""
self.lines = []
self.height = 0
self.maxWidth = self.width = maxWidth
self.maxHeight = maxHeight
boxStack = []
style = self.style
x = 0
# Start with indent in first line of text
if not splitted:
x = style["textIndent"]
lenText = len(self)
pos = 0
while pos < lenText:
# Reset values for new line
posBegin = pos
line = Line(style)
# Update boxes for next line
for box in copy.copy(boxStack):
box["x"] = 0
line.append(BoxBegin(box))
while pos < lenText:
# Get fragment, its width and set X
frag = self[pos]
fragWidth = frag["width"]
frag["x"] = x
pos += 1
# Keep in mind boxes for next lines
if isinstance(frag, BoxBegin):
boxStack.append(frag)
elif isinstance(frag, BoxEnd):
boxStack.pop()
# If space or linebreak handle special way
if frag.isSoft:
if frag.isLF:
line.append(frag)
break
# First element of line should not be a space
if x == 0:
continue
# Keep in mind last possible line break
# The elements exceed the current line
elif fragWidth + x > maxWidth:
break
# Add fragment to line and update x
x += fragWidth
line.append(frag)
# Remove trailing white spaces
while line and line[-1].name in ("space", "br"):
line.pop()
# Add line to list
line.dumpFragments()
# if line:
self.height += line.doLayout(self.width)
self.lines.append(line)
# If not enough space for current line force to split
if self.height > maxHeight:
return posBegin
# Reset variables
x = 0
# Apply alignment
self.lines[- 1].isLast = True
for line in self.lines:
line.doAlignment(maxWidth, style["textAlign"])
return None | [
"def",
"splitIntoLines",
"(",
"self",
",",
"maxWidth",
",",
"maxHeight",
",",
"splitted",
"=",
"False",
")",
":",
"self",
".",
"lines",
"=",
"[",
"]",
"self",
".",
"height",
"=",
"0",
"self",
".",
"maxWidth",
"=",
"self",
".",
"width",
"=",
"maxWidth",
"self",
".",
"maxHeight",
"=",
"maxHeight",
"boxStack",
"=",
"[",
"]",
"style",
"=",
"self",
".",
"style",
"x",
"=",
"0",
"# Start with indent in first line of text",
"if",
"not",
"splitted",
":",
"x",
"=",
"style",
"[",
"\"textIndent\"",
"]",
"lenText",
"=",
"len",
"(",
"self",
")",
"pos",
"=",
"0",
"while",
"pos",
"<",
"lenText",
":",
"# Reset values for new line",
"posBegin",
"=",
"pos",
"line",
"=",
"Line",
"(",
"style",
")",
"# Update boxes for next line",
"for",
"box",
"in",
"copy",
".",
"copy",
"(",
"boxStack",
")",
":",
"box",
"[",
"\"x\"",
"]",
"=",
"0",
"line",
".",
"append",
"(",
"BoxBegin",
"(",
"box",
")",
")",
"while",
"pos",
"<",
"lenText",
":",
"# Get fragment, its width and set X",
"frag",
"=",
"self",
"[",
"pos",
"]",
"fragWidth",
"=",
"frag",
"[",
"\"width\"",
"]",
"frag",
"[",
"\"x\"",
"]",
"=",
"x",
"pos",
"+=",
"1",
"# Keep in mind boxes for next lines",
"if",
"isinstance",
"(",
"frag",
",",
"BoxBegin",
")",
":",
"boxStack",
".",
"append",
"(",
"frag",
")",
"elif",
"isinstance",
"(",
"frag",
",",
"BoxEnd",
")",
":",
"boxStack",
".",
"pop",
"(",
")",
"# If space or linebreak handle special way",
"if",
"frag",
".",
"isSoft",
":",
"if",
"frag",
".",
"isLF",
":",
"line",
".",
"append",
"(",
"frag",
")",
"break",
"# First element of line should not be a space",
"if",
"x",
"==",
"0",
":",
"continue",
"# Keep in mind last possible line break",
"# The elements exceed the current line",
"elif",
"fragWidth",
"+",
"x",
">",
"maxWidth",
":",
"break",
"# Add fragment to line and update x",
"x",
"+=",
"fragWidth",
"line",
".",
"append",
"(",
"frag",
")",
"# Remove trailing white spaces",
"while",
"line",
"and",
"line",
"[",
"-",
"1",
"]",
".",
"name",
"in",
"(",
"\"space\"",
",",
"\"br\"",
")",
":",
"line",
".",
"pop",
"(",
")",
"# Add line to list",
"line",
".",
"dumpFragments",
"(",
")",
"# if line:",
"self",
".",
"height",
"+=",
"line",
".",
"doLayout",
"(",
"self",
".",
"width",
")",
"self",
".",
"lines",
".",
"append",
"(",
"line",
")",
"# If not enough space for current line force to split",
"if",
"self",
".",
"height",
">",
"maxHeight",
":",
"return",
"posBegin",
"# Reset variables",
"x",
"=",
"0",
"# Apply alignment",
"self",
".",
"lines",
"[",
"-",
"1",
"]",
".",
"isLast",
"=",
"True",
"for",
"line",
"in",
"self",
".",
"lines",
":",
"line",
".",
"doAlignment",
"(",
"maxWidth",
",",
"style",
"[",
"\"textAlign\"",
"]",
")",
"return",
"None"
]
| Split text into lines and calculate X positions. If we need more
space in height than available we return the rest of the text | [
"Split",
"text",
"into",
"lines",
"and",
"calculate",
"X",
"positions",
".",
"If",
"we",
"need",
"more",
"space",
"in",
"height",
"than",
"available",
"we",
"return",
"the",
"rest",
"of",
"the",
"text"
]
| 230357a392f48816532d3c2fa082a680b80ece48 | https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/paragraph.py#L330-L415 | train |
xhtml2pdf/xhtml2pdf | xhtml2pdf/paragraph.py | Text.dumpLines | def dumpLines(self):
"""
For debugging dump all line and their content
"""
for i, line in enumerate(self.lines):
logger.debug("Line %d:", i)
logger.debug(line.dumpFragments()) | python | def dumpLines(self):
"""
For debugging dump all line and their content
"""
for i, line in enumerate(self.lines):
logger.debug("Line %d:", i)
logger.debug(line.dumpFragments()) | [
"def",
"dumpLines",
"(",
"self",
")",
":",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"self",
".",
"lines",
")",
":",
"logger",
".",
"debug",
"(",
"\"Line %d:\"",
",",
"i",
")",
"logger",
".",
"debug",
"(",
"line",
".",
"dumpFragments",
"(",
")",
")"
]
| For debugging dump all line and their content | [
"For",
"debugging",
"dump",
"all",
"line",
"and",
"their",
"content"
]
| 230357a392f48816532d3c2fa082a680b80ece48 | https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/paragraph.py#L417-L423 | train |
xhtml2pdf/xhtml2pdf | xhtml2pdf/paragraph.py | Paragraph.wrap | def wrap(self, availWidth, availHeight):
"""
Determine the rectangle this paragraph really needs.
"""
# memorize available space
self.avWidth = availWidth
self.avHeight = availHeight
logger.debug("*** wrap (%f, %f)", availWidth, availHeight)
if not self.text:
logger.debug("*** wrap (%f, %f) needed", 0, 0)
return 0, 0
# Split lines
width = availWidth
self.splitIndex = self.text.splitIntoLines(width, availHeight)
self.width, self.height = availWidth, self.text.height
logger.debug("*** wrap (%f, %f) needed, splitIndex %r", self.width, self.height, self.splitIndex)
return self.width, self.height | python | def wrap(self, availWidth, availHeight):
"""
Determine the rectangle this paragraph really needs.
"""
# memorize available space
self.avWidth = availWidth
self.avHeight = availHeight
logger.debug("*** wrap (%f, %f)", availWidth, availHeight)
if not self.text:
logger.debug("*** wrap (%f, %f) needed", 0, 0)
return 0, 0
# Split lines
width = availWidth
self.splitIndex = self.text.splitIntoLines(width, availHeight)
self.width, self.height = availWidth, self.text.height
logger.debug("*** wrap (%f, %f) needed, splitIndex %r", self.width, self.height, self.splitIndex)
return self.width, self.height | [
"def",
"wrap",
"(",
"self",
",",
"availWidth",
",",
"availHeight",
")",
":",
"# memorize available space",
"self",
".",
"avWidth",
"=",
"availWidth",
"self",
".",
"avHeight",
"=",
"availHeight",
"logger",
".",
"debug",
"(",
"\"*** wrap (%f, %f)\"",
",",
"availWidth",
",",
"availHeight",
")",
"if",
"not",
"self",
".",
"text",
":",
"logger",
".",
"debug",
"(",
"\"*** wrap (%f, %f) needed\"",
",",
"0",
",",
"0",
")",
"return",
"0",
",",
"0",
"# Split lines",
"width",
"=",
"availWidth",
"self",
".",
"splitIndex",
"=",
"self",
".",
"text",
".",
"splitIntoLines",
"(",
"width",
",",
"availHeight",
")",
"self",
".",
"width",
",",
"self",
".",
"height",
"=",
"availWidth",
",",
"self",
".",
"text",
".",
"height",
"logger",
".",
"debug",
"(",
"\"*** wrap (%f, %f) needed, splitIndex %r\"",
",",
"self",
".",
"width",
",",
"self",
".",
"height",
",",
"self",
".",
"splitIndex",
")",
"return",
"self",
".",
"width",
",",
"self",
".",
"height"
]
| Determine the rectangle this paragraph really needs. | [
"Determine",
"the",
"rectangle",
"this",
"paragraph",
"really",
"needs",
"."
]
| 230357a392f48816532d3c2fa082a680b80ece48 | https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/paragraph.py#L458-L481 | train |
xhtml2pdf/xhtml2pdf | xhtml2pdf/paragraph.py | Paragraph.split | def split(self, availWidth, availHeight):
"""
Split ourselves in two paragraphs.
"""
logger.debug("*** split (%f, %f)", availWidth, availHeight)
splitted = []
if self.splitIndex:
text1 = self.text[:self.splitIndex]
text2 = self.text[self.splitIndex:]
p1 = Paragraph(Text(text1), self.style, debug=self.debug)
p2 = Paragraph(Text(text2), self.style, debug=self.debug, splitted=True)
splitted = [p1, p2]
logger.debug("*** text1 %s / text %s", len(text1), len(text2))
logger.debug('*** return %s', self.splitted)
return splitted | python | def split(self, availWidth, availHeight):
"""
Split ourselves in two paragraphs.
"""
logger.debug("*** split (%f, %f)", availWidth, availHeight)
splitted = []
if self.splitIndex:
text1 = self.text[:self.splitIndex]
text2 = self.text[self.splitIndex:]
p1 = Paragraph(Text(text1), self.style, debug=self.debug)
p2 = Paragraph(Text(text2), self.style, debug=self.debug, splitted=True)
splitted = [p1, p2]
logger.debug("*** text1 %s / text %s", len(text1), len(text2))
logger.debug('*** return %s', self.splitted)
return splitted | [
"def",
"split",
"(",
"self",
",",
"availWidth",
",",
"availHeight",
")",
":",
"logger",
".",
"debug",
"(",
"\"*** split (%f, %f)\"",
",",
"availWidth",
",",
"availHeight",
")",
"splitted",
"=",
"[",
"]",
"if",
"self",
".",
"splitIndex",
":",
"text1",
"=",
"self",
".",
"text",
"[",
":",
"self",
".",
"splitIndex",
"]",
"text2",
"=",
"self",
".",
"text",
"[",
"self",
".",
"splitIndex",
":",
"]",
"p1",
"=",
"Paragraph",
"(",
"Text",
"(",
"text1",
")",
",",
"self",
".",
"style",
",",
"debug",
"=",
"self",
".",
"debug",
")",
"p2",
"=",
"Paragraph",
"(",
"Text",
"(",
"text2",
")",
",",
"self",
".",
"style",
",",
"debug",
"=",
"self",
".",
"debug",
",",
"splitted",
"=",
"True",
")",
"splitted",
"=",
"[",
"p1",
",",
"p2",
"]",
"logger",
".",
"debug",
"(",
"\"*** text1 %s / text %s\"",
",",
"len",
"(",
"text1",
")",
",",
"len",
"(",
"text2",
")",
")",
"logger",
".",
"debug",
"(",
"'*** return %s'",
",",
"self",
".",
"splitted",
")",
"return",
"splitted"
]
| Split ourselves in two paragraphs. | [
"Split",
"ourselves",
"in",
"two",
"paragraphs",
"."
]
| 230357a392f48816532d3c2fa082a680b80ece48 | https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/paragraph.py#L483-L502 | train |
xhtml2pdf/xhtml2pdf | xhtml2pdf/paragraph.py | Paragraph.draw | def draw(self):
"""
Render the content of the paragraph.
"""
logger.debug("*** draw")
if not self.text:
return
canvas = self.canv
style = self.style
canvas.saveState()
# Draw box arround paragraph for debugging
if self.debug:
bw = 0.5
bc = Color(1, 1, 0)
bg = Color(0.9, 0.9, 0.9)
canvas.setStrokeColor(bc)
canvas.setLineWidth(bw)
canvas.setFillColor(bg)
canvas.rect(
style.leftIndent,
0,
self.width,
self.height,
fill=1,
stroke=1)
y = 0
dy = self.height
for line in self.text.lines:
y += line.height
for frag in line:
# Box
if hasattr(frag, "draw"):
frag.draw(canvas, dy - y)
# Text
if frag.get("text", ""):
canvas.setFont(frag["fontName"], frag["fontSize"])
canvas.setFillColor(frag.get("color", style["color"]))
canvas.drawString(frag["x"], dy - y + frag["y"], frag["text"])
# XXX LINK
link = frag.get("link", None)
if link:
_scheme_re = re.compile('^[a-zA-Z][-+a-zA-Z0-9]+$')
x, y, w, h = frag["x"], dy - y, frag["width"], frag["fontSize"]
rect = (x, y, w, h)
if isinstance(link, six.text_type):
link = link.encode('utf8')
parts = link.split(':', 1)
scheme = len(parts) == 2 and parts[0].lower() or ''
if _scheme_re.match(scheme) and scheme != 'document':
kind = scheme.lower() == 'pdf' and 'GoToR' or 'URI'
if kind == 'GoToR':
link = parts[1]
canvas.linkURL(link, rect, relative=1, kind=kind)
else:
if link[0] == '#':
link = link[1:]
scheme = ''
canvas.linkRect("", scheme != 'document' and link or parts[1], rect, relative=1)
canvas.restoreState() | python | def draw(self):
"""
Render the content of the paragraph.
"""
logger.debug("*** draw")
if not self.text:
return
canvas = self.canv
style = self.style
canvas.saveState()
# Draw box arround paragraph for debugging
if self.debug:
bw = 0.5
bc = Color(1, 1, 0)
bg = Color(0.9, 0.9, 0.9)
canvas.setStrokeColor(bc)
canvas.setLineWidth(bw)
canvas.setFillColor(bg)
canvas.rect(
style.leftIndent,
0,
self.width,
self.height,
fill=1,
stroke=1)
y = 0
dy = self.height
for line in self.text.lines:
y += line.height
for frag in line:
# Box
if hasattr(frag, "draw"):
frag.draw(canvas, dy - y)
# Text
if frag.get("text", ""):
canvas.setFont(frag["fontName"], frag["fontSize"])
canvas.setFillColor(frag.get("color", style["color"]))
canvas.drawString(frag["x"], dy - y + frag["y"], frag["text"])
# XXX LINK
link = frag.get("link", None)
if link:
_scheme_re = re.compile('^[a-zA-Z][-+a-zA-Z0-9]+$')
x, y, w, h = frag["x"], dy - y, frag["width"], frag["fontSize"]
rect = (x, y, w, h)
if isinstance(link, six.text_type):
link = link.encode('utf8')
parts = link.split(':', 1)
scheme = len(parts) == 2 and parts[0].lower() or ''
if _scheme_re.match(scheme) and scheme != 'document':
kind = scheme.lower() == 'pdf' and 'GoToR' or 'URI'
if kind == 'GoToR':
link = parts[1]
canvas.linkURL(link, rect, relative=1, kind=kind)
else:
if link[0] == '#':
link = link[1:]
scheme = ''
canvas.linkRect("", scheme != 'document' and link or parts[1], rect, relative=1)
canvas.restoreState() | [
"def",
"draw",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"*** draw\"",
")",
"if",
"not",
"self",
".",
"text",
":",
"return",
"canvas",
"=",
"self",
".",
"canv",
"style",
"=",
"self",
".",
"style",
"canvas",
".",
"saveState",
"(",
")",
"# Draw box arround paragraph for debugging",
"if",
"self",
".",
"debug",
":",
"bw",
"=",
"0.5",
"bc",
"=",
"Color",
"(",
"1",
",",
"1",
",",
"0",
")",
"bg",
"=",
"Color",
"(",
"0.9",
",",
"0.9",
",",
"0.9",
")",
"canvas",
".",
"setStrokeColor",
"(",
"bc",
")",
"canvas",
".",
"setLineWidth",
"(",
"bw",
")",
"canvas",
".",
"setFillColor",
"(",
"bg",
")",
"canvas",
".",
"rect",
"(",
"style",
".",
"leftIndent",
",",
"0",
",",
"self",
".",
"width",
",",
"self",
".",
"height",
",",
"fill",
"=",
"1",
",",
"stroke",
"=",
"1",
")",
"y",
"=",
"0",
"dy",
"=",
"self",
".",
"height",
"for",
"line",
"in",
"self",
".",
"text",
".",
"lines",
":",
"y",
"+=",
"line",
".",
"height",
"for",
"frag",
"in",
"line",
":",
"# Box",
"if",
"hasattr",
"(",
"frag",
",",
"\"draw\"",
")",
":",
"frag",
".",
"draw",
"(",
"canvas",
",",
"dy",
"-",
"y",
")",
"# Text",
"if",
"frag",
".",
"get",
"(",
"\"text\"",
",",
"\"\"",
")",
":",
"canvas",
".",
"setFont",
"(",
"frag",
"[",
"\"fontName\"",
"]",
",",
"frag",
"[",
"\"fontSize\"",
"]",
")",
"canvas",
".",
"setFillColor",
"(",
"frag",
".",
"get",
"(",
"\"color\"",
",",
"style",
"[",
"\"color\"",
"]",
")",
")",
"canvas",
".",
"drawString",
"(",
"frag",
"[",
"\"x\"",
"]",
",",
"dy",
"-",
"y",
"+",
"frag",
"[",
"\"y\"",
"]",
",",
"frag",
"[",
"\"text\"",
"]",
")",
"# XXX LINK",
"link",
"=",
"frag",
".",
"get",
"(",
"\"link\"",
",",
"None",
")",
"if",
"link",
":",
"_scheme_re",
"=",
"re",
".",
"compile",
"(",
"'^[a-zA-Z][-+a-zA-Z0-9]+$'",
")",
"x",
",",
"y",
",",
"w",
",",
"h",
"=",
"frag",
"[",
"\"x\"",
"]",
",",
"dy",
"-",
"y",
",",
"frag",
"[",
"\"width\"",
"]",
",",
"frag",
"[",
"\"fontSize\"",
"]",
"rect",
"=",
"(",
"x",
",",
"y",
",",
"w",
",",
"h",
")",
"if",
"isinstance",
"(",
"link",
",",
"six",
".",
"text_type",
")",
":",
"link",
"=",
"link",
".",
"encode",
"(",
"'utf8'",
")",
"parts",
"=",
"link",
".",
"split",
"(",
"':'",
",",
"1",
")",
"scheme",
"=",
"len",
"(",
"parts",
")",
"==",
"2",
"and",
"parts",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"or",
"''",
"if",
"_scheme_re",
".",
"match",
"(",
"scheme",
")",
"and",
"scheme",
"!=",
"'document'",
":",
"kind",
"=",
"scheme",
".",
"lower",
"(",
")",
"==",
"'pdf'",
"and",
"'GoToR'",
"or",
"'URI'",
"if",
"kind",
"==",
"'GoToR'",
":",
"link",
"=",
"parts",
"[",
"1",
"]",
"canvas",
".",
"linkURL",
"(",
"link",
",",
"rect",
",",
"relative",
"=",
"1",
",",
"kind",
"=",
"kind",
")",
"else",
":",
"if",
"link",
"[",
"0",
"]",
"==",
"'#'",
":",
"link",
"=",
"link",
"[",
"1",
":",
"]",
"scheme",
"=",
"''",
"canvas",
".",
"linkRect",
"(",
"\"\"",
",",
"scheme",
"!=",
"'document'",
"and",
"link",
"or",
"parts",
"[",
"1",
"]",
",",
"rect",
",",
"relative",
"=",
"1",
")",
"canvas",
".",
"restoreState",
"(",
")"
]
| Render the content of the paragraph. | [
"Render",
"the",
"content",
"of",
"the",
"paragraph",
"."
]
| 230357a392f48816532d3c2fa082a680b80ece48 | https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/paragraph.py#L504-L573 | train |
xhtml2pdf/xhtml2pdf | xhtml2pdf/pisa.py | showLogging | def showLogging(debug=False):
"""
Shortcut for enabling log dump
"""
try:
log_level = logging.WARN
log_format = LOG_FORMAT_DEBUG
if debug:
log_level = logging.DEBUG
logging.basicConfig(
level=log_level,
format=log_format)
except:
logging.basicConfig() | python | def showLogging(debug=False):
"""
Shortcut for enabling log dump
"""
try:
log_level = logging.WARN
log_format = LOG_FORMAT_DEBUG
if debug:
log_level = logging.DEBUG
logging.basicConfig(
level=log_level,
format=log_format)
except:
logging.basicConfig() | [
"def",
"showLogging",
"(",
"debug",
"=",
"False",
")",
":",
"try",
":",
"log_level",
"=",
"logging",
".",
"WARN",
"log_format",
"=",
"LOG_FORMAT_DEBUG",
"if",
"debug",
":",
"log_level",
"=",
"logging",
".",
"DEBUG",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"log_level",
",",
"format",
"=",
"log_format",
")",
"except",
":",
"logging",
".",
"basicConfig",
"(",
")"
]
| Shortcut for enabling log dump | [
"Shortcut",
"for",
"enabling",
"log",
"dump"
]
| 230357a392f48816532d3c2fa082a680b80ece48 | https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/pisa.py#L420-L434 | train |
xhtml2pdf/xhtml2pdf | xhtml2pdf/w3c/cssParser.py | CSSParser.parseFile | def parseFile(self, srcFile, closeFile=False):
"""Parses CSS file-like objects using the current cssBuilder.
Use for external stylesheets."""
try:
result = self.parse(srcFile.read())
finally:
if closeFile:
srcFile.close()
return result | python | def parseFile(self, srcFile, closeFile=False):
"""Parses CSS file-like objects using the current cssBuilder.
Use for external stylesheets."""
try:
result = self.parse(srcFile.read())
finally:
if closeFile:
srcFile.close()
return result | [
"def",
"parseFile",
"(",
"self",
",",
"srcFile",
",",
"closeFile",
"=",
"False",
")",
":",
"try",
":",
"result",
"=",
"self",
".",
"parse",
"(",
"srcFile",
".",
"read",
"(",
")",
")",
"finally",
":",
"if",
"closeFile",
":",
"srcFile",
".",
"close",
"(",
")",
"return",
"result"
]
| Parses CSS file-like objects using the current cssBuilder.
Use for external stylesheets. | [
"Parses",
"CSS",
"file",
"-",
"like",
"objects",
"using",
"the",
"current",
"cssBuilder",
".",
"Use",
"for",
"external",
"stylesheets",
"."
]
| 230357a392f48816532d3c2fa082a680b80ece48 | https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/w3c/cssParser.py#L427-L436 | train |
xhtml2pdf/xhtml2pdf | xhtml2pdf/w3c/cssParser.py | CSSParser.parse | def parse(self, src):
"""Parses CSS string source using the current cssBuilder.
Use for embedded stylesheets."""
self.cssBuilder.beginStylesheet()
try:
# XXX Some simple preprocessing
src = cssSpecial.cleanupCSS(src)
try:
src, stylesheet = self._parseStylesheet(src)
except self.ParseError as err:
err.setFullCSSSource(src)
raise
finally:
self.cssBuilder.endStylesheet()
return stylesheet | python | def parse(self, src):
"""Parses CSS string source using the current cssBuilder.
Use for embedded stylesheets."""
self.cssBuilder.beginStylesheet()
try:
# XXX Some simple preprocessing
src = cssSpecial.cleanupCSS(src)
try:
src, stylesheet = self._parseStylesheet(src)
except self.ParseError as err:
err.setFullCSSSource(src)
raise
finally:
self.cssBuilder.endStylesheet()
return stylesheet | [
"def",
"parse",
"(",
"self",
",",
"src",
")",
":",
"self",
".",
"cssBuilder",
".",
"beginStylesheet",
"(",
")",
"try",
":",
"# XXX Some simple preprocessing",
"src",
"=",
"cssSpecial",
".",
"cleanupCSS",
"(",
"src",
")",
"try",
":",
"src",
",",
"stylesheet",
"=",
"self",
".",
"_parseStylesheet",
"(",
"src",
")",
"except",
"self",
".",
"ParseError",
"as",
"err",
":",
"err",
".",
"setFullCSSSource",
"(",
"src",
")",
"raise",
"finally",
":",
"self",
".",
"cssBuilder",
".",
"endStylesheet",
"(",
")",
"return",
"stylesheet"
]
| Parses CSS string source using the current cssBuilder.
Use for embedded stylesheets. | [
"Parses",
"CSS",
"string",
"source",
"using",
"the",
"current",
"cssBuilder",
".",
"Use",
"for",
"embedded",
"stylesheets",
"."
]
| 230357a392f48816532d3c2fa082a680b80ece48 | https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/w3c/cssParser.py#L439-L456 | train |
xhtml2pdf/xhtml2pdf | xhtml2pdf/w3c/cssParser.py | CSSParser.parseInline | def parseInline(self, src):
"""Parses CSS inline source string using the current cssBuilder.
Use to parse a tag's 'sytle'-like attribute."""
self.cssBuilder.beginInline()
try:
try:
src, properties = self._parseDeclarationGroup(src.strip(), braces=False)
except self.ParseError as err:
err.setFullCSSSource(src, inline=True)
raise
result = self.cssBuilder.inline(properties)
finally:
self.cssBuilder.endInline()
return result | python | def parseInline(self, src):
"""Parses CSS inline source string using the current cssBuilder.
Use to parse a tag's 'sytle'-like attribute."""
self.cssBuilder.beginInline()
try:
try:
src, properties = self._parseDeclarationGroup(src.strip(), braces=False)
except self.ParseError as err:
err.setFullCSSSource(src, inline=True)
raise
result = self.cssBuilder.inline(properties)
finally:
self.cssBuilder.endInline()
return result | [
"def",
"parseInline",
"(",
"self",
",",
"src",
")",
":",
"self",
".",
"cssBuilder",
".",
"beginInline",
"(",
")",
"try",
":",
"try",
":",
"src",
",",
"properties",
"=",
"self",
".",
"_parseDeclarationGroup",
"(",
"src",
".",
"strip",
"(",
")",
",",
"braces",
"=",
"False",
")",
"except",
"self",
".",
"ParseError",
"as",
"err",
":",
"err",
".",
"setFullCSSSource",
"(",
"src",
",",
"inline",
"=",
"True",
")",
"raise",
"result",
"=",
"self",
".",
"cssBuilder",
".",
"inline",
"(",
"properties",
")",
"finally",
":",
"self",
".",
"cssBuilder",
".",
"endInline",
"(",
")",
"return",
"result"
]
| Parses CSS inline source string using the current cssBuilder.
Use to parse a tag's 'sytle'-like attribute. | [
"Parses",
"CSS",
"inline",
"source",
"string",
"using",
"the",
"current",
"cssBuilder",
".",
"Use",
"to",
"parse",
"a",
"tag",
"s",
"sytle",
"-",
"like",
"attribute",
"."
]
| 230357a392f48816532d3c2fa082a680b80ece48 | https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/w3c/cssParser.py#L459-L474 | train |
xhtml2pdf/xhtml2pdf | xhtml2pdf/w3c/cssParser.py | CSSParser.parseAttributes | def parseAttributes(self, attributes=None, **kwAttributes):
"""Parses CSS attribute source strings, and return as an inline stylesheet.
Use to parse a tag's highly CSS-based attributes like 'font'.
See also: parseSingleAttr
"""
attributes = attributes if attributes is not None else {}
if attributes:
kwAttributes.update(attributes)
self.cssBuilder.beginInline()
try:
properties = []
try:
for propertyName, src in six.iteritems(kwAttributes):
src, property = self._parseDeclarationProperty(src.strip(), propertyName)
properties.append(property)
except self.ParseError as err:
err.setFullCSSSource(src, inline=True)
raise
result = self.cssBuilder.inline(properties)
finally:
self.cssBuilder.endInline()
return result | python | def parseAttributes(self, attributes=None, **kwAttributes):
"""Parses CSS attribute source strings, and return as an inline stylesheet.
Use to parse a tag's highly CSS-based attributes like 'font'.
See also: parseSingleAttr
"""
attributes = attributes if attributes is not None else {}
if attributes:
kwAttributes.update(attributes)
self.cssBuilder.beginInline()
try:
properties = []
try:
for propertyName, src in six.iteritems(kwAttributes):
src, property = self._parseDeclarationProperty(src.strip(), propertyName)
properties.append(property)
except self.ParseError as err:
err.setFullCSSSource(src, inline=True)
raise
result = self.cssBuilder.inline(properties)
finally:
self.cssBuilder.endInline()
return result | [
"def",
"parseAttributes",
"(",
"self",
",",
"attributes",
"=",
"None",
",",
"*",
"*",
"kwAttributes",
")",
":",
"attributes",
"=",
"attributes",
"if",
"attributes",
"is",
"not",
"None",
"else",
"{",
"}",
"if",
"attributes",
":",
"kwAttributes",
".",
"update",
"(",
"attributes",
")",
"self",
".",
"cssBuilder",
".",
"beginInline",
"(",
")",
"try",
":",
"properties",
"=",
"[",
"]",
"try",
":",
"for",
"propertyName",
",",
"src",
"in",
"six",
".",
"iteritems",
"(",
"kwAttributes",
")",
":",
"src",
",",
"property",
"=",
"self",
".",
"_parseDeclarationProperty",
"(",
"src",
".",
"strip",
"(",
")",
",",
"propertyName",
")",
"properties",
".",
"append",
"(",
"property",
")",
"except",
"self",
".",
"ParseError",
"as",
"err",
":",
"err",
".",
"setFullCSSSource",
"(",
"src",
",",
"inline",
"=",
"True",
")",
"raise",
"result",
"=",
"self",
".",
"cssBuilder",
".",
"inline",
"(",
"properties",
")",
"finally",
":",
"self",
".",
"cssBuilder",
".",
"endInline",
"(",
")",
"return",
"result"
]
| Parses CSS attribute source strings, and return as an inline stylesheet.
Use to parse a tag's highly CSS-based attributes like 'font'.
See also: parseSingleAttr | [
"Parses",
"CSS",
"attribute",
"source",
"strings",
"and",
"return",
"as",
"an",
"inline",
"stylesheet",
".",
"Use",
"to",
"parse",
"a",
"tag",
"s",
"highly",
"CSS",
"-",
"based",
"attributes",
"like",
"font",
"."
]
| 230357a392f48816532d3c2fa082a680b80ece48 | https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/w3c/cssParser.py#L476-L501 | train |
xhtml2pdf/xhtml2pdf | xhtml2pdf/w3c/cssParser.py | CSSParser.parseSingleAttr | def parseSingleAttr(self, attrValue):
"""Parse a single CSS attribute source string, and returns the built CSS expression.
Use to parse a tag's highly CSS-based attributes like 'font'.
See also: parseAttributes
"""
results = self.parseAttributes(temp=attrValue)
if 'temp' in results[1]:
return results[1]['temp']
else:
return results[0]['temp'] | python | def parseSingleAttr(self, attrValue):
"""Parse a single CSS attribute source string, and returns the built CSS expression.
Use to parse a tag's highly CSS-based attributes like 'font'.
See also: parseAttributes
"""
results = self.parseAttributes(temp=attrValue)
if 'temp' in results[1]:
return results[1]['temp']
else:
return results[0]['temp'] | [
"def",
"parseSingleAttr",
"(",
"self",
",",
"attrValue",
")",
":",
"results",
"=",
"self",
".",
"parseAttributes",
"(",
"temp",
"=",
"attrValue",
")",
"if",
"'temp'",
"in",
"results",
"[",
"1",
"]",
":",
"return",
"results",
"[",
"1",
"]",
"[",
"'temp'",
"]",
"else",
":",
"return",
"results",
"[",
"0",
"]",
"[",
"'temp'",
"]"
]
| Parse a single CSS attribute source string, and returns the built CSS expression.
Use to parse a tag's highly CSS-based attributes like 'font'.
See also: parseAttributes | [
"Parse",
"a",
"single",
"CSS",
"attribute",
"source",
"string",
"and",
"returns",
"the",
"built",
"CSS",
"expression",
".",
"Use",
"to",
"parse",
"a",
"tag",
"s",
"highly",
"CSS",
"-",
"based",
"attributes",
"like",
"font",
"."
]
| 230357a392f48816532d3c2fa082a680b80ece48 | https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/w3c/cssParser.py#L504-L515 | train |
xhtml2pdf/xhtml2pdf | xhtml2pdf/w3c/cssParser.py | CSSParser._parseAtFrame | def _parseAtFrame(self, src):
"""
XXX Proprietary for PDF
"""
src = src[len('@frame '):].lstrip()
box, src = self._getIdent(src)
src, properties = self._parseDeclarationGroup(src.lstrip())
result = [self.cssBuilder.atFrame(box, properties)]
return src.lstrip(), result | python | def _parseAtFrame(self, src):
"""
XXX Proprietary for PDF
"""
src = src[len('@frame '):].lstrip()
box, src = self._getIdent(src)
src, properties = self._parseDeclarationGroup(src.lstrip())
result = [self.cssBuilder.atFrame(box, properties)]
return src.lstrip(), result | [
"def",
"_parseAtFrame",
"(",
"self",
",",
"src",
")",
":",
"src",
"=",
"src",
"[",
"len",
"(",
"'@frame '",
")",
":",
"]",
".",
"lstrip",
"(",
")",
"box",
",",
"src",
"=",
"self",
".",
"_getIdent",
"(",
"src",
")",
"src",
",",
"properties",
"=",
"self",
".",
"_parseDeclarationGroup",
"(",
"src",
".",
"lstrip",
"(",
")",
")",
"result",
"=",
"[",
"self",
".",
"cssBuilder",
".",
"atFrame",
"(",
"box",
",",
"properties",
")",
"]",
"return",
"src",
".",
"lstrip",
"(",
")",
",",
"result"
]
| XXX Proprietary for PDF | [
"XXX",
"Proprietary",
"for",
"PDF"
]
| 230357a392f48816532d3c2fa082a680b80ece48 | https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/w3c/cssParser.py#L788-L796 | train |
xhtml2pdf/xhtml2pdf | xhtml2pdf/util.py | ErrorMsg | def ErrorMsg():
"""
Helper to get a nice traceback as string
"""
import traceback
limit = None
_type, value, tb = sys.exc_info()
_list = traceback.format_tb(tb, limit) + \
traceback.format_exception_only(_type, value)
return "Traceback (innermost last):\n" + "%-20s %s" % (
" ".join(_list[:-1]),
_list[-1]) | python | def ErrorMsg():
"""
Helper to get a nice traceback as string
"""
import traceback
limit = None
_type, value, tb = sys.exc_info()
_list = traceback.format_tb(tb, limit) + \
traceback.format_exception_only(_type, value)
return "Traceback (innermost last):\n" + "%-20s %s" % (
" ".join(_list[:-1]),
_list[-1]) | [
"def",
"ErrorMsg",
"(",
")",
":",
"import",
"traceback",
"limit",
"=",
"None",
"_type",
",",
"value",
",",
"tb",
"=",
"sys",
".",
"exc_info",
"(",
")",
"_list",
"=",
"traceback",
".",
"format_tb",
"(",
"tb",
",",
"limit",
")",
"+",
"traceback",
".",
"format_exception_only",
"(",
"_type",
",",
"value",
")",
"return",
"\"Traceback (innermost last):\\n\"",
"+",
"\"%-20s %s\"",
"%",
"(",
"\" \"",
".",
"join",
"(",
"_list",
"[",
":",
"-",
"1",
"]",
")",
",",
"_list",
"[",
"-",
"1",
"]",
")"
]
| Helper to get a nice traceback as string | [
"Helper",
"to",
"get",
"a",
"nice",
"traceback",
"as",
"string"
]
| 230357a392f48816532d3c2fa082a680b80ece48 | https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/util.py#L119-L131 | train |
xhtml2pdf/xhtml2pdf | xhtml2pdf/util.py | transform_attrs | def transform_attrs(obj, keys, container, func, extras=None):
"""
Allows to apply one function to set of keys cheching if key is in container,
also trasform ccs key to report lab keys.
extras = Are extra params for func, it will be call like func(*[param1, param2])
obj = frag
keys = [(reportlab, css), ... ]
container = cssAttr
"""
cpextras = extras
for reportlab, css in keys:
extras = cpextras
if extras is None:
extras = []
elif not isinstance(extras, list):
extras = [extras]
if css in container:
extras.insert(0, container[css])
setattr(obj,
reportlab,
func(*extras)
) | python | def transform_attrs(obj, keys, container, func, extras=None):
"""
Allows to apply one function to set of keys cheching if key is in container,
also trasform ccs key to report lab keys.
extras = Are extra params for func, it will be call like func(*[param1, param2])
obj = frag
keys = [(reportlab, css), ... ]
container = cssAttr
"""
cpextras = extras
for reportlab, css in keys:
extras = cpextras
if extras is None:
extras = []
elif not isinstance(extras, list):
extras = [extras]
if css in container:
extras.insert(0, container[css])
setattr(obj,
reportlab,
func(*extras)
) | [
"def",
"transform_attrs",
"(",
"obj",
",",
"keys",
",",
"container",
",",
"func",
",",
"extras",
"=",
"None",
")",
":",
"cpextras",
"=",
"extras",
"for",
"reportlab",
",",
"css",
"in",
"keys",
":",
"extras",
"=",
"cpextras",
"if",
"extras",
"is",
"None",
":",
"extras",
"=",
"[",
"]",
"elif",
"not",
"isinstance",
"(",
"extras",
",",
"list",
")",
":",
"extras",
"=",
"[",
"extras",
"]",
"if",
"css",
"in",
"container",
":",
"extras",
".",
"insert",
"(",
"0",
",",
"container",
"[",
"css",
"]",
")",
"setattr",
"(",
"obj",
",",
"reportlab",
",",
"func",
"(",
"*",
"extras",
")",
")"
]
| Allows to apply one function to set of keys cheching if key is in container,
also trasform ccs key to report lab keys.
extras = Are extra params for func, it will be call like func(*[param1, param2])
obj = frag
keys = [(reportlab, css), ... ]
container = cssAttr | [
"Allows",
"to",
"apply",
"one",
"function",
"to",
"set",
"of",
"keys",
"cheching",
"if",
"key",
"is",
"in",
"container",
"also",
"trasform",
"ccs",
"key",
"to",
"report",
"lab",
"keys",
"."
]
| 230357a392f48816532d3c2fa082a680b80ece48 | https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/util.py#L140-L164 | train |
xhtml2pdf/xhtml2pdf | xhtml2pdf/util.py | copy_attrs | def copy_attrs(obj1, obj2, attrs):
"""
Allows copy a list of attributes from object2 to object1.
Useful for copy ccs attributes to fragment
"""
for attr in attrs:
value = getattr(obj2, attr) if hasattr(obj2, attr) else None
if value is None and isinstance(obj2, dict) and attr in obj2:
value = obj2[attr]
setattr(obj1, attr, value) | python | def copy_attrs(obj1, obj2, attrs):
"""
Allows copy a list of attributes from object2 to object1.
Useful for copy ccs attributes to fragment
"""
for attr in attrs:
value = getattr(obj2, attr) if hasattr(obj2, attr) else None
if value is None and isinstance(obj2, dict) and attr in obj2:
value = obj2[attr]
setattr(obj1, attr, value) | [
"def",
"copy_attrs",
"(",
"obj1",
",",
"obj2",
",",
"attrs",
")",
":",
"for",
"attr",
"in",
"attrs",
":",
"value",
"=",
"getattr",
"(",
"obj2",
",",
"attr",
")",
"if",
"hasattr",
"(",
"obj2",
",",
"attr",
")",
"else",
"None",
"if",
"value",
"is",
"None",
"and",
"isinstance",
"(",
"obj2",
",",
"dict",
")",
"and",
"attr",
"in",
"obj2",
":",
"value",
"=",
"obj2",
"[",
"attr",
"]",
"setattr",
"(",
"obj1",
",",
"attr",
",",
"value",
")"
]
| Allows copy a list of attributes from object2 to object1.
Useful for copy ccs attributes to fragment | [
"Allows",
"copy",
"a",
"list",
"of",
"attributes",
"from",
"object2",
"to",
"object1",
".",
"Useful",
"for",
"copy",
"ccs",
"attributes",
"to",
"fragment"
]
| 230357a392f48816532d3c2fa082a680b80ece48 | https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/util.py#L167-L176 | train |
xhtml2pdf/xhtml2pdf | xhtml2pdf/util.py | set_value | def set_value(obj, attrs, value, _copy=False):
"""
Allows set the same value to a list of attributes
"""
for attr in attrs:
if _copy:
value = copy(value)
setattr(obj, attr, value) | python | def set_value(obj, attrs, value, _copy=False):
"""
Allows set the same value to a list of attributes
"""
for attr in attrs:
if _copy:
value = copy(value)
setattr(obj, attr, value) | [
"def",
"set_value",
"(",
"obj",
",",
"attrs",
",",
"value",
",",
"_copy",
"=",
"False",
")",
":",
"for",
"attr",
"in",
"attrs",
":",
"if",
"_copy",
":",
"value",
"=",
"copy",
"(",
"value",
")",
"setattr",
"(",
"obj",
",",
"attr",
",",
"value",
")"
]
| Allows set the same value to a list of attributes | [
"Allows",
"set",
"the",
"same",
"value",
"to",
"a",
"list",
"of",
"attributes"
]
| 230357a392f48816532d3c2fa082a680b80ece48 | https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/util.py#L179-L186 | train |
xhtml2pdf/xhtml2pdf | xhtml2pdf/util.py | getColor | def getColor(value, default=None):
"""
Convert to color value.
This returns a Color object instance from a text bit.
"""
if isinstance(value, Color):
return value
value = str(value).strip().lower()
if value == "transparent" or value == "none":
return default
if value in COLOR_BY_NAME:
return COLOR_BY_NAME[value]
if value.startswith("#") and len(value) == 4:
value = "#" + value[1] + value[1] + \
value[2] + value[2] + value[3] + value[3]
elif rgb_re.search(value):
# e.g., value = "<css function: rgb(153, 51, 153)>", go figure:
r, g, b = [int(x) for x in rgb_re.search(value).groups()]
value = "#%02x%02x%02x" % (r, g, b)
else:
# Shrug
pass
return toColor(value, default) | python | def getColor(value, default=None):
"""
Convert to color value.
This returns a Color object instance from a text bit.
"""
if isinstance(value, Color):
return value
value = str(value).strip().lower()
if value == "transparent" or value == "none":
return default
if value in COLOR_BY_NAME:
return COLOR_BY_NAME[value]
if value.startswith("#") and len(value) == 4:
value = "#" + value[1] + value[1] + \
value[2] + value[2] + value[3] + value[3]
elif rgb_re.search(value):
# e.g., value = "<css function: rgb(153, 51, 153)>", go figure:
r, g, b = [int(x) for x in rgb_re.search(value).groups()]
value = "#%02x%02x%02x" % (r, g, b)
else:
# Shrug
pass
return toColor(value, default) | [
"def",
"getColor",
"(",
"value",
",",
"default",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"Color",
")",
":",
"return",
"value",
"value",
"=",
"str",
"(",
"value",
")",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"if",
"value",
"==",
"\"transparent\"",
"or",
"value",
"==",
"\"none\"",
":",
"return",
"default",
"if",
"value",
"in",
"COLOR_BY_NAME",
":",
"return",
"COLOR_BY_NAME",
"[",
"value",
"]",
"if",
"value",
".",
"startswith",
"(",
"\"#\"",
")",
"and",
"len",
"(",
"value",
")",
"==",
"4",
":",
"value",
"=",
"\"#\"",
"+",
"value",
"[",
"1",
"]",
"+",
"value",
"[",
"1",
"]",
"+",
"value",
"[",
"2",
"]",
"+",
"value",
"[",
"2",
"]",
"+",
"value",
"[",
"3",
"]",
"+",
"value",
"[",
"3",
"]",
"elif",
"rgb_re",
".",
"search",
"(",
"value",
")",
":",
"# e.g., value = \"<css function: rgb(153, 51, 153)>\", go figure:",
"r",
",",
"g",
",",
"b",
"=",
"[",
"int",
"(",
"x",
")",
"for",
"x",
"in",
"rgb_re",
".",
"search",
"(",
"value",
")",
".",
"groups",
"(",
")",
"]",
"value",
"=",
"\"#%02x%02x%02x\"",
"%",
"(",
"r",
",",
"g",
",",
"b",
")",
"else",
":",
"# Shrug",
"pass",
"return",
"toColor",
"(",
"value",
",",
"default",
")"
]
| Convert to color value.
This returns a Color object instance from a text bit. | [
"Convert",
"to",
"color",
"value",
".",
"This",
"returns",
"a",
"Color",
"object",
"instance",
"from",
"a",
"text",
"bit",
"."
]
| 230357a392f48816532d3c2fa082a680b80ece48 | https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/util.py#L190-L214 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.