_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q23600
heat_index
train
def heat_index(temperature, rh, mask_undefined=True): r"""Calculate the Heat Index from the current temperature and relative humidity. The implementation uses the formula outlined in [Rothfusz1990]_. This equation is a multi-variable least-squares regression of the values obtained in [Steadman1979]_. ...
python
{ "resource": "" }
q23601
apparent_temperature
train
def apparent_temperature(temperature, rh, speed, face_level_winds=False): r"""Calculate the current apparent temperature. Calculates the current apparent temperature based on the wind chill or heat index as appropriate for the current conditions. Follows [NWS10201]_. Parameters ---------- temp...
python
{ "resource": "" }
q23602
pressure_to_height_std
train
def pressure_to_height_std(pressure): r"""Convert pressure data to heights using the U.S. standard atmosphere. The implementation uses the formula outlined in [Hobbs1977]_ pg.60-61. Parameters ---------- pressure : `pint.Quantity` Atmospheric pressure Returns ------- `pint.Qua...
python
{ "resource": "" }
q23603
height_to_geopotential
train
def height_to_geopotential(height): r"""Compute geopotential for a given height. Parameters ---------- height : `pint.Quantity` Height above sea level (array_like) Returns ------- `pint.Quantity` The corresponding geopotential value(s) Examples -------- >>> fro...
python
{ "resource": "" }
q23604
geopotential_to_height
train
def geopotential_to_height(geopot): r"""Compute height from a given geopotential. Parameters ---------- geopotential : `pint.Quantity` Geopotential (array_like) Returns ------- `pint.Quantity` The corresponding height value(s) Examples -------- >>> from metpy.c...
python
{ "resource": "" }
q23605
height_to_pressure_std
train
def height_to_pressure_std(height): r"""Convert height data to pressures using the U.S. standard atmosphere. The implementation inverts the formula outlined in [Hobbs1977]_ pg.60-61. Parameters ---------- height : `pint.Quantity` Atmospheric height Returns ------- `pint.Quanti...
python
{ "resource": "" }
q23606
coriolis_parameter
train
def coriolis_parameter(latitude): r"""Calculate the coriolis parameter at each point. The implementation uses the formula outlined in [Hobbs1977]_ pg.370-371. Parameters ---------- latitude : array_like Latitude at each point Returns ------- `pint.Quantity` The corresp...
python
{ "resource": "" }
q23607
sigma_to_pressure
train
def sigma_to_pressure(sigma, psfc, ptop): r"""Calculate pressure from sigma values. Parameters ---------- sigma : ndarray The sigma levels to be converted to pressure levels. psfc : `pint.Quantity` The surface pressure value. ptop : `pint.Quantity` The pressure value a...
python
{ "resource": "" }
q23608
_check_radians
train
def _check_radians(value, max_radians=2 * np.pi): """Input validation of values that could be in degrees instead of radians. Parameters ---------- value : `pint.Quantity` The input value to check. max_radians : float Maximum absolute value of radians before warning. Returns ...
python
{ "resource": "" }
q23609
remove_observations_below_value
train
def remove_observations_below_value(x, y, z, val=0): r"""Remove all x, y, and z where z is less than val. Will not destroy original values. Parameters ---------- x: array_like x coordinate. y: array_like y coordinate. z: array_like Observation value. val: float ...
python
{ "resource": "" }
q23610
remove_nan_observations
train
def remove_nan_observations(x, y, z): r"""Remove all x, y, and z where z is nan. Will not destroy original values. Parameters ---------- x: array_like x coordinate y: array_like y coordinate z: array_like observation value Returns ------- x, y, z ...
python
{ "resource": "" }
q23611
SkewXTick.gridOn
train
def gridOn(self): # noqa: N802 """Control whether the gridline is drawn for this tick.""" return (self._gridOn and (self._has_default_loc() or transforms.interval_contains(self.get_view_interval(), self.get_loc())))
python
{ "resource": "" }
q23612
SkewXAxes._set_lim_and_transforms
train
def _set_lim_and_transforms(self): """Set limits and transforms. This is called once when the plot is created to set up all the transforms for the data, text and grids. """ # Get the standard transform setup from the Axes base class Axes._set_lim_and_transforms(self) ...
python
{ "resource": "" }
q23613
bzip_blocks_decompress_all
train
def bzip_blocks_decompress_all(data): """Decompress all of the bzip2-ed blocks. Returns the decompressed data as a `bytearray`. """ frames = bytearray() offset = 0 while offset < len(data): size_bytes = data[offset:offset + 4] offset += 4 block_cmp_bytes = abs(Struct('>l...
python
{ "resource": "" }
q23614
nexrad_to_datetime
train
def nexrad_to_datetime(julian_date, ms_midnight): """Convert NEXRAD date time format to python `datetime.datetime`.""" # Subtracting one from julian_date is because epoch date is 1 return datetime.datetime.utcfromtimestamp((julian_date - 1) * day + ms_midnight * milli)
python
{ "resource": "" }
q23615
remap_status
train
def remap_status(val): """Convert status integer value to appropriate bitmask.""" status = 0 bad = BAD_DATA if val & 0xF0 else 0 val &= 0x0F if val == 0: status = START_ELEVATION elif val == 1: status = 0 elif val == 2: status = END_ELEVATION elif val == 3: ...
python
{ "resource": "" }
q23616
reduce_lists
train
def reduce_lists(d): """Replace single item lists in a dictionary with the single item.""" for field in d: old_data = d[field] if len(old_data) == 1: d[field] = old_data[0]
python
{ "resource": "" }
q23617
float16
train
def float16(val): """Convert a 16-bit floating point value to a standard Python float.""" # Fraction is 10 LSB, Exponent middle 5, and Sign the MSB frac = val & 0x03ff exp = (val >> 10) & 0x1F sign = val >> 15 if exp: value = 2 ** (exp - 16) * (1 + float(frac) / 2**10) else: ...
python
{ "resource": "" }
q23618
date_elem
train
def date_elem(ind_days, ind_minutes): """Create a function to parse a datetime from the product-specific blocks.""" def inner(seq): return nexrad_to_datetime(seq[ind_days], seq[ind_minutes] * 60 * 1000) return inner
python
{ "resource": "" }
q23619
combine_elem
train
def combine_elem(ind1, ind2): """Create a function to combine two specified product-specific blocks into a single int.""" def inner(seq): shift = 2**16 if seq[ind1] < 0: seq[ind1] += shift if seq[ind2] < 0: seq[ind2] += shift return (seq[ind1] << 16) | seq...
python
{ "resource": "" }
q23620
relative_humidity_from_dewpoint
train
def relative_humidity_from_dewpoint(temperature, dewpt): r"""Calculate the relative humidity. Uses temperature and dewpoint in celsius to calculate relative humidity using the ratio of vapor pressure to saturation vapor pressures. Parameters ---------- temperature : `pint.Quantity` The...
python
{ "resource": "" }
q23621
exner_function
train
def exner_function(pressure, reference_pressure=mpconsts.P0): r"""Calculate the Exner function. .. math:: \Pi = \left( \frac{p}{p_0} \right)^\kappa This can be used to calculate potential temperature from temperature (and visa-versa), since .. math:: \Pi = \frac{T}{\theta} Parameters ---...
python
{ "resource": "" }
q23622
dry_lapse
train
def dry_lapse(pressure, temperature, ref_pressure=None): r"""Calculate the temperature at a level assuming only dry processes. This function lifts a parcel starting at `temperature`, conserving potential temperature. The starting pressure can be given by `ref_pressure`. Parameters ---------- p...
python
{ "resource": "" }
q23623
moist_lapse
train
def moist_lapse(pressure, temperature, ref_pressure=None): r"""Calculate the temperature at a level assuming liquid saturation processes. This function lifts a parcel starting at `temperature`. The starting pressure can be given by `ref_pressure`. Essentially, this function is calculating moist pseudo-...
python
{ "resource": "" }
q23624
el
train
def el(pressure, temperature, dewpt, parcel_temperature_profile=None): r"""Calculate the equilibrium level. This works by finding the last intersection of the ideal parcel path and the measured environmental temperature. If there is one or fewer intersections, there is no equilibrium level. Parame...
python
{ "resource": "" }
q23625
_parcel_profile_helper
train
def _parcel_profile_helper(pressure, temperature, dewpt): """Help calculate parcel profiles. Returns the temperature and pressure, above, below, and including the LCL. The other calculation functions decide what to do with the pieces. """ # Find the LCL press_lcl, temp_lcl = lcl(pressure[0], t...
python
{ "resource": "" }
q23626
_insert_lcl_level
train
def _insert_lcl_level(pressure, temperature, lcl_pressure): """Insert the LCL pressure into the profile.""" interp_temp = interpolate_1d(lcl_pressure, pressure, temperature) # Pressure needs to be increasing for searchsorted, so flip it and then convert # the index back to the original array loc = ...
python
{ "resource": "" }
q23627
dewpoint_rh
train
def dewpoint_rh(temperature, rh): r"""Calculate the ambient dewpoint given air temperature and relative humidity. Parameters ---------- temperature : `pint.Quantity` Air temperature rh : `pint.Quantity` Relative humidity expressed as a ratio in the range 0 < rh <= 1 Returns ...
python
{ "resource": "" }
q23628
dewpoint
train
def dewpoint(e): r"""Calculate the ambient dewpoint given the vapor pressure. Parameters ---------- e : `pint.Quantity` Water vapor partial pressure Returns ------- `pint.Quantity` Dew point temperature See Also -------- dewpoint_rh, saturation_vapor_pressure, ...
python
{ "resource": "" }
q23629
mixing_ratio
train
def mixing_ratio(part_press, tot_press, molecular_weight_ratio=mpconsts.epsilon): r"""Calculate the mixing ratio of a gas. This calculates mixing ratio given its partial pressure and the total pressure of the air. There are no required units for the input arrays, other than that they have the same unit...
python
{ "resource": "" }
q23630
equivalent_potential_temperature
train
def equivalent_potential_temperature(pressure, temperature, dewpoint): r"""Calculate equivalent potential temperature. This calculation must be given an air parcel's pressure, temperature, and dewpoint. The implementation uses the formula outlined in [Bolton1980]_: First, the LCL temperature is calcul...
python
{ "resource": "" }
q23631
saturation_equivalent_potential_temperature
train
def saturation_equivalent_potential_temperature(pressure, temperature): r"""Calculate saturation equivalent potential temperature. This calculation must be given an air parcel's pressure and temperature. The implementation uses the formula outlined in [Bolton1980]_ for the equivalent potential temperat...
python
{ "resource": "" }
q23632
virtual_temperature
train
def virtual_temperature(temperature, mixing, molecular_weight_ratio=mpconsts.epsilon): r"""Calculate virtual temperature. This calculation must be given an air parcel's temperature and mixing ratio. The implementation uses the formula outlined in [Hobbs2006]_ pg.80. Parameters ---------- tempe...
python
{ "resource": "" }
q23633
virtual_potential_temperature
train
def virtual_potential_temperature(pressure, temperature, mixing, molecular_weight_ratio=mpconsts.epsilon): r"""Calculate virtual potential temperature. This calculation must be given an air parcel's pressure, temperature, and mixing ratio. The implementation uses the formu...
python
{ "resource": "" }
q23634
density
train
def density(pressure, temperature, mixing, molecular_weight_ratio=mpconsts.epsilon): r"""Calculate density. This calculation must be given an air parcel's pressure, temperature, and mixing ratio. The implementation uses the formula outlined in [Hobbs2006]_ pg.67. Parameters ---------- temperat...
python
{ "resource": "" }
q23635
relative_humidity_wet_psychrometric
train
def relative_humidity_wet_psychrometric(dry_bulb_temperature, web_bulb_temperature, pressure, **kwargs): r"""Calculate the relative humidity with wet bulb and dry bulb temperatures. This uses a psychrometric relationship as outlined in [WMO8-2014]_, with coefficients...
python
{ "resource": "" }
q23636
psychrometric_vapor_pressure_wet
train
def psychrometric_vapor_pressure_wet(dry_bulb_temperature, wet_bulb_temperature, pressure, psychrometer_coefficient=6.21e-4 / units.kelvin): r"""Calculate the vapor pressure with wet bulb and dry bulb temperatures. This uses a psychrometric relationship as outlined in [WMO8...
python
{ "resource": "" }
q23637
cape_cin
train
def cape_cin(pressure, temperature, dewpt, parcel_profile): r"""Calculate CAPE and CIN. Calculate the convective available potential energy (CAPE) and convective inhibition (CIN) of a given upper air profile and parcel path. CIN is integrated between the surface and LFC, CAPE is integrated between the ...
python
{ "resource": "" }
q23638
_find_append_zero_crossings
train
def _find_append_zero_crossings(x, y): r""" Find and interpolate zero crossings. Estimate the zero crossings of an x,y series and add estimated crossings to series, returning a sorted array with no duplicate values. Parameters ---------- x : `pint.Quantity` x values of data y :...
python
{ "resource": "" }
q23639
most_unstable_parcel
train
def most_unstable_parcel(pressure, temperature, dewpoint, heights=None, bottom=None, depth=300 * units.hPa): """ Determine the most unstable parcel in a layer. Determines the most unstable parcel of air by calculating the equivalent potential temperature and finding its maximum...
python
{ "resource": "" }
q23640
surface_based_cape_cin
train
def surface_based_cape_cin(pressure, temperature, dewpoint): r"""Calculate surface-based CAPE and CIN. Calculate the convective available potential energy (CAPE) and convective inhibition (CIN) of a given upper air profile for a surface-based parcel. CIN is integrated between the surface and LFC, CAPE ...
python
{ "resource": "" }
q23641
mixed_parcel
train
def mixed_parcel(p, temperature, dewpt, parcel_start_pressure=None, heights=None, bottom=None, depth=100 * units.hPa, interpolate=True): r"""Calculate the properties of a parcel mixed from a layer. Determines the properties of an air parcel that is the result of complete mixing of a given ...
python
{ "resource": "" }
q23642
dry_static_energy
train
def dry_static_energy(heights, temperature): r"""Calculate the dry static energy of parcels. This function will calculate the dry static energy following the first two terms of equation 3.72 in [Hobbs2006]_. Notes ----- .. math::\text{dry static energy} = c_{pd} * T + gz * :math:`T` is te...
python
{ "resource": "" }
q23643
moist_static_energy
train
def moist_static_energy(heights, temperature, specific_humidity): r"""Calculate the moist static energy of parcels. This function will calculate the moist static energy following equation 3.72 in [Hobbs2006]_. Notes ----- .. math::\text{moist static energy} = c_{pd} * T + gz + L_v q * :mat...
python
{ "resource": "" }
q23644
thickness_hydrostatic
train
def thickness_hydrostatic(pressure, temperature, **kwargs): r"""Calculate the thickness of a layer via the hypsometric equation. This thickness calculation uses the pressure and temperature profiles (and optionally mixing ratio) via the hypsometric equation with virtual temperature adjustment .. math:...
python
{ "resource": "" }
q23645
thickness_hydrostatic_from_relative_humidity
train
def thickness_hydrostatic_from_relative_humidity(pressure, temperature, relative_humidity, **kwargs): r"""Calculate the thickness of a layer given pressure, temperature and relative humidity. Similar to ``thickness_hydrostatic``, this thickness calculation uses ...
python
{ "resource": "" }
q23646
brunt_vaisala_frequency_squared
train
def brunt_vaisala_frequency_squared(heights, potential_temperature, axis=0): r"""Calculate the square of the Brunt-Vaisala frequency. Brunt-Vaisala frequency squared (a measure of atmospheric stability) is given by the formula: .. math:: N^2 = \frac{g}{\theta} \frac{d\theta}{dz} This formula is b...
python
{ "resource": "" }
q23647
brunt_vaisala_frequency
train
def brunt_vaisala_frequency(heights, potential_temperature, axis=0): r"""Calculate the Brunt-Vaisala frequency. This function will calculate the Brunt-Vaisala frequency as follows: .. math:: N = \left( \frac{g}{\theta} \frac{d\theta}{dz} \right)^\frac{1}{2} This formula based off of Equations 3.75 an...
python
{ "resource": "" }
q23648
brunt_vaisala_period
train
def brunt_vaisala_period(heights, potential_temperature, axis=0): r"""Calculate the Brunt-Vaisala period. This function is a helper function for `brunt_vaisala_frequency` that calculates the period of oscilation as in Exercise 3.13 of [Hobbs2006]_: .. math:: \tau = \frac{2\pi}{N} Returns `NaN` wh...
python
{ "resource": "" }
q23649
wet_bulb_temperature
train
def wet_bulb_temperature(pressure, temperature, dewpoint): """Calculate the wet-bulb temperature using Normand's rule. This function calculates the wet-bulb temperature using the Normand method. The LCL is computed, and that parcel brought down to the starting pressure along a moist adiabat. The Norman...
python
{ "resource": "" }
q23650
static_stability
train
def static_stability(pressure, temperature, axis=0): r"""Calculate the static stability within a vertical profile. .. math:: \sigma = -\frac{RT}{p} \frac{\partial \ln \theta}{\partial p} This formuala is based on equation 4.3.6 in [Bluestein1992]_. Parameters ---------- pressure : array-like ...
python
{ "resource": "" }
q23651
dewpoint_from_specific_humidity
train
def dewpoint_from_specific_humidity(specific_humidity, temperature, pressure): r"""Calculate the dewpoint from specific humidity, temperature, and pressure. Parameters ---------- specific_humidity: `pint.Quantity` Specific humidity of air temperature: `pint.Quantity` Air temperature...
python
{ "resource": "" }
q23652
vertical_velocity_pressure
train
def vertical_velocity_pressure(w, pressure, temperature, mixing=0): r"""Calculate omega from w assuming hydrostatic conditions. This function converts vertical velocity with respect to height :math:`\left(w = \frac{Dz}{Dt}\right)` to that with respect to pressure :math:`\left(\omega = \frac{Dp}{Dt}\rig...
python
{ "resource": "" }
q23653
vertical_velocity
train
def vertical_velocity(omega, pressure, temperature, mixing=0): r"""Calculate w from omega assuming hydrostatic conditions. This function converts vertical velocity with respect to pressure :math:`\left(\omega = \frac{Dp}{Dt}\right)` to that with respect to height :math:`\left(w = \frac{Dz}{Dt}\right)` ...
python
{ "resource": "" }
q23654
make_geo
train
def make_geo(attrs_dict, globe): """Handle geostationary projection.""" attr_mapping = [('satellite_height', 'perspective_point_height'), ('sweep_axis', 'sweep_angle_axis')] kwargs = CFProjection.build_projection_kwargs(attrs_dict, attr_mapping) # CartoPy can't handle central latitu...
python
{ "resource": "" }
q23655
make_lcc
train
def make_lcc(attrs_dict, globe): """Handle Lambert conformal conic projection.""" attr_mapping = [('central_longitude', 'longitude_of_central_meridian'), ('standard_parallels', 'standard_parallel')] kwargs = CFProjection.build_projection_kwargs(attrs_dict, attr_mapping) if 'standard_...
python
{ "resource": "" }
q23656
make_mercator
train
def make_mercator(attrs_dict, globe): """Handle Mercator projection.""" attr_mapping = [('latitude_true_scale', 'standard_parallel'), ('scale_factor', 'scale_factor_at_projection_origin')] kwargs = CFProjection.build_projection_kwargs(attrs_dict, attr_mapping) # Work around the fact...
python
{ "resource": "" }
q23657
make_stereo
train
def make_stereo(attrs_dict, globe): """Handle generic stereographic projection.""" attr_mapping = [('scale_factor', 'scale_factor_at_projection_origin')] kwargs = CFProjection.build_projection_kwargs(attrs_dict, attr_mapping) return ccrs.Stereographic(globe=globe, **kwargs)
python
{ "resource": "" }
q23658
CFProjection.build_projection_kwargs
train
def build_projection_kwargs(cls, source, mapping): """Handle mapping a dictionary of metadata to keyword arguments.""" return cls._map_arg_names(source, cls._default_attr_mapping + mapping)
python
{ "resource": "" }
q23659
CFProjection._map_arg_names
train
def _map_arg_names(source, mapping): """Map one set of keys to another.""" return {cartopy_name: source[cf_name] for cartopy_name, cf_name in mapping if cf_name in source}
python
{ "resource": "" }
q23660
CFProjection.cartopy_globe
train
def cartopy_globe(self): """Initialize a `cartopy.crs.Globe` from the metadata.""" if 'earth_radius' in self._attrs: kwargs = {'ellipse': 'sphere', 'semimajor_axis': self._attrs['earth_radius'], 'semiminor_axis': self._attrs['earth_radius']} else: at...
python
{ "resource": "" }
q23661
CFProjection.to_cartopy
train
def to_cartopy(self): """Convert to a CartoPy projection.""" globe = self.cartopy_globe proj_name = self._attrs['grid_mapping_name'] try: proj_handler = self.projection_registry[proj_name] except KeyError: raise ValueError('Unhandled projection: {}'.format...
python
{ "resource": "" }
q23662
add_timestamp
train
def add_timestamp(ax, time=None, x=0.99, y=-0.04, ha='right', high_contrast=False, pretext='Created: ', time_format='%Y-%m-%dT%H:%M:%SZ', **kwargs): """Add a timestamp to a plot. Adds a timestamp to a plot, defaulting to the time of plot creation in ISO format. Parameters ---------- ...
python
{ "resource": "" }
q23663
_add_logo
train
def _add_logo(fig, x=10, y=25, zorder=100, which='metpy', size='small', **kwargs): """Add the MetPy or Unidata logo to a figure. Adds an image to the figure. Parameters ---------- fig : `matplotlib.figure` The `figure` instance used for plotting x : int x position padding in pixe...
python
{ "resource": "" }
q23664
add_metpy_logo
train
def add_metpy_logo(fig, x=10, y=25, zorder=100, size='small', **kwargs): """Add the MetPy logo to a figure. Adds an image of the MetPy logo to the figure. Parameters ---------- fig : `matplotlib.figure` The `figure` instance used for plotting x : int x position padding in pixels ...
python
{ "resource": "" }
q23665
colored_line
train
def colored_line(x, y, c, **kwargs): """Create a multi-colored line. Takes a set of points and turns them into a collection of lines colored by another array. Parameters ---------- x : array-like x-axis coordinates y : array-like y-axis coordinates c : array-like va...
python
{ "resource": "" }
q23666
convert_gempak_color
train
def convert_gempak_color(c, style='psc'): """Convert GEMPAK color numbers into corresponding Matplotlib colors. Takes a sequence of GEMPAK color numbers and turns them into equivalent Matplotlib colors. Various GEMPAK quirks are respected, such as treating negative values as equivalent to 0. Param...
python
{ "resource": "" }
q23667
process_msg3
train
def process_msg3(fname): """Handle information for message type 3.""" with open(fname, 'r') as infile: info = [] for lineno, line in enumerate(infile): parts = line.split(' ') try: var_name, desc, typ, units = parts[:4] size_hw = parts[-1]...
python
{ "resource": "" }
q23668
process_msg18
train
def process_msg18(fname): """Handle information for message type 18.""" with open(fname, 'r') as infile: info = [] for lineno, line in enumerate(infile): parts = line.split(' ') try: if len(parts) == 8: parts = parts[:6] + [parts[6] + ...
python
{ "resource": "" }
q23669
fix_type
train
def fix_type(typ, size, additional=None): """Fix up creating the appropriate struct type based on the information in the column.""" if additional is not None: my_types = types + additional else: my_types = types for t, info in my_types: if callable(t): matches = t(ty...
python
{ "resource": "" }
q23670
fix_var_name
train
def fix_var_name(var_name): """Clean up and apply standard formatting to variable names.""" name = var_name.strip() for char in '(). /#,': name = name.replace(char, '_') name = name.replace('+', 'pos_') name = name.replace('-', 'neg_') if name.endswith('_'): name = name[:-1] ...
python
{ "resource": "" }
q23671
fix_desc
train
def fix_desc(desc, units=None): """Clean up description column.""" full_desc = desc.strip() if units and units != 'N/A': if full_desc: full_desc += ' (' + units + ')' else: full_desc = units return full_desc
python
{ "resource": "" }
q23672
write_file
train
def write_file(fname, info): """Write out the generated Python code.""" with open(fname, 'w') as outfile: # File header outfile.write('# Copyright (c) 2018 MetPy Developers.\n') outfile.write('# Distributed under the terms of the BSD 3-Clause License.\n') outfile.write('# SPDX-Li...
python
{ "resource": "" }
q23673
pandas_dataframe_to_unit_arrays
train
def pandas_dataframe_to_unit_arrays(df, column_units=None): """Attach units to data in pandas dataframes and return united arrays. Parameters ---------- df : `pandas.DataFrame` Data in pandas dataframe. column_units : dict Dictionary of units to attach to columns of the dataframe. ...
python
{ "resource": "" }
q23674
concatenate
train
def concatenate(arrs, axis=0): r"""Concatenate multiple values into a new unitized object. This is essentially a unit-aware version of `numpy.concatenate`. All items must be able to be converted to the same units. If an item has no units, it will be given those of the rest of the collection, without co...
python
{ "resource": "" }
q23675
diff
train
def diff(x, **kwargs): """Calculate the n-th discrete difference along given axis. Wraps :func:`numpy.diff` to handle units. Parameters ---------- x : array-like Input data n : int, optional The number of times values are differenced. axis : int, optional The axis a...
python
{ "resource": "" }
q23676
atleast_1d
train
def atleast_1d(*arrs): r"""Convert inputs to arrays with at least one dimension. Scalars are converted to 1-dimensional arrays, whilst other higher-dimensional inputs are preserved. This is a thin wrapper around `numpy.atleast_1d` to preserve units. Parameters ---------- arrs : arbitrary p...
python
{ "resource": "" }
q23677
_check_argument_units
train
def _check_argument_units(args, dimensionality): """Yield arguments with improper dimensionality.""" for arg, val in args.items(): # Get the needed dimensionality (for printing) as well as cached, parsed version # for this argument. try: need, parsed = dimensionality[arg] ...
python
{ "resource": "" }
q23678
interpolate_to_slice
train
def interpolate_to_slice(data, points, interp_type='linear'): r"""Obtain an interpolated slice through data using xarray. Utilizing the interpolation functionality in `xarray`, this function takes a slice the given data (currently only regular grids are supported), which is given as an `xarray.DataArra...
python
{ "resource": "" }
q23679
geodesic
train
def geodesic(crs, start, end, steps): r"""Construct a geodesic path between two points. This function acts as a wrapper for the geodesic construction available in `pyproj`. Parameters ---------- crs: `cartopy.crs` Cartopy Coordinate Reference System to use for the output start: (2, ) a...
python
{ "resource": "" }
q23680
cross_section
train
def cross_section(data, start, end, steps=100, interp_type='linear'): r"""Obtain an interpolated cross-sectional slice through gridded data. Utilizing the interpolation functionality in `xarray`, this function takes a vertical cross-sectional slice along a geodesic through the given data on a regular grid,...
python
{ "resource": "" }
q23681
preprocess_xarray
train
def preprocess_xarray(func): """Decorate a function to convert all DataArray arguments to pint.Quantities. This uses the metpy xarray accessors to do the actual conversion. """ @functools.wraps(func) def wrapper(*args, **kwargs): args = tuple(a.metpy.unit_array if isinstance(a, xr.DataArray...
python
{ "resource": "" }
q23682
check_matching_coordinates
train
def check_matching_coordinates(func): """Decorate a function to make sure all given DataArrays have matching coordinates.""" @functools.wraps(func) def wrapper(*args, **kwargs): data_arrays = ([a for a in args if isinstance(a, xr.DataArray)] + [a for a in kwargs.values() if is...
python
{ "resource": "" }
q23683
_reassign_quantity_indexer
train
def _reassign_quantity_indexer(data, indexers): """Reassign a units.Quantity indexer to units of relevant coordinate.""" def _to_magnitude(val, unit): try: return val.to(unit).m except AttributeError: return val for coord_name in indexers: # Handle axis types...
python
{ "resource": "" }
q23684
resample_nn_1d
train
def resample_nn_1d(a, centers): """Return one-dimensional nearest-neighbor indexes based on user-specified centers. Parameters ---------- a : array-like 1-dimensional array of numeric values from which to extract indexes of nearest-neighbors centers : array-like 1-dimensiona...
python
{ "resource": "" }
q23685
nearest_intersection_idx
train
def nearest_intersection_idx(a, b): """Determine the index of the point just before two lines with common x values. Parameters ---------- a : array-like 1-dimensional array of y-values for line 1 b : array-like 1-dimensional array of y-values for line 2 Returns ------- ...
python
{ "resource": "" }
q23686
find_intersections
train
def find_intersections(x, a, b, direction='all'): """Calculate the best estimate of intersection. Calculates the best estimates of the intersection of two y-value data sets that share a common x-value set. Parameters ---------- x : array-like 1-dimensional array of numeric x-values ...
python
{ "resource": "" }
q23687
_next_non_masked_element
train
def _next_non_masked_element(a, idx): """Return the next non masked element of a masked array. If an array is masked, return the next non-masked element (if the given index is masked). If no other unmasked points are after the given masked point, returns none. Parameters ---------- a : array-l...
python
{ "resource": "" }
q23688
_delete_masked_points
train
def _delete_masked_points(*arrs): """Delete masked points from arrays. Takes arrays and removes masked points to help with calculations and plotting. Parameters ---------- arrs : one or more array-like source arrays Returns ------- arrs : one or more array-like arrays ...
python
{ "resource": "" }
q23689
reduce_point_density
train
def reduce_point_density(points, radius, priority=None): r"""Return a mask to reduce the density of points in irregularly-spaced data. This function is used to down-sample a collection of scattered points (e.g. surface data), returning a mask that can be used to select the points from one or more arrays ...
python
{ "resource": "" }
q23690
_get_bound_pressure_height
train
def _get_bound_pressure_height(pressure, bound, heights=None, interpolate=True): """Calculate the bounding pressure and height in a layer. Given pressure, optional heights, and a bound, return either the closest pressure/height or interpolated pressure/height. If no heights are provided, a standard atmosph...
python
{ "resource": "" }
q23691
get_layer_heights
train
def get_layer_heights(heights, depth, *args, **kwargs): """Return an atmospheric layer from upper air data with the requested bottom and depth. This function will subset an upper air dataset to contain only the specified layer using the heights only. Parameters ---------- heights : array-like ...
python
{ "resource": "" }
q23692
get_layer
train
def get_layer(pressure, *args, **kwargs): r"""Return an atmospheric layer from upper air data with the requested bottom and depth. This function will subset an upper air dataset to contain only the specified layer. The bottom of the layer can be specified with a pressure or height above the surface pre...
python
{ "resource": "" }
q23693
interp
train
def interp(x, xp, *args, **kwargs): """Wrap interpolate_1d for deprecated interp.""" return interpolate_1d(x, xp, *args, **kwargs)
python
{ "resource": "" }
q23694
find_bounding_indices
train
def find_bounding_indices(arr, values, axis, from_below=True): """Find the indices surrounding the values within arr along axis. Returns a set of above, below, good. Above and below are lists of arrays of indices. These lists are formulated such that they can be used directly to index into a numpy arra...
python
{ "resource": "" }
q23695
log_interp
train
def log_interp(x, xp, *args, **kwargs): """Wrap log_interpolate_1d for deprecated log_interp.""" return log_interpolate_1d(x, xp, *args, **kwargs)
python
{ "resource": "" }
q23696
_greater_or_close
train
def _greater_or_close(a, value, **kwargs): r"""Compare values for greater or close to boolean masks. Returns a boolean mask for values greater than or equal to a target within a specified absolute or relative tolerance (as in :func:`numpy.isclose`). Parameters ---------- a : array-like ...
python
{ "resource": "" }
q23697
_less_or_close
train
def _less_or_close(a, value, **kwargs): r"""Compare values for less or close to boolean masks. Returns a boolean mask for values less than or equal to a target within a specified absolute or relative tolerance (as in :func:`numpy.isclose`). Parameters ---------- a : array-like Array of...
python
{ "resource": "" }
q23698
grid_deltas_from_dataarray
train
def grid_deltas_from_dataarray(f): """Calculate the horizontal deltas between grid points of a DataArray. Calculate the signed delta distance between grid points of a DataArray in the horizontal directions, whether the grid is lat/lon or x/y. Parameters ---------- f : `xarray.DataArray` ...
python
{ "resource": "" }
q23699
xarray_derivative_wrap
train
def xarray_derivative_wrap(func): """Decorate the derivative functions to make them work nicely with DataArrays. This will automatically determine if the coordinates can be pulled directly from the DataArray, or if a call to lat_lon_grid_deltas is needed. """ @functools.wraps(func) def wrapper(...
python
{ "resource": "" }