repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
jjgomera/iapws
iapws/iapws97.py
_Backward3a_P_hs
def _Backward3a_P_hs(h, s): """Backward equation for region 3a, P=f(h,s) Parameters ---------- h : float Specific enthalpy, [kJ/kg] s : float Specific entropy, [kJ/kgK] Returns ------- P : float Pressure, [MPa] References ---------- IAPWS, Revised S...
python
def _Backward3a_P_hs(h, s): """Backward equation for region 3a, P=f(h,s) Parameters ---------- h : float Specific enthalpy, [kJ/kg] s : float Specific entropy, [kJ/kgK] Returns ------- P : float Pressure, [MPa] References ---------- IAPWS, Revised S...
[ "def", "_Backward3a_P_hs", "(", "h", ",", "s", ")", ":", "I", "=", "[", "0", ",", "0", ",", "0", ",", "1", ",", "1", ",", "1", ",", "1", ",", "1", ",", "2", ",", "2", ",", "3", ",", "3", ",", "3", ",", "4", ",", "4", ",", "4", ",", ...
Backward equation for region 3a, P=f(h,s) Parameters ---------- h : float Specific enthalpy, [kJ/kg] s : float Specific entropy, [kJ/kgK] Returns ------- P : float Pressure, [MPa] References ---------- IAPWS, Revised Supplementary Release on Backward Eq...
[ "Backward", "equation", "for", "region", "3a", "P", "=", "f", "(", "h", "s", ")" ]
train
https://github.com/jjgomera/iapws/blob/1e5812aab38212fb8a63736f61cdcfa427d223b1/iapws/iapws97.py#L2603-L2656
jjgomera/iapws
iapws/iapws97.py
_Backward3_P_hs
def _Backward3_P_hs(h, s): """Backward equation for region 3, P=f(h,s) Parameters ---------- h : float Specific enthalpy, [kJ/kg] s : float Specific entropy, [kJ/kgK] Returns ------- P : float Pressure, [MPa] """ sc = 4.41202148223476 if s <= sc: ...
python
def _Backward3_P_hs(h, s): """Backward equation for region 3, P=f(h,s) Parameters ---------- h : float Specific enthalpy, [kJ/kg] s : float Specific entropy, [kJ/kgK] Returns ------- P : float Pressure, [MPa] """ sc = 4.41202148223476 if s <= sc: ...
[ "def", "_Backward3_P_hs", "(", "h", ",", "s", ")", ":", "sc", "=", "4.41202148223476", "if", "s", "<=", "sc", ":", "return", "_Backward3a_P_hs", "(", "h", ",", "s", ")", "else", ":", "return", "_Backward3b_P_hs", "(", "h", ",", "s", ")" ]
Backward equation for region 3, P=f(h,s) Parameters ---------- h : float Specific enthalpy, [kJ/kg] s : float Specific entropy, [kJ/kgK] Returns ------- P : float Pressure, [MPa]
[ "Backward", "equation", "for", "region", "3", "P", "=", "f", "(", "h", "s", ")" ]
train
https://github.com/jjgomera/iapws/blob/1e5812aab38212fb8a63736f61cdcfa427d223b1/iapws/iapws97.py#L2717-L2736
jjgomera/iapws
iapws/iapws97.py
_Backward3_sat_v_P
def _Backward3_sat_v_P(P, T, x): """Backward equation for region 3 for saturated state, vs=f(P,x) Parameters ---------- T : float Temperature, [K] P : float Pressure, [MPa] x : integer Vapor quality, [-] Returns ------- v : float Specific volume, [m³...
python
def _Backward3_sat_v_P(P, T, x): """Backward equation for region 3 for saturated state, vs=f(P,x) Parameters ---------- T : float Temperature, [K] P : float Pressure, [MPa] x : integer Vapor quality, [-] Returns ------- v : float Specific volume, [m³...
[ "def", "_Backward3_sat_v_P", "(", "P", ",", "T", ",", "x", ")", ":", "if", "x", "==", "0", ":", "if", "P", "<", "19.00881189", ":", "region", "=", "\"c\"", "elif", "P", "<", "21.0434", ":", "region", "=", "\"s\"", "elif", "P", "<", "21.9316", ":"...
Backward equation for region 3 for saturated state, vs=f(P,x) Parameters ---------- T : float Temperature, [K] P : float Pressure, [MPa] x : integer Vapor quality, [-] Returns ------- v : float Specific volume, [m³/kg] Notes ----- The vapor ...
[ "Backward", "equation", "for", "region", "3", "for", "saturated", "state", "vs", "=", "f", "(", "P", "x", ")" ]
train
https://github.com/jjgomera/iapws/blob/1e5812aab38212fb8a63736f61cdcfa427d223b1/iapws/iapws97.py#L2739-L2779
jjgomera/iapws
iapws/iapws97.py
_Backward3_v_PT
def _Backward3_v_PT(P, T): """Backward equation for region 3, v=f(P,T) Parameters ---------- T : float Temperature, [K] P : float Pressure, [MPa] Returns ------- v : float Specific volume, [m³/kg] References ---------- IAPWS, Revised Supplementary R...
python
def _Backward3_v_PT(P, T): """Backward equation for region 3, v=f(P,T) Parameters ---------- T : float Temperature, [K] P : float Pressure, [MPa] Returns ------- v : float Specific volume, [m³/kg] References ---------- IAPWS, Revised Supplementary R...
[ "def", "_Backward3_v_PT", "(", "P", ",", "T", ")", ":", "if", "P", ">", "40", ":", "if", "T", "<=", "_tab_P", "(", "P", ")", ":", "region", "=", "\"a\"", "else", ":", "region", "=", "\"b\"", "elif", "25", "<", "P", "<=", "40", ":", "tcd", "="...
Backward equation for region 3, v=f(P,T) Parameters ---------- T : float Temperature, [K] P : float Pressure, [MPa] Returns ------- v : float Specific volume, [m³/kg] References ---------- IAPWS, Revised Supplementary Release on Backward Equations for S...
[ "Backward", "equation", "for", "region", "3", "v", "=", "f", "(", "P", "T", ")" ]
train
https://github.com/jjgomera/iapws/blob/1e5812aab38212fb8a63736f61cdcfa427d223b1/iapws/iapws97.py#L2782-L2961
jjgomera/iapws
iapws/iapws97.py
_Backward3x_v_PT
def _Backward3x_v_PT(T, P, x): """Backward equation for region 3x, v=f(P,T) Parameters ---------- T : float Temperature, [K] P : float Pressure, [MPa] x : char Region 3 subregion code Returns ------- v : float Specific volume, [m³/kg] References...
python
def _Backward3x_v_PT(T, P, x): """Backward equation for region 3x, v=f(P,T) Parameters ---------- T : float Temperature, [K] P : float Pressure, [MPa] x : char Region 3 subregion code Returns ------- v : float Specific volume, [m³/kg] References...
[ "def", "_Backward3x_v_PT", "(", "T", ",", "P", ",", "x", ")", ":", "par", "=", "{", "\"a\"", ":", "[", "0.0024", ",", "100", ",", "760", ",", "0.085", ",", "0.817", ",", "1", ",", "1", ",", "1", "]", ",", "\"b\"", ":", "[", "0.0041", ",", "...
Backward equation for region 3x, v=f(P,T) Parameters ---------- T : float Temperature, [K] P : float Pressure, [MPa] x : char Region 3 subregion code Returns ------- v : float Specific volume, [m³/kg] References ---------- IAPWS, Revised Sup...
[ "Backward", "equation", "for", "region", "3x", "v", "=", "f", "(", "P", "T", ")" ]
train
https://github.com/jjgomera/iapws/blob/1e5812aab38212fb8a63736f61cdcfa427d223b1/iapws/iapws97.py#L2964-L3569
jjgomera/iapws
iapws/iapws97.py
_Region4
def _Region4(P, x): """Basic equation for region 4 Parameters ---------- P : float Pressure, [MPa] x : float Vapor quality, [-] Returns ------- prop : dict Dict with calculated properties. The available properties are: * T: Saturated temperature, [K...
python
def _Region4(P, x): """Basic equation for region 4 Parameters ---------- P : float Pressure, [MPa] x : float Vapor quality, [-] Returns ------- prop : dict Dict with calculated properties. The available properties are: * T: Saturated temperature, [K...
[ "def", "_Region4", "(", "P", ",", "x", ")", ":", "T", "=", "_TSat_P", "(", "P", ")", "if", "T", ">", "623.15", ":", "rhol", "=", "1.", "/", "_Backward3_sat_v_P", "(", "P", ",", "T", ",", "0", ")", "P1", "=", "_Region3", "(", "rhol", ",", "T",...
Basic equation for region 4 Parameters ---------- P : float Pressure, [MPa] x : float Vapor quality, [-] Returns ------- prop : dict Dict with calculated properties. The available properties are: * T: Saturated temperature, [K] * P: Saturate...
[ "Basic", "equation", "for", "region", "4" ]
train
https://github.com/jjgomera/iapws/blob/1e5812aab38212fb8a63736f61cdcfa427d223b1/iapws/iapws97.py#L3573-L3618
jjgomera/iapws
iapws/iapws97.py
_Bound_TP
def _Bound_TP(T, P): """Region definition for input T and P Parameters ---------- T : float Temperature, [K] P : float Pressure, [MPa] Returns ------- region : float IAPWS-97 region code References ---------- Wagner, W; Kretzschmar, H-J: Internation...
python
def _Bound_TP(T, P): """Region definition for input T and P Parameters ---------- T : float Temperature, [K] P : float Pressure, [MPa] Returns ------- region : float IAPWS-97 region code References ---------- Wagner, W; Kretzschmar, H-J: Internation...
[ "def", "_Bound_TP", "(", "T", ",", "P", ")", ":", "region", "=", "None", "if", "1073.15", "<", "T", "<=", "2273.15", "and", "Pmin", "<=", "P", "<=", "50", ":", "region", "=", "5", "elif", "Pmin", "<=", "P", "<=", "Ps_623", ":", "Tsat", "=", "_T...
Region definition for input T and P Parameters ---------- T : float Temperature, [K] P : float Pressure, [MPa] Returns ------- region : float IAPWS-97 region code References ---------- Wagner, W; Kretzschmar, H-J: International Steam Tables: Properties ...
[ "Region", "definition", "for", "input", "T", "and", "P" ]
train
https://github.com/jjgomera/iapws/blob/1e5812aab38212fb8a63736f61cdcfa427d223b1/iapws/iapws97.py#L3813-L3851
jjgomera/iapws
iapws/iapws97.py
_Bound_Ph
def _Bound_Ph(P, h): """Region definition for input P y h Parameters ---------- P : float Pressure, [MPa] h : float Specific enthalpy, [kJ/kg] Returns ------- region : float IAPWS-97 region code References ---------- Wagner, W; Kretzschmar, H-J: Int...
python
def _Bound_Ph(P, h): """Region definition for input P y h Parameters ---------- P : float Pressure, [MPa] h : float Specific enthalpy, [kJ/kg] Returns ------- region : float IAPWS-97 region code References ---------- Wagner, W; Kretzschmar, H-J: Int...
[ "def", "_Bound_Ph", "(", "P", ",", "h", ")", ":", "region", "=", "None", "if", "Pmin", "<=", "P", "<=", "Ps_623", ":", "h14", "=", "_Region1", "(", "_TSat_P", "(", "P", ")", ",", "P", ")", "[", "\"h\"", "]", "h24", "=", "_Region2", "(", "_TSat_...
Region definition for input P y h Parameters ---------- P : float Pressure, [MPa] h : float Specific enthalpy, [kJ/kg] Returns ------- region : float IAPWS-97 region code References ---------- Wagner, W; Kretzschmar, H-J: International Steam Tables: Pro...
[ "Region", "definition", "for", "input", "P", "y", "h" ]
train
https://github.com/jjgomera/iapws/blob/1e5812aab38212fb8a63736f61cdcfa427d223b1/iapws/iapws97.py#L3854-L3925
jjgomera/iapws
iapws/iapws97.py
_Bound_Ps
def _Bound_Ps(P, s): """Region definition for input P and s Parameters ---------- P : float Pressure, [MPa] s : float Specific entropy, [kJ/kgK] Returns ------- region : float IAPWS-97 region code References ---------- Wagner, W; Kretzschmar, H-J: I...
python
def _Bound_Ps(P, s): """Region definition for input P and s Parameters ---------- P : float Pressure, [MPa] s : float Specific entropy, [kJ/kgK] Returns ------- region : float IAPWS-97 region code References ---------- Wagner, W; Kretzschmar, H-J: I...
[ "def", "_Bound_Ps", "(", "P", ",", "s", ")", ":", "region", "=", "None", "if", "Pmin", "<=", "P", "<=", "Ps_623", ":", "smin", "=", "_Region1", "(", "273.15", ",", "P", ")", "[", "\"s\"", "]", "s14", "=", "_Region1", "(", "_TSat_P", "(", "P", "...
Region definition for input P and s Parameters ---------- P : float Pressure, [MPa] s : float Specific entropy, [kJ/kgK] Returns ------- region : float IAPWS-97 region code References ---------- Wagner, W; Kretzschmar, H-J: International Steam Tables: P...
[ "Region", "definition", "for", "input", "P", "and", "s" ]
train
https://github.com/jjgomera/iapws/blob/1e5812aab38212fb8a63736f61cdcfa427d223b1/iapws/iapws97.py#L3928-L3999
jjgomera/iapws
iapws/iapws97.py
_Bound_hs
def _Bound_hs(h, s): """Region definition for input h and s Parameters ---------- h : float Specific enthalpy, [kJ/kg] s : float Specific entropy, [kJ/kgK] Returns ------- region : float IAPWS-97 region code References ---------- Wagner, W; Kretzsch...
python
def _Bound_hs(h, s): """Region definition for input h and s Parameters ---------- h : float Specific enthalpy, [kJ/kg] s : float Specific entropy, [kJ/kgK] Returns ------- region : float IAPWS-97 region code References ---------- Wagner, W; Kretzsch...
[ "def", "_Bound_hs", "(", "h", ",", "s", ")", ":", "region", "=", "None", "s13", "=", "_Region1", "(", "623.15", ",", "100", ")", "[", "\"s\"", "]", "s13s", "=", "_Region1", "(", "623.15", ",", "Ps_623", ")", "[", "\"s\"", "]", "sTPmax", "=", "_Re...
Region definition for input h and s Parameters ---------- h : float Specific enthalpy, [kJ/kg] s : float Specific entropy, [kJ/kgK] Returns ------- region : float IAPWS-97 region code References ---------- Wagner, W; Kretzschmar, H-J: International Stea...
[ "Region", "definition", "for", "input", "h", "and", "s" ]
train
https://github.com/jjgomera/iapws/blob/1e5812aab38212fb8a63736f61cdcfa427d223b1/iapws/iapws97.py#L4002-L4171
jjgomera/iapws
iapws/iapws97.py
prop0
def prop0(T, P): """Ideal gas properties Parameters ---------- T : float Temperature, [K] P : float Pressure, [MPa] Returns ------- prop : dict Dict with calculated properties. The available properties are: * v: Specific volume, [m³/kg] ...
python
def prop0(T, P): """Ideal gas properties Parameters ---------- T : float Temperature, [K] P : float Pressure, [MPa] Returns ------- prop : dict Dict with calculated properties. The available properties are: * v: Specific volume, [m³/kg] ...
[ "def", "prop0", "(", "T", ",", "P", ")", ":", "if", "T", "<=", "1073.15", ":", "Tr", "=", "540", "/", "T", "Pr", "=", "P", "/", "1.", "go", ",", "gop", ",", "gopp", ",", "got", ",", "gott", ",", "gopt", "=", "Region2_cp0", "(", "Tr", ",", ...
Ideal gas properties Parameters ---------- T : float Temperature, [K] P : float Pressure, [MPa] Returns ------- prop : dict Dict with calculated properties. The available properties are: * v: Specific volume, [m³/kg] * h: Specific enthalpy, ...
[ "Ideal", "gas", "properties" ]
train
https://github.com/jjgomera/iapws/blob/1e5812aab38212fb8a63736f61cdcfa427d223b1/iapws/iapws97.py#L4174-L4217
jjgomera/iapws
iapws/iapws97.py
IAPWS97.calculable
def calculable(self): """Check if class is calculable by its kwargs""" self._thermo = "" if self.kwargs["T"] and self.kwargs["P"]: self._thermo = "TP" elif self.kwargs["P"] and self.kwargs["h"] is not None: self._thermo = "Ph" elif self.kwargs["P"] and sel...
python
def calculable(self): """Check if class is calculable by its kwargs""" self._thermo = "" if self.kwargs["T"] and self.kwargs["P"]: self._thermo = "TP" elif self.kwargs["P"] and self.kwargs["h"] is not None: self._thermo = "Ph" elif self.kwargs["P"] and sel...
[ "def", "calculable", "(", "self", ")", ":", "self", ".", "_thermo", "=", "\"\"", "if", "self", ".", "kwargs", "[", "\"T\"", "]", "and", "self", ".", "kwargs", "[", "\"P\"", "]", ":", "self", ".", "_thermo", "=", "\"TP\"", "elif", "self", ".", "kwar...
Check if class is calculable by its kwargs
[ "Check", "if", "class", "is", "calculable", "by", "its", "kwargs" ]
train
https://github.com/jjgomera/iapws/blob/1e5812aab38212fb8a63736f61cdcfa427d223b1/iapws/iapws97.py#L4341-L4361
jjgomera/iapws
iapws/iapws97.py
IAPWS97.derivative
def derivative(self, z, x, y, fase): """Wrapper derivative for custom derived properties where x, y, z can be: P, T, v, u, h, s, g, a""" return deriv_G(self, z, x, y, fase)
python
def derivative(self, z, x, y, fase): """Wrapper derivative for custom derived properties where x, y, z can be: P, T, v, u, h, s, g, a""" return deriv_G(self, z, x, y, fase)
[ "def", "derivative", "(", "self", ",", "z", ",", "x", ",", "y", ",", "fase", ")", ":", "return", "deriv_G", "(", "self", ",", "z", ",", "x", ",", "y", ",", "fase", ")" ]
Wrapper derivative for custom derived properties where x, y, z can be: P, T, v, u, h, s, g, a
[ "Wrapper", "derivative", "for", "custom", "derived", "properties", "where", "x", "y", "z", "can", "be", ":", "P", "T", "v", "u", "h", "s", "g", "a" ]
train
https://github.com/jjgomera/iapws/blob/1e5812aab38212fb8a63736f61cdcfa427d223b1/iapws/iapws97.py#L4703-L4706
jjgomera/iapws
iapws/ammonia.py
Ttr
def Ttr(x): """Equation for the triple point of ammonia-water mixture Parameters ---------- x : float Mole fraction of ammonia in mixture, [mol/mol] Returns ------- Ttr : float Triple point temperature, [K] Notes ------ Raise :class:`NotImplementedError` if inp...
python
def Ttr(x): """Equation for the triple point of ammonia-water mixture Parameters ---------- x : float Mole fraction of ammonia in mixture, [mol/mol] Returns ------- Ttr : float Triple point temperature, [K] Notes ------ Raise :class:`NotImplementedError` if inp...
[ "def", "Ttr", "(", "x", ")", ":", "if", "0", "<=", "x", "<=", "0.33367", ":", "Ttr", "=", "273.16", "*", "(", "1", "-", "0.3439823", "*", "x", "-", "1.3274271", "*", "x", "**", "2", "-", "274.973", "*", "x", "**", "3", ")", "elif", "0.33367",...
Equation for the triple point of ammonia-water mixture Parameters ---------- x : float Mole fraction of ammonia in mixture, [mol/mol] Returns ------- Ttr : float Triple point temperature, [K] Notes ------ Raise :class:`NotImplementedError` if input isn't in limit: ...
[ "Equation", "for", "the", "triple", "point", "of", "ammonia", "-", "water", "mixture" ]
train
https://github.com/jjgomera/iapws/blob/1e5812aab38212fb8a63736f61cdcfa427d223b1/iapws/ammonia.py#L566-L601
jjgomera/iapws
iapws/ammonia.py
H2ONH3._prop
def _prop(self, rho, T, x): """Thermodynamic properties of ammonia-water mixtures Parameters ---------- T : float Temperature [K] rho : float Density [kg/m³] x : float Mole fraction of ammonia in mixture [mol/mol] Returns ...
python
def _prop(self, rho, T, x): """Thermodynamic properties of ammonia-water mixtures Parameters ---------- T : float Temperature [K] rho : float Density [kg/m³] x : float Mole fraction of ammonia in mixture [mol/mol] Returns ...
[ "def", "_prop", "(", "self", ",", "rho", ",", "T", ",", "x", ")", ":", "# FIXME: The values are good, bad difer by 1%, a error I can find", "# In Pressure happen and only use fird", "M", "=", "(", "1", "-", "x", ")", "*", "IAPWS95", ".", "M", "+", "x", "*", "N...
Thermodynamic properties of ammonia-water mixtures Parameters ---------- T : float Temperature [K] rho : float Density [kg/m³] x : float Mole fraction of ammonia in mixture [mol/mol] Returns ------- prop : dict ...
[ "Thermodynamic", "properties", "of", "ammonia", "-", "water", "mixtures" ]
train
https://github.com/jjgomera/iapws/blob/1e5812aab38212fb8a63736f61cdcfa427d223b1/iapws/ammonia.py#L210-L286
jjgomera/iapws
iapws/ammonia.py
H2ONH3._phi0
def _phi0(self, rho, T, x): """Ideal gas Helmholtz energy of binary mixtures and derivatives Parameters ---------- rho : float Density, [kg/m³] T : float Temperature, [K] x : float Mole fraction of ammonia in mixture, [mol/mol] ...
python
def _phi0(self, rho, T, x): """Ideal gas Helmholtz energy of binary mixtures and derivatives Parameters ---------- rho : float Density, [kg/m³] T : float Temperature, [K] x : float Mole fraction of ammonia in mixture, [mol/mol] ...
[ "def", "_phi0", "(", "self", ",", "rho", ",", "T", ",", "x", ")", ":", "# Define reducing parameters for mixture model", "M", "=", "(", "1", "-", "x", ")", "*", "IAPWS95", ".", "M", "+", "x", "*", "NH3", ".", "M", "tau", "=", "500", "/", "T", "de...
Ideal gas Helmholtz energy of binary mixtures and derivatives Parameters ---------- rho : float Density, [kg/m³] T : float Temperature, [K] x : float Mole fraction of ammonia in mixture, [mol/mol] Returns ------- prop ...
[ "Ideal", "gas", "Helmholtz", "energy", "of", "binary", "mixtures", "and", "derivatives" ]
train
https://github.com/jjgomera/iapws/blob/1e5812aab38212fb8a63736f61cdcfa427d223b1/iapws/ammonia.py#L288-L380
jjgomera/iapws
iapws/ammonia.py
H2ONH3._phir
def _phir(self, rho, T, x): """Residual contribution to the free Helmholtz energy Parameters ---------- rho : float Density, [kg/m³] T : float Temperature, [K] x : float Mole fraction of ammonia in mixture, [mol/mol] Returns ...
python
def _phir(self, rho, T, x): """Residual contribution to the free Helmholtz energy Parameters ---------- rho : float Density, [kg/m³] T : float Temperature, [K] x : float Mole fraction of ammonia in mixture, [mol/mol] Returns ...
[ "def", "_phir", "(", "self", ",", "rho", ",", "T", ",", "x", ")", ":", "# Temperature reducing value, Eq 4", "Tc12", "=", "0.9648407", "/", "2", "*", "(", "IAPWS95", ".", "Tc", "+", "NH3", ".", "Tc", ")", "Tn", "=", "(", "1", "-", "x", ")", "**",...
Residual contribution to the free Helmholtz energy Parameters ---------- rho : float Density, [kg/m³] T : float Temperature, [K] x : float Mole fraction of ammonia in mixture, [mol/mol] Returns ------- prop : dict ...
[ "Residual", "contribution", "to", "the", "free", "Helmholtz", "energy" ]
train
https://github.com/jjgomera/iapws/blob/1e5812aab38212fb8a63736f61cdcfa427d223b1/iapws/ammonia.py#L382-L457
jjgomera/iapws
iapws/ammonia.py
H2ONH3._Dphir
def _Dphir(self, tau, delta, x): """Departure function to the residual contribution to the free Helmholtz energy Parameters ---------- tau : float Adimensional temperature, [-] delta : float Adimensional density, [-] x : float ...
python
def _Dphir(self, tau, delta, x): """Departure function to the residual contribution to the free Helmholtz energy Parameters ---------- tau : float Adimensional temperature, [-] delta : float Adimensional density, [-] x : float ...
[ "def", "_Dphir", "(", "self", ",", "tau", ",", "delta", ",", "x", ")", ":", "fx", "=", "x", "*", "(", "1", "-", "x", "**", "0.5248379", ")", "dfx", "=", "1", "-", "1.5248379", "*", "x", "**", "0.5248379", "# Polinomial terms", "n", "=", "-", "1...
Departure function to the residual contribution to the free Helmholtz energy Parameters ---------- tau : float Adimensional temperature, [-] delta : float Adimensional density, [-] x : float Mole fraction of ammonia in mixture, [mol/mo...
[ "Departure", "function", "to", "the", "residual", "contribution", "to", "the", "free", "Helmholtz", "energy" ]
train
https://github.com/jjgomera/iapws/blob/1e5812aab38212fb8a63736f61cdcfa427d223b1/iapws/ammonia.py#L459-L563
spencerahill/aospy
aospy/data_loader.py
_preprocess_and_rename_grid_attrs
def _preprocess_and_rename_grid_attrs(func, grid_attrs=None, **kwargs): """Call a custom preprocessing method first then rename grid attrs. This wrapper is needed to generate a single function to pass to the ``preprocesss`` of xr.open_mfdataset. It makes sure that the user-specified preprocess functio...
python
def _preprocess_and_rename_grid_attrs(func, grid_attrs=None, **kwargs): """Call a custom preprocessing method first then rename grid attrs. This wrapper is needed to generate a single function to pass to the ``preprocesss`` of xr.open_mfdataset. It makes sure that the user-specified preprocess functio...
[ "def", "_preprocess_and_rename_grid_attrs", "(", "func", ",", "grid_attrs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "def", "func_wrapper", "(", "ds", ")", ":", "return", "grid_attrs_to_aospy_names", "(", "func", "(", "ds", ",", "*", "*", "kwargs", ...
Call a custom preprocessing method first then rename grid attrs. This wrapper is needed to generate a single function to pass to the ``preprocesss`` of xr.open_mfdataset. It makes sure that the user-specified preprocess function is called on the loaded Dataset before aospy's is applied. An example fo...
[ "Call", "a", "custom", "preprocessing", "method", "first", "then", "rename", "grid", "attrs", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/data_loader.py#L19-L49
spencerahill/aospy
aospy/data_loader.py
grid_attrs_to_aospy_names
def grid_attrs_to_aospy_names(data, grid_attrs=None): """Rename grid attributes to be consistent with aospy conventions. Search all of the dataset's coords and dims looking for matches to known grid attribute names; any that are found subsequently get renamed to the aospy name as specified in ``aospy.i...
python
def grid_attrs_to_aospy_names(data, grid_attrs=None): """Rename grid attributes to be consistent with aospy conventions. Search all of the dataset's coords and dims looking for matches to known grid attribute names; any that are found subsequently get renamed to the aospy name as specified in ``aospy.i...
[ "def", "grid_attrs_to_aospy_names", "(", "data", ",", "grid_attrs", "=", "None", ")", ":", "if", "grid_attrs", "is", "None", ":", "grid_attrs", "=", "{", "}", "# Override GRID_ATTRS with entries in grid_attrs", "attrs", "=", "GRID_ATTRS", ".", "copy", "(", ")", ...
Rename grid attributes to be consistent with aospy conventions. Search all of the dataset's coords and dims looking for matches to known grid attribute names; any that are found subsequently get renamed to the aospy name as specified in ``aospy.internal_names.GRID_ATTRS``. Also forces any renamed grid...
[ "Rename", "grid", "attributes", "to", "be", "consistent", "with", "aospy", "conventions", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/data_loader.py#L52-L96
spencerahill/aospy
aospy/data_loader.py
set_grid_attrs_as_coords
def set_grid_attrs_as_coords(ds): """Set available grid attributes as coordinates in a given Dataset. Grid attributes are assumed to have their internal aospy names. Grid attributes are set as coordinates, such that they are carried by all selected DataArrays with overlapping index dimensions. Par...
python
def set_grid_attrs_as_coords(ds): """Set available grid attributes as coordinates in a given Dataset. Grid attributes are assumed to have their internal aospy names. Grid attributes are set as coordinates, such that they are carried by all selected DataArrays with overlapping index dimensions. Par...
[ "def", "set_grid_attrs_as_coords", "(", "ds", ")", ":", "grid_attrs_in_ds", "=", "set", "(", "GRID_ATTRS", ".", "keys", "(", ")", ")", ".", "intersection", "(", "set", "(", "ds", ".", "coords", ")", "|", "set", "(", "ds", ".", "data_vars", ")", ")", ...
Set available grid attributes as coordinates in a given Dataset. Grid attributes are assumed to have their internal aospy names. Grid attributes are set as coordinates, such that they are carried by all selected DataArrays with overlapping index dimensions. Parameters ---------- ds : Dataset ...
[ "Set", "available", "grid", "attributes", "as", "coordinates", "in", "a", "given", "Dataset", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/data_loader.py#L99-L119
spencerahill/aospy
aospy/data_loader.py
_maybe_cast_to_float64
def _maybe_cast_to_float64(da): """Cast DataArrays to np.float64 if they are of type np.float32. Parameters ---------- da : xr.DataArray Input DataArray Returns ------- DataArray """ if da.dtype == np.float32: logging.warning('Datapoints were stored using the np.flo...
python
def _maybe_cast_to_float64(da): """Cast DataArrays to np.float64 if they are of type np.float32. Parameters ---------- da : xr.DataArray Input DataArray Returns ------- DataArray """ if da.dtype == np.float32: logging.warning('Datapoints were stored using the np.flo...
[ "def", "_maybe_cast_to_float64", "(", "da", ")", ":", "if", "da", ".", "dtype", "==", "np", ".", "float32", ":", "logging", ".", "warning", "(", "'Datapoints were stored using the np.float32 datatype.'", "'For accurate reduction operations using bottleneck, '", "'datapoints...
Cast DataArrays to np.float64 if they are of type np.float32. Parameters ---------- da : xr.DataArray Input DataArray Returns ------- DataArray
[ "Cast", "DataArrays", "to", "np", ".", "float64", "if", "they", "are", "of", "type", "np", ".", "float32", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/data_loader.py#L122-L142
spencerahill/aospy
aospy/data_loader.py
_sel_var
def _sel_var(ds, var, upcast_float32=True): """Select the specified variable by trying all possible alternative names. Parameters ---------- ds : Dataset Dataset possibly containing var var : aospy.Var Variable to find data for upcast_float32 : bool (default True) Whethe...
python
def _sel_var(ds, var, upcast_float32=True): """Select the specified variable by trying all possible alternative names. Parameters ---------- ds : Dataset Dataset possibly containing var var : aospy.Var Variable to find data for upcast_float32 : bool (default True) Whethe...
[ "def", "_sel_var", "(", "ds", ",", "var", ",", "upcast_float32", "=", "True", ")", ":", "for", "name", "in", "var", ".", "names", ":", "try", ":", "da", "=", "ds", "[", "name", "]", ".", "rename", "(", "var", ".", "name", ")", "if", "upcast_float...
Select the specified variable by trying all possible alternative names. Parameters ---------- ds : Dataset Dataset possibly containing var var : aospy.Var Variable to find data for upcast_float32 : bool (default True) Whether to cast a float32 DataArray up to float64 Re...
[ "Select", "the", "specified", "variable", "by", "trying", "all", "possible", "alternative", "names", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/data_loader.py#L145-L176
spencerahill/aospy
aospy/data_loader.py
_prep_time_data
def _prep_time_data(ds): """Prepare time coordinate information in Dataset for use in aospy. 1. If the Dataset contains a time bounds coordinate, add attributes representing the true beginning and end dates of the time interval used to construct the Dataset 2. If the Dataset contains a time b...
python
def _prep_time_data(ds): """Prepare time coordinate information in Dataset for use in aospy. 1. If the Dataset contains a time bounds coordinate, add attributes representing the true beginning and end dates of the time interval used to construct the Dataset 2. If the Dataset contains a time b...
[ "def", "_prep_time_data", "(", "ds", ")", ":", "ds", "=", "times", ".", "ensure_time_as_index", "(", "ds", ")", "if", "TIME_BOUNDS_STR", "in", "ds", ":", "ds", "=", "times", ".", "ensure_time_avg_has_cf_metadata", "(", "ds", ")", "ds", "[", "TIME_STR", "]"...
Prepare time coordinate information in Dataset for use in aospy. 1. If the Dataset contains a time bounds coordinate, add attributes representing the true beginning and end dates of the time interval used to construct the Dataset 2. If the Dataset contains a time bounds coordinate, overwrite the ...
[ "Prepare", "time", "coordinate", "information", "in", "Dataset", "for", "use", "in", "aospy", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/data_loader.py#L179-L216
spencerahill/aospy
aospy/data_loader.py
_load_data_from_disk
def _load_data_from_disk(file_set, preprocess_func=lambda ds: ds, data_vars='minimal', coords='minimal', grid_attrs=None, **kwargs): """Load a Dataset from a list or glob-string of files. Datasets from files are concatenated along time, and all grid attribu...
python
def _load_data_from_disk(file_set, preprocess_func=lambda ds: ds, data_vars='minimal', coords='minimal', grid_attrs=None, **kwargs): """Load a Dataset from a list or glob-string of files. Datasets from files are concatenated along time, and all grid attribu...
[ "def", "_load_data_from_disk", "(", "file_set", ",", "preprocess_func", "=", "lambda", "ds", ":", "ds", ",", "data_vars", "=", "'minimal'", ",", "coords", "=", "'minimal'", ",", "grid_attrs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "apply_preload_use...
Load a Dataset from a list or glob-string of files. Datasets from files are concatenated along time, and all grid attributes are renamed to their aospy internal names. Parameters ---------- file_set : list or str List of paths to files or glob-string preprocess_func : function (optiona...
[ "Load", "a", "Dataset", "from", "a", "list", "or", "glob", "-", "string", "of", "files", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/data_loader.py#L219-L253
spencerahill/aospy
aospy/data_loader.py
_setattr_default
def _setattr_default(obj, attr, value, default): """Set an attribute of an object to a value or default value.""" if value is None: setattr(obj, attr, default) else: setattr(obj, attr, value)
python
def _setattr_default(obj, attr, value, default): """Set an attribute of an object to a value or default value.""" if value is None: setattr(obj, attr, default) else: setattr(obj, attr, value)
[ "def", "_setattr_default", "(", "obj", ",", "attr", ",", "value", ",", "default", ")", ":", "if", "value", "is", "None", ":", "setattr", "(", "obj", ",", "attr", ",", "default", ")", "else", ":", "setattr", "(", "obj", ",", "attr", ",", "value", ")...
Set an attribute of an object to a value or default value.
[ "Set", "an", "attribute", "of", "an", "object", "to", "a", "value", "or", "default", "value", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/data_loader.py#L267-L272
spencerahill/aospy
aospy/data_loader.py
DataLoader.load_variable
def load_variable(self, var=None, start_date=None, end_date=None, time_offset=None, grid_attrs=None, **DataAttrs): """Load a DataArray for requested variable and time range. Automatically renames all grid attributes to match aospy conventions. Parameters ---------...
python
def load_variable(self, var=None, start_date=None, end_date=None, time_offset=None, grid_attrs=None, **DataAttrs): """Load a DataArray for requested variable and time range. Automatically renames all grid attributes to match aospy conventions. Parameters ---------...
[ "def", "load_variable", "(", "self", ",", "var", "=", "None", ",", "start_date", "=", "None", ",", "end_date", "=", "None", ",", "time_offset", "=", "None", ",", "grid_attrs", "=", "None", ",", "*", "*", "DataAttrs", ")", ":", "file_set", "=", "self", ...
Load a DataArray for requested variable and time range. Automatically renames all grid attributes to match aospy conventions. Parameters ---------- var : Var aospy Var object start_date : datetime.datetime start date for interval end_date : datet...
[ "Load", "a", "DataArray", "for", "requested", "variable", "and", "time", "range", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/data_loader.py#L277-L324
spencerahill/aospy
aospy/data_loader.py
DataLoader._load_or_get_from_model
def _load_or_get_from_model(self, var, start_date=None, end_date=None, time_offset=None, model=None, **DataAttrs): """Load a DataArray for the requested variable and time range Supports both access of grid attributes either through the DataLoader or through an op...
python
def _load_or_get_from_model(self, var, start_date=None, end_date=None, time_offset=None, model=None, **DataAttrs): """Load a DataArray for the requested variable and time range Supports both access of grid attributes either through the DataLoader or through an op...
[ "def", "_load_or_get_from_model", "(", "self", ",", "var", ",", "start_date", "=", "None", ",", "end_date", "=", "None", ",", "time_offset", "=", "None", ",", "model", "=", "None", ",", "*", "*", "DataAttrs", ")", ":", "grid_attrs", "=", "None", "if", ...
Load a DataArray for the requested variable and time range Supports both access of grid attributes either through the DataLoader or through an optionally-provided Model object. Defaults to using the version found in the DataLoader first.
[ "Load", "a", "DataArray", "for", "the", "requested", "variable", "and", "time", "range" ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/data_loader.py#L326-L350
spencerahill/aospy
aospy/data_loader.py
DataLoader.recursively_compute_variable
def recursively_compute_variable(self, var, start_date=None, end_date=None, time_offset=None, model=None, **DataAttrs): """Compute a variable recursively, loading data where needed. An obvious requirement here is that the variabl...
python
def recursively_compute_variable(self, var, start_date=None, end_date=None, time_offset=None, model=None, **DataAttrs): """Compute a variable recursively, loading data where needed. An obvious requirement here is that the variabl...
[ "def", "recursively_compute_variable", "(", "self", ",", "var", ",", "start_date", "=", "None", ",", "end_date", "=", "None", ",", "time_offset", "=", "None", ",", "model", "=", "None", ",", "*", "*", "DataAttrs", ")", ":", "if", "var", ".", "variables",...
Compute a variable recursively, loading data where needed. An obvious requirement here is that the variable must eventually be able to be expressed in terms of model-native quantities; otherwise the recursion will never stop. Parameters ---------- var : Var ...
[ "Compute", "a", "variable", "recursively", "loading", "data", "where", "needed", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/data_loader.py#L352-L389
spencerahill/aospy
aospy/data_loader.py
DataLoader._maybe_apply_time_shift
def _maybe_apply_time_shift(da, time_offset=None, **DataAttrs): """Apply specified time shift to DataArray""" if time_offset is not None: time = times.apply_time_offset(da[TIME_STR], **time_offset) da[TIME_STR] = time return da
python
def _maybe_apply_time_shift(da, time_offset=None, **DataAttrs): """Apply specified time shift to DataArray""" if time_offset is not None: time = times.apply_time_offset(da[TIME_STR], **time_offset) da[TIME_STR] = time return da
[ "def", "_maybe_apply_time_shift", "(", "da", ",", "time_offset", "=", "None", ",", "*", "*", "DataAttrs", ")", ":", "if", "time_offset", "is", "not", "None", ":", "time", "=", "times", ".", "apply_time_offset", "(", "da", "[", "TIME_STR", "]", ",", "*", ...
Apply specified time shift to DataArray
[ "Apply", "specified", "time", "shift", "to", "DataArray" ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/data_loader.py#L392-L397
spencerahill/aospy
aospy/data_loader.py
DictDataLoader._generate_file_set
def _generate_file_set(self, var=None, start_date=None, end_date=None, domain=None, intvl_in=None, dtype_in_vert=None, dtype_in_time=None, intvl_out=None): """Returns the file_set for the given interval in.""" try: return self.file_map[in...
python
def _generate_file_set(self, var=None, start_date=None, end_date=None, domain=None, intvl_in=None, dtype_in_vert=None, dtype_in_time=None, intvl_out=None): """Returns the file_set for the given interval in.""" try: return self.file_map[in...
[ "def", "_generate_file_set", "(", "self", ",", "var", "=", "None", ",", "start_date", "=", "None", ",", "end_date", "=", "None", ",", "domain", "=", "None", ",", "intvl_in", "=", "None", ",", "dtype_in_vert", "=", "None", ",", "dtype_in_time", "=", "None...
Returns the file_set for the given interval in.
[ "Returns", "the", "file_set", "for", "the", "given", "interval", "in", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/data_loader.py#L463-L471
spencerahill/aospy
aospy/data_loader.py
GFDLDataLoader._maybe_apply_time_shift
def _maybe_apply_time_shift(da, time_offset=None, **DataAttrs): """Correct off-by-one error in GFDL instantaneous model data. Instantaneous data that is outputted by GFDL models is generally off by one timestep. For example, a netCDF file that is supposed to correspond to 6 hourly data...
python
def _maybe_apply_time_shift(da, time_offset=None, **DataAttrs): """Correct off-by-one error in GFDL instantaneous model data. Instantaneous data that is outputted by GFDL models is generally off by one timestep. For example, a netCDF file that is supposed to correspond to 6 hourly data...
[ "def", "_maybe_apply_time_shift", "(", "da", ",", "time_offset", "=", "None", ",", "*", "*", "DataAttrs", ")", ":", "if", "time_offset", "is", "not", "None", ":", "time", "=", "times", ".", "apply_time_offset", "(", "da", "[", "TIME_STR", "]", ",", "*", ...
Correct off-by-one error in GFDL instantaneous model data. Instantaneous data that is outputted by GFDL models is generally off by one timestep. For example, a netCDF file that is supposed to correspond to 6 hourly data for the month of January, will have its last time value be in Febr...
[ "Correct", "off", "-", "by", "-", "one", "error", "in", "GFDL", "instantaneous", "model", "data", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/data_loader.py#L617-L636
spencerahill/aospy
aospy/var.py
Var.to_plot_units
def to_plot_units(self, data, dtype_vert=False): """Convert the given data to plotting units.""" if dtype_vert == 'vert_av' or not dtype_vert: conv_factor = self.units.plot_units_conv elif dtype_vert == ('vert_int'): conv_factor = self.units.vert_int_plot_units_conv ...
python
def to_plot_units(self, data, dtype_vert=False): """Convert the given data to plotting units.""" if dtype_vert == 'vert_av' or not dtype_vert: conv_factor = self.units.plot_units_conv elif dtype_vert == ('vert_int'): conv_factor = self.units.vert_int_plot_units_conv ...
[ "def", "to_plot_units", "(", "self", ",", "data", ",", "dtype_vert", "=", "False", ")", ":", "if", "dtype_vert", "==", "'vert_av'", "or", "not", "dtype_vert", ":", "conv_factor", "=", "self", ".", "units", ".", "plot_units_conv", "elif", "dtype_vert", "==", ...
Convert the given data to plotting units.
[ "Convert", "the", "given", "data", "to", "plotting", "units", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/var.py#L119-L131
spencerahill/aospy
aospy/var.py
Var.mask_unphysical
def mask_unphysical(self, data): """Mask data array where values are outside physically valid range.""" if not self.valid_range: return data else: return np.ma.masked_outside(data, np.min(self.valid_range), np.max(self.valid_range))
python
def mask_unphysical(self, data): """Mask data array where values are outside physically valid range.""" if not self.valid_range: return data else: return np.ma.masked_outside(data, np.min(self.valid_range), np.max(self.valid_range))
[ "def", "mask_unphysical", "(", "self", ",", "data", ")", ":", "if", "not", "self", ".", "valid_range", ":", "return", "data", "else", ":", "return", "np", ".", "ma", ".", "masked_outside", "(", "data", ",", "np", ".", "min", "(", "self", ".", "valid_...
Mask data array where values are outside physically valid range.
[ "Mask", "data", "array", "where", "values", "are", "outside", "physically", "valid", "range", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/var.py#L133-L139
spencerahill/aospy
aospy/utils/vertcoord.py
to_radians
def to_radians(arr, is_delta=False): """Force data with units either degrees or radians to be radians.""" # Infer the units from embedded metadata, if it's there. try: units = arr.units except AttributeError: pass else: if units.lower().startswith('degrees'): warn...
python
def to_radians(arr, is_delta=False): """Force data with units either degrees or radians to be radians.""" # Infer the units from embedded metadata, if it's there. try: units = arr.units except AttributeError: pass else: if units.lower().startswith('degrees'): warn...
[ "def", "to_radians", "(", "arr", ",", "is_delta", "=", "False", ")", ":", "# Infer the units from embedded metadata, if it's there.", "try", ":", "units", "=", "arr", ".", "units", "except", "AttributeError", ":", "pass", "else", ":", "if", "units", ".", "lower"...
Force data with units either degrees or radians to be radians.
[ "Force", "data", "with", "units", "either", "degrees", "or", "radians", "to", "be", "radians", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/utils/vertcoord.py#L12-L32
spencerahill/aospy
aospy/utils/vertcoord.py
to_pascal
def to_pascal(arr, is_dp=False): """Force data with units either hPa or Pa to be in Pa.""" threshold = 400 if is_dp else 1200 if np.max(np.abs(arr)) < threshold: warn_msg = "Conversion applied: hPa -> Pa to array: {}".format(arr) logging.debug(warn_msg) return arr*100. return arr
python
def to_pascal(arr, is_dp=False): """Force data with units either hPa or Pa to be in Pa.""" threshold = 400 if is_dp else 1200 if np.max(np.abs(arr)) < threshold: warn_msg = "Conversion applied: hPa -> Pa to array: {}".format(arr) logging.debug(warn_msg) return arr*100. return arr
[ "def", "to_pascal", "(", "arr", ",", "is_dp", "=", "False", ")", ":", "threshold", "=", "400", "if", "is_dp", "else", "1200", "if", "np", ".", "max", "(", "np", ".", "abs", "(", "arr", ")", ")", "<", "threshold", ":", "warn_msg", "=", "\"Conversion...
Force data with units either hPa or Pa to be in Pa.
[ "Force", "data", "with", "units", "either", "hPa", "or", "Pa", "to", "be", "in", "Pa", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/utils/vertcoord.py#L35-L42
spencerahill/aospy
aospy/utils/vertcoord.py
to_hpa
def to_hpa(arr): """Convert pressure array from Pa to hPa (if needed).""" if np.max(np.abs(arr)) > 1200.: warn_msg = "Conversion applied: Pa -> hPa to array: {}".format(arr) logging.debug(warn_msg) return arr / 100. return arr
python
def to_hpa(arr): """Convert pressure array from Pa to hPa (if needed).""" if np.max(np.abs(arr)) > 1200.: warn_msg = "Conversion applied: Pa -> hPa to array: {}".format(arr) logging.debug(warn_msg) return arr / 100. return arr
[ "def", "to_hpa", "(", "arr", ")", ":", "if", "np", ".", "max", "(", "np", ".", "abs", "(", "arr", ")", ")", ">", "1200.", ":", "warn_msg", "=", "\"Conversion applied: Pa -> hPa to array: {}\"", ".", "format", "(", "arr", ")", "logging", ".", "debug", "...
Convert pressure array from Pa to hPa (if needed).
[ "Convert", "pressure", "array", "from", "Pa", "to", "hPa", "(", "if", "needed", ")", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/utils/vertcoord.py#L45-L51
spencerahill/aospy
aospy/utils/vertcoord.py
replace_coord
def replace_coord(arr, old_dim, new_dim, new_coord): """Replace a coordinate with new one; new and old must have same shape.""" new_arr = arr.rename({old_dim: new_dim}) new_arr[new_dim] = new_coord return new_arr
python
def replace_coord(arr, old_dim, new_dim, new_coord): """Replace a coordinate with new one; new and old must have same shape.""" new_arr = arr.rename({old_dim: new_dim}) new_arr[new_dim] = new_coord return new_arr
[ "def", "replace_coord", "(", "arr", ",", "old_dim", ",", "new_dim", ",", "new_coord", ")", ":", "new_arr", "=", "arr", ".", "rename", "(", "{", "old_dim", ":", "new_dim", "}", ")", "new_arr", "[", "new_dim", "]", "=", "new_coord", "return", "new_arr" ]
Replace a coordinate with new one; new and old must have same shape.
[ "Replace", "a", "coordinate", "with", "new", "one", ";", "new", "and", "old", "must", "have", "same", "shape", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/utils/vertcoord.py#L59-L63
spencerahill/aospy
aospy/utils/vertcoord.py
to_pfull_from_phalf
def to_pfull_from_phalf(arr, pfull_coord): """Compute data at full pressure levels from values at half levels.""" phalf_top = arr.isel(**{internal_names.PHALF_STR: slice(1, None)}) phalf_top = replace_coord(phalf_top, internal_names.PHALF_STR, internal_names.PFULL_STR, pfull_co...
python
def to_pfull_from_phalf(arr, pfull_coord): """Compute data at full pressure levels from values at half levels.""" phalf_top = arr.isel(**{internal_names.PHALF_STR: slice(1, None)}) phalf_top = replace_coord(phalf_top, internal_names.PHALF_STR, internal_names.PFULL_STR, pfull_co...
[ "def", "to_pfull_from_phalf", "(", "arr", ",", "pfull_coord", ")", ":", "phalf_top", "=", "arr", ".", "isel", "(", "*", "*", "{", "internal_names", ".", "PHALF_STR", ":", "slice", "(", "1", ",", "None", ")", "}", ")", "phalf_top", "=", "replace_coord", ...
Compute data at full pressure levels from values at half levels.
[ "Compute", "data", "at", "full", "pressure", "levels", "from", "values", "at", "half", "levels", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/utils/vertcoord.py#L66-L75
spencerahill/aospy
aospy/utils/vertcoord.py
to_phalf_from_pfull
def to_phalf_from_pfull(arr, val_toa=0, val_sfc=0): """Compute data at half pressure levels from values at full levels. Could be the pressure array itself, but it could also be any other data defined at pressure levels. Requires specification of values at surface and top of atmosphere. """ pha...
python
def to_phalf_from_pfull(arr, val_toa=0, val_sfc=0): """Compute data at half pressure levels from values at full levels. Could be the pressure array itself, but it could also be any other data defined at pressure levels. Requires specification of values at surface and top of atmosphere. """ pha...
[ "def", "to_phalf_from_pfull", "(", "arr", ",", "val_toa", "=", "0", ",", "val_sfc", "=", "0", ")", ":", "phalf", "=", "np", ".", "zeros", "(", "(", "arr", ".", "shape", "[", "0", "]", "+", "1", ",", "arr", ".", "shape", "[", "1", "]", ",", "a...
Compute data at half pressure levels from values at full levels. Could be the pressure array itself, but it could also be any other data defined at pressure levels. Requires specification of values at surface and top of atmosphere.
[ "Compute", "data", "at", "half", "pressure", "levels", "from", "values", "at", "full", "levels", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/utils/vertcoord.py#L78-L89
spencerahill/aospy
aospy/utils/vertcoord.py
pfull_from_ps
def pfull_from_ps(bk, pk, ps, pfull_coord): """Compute pressure at full levels from surface pressure.""" return to_pfull_from_phalf(phalf_from_ps(bk, pk, ps), pfull_coord)
python
def pfull_from_ps(bk, pk, ps, pfull_coord): """Compute pressure at full levels from surface pressure.""" return to_pfull_from_phalf(phalf_from_ps(bk, pk, ps), pfull_coord)
[ "def", "pfull_from_ps", "(", "bk", ",", "pk", ",", "ps", ",", "pfull_coord", ")", ":", "return", "to_pfull_from_phalf", "(", "phalf_from_ps", "(", "bk", ",", "pk", ",", "ps", ")", ",", "pfull_coord", ")" ]
Compute pressure at full levels from surface pressure.
[ "Compute", "pressure", "at", "full", "levels", "from", "surface", "pressure", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/utils/vertcoord.py#L92-L94
spencerahill/aospy
aospy/utils/vertcoord.py
d_deta_from_phalf
def d_deta_from_phalf(arr, pfull_coord): """Compute pressure level thickness from half level pressures.""" d_deta = arr.diff(dim=internal_names.PHALF_STR, n=1) return replace_coord(d_deta, internal_names.PHALF_STR, internal_names.PFULL_STR, pfull_coord)
python
def d_deta_from_phalf(arr, pfull_coord): """Compute pressure level thickness from half level pressures.""" d_deta = arr.diff(dim=internal_names.PHALF_STR, n=1) return replace_coord(d_deta, internal_names.PHALF_STR, internal_names.PFULL_STR, pfull_coord)
[ "def", "d_deta_from_phalf", "(", "arr", ",", "pfull_coord", ")", ":", "d_deta", "=", "arr", ".", "diff", "(", "dim", "=", "internal_names", ".", "PHALF_STR", ",", "n", "=", "1", ")", "return", "replace_coord", "(", "d_deta", ",", "internal_names", ".", "...
Compute pressure level thickness from half level pressures.
[ "Compute", "pressure", "level", "thickness", "from", "half", "level", "pressures", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/utils/vertcoord.py#L97-L101
spencerahill/aospy
aospy/utils/vertcoord.py
d_deta_from_pfull
def d_deta_from_pfull(arr): """Compute $\partial/\partial\eta$ of the array on full hybrid levels. $\eta$ is the model vertical coordinate, and its value is assumed to simply increment by 1 from 0 at the surface upwards. The data to be differenced is assumed to be defined at full pressure levels. ...
python
def d_deta_from_pfull(arr): """Compute $\partial/\partial\eta$ of the array on full hybrid levels. $\eta$ is the model vertical coordinate, and its value is assumed to simply increment by 1 from 0 at the surface upwards. The data to be differenced is assumed to be defined at full pressure levels. ...
[ "def", "d_deta_from_pfull", "(", "arr", ")", ":", "# noqa: W605", "right", "=", "arr", "[", "{", "internal_names", ".", "PFULL_STR", ":", "slice", "(", "2", ",", "None", ",", "None", ")", "}", "]", ".", "values", "left", "=", "arr", "[", "{", "intern...
Compute $\partial/\partial\eta$ of the array on full hybrid levels. $\eta$ is the model vertical coordinate, and its value is assumed to simply increment by 1 from 0 at the surface upwards. The data to be differenced is assumed to be defined at full pressure levels. Parameters ---------- arr ...
[ "Compute", "$", "\\", "partial", "/", "\\", "partial", "\\", "eta$", "of", "the", "array", "on", "full", "hybrid", "levels", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/utils/vertcoord.py#L104-L131
spencerahill/aospy
aospy/utils/vertcoord.py
dp_from_ps
def dp_from_ps(bk, pk, ps, pfull_coord): """Compute pressure level thickness from surface pressure""" return d_deta_from_phalf(phalf_from_ps(bk, pk, ps), pfull_coord)
python
def dp_from_ps(bk, pk, ps, pfull_coord): """Compute pressure level thickness from surface pressure""" return d_deta_from_phalf(phalf_from_ps(bk, pk, ps), pfull_coord)
[ "def", "dp_from_ps", "(", "bk", ",", "pk", ",", "ps", ",", "pfull_coord", ")", ":", "return", "d_deta_from_phalf", "(", "phalf_from_ps", "(", "bk", ",", "pk", ",", "ps", ")", ",", "pfull_coord", ")" ]
Compute pressure level thickness from surface pressure
[ "Compute", "pressure", "level", "thickness", "from", "surface", "pressure" ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/utils/vertcoord.py#L134-L136
spencerahill/aospy
aospy/utils/vertcoord.py
integrate
def integrate(arr, ddim, dim=False, is_pressure=False): """Integrate along the given dimension.""" if is_pressure: dim = vert_coord_name(ddim) return (arr*ddim).sum(dim=dim)
python
def integrate(arr, ddim, dim=False, is_pressure=False): """Integrate along the given dimension.""" if is_pressure: dim = vert_coord_name(ddim) return (arr*ddim).sum(dim=dim)
[ "def", "integrate", "(", "arr", ",", "ddim", ",", "dim", "=", "False", ",", "is_pressure", "=", "False", ")", ":", "if", "is_pressure", ":", "dim", "=", "vert_coord_name", "(", "ddim", ")", "return", "(", "arr", "*", "ddim", ")", ".", "sum", "(", "...
Integrate along the given dimension.
[ "Integrate", "along", "the", "given", "dimension", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/utils/vertcoord.py#L139-L143
spencerahill/aospy
aospy/utils/vertcoord.py
get_dim_name
def get_dim_name(arr, names): """Determine if an object has an attribute name matching a given list.""" for name in names: # TODO: raise warning/exception when multiple names arr attrs. if hasattr(arr, name): return name raise AttributeError("No attributes of the object `{0}` mat...
python
def get_dim_name(arr, names): """Determine if an object has an attribute name matching a given list.""" for name in names: # TODO: raise warning/exception when multiple names arr attrs. if hasattr(arr, name): return name raise AttributeError("No attributes of the object `{0}` mat...
[ "def", "get_dim_name", "(", "arr", ",", "names", ")", ":", "for", "name", "in", "names", ":", "# TODO: raise warning/exception when multiple names arr attrs.", "if", "hasattr", "(", "arr", ",", "name", ")", ":", "return", "name", "raise", "AttributeError", "(", ...
Determine if an object has an attribute name matching a given list.
[ "Determine", "if", "an", "object", "has", "an", "attribute", "name", "matching", "a", "given", "list", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/utils/vertcoord.py#L146-L153
spencerahill/aospy
aospy/utils/vertcoord.py
int_dp_g
def int_dp_g(arr, dp): """Mass weighted integral.""" return integrate(arr, to_pascal(dp, is_dp=True), vert_coord_name(dp)) / GRAV_EARTH
python
def int_dp_g(arr, dp): """Mass weighted integral.""" return integrate(arr, to_pascal(dp, is_dp=True), vert_coord_name(dp)) / GRAV_EARTH
[ "def", "int_dp_g", "(", "arr", ",", "dp", ")", ":", "return", "integrate", "(", "arr", ",", "to_pascal", "(", "dp", ",", "is_dp", "=", "True", ")", ",", "vert_coord_name", "(", "dp", ")", ")", "/", "GRAV_EARTH" ]
Mass weighted integral.
[ "Mass", "weighted", "integral", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/utils/vertcoord.py#L161-L164
spencerahill/aospy
aospy/utils/vertcoord.py
dp_from_p
def dp_from_p(p, ps, p_top=0., p_bot=1.1e5): """Get level thickness of pressure data, incorporating surface pressure. Level edges are defined as halfway between the levels, as well as the user- specified uppermost and lowermost values. The dp of levels whose bottom pressure is less than the surface pr...
python
def dp_from_p(p, ps, p_top=0., p_bot=1.1e5): """Get level thickness of pressure data, incorporating surface pressure. Level edges are defined as halfway between the levels, as well as the user- specified uppermost and lowermost values. The dp of levels whose bottom pressure is less than the surface pr...
[ "def", "dp_from_p", "(", "p", ",", "ps", ",", "p_top", "=", "0.", ",", "p_bot", "=", "1.1e5", ")", ":", "p_str", "=", "get_dim_name", "(", "p", ",", "(", "internal_names", ".", "PLEVEL_STR", ",", "'plev'", ")", ")", "p_vals", "=", "to_pascal", "(", ...
Get level thickness of pressure data, incorporating surface pressure. Level edges are defined as halfway between the levels, as well as the user- specified uppermost and lowermost values. The dp of levels whose bottom pressure is less than the surface pressure is not changed by ps, since they don't in...
[ "Get", "level", "thickness", "of", "pressure", "data", "incorporating", "surface", "pressure", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/utils/vertcoord.py#L167-L228
spencerahill/aospy
aospy/utils/vertcoord.py
level_thickness
def level_thickness(p, p_top=0., p_bot=1.01325e5): """ Calculates the thickness, in Pa, of each pressure level. Assumes that the pressure values given are at the center of that model level, except for the lowest value (typically 1000 hPa), which is the bottom boundary. The uppermost level extends t...
python
def level_thickness(p, p_top=0., p_bot=1.01325e5): """ Calculates the thickness, in Pa, of each pressure level. Assumes that the pressure values given are at the center of that model level, except for the lowest value (typically 1000 hPa), which is the bottom boundary. The uppermost level extends t...
[ "def", "level_thickness", "(", "p", ",", "p_top", "=", "0.", ",", "p_bot", "=", "1.01325e5", ")", ":", "p_vals", "=", "to_pascal", "(", "p", ".", "values", ".", "copy", "(", ")", ")", "dp_vals", "=", "np", ".", "empty_like", "(", "p_vals", ")", "# ...
Calculates the thickness, in Pa, of each pressure level. Assumes that the pressure values given are at the center of that model level, except for the lowest value (typically 1000 hPa), which is the bottom boundary. The uppermost level extends to 0 hPa. Unlike `dp_from_p`, this does not incorporate the...
[ "Calculates", "the", "thickness", "in", "Pa", "of", "each", "pressure", "level", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/utils/vertcoord.py#L231-L252
spencerahill/aospy
aospy/utils/vertcoord.py
does_coord_increase_w_index
def does_coord_increase_w_index(arr): """Determine if the array values increase with the index. Useful, e.g., for pressure, which sometimes is indexed surface to TOA and sometimes the opposite. """ diff = np.diff(arr) if not np.all(np.abs(np.sign(diff))): raise ValueError("Array is not ...
python
def does_coord_increase_w_index(arr): """Determine if the array values increase with the index. Useful, e.g., for pressure, which sometimes is indexed surface to TOA and sometimes the opposite. """ diff = np.diff(arr) if not np.all(np.abs(np.sign(diff))): raise ValueError("Array is not ...
[ "def", "does_coord_increase_w_index", "(", "arr", ")", ":", "diff", "=", "np", ".", "diff", "(", "arr", ")", "if", "not", "np", ".", "all", "(", "np", ".", "abs", "(", "np", ".", "sign", "(", "diff", ")", ")", ")", ":", "raise", "ValueError", "("...
Determine if the array values increase with the index. Useful, e.g., for pressure, which sometimes is indexed surface to TOA and sometimes the opposite.
[ "Determine", "if", "the", "array", "values", "increase", "with", "the", "index", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/utils/vertcoord.py#L255-L265
spencerahill/aospy
aospy/utils/times.py
apply_time_offset
def apply_time_offset(time, years=0, months=0, days=0, hours=0): """Apply a specified offset to the given time array. This is useful for GFDL model output of instantaneous values. For example, 3 hourly data postprocessed to netCDF files spanning 1 year each will actually have time values that are offs...
python
def apply_time_offset(time, years=0, months=0, days=0, hours=0): """Apply a specified offset to the given time array. This is useful for GFDL model output of instantaneous values. For example, 3 hourly data postprocessed to netCDF files spanning 1 year each will actually have time values that are offs...
[ "def", "apply_time_offset", "(", "time", ",", "years", "=", "0", ",", "months", "=", "0", ",", "days", "=", "0", ",", "hours", "=", "0", ")", ":", "return", "(", "pd", ".", "to_datetime", "(", "time", ".", "values", ")", "+", "pd", ".", "DateOffs...
Apply a specified offset to the given time array. This is useful for GFDL model output of instantaneous values. For example, 3 hourly data postprocessed to netCDF files spanning 1 year each will actually have time values that are offset by 3 hours, such that the first value is for 1 Jan 03:00 and the ...
[ "Apply", "a", "specified", "offset", "to", "the", "given", "time", "array", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/utils/times.py#L19-L58
spencerahill/aospy
aospy/utils/times.py
average_time_bounds
def average_time_bounds(ds): """Return the average of each set of time bounds in the Dataset. Useful for creating a new time array to replace the Dataset's native time array, in the case that the latter matches either the start or end bounds. This can cause errors in grouping (akin to an off-by-one err...
python
def average_time_bounds(ds): """Return the average of each set of time bounds in the Dataset. Useful for creating a new time array to replace the Dataset's native time array, in the case that the latter matches either the start or end bounds. This can cause errors in grouping (akin to an off-by-one err...
[ "def", "average_time_bounds", "(", "ds", ")", ":", "bounds", "=", "ds", "[", "TIME_BOUNDS_STR", "]", "new_times", "=", "bounds", ".", "mean", "(", "dim", "=", "BOUNDS_STR", ",", "keep_attrs", "=", "True", ")", "new_times", "=", "new_times", ".", "drop", ...
Return the average of each set of time bounds in the Dataset. Useful for creating a new time array to replace the Dataset's native time array, in the case that the latter matches either the start or end bounds. This can cause errors in grouping (akin to an off-by-one error) if the timesteps span e.g. o...
[ "Return", "the", "average", "of", "each", "set", "of", "time", "bounds", "in", "the", "Dataset", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/utils/times.py#L61-L95
spencerahill/aospy
aospy/utils/times.py
monthly_mean_at_each_ind
def monthly_mean_at_each_ind(monthly_means, sub_monthly_timeseries): """Copy monthly mean over each time index in that month. Parameters ---------- monthly_means : xarray.DataArray array of monthly means sub_monthly_timeseries : xarray.DataArray array of a timeseries at sub-monthly ...
python
def monthly_mean_at_each_ind(monthly_means, sub_monthly_timeseries): """Copy monthly mean over each time index in that month. Parameters ---------- monthly_means : xarray.DataArray array of monthly means sub_monthly_timeseries : xarray.DataArray array of a timeseries at sub-monthly ...
[ "def", "monthly_mean_at_each_ind", "(", "monthly_means", ",", "sub_monthly_timeseries", ")", ":", "time", "=", "monthly_means", "[", "TIME_STR", "]", "start", "=", "time", ".", "indexes", "[", "TIME_STR", "]", "[", "0", "]", ".", "replace", "(", "day", "=", ...
Copy monthly mean over each time index in that month. Parameters ---------- monthly_means : xarray.DataArray array of monthly means sub_monthly_timeseries : xarray.DataArray array of a timeseries at sub-monthly time resolution Returns ------- xarray.DataArray with eath mont...
[ "Copy", "monthly", "mean", "over", "each", "time", "index", "in", "that", "month", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/utils/times.py#L121-L145
spencerahill/aospy
aospy/utils/times.py
yearly_average
def yearly_average(arr, dt): """Average a sub-yearly time-series over each year. Resulting timeseries comprises one value for each year in which the original array had valid data. Accounts for (i.e. ignores) masked values in original data when computing the annual averages. Parameters -------...
python
def yearly_average(arr, dt): """Average a sub-yearly time-series over each year. Resulting timeseries comprises one value for each year in which the original array had valid data. Accounts for (i.e. ignores) masked values in original data when computing the annual averages. Parameters -------...
[ "def", "yearly_average", "(", "arr", ",", "dt", ")", ":", "assert_matching_time_coord", "(", "arr", ",", "dt", ")", "yr_str", "=", "TIME_STR", "+", "'.year'", "# Retain original data's mask.", "dt", "=", "dt", ".", "where", "(", "np", ".", "isfinite", "(", ...
Average a sub-yearly time-series over each year. Resulting timeseries comprises one value for each year in which the original array had valid data. Accounts for (i.e. ignores) masked values in original data when computing the annual averages. Parameters ---------- arr : xarray.DataArray ...
[ "Average", "a", "sub", "-", "yearly", "time", "-", "series", "over", "each", "year", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/utils/times.py#L148-L175
spencerahill/aospy
aospy/utils/times.py
ensure_datetime
def ensure_datetime(obj): """Return the object if it is a datetime-like object Parameters ---------- obj : Object to be tested. Returns ------- The original object if it is a datetime-like object Raises ------ TypeError if `obj` is not datetime-like """ _VALID_TYPES = ...
python
def ensure_datetime(obj): """Return the object if it is a datetime-like object Parameters ---------- obj : Object to be tested. Returns ------- The original object if it is a datetime-like object Raises ------ TypeError if `obj` is not datetime-like """ _VALID_TYPES = ...
[ "def", "ensure_datetime", "(", "obj", ")", ":", "_VALID_TYPES", "=", "(", "str", ",", "datetime", ".", "datetime", ",", "cftime", ".", "datetime", ",", "np", ".", "datetime64", ")", "if", "isinstance", "(", "obj", ",", "_VALID_TYPES", ")", ":", "return",...
Return the object if it is a datetime-like object Parameters ---------- obj : Object to be tested. Returns ------- The original object if it is a datetime-like object Raises ------ TypeError if `obj` is not datetime-like
[ "Return", "the", "object", "if", "it", "is", "a", "datetime", "-", "like", "object" ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/utils/times.py#L178-L198
spencerahill/aospy
aospy/utils/times.py
month_indices
def month_indices(months): """Convert string labels for months to integer indices. Parameters ---------- months : str, int If int, number of the desired month, where January=1, February=2, etc. If str, must match either 'ann' or some subset of 'jfmamjjasond'. If 'ann', use...
python
def month_indices(months): """Convert string labels for months to integer indices. Parameters ---------- months : str, int If int, number of the desired month, where January=1, February=2, etc. If str, must match either 'ann' or some subset of 'jfmamjjasond'. If 'ann', use...
[ "def", "month_indices", "(", "months", ")", ":", "if", "not", "isinstance", "(", "months", ",", "(", "int", ",", "str", ")", ")", ":", "raise", "TypeError", "(", "\"`months` must be of type int or str: \"", "\"type(months) == {}\"", ".", "format", "(", "type", ...
Convert string labels for months to integer indices. Parameters ---------- months : str, int If int, number of the desired month, where January=1, February=2, etc. If str, must match either 'ann' or some subset of 'jfmamjjasond'. If 'ann', use all months. Otherwise, use the ...
[ "Convert", "string", "labels", "for", "months", "to", "integer", "indices", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/utils/times.py#L221-L262
spencerahill/aospy
aospy/utils/times.py
_month_conditional
def _month_conditional(time, months): """Create a conditional statement for selecting data in a DataArray. Parameters ---------- time : xarray.DataArray Array of times for which to subsample for specific months. months : int, str, or xarray.DataArray of times If int or str, passed ...
python
def _month_conditional(time, months): """Create a conditional statement for selecting data in a DataArray. Parameters ---------- time : xarray.DataArray Array of times for which to subsample for specific months. months : int, str, or xarray.DataArray of times If int or str, passed ...
[ "def", "_month_conditional", "(", "time", ",", "months", ")", ":", "if", "isinstance", "(", "months", ",", "(", "int", ",", "str", ")", ")", ":", "months_array", "=", "month_indices", "(", "months", ")", "else", ":", "months_array", "=", "months", "cond"...
Create a conditional statement for selecting data in a DataArray. Parameters ---------- time : xarray.DataArray Array of times for which to subsample for specific months. months : int, str, or xarray.DataArray of times If int or str, passed to `month_indices` Returns ------- ...
[ "Create", "a", "conditional", "statement", "for", "selecting", "data", "in", "a", "DataArray", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/utils/times.py#L265-L289
spencerahill/aospy
aospy/utils/times.py
extract_months
def extract_months(time, months): """Extract times within specified months of the year. Parameters ---------- time : xarray.DataArray Array of times that can be represented by numpy.datetime64 objects (i.e. the year is between 1678 and 2262). months : Desired months of the year to...
python
def extract_months(time, months): """Extract times within specified months of the year. Parameters ---------- time : xarray.DataArray Array of times that can be represented by numpy.datetime64 objects (i.e. the year is between 1678 and 2262). months : Desired months of the year to...
[ "def", "extract_months", "(", "time", ",", "months", ")", ":", "inds", "=", "_month_conditional", "(", "time", ",", "months", ")", "return", "time", ".", "sel", "(", "time", "=", "inds", ")" ]
Extract times within specified months of the year. Parameters ---------- time : xarray.DataArray Array of times that can be represented by numpy.datetime64 objects (i.e. the year is between 1678 and 2262). months : Desired months of the year to include Returns ------- xar...
[ "Extract", "times", "within", "specified", "months", "of", "the", "year", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/utils/times.py#L292-L307
spencerahill/aospy
aospy/utils/times.py
ensure_time_avg_has_cf_metadata
def ensure_time_avg_has_cf_metadata(ds): """Add time interval length and bounds coordinates for time avg data. If the Dataset or DataArray contains time average data, enforce that there are coordinates that track the lower and upper bounds of the time intervals, and that there is a coordinate that trac...
python
def ensure_time_avg_has_cf_metadata(ds): """Add time interval length and bounds coordinates for time avg data. If the Dataset or DataArray contains time average data, enforce that there are coordinates that track the lower and upper bounds of the time intervals, and that there is a coordinate that trac...
[ "def", "ensure_time_avg_has_cf_metadata", "(", "ds", ")", ":", "# noqa: E501", "if", "TIME_WEIGHTS_STR", "not", "in", "ds", ":", "time_weights", "=", "ds", "[", "TIME_BOUNDS_STR", "]", ".", "diff", "(", "BOUNDS_STR", ")", "time_weights", "=", "time_weights", "."...
Add time interval length and bounds coordinates for time avg data. If the Dataset or DataArray contains time average data, enforce that there are coordinates that track the lower and upper bounds of the time intervals, and that there is a coordinate that tracks the amount of time per time average inter...
[ "Add", "time", "interval", "length", "and", "bounds", "coordinates", "for", "time", "avg", "data", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/utils/times.py#L310-L357
spencerahill/aospy
aospy/utils/times.py
add_uniform_time_weights
def add_uniform_time_weights(ds): """Append uniform time weights to a Dataset. All DataArrays with a time coordinate require a time weights coordinate. For Datasets read in without a time bounds coordinate or explicit time weights built in, aospy adds uniform time weights at each point in the time ...
python
def add_uniform_time_weights(ds): """Append uniform time weights to a Dataset. All DataArrays with a time coordinate require a time weights coordinate. For Datasets read in without a time bounds coordinate or explicit time weights built in, aospy adds uniform time weights at each point in the time ...
[ "def", "add_uniform_time_weights", "(", "ds", ")", ":", "time", "=", "ds", "[", "TIME_STR", "]", "unit_interval", "=", "time", ".", "attrs", "[", "'units'", "]", ".", "split", "(", "'since'", ")", "[", "0", "]", ".", "strip", "(", ")", "time_weights", ...
Append uniform time weights to a Dataset. All DataArrays with a time coordinate require a time weights coordinate. For Datasets read in without a time bounds coordinate or explicit time weights built in, aospy adds uniform time weights at each point in the time coordinate. Parameters ---------...
[ "Append", "uniform", "time", "weights", "to", "a", "Dataset", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/utils/times.py#L360-L383
spencerahill/aospy
aospy/utils/times.py
_assert_has_data_for_time
def _assert_has_data_for_time(da, start_date, end_date): """Check to make sure data is in Dataset for the given time range. Parameters ---------- da : DataArray DataArray with a time variable start_date : datetime-like object or str start date end_date : datetime-like object o...
python
def _assert_has_data_for_time(da, start_date, end_date): """Check to make sure data is in Dataset for the given time range. Parameters ---------- da : DataArray DataArray with a time variable start_date : datetime-like object or str start date end_date : datetime-like object o...
[ "def", "_assert_has_data_for_time", "(", "da", ",", "start_date", ",", "end_date", ")", ":", "if", "isinstance", "(", "start_date", ",", "str", ")", "and", "isinstance", "(", "end_date", ",", "str", ")", ":", "logging", ".", "warning", "(", "'When using stri...
Check to make sure data is in Dataset for the given time range. Parameters ---------- da : DataArray DataArray with a time variable start_date : datetime-like object or str start date end_date : datetime-like object or str end date Raises ------ AssertionErro...
[ "Check", "to", "make", "sure", "data", "is", "in", "Dataset", "for", "the", "given", "time", "range", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/utils/times.py#L386-L431
spencerahill/aospy
aospy/utils/times.py
sel_time
def sel_time(da, start_date, end_date): """Subset a DataArray or Dataset for a given date range. Ensures that data are present for full extent of requested range. Appends start and end date of the subset to the DataArray. Parameters ---------- da : DataArray or Dataset data to subset ...
python
def sel_time(da, start_date, end_date): """Subset a DataArray or Dataset for a given date range. Ensures that data are present for full extent of requested range. Appends start and end date of the subset to the DataArray. Parameters ---------- da : DataArray or Dataset data to subset ...
[ "def", "sel_time", "(", "da", ",", "start_date", ",", "end_date", ")", ":", "_assert_has_data_for_time", "(", "da", ",", "start_date", ",", "end_date", ")", "da", "[", "SUBSET_START_DATE_STR", "]", "=", "xr", ".", "DataArray", "(", "start_date", ")", "da", ...
Subset a DataArray or Dataset for a given date range. Ensures that data are present for full extent of requested range. Appends start and end date of the subset to the DataArray. Parameters ---------- da : DataArray or Dataset data to subset start_date : np.datetime64 start of ...
[ "Subset", "a", "DataArray", "or", "Dataset", "for", "a", "given", "date", "range", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/utils/times.py#L434-L463
spencerahill/aospy
aospy/utils/times.py
assert_matching_time_coord
def assert_matching_time_coord(arr1, arr2): """Check to see if two DataArrays have the same time coordinate. Parameters ---------- arr1 : DataArray or Dataset First DataArray or Dataset arr2 : DataArray or Dataset Second DataArray or Dataset Raises ------ ValueError ...
python
def assert_matching_time_coord(arr1, arr2): """Check to see if two DataArrays have the same time coordinate. Parameters ---------- arr1 : DataArray or Dataset First DataArray or Dataset arr2 : DataArray or Dataset Second DataArray or Dataset Raises ------ ValueError ...
[ "def", "assert_matching_time_coord", "(", "arr1", ",", "arr2", ")", ":", "message", "=", "(", "'Time weights not indexed by the same time coordinate as'", "' computed data. This will lead to an improperly computed'", "' time weighted average. Exiting.\\n'", "'arr1: {}\\narr2: {}'", "...
Check to see if two DataArrays have the same time coordinate. Parameters ---------- arr1 : DataArray or Dataset First DataArray or Dataset arr2 : DataArray or Dataset Second DataArray or Dataset Raises ------ ValueError If the time coordinates are not identical betw...
[ "Check", "to", "see", "if", "two", "DataArrays", "have", "the", "same", "time", "coordinate", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/utils/times.py#L466-L486
spencerahill/aospy
aospy/utils/times.py
ensure_time_as_index
def ensure_time_as_index(ds): """Ensures that time is an indexed coordinate on relevant quantites. Sometimes when the data we load from disk has only one timestep, the indexing of time-defined quantities in the resulting xarray.Dataset gets messed up, in that the time bounds array and data variables do...
python
def ensure_time_as_index(ds): """Ensures that time is an indexed coordinate on relevant quantites. Sometimes when the data we load from disk has only one timestep, the indexing of time-defined quantities in the resulting xarray.Dataset gets messed up, in that the time bounds array and data variables do...
[ "def", "ensure_time_as_index", "(", "ds", ")", ":", "time_indexed_coords", "=", "{", "TIME_WEIGHTS_STR", ",", "TIME_BOUNDS_STR", "}", "time_indexed_vars", "=", "set", "(", "ds", ".", "data_vars", ")", ".", "union", "(", "time_indexed_coords", ")", "time_indexed_va...
Ensures that time is an indexed coordinate on relevant quantites. Sometimes when the data we load from disk has only one timestep, the indexing of time-defined quantities in the resulting xarray.Dataset gets messed up, in that the time bounds array and data variables don't get indexed by time, even tho...
[ "Ensures", "that", "time", "is", "an", "indexed", "coordinate", "on", "relevant", "quantites", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/utils/times.py#L489-L522
spencerahill/aospy
aospy/utils/times.py
infer_year
def infer_year(date): """Given a datetime-like object or string infer the year. Parameters ---------- date : datetime-like object or str Input date Returns ------- int Examples -------- >>> infer_year('2000') 2000 >>> infer_year('2000-01') 2000 >>> infe...
python
def infer_year(date): """Given a datetime-like object or string infer the year. Parameters ---------- date : datetime-like object or str Input date Returns ------- int Examples -------- >>> infer_year('2000') 2000 >>> infer_year('2000-01') 2000 >>> infe...
[ "def", "infer_year", "(", "date", ")", ":", "if", "isinstance", "(", "date", ",", "str", ")", ":", "# Look for a string that begins with four numbers; the first four", "# numbers found are the year.", "pattern", "=", "r'(?P<year>\\d{4})'", "result", "=", "re", ".", "mat...
Given a datetime-like object or string infer the year. Parameters ---------- date : datetime-like object or str Input date Returns ------- int Examples -------- >>> infer_year('2000') 2000 >>> infer_year('2000-01') 2000 >>> infer_year('2000-01-31') 2000...
[ "Given", "a", "datetime", "-", "like", "object", "or", "string", "infer", "the", "year", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/utils/times.py#L525-L565
spencerahill/aospy
aospy/utils/times.py
maybe_convert_to_index_date_type
def maybe_convert_to_index_date_type(index, date): """Convert a datetime-like object to the index's date type. Datetime indexing in xarray can be done using either a pandas DatetimeIndex or a CFTimeIndex. Both support partial-datetime string indexing regardless of the calendar type of the underlying d...
python
def maybe_convert_to_index_date_type(index, date): """Convert a datetime-like object to the index's date type. Datetime indexing in xarray can be done using either a pandas DatetimeIndex or a CFTimeIndex. Both support partial-datetime string indexing regardless of the calendar type of the underlying d...
[ "def", "maybe_convert_to_index_date_type", "(", "index", ",", "date", ")", ":", "if", "isinstance", "(", "date", ",", "str", ")", ":", "return", "date", "if", "isinstance", "(", "index", ",", "pd", ".", "DatetimeIndex", ")", ":", "if", "isinstance", "(", ...
Convert a datetime-like object to the index's date type. Datetime indexing in xarray can be done using either a pandas DatetimeIndex or a CFTimeIndex. Both support partial-datetime string indexing regardless of the calendar type of the underlying data; therefore if a string is passed as a date, we ret...
[ "Convert", "a", "datetime", "-", "like", "object", "to", "the", "index", "s", "date", "type", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/utils/times.py#L568-L614
spencerahill/aospy
aospy/region.py
Region._make_mask
def _make_mask(self, data, lon_str=LON_STR, lat_str=LAT_STR): """Construct the mask that defines a region on a given data's grid.""" mask = False for west, east, south, north in self.mask_bounds: if west < east: mask_lon = (data[lon_str] > west) & (data[lon_str] < eas...
python
def _make_mask(self, data, lon_str=LON_STR, lat_str=LAT_STR): """Construct the mask that defines a region on a given data's grid.""" mask = False for west, east, south, north in self.mask_bounds: if west < east: mask_lon = (data[lon_str] > west) & (data[lon_str] < eas...
[ "def", "_make_mask", "(", "self", ",", "data", ",", "lon_str", "=", "LON_STR", ",", "lat_str", "=", "LAT_STR", ")", ":", "mask", "=", "False", "for", "west", ",", "east", ",", "south", ",", "north", "in", "self", ".", "mask_bounds", ":", "if", "west"...
Construct the mask that defines a region on a given data's grid.
[ "Construct", "the", "mask", "that", "defines", "a", "region", "on", "a", "given", "data", "s", "grid", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/region.py#L220-L230
spencerahill/aospy
aospy/region.py
Region.mask_var
def mask_var(self, data, lon_cyclic=True, lon_str=LON_STR, lat_str=LAT_STR): """Mask the given data outside this region. Parameters ---------- data : xarray.DataArray The array to be regionally masked. lon_cyclic : bool, optional (default True) ...
python
def mask_var(self, data, lon_cyclic=True, lon_str=LON_STR, lat_str=LAT_STR): """Mask the given data outside this region. Parameters ---------- data : xarray.DataArray The array to be regionally masked. lon_cyclic : bool, optional (default True) ...
[ "def", "mask_var", "(", "self", ",", "data", ",", "lon_cyclic", "=", "True", ",", "lon_str", "=", "LON_STR", ",", "lat_str", "=", "LAT_STR", ")", ":", "# TODO: is this still necessary?", "if", "not", "lon_cyclic", ":", "if", "self", ".", "west_bound", ">", ...
Mask the given data outside this region. Parameters ---------- data : xarray.DataArray The array to be regionally masked. lon_cyclic : bool, optional (default True) Whether or not the longitudes of ``data`` span the whole globe, meaning that they shou...
[ "Mask", "the", "given", "data", "outside", "this", "region", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/region.py#L232-L264
spencerahill/aospy
aospy/region.py
Region.ts
def ts(self, data, lon_cyclic=True, lon_str=LON_STR, lat_str=LAT_STR, land_mask_str=LAND_MASK_STR, sfc_area_str=SFC_AREA_STR): """Create yearly time-series of region-averaged data. Parameters ---------- data : xarray.DataArray The array to create the regional time...
python
def ts(self, data, lon_cyclic=True, lon_str=LON_STR, lat_str=LAT_STR, land_mask_str=LAND_MASK_STR, sfc_area_str=SFC_AREA_STR): """Create yearly time-series of region-averaged data. Parameters ---------- data : xarray.DataArray The array to create the regional time...
[ "def", "ts", "(", "self", ",", "data", ",", "lon_cyclic", "=", "True", ",", "lon_str", "=", "LON_STR", ",", "lat_str", "=", "LAT_STR", ",", "land_mask_str", "=", "LAND_MASK_STR", ",", "sfc_area_str", "=", "SFC_AREA_STR", ")", ":", "data_masked", "=", "self...
Create yearly time-series of region-averaged data. Parameters ---------- data : xarray.DataArray The array to create the regional timeseries of lon_cyclic : { None, True, False }, optional (default True) Whether or not the longitudes of ``data`` span the whole gl...
[ "Create", "yearly", "time", "-", "series", "of", "region", "-", "averaged", "data", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/region.py#L266-L304
spencerahill/aospy
aospy/region.py
Region.av
def av(self, data, lon_str=LON_STR, lat_str=LAT_STR, land_mask_str=LAND_MASK_STR, sfc_area_str=SFC_AREA_STR): """Time-average of region-averaged data. Parameters ---------- data : xarray.DataArray The array to compute the regional time-average of lat_str, ...
python
def av(self, data, lon_str=LON_STR, lat_str=LAT_STR, land_mask_str=LAND_MASK_STR, sfc_area_str=SFC_AREA_STR): """Time-average of region-averaged data. Parameters ---------- data : xarray.DataArray The array to compute the regional time-average of lat_str, ...
[ "def", "av", "(", "self", ",", "data", ",", "lon_str", "=", "LON_STR", ",", "lat_str", "=", "LAT_STR", ",", "land_mask_str", "=", "LAND_MASK_STR", ",", "sfc_area_str", "=", "SFC_AREA_STR", ")", ":", "ts", "=", "self", ".", "ts", "(", "data", ",", "lon_...
Time-average of region-averaged data. Parameters ---------- data : xarray.DataArray The array to compute the regional time-average of lat_str, lon_str, land_mask_str, sfc_area_str : str, optional The name of the latitude, longitude, land mask, and surface area ...
[ "Time", "-", "average", "of", "region", "-", "averaged", "data", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/region.py#L306-L330
spencerahill/aospy
aospy/model.py
_rename_coords
def _rename_coords(ds, attrs): """Rename coordinates to aospy's internal names.""" for name_int, names_ext in attrs.items(): # Check if coord is in dataset already. ds_coord_name = set(names_ext).intersection(set(ds.coords)) if ds_coord_name: # Rename to the aospy internal na...
python
def _rename_coords(ds, attrs): """Rename coordinates to aospy's internal names.""" for name_int, names_ext in attrs.items(): # Check if coord is in dataset already. ds_coord_name = set(names_ext).intersection(set(ds.coords)) if ds_coord_name: # Rename to the aospy internal na...
[ "def", "_rename_coords", "(", "ds", ",", "attrs", ")", ":", "for", "name_int", ",", "names_ext", "in", "attrs", ".", "items", "(", ")", ":", "# Check if coord is in dataset already.", "ds_coord_name", "=", "set", "(", "names_ext", ")", ".", "intersection", "("...
Rename coordinates to aospy's internal names.
[ "Rename", "coordinates", "to", "aospy", "s", "internal", "names", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/model.py#L21-L36
spencerahill/aospy
aospy/model.py
_bounds_from_array
def _bounds_from_array(arr, dim_name, bounds_name): """Get the bounds of an array given its center values. E.g. if lat-lon grid center lat/lon values are known, but not the bounds of each grid box. The algorithm assumes that the bounds are simply halfway between each pair of center values. """ ...
python
def _bounds_from_array(arr, dim_name, bounds_name): """Get the bounds of an array given its center values. E.g. if lat-lon grid center lat/lon values are known, but not the bounds of each grid box. The algorithm assumes that the bounds are simply halfway between each pair of center values. """ ...
[ "def", "_bounds_from_array", "(", "arr", ",", "dim_name", ",", "bounds_name", ")", ":", "# TODO: don't assume needed dimension is in axis=0", "# TODO: refactor to get rid of repetitive code", "spacing", "=", "arr", ".", "diff", "(", "dim_name", ")", ".", "values", "lower"...
Get the bounds of an array given its center values. E.g. if lat-lon grid center lat/lon values are known, but not the bounds of each grid box. The algorithm assumes that the bounds are simply halfway between each pair of center values.
[ "Get", "the", "bounds", "of", "an", "array", "given", "its", "center", "values", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/model.py#L39-L58
spencerahill/aospy
aospy/model.py
_diff_bounds
def _diff_bounds(bounds, coord): """Get grid spacing by subtracting upper and lower bounds.""" try: return bounds[:, 1] - bounds[:, 0] except IndexError: diff = np.diff(bounds, axis=0) return xr.DataArray(diff, dims=coord.dims, coords=coord.coords)
python
def _diff_bounds(bounds, coord): """Get grid spacing by subtracting upper and lower bounds.""" try: return bounds[:, 1] - bounds[:, 0] except IndexError: diff = np.diff(bounds, axis=0) return xr.DataArray(diff, dims=coord.dims, coords=coord.coords)
[ "def", "_diff_bounds", "(", "bounds", ",", "coord", ")", ":", "try", ":", "return", "bounds", "[", ":", ",", "1", "]", "-", "bounds", "[", ":", ",", "0", "]", "except", "IndexError", ":", "diff", "=", "np", ".", "diff", "(", "bounds", ",", "axis"...
Get grid spacing by subtracting upper and lower bounds.
[ "Get", "grid", "spacing", "by", "subtracting", "upper", "and", "lower", "bounds", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/model.py#L61-L67
spencerahill/aospy
aospy/model.py
_grid_sfc_area
def _grid_sfc_area(lon, lat, lon_bounds=None, lat_bounds=None): """Calculate surface area of each grid cell in a lon-lat grid.""" # Compute the bounds if not given. if lon_bounds is None: lon_bounds = _bounds_from_array( lon, internal_names.LON_STR, internal_names.LON_BOUNDS_STR) if ...
python
def _grid_sfc_area(lon, lat, lon_bounds=None, lat_bounds=None): """Calculate surface area of each grid cell in a lon-lat grid.""" # Compute the bounds if not given. if lon_bounds is None: lon_bounds = _bounds_from_array( lon, internal_names.LON_STR, internal_names.LON_BOUNDS_STR) if ...
[ "def", "_grid_sfc_area", "(", "lon", ",", "lat", ",", "lon_bounds", "=", "None", ",", "lat_bounds", "=", "None", ")", ":", "# Compute the bounds if not given.", "if", "lon_bounds", "is", "None", ":", "lon_bounds", "=", "_bounds_from_array", "(", "lon", ",", "i...
Calculate surface area of each grid cell in a lon-lat grid.
[ "Calculate", "surface", "area", "of", "each", "grid", "cell", "in", "a", "lon", "-", "lat", "grid", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/model.py#L70-L97
spencerahill/aospy
aospy/model.py
Model._get_grid_files
def _get_grid_files(self): """Get the files holding grid data for an aospy object.""" grid_file_paths = self.grid_file_paths datasets = [] if isinstance(grid_file_paths, str): grid_file_paths = [grid_file_paths] for path in grid_file_paths: try: ...
python
def _get_grid_files(self): """Get the files holding grid data for an aospy object.""" grid_file_paths = self.grid_file_paths datasets = [] if isinstance(grid_file_paths, str): grid_file_paths = [grid_file_paths] for path in grid_file_paths: try: ...
[ "def", "_get_grid_files", "(", "self", ")", ":", "grid_file_paths", "=", "self", ".", "grid_file_paths", "datasets", "=", "[", "]", "if", "isinstance", "(", "grid_file_paths", ",", "str", ")", ":", "grid_file_paths", "=", "[", "grid_file_paths", "]", "for", ...
Get the files holding grid data for an aospy object.
[ "Get", "the", "files", "holding", "grid", "data", "for", "an", "aospy", "object", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/model.py#L221-L236
spencerahill/aospy
aospy/model.py
Model._set_mult_grid_attr
def _set_mult_grid_attr(self): """ Set multiple attrs from grid file given their names in the grid file. """ grid_objs = self._get_grid_files() if self.grid_attrs is None: self.grid_attrs = {} # Override GRID_ATTRS with entries in grid_attrs attrs = ...
python
def _set_mult_grid_attr(self): """ Set multiple attrs from grid file given their names in the grid file. """ grid_objs = self._get_grid_files() if self.grid_attrs is None: self.grid_attrs = {} # Override GRID_ATTRS with entries in grid_attrs attrs = ...
[ "def", "_set_mult_grid_attr", "(", "self", ")", ":", "grid_objs", "=", "self", ".", "_get_grid_files", "(", ")", "if", "self", ".", "grid_attrs", "is", "None", ":", "self", ".", "grid_attrs", "=", "{", "}", "# Override GRID_ATTRS with entries in grid_attrs", "at...
Set multiple attrs from grid file given their names in the grid file.
[ "Set", "multiple", "attrs", "from", "grid", "file", "given", "their", "names", "in", "the", "grid", "file", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/model.py#L238-L268
spencerahill/aospy
aospy/model.py
Model.set_grid_data
def set_grid_data(self): """Populate the attrs that hold grid data.""" if self._grid_data_is_set: return self._set_mult_grid_attr() if not np.any(getattr(self, 'sfc_area', None)): try: sfc_area = _grid_sfc_area(self.lon, self.lat, self.lon_bounds, ...
python
def set_grid_data(self): """Populate the attrs that hold grid data.""" if self._grid_data_is_set: return self._set_mult_grid_attr() if not np.any(getattr(self, 'sfc_area', None)): try: sfc_area = _grid_sfc_area(self.lon, self.lat, self.lon_bounds, ...
[ "def", "set_grid_data", "(", "self", ")", ":", "if", "self", ".", "_grid_data_is_set", ":", "return", "self", ".", "_set_mult_grid_attr", "(", ")", "if", "not", "np", ".", "any", "(", "getattr", "(", "self", ",", "'sfc_area'", ",", "None", ")", ")", ":...
Populate the attrs that hold grid data.
[ "Populate", "the", "attrs", "that", "hold", "grid", "data", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/model.py#L270-L287
spencerahill/aospy
aospy/utils/longitude.py
_other_to_lon
def _other_to_lon(func): """Wrapper for casting Longitude operator arguments to Longitude""" def func_other_to_lon(obj, other): return func(obj, _maybe_cast_to_lon(other)) return func_other_to_lon
python
def _other_to_lon(func): """Wrapper for casting Longitude operator arguments to Longitude""" def func_other_to_lon(obj, other): return func(obj, _maybe_cast_to_lon(other)) return func_other_to_lon
[ "def", "_other_to_lon", "(", "func", ")", ":", "def", "func_other_to_lon", "(", "obj", ",", "other", ")", ":", "return", "func", "(", "obj", ",", "_maybe_cast_to_lon", "(", "other", ")", ")", "return", "func_other_to_lon" ]
Wrapper for casting Longitude operator arguments to Longitude
[ "Wrapper", "for", "casting", "Longitude", "operator", "arguments", "to", "Longitude" ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/utils/longitude.py#L78-L82
spencerahill/aospy
aospy/automate.py
_get_attr_by_tag
def _get_attr_by_tag(obj, tag, attr_name): """Get attribute from an object via a string tag. Parameters ---------- obj : object from which to get the attribute attr_name : str Unmodified name of the attribute to be found. The actual attribute that is returned may be modified be 'ta...
python
def _get_attr_by_tag(obj, tag, attr_name): """Get attribute from an object via a string tag. Parameters ---------- obj : object from which to get the attribute attr_name : str Unmodified name of the attribute to be found. The actual attribute that is returned may be modified be 'ta...
[ "def", "_get_attr_by_tag", "(", "obj", ",", "tag", ",", "attr_name", ")", ":", "attr_name", "=", "_TAG_ATTR_MODIFIERS", "[", "tag", "]", "+", "attr_name", "return", "getattr", "(", "obj", ",", "attr_name", ")" ]
Get attribute from an object via a string tag. Parameters ---------- obj : object from which to get the attribute attr_name : str Unmodified name of the attribute to be found. The actual attribute that is returned may be modified be 'tag'. tag : str Tag specifying how to mo...
[ "Get", "attribute", "from", "an", "object", "via", "a", "string", "tag", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/automate.py#L34-L52
spencerahill/aospy
aospy/automate.py
_permuted_dicts_of_specs
def _permuted_dicts_of_specs(specs): """Create {name: value} dict, one each for every permutation. Each permutation becomes a dictionary, with the keys being the attr names and the values being the corresponding value for that permutation. These dicts can then be directly passed to the Calc constructo...
python
def _permuted_dicts_of_specs(specs): """Create {name: value} dict, one each for every permutation. Each permutation becomes a dictionary, with the keys being the attr names and the values being the corresponding value for that permutation. These dicts can then be directly passed to the Calc constructo...
[ "def", "_permuted_dicts_of_specs", "(", "specs", ")", ":", "permuter", "=", "itertools", ".", "product", "(", "*", "specs", ".", "values", "(", ")", ")", "return", "[", "dict", "(", "zip", "(", "specs", ".", "keys", "(", ")", ",", "perm", ")", ")", ...
Create {name: value} dict, one each for every permutation. Each permutation becomes a dictionary, with the keys being the attr names and the values being the corresponding value for that permutation. These dicts can then be directly passed to the Calc constructor.
[ "Create", "{", "name", ":", "value", "}", "dict", "one", "each", "for", "every", "permutation", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/automate.py#L55-L64
spencerahill/aospy
aospy/automate.py
_get_all_objs_of_type
def _get_all_objs_of_type(type_, parent): """Get all attributes of the given type from the given object. Parameters ---------- type_ : The desired type parent : The object from which to get the attributes with type matching 'type_' Returns ------- A list (possibly empty) of att...
python
def _get_all_objs_of_type(type_, parent): """Get all attributes of the given type from the given object. Parameters ---------- type_ : The desired type parent : The object from which to get the attributes with type matching 'type_' Returns ------- A list (possibly empty) of att...
[ "def", "_get_all_objs_of_type", "(", "type_", ",", "parent", ")", ":", "return", "set", "(", "[", "obj", "for", "obj", "in", "parent", ".", "__dict__", ".", "values", "(", ")", "if", "isinstance", "(", "obj", ",", "type_", ")", "]", ")" ]
Get all attributes of the given type from the given object. Parameters ---------- type_ : The desired type parent : The object from which to get the attributes with type matching 'type_' Returns ------- A list (possibly empty) of attributes from 'parent'
[ "Get", "all", "attributes", "of", "the", "given", "type", "from", "the", "given", "object", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/automate.py#L101-L115
spencerahill/aospy
aospy/automate.py
_prune_invalid_time_reductions
def _prune_invalid_time_reductions(spec): """Prune time reductions of spec with no time dimension.""" valid_reductions = [] if not spec['var'].def_time and spec['dtype_out_time'] is not None: for reduction in spec['dtype_out_time']: if reduction not in _TIME_DEFINED_REDUCTIONS: ...
python
def _prune_invalid_time_reductions(spec): """Prune time reductions of spec with no time dimension.""" valid_reductions = [] if not spec['var'].def_time and spec['dtype_out_time'] is not None: for reduction in spec['dtype_out_time']: if reduction not in _TIME_DEFINED_REDUCTIONS: ...
[ "def", "_prune_invalid_time_reductions", "(", "spec", ")", ":", "valid_reductions", "=", "[", "]", "if", "not", "spec", "[", "'var'", "]", ".", "def_time", "and", "spec", "[", "'dtype_out_time'", "]", "is", "not", "None", ":", "for", "reduction", "in", "sp...
Prune time reductions of spec with no time dimension.
[ "Prune", "time", "reductions", "of", "spec", "with", "no", "time", "dimension", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/automate.py#L247-L262
spencerahill/aospy
aospy/automate.py
_compute_or_skip_on_error
def _compute_or_skip_on_error(calc, compute_kwargs): """Execute the Calc, catching and logging exceptions, but don't re-raise. Prevents one failed calculation from stopping a larger requested set of calculations. """ try: return calc.compute(**compute_kwargs) except Exception: m...
python
def _compute_or_skip_on_error(calc, compute_kwargs): """Execute the Calc, catching and logging exceptions, but don't re-raise. Prevents one failed calculation from stopping a larger requested set of calculations. """ try: return calc.compute(**compute_kwargs) except Exception: m...
[ "def", "_compute_or_skip_on_error", "(", "calc", ",", "compute_kwargs", ")", ":", "try", ":", "return", "calc", ".", "compute", "(", "*", "*", "compute_kwargs", ")", "except", "Exception", ":", "msg", "=", "(", "\"Skipping aospy calculation `{0}` due to error with t...
Execute the Calc, catching and logging exceptions, but don't re-raise. Prevents one failed calculation from stopping a larger requested set of calculations.
[ "Execute", "the", "Calc", "catching", "and", "logging", "exceptions", "but", "don", "t", "re", "-", "raise", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/automate.py#L265-L277
spencerahill/aospy
aospy/automate.py
_submit_calcs_on_client
def _submit_calcs_on_client(calcs, client, func): """Submit calculations via dask.bag and a distributed client""" logging.info('Connected to client: {}'.format(client)) if LooseVersion(dask.__version__) < '0.18': dask_option_setter = dask.set_options else: dask_option_setter = dask.confi...
python
def _submit_calcs_on_client(calcs, client, func): """Submit calculations via dask.bag and a distributed client""" logging.info('Connected to client: {}'.format(client)) if LooseVersion(dask.__version__) < '0.18': dask_option_setter = dask.set_options else: dask_option_setter = dask.confi...
[ "def", "_submit_calcs_on_client", "(", "calcs", ",", "client", ",", "func", ")", ":", "logging", ".", "info", "(", "'Connected to client: {}'", ".", "format", "(", "client", ")", ")", "if", "LooseVersion", "(", "dask", ".", "__version__", ")", "<", "'0.18'",...
Submit calculations via dask.bag and a distributed client
[ "Submit", "calculations", "via", "dask", ".", "bag", "and", "a", "distributed", "client" ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/automate.py#L280-L288
spencerahill/aospy
aospy/automate.py
_exec_calcs
def _exec_calcs(calcs, parallelize=False, client=None, **compute_kwargs): """Execute the given calculations. Parameters ---------- calcs : Sequence of ``aospy.Calc`` objects parallelize : bool, default False Whether to submit the calculations in parallel or not client : distributed.Clie...
python
def _exec_calcs(calcs, parallelize=False, client=None, **compute_kwargs): """Execute the given calculations. Parameters ---------- calcs : Sequence of ``aospy.Calc`` objects parallelize : bool, default False Whether to submit the calculations in parallel or not client : distributed.Clie...
[ "def", "_exec_calcs", "(", "calcs", ",", "parallelize", "=", "False", ",", "client", "=", "None", ",", "*", "*", "compute_kwargs", ")", ":", "if", "parallelize", ":", "def", "func", "(", "calc", ")", ":", "\"\"\"Wrap _compute_or_skip_on_error to require only the...
Execute the given calculations. Parameters ---------- calcs : Sequence of ``aospy.Calc`` objects parallelize : bool, default False Whether to submit the calculations in parallel or not client : distributed.Client or None The distributed Client used if parallelize is set to True; if ...
[ "Execute", "the", "given", "calculations", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/automate.py#L302-L339
spencerahill/aospy
aospy/automate.py
submit_mult_calcs
def submit_mult_calcs(calc_suite_specs, exec_options=None): """Generate and execute all specified computations. Once the calculations are prepped and submitted for execution, any calculation that triggers any exception or error is skipped, and the rest of the calculations proceed unaffected. This prev...
python
def submit_mult_calcs(calc_suite_specs, exec_options=None): """Generate and execute all specified computations. Once the calculations are prepped and submitted for execution, any calculation that triggers any exception or error is skipped, and the rest of the calculations proceed unaffected. This prev...
[ "def", "submit_mult_calcs", "(", "calc_suite_specs", ",", "exec_options", "=", "None", ")", ":", "if", "exec_options", "is", "None", ":", "exec_options", "=", "dict", "(", ")", "if", "exec_options", ".", "pop", "(", "'prompt_verify'", ",", "False", ")", ":",...
Generate and execute all specified computations. Once the calculations are prepped and submitted for execution, any calculation that triggers any exception or error is skipped, and the rest of the calculations proceed unaffected. This prevents an error in a single calculation from crashing a large sui...
[ "Generate", "and", "execute", "all", "specified", "computations", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/automate.py#L355-L508
spencerahill/aospy
aospy/automate.py
CalcSuite._get_requested_spec
def _get_requested_spec(self, obj, spec_name): """Helper to translate user specifications to needed objects.""" requested = self._specs_in[spec_name] if isinstance(requested, str): return _get_attr_by_tag(obj, requested, spec_name) else: return requested
python
def _get_requested_spec(self, obj, spec_name): """Helper to translate user specifications to needed objects.""" requested = self._specs_in[spec_name] if isinstance(requested, str): return _get_attr_by_tag(obj, requested, spec_name) else: return requested
[ "def", "_get_requested_spec", "(", "self", ",", "obj", ",", "spec_name", ")", ":", "requested", "=", "self", ".", "_specs_in", "[", "spec_name", "]", "if", "isinstance", "(", "requested", ",", "str", ")", ":", "return", "_get_attr_by_tag", "(", "obj", ",",...
Helper to translate user specifications to needed objects.
[ "Helper", "to", "translate", "user", "specifications", "to", "needed", "objects", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/automate.py#L152-L158
spencerahill/aospy
aospy/automate.py
CalcSuite._permute_core_specs
def _permute_core_specs(self): """Generate all requested combinations of the core objects.""" obj_trees = [] projects = self._get_requested_spec(self._obj_lib, _PROJECTS_STR) for project in projects: models = self._get_requested_spec(project, _MODELS_STR) for mode...
python
def _permute_core_specs(self): """Generate all requested combinations of the core objects.""" obj_trees = [] projects = self._get_requested_spec(self._obj_lib, _PROJECTS_STR) for project in projects: models = self._get_requested_spec(project, _MODELS_STR) for mode...
[ "def", "_permute_core_specs", "(", "self", ")", ":", "obj_trees", "=", "[", "]", "projects", "=", "self", ".", "_get_requested_spec", "(", "self", ".", "_obj_lib", ",", "_PROJECTS_STR", ")", "for", "project", "in", "projects", ":", "models", "=", "self", "...
Generate all requested combinations of the core objects.
[ "Generate", "all", "requested", "combinations", "of", "the", "core", "objects", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/automate.py#L160-L174
spencerahill/aospy
aospy/automate.py
CalcSuite._get_regions
def _get_regions(self): """Get the requested regions.""" if self._specs_in[_REGIONS_STR] == 'all': return [_get_all_objs_of_type( Region, getattr(self._obj_lib, 'regions', self._obj_lib) )] else: return [set(self._specs_in[_REGIONS_STR])]
python
def _get_regions(self): """Get the requested regions.""" if self._specs_in[_REGIONS_STR] == 'all': return [_get_all_objs_of_type( Region, getattr(self._obj_lib, 'regions', self._obj_lib) )] else: return [set(self._specs_in[_REGIONS_STR])]
[ "def", "_get_regions", "(", "self", ")", ":", "if", "self", ".", "_specs_in", "[", "_REGIONS_STR", "]", "==", "'all'", ":", "return", "[", "_get_all_objs_of_type", "(", "Region", ",", "getattr", "(", "self", ".", "_obj_lib", ",", "'regions'", ",", "self", ...
Get the requested regions.
[ "Get", "the", "requested", "regions", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/automate.py#L176-L183
spencerahill/aospy
aospy/automate.py
CalcSuite._get_variables
def _get_variables(self): """Get the requested variables.""" if self._specs_in[_VARIABLES_STR] == 'all': return _get_all_objs_of_type( Var, getattr(self._obj_lib, 'variables', self._obj_lib) ) else: return set(self._specs_in[_VARIABLES_STR])
python
def _get_variables(self): """Get the requested variables.""" if self._specs_in[_VARIABLES_STR] == 'all': return _get_all_objs_of_type( Var, getattr(self._obj_lib, 'variables', self._obj_lib) ) else: return set(self._specs_in[_VARIABLES_STR])
[ "def", "_get_variables", "(", "self", ")", ":", "if", "self", ".", "_specs_in", "[", "_VARIABLES_STR", "]", "==", "'all'", ":", "return", "_get_all_objs_of_type", "(", "Var", ",", "getattr", "(", "self", ".", "_obj_lib", ",", "'variables'", ",", "self", "....
Get the requested variables.
[ "Get", "the", "requested", "variables", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/automate.py#L185-L192
spencerahill/aospy
aospy/automate.py
CalcSuite._get_aux_specs
def _get_aux_specs(self): """Get and pre-process all of the non-core specifications.""" # Drop the "core" specifications, which are handled separately. specs = self._specs_in.copy() [specs.pop(core) for core in self._CORE_SPEC_NAMES] specs[_REGIONS_STR] = self._get_regions() ...
python
def _get_aux_specs(self): """Get and pre-process all of the non-core specifications.""" # Drop the "core" specifications, which are handled separately. specs = self._specs_in.copy() [specs.pop(core) for core in self._CORE_SPEC_NAMES] specs[_REGIONS_STR] = self._get_regions() ...
[ "def", "_get_aux_specs", "(", "self", ")", ":", "# Drop the \"core\" specifications, which are handled separately.", "specs", "=", "self", ".", "_specs_in", ".", "copy", "(", ")", "[", "specs", ".", "pop", "(", "core", ")", "for", "core", "in", "self", ".", "_...
Get and pre-process all of the non-core specifications.
[ "Get", "and", "pre", "-", "process", "all", "of", "the", "non", "-", "core", "specifications", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/automate.py#L205-L216
spencerahill/aospy
aospy/automate.py
CalcSuite._permute_aux_specs
def _permute_aux_specs(self): """Generate all permutations of the non-core specifications.""" # Convert to attr names that Calc is expecting. calc_aux_mapping = self._NAMES_SUITE_TO_CALC.copy() # Special case: manually add 'library' to mapping calc_aux_mapping[_OBJ_LIB_STR] = Non...
python
def _permute_aux_specs(self): """Generate all permutations of the non-core specifications.""" # Convert to attr names that Calc is expecting. calc_aux_mapping = self._NAMES_SUITE_TO_CALC.copy() # Special case: manually add 'library' to mapping calc_aux_mapping[_OBJ_LIB_STR] = Non...
[ "def", "_permute_aux_specs", "(", "self", ")", ":", "# Convert to attr names that Calc is expecting.", "calc_aux_mapping", "=", "self", ".", "_NAMES_SUITE_TO_CALC", ".", "copy", "(", ")", "# Special case: manually add 'library' to mapping", "calc_aux_mapping", "[", "_OBJ_LIB_ST...
Generate all permutations of the non-core specifications.
[ "Generate", "all", "permutations", "of", "the", "non", "-", "core", "specifications", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/automate.py#L218-L229
spencerahill/aospy
aospy/automate.py
CalcSuite._combine_core_aux_specs
def _combine_core_aux_specs(self): """Combine permutations over core and auxilliary Calc specs.""" all_specs = [] for core_dict in self._permute_core_specs(): for aux_dict in self._permute_aux_specs(): all_specs.append(_merge_dicts(core_dict, aux_dict)) return...
python
def _combine_core_aux_specs(self): """Combine permutations over core and auxilliary Calc specs.""" all_specs = [] for core_dict in self._permute_core_specs(): for aux_dict in self._permute_aux_specs(): all_specs.append(_merge_dicts(core_dict, aux_dict)) return...
[ "def", "_combine_core_aux_specs", "(", "self", ")", ":", "all_specs", "=", "[", "]", "for", "core_dict", "in", "self", ".", "_permute_core_specs", "(", ")", ":", "for", "aux_dict", "in", "self", ".", "_permute_aux_specs", "(", ")", ":", "all_specs", ".", "...
Combine permutations over core and auxilliary Calc specs.
[ "Combine", "permutations", "over", "core", "and", "auxilliary", "Calc", "specs", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/automate.py#L231-L237
spencerahill/aospy
aospy/automate.py
CalcSuite.create_calcs
def create_calcs(self): """Generate a Calc object for each requested parameter combination.""" specs = self._combine_core_aux_specs() for spec in specs: spec['dtype_out_time'] = _prune_invalid_time_reductions(spec) return [Calc(**sp) for sp in specs]
python
def create_calcs(self): """Generate a Calc object for each requested parameter combination.""" specs = self._combine_core_aux_specs() for spec in specs: spec['dtype_out_time'] = _prune_invalid_time_reductions(spec) return [Calc(**sp) for sp in specs]
[ "def", "create_calcs", "(", "self", ")", ":", "specs", "=", "self", ".", "_combine_core_aux_specs", "(", ")", "for", "spec", "in", "specs", ":", "spec", "[", "'dtype_out_time'", "]", "=", "_prune_invalid_time_reductions", "(", "spec", ")", "return", "[", "Ca...
Generate a Calc object for each requested parameter combination.
[ "Generate", "a", "Calc", "object", "for", "each", "requested", "parameter", "combination", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/automate.py#L239-L244
spencerahill/aospy
aospy/utils/io.py
data_in_label
def data_in_label(intvl_in, dtype_in_time, dtype_in_vert=False): """Create string label specifying the input data of a calculation.""" intvl_lbl = intvl_in time_lbl = dtype_in_time lbl = '_'.join(['from', intvl_lbl, time_lbl]).replace('__', '_') vert_lbl = dtype_in_vert if dtype_in_vert else False ...
python
def data_in_label(intvl_in, dtype_in_time, dtype_in_vert=False): """Create string label specifying the input data of a calculation.""" intvl_lbl = intvl_in time_lbl = dtype_in_time lbl = '_'.join(['from', intvl_lbl, time_lbl]).replace('__', '_') vert_lbl = dtype_in_vert if dtype_in_vert else False ...
[ "def", "data_in_label", "(", "intvl_in", ",", "dtype_in_time", ",", "dtype_in_vert", "=", "False", ")", ":", "intvl_lbl", "=", "intvl_in", "time_lbl", "=", "dtype_in_time", "lbl", "=", "'_'", ".", "join", "(", "[", "'from'", ",", "intvl_lbl", ",", "time_lbl"...
Create string label specifying the input data of a calculation.
[ "Create", "string", "label", "specifying", "the", "input", "data", "of", "a", "calculation", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/utils/io.py#L8-L16
spencerahill/aospy
aospy/utils/io.py
time_label
def time_label(intvl, return_val=True): """Create time interval label for aospy data I/O.""" # Monthly labels are 2 digit integers: '01' for jan, '02' for feb, etc. if type(intvl) in [list, tuple, np.ndarray] and len(intvl) == 1: label = '{:02}'.format(intvl[0]) value = np.array(intvl) e...
python
def time_label(intvl, return_val=True): """Create time interval label for aospy data I/O.""" # Monthly labels are 2 digit integers: '01' for jan, '02' for feb, etc. if type(intvl) in [list, tuple, np.ndarray] and len(intvl) == 1: label = '{:02}'.format(intvl[0]) value = np.array(intvl) e...
[ "def", "time_label", "(", "intvl", ",", "return_val", "=", "True", ")", ":", "# Monthly labels are 2 digit integers: '01' for jan, '02' for feb, etc.", "if", "type", "(", "intvl", ")", "in", "[", "list", ",", "tuple", ",", "np", ".", "ndarray", "]", "and", "len"...
Create time interval label for aospy data I/O.
[ "Create", "time", "interval", "label", "for", "aospy", "data", "I", "/", "O", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/utils/io.py#L38-L72
spencerahill/aospy
aospy/utils/io.py
data_name_gfdl
def data_name_gfdl(name, domain, data_type, intvl_type, data_yr, intvl, data_in_start_yr, data_in_dur): """Determine the filename of GFDL model data output.""" # Determine starting year of netCDF file to be accessed. extra_yrs = (data_yr - data_in_start_yr) % data_in_dur data_in_yr = ...
python
def data_name_gfdl(name, domain, data_type, intvl_type, data_yr, intvl, data_in_start_yr, data_in_dur): """Determine the filename of GFDL model data output.""" # Determine starting year of netCDF file to be accessed. extra_yrs = (data_yr - data_in_start_yr) % data_in_dur data_in_yr = ...
[ "def", "data_name_gfdl", "(", "name", ",", "domain", ",", "data_type", ",", "intvl_type", ",", "data_yr", ",", "intvl", ",", "data_in_start_yr", ",", "data_in_dur", ")", ":", "# Determine starting year of netCDF file to be accessed.", "extra_yrs", "=", "(", "data_yr",...
Determine the filename of GFDL model data output.
[ "Determine", "the", "filename", "of", "GFDL", "model", "data", "output", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/utils/io.py#L75-L122
spencerahill/aospy
aospy/utils/io.py
dmget
def dmget(files_list): """Call GFDL command 'dmget' to access archived files.""" if isinstance(files_list, str): files_list = [files_list] archive_files = [] for f in files_list: if f.startswith('/archive'): archive_files.append(f) try: subprocess.call(['dmget'] ...
python
def dmget(files_list): """Call GFDL command 'dmget' to access archived files.""" if isinstance(files_list, str): files_list = [files_list] archive_files = [] for f in files_list: if f.startswith('/archive'): archive_files.append(f) try: subprocess.call(['dmget'] ...
[ "def", "dmget", "(", "files_list", ")", ":", "if", "isinstance", "(", "files_list", ",", "str", ")", ":", "files_list", "=", "[", "files_list", "]", "archive_files", "=", "[", "]", "for", "f", "in", "files_list", ":", "if", "f", ".", "startswith", "(",...
Call GFDL command 'dmget' to access archived files.
[ "Call", "GFDL", "command", "dmget", "to", "access", "archived", "files", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/utils/io.py#L125-L137
spencerahill/aospy
aospy/calc.py
_replace_pressure
def _replace_pressure(arguments, dtype_in_vert): """Replace p and dp Vars with appropriate Var objects specific to the dtype_in_vert.""" arguments_out = [] for arg in arguments: if isinstance(arg, Var): if arg.name == 'p': arguments_out.append(_P_VARS[dtype_in_vert]) ...
python
def _replace_pressure(arguments, dtype_in_vert): """Replace p and dp Vars with appropriate Var objects specific to the dtype_in_vert.""" arguments_out = [] for arg in arguments: if isinstance(arg, Var): if arg.name == 'p': arguments_out.append(_P_VARS[dtype_in_vert]) ...
[ "def", "_replace_pressure", "(", "arguments", ",", "dtype_in_vert", ")", ":", "arguments_out", "=", "[", "]", "for", "arg", "in", "arguments", ":", "if", "isinstance", "(", "arg", ",", "Var", ")", ":", "if", "arg", ".", "name", "==", "'p'", ":", "argum...
Replace p and dp Vars with appropriate Var objects specific to the dtype_in_vert.
[ "Replace", "p", "and", "dp", "Vars", "with", "appropriate", "Var", "objects", "specific", "to", "the", "dtype_in_vert", "." ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/calc.py#L28-L42
spencerahill/aospy
aospy/calc.py
_add_metadata_as_attrs
def _add_metadata_as_attrs(data, units, description, dtype_out_vert): """Add metadata attributes to Dataset or DataArray""" if isinstance(data, xr.DataArray): return _add_metadata_as_attrs_da(data, units, description, dtype_out_vert) else: for name, a...
python
def _add_metadata_as_attrs(data, units, description, dtype_out_vert): """Add metadata attributes to Dataset or DataArray""" if isinstance(data, xr.DataArray): return _add_metadata_as_attrs_da(data, units, description, dtype_out_vert) else: for name, a...
[ "def", "_add_metadata_as_attrs", "(", "data", ",", "units", ",", "description", ",", "dtype_out_vert", ")", ":", "if", "isinstance", "(", "data", ",", "xr", ".", "DataArray", ")", ":", "return", "_add_metadata_as_attrs_da", "(", "data", ",", "units", ",", "d...
Add metadata attributes to Dataset or DataArray
[ "Add", "metadata", "attributes", "to", "Dataset", "or", "DataArray" ]
train
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/calc.py#L594-L603