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_documentation_string
stringlengths
1
47.2k
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...
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...
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: ...
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]
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³...
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 ...
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...
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...
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...
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...
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...
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...
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...
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 ...
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...
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...
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...
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...
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...
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...
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] ...
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, ...
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...
Check if class is calculable by its kwargs
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)
Wrapper derivative for custom derived properties where x, y, z can be: P, T, v, u, h, s, g, a
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...
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: ...
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 ...
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 ...
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] ...
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 ...
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 ...
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 ...
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 ...
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...
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...
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...
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...
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...
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...
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 ...
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...
Cast DataArrays to np.float64 if they are of type np.float32. Parameters ---------- da : xr.DataArray Input DataArray Returns ------- DataArray
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...
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...
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...
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 ...
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...
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...
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)
Set an attribute of an object to a value or default value.
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 ---------...
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...
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...
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.
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...
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 ...
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
Apply specified time shift to DataArray
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...
Returns the file_set for the given interval in.
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...
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...
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 ...
Convert the given data to plotting units.
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))
Mask data array where values are outside physically valid range.
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...
Force data with units either degrees or radians to be radians.
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
Force data with units either hPa or Pa to be in Pa.
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
Convert pressure array from Pa to hPa (if needed).
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
Replace a coordinate with new one; new and old must have same shape.
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...
Compute data at full pressure levels from values at half levels.
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...
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.
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)
Compute pressure at full levels from surface pressure.
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)
Compute pressure level thickness from half level pressures.
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. ...
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 ...
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)
Compute pressure level thickness from surface pressure
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)
Integrate along the given dimension.
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...
Determine if an object has an attribute name matching a given list.
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
Mass weighted integral.
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...
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...
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...
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...
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 ...
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.
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...
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 ...
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...
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...
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 ...
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...
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 -------...
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 ...
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 = ...
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
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...
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 ...
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 ...
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 ------- ...
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...
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...
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...
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...
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 ...
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 ---------...
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...
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...
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 ...
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 ...
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 ...
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...
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...
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...
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...
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...
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...
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...
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...
Construct the mask that defines a region on a given data's grid.
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) ...
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...
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...
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...
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, ...
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 ...
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...
Rename coordinates to aospy's internal names.
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. """ ...
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.
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)
Get grid spacing by subtracting upper and lower bounds.
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 ...
Calculate surface area of each grid cell in a lon-lat grid.
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: ...
Get the files holding grid data for an aospy object.
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 = ...
Set multiple attrs from grid file given their names in the grid file.
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, ...
Populate the attrs that hold grid data.
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
Wrapper for casting Longitude operator arguments to Longitude
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...
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...
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...
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.
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...
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'
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: ...
Prune time reductions of spec with no time dimension.
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...
Execute the Calc, catching and logging exceptions, but don't re-raise. Prevents one failed calculation from stopping a larger requested set of calculations.
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...
Submit calculations via dask.bag and a distributed client
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...
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 ...
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...
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...
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
Helper to translate user specifications to needed objects.
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...
Generate all requested combinations of the core objects.
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])]
Get the requested regions.
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])
Get the requested variables.
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() ...
Get and pre-process all of the non-core specifications.
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...
Generate all permutations of the non-core specifications.
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...
Combine permutations over core and auxilliary Calc specs.
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]
Generate a Calc object for each requested parameter combination.
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 ...
Create string label specifying the input data of a calculation.
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...
Create time interval label for aospy data I/O.
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 = ...
Determine the filename of GFDL model data output.
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'] ...
Call GFDL command 'dmget' to access archived files.
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]) ...
Replace p and dp Vars with appropriate Var objects specific to the dtype_in_vert.
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...
Add metadata attributes to Dataset or DataArray
https://github.com/spencerahill/aospy/blob/2f6e775b9b9956c54af117fdcdce2c87196afb6c/aospy/calc.py#L594-L603