signature
stringlengths 8
3.44k
| body
stringlengths 0
1.41M
| docstring
stringlengths 1
122k
| id
stringlengths 5
17
|
|---|---|---|---|
def with_scale(self, new_scale):
|
return MetPyMapFeature(self.name, new_scale, **self.kwargs)<EOL>
|
Return a copy of the feature with a new scale.
Parameters
----------
new_scale
The new dataset scale, i.e. one of '500k', '5m', or '20m'.
Corresponding to 1:500,000, 1:5,000,000, and 1:20,000,000
respectively.
|
f8524:c0:m2
|
@property<EOL><INDENT>def panel(self):<DEDENT>
|
return self.panels[<NUM_LIT:0>]<EOL>
|
Provide simple access for a single panel.
|
f8525:c1:m0
|
@property<EOL><INDENT>def figure(self):<DEDENT>
|
if not hasattr(self, '<STR_LIT>'):<EOL><INDENT>self._fig = plt.figure(figsize=self.size)<EOL><DEDENT>return self._fig<EOL>
|
Provide access to the underlying figure object.
|
f8525:c1:m3
|
def refresh(self, _):
|
<EOL>self.draw()<EOL>self.figure.canvas.draw()<EOL>try:<EOL><INDENT>self.figure.canvas.flush_events()<EOL><DEDENT>except NotImplementedError:<EOL><INDENT>pass<EOL><DEDENT>
|
Refresh the rendering of all panels.
|
f8525:c1:m4
|
def draw(self):
|
for panel in self.panels:<EOL><INDENT>with panel.hold_trait_notifications():<EOL><INDENT>panel.draw()<EOL><DEDENT><DEDENT>
|
Draw the collection of panels.
|
f8525:c1:m5
|
def save(self, *args, **kwargs):
|
self.draw()<EOL>self.figure.savefig(*args, **kwargs)<EOL>
|
Save the constructed graphic as an image file.
|
f8525:c1:m6
|
def show(self):
|
self.draw()<EOL>self.figure.show()<EOL>
|
Show the constructed graphic on the screen.
|
f8525:c1:m7
|
@observe('<STR_LIT>')<EOL><INDENT>def _plots_changed(self, change):<DEDENT>
|
for plot in change.new:<EOL><INDENT>plot.parent = self<EOL>plot.observe(self.refresh, names=('<STR_LIT>'))<EOL><DEDENT>self._need_redraw = True<EOL>
|
Handle when our collection of plots changes.
|
f8525:c2:m0
|
@observe('<STR_LIT>')<EOL><INDENT>def _parent_changed(self, _):<DEDENT>
|
self.ax = None<EOL>
|
Handle when the parent is changed.
|
f8525:c2:m1
|
@property<EOL><INDENT>def _proj_obj(self):<DEDENT>
|
if is_string_like(self.projection):<EOL><INDENT>if self.projection == '<STR_LIT:data>':<EOL><INDENT>return self.plots[<NUM_LIT:0>].griddata.metpy.cartopy_crs<EOL><DEDENT>else:<EOL><INDENT>return _projections[self.projection]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return self.projection<EOL><DEDENT>
|
Return the projection as a Cartopy object.
Handles looking up a string for the projection, or if the projection
is set to ``'data'`` looks at the data for the projection.
|
f8525:c2:m2
|
@property<EOL><INDENT>def _layer_features(self):<DEDENT>
|
for item in self.layers:<EOL><INDENT>if is_string_like(item):<EOL><INDENT>item = item.upper()<EOL>try:<EOL><INDENT>scaler = cfeature.AdaptiveScaler('<STR_LIT>', (('<STR_LIT>', <NUM_LIT:50>), ('<STR_LIT>', <NUM_LIT:15>)))<EOL>feat = getattr(cfeature, item).with_scale(scaler)<EOL><DEDENT>except AttributeError:<EOL><INDENT>scaler = cfeature.AdaptiveScaler('<STR_LIT>', (('<STR_LIT>', <NUM_LIT:5>), ('<STR_LIT>', <NUM_LIT:1>)))<EOL>feat = getattr(cartopy_utils, item).with_scale(scaler)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>feat = item<EOL><DEDENT>yield feat<EOL><DEDENT>
|
Iterate over all map features and return as Cartopy objects.
Handle converting names of maps to auto-scaling map features.
|
f8525:c2:m3
|
@observe('<STR_LIT>')<EOL><INDENT>def _set_need_redraw(self, _):<DEDENT>
|
self._need_redraw = True<EOL>
|
Watch traits and set the need redraw flag as necessary.
|
f8525:c2:m4
|
@property<EOL><INDENT>def ax(self):<DEDENT>
|
<EOL>if getattr(self, '<STR_LIT>', None) is None:<EOL><INDENT>self._ax = self.parent.figure.add_subplot(*self.layout, projection=self._proj_obj)<EOL><DEDENT>return self._ax<EOL>
|
Get the :class:`matplotlib.axes.Axes` to draw on.
Creates a new instance if necessary.
|
f8525:c2:m5
|
@ax.setter<EOL><INDENT>def ax(self, val):<DEDENT>
|
if getattr(self, '<STR_LIT>', None) is not None:<EOL><INDENT>self._ax.cla()<EOL><DEDENT>self._ax = val<EOL>
|
Set the :class:`matplotlib.axes.Axes` to draw on.
Clears existing state as necessary.
|
f8525:c2:m6
|
def refresh(self, changed):
|
self._need_redraw = changed.new<EOL>
|
Refresh the drawing if necessary.
|
f8525:c2:m7
|
def draw(self):
|
<EOL>if self._need_redraw:<EOL><INDENT>for p in self.plots:<EOL><INDENT>with p.hold_trait_notifications():<EOL><INDENT>p.draw()<EOL><DEDENT><DEDENT>for feat in self._layer_features:<EOL><INDENT>self.ax.add_feature(feat)<EOL><DEDENT>if self.area == '<STR_LIT>':<EOL><INDENT>self.ax.set_global()<EOL><DEDENT>elif self.area is not None:<EOL><INDENT>if is_string_like(self.area):<EOL><INDENT>area = _areas[self.area]<EOL><DEDENT>else:<EOL><INDENT>area = self.area<EOL><DEDENT>self.ax.set_extent(area, ccrs.PlateCarree())<EOL><DEDENT>title = self.title or '<STR_LIT:U+002CU+0020>'.join(plot.name for plot in self.plots)<EOL>self.ax.set_title(title)<EOL>self._need_redraw = False<EOL><DEDENT>
|
Draw the panel.
|
f8525:c2:m8
|
@property<EOL><INDENT>def _cmap_obj(self):<DEDENT>
|
try:<EOL><INDENT>return ctables.registry.get_colortable(self.colormap)<EOL><DEDENT>except KeyError:<EOL><INDENT>return plt.get_cmap(self.colormap)<EOL><DEDENT>
|
Return the colormap object.
Handle convert the name of the colormap to an object from matplotlib or metpy.
|
f8525:c3:m0
|
@property<EOL><INDENT>def _norm_obj(self):<DEDENT>
|
return plt.Normalize(*self.image_range)<EOL>
|
Return the normalization object.
Converts the tuple image range to a matplotlib normalization instance.
|
f8525:c3:m1
|
def clear(self):
|
if getattr(self, '<STR_LIT>', None) is not None:<EOL><INDENT>self.clear_handle()<EOL>self._need_redraw = True<EOL><DEDENT>
|
Clear the plot.
Resets all internal state and sets need for redraw.
|
f8525:c3:m2
|
def clear_handle(self):
|
self.handle.remove()<EOL>self.handle = None<EOL>
|
Clear the handle to the plot instance.
|
f8525:c3:m3
|
@observe('<STR_LIT>')<EOL><INDENT>def _parent_changed(self, _):<DEDENT>
|
self.clear()<EOL>
|
Handle setting the parent object for the plot.
|
f8525:c3:m4
|
@observe('<STR_LIT>', '<STR_LIT>', '<STR_LIT:time>')<EOL><INDENT>def _update_data(self, _=None):<DEDENT>
|
self._griddata = None<EOL>self.clear()<EOL>
|
Handle updating the internal cache of data.
Responds to changes in various subsetting parameters.
|
f8525:c3:m5
|
@property<EOL><INDENT>def data(self):<DEDENT>
|
return self._data<EOL>
|
Access the current data subset.
|
f8525:c3:m6
|
@property<EOL><INDENT>def griddata(self):<DEDENT>
|
if getattr(self, '<STR_LIT>', None) is None:<EOL><INDENT>if self.field:<EOL><INDENT>data = self.data.metpy.parse_cf(self.field)<EOL><DEDENT>elif not hasattr(self.data.metpy, '<STR_LIT:x>'):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>data = self.data<EOL><DEDENT>subset = {'<STR_LIT>': '<STR_LIT>'}<EOL>if self.level is not None:<EOL><INDENT>subset[data.metpy.vertical.name] = self.level<EOL><DEDENT>if self.time is not None:<EOL><INDENT>subset[data.metpy.time.name] = self.time<EOL><DEDENT>self._griddata = data.metpy.sel(**subset).squeeze()<EOL><DEDENT>return self._griddata<EOL>
|
Return the internal cached data.
|
f8525:c3:m8
|
@property<EOL><INDENT>def plotdata(self):<DEDENT>
|
x = self.griddata.metpy.x<EOL>y = self.griddata.metpy.y<EOL>if '<STR_LIT>' in x.units:<EOL><INDENT>import numpy as np<EOL>x, y, _ = self.griddata.metpy.cartopy_crs.transform_points(ccrs.PlateCarree(),<EOL>*np.meshgrid(x, y)).T<EOL>x = x[:, <NUM_LIT:0>] % <NUM_LIT><EOL>y = y[<NUM_LIT:0>, :]<EOL><DEDENT>return x, y, self.griddata<EOL>
|
Return the data for plotting.
The data array, x coordinates, and y coordinates.
|
f8525:c3:m9
|
@property<EOL><INDENT>def name(self):<DEDENT>
|
ret = self.field<EOL>if self.level is not None:<EOL><INDENT>ret += '<STR_LIT>'.format(self.level)<EOL><DEDENT>return ret<EOL>
|
Generate a name for the plot.
|
f8525:c3:m10
|
def draw(self):
|
if self._need_redraw:<EOL><INDENT>if getattr(self, '<STR_LIT>', None) is None:<EOL><INDENT>self._build()<EOL><DEDENT>self._need_redraw = False<EOL><DEDENT>
|
Draw the plot.
|
f8525:c3:m11
|
@observe('<STR_LIT>', '<STR_LIT>')<EOL><INDENT>def _set_need_redraw(self, _):<DEDENT>
|
if hasattr(self, '<STR_LIT>'):<EOL><INDENT>self.handle.set_cmap(self._cmap_obj)<EOL>self.handle.set_norm(self._norm_obj)<EOL>self._need_redraw = True<EOL><DEDENT>
|
Handle changes to attributes that just need a simple redraw.
|
f8525:c4:m0
|
@property<EOL><INDENT>def plotdata(self):<DEDENT>
|
x = self.griddata.metpy.x<EOL>y = self.griddata.metpy.y<EOL>if '<STR_LIT>' in x.units:<EOL><INDENT>x = x.data<EOL>x[x > <NUM_LIT>] -= <NUM_LIT><EOL><DEDENT>return x, y, self.griddata<EOL>
|
Return the data for plotting.
The data array, x coordinates, and y coordinates.
|
f8525:c4:m1
|
def _build(self):
|
x, y, imdata = self.plotdata<EOL>extents = (x[<NUM_LIT:0>], x[-<NUM_LIT:1>], y.min(), y.max())<EOL>origin = '<STR_LIT>' if y[<NUM_LIT:0>] > y[-<NUM_LIT:1>] else '<STR_LIT>'<EOL>self.handle = self.parent.ax.imshow(imdata, extent=extents, origin=origin,<EOL>cmap=self._cmap_obj, norm=self._norm_obj,<EOL>transform=imdata.metpy.cartopy_crs)<EOL>
|
Build the plot by calling any plotting methods as necessary.
|
f8525:c4:m2
|
@observe('<STR_LIT>', '<STR_LIT>', '<STR_LIT>')<EOL><INDENT>def _set_need_rebuild(self, _):<DEDENT>
|
<EOL>self.clear()<EOL>
|
Handle changes to attributes that need to regenerate everything.
|
f8525:c5:m0
|
def clear_handle(self):
|
for col in self.handle.collections:<EOL><INDENT>col.remove()<EOL><DEDENT>self.handle = None<EOL>
|
Clear the handle to the plot instance.
|
f8525:c5:m1
|
def _build(self):
|
x, y, imdata = self.plotdata<EOL>self.handle = self.parent.ax.contour(x, y, imdata, self.contours,<EOL>colors=self.linecolor, linewidths=self.linewidth,<EOL>transform=imdata.metpy.cartopy_crs)<EOL>
|
Build the plot by calling any plotting methods as necessary.
|
f8525:c5:m2
|
def __init__(self, ax, x, y, fontsize=<NUM_LIT:10>, spacing=None, transform=None, **kwargs):
|
self.ax = ax<EOL>self.x = x<EOL>self.y = y<EOL>self.fontsize = fontsize<EOL>self.spacing = fontsize if spacing is None else spacing<EOL>self.transform = transform<EOL>self.items = {}<EOL>self.barbs = None<EOL>self.default_kwargs = kwargs<EOL>
|
Initialize the StationPlot with items that do not change.
This sets up the axes and station locations. The `fontsize` and `spacing`
are also specified here to ensure that they are consistent between individual
station elements.
Parameters
----------
ax : matplotlib.axes.Axes
The :class:`~matplotlib.axes.Axes` for plotting
x : array_like
The x location of the stations in the plot
y : array_like
The y location of the stations in the plot
fontsize : int
The fontsize to use for drawing text
spacing : int
The spacing, in points, that corresponds to a single increment between
station plot elements.
transform : matplotlib.transforms.Transform (or compatible)
The default transform to apply to the x and y positions when plotting.
kwargs
Additional keyword arguments to use for matplotlib's plotting functions.
These will be passed to all the plotting methods, and thus need to be valid
for all plot types, such as `clip_on`.
|
f8526:c0:m0
|
def plot_symbol(self, location, codes, symbol_mapper, **kwargs):
|
<EOL>kwargs['<STR_LIT>'] = wx_symbol_font.copy()<EOL>return self.plot_parameter(location, codes, symbol_mapper, **kwargs)<EOL>
|
At the specified location in the station model plot a set of symbols.
This specifies that at the offset `location`, the data in `codes` should be
converted to unicode characters (for our :data:`wx_symbol_font`) using `symbol_mapper`,
and plotted.
Additional keyword arguments given will be passed onto the actual plotting
code; this is useful for specifying things like color or font properties.
If something has already been plotted at this location, it will be replaced.
Parameters
----------
location : str or tuple[float, float]
The offset (relative to center) to plot this parameter. If str, should be one of
'C', 'N', 'NE', 'E', 'SE', 'S', 'SW', 'W', or 'NW'. Otherwise, should be a tuple
specifying the number of increments in the x and y directions; increments
are multiplied by `spacing` to give offsets in x and y relative to the center.
codes : array_like
The numeric values that should be converted to unicode characters for plotting.
symbol_mapper : callable
Controls converting data values to unicode code points for the
:data:`wx_symbol_font` font. This should take a value and return a single unicode
character. See :mod:`metpy.plots.wx_symbols` for included mappers.
kwargs
Additional keyword arguments to use for matplotlib's plotting functions.
.. plot::
import matplotlib.pyplot as plt
import numpy as np
from math import ceil
from metpy.plots import StationPlot
from metpy.plots.wx_symbols import current_weather, current_weather_auto
from metpy.plots.wx_symbols import low_clouds, mid_clouds, high_clouds
from metpy.plots.wx_symbols import sky_cover, pressure_tendency
def plot_symbols(mapper, name, nwrap=12, figsize=(10, 1.4)):
# Determine how many symbols there are and layout in rows of nwrap
# if there are more than nwrap symbols
num_symbols = len(mapper)
codes = np.arange(len(mapper))
ncols = nwrap
if num_symbols <= nwrap:
nrows = 1
x = np.linspace(0, 1, len(mapper))
y = np.ones_like(x)
ax_height = 0.8
else:
nrows = int(ceil(num_symbols / ncols))
x = np.tile(np.linspace(0, 1, ncols), nrows)[:num_symbols]
y = np.repeat(np.arange(nrows, 0, -1), ncols)[:num_symbols]
figsize = (10, 1 * nrows + 0.4)
ax_height = 0.8 + 0.018 * nrows
fig = plt.figure(figsize=figsize, dpi=300)
ax = fig.add_axes([0, 0, 1, ax_height])
ax.set_title(name, size=20)
ax.xaxis.set_ticks([])
ax.yaxis.set_ticks([])
ax.set_frame_on(False)
# Plot
sp = StationPlot(ax, x, y, fontsize=36)
sp.plot_symbol('C', codes, mapper)
sp.plot_parameter((0, -1), codes, fontsize=18)
ax.set_ylim(-0.05, nrows + 0.5)
plt.show()
plot_symbols(current_weather, "Current Weather Symbols")
plot_symbols(current_weather_auto, "Current Weather Auto Reported Symbols")
plot_symbols(low_clouds, "Low Cloud Symbols")
plot_symbols(mid_clouds, "Mid Cloud Symbols")
plot_symbols(high_clouds, "High Cloud Symbols")
plot_symbols(sky_cover, "Sky Cover Symbols")
plot_symbols(pressure_tendency, "Pressure Tendency Symbols")
See Also
--------
plot_barb, plot_parameter, plot_text
|
f8526:c0:m1
|
def plot_parameter(self, location, parameter, formatter='<STR_LIT>', **kwargs):
|
text = self._to_string_list(parameter, formatter)<EOL>return self.plot_text(location, text, **kwargs)<EOL>
|
At the specified location in the station model plot a set of values.
This specifies that at the offset `location`, the data in `parameter` should be
plotted. The conversion of the data values to a string is controlled by `formatter`.
Additional keyword arguments given will be passed onto the actual plotting
code; this is useful for specifying things like color or font properties.
If something has already been plotted at this location, it will be replaced.
Parameters
----------
location : str or tuple[float, float]
The offset (relative to center) to plot this parameter. If str, should be one of
'C', 'N', 'NE', 'E', 'SE', 'S', 'SW', 'W', or 'NW'. Otherwise, should be a tuple
specifying the number of increments in the x and y directions; increments
are multiplied by `spacing` to give offsets in x and y relative to the center.
parameter : array_like
The numeric values that should be plotted
formatter : str or callable, optional
How to format the data as a string for plotting. If a string, it should be
compatible with the :func:`format` builtin. If a callable, this should take a
value and return a string. Defaults to '0.f'.
kwargs
Additional keyword arguments to use for matplotlib's plotting functions.
See Also
--------
plot_barb, plot_symbol, plot_text
|
f8526:c0:m2
|
def plot_text(self, location, text, **kwargs):
|
location = self._handle_location(location)<EOL>kwargs = self._make_kwargs(kwargs)<EOL>text_collection = self.ax.scattertext(self.x, self.y, text, loc=location,<EOL>size=kwargs.pop('<STR_LIT>', self.fontsize),<EOL>**kwargs)<EOL>if location in self.items:<EOL><INDENT>self.items[location].remove()<EOL><DEDENT>self.items[location] = text_collection<EOL>return text_collection<EOL>
|
At the specified location in the station model plot a collection of text.
This specifies that at the offset `location`, the strings in `text` should be
plotted.
Additional keyword arguments given will be passed onto the actual plotting
code; this is useful for specifying things like color or font properties.
If something has already been plotted at this location, it will be replaced.
Parameters
----------
location : str or tuple[float, float]
The offset (relative to center) to plot this parameter. If str, should be one of
'C', 'N', 'NE', 'E', 'SE', 'S', 'SW', 'W', or 'NW'. Otherwise, should be a tuple
specifying the number of increments in the x and y directions; increments
are multiplied by `spacing` to give offsets in x and y relative to the center.
text : list (or array) of strings
The strings that should be plotted
kwargs
Additional keyword arguments to use for matplotlib's plotting functions.
See Also
--------
plot_barb, plot_parameter, plot_symbol
|
f8526:c0:m3
|
def plot_barb(self, u, v, **kwargs):
|
kwargs = self._make_kwargs(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>u = np.array(u)<EOL>v = np.array(v)<EOL>pivot = <NUM_LIT> * np.sqrt(self.fontsize)<EOL>length = <NUM_LIT> * np.sqrt(self.fontsize)<EOL>defaults = {'<STR_LIT>': {'<STR_LIT>': <NUM_LIT>, '<STR_LIT>': <NUM_LIT:0.5>, '<STR_LIT>': <NUM_LIT>},<EOL>'<STR_LIT>': length, '<STR_LIT>': pivot}<EOL>defaults.update(kwargs)<EOL>if self.barbs:<EOL><INDENT>self.barbs.remove()<EOL><DEDENT>if hasattr(self.ax, '<STR_LIT>') and '<STR_LIT>' in kwargs:<EOL><INDENT>trans = kwargs['<STR_LIT>']<EOL>try:<EOL><INDENT>kwargs['<STR_LIT>'] = trans._as_mpl_transform(self.ax)<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT>u, v = self.ax.projection.transform_vectors(trans, self.x, self.y, u, v)<EOL>self.barbs = matplotlib.axes.Axes.barbs(self.ax, self.x, self.y, u, v, **defaults)<EOL><DEDENT>else:<EOL><INDENT>self.barbs = self.ax.barbs(self.x, self.y, u, v, **defaults)<EOL><DEDENT>
|
r"""At the center of the station model plot wind barbs.
Additional keyword arguments given will be passed onto matplotlib's
:meth:`~matplotlib.axes.Axes.barbs` function; this is useful for specifying things
like color or line width.
Parameters
----------
u : array-like
The data to use for the u-component of the barbs.
v : array-like
The data to use for the v-component of the barbs.
plot_units: `pint.unit`
Units to plot in (performing conversion if necessary). Defaults to given units.
kwargs
Additional keyword arguments to pass to matplotlib's
:meth:`~matplotlib.axes.Axes.barbs` function.
See Also
--------
plot_parameter, plot_symbol, plot_text
|
f8526:c0:m4
|
def _make_kwargs(self, kwargs):
|
<EOL>all_kw = self.default_kwargs.copy()<EOL>all_kw.update(kwargs)<EOL>if '<STR_LIT>' not in all_kw and self.transform:<EOL><INDENT>all_kw['<STR_LIT>'] = self.transform<EOL><DEDENT>return all_kw<EOL>
|
Assemble kwargs as necessary.
Inserts our defaults as well as ensures transform is present when appropriate.
|
f8526:c0:m5
|
@staticmethod<EOL><INDENT>def _to_string_list(vals, fmt):<DEDENT>
|
if not callable(fmt):<EOL><INDENT>def formatter(s):<EOL><INDENT>"""<STR_LIT>"""<EOL>if hasattr(s, '<STR_LIT>'):<EOL><INDENT>s = s.item()<EOL><DEDENT>return format(s, fmt)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>formatter = fmt<EOL><DEDENT>return [formatter(v) if np.isfinite(v) else '<STR_LIT>' for v in vals]<EOL>
|
Convert a sequence of values to a list of strings.
|
f8526:c0:m6
|
def _handle_location(self, location):
|
if is_string_like(location):<EOL><INDENT>location = self.location_names[location]<EOL><DEDENT>xoff, yoff = location<EOL>return xoff * self.spacing, yoff * self.spacing<EOL>
|
Process locations to get a consistent set of tuples for location.
|
f8526:c0:m7
|
def add_value(self, location, name, fmt='<STR_LIT>', units=None, **kwargs):
|
self[location] = (self.PlotTypes.value, name, (fmt, units, kwargs))<EOL>
|
r"""Add a numeric value to the station layout.
This specifies that at the offset `location`, data should be pulled from the data
container using the key `name` and plotted. The conversion of the data values to
a string is controlled by `fmt`. The units required for plotting can also
be passed in using `units`, which will cause the data to be converted before
plotting.
Additional keyword arguments given will be passed onto the actual plotting
code; this is useful for specifying things like color or font properties.
Parameters
----------
location : str or tuple[float, float]
The offset (relative to center) to plot this value. If str, should be one of
'C', 'N', 'NE', 'E', 'SE', 'S', 'SW', 'W', or 'NW'. Otherwise, should be a tuple
specifying the number of increments in the x and y directions.
name : str
The name of the parameter, which is used as a key to pull data out of the
data container passed to :meth:`plot`.
fmt : str or callable, optional
How to format the data as a string for plotting. If a string, it should be
compatible with the :func:`format` builtin. If a callable, this should take a
value and return a string. Defaults to '0.f'.
units : pint-compatible unit, optional
The units to use for plotting. Data will be converted to this unit before
conversion to a string. If not specified, no conversion is done.
kwargs
Additional keyword arguments to use for matplotlib's plotting functions.
See Also
--------
add_barb, add_symbol, add_text
|
f8526:c1:m0
|
def add_symbol(self, location, name, symbol_mapper, **kwargs):
|
self[location] = (self.PlotTypes.symbol, name, (symbol_mapper, kwargs))<EOL>
|
r"""Add a symbol to the station layout.
This specifies that at the offset `location`, data should be pulled from the data
container using the key `name` and plotted. Data values will converted to glyphs
appropriate for MetPy's symbol font using the callable `symbol_mapper`.
Additional keyword arguments given will be passed onto the actual plotting
code; this is useful for specifying things like color or font properties.
Parameters
----------
location : str or tuple[float, float]
The offset (relative to center) to plot this value. If str, should be one of
'C', 'N', 'NE', 'E', 'SE', 'S', 'SW', 'W', or 'NW'. Otherwise, should be a tuple
specifying the number of increments in the x and y directions.
name : str
The name of the parameter, which is used as a key to pull data out of the
data container passed to :meth:`plot`.
symbol_mapper : callable
Controls converting data values to unicode code points for the
:data:`wx_symbol_font` font. This should take a value and return a single unicode
character. See :mod:`metpy.plots.wx_symbols` for included mappers.
kwargs
Additional keyword arguments to use for matplotlib's plotting functions.
See Also
--------
add_barb, add_text, add_value
|
f8526:c1:m1
|
def add_text(self, location, name, **kwargs):
|
self[location] = (self.PlotTypes.text, name, kwargs)<EOL>
|
r"""Add a text field to the station layout.
This specifies that at the offset `location`, data should be pulled from the data
container using the key `name` and plotted directly as text with no conversion
applied.
Additional keyword arguments given will be passed onto the actual plotting
code; this is useful for specifying things like color or font properties.
Parameters
----------
location : str or tuple(float, float)
The offset (relative to center) to plot this value. If str, should be one of
'C', 'N', 'NE', 'E', 'SE', 'S', 'SW', 'W', or 'NW'. Otherwise, should be a tuple
specifying the number of increments in the x and y directions.
name : str
The name of the parameter, which is used as a key to pull data out of the
data container passed to :meth:`plot`.
kwargs
Additional keyword arguments to use for matplotlib's plotting functions.
See Also
--------
add_barb, add_symbol, add_value
|
f8526:c1:m2
|
def add_barb(self, u_name, v_name, units=None, **kwargs):
|
<EOL>self['<STR_LIT>'] = (self.PlotTypes.barb, (u_name, v_name), (units, kwargs))<EOL>
|
r"""Add a wind barb to the center of the station layout.
This specifies that u- and v-component data should be pulled from the data
container using the keys `u_name` and `v_name`, respectively, and plotted as
a wind barb at the center of the station plot. If `units` are given, both
components will be converted to these units.
Additional keyword arguments given will be passed onto the actual plotting
code; this is useful for specifying things like color or line width.
Parameters
----------
u_name : str
The name of the parameter for the u-component for `barbs`, which is used as
a key to pull data out of the data container passed to :meth:`plot`.
v_name : str
The name of the parameter for the v-component for `barbs`, which is used as
a key to pull data out of the data container passed to :meth:`plot`.
units : pint-compatible unit, optional
The units to use for plotting. Data will be converted to this unit before
conversion to a string. If not specified, no conversion is done.
kwargs
Additional keyword arguments to use for matplotlib's
:meth:`~matplotlib.axes.Axes.barbs` function.
See Also
--------
add_symbol, add_text, add_value
|
f8526:c1:m3
|
def names(self):
|
ret = []<EOL>for item in self.values():<EOL><INDENT>if item[<NUM_LIT:0>] == self.PlotTypes.barb:<EOL><INDENT>ret.extend(item[<NUM_LIT:1>])<EOL><DEDENT>else:<EOL><INDENT>ret.append(item[<NUM_LIT:1>])<EOL><DEDENT><DEDENT>return ret<EOL>
|
Get the list of names used by the layout.
Returns
-------
list[str]
the list of names of variables used by the layout
|
f8526:c1:m4
|
def plot(self, plotter, data_dict):
|
def coerce_data(dat, u):<EOL><INDENT>try:<EOL><INDENT>return dat.to(u).magnitude<EOL><DEDENT>except AttributeError:<EOL><INDENT>return dat<EOL><DEDENT><DEDENT>for loc, info in self.items():<EOL><INDENT>typ, name, args = info<EOL>if typ == self.PlotTypes.barb:<EOL><INDENT>u_name, v_name = name<EOL>u_data = data_dict.get(u_name)<EOL>v_data = data_dict.get(v_name)<EOL>if not (v_data is None or u_data is None):<EOL><INDENT>units, kwargs = args<EOL>plotter.plot_barb(coerce_data(u_data, units), coerce_data(v_data, units),<EOL>**kwargs)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>data = data_dict.get(name)<EOL>if data is not None:<EOL><INDENT>if typ == self.PlotTypes.value:<EOL><INDENT>fmt, units, kwargs = args<EOL>plotter.plot_parameter(loc, coerce_data(data, units), fmt, **kwargs)<EOL><DEDENT>elif typ == self.PlotTypes.symbol:<EOL><INDENT>mapper, kwargs = args<EOL>plotter.plot_symbol(loc, data, mapper, **kwargs)<EOL><DEDENT>elif typ == self.PlotTypes.text:<EOL><INDENT>plotter.plot_text(loc, data, **args)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>
|
Plot a collection of data using this layout for a station plot.
This function iterates through the entire specified layout, pulling the fields named
in the layout from `data_dict` and plotting them using `plotter` as specified
in the layout. Fields present in the layout, but not in `data_dict`, are ignored.
Parameters
----------
plotter : StationPlot
:class:`StationPlot` to use to plot the data. This controls the axes,
spacing, station locations, etc.
data_dict : dict[str, array-like]
Data container that maps a name to an array of data. Data from this object
will be used to fill out the station plot.
|
f8526:c1:m5
|
def __repr__(self):
|
return ('<STR_LIT:{>'<EOL>+ '<STR_LIT:U+002CU+0020>'.join('<STR_LIT>'.format(loc, info)<EOL>for loc, info in sorted(self.items()))<EOL>+ '<STR_LIT:}>')<EOL>
|
Return string representation of layout.
|
f8526:c1:m6
|
def __init__(self, num, font_start, font_jumps=None, char_jumps=None):
|
next_font_jump = self._safe_pop(font_jumps)<EOL>next_char_jump = self._safe_pop(char_jumps)<EOL>font_point = font_start<EOL>self.chrs = []<EOL>code = <NUM_LIT:0><EOL>while code < num:<EOL><INDENT>if next_char_jump and code >= next_char_jump[<NUM_LIT:0>]:<EOL><INDENT>jump_len = next_char_jump[<NUM_LIT:1>]<EOL>code += jump_len<EOL>self.chrs.extend(['<STR_LIT>'] * jump_len)<EOL>next_char_jump = self._safe_pop(char_jumps)<EOL><DEDENT>else:<EOL><INDENT>self.chrs.append(code_point(font_point))<EOL>if next_font_jump and code >= next_font_jump[<NUM_LIT:0>]:<EOL><INDENT>font_point += next_font_jump[<NUM_LIT:1>]<EOL>next_font_jump = self._safe_pop(font_jumps)<EOL><DEDENT>code += <NUM_LIT:1><EOL>font_point += <NUM_LIT:1><EOL><DEDENT><DEDENT>
|
Initialize the instance.
Parameters
----------
num : int
The number of values that will be mapped
font_start : int
The first code point in the font to use in the mapping
font_jumps : list[int, int], optional
Sequence of code point jumps in the font. These are places where the next
font code point does not correspond to a new input code. This is usually caused
by there being multiple symbols for a single code. Defaults to :data:`None`, which
indicates no jumps.
char_jumps : list[int, int], optional
Sequence of code jumps. These are places where the next code value does not
have a valid code point in the font. This usually comes from place in the WMO
table where codes have no symbol. Defaults to :data:`None`, which indicates no
jumps.
|
f8527:c0:m0
|
@staticmethod<EOL><INDENT>def _safe_pop(l):<DEDENT>
|
return l.pop(<NUM_LIT:0>) if l else None<EOL>
|
Safely pop from a list.
Returns None if list empty.
|
f8527:c0:m1
|
def __call__(self, code):
|
return self.chrs[code]<EOL>
|
Return the Unicode code point corresponding to `code`.
|
f8527:c0:m2
|
def __len__(self):
|
return len(self.chrs)<EOL>
|
Return the number of codes supported by this mapping.
|
f8527:c0:m3
|
def alt_char(self, code, alt):
|
return code_point(ord(self(code)) + alt)<EOL>
|
Get one of the alternate code points for a given value.
In the WMO tables, some code have multiple symbols. This allows getting that
symbol rather than main one.
Parameters
----------
code : int
The code for looking up the font code point
alt : int
The number of the alternate symbol
Returns
-------
int
The appropriate code point in the font
|
f8527:c0:m4
|
@CFProjection.register('<STR_LIT>')<EOL>def make_geo(attrs_dict, globe):
|
attr_mapping = [('<STR_LIT>', '<STR_LIT>'),<EOL>('<STR_LIT>', '<STR_LIT>')]<EOL>kwargs = CFProjection.build_projection_kwargs(attrs_dict, attr_mapping)<EOL>if not kwargs.get('<STR_LIT>'):<EOL><INDENT>kwargs.pop('<STR_LIT>', None)<EOL><DEDENT>if '<STR_LIT>' not in kwargs:<EOL><INDENT>kwargs['<STR_LIT>'] = '<STR_LIT:x>' if attrs_dict['<STR_LIT>'] == '<STR_LIT:y>' else '<STR_LIT:y>'<EOL><DEDENT>return ccrs.Geostationary(globe=globe, **kwargs)<EOL>
|
Handle geostationary projection.
|
f8528:m0
|
@CFProjection.register('<STR_LIT>')<EOL>def make_lcc(attrs_dict, globe):
|
attr_mapping = [('<STR_LIT>', '<STR_LIT>'),<EOL>('<STR_LIT>', '<STR_LIT>')]<EOL>kwargs = CFProjection.build_projection_kwargs(attrs_dict, attr_mapping)<EOL>if '<STR_LIT>' in kwargs:<EOL><INDENT>try:<EOL><INDENT>len(kwargs['<STR_LIT>'])<EOL><DEDENT>except TypeError:<EOL><INDENT>kwargs['<STR_LIT>'] = [kwargs['<STR_LIT>']]<EOL><DEDENT><DEDENT>return ccrs.LambertConformal(globe=globe, **kwargs)<EOL>
|
Handle Lambert conformal conic projection.
|
f8528:m1
|
@CFProjection.register('<STR_LIT>')<EOL>def make_latlon(attrs_dict, globe):
|
<EOL>return ccrs.PlateCarree()<EOL>
|
Handle plain latitude/longitude mapping.
|
f8528:m2
|
@CFProjection.register('<STR_LIT>')<EOL>def make_mercator(attrs_dict, globe):
|
attr_mapping = [('<STR_LIT>', '<STR_LIT>'),<EOL>('<STR_LIT>', '<STR_LIT>')]<EOL>kwargs = CFProjection.build_projection_kwargs(attrs_dict, attr_mapping)<EOL>if not kwargs.get('<STR_LIT>'):<EOL><INDENT>kwargs.pop('<STR_LIT>', None)<EOL><DEDENT>if not kwargs.get('<STR_LIT>'):<EOL><INDENT>kwargs.pop('<STR_LIT>', None)<EOL><DEDENT>return ccrs.Mercator(globe=globe, **kwargs)<EOL>
|
Handle Mercator projection.
|
f8528:m3
|
@CFProjection.register('<STR_LIT>')<EOL>def make_stereo(attrs_dict, globe):
|
attr_mapping = [('<STR_LIT>', '<STR_LIT>')]<EOL>kwargs = CFProjection.build_projection_kwargs(attrs_dict, attr_mapping)<EOL>return ccrs.Stereographic(globe=globe, **kwargs)<EOL>
|
Handle generic stereographic projection.
|
f8528:m4
|
@CFProjection.register('<STR_LIT>')<EOL>def make_polar_stereo(attrs_dict, globe):
|
attr_mapping = [('<STR_LIT>', '<STR_LIT>'),<EOL>('<STR_LIT>', '<STR_LIT>'),<EOL>('<STR_LIT>', '<STR_LIT>')]<EOL>kwargs = CFProjection.build_projection_kwargs(attrs_dict, attr_mapping)<EOL>return ccrs.Stereographic(globe=globe, **kwargs)<EOL>
|
Handle polar stereographic projection.
|
f8528:m5
|
def __init__(self, attrs):
|
self._attrs = attrs<EOL>
|
Initialize the CF Projection handler with a set of metadata attributes.
|
f8528:c0:m0
|
@classmethod<EOL><INDENT>def register(cls, name):<DEDENT>
|
return cls.projection_registry.register(name)<EOL>
|
Register a new projection to handle.
|
f8528:c0:m1
|
@classmethod<EOL><INDENT>def build_projection_kwargs(cls, source, mapping):<DEDENT>
|
return cls._map_arg_names(source, cls._default_attr_mapping + mapping)<EOL>
|
Handle mapping a dictionary of metadata to keyword arguments.
|
f8528:c0:m2
|
@staticmethod<EOL><INDENT>def _map_arg_names(source, mapping):<DEDENT>
|
return {cartopy_name: source[cf_name] for cartopy_name, cf_name in mapping<EOL>if cf_name in source}<EOL>
|
Map one set of keys to another.
|
f8528:c0:m3
|
@property<EOL><INDENT>def cartopy_globe(self):<DEDENT>
|
if '<STR_LIT>' in self._attrs:<EOL><INDENT>kwargs = {'<STR_LIT>': '<STR_LIT>', '<STR_LIT>': self._attrs['<STR_LIT>'],<EOL>'<STR_LIT>': self._attrs['<STR_LIT>']}<EOL><DEDENT>else:<EOL><INDENT>attr_mapping = [('<STR_LIT>', '<STR_LIT>'),<EOL>('<STR_LIT>', '<STR_LIT>'),<EOL>('<STR_LIT>', '<STR_LIT>')]<EOL>kwargs = self._map_arg_names(self._attrs, attr_mapping)<EOL>kwargs['<STR_LIT>'] = None if kwargs else '<STR_LIT>'<EOL><DEDENT>return ccrs.Globe(**kwargs)<EOL>
|
Initialize a `cartopy.crs.Globe` from the metadata.
|
f8528:c0:m4
|
def to_cartopy(self):
|
globe = self.cartopy_globe<EOL>proj_name = self._attrs['<STR_LIT>']<EOL>try:<EOL><INDENT>proj_handler = self.projection_registry[proj_name]<EOL><DEDENT>except KeyError:<EOL><INDENT>raise ValueError('<STR_LIT>'.format(proj_name))<EOL><DEDENT>return proj_handler(self._attrs, globe)<EOL>
|
Convert to a CartoPy projection.
|
f8528:c0:m5
|
def to_dict(self):
|
return self._attrs.copy()<EOL>
|
Get the dictionary of metadata attributes.
|
f8528:c0:m6
|
def __str__(self):
|
return '<STR_LIT>' + self._attrs['<STR_LIT>']<EOL>
|
Get a string representation of the projection.
|
f8528:c0:m7
|
def __getitem__(self, item):
|
return self._attrs[item]<EOL>
|
Return a given attribute.
|
f8528:c0:m8
|
def __eq__(self, other):
|
return self.__class__ == other.__class__ and self.to_dict() == other.to_dict()<EOL>
|
Test equality (CFProjection with matching attrs).
|
f8528:c0:m9
|
def __ne__(self, other):
|
return not self.__eq__(other)<EOL>
|
Test inequality (not equal to).
|
f8528:c0:m10
|
@exporter.export<EOL>def read_colortable(fobj):
|
ret = []<EOL>try:<EOL><INDENT>for line in fobj:<EOL><INDENT>literal = _parse(line)<EOL>if literal:<EOL><INDENT>ret.append(mcolors.colorConverter.to_rgb(literal))<EOL><DEDENT><DEDENT>return ret<EOL><DEDENT>except (SyntaxError, ValueError):<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>
|
r"""Read colortable information from a file.
Reads a colortable, which consists of one color per line of the file, where
a color can be one of: a tuple of 3 floats, a string with a HTML color name,
or a string with a HTML hex color.
Parameters
----------
fobj : a file-like object
A file-like object to read the colors from
Returns
-------
List of tuples
A list of the RGB color values, where each RGB color is a tuple of 3 floats in the
range of [0, 1].
|
f8529:m1
|
def convert_gempak_table(infile, outfile):
|
for line in infile:<EOL><INDENT>if not line.startswith('<STR_LIT:!>') and line.strip():<EOL><INDENT>r, g, b = map(int, line.split())<EOL>outfile.write('<STR_LIT>'.format(r / <NUM_LIT:255>, g / <NUM_LIT:255>, b / <NUM_LIT:255>))<EOL><DEDENT><DEDENT>
|
r"""Convert a GEMPAK color table to one MetPy can read.
Reads lines from a GEMPAK-style color table file, and writes them to another file in
a format that MetPy can parse.
Parameters
----------
infile : file-like object
The file-like object to read from
outfile : file-like object
The file-like object to write to
|
f8529:m2
|
def scan_resource(self, pkg, path):
|
for fname in resource_listdir(pkg, path):<EOL><INDENT>if fname.endswith(TABLE_EXT):<EOL><INDENT>table_path = posixpath.join(path, fname)<EOL>with contextlib.closing(resource_stream(pkg, table_path)) as stream:<EOL><INDENT>self.add_colortable(stream,<EOL>posixpath.splitext(posixpath.basename(fname))[<NUM_LIT:0>])<EOL><DEDENT><DEDENT><DEDENT>
|
r"""Scan a resource directory for colortable files and add them to the registry.
Parameters
----------
pkg : str
The package containing the resource directory
path : str
The path to the directory with the color tables
|
f8529:c0:m0
|
def scan_dir(self, path):
|
for fname in glob.glob(os.path.join(path, '<STR_LIT:*>' + TABLE_EXT)):<EOL><INDENT>if os.path.isfile(fname):<EOL><INDENT>with open(fname, '<STR_LIT:r>') as fobj:<EOL><INDENT>try:<EOL><INDENT>self.add_colortable(fobj, os.path.splitext(os.path.basename(fname))[<NUM_LIT:0>])<EOL>log.debug('<STR_LIT>', fname)<EOL><DEDENT>except RuntimeError:<EOL><INDENT>log.info('<STR_LIT>', fname)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>
|
r"""Scan a directory on disk for color table files and add them to the registry.
Parameters
----------
path : str
The path to the directory with the color tables
|
f8529:c0:m1
|
def add_colortable(self, fobj, name):
|
self[name] = read_colortable(fobj)<EOL>self[name + '<STR_LIT>'] = self[name][::-<NUM_LIT:1>]<EOL>
|
r"""Add a color table from a file to the registry.
Parameters
----------
fobj : file-like object
The file to read the color table from
name : str
The name under which the color table will be stored
|
f8529:c0:m2
|
def get_with_steps(self, name, start, step):
|
from numpy import arange<EOL>num_steps = len(self[name]) + <NUM_LIT:1><EOL>boundaries = arange(start, start + step * num_steps, step)<EOL>return self.get_with_boundaries(name, boundaries)<EOL>
|
r"""Get a color table from the registry with a corresponding norm.
Builds a `matplotlib.colors.BoundaryNorm` using `start`, `step`, and
the number of colors, based on the color table obtained from `name`.
Parameters
----------
name : str
The name under which the color table will be stored
start : float
The starting boundary
step : float
The step between boundaries
Returns
-------
`matplotlib.colors.BoundaryNorm`, `matplotlib.colors.ListedColormap`
The boundary norm based on `start` and `step` with the number of colors
from the number of entries matching the color table, and the color table itself.
|
f8529:c0:m3
|
def get_with_range(self, name, start, end):
|
from numpy import linspace<EOL>num_steps = len(self[name]) + <NUM_LIT:1><EOL>boundaries = linspace(start, end, num_steps)<EOL>return self.get_with_boundaries(name, boundaries)<EOL>
|
r"""Get a color table from the registry with a corresponding norm.
Builds a `matplotlib.colors.BoundaryNorm` using `start`, `end`, and
the number of colors, based on the color table obtained from `name`.
Parameters
----------
name : str
The name under which the color table will be stored
start : float
The starting boundary
end : float
The ending boundary
Returns
-------
`matplotlib.colors.BoundaryNorm`, `matplotlib.colors.ListedColormap`
The boundary norm based on `start` and `end` with the number of colors
from the number of entries matching the color table, and the color table itself.
|
f8529:c0:m4
|
def get_with_boundaries(self, name, boundaries):
|
cmap = self.get_colortable(name)<EOL>return mcolors.BoundaryNorm(boundaries, cmap.N), cmap<EOL>
|
r"""Get a color table from the registry with a corresponding norm.
Builds a `matplotlib.colors.BoundaryNorm` using `boundaries`.
Parameters
----------
name : str
The name under which the color table will be stored
boundaries : array_like
The list of boundaries for the norm
Returns
-------
`matplotlib.colors.BoundaryNorm`, `matplotlib.colors.ListedColormap`
The boundary norm based on `boundaries`, and the color table itself.
|
f8529:c0:m5
|
def get_colortable(self, name):
|
return mcolors.ListedColormap(self[name], name=name)<EOL>
|
r"""Get a color table from the registry.
Parameters
----------
name : str
The name under which the color table will be stored
Returns
-------
`matplotlib.colors.ListedColormap`
The color table corresponding to `name`
|
f8529:c0:m6
|
def basic_map(proj):
|
fig = plt.figure(figsize=(<NUM_LIT:15>, <NUM_LIT:10>))<EOL>add_metpy_logo(fig, <NUM_LIT:0>, <NUM_LIT>, size='<STR_LIT>')<EOL>view = fig.add_axes([<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:1>], projection=proj)<EOL>view.set_extent([-<NUM_LIT>, -<NUM_LIT>, <NUM_LIT:20>, <NUM_LIT:50>])<EOL>view.add_feature(cfeature.STATES.with_scale('<STR_LIT>'))<EOL>view.add_feature(cfeature.OCEAN)<EOL>view.add_feature(cfeature.COASTLINE)<EOL>view.add_feature(cfeature.BORDERS, linestyle='<STR_LIT::>')<EOL>return fig, view<EOL>
|
Make our basic default map for plotting
|
f8539:m0
|
def draw_polygon_with_info(ax, polygon, off_x=<NUM_LIT:0>, off_y=<NUM_LIT:0>):
|
pts = np.array(polygon)[ConvexHull(polygon).vertices]<EOL>for i, pt in enumerate(pts):<EOL><INDENT>ax.plot([pt[<NUM_LIT:0>], pts[(i + <NUM_LIT:1>) % len(pts)][<NUM_LIT:0>]],<EOL>[pt[<NUM_LIT:1>], pts[(i + <NUM_LIT:1>) % len(pts)][<NUM_LIT:1>]], '<STR_LIT>')<EOL><DEDENT>avex, avey = np.mean(pts, axis=<NUM_LIT:0>)<EOL>ax.annotate('<STR_LIT>'.format(geometry.area(pts)), xy=(avex + off_x, avey + off_y),<EOL>fontsize=<NUM_LIT:12>)<EOL>
|
Draw one of the natural neighbor polygons with some information.
|
f8543:m1
|
def __init__(self, fig, dates, probeid, time=None, axis=<NUM_LIT:0>):
|
if not time:<EOL><INDENT>time = dt.datetime.utcnow()<EOL><DEDENT>self.start = dates[<NUM_LIT:0>]<EOL>self.fig = fig<EOL>self.end = dates[-<NUM_LIT:1>]<EOL>self.axis_num = <NUM_LIT:0><EOL>self.dates = mpl.dates.date2num(dates)<EOL>self.time = time.strftime('<STR_LIT>')<EOL>self.title = '<STR_LIT>'.format(self.time, probeid)<EOL>
|
Required input:
fig: figure object
dates: array of dates corresponding to the data
probeid: ID of the station
Optional Input:
time: Time the data is to be plotted
axis: number that controls the new axis to be plotted (FOR FUTURE)
|
f8548:c0:m0
|
def plot_winds(self, ws, wd, wsmax, plot_range=None):
|
<EOL>self.ax1 = fig.add_subplot(<NUM_LIT:4>, <NUM_LIT:1>, <NUM_LIT:1>)<EOL>ln1 = self.ax1.plot(self.dates, ws, label='<STR_LIT>')<EOL>self.ax1.fill_between(self.dates, ws, <NUM_LIT:0>)<EOL>self.ax1.set_xlim(self.start, self.end)<EOL>if not plot_range:<EOL><INDENT>plot_range = [<NUM_LIT:0>, <NUM_LIT:20>, <NUM_LIT:1>]<EOL><DEDENT>self.ax1.set_ylabel('<STR_LIT>', multialignment='<STR_LIT>')<EOL>self.ax1.set_ylim(plot_range[<NUM_LIT:0>], plot_range[<NUM_LIT:1>], plot_range[<NUM_LIT:2>])<EOL>self.ax1.grid(b=True, which='<STR_LIT>', axis='<STR_LIT:y>', color='<STR_LIT:k>', linestyle='<STR_LIT>',<EOL>linewidth=<NUM_LIT:0.5>)<EOL>ln2 = self.ax1.plot(self.dates, wsmax, '<STR_LIT>', label='<STR_LIT>')<EOL>ax7 = self.ax1.twinx()<EOL>ln3 = ax7.plot(self.dates, wd, '<STR_LIT>', linewidth=<NUM_LIT:0.5>, label='<STR_LIT>')<EOL>ax7.set_ylabel('<STR_LIT>', multialignment='<STR_LIT>')<EOL>ax7.set_ylim(<NUM_LIT:0>, <NUM_LIT>)<EOL>ax7.set_yticks(np.arange(<NUM_LIT>, <NUM_LIT>, <NUM_LIT>), ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'])<EOL>lns = ln1 + ln2 + ln3<EOL>labs = [l.get_label() for l in lns]<EOL>ax7.xaxis.set_major_formatter(mpl.dates.DateFormatter('<STR_LIT>'))<EOL>ax7.legend(lns, labs, loc='<STR_LIT>',<EOL>bbox_to_anchor=(<NUM_LIT:0.5>, <NUM_LIT>), ncol=<NUM_LIT:3>, prop={'<STR_LIT:size>': <NUM_LIT:12>})<EOL>
|
Required input:
ws: Wind speeds (knots)
wd: Wind direction (degrees)
wsmax: Wind gust (knots)
Optional Input:
plot_range: Data range for making figure (list of (min,max,step))
|
f8548:c0:m1
|
def plot_thermo(self, t, td, plot_range=None):
|
<EOL>if not plot_range:<EOL><INDENT>plot_range = [<NUM_LIT:10>, <NUM_LIT>, <NUM_LIT:2>]<EOL><DEDENT>self.ax2 = fig.add_subplot(<NUM_LIT:4>, <NUM_LIT:1>, <NUM_LIT:2>, sharex=self.ax1)<EOL>ln4 = self.ax2.plot(self.dates, t, '<STR_LIT>', label='<STR_LIT>')<EOL>self.ax2.fill_between(self.dates, t, td, color='<STR_LIT:r>')<EOL>self.ax2.set_ylabel('<STR_LIT>', multialignment='<STR_LIT>')<EOL>self.ax2.grid(b=True, which='<STR_LIT>', axis='<STR_LIT:y>', color='<STR_LIT:k>', linestyle='<STR_LIT>',<EOL>linewidth=<NUM_LIT:0.5>)<EOL>self.ax2.set_ylim(plot_range[<NUM_LIT:0>], plot_range[<NUM_LIT:1>], plot_range[<NUM_LIT:2>])<EOL>ln5 = self.ax2.plot(self.dates, td, '<STR_LIT>', label='<STR_LIT>')<EOL>self.ax2.fill_between(self.dates, td, self.ax2.get_ylim()[<NUM_LIT:0>], color='<STR_LIT:g>')<EOL>ax_twin = self.ax2.twinx()<EOL>ax_twin.set_ylim(plot_range[<NUM_LIT:0>], plot_range[<NUM_LIT:1>], plot_range[<NUM_LIT:2>])<EOL>lns = ln4 + ln5<EOL>labs = [l.get_label() for l in lns]<EOL>ax_twin.xaxis.set_major_formatter(mpl.dates.DateFormatter('<STR_LIT>'))<EOL>self.ax2.legend(lns, labs, loc='<STR_LIT>',<EOL>bbox_to_anchor=(<NUM_LIT:0.5>, <NUM_LIT>), ncol=<NUM_LIT:2>, prop={'<STR_LIT:size>': <NUM_LIT:12>})<EOL>
|
Required input:
T: Temperature (deg F)
TD: Dewpoint (deg F)
Optional Input:
plot_range: Data range for making figure (list of (min,max,step))
|
f8548:c0:m2
|
def plot_rh(self, rh, plot_range=None):
|
<EOL>if not plot_range:<EOL><INDENT>plot_range = [<NUM_LIT:0>, <NUM_LIT:100>, <NUM_LIT:4>]<EOL><DEDENT>self.ax3 = fig.add_subplot(<NUM_LIT:4>, <NUM_LIT:1>, <NUM_LIT:3>, sharex=self.ax1)<EOL>self.ax3.plot(self.dates, rh, '<STR_LIT>', label='<STR_LIT>')<EOL>self.ax3.legend(loc='<STR_LIT>', bbox_to_anchor=(<NUM_LIT:0.5>, <NUM_LIT>), prop={'<STR_LIT:size>': <NUM_LIT:12>})<EOL>self.ax3.grid(b=True, which='<STR_LIT>', axis='<STR_LIT:y>', color='<STR_LIT:k>', linestyle='<STR_LIT>',<EOL>linewidth=<NUM_LIT:0.5>)<EOL>self.ax3.set_ylim(plot_range[<NUM_LIT:0>], plot_range[<NUM_LIT:1>], plot_range[<NUM_LIT:2>])<EOL>self.ax3.fill_between(self.dates, rh, self.ax3.get_ylim()[<NUM_LIT:0>], color='<STR_LIT:g>')<EOL>self.ax3.set_ylabel('<STR_LIT>', multialignment='<STR_LIT>')<EOL>self.ax3.xaxis.set_major_formatter(mpl.dates.DateFormatter('<STR_LIT>'))<EOL>axtwin = self.ax3.twinx()<EOL>axtwin.set_ylim(plot_range[<NUM_LIT:0>], plot_range[<NUM_LIT:1>], plot_range[<NUM_LIT:2>])<EOL>
|
Required input:
RH: Relative humidity (%)
Optional Input:
plot_range: Data range for making figure (list of (min,max,step))
|
f8548:c0:m3
|
def plot_pressure(self, p, plot_range=None):
|
<EOL>if not plot_range:<EOL><INDENT>plot_range = [<NUM_LIT>, <NUM_LIT>, <NUM_LIT:2>]<EOL><DEDENT>self.ax4 = fig.add_subplot(<NUM_LIT:4>, <NUM_LIT:1>, <NUM_LIT:4>, sharex=self.ax1)<EOL>self.ax4.plot(self.dates, p, '<STR_LIT:m>', label='<STR_LIT>')<EOL>self.ax4.set_ylabel('<STR_LIT>', multialignment='<STR_LIT>')<EOL>self.ax4.set_ylim(plot_range[<NUM_LIT:0>], plot_range[<NUM_LIT:1>], plot_range[<NUM_LIT:2>])<EOL>axtwin = self.ax4.twinx()<EOL>axtwin.set_ylim(plot_range[<NUM_LIT:0>], plot_range[<NUM_LIT:1>], plot_range[<NUM_LIT:2>])<EOL>axtwin.fill_between(self.dates, p, axtwin.get_ylim()[<NUM_LIT:0>], color='<STR_LIT:m>')<EOL>axtwin.xaxis.set_major_formatter(mpl.dates.DateFormatter('<STR_LIT>'))<EOL>self.ax4.legend(loc='<STR_LIT>', bbox_to_anchor=(<NUM_LIT:0.5>, <NUM_LIT>), prop={'<STR_LIT:size>': <NUM_LIT:12>})<EOL>self.ax4.grid(b=True, which='<STR_LIT>', axis='<STR_LIT:y>', color='<STR_LIT:k>', linestyle='<STR_LIT>',<EOL>linewidth=<NUM_LIT:0.5>)<EOL>
|
Required input:
P: Mean Sea Level Pressure (hPa)
Optional Input:
plot_range: Data range for making figure (list of (min,max,step))
|
f8548:c0:m4
|
def get_root():
|
root = os.path.realpath(os.path.abspath(os.getcwd()))<EOL>setup_py = os.path.join(root, "<STR_LIT>")<EOL>versioneer_py = os.path.join(root, "<STR_LIT>")<EOL>if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)):<EOL><INDENT>root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[<NUM_LIT:0>])))<EOL>setup_py = os.path.join(root, "<STR_LIT>")<EOL>versioneer_py = os.path.join(root, "<STR_LIT>")<EOL><DEDENT>if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)):<EOL><INDENT>err = ("<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>raise VersioneerBadRootError(err)<EOL><DEDENT>try:<EOL><INDENT>me = os.path.realpath(os.path.abspath(__file__))<EOL>me_dir = os.path.normcase(os.path.splitext(me)[<NUM_LIT:0>])<EOL>vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[<NUM_LIT:0>])<EOL>if me_dir != vsr_dir:<EOL><INDENT>print("<STR_LIT>"<EOL>% (os.path.dirname(me), versioneer_py))<EOL><DEDENT><DEDENT>except NameError:<EOL><INDENT>pass<EOL><DEDENT>return root<EOL>
|
Get the project root directory.
We require that all commands are run from the project root, i.e. the
directory that contains setup.py, setup.cfg, and versioneer.py .
|
f8563:m0
|
def get_config_from_root(root):
|
<EOL>setup_cfg = os.path.join(root, "<STR_LIT>")<EOL>parser = configparser.SafeConfigParser()<EOL>with open(setup_cfg, "<STR_LIT:r>") as f:<EOL><INDENT>parser.readfp(f)<EOL><DEDENT>VCS = parser.get("<STR_LIT>", "<STR_LIT>") <EOL>def get(parser, name):<EOL><INDENT>if parser.has_option("<STR_LIT>", name):<EOL><INDENT>return parser.get("<STR_LIT>", name)<EOL><DEDENT>return None<EOL><DEDENT>cfg = VersioneerConfig()<EOL>cfg.VCS = VCS<EOL>cfg.style = get(parser, "<STR_LIT>") or "<STR_LIT>"<EOL>cfg.versionfile_source = get(parser, "<STR_LIT>")<EOL>cfg.versionfile_build = get(parser, "<STR_LIT>")<EOL>cfg.tag_prefix = get(parser, "<STR_LIT>")<EOL>if cfg.tag_prefix in ("<STR_LIT>", '<STR_LIT>'):<EOL><INDENT>cfg.tag_prefix = "<STR_LIT>"<EOL><DEDENT>cfg.parentdir_prefix = get(parser, "<STR_LIT>")<EOL>cfg.verbose = get(parser, "<STR_LIT>")<EOL>return cfg<EOL>
|
Read the project setup.cfg file to determine Versioneer config.
|
f8563: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.
|
f8563: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><INDENT>e = sys.exc_info()[<NUM_LIT:1>]<EOL>if e.errno == errno.ENOENT:<EOL><INDENT>continue<EOL><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % dispcmd)<EOL>print(e)<EOL><DEDENT>return None, None<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % (commands,))<EOL><DEDENT>return None, None<EOL><DEDENT>stdout = p.communicate()[<NUM_LIT:0>].strip()<EOL>if sys.version_info[<NUM_LIT:0>] >= <NUM_LIT:3>:<EOL><INDENT>stdout = stdout.decode()<EOL><DEDENT>if p.returncode != <NUM_LIT:0>:<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % dispcmd)<EOL>print("<STR_LIT>" % stdout)<EOL><DEDENT>return None, p.returncode<EOL><DEDENT>return stdout, p.returncode<EOL>
|
Call the given command(s).
|
f8563:m3
|
@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().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().startswith("<STR_LIT>"):<EOL><INDENT>mo = re.search(r'<STR_LIT>', line)<EOL>if mo:<EOL><INDENT>keywords["<STR_LIT:date>"] = mo.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT><DEDENT>f.close()<EOL><DEDENT>except EnvironmentError:<EOL><INDENT>pass<EOL><DEDENT>return keywords<EOL>
|
Extract version information from the given file.
|
f8563:m4
|
@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>"].strip()<EOL>if refnames.startswith("<STR_LIT>"):<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>refs = set([r.strip() for r in refnames.strip("<STR_LIT>").split("<STR_LIT:U+002C>")])<EOL>TAG = "<STR_LIT>"<EOL>tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])<EOL>if not tags:<EOL><INDENT>tags = set([r for r in refs if re.search(r'<STR_LIT>', r)])<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % "<STR_LIT:U+002C>".join(refs - tags))<EOL><DEDENT><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % "<STR_LIT:U+002C>".join(sorted(tags)))<EOL><DEDENT>for ref in sorted(tags):<EOL><INDENT>if ref.startswith(tag_prefix):<EOL><INDENT>r = ref[len(tag_prefix):]<EOL>if verbose:<EOL><INDENT>print("<STR_LIT>" % r)<EOL><DEDENT>return {"<STR_LIT:version>": r,<EOL>"<STR_LIT>": keywords["<STR_LIT>"].strip(),<EOL>"<STR_LIT>": False, "<STR_LIT:error>": None,<EOL>"<STR_LIT:date>": date}<EOL><DEDENT><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>return {"<STR_LIT:version>": "<STR_LIT>",<EOL>"<STR_LIT>": keywords["<STR_LIT>"].strip(),<EOL>"<STR_LIT>": False, "<STR_LIT:error>": "<STR_LIT>", "<STR_LIT:date>": None}<EOL>
|
Get version information from git keywords.
|
f8563:m5
|
@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 NotThisMethod("<STR_LIT>")<EOL><DEDENT>describe_out, rc = run_command(GITS, ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>", "<STR_LIT>" % tag_prefix],<EOL>cwd=root)<EOL>if describe_out is None:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>describe_out = describe_out.strip()<EOL>full_out, rc = run_command(GITS, ["<STR_LIT>", "<STR_LIT>"], cwd=root)<EOL>if full_out is None:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>full_out = full_out.strip()<EOL>pieces = {}<EOL>pieces["<STR_LIT>"] = full_out<EOL>pieces["<STR_LIT>"] = full_out[:<NUM_LIT:7>] <EOL>pieces["<STR_LIT:error>"] = None<EOL>git_describe = describe_out<EOL>dirty = git_describe.endswith("<STR_LIT>")<EOL>pieces["<STR_LIT>"] = dirty<EOL>if dirty:<EOL><INDENT>git_describe = git_describe[:git_describe.rindex("<STR_LIT>")]<EOL><DEDENT>if "<STR_LIT:->" in git_describe:<EOL><INDENT>mo = re.search(r'<STR_LIT>', git_describe)<EOL>if not mo:<EOL><INDENT>pieces["<STR_LIT:error>"] = ("<STR_LIT>"<EOL>% describe_out)<EOL>return pieces<EOL><DEDENT>full_tag = mo.group(<NUM_LIT:1>)<EOL>if not full_tag.startswith(tag_prefix):<EOL><INDENT>if verbose:<EOL><INDENT>fmt = "<STR_LIT>"<EOL>print(fmt % (full_tag, tag_prefix))<EOL><DEDENT>pieces["<STR_LIT:error>"] = ("<STR_LIT>"<EOL>% (full_tag, tag_prefix))<EOL>return pieces<EOL><DEDENT>pieces["<STR_LIT>"] = full_tag[len(tag_prefix):]<EOL>pieces["<STR_LIT>"] = int(mo.group(<NUM_LIT:2>))<EOL>pieces["<STR_LIT>"] = mo.group(<NUM_LIT:3>)<EOL><DEDENT>else:<EOL><INDENT>pieces["<STR_LIT>"] = None<EOL>count_out, rc = run_command(GITS, ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>"],<EOL>cwd=root)<EOL>pieces["<STR_LIT>"] = int(count_out) <EOL><DEDENT>date = run_command(GITS, ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"],<EOL>cwd=root)[<NUM_LIT:0>].strip()<EOL>pieces["<STR_LIT: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>return pieces<EOL>
|
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.
|
f8563:m6
|
def do_vcs_install(manifest_in, versionfile_source, ipy):
|
GITS = ["<STR_LIT>"]<EOL>if sys.platform == "<STR_LIT:win32>":<EOL><INDENT>GITS = ["<STR_LIT>", "<STR_LIT>"]<EOL><DEDENT>files = [manifest_in, versionfile_source]<EOL>if ipy:<EOL><INDENT>files.append(ipy)<EOL><DEDENT>try:<EOL><INDENT>me = __file__<EOL>if me.endswith("<STR_LIT>") or me.endswith("<STR_LIT>"):<EOL><INDENT>me = os.path.splitext(me)[<NUM_LIT:0>] + "<STR_LIT>"<EOL><DEDENT>versioneer_file = os.path.relpath(me)<EOL><DEDENT>except NameError:<EOL><INDENT>versioneer_file = "<STR_LIT>"<EOL><DEDENT>files.append(versioneer_file)<EOL>present = False<EOL>try:<EOL><INDENT>f = open("<STR_LIT>", "<STR_LIT:r>")<EOL>for line in f.readlines():<EOL><INDENT>if line.strip().startswith(versionfile_source):<EOL><INDENT>if "<STR_LIT>" in line.strip().split()[<NUM_LIT:1>:]:<EOL><INDENT>present = True<EOL><DEDENT><DEDENT><DEDENT>f.close()<EOL><DEDENT>except EnvironmentError:<EOL><INDENT>pass<EOL><DEDENT>if not present:<EOL><INDENT>f = open("<STR_LIT>", "<STR_LIT>")<EOL>f.write("<STR_LIT>" % versionfile_source)<EOL>f.close()<EOL>files.append("<STR_LIT>")<EOL><DEDENT>run_command(GITS, ["<STR_LIT>", "<STR_LIT>"] + files)<EOL>
|
Git-specific installation logic for Versioneer.
For Git, this means creating/changing .gitattributes to mark _version.py
for export-subst keyword substitution.
|
f8563:m7
|
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>else:<EOL><INDENT>rootdirs.append(root)<EOL>root = os.path.dirname(root) <EOL><DEDENT><DEDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" %<EOL>(str(rootdirs), parentdir_prefix))<EOL><DEDENT>raise NotThisMethod("<STR_LIT>")<EOL>
|
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
|
f8563:m8
|
def versions_from_file(filename):
|
try:<EOL><INDENT>with open(filename) as f:<EOL><INDENT>contents = f.read()<EOL><DEDENT><DEDENT>except EnvironmentError:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>mo = re.search(r"<STR_LIT>",<EOL>contents, re.M | re.S)<EOL>if not mo:<EOL><INDENT>mo = re.search(r"<STR_LIT>",<EOL>contents, re.M | re.S)<EOL><DEDENT>if not mo:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>return json.loads(mo.group(<NUM_LIT:1>))<EOL>
|
Try to determine the version from _version.py if present.
|
f8563:m9
|
def write_to_version_file(filename, versions):
|
os.unlink(filename)<EOL>contents = json.dumps(versions, sort_keys=True,<EOL>indent=<NUM_LIT:1>, separators=("<STR_LIT:U+002C>", "<STR_LIT>"))<EOL>with open(filename, "<STR_LIT:w>") as f:<EOL><INDENT>f.write(SHORT_VERSION_PY % contents)<EOL><DEDENT>print("<STR_LIT>" % (filename, versions["<STR_LIT:version>"]))<EOL>
|
Write the given version number to the given _version.py file.
|
f8563:m10
|
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 .
|
f8563:m11
|
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><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % (pieces["<STR_LIT>"],<EOL>pieces["<STR_LIT>"])<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT>return rendered<EOL>
|
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]
|
f8563:m12
|
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
|
f8563:m13
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.