code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
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] = times.average_time_bounds(ds) else: logging.warning("dt array not found. Assuming equally spaced " "values in time, even though this may not be " "the case") ds = times.add_uniform_time_weights(ds) # Suppress enable_cftimeindex is a no-op warning; we'll keep setting it for # now to maintain backwards compatibility for older xarray versions. with warnings.catch_warnings(): warnings.filterwarnings('ignore') with xr.set_options(enable_cftimeindex=True): ds = xr.decode_cf(ds, decode_times=True, decode_coords=False, mask_and_scale=True) return ds
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 bounds coordinate, overwrite the time coordinate values with the averages of the time bounds at each timestep 3. Decode the times into np.datetime64 objects for time indexing Parameters ---------- ds : Dataset Pre-processed Dataset with time coordinate renamed to internal_names.TIME_STR Returns ------- Dataset The processed Dataset
5.953938
5.844949
1.018647
apply_preload_user_commands(file_set) func = _preprocess_and_rename_grid_attrs(preprocess_func, grid_attrs, **kwargs) return xr.open_mfdataset(file_set, preprocess=func, concat_dim=TIME_STR, decode_times=False, decode_coords=False, mask_and_scale=True, data_vars=data_vars, coords=coords)
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 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 (optional) Custom function to call before applying any aospy logic to the loaded dataset data_vars : str (default 'minimal') Mode for concatenating data variables in call to ``xr.open_mfdataset`` coords : str (default 'minimal') Mode for concatenating coordinate variables in call to ``xr.open_mfdataset``. grid_attrs : dict Overriding dictionary of grid attributes mapping aospy internal names to names of grid attributes used in a particular model. Returns ------- Dataset
4.306539
4.840895
0.889616
if value is None: setattr(obj, attr, default) else: setattr(obj, attr, value)
def _setattr_default(obj, attr, value, default)
Set an attribute of an object to a value or default value.
2.16193
2.137676
1.011346
file_set = self._generate_file_set(var=var, start_date=start_date, end_date=end_date, **DataAttrs) ds = _load_data_from_disk( file_set, self.preprocess_func, data_vars=self.data_vars, coords=self.coords, start_date=start_date, end_date=end_date, time_offset=time_offset, grid_attrs=grid_attrs, **DataAttrs ) if var.def_time: ds = _prep_time_data(ds) start_date = times.maybe_convert_to_index_date_type( ds.indexes[TIME_STR], start_date) end_date = times.maybe_convert_to_index_date_type( ds.indexes[TIME_STR], end_date) ds = set_grid_attrs_as_coords(ds) da = _sel_var(ds, var, self.upcast_float32) if var.def_time: da = self._maybe_apply_time_shift(da, time_offset, **DataAttrs) return times.sel_time(da, start_date, end_date).load() else: return da.load()
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 ---------- var : Var aospy Var object start_date : datetime.datetime start date for interval end_date : datetime.datetime end date for interval time_offset : dict Option to add a time offset to the time coordinate to correct for incorrect metadata. grid_attrs : dict (optional) Overriding dictionary of grid attributes mapping aospy internal names to names of grid attributes used in a particular model. **DataAttrs Attributes needed to identify a unique set of files to load from Returns ------- da : DataArray DataArray for the specified variable, date range, and interval in
3.193835
3.387762
0.942757
grid_attrs = None if model is None else model.grid_attrs try: return self.load_variable( var, start_date=start_date, end_date=end_date, time_offset=time_offset, grid_attrs=grid_attrs, **DataAttrs) except (KeyError, IOError) as e: if var.name not in GRID_ATTRS or model is None: raise e else: try: return getattr(model, var.name) except AttributeError: raise AttributeError( 'Grid attribute {} could not be located either ' 'through this DataLoader or in the provided Model ' 'object: {}.'.format(var, 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 optionally-provided Model object. Defaults to using the version found in the DataLoader first.
3.279009
2.920935
1.122589
if var.variables is None: return self._load_or_get_from_model( var, start_date, end_date, time_offset, model, **DataAttrs) else: data = [self.recursively_compute_variable( v, start_date, end_date, time_offset, model, **DataAttrs) for v in var.variables] return var.func(*data).rename(var.name)
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 variable must eventually be able to be expressed in terms of model-native quantities; otherwise the recursion will never stop. Parameters ---------- var : Var aospy Var object start_date : datetime.datetime start date for interval end_date : datetime.datetime end date for interval time_offset : dict Option to add a time offset to the time coordinate to correct for incorrect metadata. model : Model aospy Model object (optional) **DataAttrs Attributes needed to identify a unique set of files to load from Returns ------- da : DataArray DataArray for the specified variable, date range, and interval in
2.580579
3.033521
0.850688
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)
Apply specified time shift to DataArray
4.511232
4.27605
1.055
try: return self.file_map[intvl_in] except KeyError: raise KeyError('File set does not exist for the specified' ' intvl_in {0}'.format(intvl_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, intvl_out=None)
Returns the file_set for the given interval in.
4.07582
3.810981
1.069494
if time_offset is not None: time = times.apply_time_offset(da[TIME_STR], **time_offset) da[TIME_STR] = time else: if DataAttrs['dtype_in_time'] == 'inst': if DataAttrs['intvl_in'].endswith('hr'): offset = -1 * int(DataAttrs['intvl_in'][0]) else: offset = 0 time = times.apply_time_offset(da[TIME_STR], hours=offset) da[TIME_STR] = time return da
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 for the month of January, will have its last time value be in February.
3.988539
3.958483
1.007593
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 else: raise ValueError("dtype_vert value `{0}` not recognized. Only " "bool(dtype_vert) = False, 'vert_av', and " "'vert_int' supported.".format(dtype_vert)) if isinstance(data, dict): return {key: val*conv_factor for key, val in data.items()} return data*conv_factor
def to_plot_units(self, data, dtype_vert=False)
Convert the given data to plotting units.
3.814691
3.715133
1.026798
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)
Mask data array where values are outside physically valid range.
2.774032
2.506755
1.106623
# Infer the units from embedded metadata, if it's there. try: units = arr.units except AttributeError: pass else: if units.lower().startswith('degrees'): warn_msg = ("Conversion applied: degrees -> radians to array: " "{}".format(arr)) logging.debug(warn_msg) return np.deg2rad(arr) # Otherwise, assume degrees if the values are sufficiently large. threshold = 0.1*np.pi if is_delta else 4*np.pi if np.max(np.abs(arr)) > threshold: warn_msg = ("Conversion applied: degrees -> radians to array: " "{}".format(arr)) logging.debug(warn_msg) return np.deg2rad(arr) return arr
def to_radians(arr, is_delta=False)
Force data with units either degrees or radians to be radians.
3.487835
3.465497
1.006446
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)
Force data with units either hPa or Pa to be in Pa.
6.590588
4.879103
1.350779
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)
Convert pressure array from Pa to hPa (if needed).
6.673097
5.211177
1.280536
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)
Replace a coordinate with new one; new and old must have same shape.
2.240313
2.42081
0.92544
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_coord) phalf_bot = arr.isel(**{internal_names.PHALF_STR: slice(None, -1)}) phalf_bot = replace_coord(phalf_bot, internal_names.PHALF_STR, internal_names.PFULL_STR, pfull_coord) return 0.5*(phalf_bot + phalf_top)
def to_pfull_from_phalf(arr, pfull_coord)
Compute data at full pressure levels from values at half levels.
2.315139
2.300497
1.006365
phalf = np.zeros((arr.shape[0] + 1, arr.shape[1], arr.shape[2])) phalf[0] = val_toa phalf[-1] = val_sfc phalf[1:-1] = 0.5*(arr[:-1] + arr[1:]) return phalf
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.
1.910769
2.154619
0.886824
return to_pfull_from_phalf(phalf_from_ps(bk, pk, ps), pfull_coord)
def pfull_from_ps(bk, pk, ps, pfull_coord)
Compute pressure at full levels from surface pressure.
4.906771
5.428657
0.903865
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)
Compute pressure level thickness from half level pressures.
5.020474
4.900148
1.024556
# noqa: W605 right = arr[{internal_names.PFULL_STR: slice(2, None, None)}].values left = arr[{internal_names.PFULL_STR: slice(0, -2, 1)}].values deriv = xr.DataArray(np.zeros(arr.shape), dims=arr.dims, coords=arr.coords) deriv[{internal_names.PFULL_STR: slice(1, -1, 1)}] = (right - left) / 2. deriv[{internal_names.PFULL_STR: 0}] = ( arr[{internal_names.PFULL_STR: 1}].values - arr[{internal_names.PFULL_STR: 0}].values) deriv[{internal_names.PFULL_STR: -1}] = ( arr[{internal_names.PFULL_STR: -1}].values - arr[{internal_names.PFULL_STR: -2}].values) return deriv
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. Parameters ---------- arr : xarray.DataArray containing the 'pfull' dim Returns ------- deriv : xarray.DataArray with the derivative along 'pfull' computed via 2nd order centered differencing.
2.22223
2.201777
1.00929
return d_deta_from_phalf(phalf_from_ps(bk, pk, ps), pfull_coord)
def dp_from_ps(bk, pk, ps, pfull_coord)
Compute pressure level thickness from surface pressure
7.312531
7.742322
0.944488
if is_pressure: dim = vert_coord_name(ddim) return (arr*ddim).sum(dim=dim)
def integrate(arr, ddim, dim=False, is_pressure=False)
Integrate along the given dimension.
6.341306
5.942203
1.067164
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}` match the " "specified names of `{1}`".format(arr, names))
def get_dim_name(arr, names)
Determine if an object has an attribute name matching a given list.
8.619428
7.409866
1.163237
return integrate(arr, to_pascal(dp, is_dp=True), vert_coord_name(dp)) / GRAV_EARTH
def int_dp_g(arr, dp)
Mass weighted integral.
28.879616
24.92156
1.158821
p_str = get_dim_name(p, (internal_names.PLEVEL_STR, 'plev')) p_vals = to_pascal(p.values.copy()) # Layer edges are halfway between the given pressure levels. p_edges_interior = 0.5*(p_vals[:-1] + p_vals[1:]) p_edges = np.concatenate(([p_bot], p_edges_interior, [p_top])) p_edge_above = p_edges[1:] p_edge_below = p_edges[:-1] dp = p_edge_below - p_edge_above if not all(np.sign(dp)): raise ValueError("dp array not all > 0 : {}".format(dp)) # Pressure difference between ps and the upper edge of each pressure level. p_edge_above_xr = xr.DataArray(p_edge_above, dims=p.dims, coords=p.coords) dp_to_sfc = ps - p_edge_above_xr # Find the level adjacent to the masked, under-ground levels. change = xr.DataArray(np.zeros(dp_to_sfc.shape), dims=dp_to_sfc.dims, coords=dp_to_sfc.coords) change[{p_str: slice(1, None)}] = np.diff( np.sign(ps - to_pascal(p.copy())) ) dp_combined = xr.DataArray(np.where(change, dp_to_sfc, dp), dims=dp_to_sfc.dims, coords=dp_to_sfc.coords) # Mask levels that are under ground. above_ground = ps > to_pascal(p.copy()) above_ground[p_str] = p[p_str] dp_with_ps = dp_combined.where(above_ground) # Revert to original dim order. possible_dim_orders = [ (internal_names.TIME_STR, p_str, internal_names.LAT_STR, internal_names.LON_STR), (internal_names.TIME_STR, p_str, internal_names.LAT_STR), (internal_names.TIME_STR, p_str, internal_names.LON_STR), (internal_names.TIME_STR, p_str), (p_str, internal_names.LAT_STR, internal_names.LON_STR), (p_str, internal_names.LAT_STR), (p_str, internal_names.LON_STR), (p_str,), ] for dim_order in possible_dim_orders: try: return dp_with_ps.transpose(*dim_order) except ValueError: logging.debug("Failed transpose to dims: {}".format(dim_order)) else: logging.debug("No transpose was successful.") return dp_with_ps
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 pressure is not changed by ps, since they don't intersect the surface. If ps is in between a level's top and bottom pressures, then its dp becomes the pressure difference between its top and ps. If ps is less than a level's top and bottom pressures, then that level is underground and its values are masked. Note that postprocessing routines (e.g. at GFDL) typically mask out data wherever the surface pressure is less than the level's given value, not the level's upper edge. This masks out more levels than the
3.134053
2.961756
1.058174
p_vals = to_pascal(p.values.copy()) dp_vals = np.empty_like(p_vals) # Bottom level extends from p[0] to halfway betwen p[0] and p[1]. dp_vals[0] = p_bot - 0.5*(p_vals[0] + p_vals[1]) # Middle levels extend from halfway between [k-1], [k] and [k], [k+1]. dp_vals[1:-1] = 0.5*(p_vals[0:-2] - p_vals[2:]) # Top level extends from halfway between top two levels to 0 hPa. dp_vals[-1] = 0.5*(p_vals[-2] + p_vals[-1]) - p_top dp = p.copy() dp.values = dp_vals return dp
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 to 0 hPa. Unlike `dp_from_p`, this does not incorporate the surface pressure.
3.364545
3.231591
1.041142
diff = np.diff(arr) if not np.all(np.abs(np.sign(diff))): raise ValueError("Array is not monotonic: {}".format(arr)) # Since we know its monotonic, just test the first value. return bool(diff[0])
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.
5.059487
4.985662
1.014808
return (pd.to_datetime(time.values) + pd.DateOffset(years=years, months=months, days=days, hours=hours))
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 offset by 3 hours, such that the first value is for 1 Jan 03:00 and the last value is 1 Jan 00:00 of the subsequent year. This causes problems in xarray, e.g. when trying to group by month. It is resolved by manually subtracting off those three hours, such that the dates span from 1 Jan 00:00 to 31 Dec 21:00 as desired. Parameters ---------- time : xarray.DataArray representing a timeseries years, months, days, hours : int, optional The number of years, months, days, and hours, respectively, to offset the time array by. Positive values move the times later. Returns ------- pandas.DatetimeIndex Examples -------- Case of a length-1 input time array: >>> times = xr.DataArray(datetime.datetime(1899, 12, 31, 21)) >>> apply_time_offset(times) Timestamp('1900-01-01 00:00:00') Case of input time array with length greater than one: >>> times = xr.DataArray([datetime.datetime(1899, 12, 31, 21), ... datetime.datetime(1899, 1, 31, 21)]) >>> apply_time_offset(times) # doctest: +NORMALIZE_WHITESPACE DatetimeIndex(['1900-01-01', '1899-02-01'], dtype='datetime64[ns]', freq=None)
2.996847
3.991154
0.750872
bounds = ds[TIME_BOUNDS_STR] new_times = bounds.mean(dim=BOUNDS_STR, keep_attrs=True) new_times = new_times.drop(TIME_STR).rename(TIME_STR) new_times[TIME_STR] = new_times return new_times
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 error) if the timesteps span e.g. one full month each. Note that the Dataset's times must not have already undergone "CF decoding", wherein they are converted from floats using the 'units' attribute into datetime objects. Parameters ---------- ds : xarray.Dataset A Dataset containing a time bounds array with name matching internal_names.TIME_BOUNDS_STR. This time bounds array must have two dimensions, one of which's coordinates is the Dataset's time array, and the other is length-2. Returns ------- xarray.DataArray The mean of the start and end times of each timestep in the original Dataset. Raises ------ ValueError If the time bounds array doesn't match the shape specified above.
3.834415
3.877947
0.988774
time = monthly_means[TIME_STR] start = time.indexes[TIME_STR][0].replace(day=1, hour=0) end = time.indexes[TIME_STR][-1] new_indices = pd.DatetimeIndex(start=start, end=end, freq='MS') arr_new = monthly_means.reindex(time=new_indices, method='backfill') return arr_new.reindex_like(sub_monthly_timeseries, method='pad')
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 time resolution Returns ------- xarray.DataArray with eath monthly mean value from `monthly_means` repeated at each time within that month from `sub_monthly_timeseries` See Also -------- monthly_mean_ts : Create timeseries of monthly mean values
3.563926
4.08022
0.873464
assert_matching_time_coord(arr, dt) yr_str = TIME_STR + '.year' # Retain original data's mask. dt = dt.where(np.isfinite(arr)) return ((arr*dt).groupby(yr_str).sum(TIME_STR) / dt.groupby(yr_str).sum(TIME_STR))
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 ---------- arr : xarray.DataArray The array to be averaged dt : xarray.DataArray Array of the duration of each timestep Returns ------- xarray.DataArray Has the same shape and mask as the original ``arr``, except for the time dimension, which is truncated to one value for each year that ``arr`` spanned
6.867041
6.834945
1.004696
_VALID_TYPES = (str, datetime.datetime, cftime.datetime, np.datetime64) if isinstance(obj, _VALID_TYPES): return obj raise TypeError("datetime-like object required. " "Type given: {}".format(type(obj)))
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
4.297322
4.368897
0.983617
if not isinstance(months, (int, str)): raise TypeError("`months` must be of type int or str: " "type(months) == {}".format(type(months))) if isinstance(months, int): return [months] if months.lower() == 'ann': return np.arange(1, 13) first_letter = 'jfmamjjasond' * 2 # Python indexing starts at 0; month indices start at 1 for January. count = first_letter.count(months) if (count == 0) or (count > 2): message = ("The user must provide a unique pattern of consecutive " "first letters of months within '{}'. The provided " "string '{}' does not comply." " For individual months use integers." "".format(first_letter, months)) raise ValueError(message) st_ind = first_letter.find(months.lower()) return np.arange(st_ind, st_ind + len(months)) % 12 + 1
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 all months. Otherwise, use the specified months. Returns ------- np.ndarray of integers corresponding to desired month indices Raises ------ TypeError : If `months` is not an int or str See also -------- _month_conditional
4.986366
4.432405
1.12498
if isinstance(months, (int, str)): months_array = month_indices(months) else: months_array = months cond = False for month in months_array: cond |= (time['{}.month'.format(TIME_STR)] == month) return cond
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 to `month_indices` Returns ------- Array of bools specifying which months to keep See Also -------- month_indices
4.602437
4.761626
0.966568
inds = _month_conditional(time, months) return time.sel(time=inds)
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 include Returns ------- xarray.DataArray of the desired times
11.897555
17.777658
0.669242
# noqa: E501 if TIME_WEIGHTS_STR not in ds: time_weights = ds[TIME_BOUNDS_STR].diff(BOUNDS_STR) time_weights = time_weights.rename(TIME_WEIGHTS_STR).squeeze() if BOUNDS_STR in time_weights.coords: time_weights = time_weights.drop(BOUNDS_STR) ds[TIME_WEIGHTS_STR] = time_weights raw_start_date = ds[TIME_BOUNDS_STR].isel(**{TIME_STR: 0, BOUNDS_STR: 0}) ds[RAW_START_DATE_STR] = raw_start_date.reset_coords(drop=True) raw_end_date = ds[TIME_BOUNDS_STR].isel(**{TIME_STR: -1, BOUNDS_STR: 1}) ds[RAW_END_DATE_STR] = raw_end_date.reset_coords(drop=True) for coord in [TIME_BOUNDS_STR, RAW_START_DATE_STR, RAW_END_DATE_STR]: ds[coord].attrs['units'] = ds[TIME_STR].attrs['units'] if 'calendar' in ds[TIME_STR].attrs: ds[coord].attrs['calendar'] = ds[TIME_STR].attrs['calendar'] unit_interval = ds[TIME_STR].attrs['units'].split('since')[0].strip() ds[TIME_WEIGHTS_STR].attrs['units'] = unit_interval return ds
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 tracks the amount of time per time average interval. CF conventions require that a quantity stored as time averages over time intervals must have time and time_bounds coordinates [1]_. aospy further requires AVERAGE_DT for time average data, for accurate time-weighted averages, which can be inferred from the CF-required time_bounds coordinate if needed. This step should be done prior to decoding CF metadata with xarray to ensure proper computed timedeltas for different calendar types. .. [1] http://cfconventions.org/cf-conventions/v1.6.0/cf-conventions.html#_data_representative_of_cells Parameters ---------- ds : Dataset or DataArray Input data Returns ------- Dataset or DataArray Time average metadata attributes added if needed.
2.096537
2.132241
0.983255
time = ds[TIME_STR] unit_interval = time.attrs['units'].split('since')[0].strip() time_weights = xr.ones_like(time) time_weights.attrs['units'] = unit_interval del time_weights.attrs['calendar'] ds[TIME_WEIGHTS_STR] = time_weights return ds
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 coordinate. Parameters ---------- ds : Dataset Input data Returns ------- Dataset
3.372208
4.330251
0.778756
if isinstance(start_date, str) and isinstance(end_date, str): logging.warning( 'When using strings to specify start and end dates, the check ' 'to determine if data exists for the full extent of the desired ' 'interval is not implemented. Therefore it is possible that ' 'you are doing a calculation for a lesser interval than you ' 'specified. If you would like this check to occur, use explicit ' 'datetime-like objects for bounds instead.') return if RAW_START_DATE_STR in da.coords: with warnings.catch_warnings(record=True): da_start = da[RAW_START_DATE_STR].values da_end = da[RAW_END_DATE_STR].values else: times = da.time.isel(**{TIME_STR: [0, -1]}) da_start, da_end = times.values message = ('Data does not exist for requested time range: {0} to {1};' ' found data from time range: {2} to {3}.') # Add tolerance of one second, due to precision of cftime.datetimes tol = datetime.timedelta(seconds=1) if isinstance(da_start, np.datetime64): tol = np.timedelta64(tol, 'ns') range_exists = ((da_start - tol) <= start_date and (da_end + tol) >= end_date) assert (range_exists), message.format(start_date, end_date, da_start, da_end)
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 or str end date Raises ------ AssertionError If the time range is not within the time range of the DataArray
4.294396
4.349617
0.987304
_assert_has_data_for_time(da, start_date, end_date) da[SUBSET_START_DATE_STR] = xr.DataArray(start_date) da[SUBSET_END_DATE_STR] = xr.DataArray(end_date) return da.sel(**{TIME_STR: slice(start_date, end_date)})
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 start_date : np.datetime64 start of date interval end_date : np.datetime64 end of date interval Returns ---------- da : DataArray or Dataset subsetted data Raises ------ AssertionError if data for requested range do not exist for part or all of requested range
2.893668
3.734343
0.77488
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: {}') if not (arr1[TIME_STR].identical(arr2[TIME_STR])): raise ValueError(message.format(arr1[TIME_STR], arr2[TIME_STR]))
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 If the time coordinates are not identical between the two Datasets
5.891304
7.115609
0.827941
time_indexed_coords = {TIME_WEIGHTS_STR, TIME_BOUNDS_STR} time_indexed_vars = set(ds.data_vars).union(time_indexed_coords) time_indexed_vars = time_indexed_vars.intersection(ds.variables) variables_to_replace = {} for name in time_indexed_vars: if TIME_STR not in ds[name].indexes: da = ds[name] if TIME_STR not in da.dims: da = ds[name].expand_dims(TIME_STR) da = da.assign_coords(**{TIME_STR: ds[TIME_STR]}) variables_to_replace[name] = da return ds.assign(**variables_to_replace)
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 don't get indexed by time, even though they should. Therefore, we need this helper function to (possibly) correct this. Note that this must be applied before CF-conventions are decoded; otherwise it casts ``np.datetime64[ns]`` as ``int`` values. Parameters ---------- ds : Dataset Dataset with a time coordinate Returns ------- Dataset
3.039738
3.347014
0.908194
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.match(pattern, date) if result: return int(result.groupdict()['year']) else: raise ValueError('Invalid date string provided: {}'.format(date)) elif isinstance(date, np.datetime64): return date.item().year else: return date.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 >>> infer_year('2000-01-31') 2000 >>> infer_year(datetime.datetime(2000, 1, 1)) 2000 >>> infer_year(np.datetime64('2000-01-01')) 2000 >>> infer_year(DatetimeNoLeap(2000, 1, 1)) 2000 >>>
3.351907
3.598479
0.931479
if isinstance(date, str): return date if isinstance(index, pd.DatetimeIndex): if isinstance(date, np.datetime64): return date else: return np.datetime64(str(date)) else: date_type = index.date_type if isinstance(date, date_type): return date else: if isinstance(date, np.datetime64): # Convert to datetime.date or datetime.datetime object date = date.item() if isinstance(date, datetime.date): # Convert to a datetime.datetime object date = datetime.datetime.combine( date, datetime.datetime.min.time()) return date_type(date.year, date.month, date.day, date.hour, date.minute, date.second, date.microsecond)
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 data; therefore if a string is passed as a date, we return it unchanged. If a datetime-like object is provided, it will be converted to the underlying date type of the index. For a DatetimeIndex that is np.datetime64; for a CFTimeIndex that is an object of type cftime.datetime specific to the calendar used. Parameters ---------- index : pd.Index Input time index date : datetime-like object or str Input datetime Returns ------- date of the type appropriate for the time index of the Dataset
2.113353
2.178671
0.970019
mask = False for west, east, south, north in self.mask_bounds: if west < east: mask_lon = (data[lon_str] > west) & (data[lon_str] < east) else: mask_lon = (data[lon_str] < west) | (data[lon_str] > east) mask_lat = (data[lat_str] > south) & (data[lat_str] < north) mask |= mask_lon & mask_lat return 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.
1.953629
1.895362
1.030742
# TODO: is this still necessary? if not lon_cyclic: if self.west_bound > self.east_bound: raise ValueError("Longitudes of data to be masked are " "specified as non-cyclic, but Region's " "definition requires wraparound longitudes.") masked = data.where(self._make_mask(data, lon_str=lon_str, lat_str=lat_str)) return masked
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) Whether or not the longitudes of ``data`` span the whole globe, meaning that they should be wrapped around as necessary to cover the Region's full width. lon_str, lat_str : str, optional The names of the longitude and latitude dimensions, respectively, in the data to be masked. Defaults are ``aospy.internal_names.LON_STR`` and ``aospy.internal_names.LON_STR``, respectively. Returns ------- xarray.DataArray The original array with points outside of the region masked.
5.6724
4.967589
1.141882
data_masked = self.mask_var(data, lon_cyclic=lon_cyclic, lon_str=lon_str, lat_str=lat_str) sfc_area = data[sfc_area_str] sfc_area_masked = self.mask_var(sfc_area, lon_cyclic=lon_cyclic, lon_str=lon_str, lat_str=lat_str) land_mask = _get_land_mask(data, self.do_land_mask, land_mask_str=land_mask_str) weights = sfc_area_masked * land_mask # Mask weights where data values are initially invalid in addition # to applying the region mask. weights = weights.where(np.isfinite(data)) weights_reg_sum = weights.sum(lon_str).sum(lat_str) data_reg_sum = (data_masked * sfc_area_masked * land_mask).sum(lat_str).sum(lon_str) return data_reg_sum / weights_reg_sum
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 timeseries of lon_cyclic : { None, True, False }, optional (default True) Whether or not the longitudes of ``data`` span the whole globe, meaning that they should be wrapped around as necessary to cover the Region's full width. lat_str, lon_str, land_mask_str, sfc_area_str : str, optional The name of the latitude, longitude, land mask, and surface area coordinates, respectively, in ``data``. Defaults are the corresponding values in ``aospy.internal_names``. Returns ------- xarray.DataArray The timeseries of values averaged within the region and within each year, one value per year.
2.615649
2.755874
0.949118
ts = self.ts(data, lon_str=lon_str, lat_str=lat_str, land_mask_str=land_mask_str, sfc_area_str=sfc_area_str) if YEAR_STR not in ts.coords: return ts else: return ts.mean(YEAR_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)
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 coordinates, respectively, in ``data``. Defaults are the corresponding values in ``aospy.internal_names``. Returns ------- xarray.DataArray The region-averaged and time-averaged data.
2.279397
2.652893
0.859212
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 name. try: ds = ds.rename({list(ds_coord_name)[0]: name_int}) logging.debug("Rename coord from `{0}` to `{1}` for " "Dataset `{2}`".format(ds_coord_name, name_int, ds)) # xarray throws a ValueError if the name already exists except ValueError: ds = ds return ds
def _rename_coords(ds, attrs)
Rename coordinates to aospy's internal names.
4.927115
4.10816
1.199348
# 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 = xr.DataArray(np.empty_like(arr), dims=arr.dims, coords=arr.coords) lower.values[:-1] = arr.values[:-1] - 0.5*spacing lower.values[-1] = arr.values[-1] - 0.5*spacing[-1] upper = xr.DataArray(np.empty_like(arr), dims=arr.dims, coords=arr.coords) upper.values[:-1] = arr.values[:-1] + 0.5*spacing upper.values[-1] = arr.values[-1] + 0.5*spacing[-1] bounds = xr.concat([lower, upper], dim='bounds') return bounds.T
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.
2.348319
2.335319
1.005566
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)
Get grid spacing by subtracting upper and lower bounds.
3.185126
2.863196
1.112437
# 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 lat_bounds is None: lat_bounds = _bounds_from_array( lat, internal_names.LAT_STR, internal_names.LAT_BOUNDS_STR) # Compute the surface area. dlon = _diff_bounds(utils.vertcoord.to_radians(lon_bounds, is_delta=True), lon) sinlat_bounds = np.sin(utils.vertcoord.to_radians(lat_bounds, is_delta=True)) dsinlat = np.abs(_diff_bounds(sinlat_bounds, lat)) sfc_area = dlon*dsinlat*(RADIUS_EARTH**2) # Rename the coordinates such that they match the actual lat / lon. try: sfc_area = sfc_area.rename( {internal_names.LAT_BOUNDS_STR: internal_names.LAT_STR, internal_names.LON_BOUNDS_STR: internal_names.LON_STR}) except ValueError: pass # Clean up: correct names and dimension order. sfc_area = sfc_area.rename(internal_names.SFC_AREA_STR) sfc_area[internal_names.LAT_STR] = lat sfc_area[internal_names.LON_STR] = lon return sfc_area.transpose()
def _grid_sfc_area(lon, lat, lon_bounds=None, lat_bounds=None)
Calculate surface area of each grid cell in a lon-lat grid.
2.722877
2.730713
0.99713
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: ds = xr.open_dataset(path, decode_times=False) except (TypeError, AttributeError): ds = xr.open_mfdataset(path, decode_times=False).load() except (RuntimeError, OSError) as e: msg = str(e) + ': {}'.format(path) raise RuntimeError(msg) datasets.append(ds) return tuple(datasets)
def _get_grid_files(self)
Get the files holding grid data for an aospy object.
2.343647
2.224237
1.053686
grid_objs = self._get_grid_files() if self.grid_attrs is None: self.grid_attrs = {} # Override GRID_ATTRS with entries in grid_attrs attrs = internal_names.GRID_ATTRS.copy() for k, v in self.grid_attrs.items(): if k not in attrs: raise ValueError( 'Unrecognized internal name, {!r}, specified for a ' 'custom grid attribute name. See the full list of ' 'valid internal names below:\n\n{}'.format( k, list(internal_names.GRID_ATTRS.keys()))) attrs[k] = (v, ) for name_int, names_ext in attrs.items(): for name in names_ext: grid_attr = _get_grid_attr(grid_objs, name) if grid_attr is not None: TIME_STR = internal_names.TIME_STR renamed_attr = _rename_coords(grid_attr, attrs) if ((TIME_STR not in renamed_attr.dims) and (TIME_STR in renamed_attr.coords)): renamed_attr = renamed_attr.drop(TIME_STR) setattr(self, name_int, renamed_attr) break
def _set_mult_grid_attr(self)
Set multiple attrs from grid file given their names in the grid file.
3.704448
3.6037
1.027957
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, self.lat_bounds) except AttributeError: sfc_area = _grid_sfc_area(self.lon, self.lat) self.sfc_area = sfc_area try: self.levs_thick = utils.vertcoord.level_thickness(self.level) except AttributeError: self.level = None self.levs_thick = None self._grid_data_is_set = True
def set_grid_data(self)
Populate the attrs that hold grid data.
3.399811
3.185146
1.067396
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)
Wrapper for casting Longitude operator arguments to Longitude
3.544845
3.542003
1.000802
attr_name = _TAG_ATTR_MODIFIERS[tag] + attr_name return getattr(obj, attr_name)
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 'tag'. tag : str Tag specifying how to modify 'attr_name' by pre-pending it with 'tag'. Must be a key of the _TAG_ATTR_MODIFIERS dict. Returns ------- the specified attribute of obj
4.561489
4.086056
1.116355
permuter = itertools.product(*specs.values()) return [dict(zip(specs.keys(), perm)) for perm in permuter]
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 constructor.
3.362581
4.17366
0.805667
return set([obj for obj in parent.__dict__.values() if isinstance(obj, 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 attributes from 'parent'
4.335925
7.08416
0.612059
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: valid_reductions.append(reduction) else: msg = ("Var {0} has no time dimension " "for the given time reduction " "{1} so this calculation will " "be skipped".format(spec['var'].name, reduction)) logging.info(msg) else: valid_reductions = spec['dtype_out_time'] return valid_reductions
def _prune_invalid_time_reductions(spec)
Prune time reductions of spec with no time dimension.
4.404534
4.110774
1.071461
try: return calc.compute(**compute_kwargs) except Exception: msg = ("Skipping aospy calculation `{0}` due to error with the " "following traceback: \n{1}") logging.warning(msg.format(calc, traceback.format_exc())) return None
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.
4.604259
4.809327
0.95736
logging.info('Connected to client: {}'.format(client)) if LooseVersion(dask.__version__) < '0.18': dask_option_setter = dask.set_options else: dask_option_setter = dask.config.set with dask_option_setter(get=client.get): return db.from_sequence(calcs).map(func).compute()
def _submit_calcs_on_client(calcs, client, func)
Submit calculations via dask.bag and a distributed client
3.966373
3.706249
1.070185
if parallelize: def func(calc): if 'write_to_tar' in compute_kwargs: compute_kwargs['write_to_tar'] = False return _compute_or_skip_on_error(calc, compute_kwargs) if client is None: n_workers = _n_workers_for_local_cluster(calcs) with distributed.LocalCluster(n_workers=n_workers) as cluster: with distributed.Client(cluster) as client: result = _submit_calcs_on_client(calcs, client, func) else: result = _submit_calcs_on_client(calcs, client, func) if compute_kwargs['write_to_tar']: _serial_write_to_tar(calcs) return result else: return [_compute_or_skip_on_error(calc, compute_kwargs) for calc in 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.Client or None The distributed Client used if parallelize is set to True; if None a distributed LocalCluster is used. compute_kwargs : dict of keyword arguments passed to ``Calc.compute`` Returns ------- A list of the values returned by each Calc object that was executed.
2.812955
2.891626
0.972794
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)
Helper to translate user specifications to needed objects.
5.00341
4.811213
1.039948
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 model in models: runs = self._get_requested_spec(model, _RUNS_STR) for run in runs: obj_trees.append({ self._NAMES_SUITE_TO_CALC[_PROJECTS_STR]: project, self._NAMES_SUITE_TO_CALC[_MODELS_STR]: model, self._NAMES_SUITE_TO_CALC[_RUNS_STR]: run, }) return obj_trees
def _permute_core_specs(self)
Generate all requested combinations of the core objects.
3.340185
3.056169
1.092932
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)
Get the requested regions.
7.586474
6.757013
1.122756
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)
Get the requested variables.
7.865887
7.11902
1.104911
# 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() specs[_VARIABLES_STR] = self._get_variables() specs['date_ranges'] = self._get_date_ranges() specs['output_time_regional_reductions'] = self._get_time_reg_reducts() return specs
def _get_aux_specs(self)
Get and pre-process all of the non-core specifications.
5.594725
4.718198
1.185776
# 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] = None [calc_aux_mapping.pop(core) for core in self._CORE_SPEC_NAMES] specs = self._get_aux_specs() for suite_name, calc_name in calc_aux_mapping.items(): specs[calc_name] = specs.pop(suite_name) return _permuted_dicts_of_specs(specs)
def _permute_aux_specs(self)
Generate all permutations of the non-core specifications.
7.810459
7.600087
1.02768
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 all_specs
def _combine_core_aux_specs(self)
Combine permutations over core and auxilliary Calc specs.
3.129258
2.606535
1.200543
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)
Generate a Calc object for each requested parameter combination.
19.606003
14.506931
1.351492
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 if vert_lbl: lbl = '_'.join([lbl, vert_lbl]).replace('__', '_') return lbl
def data_in_label(intvl_in, dtype_in_time, dtype_in_vert=False)
Create string label specifying the input data of a calculation.
2.932581
2.77082
1.05838
# 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) elif type(intvl) == int and intvl in range(1, 13): label = '{:02}'.format(intvl) value = np.array([intvl]) # Seasonal and annual time labels are short strings. else: labels = {'jfm': (1, 2, 3), 'fma': (2, 3, 4), 'mam': (3, 4, 5), 'amj': (4, 5, 6), 'mjj': (5, 6, 7), 'jja': (6, 7, 8), 'jas': (7, 8, 9), 'aso': (8, 9, 10), 'son': (9, 10, 11), 'ond': (10, 11, 12), 'ndj': (11, 12, 1), 'djf': (1, 2, 12), 'jjas': (6, 7, 8, 9), 'djfm': (12, 1, 2, 3), 'ann': range(1, 13)} for lbl, vals in labels.items(): if intvl == lbl or set(intvl) == set(vals): label = lbl value = np.array(vals) break if return_val: return label, value else: return label
def time_label(intvl, return_val=True)
Create time interval label for aospy data I/O.
2.273172
2.253132
1.008894
# Determine starting year of netCDF file to be accessed. extra_yrs = (data_yr - data_in_start_yr) % data_in_dur data_in_yr = data_yr - extra_yrs # Determine file name. Two cases: time series (ts) or time-averaged (av). if data_type in ('ts', 'inst'): if intvl_type == 'annual': if data_in_dur == 1: filename = '.'.join([domain, '{:04d}'.format(data_in_yr), name, 'nc']) else: filename = '.'.join([domain, '{:04d}-{:04d}'.format( data_in_yr, data_in_yr + data_in_dur - 1 ), name, 'nc']) elif intvl_type == 'monthly': filename = (domain + '.{:04d}'.format(data_in_yr) + '01-' + '{:04d}'.format(int(data_in_yr+data_in_dur-1)) + '12.' + name + '.nc') elif intvl_type == 'daily': filename = (domain + '.{:04d}'.format(data_in_yr) + '0101-' + '{:04d}'.format(int(data_in_yr+data_in_dur-1)) + '1231.' + name + '.nc') elif 'hr' in intvl_type: filename = '.'.join( [domain, '{:04d}010100-{:04d}123123'.format( data_in_yr, data_in_yr + data_in_dur - 1), name, 'nc'] ) elif data_type == 'av': if intvl_type in ['annual', 'ann']: label = 'ann' elif intvl_type in ['seasonal', 'seas']: label = intvl.upper() elif intvl_type in ['monthly', 'mon']: label, val = time_label(intvl) if data_in_dur == 1: filename = (domain + '.{:04d}'.format(data_in_yr) + '.' + label + '.nc') else: filename = (domain + '.{:04d}'.format(data_in_yr) + '-' + '{:04d}'.format(int(data_in_yr+data_in_dur-1)) + '.' + label + '.nc') elif data_type == 'av_ts': filename = (domain + '.{:04d}'.format(data_in_yr) + '-' + '{:04d}'.format(int(data_in_yr+data_in_dur-1)) + '.01-12.nc') return filename
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.
1.966699
1.981943
0.992308
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'] + archive_files) except OSError: logging.debug('dmget command not found in this machine')
def dmget(files_list)
Call GFDL command 'dmget' to access archived files.
3.068018
2.763976
1.110002
arguments_out = [] for arg in arguments: if isinstance(arg, Var): if arg.name == 'p': arguments_out.append(_P_VARS[dtype_in_vert]) elif arg.name == 'dp': arguments_out.append(_DP_VARS[dtype_in_vert]) else: arguments_out.append(arg) else: arguments_out.append(arg) return arguments_out
def _replace_pressure(arguments, dtype_in_vert)
Replace p and dp Vars with appropriate Var objects specific to the dtype_in_vert.
2.016831
1.771103
1.138743
if isinstance(data, xr.DataArray): return _add_metadata_as_attrs_da(data, units, description, dtype_out_vert) else: for name, arr in data.data_vars.items(): _add_metadata_as_attrs_da(arr, units, description, dtype_out_vert) return data
def _add_metadata_as_attrs(data, units, description, dtype_out_vert)
Add metadata attributes to Dataset or DataArray
2.150462
2.085789
1.031007
if dtype_out_vert == 'vert_int': if units != '': units = '(vertical integral of {0}): {0} kg m^-2)'.format(units) else: units = '(vertical integral of quantity with unspecified units)' data.attrs['units'] = units data.attrs['description'] = description return data
def _add_metadata_as_attrs_da(data, units, description, dtype_out_vert)
Add metadata attributes to DataArray
5.373032
5.262632
1.020978
return os.path.join(self.proj.direc_out, self.proj.name, self.model.name, self.run.name, self.name)
def _dir_out(self)
Create string of the data directory to save individual .nc files.
5.04162
4.418098
1.141129
return os.path.join(self.proj.tar_direc_out, self.proj.name, self.model.name, self.run.name)
def _dir_tar_out(self)
Create string of the data directory to store a tar file.
6.56438
5.744304
1.142763
if dtype_out_time is None: dtype_out_time = '' out_lbl = utils.io.data_out_label(self.intvl_out, dtype_out_time, dtype_vert=self.dtype_out_vert) in_lbl = utils.io.data_in_label(self.intvl_in, self.dtype_in_time, self.dtype_in_vert) start_year = utils.times.infer_year(self.start_date) end_year = utils.times.infer_year(self.end_date) yr_lbl = utils.io.yr_label((start_year, end_year)) return '.'.join( [self.name, out_lbl, in_lbl, self.model.name, self.run.name, yr_lbl, extension] ).replace('..', '.')
def _file_name(self, dtype_out_time, extension='nc')
Create the name of the aospy file.
3.111372
3.046329
1.021351
try: return '{0} {1} ({2})'.format(args[0], args[1], ctime()) except IndexError: return '{0} ({1})'.format(args[0], ctime())
def _print_verbose(*args)
Print diagnostic message.
3.288032
3.131624
1.049945
times = utils.times.extract_months( arr[internal_names.TIME_STR], self.months ) return arr.sel(time=times)
def _to_desired_dates(self, arr)
Restrict the xarray DataArray or Dataset to the desired months.
15.845362
10.08012
1.571942
for name_int, names_ext in self._grid_attrs.items(): ds_coord_name = set(names_ext).intersection(set(ds.coords) | set(ds.data_vars)) model_attr = getattr(self.model, name_int, None) if ds_coord_name and (model_attr is not None): # Force coords to have desired name. ds = ds.rename({list(ds_coord_name)[0]: name_int}) ds = ds.set_coords(name_int) if not np.array_equal(ds[name_int], model_attr): if np.allclose(ds[name_int], model_attr): msg = ("Values for '{0}' are nearly (but not exactly) " "the same in the Run {1} and the Model {2}. " "Therefore replacing Run's values with the " "model's.".format(name_int, self.run, self.model)) logging.info(msg) ds[name_int].values = model_attr.values else: msg = ("Model coordinates for '{0}' do not match those" " in Run: {1} vs. {2}" "".format(name_int, ds[name_int], model_attr)) logging.info(msg) else: # Bring in coord from model object if it exists. ds = ds.load() if model_attr is not None: ds[name_int] = model_attr ds = ds.set_coords(name_int) if (self.dtype_in_vert == 'pressure' and internal_names.PLEVEL_STR in ds.coords): self.pressure = ds.level return ds
def _add_grid_attributes(self, ds)
Add model grid attributes to a dataset
3.870942
3.855134
1.004101
logging.info(self._print_verbose("Getting input data:", var)) if isinstance(var, (float, int)): return var else: cond_pfull = ((not hasattr(self, internal_names.PFULL_STR)) and var.def_vert and self.dtype_in_vert == internal_names.ETA_STR) data = self.data_loader.recursively_compute_variable( var, start_date, end_date, self.time_offset, self.model, **self.data_loader_attrs) name = data.name data = self._add_grid_attributes(data.to_dataset(name=data.name)) data = data[name] if cond_pfull: try: self.pfull_coord = data[internal_names.PFULL_STR] except KeyError: pass # Force all data to be at full pressure levels, not half levels. bool_to_pfull = (self.dtype_in_vert == internal_names.ETA_STR and var.def_vert == internal_names.PHALF_STR) if bool_to_pfull: data = utils.vertcoord.to_pfull_from_phalf(data, self.pfull_coord) if var.def_time: # Restrict to the desired dates within each year. if self.dtype_in_time != 'av': return self._to_desired_dates(data) else: return data
def _get_input_data(self, var, start_date, end_date)
Get the data for a single variable over the desired date range.
6.582538
6.55445
1.004285
return [self._get_input_data(var, start_date, end_date) for var in _replace_pressure(self.variables, self.dtype_in_vert)]
def _get_all_data(self, start_date, end_date)
Get the needed data from all of the vars in the calculation.
12.842465
11.641893
1.103125
local_ts = self._local_ts(*data) dt = local_ts[internal_names.TIME_WEIGHTS_STR] # Convert dt to units of days to prevent overflow dt = dt / np.timedelta64(1, 'D') return local_ts, dt
def _compute(self, data)
Perform the calculation.
9.001415
8.594779
1.047312
# Get results at each desired timestep and spatial point. full_ts, dt = self._compute(data) # Vertically integrate. vert_types = ('vert_int', 'vert_av') if self.dtype_out_vert in vert_types and self.var.def_vert: dp = self._get_input_data(_DP_VARS[self.dtype_in_vert], self.start_date, self.end_date) full_ts = utils.vertcoord.int_dp_g(full_ts, dp) if self.dtype_out_vert == 'vert_av': ps = self._get_input_data(utils.vertcoord.ps, self.start_date, self.end_date) full_ts *= (GRAV_EARTH / ps) return full_ts, dt
def _compute_full_ts(self, data)
Perform calculation and create yearly timeseries at each point.
6.781097
6.55569
1.034383
time_defined = self.def_time and not ('av' in self.dtype_in_time) if time_defined: arr = utils.times.yearly_average(arr, dt) return arr
def _full_to_yearly_ts(self, arr, dt)
Average the full timeseries within each year.
13.040777
11.152527
1.169311
if self.dtype_in_time == 'av' or not self.def_time: return arr reductions = { 'ts': lambda xarr: xarr, 'av': lambda xarr: xarr.mean(internal_names.YEAR_STR), 'std': lambda xarr: xarr.std(internal_names.YEAR_STR), } try: return reductions[reduction](arr) except KeyError: raise ValueError("Specified time-reduction method '{}' is not " "supported".format(reduction))
def _time_reduce(self, arr, reduction)
Perform the specified time reduction on a local time-series.
4.873247
4.895875
0.995378
# Get pressure values for data output on hybrid vertical coordinates. bool_pfull = (self.def_vert and self.dtype_in_vert == internal_names.ETA_STR and self.dtype_out_vert is False) if bool_pfull: pfull_data = self._get_input_data(_P_VARS[self.dtype_in_vert], self.start_date, self.end_date) pfull = self._full_to_yearly_ts( pfull_data, arr[internal_names.TIME_WEIGHTS_STR] ).rename('pressure') # Loop over the regions, performing the calculation. reg_dat = {} for reg in self.region: # Just pass along the data if averaged already. if 'av' in self.dtype_in_time: data_out = reg.ts(arr) # Otherwise perform the calculation. else: method = getattr(reg, func) data_out = method(arr) if bool_pfull: # Don't apply e.g. standard deviation to coordinates. if func not in ['av', 'ts']: method = reg.ts # Convert Pa to hPa coord = method(pfull) * 1e-2 data_out = data_out.assign_coords( **{reg.name + '_pressure': coord} ) reg_dat.update(**{reg.name: data_out}) return xr.Dataset(reg_dat)
def region_calcs(self, arr, func)
Perform a calculation for all regions.
6.801505
6.714948
1.01289
logging.info(self._print_verbose("Applying desired time-" "reduction methods.")) reduc_specs = [r.split('.') for r in self.dtype_out_time] reduced = {} for reduc, specs in zip(self.dtype_out_time, reduc_specs): func = specs[-1] if 'reg' in specs: reduced.update({reduc: self.region_calcs(data, func)}) else: reduced.update({reduc: self._time_reduce(data, func)}) return OrderedDict(sorted(reduced.items(), key=lambda t: t[0]))
def _apply_all_time_reductions(self, data)
Apply all requested time reductions to the data.
6.070118
5.756464
1.054487
data = self._get_all_data(self.start_date, self.end_date) logging.info('Computing timeseries for {0} -- ' '{1}.'.format(self.start_date, self.end_date)) full, full_dt = self._compute_full_ts(data) full_out = self._full_to_yearly_ts(full, full_dt) reduced = self._apply_all_time_reductions(full_out) logging.info("Writing desired gridded outputs to disk.") for dtype_time, data in reduced.items(): data = _add_metadata_as_attrs(data, self.var.units, self.var.description, self.dtype_out_vert) self.save(data, dtype_time, dtype_out_vert=self.dtype_out_vert, save_files=True, write_to_tar=write_to_tar) return self
def compute(self, write_to_tar=True)
Perform all desired calculations on the data and save externally.
5.062117
5.013908
1.009615
path = self.path_out[dtype_out_time] if not os.path.isdir(self.dir_out): os.makedirs(self.dir_out) if 'reg' in dtype_out_time: try: reg_data = xr.open_dataset(path) except (EOFError, RuntimeError, IOError): reg_data = xr.Dataset() reg_data.update(data) data_out = reg_data else: data_out = data if isinstance(data_out, xr.DataArray): data_out = xr.Dataset({self.name: data_out}) data_out.to_netcdf(path, engine='netcdf4', format='NETCDF3_64BIT')
def _save_files(self, data, dtype_out_time)
Save the data to netcdf files in direc_out.
2.54443
2.407899
1.056701
# When submitted in parallel and the directory does not exist yet # multiple processes may try to create a new directory; this leads # to an OSError for all processes that tried to make the # directory, but were later than the first. try: os.makedirs(self.dir_tar_out) except OSError: pass # tarfile 'append' mode won't overwrite the old file, which we want. # So open in 'read' mode, extract the file, and then delete it. # But 'read' mode throws OSError if file doesn't exist: make it first. utils.io.dmget([self.path_tar_out]) with tarfile.open(self.path_tar_out, 'a') as tar: pass with tarfile.open(self.path_tar_out, 'r') as tar: old_data_path = os.path.join(self.dir_tar_out, self.file_name[dtype_out_time]) try: tar.extract(self.file_name[dtype_out_time], path=old_data_path) except KeyError: pass else: # The os module treats files on archive as non-empty # directories, so can't use os.remove or os.rmdir. shutil.rmtree(old_data_path) retcode = subprocess.call([ "tar", "--delete", "--file={}".format(self.path_tar_out), self.file_name[dtype_out_time] ]) if retcode: msg = ("The 'tar' command to save your aospy output " "exited with an error. Most likely, this is due " "to using an old version of 'tar' (especially if " "you are on a Mac). Consider installing a newer " "version of 'tar' or disabling tar output by " "setting `write_to_tar=False` in the " "`calc_exec_options` argument of " "`submit_mult_calcs`.") logging.warn(msg) with tarfile.open(self.path_tar_out, 'a') as tar: tar.add(self.path_out[dtype_out_time], arcname=self.file_name[dtype_out_time])
def _write_to_tar(self, dtype_out_time)
Add the data to the tar file in tar_out_direc.
4.526497
4.545104
0.995906
try: self.data_out.update({dtype: data}) except AttributeError: self.data_out = {dtype: data}
def _update_data_out(self, data, dtype)
Append the data of the given dtype_out to the data_out attr.
2.878747
2.345526
1.227335
self._update_data_out(data, dtype_out_time) if save_files: self._save_files(data, dtype_out_time) if write_to_tar and self.proj.tar_direc_out: self._write_to_tar(dtype_out_time) logging.info('\t{}'.format(self.path_out[dtype_out_time]))
def save(self, data, dtype_out_time, dtype_out_vert=False, save_files=True, write_to_tar=False)
Save aospy data to data_out attr and to an external file.
3.647864
3.356677
1.086749
ds = xr.open_dataset(self.path_out[dtype_out_time]) if region: arr = ds[region.name] # Use region-specific pressure values if available. if (self.dtype_in_vert == internal_names.ETA_STR and not dtype_out_vert): reg_pfull_str = region.name + '_pressure' arr = arr.drop([r for r in arr.coords.iterkeys() if r not in (internal_names.PFULL_STR, reg_pfull_str)]) # Rename pfull to pfull_ref always. arr = arr.rename({internal_names.PFULL_STR: internal_names.PFULL_STR + '_ref'}) # Rename region_pfull to pfull if its there. if hasattr(arr, reg_pfull_str): return arr.rename({reg_pfull_str: internal_names.PFULL_STR}) return arr return arr return ds[self.name]
def _load_from_disk(self, dtype_out_time, dtype_out_vert=False, region=False)
Load aospy data saved as netcdf files on the file system.
4.39707
4.381725
1.003502
path = os.path.join(self.dir_tar_out, 'data.tar') utils.io.dmget([path]) with tarfile.open(path, 'r') as data_tar: ds = xr.open_dataset( data_tar.extractfile(self.file_name[dtype_out_time]) ) return ds[self.name]
def _load_from_tar(self, dtype_out_time, dtype_out_vert=False)
Load data save in tarball form on the file system.
4.714396
4.618717
1.020715
msg = ("Loading data from disk for object={0}, dtype_out_time={1}, " "dtype_out_vert={2}, and region=" "{3}".format(self, dtype_out_time, dtype_out_vert, region)) logging.info(msg + ' ({})'.format(ctime())) # Grab from the object if its there. try: data = self.data_out[dtype_out_time] except (AttributeError, KeyError): # Otherwise get from disk. Try scratch first, then archive. try: data = self._load_from_disk(dtype_out_time, dtype_out_vert, region=region) except IOError: data = self._load_from_tar(dtype_out_time, dtype_out_vert) # Copy the array to self.data_out for ease of future access. self._update_data_out(data, dtype_out_time) # Apply desired plotting/cleanup methods. if mask_unphysical: data = self.var.mask_unphysical(data) if plot_units: data = self.var.to_plot_units(data, dtype_vert=dtype_out_vert) return data
def load(self, dtype_out_time, dtype_out_vert=False, region=False, plot_units=False, mask_unphysical=False)
Load the data from the object if possible or from disk.
3.731133
3.6155
1.031982
total = total_precip(precip_largescale, precip_convective) # Mask using xarray's `where` method to prevent divide-by-zero. return precip_convective / total.where(total)
def conv_precip_frac(precip_largescale, precip_convective)
Fraction of total precip that is from convection parameterization. Parameters ---------- precip_largescale, precip_convective : xarray.DataArrays Precipitation from grid-scale condensation and from convective parameterization, respectively. Returns ------- xarray.DataArray
5.846544
6.395008
0.914236