signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
@property<EOL><INDENT>def dtype(self):<DEDENT>
return self._data.dtype<EOL>
numpy.dtype: Describes the layout of each element of the data.
f8497:c3:m6
@property<EOL><INDENT>def datatype(self):<DEDENT>
return self._data.dtype<EOL>
numpy.dtype: Describes the layout of each element of the data.
f8497:c3:m7
@property<EOL><INDENT>def dimensions(self):<DEDENT>
return self._dimensions<EOL>
tuple[str]: all the names of :class:`Dimension` used by this :class:`Variable`.
f8497:c3:m8
def __setitem__(self, ind, value):
self._data[ind] = value<EOL>
Handle setting values on the Variable.
f8497:c3:m9
def __getitem__(self, ind):
return self._data[ind]<EOL>
Handle getting values from the Variable.
f8497:c3:m10
def __str__(self):
groups = [str(type(self))<EOL>+ '<STR_LIT>'.format(self, '<STR_LIT:U+002CU+0020>'.join(self.dimensions))]<EOL>for att in self.ncattrs():<EOL><INDENT>groups.append('<STR_LIT>'.format(att, getattr(self, att)))<EOL><DEDENT>if self.ndim:<EOL><INDENT>shape = tuple(int(s) for s in self.shape)<EOL>if self.ndim > <NUM_LIT:1>:<...
Return a string representation of the Variable.
f8497:c3:m11
def __init__(self, group, name, size=None):
self._group = group<EOL>self.name = name<EOL>self.size = size<EOL>
Initialize a Dimension. Instead of constructing a Dimension directly, you should use ``Group.createDimension``. Parameters ---------- group : Group The parent Group that owns this Variable. name : str The name of this Variable. size : int or None...
f8497:c4:m0
def group(self):
return self._group<EOL>
Get the Group that owns this Dimension. Returns ------- Group The parent Group.
f8497:c4:m1
def __len__(self):
return self.size<EOL>
Return the length of this Dimension.
f8497:c4:m2
def __str__(self):
return '<STR_LIT>'.format(type(self), self)<EOL>
Return a string representation of this Dimension.
f8497:c4:m3
def register_processor(num):
def inner(func):<EOL><INDENT>"""<STR_LIT>"""<EOL>processors[num] = func<EOL>return func<EOL><DEDENT>return inner<EOL>
Register functions to handle particular message numbers.
f8500:m0
@register_processor(<NUM_LIT:3>)<EOL>def process_msg3(fname):
with open(fname, '<STR_LIT:r>') as infile:<EOL><INDENT>info = []<EOL>for lineno, line in enumerate(infile):<EOL><INDENT>parts = line.split('<STR_LIT:U+0020>')<EOL>try:<EOL><INDENT>var_name, desc, typ, units = parts[:<NUM_LIT:4>]<EOL>size_hw = parts[-<NUM_LIT:1>]<EOL>if '<STR_LIT:->' in size_hw:<EOL><INDENT>start, end =...
Handle information for message type 3.
f8500:m1
@register_processor(<NUM_LIT>)<EOL>def process_msg18(fname):
with open(fname, '<STR_LIT:r>') as infile:<EOL><INDENT>info = []<EOL>for lineno, line in enumerate(infile):<EOL><INDENT>parts = line.split('<STR_LIT:U+0020>')<EOL>try:<EOL><INDENT>if len(parts) == <NUM_LIT:8>:<EOL><INDENT>parts = parts[:<NUM_LIT:6>] + [parts[<NUM_LIT:6>] + parts[<NUM_LIT:7>]]<EOL><DEDENT>var_name, desc...
Handle information for message type 18.
f8500:m2
def fix_type(typ, size, additional=None):
if additional is not None:<EOL><INDENT>my_types = types + additional<EOL><DEDENT>else:<EOL><INDENT>my_types = types<EOL><DEDENT>for t, info in my_types:<EOL><INDENT>if callable(t):<EOL><INDENT>matches = t(typ)<EOL><DEDENT>else:<EOL><INDENT>matches = t == typ<EOL><DEDENT>if matches:<EOL><INDENT>if callable(info):<EOL><I...
Fix up creating the appropriate struct type based on the information in the column.
f8500:m3
def fix_var_name(var_name):
name = var_name.strip()<EOL>for char in '<STR_LIT>':<EOL><INDENT>name = name.replace(char, '<STR_LIT:_>')<EOL><DEDENT>name = name.replace('<STR_LIT:+>', '<STR_LIT>')<EOL>name = name.replace('<STR_LIT:->', '<STR_LIT>')<EOL>if name.endswith('<STR_LIT:_>'):<EOL><INDENT>name = name[:-<NUM_LIT:1>]<EOL><DEDENT>return name<EO...
Clean up and apply standard formatting to variable names.
f8500:m4
def fix_desc(desc, units=None):
full_desc = desc.strip()<EOL>if units and units != '<STR_LIT>':<EOL><INDENT>if full_desc:<EOL><INDENT>full_desc += '<STR_LIT>' + units + '<STR_LIT:)>'<EOL><DEDENT>else:<EOL><INDENT>full_desc = units<EOL><DEDENT><DEDENT>return full_desc<EOL>
Clean up description column.
f8500:m5
def ignored_item(item):
return item['<STR_LIT:name>'].upper() == '<STR_LIT>' or '<STR_LIT:x>' in item['<STR_LIT>']<EOL>
Determine whether this item should be ignored.
f8500:m6
def need_desc(item):
return item['<STR_LIT>'] and not ignored_item(item)<EOL>
Determine whether we need a description for this item.
f8500:m7
def field_name(item):
return '<STR_LIT>'.format(item['<STR_LIT:name>']) if not ignored_item(item) else None<EOL>
Return the field name if appropriate.
f8500:m8
def field_fmt(item):
return '<STR_LIT>'.format(item['<STR_LIT>']) if '<STR_LIT:">' not in item['<STR_LIT>'] else item['<STR_LIT>']<EOL>
Return the field format if appropriate.
f8500:m9
def write_file(fname, info):
with open(fname, '<STR_LIT:w>') as outfile:<EOL><INDENT>outfile.write('<STR_LIT>')<EOL>outfile.write('<STR_LIT>')<EOL>outfile.write('<STR_LIT>')<EOL>outfile.write('<STR_LIT>')<EOL>outfile.write('<STR_LIT>')<EOL>outfile.write('<STR_LIT>')<EOL>outdata = '<STR_LIT>'.join('<STR_LIT>'.format(<EOL>**i) for i in info if need_...
Write out the generated Python code.
f8500:m10
def warn_deprecated(since, message='<STR_LIT>', name='<STR_LIT>', alternative='<STR_LIT>', pending=False,<EOL>obj_type='<STR_LIT>', addendum='<STR_LIT>'):
message = _generate_deprecation_message(since, message, name, alternative,<EOL>pending, obj_type)<EOL>warnings.warn(message, metpyDeprecation, stacklevel=<NUM_LIT:1>)<EOL>
Display deprecation warning in a standard way. Parameters ---------- since : str The release at which this API became deprecated. message : str, optional Override the default deprecation message. The format specifier `%(name)s` may be used for the name of the function, ...
f8504:m1
def deprecated(since, message='<STR_LIT>', name='<STR_LIT>', alternative='<STR_LIT>', pending=False,<EOL>obj_type=None, addendum='<STR_LIT>'):
def deprecate(obj, message=message, name=name, alternative=alternative,<EOL>pending=pending, addendum=addendum):<EOL><INDENT>import textwrap<EOL>if not name:<EOL><INDENT>name = obj.__name__<EOL><DEDENT>if isinstance(obj, type):<EOL><INDENT>obj_type = '<STR_LIT:class>'<EOL>old_doc = obj.__doc__<EOL>func = obj.__init__<E...
Mark a function or a class as deprecated. Parameters ---------- since : str The release at which this API became deprecated. This is required. message : str, optional Override the default deprecation message. The format specifier `%(name)s` may be used for the name of...
f8504:m2
def get_keywords():
<EOL>git_refnames = "<STR_LIT>"<EOL>git_full = "<STR_LIT>"<EOL>git_date = "<STR_LIT>"<EOL>keywords = {"<STR_LIT>": git_refnames, "<STR_LIT>": git_full, "<STR_LIT:date>": git_date}<EOL>return keywords<EOL>
Get the keywords needed to look up the version information.
f8505:m0
def get_config():
<EOL>cfg = VersioneerConfig()<EOL>cfg.VCS = "<STR_LIT>"<EOL>cfg.style = "<STR_LIT>"<EOL>cfg.tag_prefix = "<STR_LIT:v>"<EOL>cfg.parentdir_prefix = "<STR_LIT>"<EOL>cfg.versionfile_source = "<STR_LIT>"<EOL>cfg.verbose = False<EOL>return cfg<EOL>
Create, populate and return the VersioneerConfig() object.
f8505:m1
def register_vcs_handler(vcs, method):
def decorate(f):<EOL><INDENT>"""<STR_LIT>"""<EOL>if vcs not in HANDLERS:<EOL><INDENT>HANDLERS[vcs] = {}<EOL><DEDENT>HANDLERS[vcs][method] = f<EOL>return f<EOL><DEDENT>return decorate<EOL>
Decorator to mark a method as the handler for a particular VCS.
f8505:m2
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,<EOL>env=None):
assert isinstance(commands, list)<EOL>p = None<EOL>for c in commands:<EOL><INDENT>try:<EOL><INDENT>dispcmd = str([c] + args)<EOL>p = subprocess.Popen([c] + args, cwd=cwd, env=env,<EOL>stdout=subprocess.PIPE,<EOL>stderr=(subprocess.PIPE if hide_stderr<EOL>else None))<EOL>break<EOL><DEDENT>except EnvironmentError:<EOL><I...
Call the given command(s).
f8505:m3
def versions_from_parentdir(parentdir_prefix, root, verbose):
rootdirs = []<EOL>for i in range(<NUM_LIT:3>):<EOL><INDENT>dirname = os.path.basename(root)<EOL>if dirname.startswith(parentdir_prefix):<EOL><INDENT>return {"<STR_LIT:version>": dirname[len(parentdir_prefix):],<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT>": False, "<STR_LIT:error>": None, "<STR_LIT:date>": None}<EOL><DEDENT>e...
Try to determine the version from the parent directory name. Source tarballs conventionally unpack into a directory that includes both the project name and a version string. We will also support searching up two directory levels for an appropriately named parent directory
f8505:m4
@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_get_keywords(versionfile_abs):
<EOL>keywords = {}<EOL>try:<EOL><INDENT>f = open(versionfile_abs, "<STR_LIT:r>")<EOL>for line in f.readlines():<EOL><INDENT>if line.strip().startswith("<STR_LIT>"):<EOL><INDENT>mo = re.search(r'<STR_LIT>', line)<EOL>if mo:<EOL><INDENT>keywords["<STR_LIT>"] = mo.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>if line.strip().sta...
Extract version information from the given file.
f8505:m5
@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_versions_from_keywords(keywords, tag_prefix, verbose):
if not keywords:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>date = keywords.get("<STR_LIT:date>")<EOL>if date is not None:<EOL><INDENT>date = date.strip().replace("<STR_LIT:U+0020>", "<STR_LIT:T>", <NUM_LIT:1>).replace("<STR_LIT:U+0020>", "<STR_LIT>", <NUM_LIT:1>)<EOL><DEDENT>refnames = keywords["<STR_LIT...
Get version information from git keywords.
f8505:m6
@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
GITS = ["<STR_LIT>"]<EOL>if sys.platform == "<STR_LIT:win32>":<EOL><INDENT>GITS = ["<STR_LIT>", "<STR_LIT>"]<EOL><DEDENT>out, rc = run_command(GITS, ["<STR_LIT>", "<STR_LIT>"], cwd=root,<EOL>hide_stderr=True)<EOL>if rc != <NUM_LIT:0>:<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % root)<EOL><DEDENT>raise NotTh...
Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree.
f8505:m7
def plus_or_dot(pieces):
if "<STR_LIT:+>" in pieces.get("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>return "<STR_LIT:.>"<EOL><DEDENT>return "<STR_LIT:+>"<EOL>
Return a + if we don't already have one, else return a .
f8505:m8
def render_pep440(pieces):
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += plus_or_dot(pieces)<EOL>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT><...
Build up version string, with post-release "local version identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty Exceptions: 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]
f8505:m9
def render_pep440_pre(pieces):
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT>return rendered<EOL>
TAG[.post.devDISTANCE] -- No -dirty. Exceptions: 1: no tags. 0.post.devDISTANCE
f8505:m10
def render_pep440_post(pieces):
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>rendered += plus_or_dot(pieces)<EOL>rendered += "<STR_LIT>" % pieces...
TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that .dev0 sorts backwards (a dirty tree will appear "older" than the corresponding clean one), but you shouldn't be releasing software with -dirty anyways. Exceptions: 1: no tags. 0.postDISTANCE[.dev0]
f8505:m11
def render_pep440_old(pieces):
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<...
TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. Eexceptions: 1: no tags. 0.postDISTANCE[.dev0]
f8505:m12
def render_git_describe(pieces):
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL><DEDENT>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL...
TAG[-DISTANCE-gHEX][-dirty]. Like 'git describe --tags --dirty --always'. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix)
f8505:m13
def render_git_describe_long(pieces):
if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL><DEDENT>else:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL><DEDENT>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>return rendered<EOL>
TAG-DISTANCE-gHEX[-dirty]. Like 'git describe --tags --dirty --always -long'. The distance/hash is unconditional. Exceptions: 1: no tags. HEX[-dirty] (note: no 'g' prefix)
f8505:m14
def render(pieces, style):
if pieces["<STR_LIT:error>"]:<EOL><INDENT>return {"<STR_LIT:version>": "<STR_LIT>",<EOL>"<STR_LIT>": pieces.get("<STR_LIT>"),<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT:error>": pieces["<STR_LIT:error>"],<EOL>"<STR_LIT:date>": None}<EOL><DEDENT>if not style or style == "<STR_LIT:default>":<EOL><INDENT>style = "<STR_LIT>" <E...
Render the given version pieces into the requested style.
f8505:m15
def get_versions():
<EOL>cfg = get_config()<EOL>verbose = cfg.verbose<EOL>try:<EOL><INDENT>return git_versions_from_keywords(get_keywords(), cfg.tag_prefix,<EOL>verbose)<EOL><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>root = os.path.realpath(__file__)<EOL>for i in cfg.versionfile_source.split('<STR_LIT:/>')...
Get version information or return default if unable to do so.
f8505:m16
def get_upper_air_data(date, station):
sounding_key = '<STR_LIT>'.format(date, station)<EOL>sounding_files = {'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>'}<EOL>fname = sounding_files[sounding_key]<EOL>fobj = get_test_data(fname)<EOL>def to_float(s):<EOL><INDE...
Get upper air observations from the test data cache. Parameters ---------- time : datetime The date and time of the desired observation. station : str The three letter ICAO identifier of the station for which data should be downloaded. Returns ------- dict :...
f8506:m0
def check_and_drop_units(actual, desired):
try:<EOL><INDENT>if hasattr(desired, '<STR_LIT>'):<EOL><INDENT>if not hasattr(actual, '<STR_LIT>'):<EOL><INDENT>actual = units.Quantity(actual, '<STR_LIT>')<EOL><DEDENT>actual = actual.to(desired.units)<EOL><DEDENT>else:<EOL><INDENT>if hasattr(actual, '<STR_LIT>'):<EOL><INDENT>actual = actual.to('<STR_LIT>')<EOL><DEDEN...
r"""Check that the units on the passed in arrays are compatible; return the magnitudes. Parameters ---------- actual : `pint.Quantity` or array-like desired : `pint.Quantity` or array-like Returns ------- actual, desired array-like versions of `actual` and `desired` once they have...
f8506:m1
def assert_nan(value, units):
if not np.isnan(value):<EOL><INDENT>pytest.fail('<STR_LIT>'.format(value))<EOL><DEDENT>check_and_drop_units(value, np.nan * units)<EOL>return True<EOL>
Check for nan with proper units.
f8506:m2
def assert_almost_equal(actual, desired, decimal=<NUM_LIT:7>):
actual, desired = check_and_drop_units(actual, desired)<EOL>numpy.testing.assert_almost_equal(actual, desired, decimal)<EOL>
Check that values are almost equal, including units. Wrapper around :func:`numpy.testing.assert_almost_equal`
f8506:m3
def assert_array_almost_equal(actual, desired, decimal=<NUM_LIT:7>):
actual, desired = check_and_drop_units(actual, desired)<EOL>numpy.testing.assert_array_almost_equal(actual, desired, decimal)<EOL>
Check that arrays are almost equal, including units. Wrapper around :func:`numpy.testing.assert_array_almost_equal`
f8506:m4
def assert_array_equal(actual, desired):
actual, desired = check_and_drop_units(actual, desired)<EOL>numpy.testing.assert_array_equal(actual, desired)<EOL>
Check that arrays are equal, including units. Wrapper around :func:`numpy.testing.assert_array_equal`
f8506:m5
def assert_xarray_allclose(actual, desired):
xr.testing.assert_allclose(actual, desired)<EOL>assert desired.metpy.coordinates_identical(actual)<EOL>assert desired.attrs == actual.attrs<EOL>
Check that the xarrays are almost equal, including coordinates and attributes.
f8506:m6
def ignore_deprecation(func):
@functools.wraps(func)<EOL>def wrapper(*args, **kwargs):<EOL><INDENT>with pytest.warns(MetpyDeprecationWarning):<EOL><INDENT>return func(*args, **kwargs)<EOL><DEDENT><DEDENT>return wrapper<EOL>
Decorate a function to swallow metpy deprecation warnings, making sure they are present. This should be used on deprecation function tests to make sure the deprecation warnings are not failing the tests, but still allow testing of those functions.
f8506:m9
def pandas_dataframe_to_unit_arrays(df, column_units=None):
if not column_units:<EOL><INDENT>try:<EOL><INDENT>column_units = df.units<EOL><DEDENT>except AttributeError:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT><DEDENT>res = {}<EOL>for column in df:<EOL><INDENT>if column in column_units and column_units[column]:<EOL><INDENT>res[column] = df[column].v...
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. Overrides the units attribute if it is attached to the data...
f8507:m0
def concatenate(arrs, axis=<NUM_LIT:0>):
dest = '<STR_LIT>'<EOL>for a in arrs:<EOL><INDENT>if hasattr(a, '<STR_LIT>'):<EOL><INDENT>dest = a.units<EOL>break<EOL><DEDENT><DEDENT>data = []<EOL>for a in arrs:<EOL><INDENT>if hasattr(a, '<STR_LIT:to>'):<EOL><INDENT>a = a.to(dest).magnitude<EOL><DEDENT>data.append(np.atleast_1d(a))<EOL><DEDENT>data = np.ma.concatena...
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 conversion. The first units found in ...
f8507:m1
def diff(x, **kwargs):
ret = np.diff(x, **kwargs)<EOL>if hasattr(x, '<STR_LIT>'):<EOL><INDENT>it = x.flat<EOL>true_units = (next(it) - next(it)).units<EOL>ret = ret * true_units<EOL><DEDENT>return ret<EOL>
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 along which the difference is t...
f8507:m2
def atleast_1d(*arrs):
mags = [a.magnitude if hasattr(a, '<STR_LIT>') else a for a in arrs]<EOL>orig_units = [a.units if hasattr(a, '<STR_LIT>') else None for a in arrs]<EOL>ret = np.atleast_1d(*mags)<EOL>if len(mags) == <NUM_LIT:1>:<EOL><INDENT>if orig_units[<NUM_LIT:0>] is not None:<EOL><INDENT>return units.Quantity(ret, orig_units[<NUM_LI...
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 positional arguments ...
f8507:m3
def atleast_2d(*arrs):
mags = [a.magnitude if hasattr(a, '<STR_LIT>') else a for a in arrs]<EOL>orig_units = [a.units if hasattr(a, '<STR_LIT>') else None for a in arrs]<EOL>ret = np.atleast_2d(*mags)<EOL>if len(mags) == <NUM_LIT:1>:<EOL><INDENT>if orig_units[<NUM_LIT:0>] is not None:<EOL><INDENT>return units.Quantity(ret, orig_units[<NUM_LI...
r"""Convert inputs to arrays with at least two dimensions. Scalars and 1-dimensional arrays are converted to 2-dimensional arrays, whilst other higher-dimensional inputs are preserved. This is a thin wrapper around `numpy.atleast_2d` to preserve units. Parameters ---------- arrs : arbitrary po...
f8507:m4
def masked_array(data, data_units=None, **kwargs):
if data_units is None:<EOL><INDENT>data_units = data.units<EOL><DEDENT>return units.Quantity(np.ma.masked_array(data, **kwargs), data_units)<EOL>
Create a :class:`numpy.ma.MaskedArray` with units attached. This is a thin wrapper around :func:`numpy.ma.masked_array` that ensures that units are properly attached to the result (otherwise units are silently lost). Units are taken from the ``units`` argument, or if this is ``None``, the units on ``data``...
f8507:m5
def _check_argument_units(args, dimensionality):
for arg, val in args.items():<EOL><INDENT>try:<EOL><INDENT>need, parsed = dimensionality[arg]<EOL><DEDENT>except KeyError:<EOL><INDENT>continue<EOL><DEDENT>try:<EOL><INDENT>if val.dimensionality != parsed:<EOL><INDENT>yield arg, val.units, need<EOL><DEDENT><DEDENT>except AttributeError:<EOL><INDENT>if parsed != '<STR_L...
Yield arguments with improper dimensionality.
f8507:m6
def check_units(*units_by_pos, **units_by_name):
try:<EOL><INDENT>from inspect import signature<EOL>def dec(func):<EOL><INDENT>sig = signature(func)<EOL>bound_units = sig.bind_partial(*units_by_pos, **units_by_name)<EOL>dims = {name: (orig, units.get_dimensionality(orig.replace('<STR_LIT>', '<STR_LIT>')))<EOL>for name, orig in bound_units.arguments.items()}<EOL>@func...
Create a decorator to check units of function arguments.
f8507:m7
def is_string_like(s):
return isinstance(s, string_type)<EOL>
Check if an object is a string.
f8509:m0
def broadcast_indices(x, minv, ndim, axis):
ret = []<EOL>for dim in range(ndim):<EOL><INDENT>if dim == axis:<EOL><INDENT>ret.append(minv)<EOL><DEDENT>else:<EOL><INDENT>broadcast_slice = [np.newaxis] * ndim<EOL>broadcast_slice[dim] = slice(None)<EOL>dim_inds = np.arange(x.shape[dim])<EOL>ret.append(dim_inds[tuple(broadcast_slice)])<EOL><DEDENT><DEDENT>return tupl...
Calculate index values to properly broadcast index array within data array. See usage in interp.
f8509:m2
def __init__(self):
self._registry = {}<EOL>
Initialize an empty registry.
f8509:c0:m0
def register(self, name):
def dec(func):<EOL><INDENT>self._registry[name] = func<EOL>return func<EOL><DEDENT>return dec<EOL>
Register a callable with the registry under a particular name. Parameters ---------- name : str The name under which to register a function Returns ------- dec : callable A decorator that takes a function and will register it under the name.
f8509:c0:m1
def __getitem__(self, name):
return self._registry[name]<EOL>
Return any callable registered under name.
f8509:c0:m2
def __init__(self, globls):
self.globls = globls<EOL>self.exports = globls.setdefault('<STR_LIT>', [])<EOL>
Initialize the Exporter.
f8510:c0:m0
def export(self, defn):
self.exports.append(defn.__name__)<EOL>return defn<EOL>
Declare a function or class as exported.
f8510:c0:m1
def __enter__(self):
self.start_vars = set(self.globls)<EOL>
Start a block tracking all instances created at global scope.
f8510:c0:m2
def __exit__(self, exc_type, exc_val, exc_tb):
self.exports.extend(set(self.globls) - self.start_vars)<EOL>del self.start_vars<EOL>
Exit the instance tracking block.
f8510:c0:m3
def add_timestamp(ax, time=None, x=<NUM_LIT>, y=-<NUM_LIT>, ha='<STR_LIT:right>', high_contrast=False,<EOL>pretext='<STR_LIT>', time_format='<STR_LIT>', **kwargs):
if high_contrast:<EOL><INDENT>text_args = {'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>':<EOL>[mpatheffects.withStroke(linewidth=<NUM_LIT:2>, foreground='<STR_LIT>')]}<EOL><DEDENT>else:<EOL><INDENT>text_args = {}<EOL><DEDENT>text_args.update(**kwargs)<EOL>if not time:<EOL><INDENT>time = datetime.utcnow()<EOL><DEDENT>timest...
Add a timestamp to a plot. Adds a timestamp to a plot, defaulting to the time of plot creation in ISO format. Parameters ---------- ax : `matplotlib.axes.Axes` The `Axes` instance used for plotting time : `datetime.datetime` Specific time to be plotted - datetime.utcnow will be use...
f8511:m0
def _add_logo(fig, x=<NUM_LIT:10>, y=<NUM_LIT>, zorder=<NUM_LIT:100>, which='<STR_LIT>', size='<STR_LIT>', **kwargs):
fname_suffix = {'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>'}<EOL>fname_prefix = {'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>'}<EOL>try:<EOL><INDENT>fname = fname_prefix[which] + fname_suffix[size]<EOL>fpath = posixpath.join('<STR_LIT>', fname)<EOL><DEDENT>except KeyError:<EOL><INDENT>raise ValueErr...
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 pixels y : float y position padding in pixels zorder : int The zorder of...
f8511:m1
def add_metpy_logo(fig, x=<NUM_LIT:10>, y=<NUM_LIT>, zorder=<NUM_LIT:100>, size='<STR_LIT>', **kwargs):
return _add_logo(fig, x=x, y=y, zorder=zorder, which='<STR_LIT>', size=size, **kwargs)<EOL>
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 y : float y position padding in pixels zorder : int The zo...
f8511:m2
def add_unidata_logo(fig, x=<NUM_LIT:10>, y=<NUM_LIT>, zorder=<NUM_LIT:100>, size='<STR_LIT>', **kwargs):
return _add_logo(fig, x=x, y=y, zorder=zorder, which='<STR_LIT>', size=size, **kwargs)<EOL>
Add the Unidata 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 y : float y position padding in pixels zorder : int The ...
f8511:m3
def colored_line(x, y, c, **kwargs):
<EOL>nan_mask = ~(np.isnan(x) | np.isnan(y) | np.isnan(c))<EOL>x = x[nan_mask]<EOL>y = y[nan_mask]<EOL>c = c[nan_mask]<EOL>points = concatenate([x, y])<EOL>num_pts = points.size // <NUM_LIT:2><EOL>final_shape = (num_pts - <NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:2>)<EOL>final_strides = (points.itemsize, points.itemsize, num_...
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 values used for color-mapping kwargs : dic...
f8511:m4
def convert_gempak_color(c, style='<STR_LIT>'):
def normalize(x):<EOL><INDENT>"""<STR_LIT>"""<EOL>x = int(x)<EOL>if x < <NUM_LIT:0> or x == <NUM_LIT>:<EOL><INDENT>x = <NUM_LIT:0><EOL><DEDENT>else:<EOL><INDENT>x = x % <NUM_LIT:32><EOL><DEDENT>return x<EOL><DEDENT>cols = ['<STR_LIT>', <EOL>'<STR_LIT>', <EOL>'<STR_LIT>', <EOL>'<STR_LIT>', <EOL...
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. Parameters ---------- c : int or sequence of i...
f8511:m5
def update_position(self, loc):
<EOL>self._loc = loc<EOL>super(SkewXTick, self).update_position(loc)<EOL>
Set the location of tick in data coords with scalar *loc*.
f8522:c0:m0
@property<EOL><INDENT>def gridOn(self): <DEDENT>
return (self._gridOn and (self._has_default_loc()<EOL>or transforms.interval_contains(self.get_view_interval(), self.get_loc())))<EOL>
Control whether the gridline is drawn for this tick.
f8522:c0:m4
@property<EOL><INDENT>def tick1On(self): <DEDENT>
return self._tick1On and self._need_lower()<EOL>
Control whether the lower tick mark is drawn for this tick.
f8522:c0:m6
@property<EOL><INDENT>def label1On(self): <DEDENT>
return self._label1On and self._need_lower()<EOL>
Control whether the lower tick label is drawn for this tick.
f8522:c0:m8
@property<EOL><INDENT>def tick2On(self): <DEDENT>
return self._tick2On and self._need_upper()<EOL>
Control whether the upper tick mark is drawn for this tick.
f8522:c0:m10
@property<EOL><INDENT>def label2On(self): <DEDENT>
return self._label2On and self._need_upper()<EOL>
Control whether the upper tick label is drawn for this tick.
f8522:c0:m12
def get_view_interval(self):
return self.axes.xaxis.get_view_interval()<EOL>
Get the view interval.
f8522:c0:m14
def get_view_interval(self):
return self.axes.upper_xlim[<NUM_LIT:0>], self.axes.lower_xlim[<NUM_LIT:1>]<EOL>
Get the view interval.
f8522:c1:m1
def __init__(self, *args, **kwargs):
<EOL>self.rot = kwargs.pop('<STR_LIT>', <NUM_LIT:30>)<EOL>Axes.__init__(self, *args, **kwargs)<EOL>
r"""Initialize `SkewXAxes`. Parameters ---------- args : Arbitrary positional arguments Passed to :class:`matplotlib.axes.Axes` position: int, optional The rotation of the x-axis against the y-axis, in degrees. kwargs : Arbitrary keyword arguments ...
f8522:c3:m0
def _set_lim_and_transforms(self):
<EOL>Axes._set_lim_and_transforms(self)<EOL>self.transDataToAxes = (self.transScale<EOL>+ (self.transLimits<EOL>+ transforms.Affine2D().skew_deg(self.rot, <NUM_LIT:0>)))<EOL>self.transData = self.transDataToAxes + self.transAxes<EOL>self._xaxis_transform = (<EOL>transforms.blended_transform_factory(self.transScale + se...
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.
f8522:c3:m3
@property<EOL><INDENT>def lower_xlim(self):<DEDENT>
return self.axes.viewLim.intervalx<EOL>
Get the data limits for the x-axis along the bottom of the axes.
f8522:c3:m4
@property<EOL><INDENT>def upper_xlim(self):<DEDENT>
return self.transDataToAxes.inverted().transform([[<NUM_LIT:0.>, <NUM_LIT:1.>], [<NUM_LIT:1.>, <NUM_LIT:1.>]])[:, <NUM_LIT:0>]<EOL>
Get the data limits for the x-axis along the top of the axes.
f8522:c3:m5
def __init__(self, fig=None, rotation=<NUM_LIT:30>, subplot=None, rect=None):
if fig is None:<EOL><INDENT>import matplotlib.pyplot as plt<EOL>figsize = plt.rcParams.get('<STR_LIT>', (<NUM_LIT:7>, <NUM_LIT:7>))<EOL>fig = plt.figure(figsize=figsize)<EOL><DEDENT>self._fig = fig<EOL>if rect and subplot:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>elif rect:<EOL><INDENT>self.ax = fig.add_ax...
r"""Create SkewT - logP plots. Parameters ---------- fig : matplotlib.figure.Figure, optional Source figure to use for plotting. If none is given, a new :class:`matplotlib.figure.Figure` instance will be created. rotation : float or int, optional Cont...
f8522:c4:m0
def plot(self, p, t, *args, **kwargs):
<EOL>t, p = _delete_masked_points(t, p)<EOL>lines = self.ax.semilogy(t, p, *args, **kwargs)<EOL>self.ax.yaxis.set_major_formatter(ScalarFormatter())<EOL>self.ax.yaxis.set_major_locator(MultipleLocator(<NUM_LIT:100>))<EOL>self.ax.yaxis.set_minor_formatter(NullFormatter())<EOL>if not self.ax.yaxis_inverted():<EOL><INDENT...
r"""Plot data. Simple wrapper around plot so that pressure is the first (independent) input. This is essentially a wrapper around `semilogy`. It also sets some appropriate ticking and plot ranges. Parameters ---------- p : array_like pressure values ...
f8522:c4:m1
def plot_barbs(self, p, u, v, c=None, xloc=<NUM_LIT:1.0>, x_clip_radius=<NUM_LIT:0.1>,<EOL>y_clip_radius=<NUM_LIT>, **kwargs):
<EOL>plotting_units = kwargs.pop('<STR_LIT>', None)<EOL>if plotting_units:<EOL><INDENT>if hasattr(u, '<STR_LIT>') and hasattr(v, '<STR_LIT>'):<EOL><INDENT>u = u.to(plotting_units)<EOL>v = v.to(plotting_units)<EOL><DEDENT>else:<EOL><INDENT>raise ValueError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT><DEDENT>x = np.empty_li...
r"""Plot wind barbs. Adds wind barbs to the skew-T plot. This is a wrapper around the `barbs` command that adds to appropriate transform to place the barbs in a vertical line, located as a function of pressure. Parameters ---------- p : array_like pressure v...
f8522:c4:m2
def plot_dry_adiabats(self, t0=None, p=None, **kwargs):
<EOL>if t0 is None:<EOL><INDENT>xmin, xmax = self.ax.get_xlim()<EOL>t0 = np.arange(xmin, xmax + <NUM_LIT:1>, <NUM_LIT:10>) * units.degC<EOL><DEDENT>if p is None:<EOL><INDENT>p = np.linspace(*self.ax.get_ylim()) * units.mbar<EOL><DEDENT>t = dry_lapse(p, t0[:, np.newaxis], <NUM_LIT> * units.mbar).to(units.degC)<EOL>lined...
r"""Plot dry adiabats. Adds dry adiabats (lines of constant potential temperature) to the plot. The default style of these lines is dashed red lines with an alpha value of 0.5. These can be overridden using keyword arguments. Parameters ---------- t0 : array_like, optio...
f8522:c4:m3
def plot_moist_adiabats(self, t0=None, p=None, **kwargs):
<EOL>if t0 is None:<EOL><INDENT>xmin, xmax = self.ax.get_xlim()<EOL>t0 = np.concatenate((np.arange(xmin, <NUM_LIT:0>, <NUM_LIT:10>),<EOL>np.arange(<NUM_LIT:0>, xmax + <NUM_LIT:1>, <NUM_LIT:5>))) * units.degC<EOL><DEDENT>if p is None:<EOL><INDENT>p = np.linspace(*self.ax.get_ylim()) * units.mbar<EOL><DEDENT>t = moist_la...
r"""Plot moist adiabats. Adds saturated pseudo-adiabats (lines of constant equivalent potential temperature) to the plot. The default style of these lines is dashed blue lines with an alpha value of 0.5. These can be overridden using keyword arguments. Parameters ------...
f8522:c4:m4
def plot_mixing_lines(self, w=None, p=None, **kwargs):
<EOL>if w is None:<EOL><INDENT>w = np.array([<NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>,<EOL><NUM_LIT>, <NUM_LIT>, <NUM_LIT>]).reshape(-<NUM_LIT:1>, <NUM_LIT:1>)<EOL><DEDENT>if p is None:<EOL><INDENT>p = np.linspace(<NUM_LIT>, max(self.ax.get_ylim())) * units.mbar<EOL><DEDENT>td = dewpoint(vapor_p...
r"""Plot lines of constant mixing ratio. Adds lines of constant mixing ratio (isohumes) to the plot. The default style of these lines is dashed green lines with an alpha value of 0.8. These can be overridden using keyword arguments. Parameters ---------- w : array_like,...
f8522:c4:m5
def shade_area(self, y, x1, x2=<NUM_LIT:0>, which='<STR_LIT>', **kwargs):
fill_properties = {'<STR_LIT>':<EOL>{'<STR_LIT>': '<STR_LIT>', '<STR_LIT>': <NUM_LIT>, '<STR_LIT>': x1 > x2},<EOL>'<STR_LIT>':<EOL>{'<STR_LIT>': '<STR_LIT>', '<STR_LIT>': <NUM_LIT>, '<STR_LIT>': x1 < x2},<EOL>'<STR_LIT>':<EOL>{'<STR_LIT>': '<STR_LIT>', '<STR_LIT>': <NUM_LIT>, '<STR_LIT>': None}}<EOL>try:<EOL><INDENT>fi...
r"""Shade area between two curves. Shades areas between curves. Area can be where one is greater or less than the other or all areas shaded. Parameters ---------- y : array_like 1-dimensional array of numeric y-values x1 : array_like 1-dimensiona...
f8522:c4:m6
def shade_cape(self, p, t, t_parcel, **kwargs):
return self.shade_area(p, t_parcel, t, which='<STR_LIT>', **kwargs)<EOL>
r"""Shade areas of CAPE. Shades areas where the parcel is warmer than the environment (areas of positive buoyancy. Parameters ---------- p : array_like Pressure values t : array_like Temperature values t_parcel : array_like Pa...
f8522:c4:m7
def shade_cin(self, p, t, t_parcel, **kwargs):
return self.shade_area(p, t_parcel, t, which='<STR_LIT>', **kwargs)<EOL>
r"""Shade areas of CIN. Shades areas where the parcel is cooler than the environment (areas of negative buoyancy. Parameters ---------- p : array_like Pressure values t : array_like Temperature values t_parcel : array_like Par...
f8522:c4:m8
def __init__(self, ax=None, component_range=<NUM_LIT>):
if ax is None:<EOL><INDENT>import matplotlib.pyplot as plt<EOL>self.ax = plt.figure().add_subplot(<NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>self.ax = ax<EOL><DEDENT>self.ax.set_aspect('<STR_LIT>', '<STR_LIT>')<EOL>self.ax.set_xlim(-component_range, component_range)<EOL>self.ax.set_ylim(-compo...
r"""Create a Hodograph instance. Parameters ---------- ax : `matplotlib.axes.Axes`, optional The `Axes` instance used for plotting component_range : value The maximum range of the plot. Used to set plot bounds and control the maximum number of grid ri...
f8522:c5:m0
def add_grid(self, increment=<NUM_LIT>, **kwargs):
<EOL>grid_args = {'<STR_LIT>': '<STR_LIT>', '<STR_LIT>': '<STR_LIT>'}<EOL>if kwargs:<EOL><INDENT>grid_args.update(kwargs)<EOL><DEDENT>circle_args = grid_args.copy()<EOL>color = circle_args.pop('<STR_LIT>', None)<EOL>circle_args['<STR_LIT>'] = color<EOL>circle_args['<STR_LIT>'] = False<EOL>self.rings = []<EOL>for r in n...
r"""Add grid lines to hodograph. Creates lines for the x- and y-axes, as well as circles denoting wind speed values. Parameters ---------- increment : value, optional The value increment between rings kwargs Other kwargs to control appearance of lines ...
f8522:c5:m1
@staticmethod<EOL><INDENT>def _form_line_args(kwargs):<DEDENT>
def_args = {'<STR_LIT>': <NUM_LIT:3>}<EOL>def_args.update(kwargs)<EOL>return def_args<EOL>
Simplify taking the default line style and extending with kwargs.
f8522:c5:m2
def plot(self, u, v, **kwargs):
line_args = self._form_line_args(kwargs)<EOL>u, v = _delete_masked_points(u, v)<EOL>return self.ax.plot(u, v, **line_args)<EOL>
r"""Plot u, v data. Plots the wind data on the hodograph. Parameters ---------- u : array_like u-component of wind v : array_like v-component of wind kwargs Other keyword arguments to pass to :meth:`matplotlib.axes.Axes.plot` ...
f8522:c5:m3
def wind_vectors(self, u, v, **kwargs):
quiver_args = {'<STR_LIT>': '<STR_LIT>', '<STR_LIT>': <NUM_LIT:1>}<EOL>quiver_args.update(**kwargs)<EOL>center_position = np.zeros_like(u)<EOL>return self.ax.quiver(center_position, center_position,<EOL>u, v, **quiver_args)<EOL>
r"""Plot u, v data as wind vectors. Plot the wind data as vectors for each level, beginning at the origin. Parameters ---------- u : array_like u-component of wind v : array_like v-component of wind kwargs Other keyword arguments to p...
f8522:c5:m4
def plot_colormapped(self, u, v, c, bounds=None, colors=None, **kwargs):
u, v, c = _delete_masked_points(u, v, c)<EOL>if colors:<EOL><INDENT>cmap = mcolors.ListedColormap(colors)<EOL>if bounds.dimensionality == {'<STR_LIT>': <NUM_LIT:1.0>}:<EOL><INDENT>interpolation_heights = [bound.m for bound in bounds if bound not in c]<EOL>interpolation_heights = np.array(interpolation_heights) * bounds...
r"""Plot u, v data, with line colored based on a third set of data. Plots the wind data on the hodograph, but with a colormapped line. Takes a third variable besides the winds and either a colormap to color it with or a series of bounds and colors to create a colormap and norm to control colorm...
f8522:c5:m5
def __init__(self, name, scale, **kwargs):
super(MetPyMapFeature, self).__init__('<STR_LIT>', name, scale, **kwargs)<EOL>
Create USCountiesFeature instance.
f8524:c0:m0
def geometries(self):
<EOL>fname = '<STR_LIT>'.format(self.name, self.scale)<EOL>for extension in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>get_test_data(fname + extension)<EOL><DEDENT>path = get_test_data(fname + '<STR_LIT>', as_file_obj=False)<EOL>return iter(tuple(shpreader.Reader(path).geometries()))<EOL>
Return an iterator of (shapely) geometries for this feature.
f8524:c0:m1