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 th... | 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 ... | 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=Fals... | 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 (optiona... | 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, e... | 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 : datet... | 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:
... | 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)
... | 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
... | 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... | 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 Febr... | 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 "
... | 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))
... | 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... | 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)}] =... | 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 ... | 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_ed... | 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 in... | 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... | 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... | 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 ... | 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. o... | 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_month... | 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 mont... | 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
... | 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 = 'j... | 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
... | 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
-------
... | 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
-------
xar... | 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] = t... | 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 inter... | 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
---------... | 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 th... | 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
------
AssertionErro... | 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 ... | 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 ValueErr... | 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 betw... | 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:
... | 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 tho... | 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:
... | 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... | 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):
... | 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 ret... | 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... | 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 re... | 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 shou... | 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=... | 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 gl... | 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
... | 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_... | 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.v... | 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_S... | 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, A... | 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:
... | 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)
... | 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 mo... | 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 ti... | 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)... | 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 ... | 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)
... | 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.... | 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 = sel... | 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)
... | 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':
... | 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 fo... | 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... | 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,
... | 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... | 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,
... | 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_a... | 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_ve... | 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_... | 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:
... | 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_v... | 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... | 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)
red... | 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 = x... | 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... | 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_st... | 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:
... | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.