repo
stringlengths 2
152
⌀ | file
stringlengths 15
239
| code
stringlengths 0
58.4M
| file_length
int64 0
58.4M
| avg_line_length
float64 0
1.81M
| max_line_length
int64 0
12.7M
| extension_type
stringclasses 364
values |
---|---|---|---|---|---|---|
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_gridspec.py | import matplotlib.gridspec as gridspec
import pytest
def test_equal():
gs = gridspec.GridSpec(2, 1)
assert gs[0, 0] == gs[0, 0]
assert gs[:, 0] == gs[:, 0]
def test_width_ratios():
"""
Addresses issue #5835.
See at https://github.com/matplotlib/matplotlib/issues/5835.
"""
with pytest.raises(ValueError):
gridspec.GridSpec(1, 1, width_ratios=[2, 1, 3])
def test_height_ratios():
"""
Addresses issue #5835.
See at https://github.com/matplotlib/matplotlib/issues/5835.
"""
with pytest.raises(ValueError):
gridspec.GridSpec(1, 1, height_ratios=[2, 1, 3])
| 626 | 22.222222 | 64 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_figure.py | from __future__ import absolute_import, division, print_function
import sys
import warnings
from matplotlib import rcParams
from matplotlib.testing.decorators import image_comparison
from matplotlib.axes import Axes
from matplotlib.ticker import AutoMinorLocator, FixedFormatter
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.gridspec as gridspec
import numpy as np
import pytest
@image_comparison(baseline_images=['figure_align_labels'])
def test_align_labels():
# Check the figure.align_labels() command
fig = plt.figure(tight_layout=True)
gs = gridspec.GridSpec(3, 3)
ax = fig.add_subplot(gs[0, :2])
ax.plot(np.arange(0, 1e6, 1000))
ax.set_ylabel('Ylabel0 0')
ax = fig.add_subplot(gs[0, -1])
ax.plot(np.arange(0, 1e4, 100))
for i in range(3):
ax = fig.add_subplot(gs[1, i])
ax.set_ylabel('YLabel1 %d' % i)
ax.set_xlabel('XLabel1 %d' % i)
if i in [0, 2]:
ax.xaxis.set_label_position("top")
ax.xaxis.tick_top()
if i == 0:
for tick in ax.get_xticklabels():
tick.set_rotation(90)
if i == 2:
ax.yaxis.set_label_position("right")
ax.yaxis.tick_right()
for i in range(3):
ax = fig.add_subplot(gs[2, i])
ax.set_xlabel('XLabel2 %d' % (i))
ax.set_ylabel('YLabel2 %d' % (i))
if i == 2:
ax.plot(np.arange(0, 1e4, 10))
ax.yaxis.set_label_position("right")
ax.yaxis.tick_right()
for tick in ax.get_xticklabels():
tick.set_rotation(90)
fig.align_labels()
def test_figure_label():
# pyplot figure creation, selection and closing with figure label and
# number
plt.close('all')
plt.figure('today')
plt.figure(3)
plt.figure('tomorrow')
plt.figure()
plt.figure(0)
plt.figure(1)
plt.figure(3)
assert plt.get_fignums() == [0, 1, 3, 4, 5]
assert plt.get_figlabels() == ['', 'today', '', 'tomorrow', '']
plt.close(10)
plt.close()
plt.close(5)
plt.close('tomorrow')
assert plt.get_fignums() == [0, 1]
assert plt.get_figlabels() == ['', 'today']
def test_fignum_exists():
# pyplot figure creation, selection and closing with fignum_exists
plt.figure('one')
plt.figure(2)
plt.figure('three')
plt.figure()
assert plt.fignum_exists('one')
assert plt.fignum_exists(2)
assert plt.fignum_exists('three')
assert plt.fignum_exists(4)
plt.close('one')
plt.close(4)
assert not plt.fignum_exists('one')
assert not plt.fignum_exists(4)
def test_clf_keyword():
# test if existing figure is cleared with figure() and subplots()
text1 = 'A fancy plot'
text2 = 'Really fancy!'
fig0 = plt.figure(num=1)
fig0.suptitle(text1)
assert [t.get_text() for t in fig0.texts] == [text1]
fig1 = plt.figure(num=1, clear=False)
fig1.text(0.5, 0.5, text2)
assert fig0 is fig1
assert [t.get_text() for t in fig1.texts] == [text1, text2]
fig2, ax2 = plt.subplots(2, 1, num=1, clear=True)
assert fig0 is fig2
assert [t.get_text() for t in fig2.texts] == []
@image_comparison(baseline_images=['figure_today'])
def test_figure():
# named figure support
fig = plt.figure('today')
ax = fig.add_subplot(111)
ax.set_title(fig.get_label())
ax.plot(np.arange(5))
# plot red line in a different figure.
plt.figure('tomorrow')
plt.plot([0, 1], [1, 0], 'r')
# Return to the original; make sure the red line is not there.
plt.figure('today')
plt.close('tomorrow')
@image_comparison(baseline_images=['figure_legend'])
def test_figure_legend():
fig, axes = plt.subplots(2)
axes[0].plot([0, 1], [1, 0], label='x', color='g')
axes[0].plot([0, 1], [0, 1], label='y', color='r')
axes[0].plot([0, 1], [0.5, 0.5], label='y', color='k')
axes[1].plot([0, 1], [1, 0], label='_y', color='r')
axes[1].plot([0, 1], [0, 1], label='z', color='b')
fig.legend()
def test_gca():
fig = plt.figure()
ax1 = fig.add_axes([0, 0, 1, 1])
assert fig.gca(projection='rectilinear') is ax1
assert fig.gca() is ax1
ax2 = fig.add_subplot(121, projection='polar')
assert fig.gca() is ax2
assert fig.gca(polar=True)is ax2
ax3 = fig.add_subplot(122)
assert fig.gca() is ax3
# the final request for a polar axes will end up creating one
# with a spec of 111.
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
# Changing the projection will throw a warning
assert fig.gca(polar=True) is not ax3
assert len(w) == 1
assert fig.gca(polar=True) is not ax2
assert fig.gca().get_geometry() == (1, 1, 1)
fig.sca(ax1)
assert fig.gca(projection='rectilinear') is ax1
assert fig.gca() is ax1
@image_comparison(baseline_images=['figure_suptitle'])
def test_suptitle():
fig, _ = plt.subplots()
fig.suptitle('hello', color='r')
fig.suptitle('title', color='g', rotation='30')
def test_suptitle_fontproperties():
from matplotlib.font_manager import FontProperties
fig, ax = plt.subplots()
fps = FontProperties(size='large', weight='bold')
txt = fig.suptitle('fontprops title', fontproperties=fps)
assert txt.get_fontsize() == fps.get_size_in_points()
assert txt.get_weight() == fps.get_weight()
@image_comparison(baseline_images=['alpha_background'],
# only test png and svg. The PDF output appears correct,
# but Ghostscript does not preserve the background color.
extensions=['png', 'svg'],
savefig_kwarg={'facecolor': (0, 1, 0.4),
'edgecolor': 'none'})
def test_alpha():
# We want an image which has a background color and an
# alpha of 0.4.
fig = plt.figure(figsize=[2, 1])
fig.set_facecolor((0, 1, 0.4))
fig.patch.set_alpha(0.4)
import matplotlib.patches as mpatches
fig.patches.append(mpatches.CirclePolygon([20, 20],
radius=15,
alpha=0.6,
facecolor='red'))
def test_too_many_figures():
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
for i in range(rcParams['figure.max_open_warning'] + 1):
plt.figure()
assert len(w) == 1
def test_iterability_axes_argument():
# This is a regression test for matplotlib/matplotlib#3196. If one of the
# arguments returned by _as_mpl_axes defines __getitem__ but is not
# iterable, this would raise an execption. This is because we check
# whether the arguments are iterable, and if so we try and convert them
# to a tuple. However, the ``iterable`` function returns True if
# __getitem__ is present, but some classes can define __getitem__ without
# being iterable. The tuple conversion is now done in a try...except in
# case it fails.
class MyAxes(Axes):
def __init__(self, *args, **kwargs):
kwargs.pop('myclass', None)
return Axes.__init__(self, *args, **kwargs)
class MyClass(object):
def __getitem__(self, item):
if item != 'a':
raise ValueError("item should be a")
def _as_mpl_axes(self):
return MyAxes, {'myclass': self}
fig = plt.figure()
fig.add_subplot(1, 1, 1, projection=MyClass())
plt.close(fig)
def test_set_fig_size():
fig = plt.figure()
# check figwidth
fig.set_figwidth(5)
assert fig.get_figwidth() == 5
# check figheight
fig.set_figheight(1)
assert fig.get_figheight() == 1
# check using set_size_inches
fig.set_size_inches(2, 4)
assert fig.get_figwidth() == 2
assert fig.get_figheight() == 4
# check using tuple to first argument
fig.set_size_inches((1, 3))
assert fig.get_figwidth() == 1
assert fig.get_figheight() == 3
def test_axes_remove():
fig, axes = plt.subplots(2, 2)
axes[-1, -1].remove()
for ax in axes.ravel()[:-1]:
assert ax in fig.axes
assert axes[-1, -1] not in fig.axes
assert len(fig.axes) == 3
def test_figaspect():
w, h = plt.figaspect(np.float64(2) / np.float64(1))
assert h / w == 2
w, h = plt.figaspect(2)
assert h / w == 2
w, h = plt.figaspect(np.zeros((1, 2)))
assert h / w == 0.5
w, h = plt.figaspect(np.zeros((2, 2)))
assert h / w == 1
@pytest.mark.parametrize('which', [None, 'both', 'major', 'minor'])
def test_autofmt_xdate(which):
date = ['3 Jan 2013', '4 Jan 2013', '5 Jan 2013', '6 Jan 2013',
'7 Jan 2013', '8 Jan 2013', '9 Jan 2013', '10 Jan 2013',
'11 Jan 2013', '12 Jan 2013', '13 Jan 2013', '14 Jan 2013']
time = ['16:44:00', '16:45:00', '16:46:00', '16:47:00', '16:48:00',
'16:49:00', '16:51:00', '16:52:00', '16:53:00', '16:55:00',
'16:56:00', '16:57:00']
angle = 60
minors = [1, 2, 3, 4, 5, 6, 7]
x = mdates.datestr2num(date)
y = mdates.datestr2num(time)
fig, ax = plt.subplots()
ax.plot(x, y)
ax.yaxis_date()
ax.xaxis_date()
ax.xaxis.set_minor_locator(AutoMinorLocator(2))
ax.xaxis.set_minor_formatter(FixedFormatter(minors))
fig.autofmt_xdate(0.2, angle, 'right', which)
if which in ('both', 'major', None):
for label in fig.axes[0].get_xticklabels(False, 'major'):
assert int(label.get_rotation()) == angle
if which in ('both', 'minor'):
for label in fig.axes[0].get_xticklabels(True, 'minor'):
assert int(label.get_rotation()) == angle
@pytest.mark.style('default')
def test_change_dpi():
fig = plt.figure(figsize=(4, 4))
fig.canvas.draw()
assert fig.canvas.renderer.height == 400
assert fig.canvas.renderer.width == 400
fig.dpi = 50
fig.canvas.draw()
assert fig.canvas.renderer.height == 200
assert fig.canvas.renderer.width == 200
def test_invalid_figure_size():
with pytest.raises(ValueError):
plt.figure(figsize=(1, np.nan))
fig = plt.figure()
with pytest.raises(ValueError):
fig.set_size_inches(1, np.nan)
with pytest.raises(ValueError):
fig.add_axes((.1, .1, .5, np.nan))
def test_subplots_shareax_loglabels():
fig, ax_arr = plt.subplots(2, 2, sharex=True, sharey=True, squeeze=False)
for ax in ax_arr.flatten():
ax.plot([10, 20, 30], [10, 20, 30])
ax.set_yscale("log")
ax.set_xscale("log")
for ax in ax_arr[0, :]:
assert 0 == len(ax.xaxis.get_ticklabels(which='both'))
for ax in ax_arr[1, :]:
assert 0 < len(ax.xaxis.get_ticklabels(which='both'))
for ax in ax_arr[:, 1]:
assert 0 == len(ax.yaxis.get_ticklabels(which='both'))
for ax in ax_arr[:, 0]:
assert 0 < len(ax.yaxis.get_ticklabels(which='both'))
def test_savefig():
fig = plt.figure()
msg = "savefig() takes 2 positional arguments but 3 were given"
with pytest.raises(TypeError, message=msg):
fig.savefig("fname1.png", "fname2.png")
def test_figure_repr():
fig = plt.figure(figsize=(10, 20), dpi=10)
assert repr(fig) == "<Figure size 100x200 with 0 Axes>"
@pytest.mark.skipif(sys.version_info < (3, 6), reason="requires Python 3.6+")
@pytest.mark.parametrize("fmt", ["png", "pdf", "ps", "eps", "svg"])
def test_fspath(fmt, tmpdir):
from pathlib import Path
out = Path(tmpdir, "test.{}".format(fmt))
plt.savefig(out)
with out.open("rb") as file:
# All the supported formats include the format name (case-insensitive)
# in the first 100 bytes.
assert fmt.encode("ascii") in file.read(100).lower()
| 11,808 | 29.357326 | 78 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_widgets.py | from __future__ import absolute_import, division, print_function
try:
# mock in python 3.3+
from unittest import mock
except ImportError:
import mock
import matplotlib.widgets as widgets
import matplotlib.pyplot as plt
from matplotlib.testing.decorators import image_comparison
from numpy.testing import assert_allclose
import pytest
def get_ax():
fig, ax = plt.subplots(1, 1)
ax.plot([0, 200], [0, 200])
ax.set_aspect(1.0)
ax.figure.canvas.draw()
return ax
def do_event(tool, etype, button=1, xdata=0, ydata=0, key=None, step=1):
"""
*name*
the event name
*canvas*
the FigureCanvas instance generating the event
*guiEvent*
the GUI event that triggered the matplotlib event
*x*
x position - pixels from left of canvas
*y*
y position - pixels from bottom of canvas
*inaxes*
the :class:`~matplotlib.axes.Axes` instance if mouse is over axes
*xdata*
x coord of mouse in data coords
*ydata*
y coord of mouse in data coords
*button*
button pressed None, 1, 2, 3, 'up', 'down' (up and down are used
for scroll events)
*key*
the key depressed when the mouse event triggered (see
:class:`KeyEvent`)
*step*
number of scroll steps (positive for 'up', negative for 'down')
"""
event = mock.Mock()
event.button = button
ax = tool.ax
event.x, event.y = ax.transData.transform([(xdata, ydata),
(xdata, ydata)])[00]
event.xdata, event.ydata = xdata, ydata
event.inaxes = ax
event.canvas = ax.figure.canvas
event.key = key
event.step = step
event.guiEvent = None
event.name = 'Custom'
func = getattr(tool, etype)
func(event)
def check_rectangle(**kwargs):
ax = get_ax()
def onselect(epress, erelease):
ax._got_onselect = True
assert epress.xdata == 100
assert epress.ydata == 100
assert erelease.xdata == 199
assert erelease.ydata == 199
tool = widgets.RectangleSelector(ax, onselect, **kwargs)
do_event(tool, 'press', xdata=100, ydata=100, button=1)
do_event(tool, 'onmove', xdata=199, ydata=199, button=1)
# purposely drag outside of axis for release
do_event(tool, 'release', xdata=250, ydata=250, button=1)
if kwargs.get('drawtype', None) not in ['line', 'none']:
assert_allclose(tool.geometry,
[[100., 100, 199, 199, 100], [100, 199, 199, 100, 100]],
err_msg=tool.geometry)
assert ax._got_onselect
def test_rectangle_selector():
check_rectangle()
check_rectangle(drawtype='line', useblit=False)
check_rectangle(useblit=True, button=1)
check_rectangle(drawtype='none', minspanx=10, minspany=10)
check_rectangle(minspanx=10, minspany=10, spancoords='pixels')
check_rectangle(rectprops=dict(fill=True))
def test_ellipse():
"""For ellipse, test out the key modifiers"""
ax = get_ax()
def onselect(epress, erelease):
pass
tool = widgets.EllipseSelector(ax, onselect=onselect,
maxdist=10, interactive=True)
tool.extents = (100, 150, 100, 150)
# drag the rectangle
do_event(tool, 'press', xdata=10, ydata=10, button=1,
key=' ')
do_event(tool, 'onmove', xdata=30, ydata=30, button=1)
do_event(tool, 'release', xdata=30, ydata=30, button=1)
assert tool.extents == (120, 170, 120, 170)
# create from center
do_event(tool, 'on_key_press', xdata=100, ydata=100, button=1,
key='control')
do_event(tool, 'press', xdata=100, ydata=100, button=1)
do_event(tool, 'onmove', xdata=125, ydata=125, button=1)
do_event(tool, 'release', xdata=125, ydata=125, button=1)
do_event(tool, 'on_key_release', xdata=100, ydata=100, button=1,
key='control')
assert tool.extents == (75, 125, 75, 125)
# create a square
do_event(tool, 'on_key_press', xdata=10, ydata=10, button=1,
key='shift')
do_event(tool, 'press', xdata=10, ydata=10, button=1)
do_event(tool, 'onmove', xdata=35, ydata=30, button=1)
do_event(tool, 'release', xdata=35, ydata=30, button=1)
do_event(tool, 'on_key_release', xdata=10, ydata=10, button=1,
key='shift')
extents = [int(e) for e in tool.extents]
assert extents == [10, 35, 10, 34]
# create a square from center
do_event(tool, 'on_key_press', xdata=100, ydata=100, button=1,
key='ctrl+shift')
do_event(tool, 'press', xdata=100, ydata=100, button=1)
do_event(tool, 'onmove', xdata=125, ydata=130, button=1)
do_event(tool, 'release', xdata=125, ydata=130, button=1)
do_event(tool, 'on_key_release', xdata=100, ydata=100, button=1,
key='ctrl+shift')
extents = [int(e) for e in tool.extents]
assert extents == [70, 129, 70, 130]
assert tool.geometry.shape == (2, 73)
assert_allclose(tool.geometry[:, 0], [70., 100])
def test_rectangle_handles():
ax = get_ax()
def onselect(epress, erelease):
pass
tool = widgets.RectangleSelector(ax, onselect=onselect,
maxdist=10, interactive=True)
tool.extents = (100, 150, 100, 150)
assert tool.corners == (
(100, 150, 150, 100), (100, 100, 150, 150))
assert tool.extents == (100, 150, 100, 150)
assert tool.edge_centers == (
(100, 125.0, 150, 125.0), (125.0, 100, 125.0, 150))
assert tool.extents == (100, 150, 100, 150)
# grab a corner and move it
do_event(tool, 'press', xdata=100, ydata=100)
do_event(tool, 'onmove', xdata=120, ydata=120)
do_event(tool, 'release', xdata=120, ydata=120)
assert tool.extents == (120, 150, 120, 150)
# grab the center and move it
do_event(tool, 'press', xdata=132, ydata=132)
do_event(tool, 'onmove', xdata=120, ydata=120)
do_event(tool, 'release', xdata=120, ydata=120)
assert tool.extents == (108, 138, 108, 138)
# create a new rectangle
do_event(tool, 'press', xdata=10, ydata=10)
do_event(tool, 'onmove', xdata=100, ydata=100)
do_event(tool, 'release', xdata=100, ydata=100)
assert tool.extents == (10, 100, 10, 100)
def check_span(*args, **kwargs):
ax = get_ax()
def onselect(vmin, vmax):
ax._got_onselect = True
assert vmin == 100
assert vmax == 150
def onmove(vmin, vmax):
assert vmin == 100
assert vmax == 125
ax._got_on_move = True
if 'onmove_callback' in kwargs:
kwargs['onmove_callback'] = onmove
tool = widgets.SpanSelector(ax, onselect, *args, **kwargs)
do_event(tool, 'press', xdata=100, ydata=100, button=1)
do_event(tool, 'onmove', xdata=125, ydata=125, button=1)
do_event(tool, 'release', xdata=150, ydata=150, button=1)
assert ax._got_onselect
if 'onmove_callback' in kwargs:
assert ax._got_on_move
def test_span_selector():
check_span('horizontal', minspan=10, useblit=True)
check_span('vertical', onmove_callback=True, button=1)
check_span('horizontal', rectprops=dict(fill=True))
def check_lasso_selector(**kwargs):
ax = get_ax()
def onselect(verts):
ax._got_onselect = True
assert verts == [(100, 100), (125, 125), (150, 150)]
tool = widgets.LassoSelector(ax, onselect, **kwargs)
do_event(tool, 'press', xdata=100, ydata=100, button=1)
do_event(tool, 'onmove', xdata=125, ydata=125, button=1)
do_event(tool, 'release', xdata=150, ydata=150, button=1)
assert ax._got_onselect
def test_lasso_selector():
check_lasso_selector()
check_lasso_selector(useblit=False, lineprops=dict(color='red'))
check_lasso_selector(useblit=True, button=1)
def test_CheckButtons():
ax = get_ax()
check = widgets.CheckButtons(ax, ('a', 'b', 'c'), (True, False, True))
assert check.get_status() == [True, False, True]
check.set_active(0)
assert check.get_status() == [False, False, True]
cid = check.on_clicked(lambda: None)
check.disconnect(cid)
@image_comparison(baseline_images=['check_radio_buttons'], extensions=['png'],
style='default')
def test_check_radio_buttons_image():
get_ax()
plt.subplots_adjust(left=0.3)
rax1 = plt.axes([0.05, 0.7, 0.15, 0.15])
rax2 = plt.axes([0.05, 0.2, 0.15, 0.15])
widgets.RadioButtons(rax1, ('Radio 1', 'Radio 2', 'Radio 3'))
widgets.CheckButtons(rax2, ('Check 1', 'Check 2', 'Check 3'),
(False, True, True))
def test_slider_slidermin_slidermax_invalid():
fig, ax = plt.subplots()
# test min/max with floats
with pytest.raises(ValueError):
widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0,
slidermin=10.0)
with pytest.raises(ValueError):
widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0,
slidermax=10.0)
def test_slider_slidermin_slidermax():
fig, ax = plt.subplots()
slider_ = widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0,
valinit=5.0)
slider = widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0,
valinit=1.0, slidermin=slider_)
assert slider.val == slider_.val
slider = widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0,
valinit=10.0, slidermax=slider_)
assert slider.val == slider_.val
def test_slider_valmin_valmax():
fig, ax = plt.subplots()
slider = widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0,
valinit=-10.0)
assert slider.val == slider.valmin
slider = widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0,
valinit=25.0)
assert slider.val == slider.valmax
def check_polygon_selector(event_sequence, expected_result, selections_count):
"""Helper function to test Polygon Selector
Parameters
----------
event_sequence : list of tuples (etype, dict())
A sequence of events to perform. The sequence is a list of tuples
where the first element of the tuple is an etype (e.g., 'onmove',
'press', etc.), and the second element of the tuple is a dictionary of
the arguments for the event (e.g., xdata=5, key='shift', etc.).
expected_result : list of vertices (xdata, ydata)
The list of vertices that are expected to result from the event
sequence.
selections_count : int
Wait for the tool to call its `onselect` function `selections_count`
times, before comparing the result to the `expected_result`
"""
ax = get_ax()
ax._selections_count = 0
def onselect(vertices):
ax._selections_count += 1
ax._current_result = vertices
tool = widgets.PolygonSelector(ax, onselect)
for (etype, event_args) in event_sequence:
do_event(tool, etype, **event_args)
assert ax._selections_count == selections_count
assert ax._current_result == expected_result
def polygon_place_vertex(xdata, ydata):
return [('onmove', dict(xdata=xdata, ydata=ydata)),
('press', dict(xdata=xdata, ydata=ydata)),
('release', dict(xdata=xdata, ydata=ydata))]
def test_polygon_selector():
# Simple polygon
expected_result = [(50, 50), (150, 50), (50, 150)]
event_sequence = (polygon_place_vertex(50, 50)
+ polygon_place_vertex(150, 50)
+ polygon_place_vertex(50, 150)
+ polygon_place_vertex(50, 50))
check_polygon_selector(event_sequence, expected_result, 1)
# Move first vertex before completing the polygon.
expected_result = [(75, 50), (150, 50), (50, 150)]
event_sequence = (polygon_place_vertex(50, 50)
+ polygon_place_vertex(150, 50)
+ [('on_key_press', dict(key='control')),
('onmove', dict(xdata=50, ydata=50)),
('press', dict(xdata=50, ydata=50)),
('onmove', dict(xdata=75, ydata=50)),
('release', dict(xdata=75, ydata=50)),
('on_key_release', dict(key='control'))]
+ polygon_place_vertex(50, 150)
+ polygon_place_vertex(75, 50))
check_polygon_selector(event_sequence, expected_result, 1)
# Move first two vertices at once before completing the polygon.
expected_result = [(50, 75), (150, 75), (50, 150)]
event_sequence = (polygon_place_vertex(50, 50)
+ polygon_place_vertex(150, 50)
+ [('on_key_press', dict(key='shift')),
('onmove', dict(xdata=100, ydata=100)),
('press', dict(xdata=100, ydata=100)),
('onmove', dict(xdata=100, ydata=125)),
('release', dict(xdata=100, ydata=125)),
('on_key_release', dict(key='shift'))]
+ polygon_place_vertex(50, 150)
+ polygon_place_vertex(50, 75))
check_polygon_selector(event_sequence, expected_result, 1)
# Move first vertex after completing the polygon.
expected_result = [(75, 50), (150, 50), (50, 150)]
event_sequence = (polygon_place_vertex(50, 50)
+ polygon_place_vertex(150, 50)
+ polygon_place_vertex(50, 150)
+ polygon_place_vertex(50, 50)
+ [('onmove', dict(xdata=50, ydata=50)),
('press', dict(xdata=50, ydata=50)),
('onmove', dict(xdata=75, ydata=50)),
('release', dict(xdata=75, ydata=50))])
check_polygon_selector(event_sequence, expected_result, 2)
# Move all vertices after completing the polygon.
expected_result = [(75, 75), (175, 75), (75, 175)]
event_sequence = (polygon_place_vertex(50, 50)
+ polygon_place_vertex(150, 50)
+ polygon_place_vertex(50, 150)
+ polygon_place_vertex(50, 50)
+ [('on_key_press', dict(key='shift')),
('onmove', dict(xdata=100, ydata=100)),
('press', dict(xdata=100, ydata=100)),
('onmove', dict(xdata=125, ydata=125)),
('release', dict(xdata=125, ydata=125)),
('on_key_release', dict(key='shift'))])
check_polygon_selector(event_sequence, expected_result, 2)
# Try to move a vertex and move all before placing any vertices.
expected_result = [(50, 50), (150, 50), (50, 150)]
event_sequence = ([('on_key_press', dict(key='control')),
('onmove', dict(xdata=100, ydata=100)),
('press', dict(xdata=100, ydata=100)),
('onmove', dict(xdata=125, ydata=125)),
('release', dict(xdata=125, ydata=125)),
('on_key_release', dict(key='control')),
('on_key_press', dict(key='shift')),
('onmove', dict(xdata=100, ydata=100)),
('press', dict(xdata=100, ydata=100)),
('onmove', dict(xdata=125, ydata=125)),
('release', dict(xdata=125, ydata=125)),
('on_key_release', dict(key='shift'))]
+ polygon_place_vertex(50, 50)
+ polygon_place_vertex(150, 50)
+ polygon_place_vertex(50, 150)
+ polygon_place_vertex(50, 50))
check_polygon_selector(event_sequence, expected_result, 1)
# Try to place vertex out-of-bounds, then reset, and start a new polygon.
expected_result = [(50, 50), (150, 50), (50, 150)]
event_sequence = (polygon_place_vertex(50, 50)
+ polygon_place_vertex(250, 50)
+ [('on_key_press', dict(key='escape')),
('on_key_release', dict(key='escape'))]
+ polygon_place_vertex(50, 50)
+ polygon_place_vertex(150, 50)
+ polygon_place_vertex(50, 150)
+ polygon_place_vertex(50, 50))
check_polygon_selector(event_sequence, expected_result, 1)
| 16,496 | 35.578714 | 78 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_text.py | from __future__ import absolute_import, division, print_function
import six
import io
import warnings
import numpy as np
from numpy.testing import assert_almost_equal
import pytest
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.testing.decorators import image_comparison
needs_usetex = pytest.mark.xfail(
not matplotlib.checkdep_usetex(True),
reason="This test needs a TeX installation")
@image_comparison(baseline_images=['font_styles'])
def test_font_styles():
from matplotlib import _get_data_path
data_path = _get_data_path()
def find_matplotlib_font(**kw):
prop = FontProperties(**kw)
path = findfont(prop, directory=data_path)
return FontProperties(fname=path)
from matplotlib.font_manager import FontProperties, findfont
warnings.filterwarnings(
'ignore',
r"findfont: Font family \[u?'Foo'\] not found. Falling back to .",
UserWarning,
module='matplotlib.font_manager')
plt.figure()
ax = plt.subplot(1, 1, 1)
normalFont = find_matplotlib_font(
family="sans-serif",
style="normal",
variant="normal",
size=14)
ax.annotate(
"Normal Font",
(0.1, 0.1),
xycoords='axes fraction',
fontproperties=normalFont)
boldFont = find_matplotlib_font(
family="Foo",
style="normal",
variant="normal",
weight="bold",
stretch=500,
size=14)
ax.annotate(
"Bold Font",
(0.1, 0.2),
xycoords='axes fraction',
fontproperties=boldFont)
boldItemFont = find_matplotlib_font(
family="sans serif",
style="italic",
variant="normal",
weight=750,
stretch=500,
size=14)
ax.annotate(
"Bold Italic Font",
(0.1, 0.3),
xycoords='axes fraction',
fontproperties=boldItemFont)
lightFont = find_matplotlib_font(
family="sans-serif",
style="normal",
variant="normal",
weight=200,
stretch=500,
size=14)
ax.annotate(
"Light Font",
(0.1, 0.4),
xycoords='axes fraction',
fontproperties=lightFont)
condensedFont = find_matplotlib_font(
family="sans-serif",
style="normal",
variant="normal",
weight=500,
stretch=100,
size=14)
ax.annotate(
"Condensed Font",
(0.1, 0.5),
xycoords='axes fraction',
fontproperties=condensedFont)
ax.set_xticks([])
ax.set_yticks([])
@image_comparison(baseline_images=['multiline'])
def test_multiline():
plt.figure()
ax = plt.subplot(1, 1, 1)
ax.set_title("multiline\ntext alignment")
plt.text(
0.2, 0.5, "TpTpTp\n$M$\nTpTpTp", size=20, ha="center", va="top")
plt.text(
0.5, 0.5, "TpTpTp\n$M^{M^{M^{M}}}$\nTpTpTp", size=20,
ha="center", va="top")
plt.text(
0.8, 0.5, "TpTpTp\n$M_{q_{q_{q}}}$\nTpTpTp", size=20,
ha="center", va="top")
plt.xlim(0, 1)
plt.ylim(0, 0.8)
ax.set_xticks([])
ax.set_yticks([])
@image_comparison(baseline_images=['antialiased'], extensions=['png'])
def test_antialiasing():
matplotlib.rcParams['text.antialiased'] = True
fig = plt.figure(figsize=(5.25, 0.75))
fig.text(0.5, 0.75, "antialiased", horizontalalignment='center',
verticalalignment='center')
fig.text(0.5, 0.25, r"$\sqrt{x}$", horizontalalignment='center',
verticalalignment='center')
# NOTE: We don't need to restore the rcParams here, because the
# test cleanup will do it for us. In fact, if we do it here, it
# will turn antialiasing back off before the images are actually
# rendered.
def test_afm_kerning():
from matplotlib.afm import AFM
from matplotlib.font_manager import findfont
fn = findfont("Helvetica", fontext="afm")
with open(fn, 'rb') as fh:
afm = AFM(fh)
assert afm.string_width_height('VAVAVAVAVAVA') == (7174.0, 718)
@image_comparison(baseline_images=['text_contains'], extensions=['png'])
def test_contains():
import matplotlib.backend_bases as mbackend
fig = plt.figure()
ax = plt.axes()
mevent = mbackend.MouseEvent(
'button_press_event', fig.canvas, 0.5, 0.5, 1, None)
xs = np.linspace(0.25, 0.75, 30)
ys = np.linspace(0.25, 0.75, 30)
xs, ys = np.meshgrid(xs, ys)
txt = plt.text(
0.48, 0.52, 'hello world', ha='center', fontsize=30, rotation=30)
# uncomment to draw the text's bounding box
# txt.set_bbox(dict(edgecolor='black', facecolor='none'))
# draw the text. This is important, as the contains method can only work
# when a renderer exists.
fig.canvas.draw()
for x, y in zip(xs.flat, ys.flat):
mevent.x, mevent.y = plt.gca().transAxes.transform_point([x, y])
contains, _ = txt.contains(mevent)
color = 'yellow' if contains else 'red'
# capture the viewLim, plot a point, and reset the viewLim
vl = ax.viewLim.frozen()
ax.plot(x, y, 'o', color=color)
ax.viewLim.set(vl)
@image_comparison(baseline_images=['titles'])
def test_titles():
# left and right side titles
plt.figure()
ax = plt.subplot(1, 1, 1)
ax.set_title("left title", loc="left")
ax.set_title("right title", loc="right")
ax.set_xticks([])
ax.set_yticks([])
@image_comparison(baseline_images=['text_alignment'])
def test_alignment():
plt.figure()
ax = plt.subplot(1, 1, 1)
x = 0.1
for rotation in (0, 30):
for alignment in ('top', 'bottom', 'baseline', 'center'):
ax.text(
x, 0.5, alignment + " Tj", va=alignment, rotation=rotation,
bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5))
ax.text(
x, 1.0, r'$\sum_{i=0}^{j}$', va=alignment, rotation=rotation)
x += 0.1
ax.plot([0, 1], [0.5, 0.5])
ax.plot([0, 1], [1.0, 1.0])
ax.set_xlim([0, 1])
ax.set_ylim([0, 1.5])
ax.set_xticks([])
ax.set_yticks([])
@image_comparison(baseline_images=['axes_titles'], extensions=['png'])
def test_axes_titles():
# Related to issue #3327
plt.figure()
ax = plt.subplot(1, 1, 1)
ax.set_title('center', loc='center', fontsize=20, fontweight=700)
ax.set_title('left', loc='left', fontsize=12, fontweight=400)
ax.set_title('right', loc='right', fontsize=12, fontweight=400)
def test_set_position():
fig, ax = plt.subplots()
# test set_position
ann = ax.annotate(
'test', (0, 0), xytext=(0, 0), textcoords='figure pixels')
fig.canvas.draw()
init_pos = ann.get_window_extent(fig.canvas.renderer)
shift_val = 15
ann.set_position((shift_val, shift_val))
fig.canvas.draw()
post_pos = ann.get_window_extent(fig.canvas.renderer)
for a, b in zip(init_pos.min, post_pos.min):
assert a + shift_val == b
# test xyann
ann = ax.annotate(
'test', (0, 0), xytext=(0, 0), textcoords='figure pixels')
fig.canvas.draw()
init_pos = ann.get_window_extent(fig.canvas.renderer)
shift_val = 15
ann.xyann = (shift_val, shift_val)
fig.canvas.draw()
post_pos = ann.get_window_extent(fig.canvas.renderer)
for a, b in zip(init_pos.min, post_pos.min):
assert a + shift_val == b
def test_get_rotation_string():
from matplotlib import text
assert text.get_rotation('horizontal') == 0.
assert text.get_rotation('vertical') == 90.
assert text.get_rotation('15.') == 15.
def test_get_rotation_float():
from matplotlib import text
for i in [15., 16.70, 77.4]:
assert text.get_rotation(i) == i
def test_get_rotation_int():
from matplotlib import text
for i in [67, 16, 41]:
assert text.get_rotation(i) == float(i)
def test_get_rotation_raises():
from matplotlib import text
with pytest.raises(ValueError):
text.get_rotation('hozirontal')
def test_get_rotation_none():
from matplotlib import text
assert text.get_rotation(None) == 0.0
def test_get_rotation_mod360():
from matplotlib import text
for i, j in zip([360., 377., 720+177.2], [0., 17., 177.2]):
assert_almost_equal(text.get_rotation(i), j)
@image_comparison(baseline_images=['text_bboxclip'])
def test_bbox_clipping():
plt.text(0.9, 0.2, 'Is bbox clipped?', backgroundcolor='r', clip_on=True)
t = plt.text(0.9, 0.5, 'Is fancy bbox clipped?', clip_on=True)
t.set_bbox({"boxstyle": "round, pad=0.1"})
@image_comparison(baseline_images=['annotation_negative_ax_coords'],
extensions=['png'])
def test_annotation_negative_ax_coords():
fig, ax = plt.subplots()
ax.annotate('+ pts',
xytext=[30, 20], textcoords='axes points',
xy=[30, 20], xycoords='axes points', fontsize=32)
ax.annotate('- pts',
xytext=[30, -20], textcoords='axes points',
xy=[30, -20], xycoords='axes points', fontsize=32,
va='top')
ax.annotate('+ frac',
xytext=[0.75, 0.05], textcoords='axes fraction',
xy=[0.75, 0.05], xycoords='axes fraction', fontsize=32)
ax.annotate('- frac',
xytext=[0.75, -0.05], textcoords='axes fraction',
xy=[0.75, -0.05], xycoords='axes fraction', fontsize=32,
va='top')
ax.annotate('+ pixels',
xytext=[160, 25], textcoords='axes pixels',
xy=[160, 25], xycoords='axes pixels', fontsize=32)
ax.annotate('- pixels',
xytext=[160, -25], textcoords='axes pixels',
xy=[160, -25], xycoords='axes pixels', fontsize=32,
va='top')
@image_comparison(baseline_images=['annotation_negative_fig_coords'],
extensions=['png'])
def test_annotation_negative_fig_coords():
fig, ax = plt.subplots()
ax.annotate('+ pts',
xytext=[10, 120], textcoords='figure points',
xy=[10, 120], xycoords='figure points', fontsize=32)
ax.annotate('- pts',
xytext=[-10, 180], textcoords='figure points',
xy=[-10, 180], xycoords='figure points', fontsize=32,
va='top')
ax.annotate('+ frac',
xytext=[0.05, 0.55], textcoords='figure fraction',
xy=[0.05, 0.55], xycoords='figure fraction', fontsize=32)
ax.annotate('- frac',
xytext=[-0.05, 0.5], textcoords='figure fraction',
xy=[-0.05, 0.5], xycoords='figure fraction', fontsize=32,
va='top')
ax.annotate('+ pixels',
xytext=[50, 50], textcoords='figure pixels',
xy=[50, 50], xycoords='figure pixels', fontsize=32)
ax.annotate('- pixels',
xytext=[-50, 100], textcoords='figure pixels',
xy=[-50, 100], xycoords='figure pixels', fontsize=32,
va='top')
def test_text_stale():
fig, (ax1, ax2) = plt.subplots(1, 2)
plt.draw_all()
assert not ax1.stale
assert not ax2.stale
assert not fig.stale
txt1 = ax1.text(.5, .5, 'aardvark')
assert ax1.stale
assert txt1.stale
assert fig.stale
ann1 = ax2.annotate('aardvark', xy=[.5, .5])
assert ax2.stale
assert ann1.stale
assert fig.stale
plt.draw_all()
assert not ax1.stale
assert not ax2.stale
assert not fig.stale
@image_comparison(baseline_images=['agg_text_clip'],
extensions=['png'])
def test_agg_text_clip():
np.random.seed(1)
fig, (ax1, ax2) = plt.subplots(2)
for x, y in np.random.rand(10, 2):
ax1.text(x, y, "foo", clip_on=True)
ax2.text(x, y, "foo")
def test_text_size_binding():
from matplotlib.font_manager import FontProperties
matplotlib.rcParams['font.size'] = 10
fp = FontProperties(size='large')
sz1 = fp.get_size_in_points()
matplotlib.rcParams['font.size'] = 100
assert sz1 == fp.get_size_in_points()
@image_comparison(baseline_images=['font_scaling'],
extensions=['pdf'])
def test_font_scaling():
matplotlib.rcParams['pdf.fonttype'] = 42
fig, ax = plt.subplots(figsize=(6.4, 12.4))
ax.xaxis.set_major_locator(plt.NullLocator())
ax.yaxis.set_major_locator(plt.NullLocator())
ax.set_ylim(-10, 600)
for i, fs in enumerate(range(4, 43, 2)):
ax.text(0.1, i*30, "{fs} pt font size".format(fs=fs), fontsize=fs)
@pytest.mark.parametrize('spacing1, spacing2', [(0.4, 2), (2, 0.4), (2, 2)])
def test_two_2line_texts(spacing1, spacing2):
text_string = 'line1\nline2'
fig = plt.figure()
renderer = fig.canvas.get_renderer()
text1 = plt.text(0.25, 0.5, text_string, linespacing=spacing1)
text2 = plt.text(0.25, 0.5, text_string, linespacing=spacing2)
fig.canvas.draw()
box1 = text1.get_window_extent(renderer=renderer)
box2 = text2.get_window_extent(renderer=renderer)
# line spacing only affects height
assert box1.width == box2.width
if (spacing1 == spacing2):
assert box1.height == box2.height
else:
assert box1.height != box2.height
def test_nonfinite_pos():
fig, ax = plt.subplots()
ax.text(0, np.nan, 'nan')
ax.text(np.inf, 0, 'inf')
fig.canvas.draw()
def test_hinting_factor_backends():
plt.rcParams['text.hinting_factor'] = 1
fig = plt.figure()
t = fig.text(0.5, 0.5, 'some text')
fig.savefig(io.BytesIO(), format='svg')
expected = t.get_window_extent().intervalx
fig.savefig(io.BytesIO(), format='png')
# Backends should apply hinting_factor consistently (within 10%).
np.testing.assert_allclose(t.get_window_extent().intervalx, expected,
rtol=0.1)
@needs_usetex
def test_single_artist_usetex():
# Check that a single artist marked with usetex does not get passed through
# the mathtext parser at all (for the Agg backend) (the mathtext parser
# currently fails to parse \frac12, requiring \frac{1}{2} instead).
fig, ax = plt.subplots()
ax.text(.5, .5, r"$\frac12$", usetex=True)
fig.canvas.draw()
| 14,175 | 28.719078 | 79 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_patheffects.py | from __future__ import absolute_import, division, print_function
import numpy as np
import pytest
from matplotlib.testing.decorators import image_comparison
import matplotlib.pyplot as plt
import matplotlib.patheffects as path_effects
@image_comparison(baseline_images=['patheffect1'], remove_text=True)
def test_patheffect1():
ax1 = plt.subplot(111)
ax1.imshow([[1, 2], [2, 3]])
txt = ax1.annotate("test", (1., 1.), (0., 0),
arrowprops=dict(arrowstyle="->",
connectionstyle="angle3", lw=2),
size=20, ha="center",
path_effects=[path_effects.withStroke(linewidth=3,
foreground="w")])
txt.arrow_patch.set_path_effects([path_effects.Stroke(linewidth=5,
foreground="w"),
path_effects.Normal()])
pe = [path_effects.withStroke(linewidth=3, foreground="w")]
ax1.grid(True, linestyle="-", path_effects=pe)
@image_comparison(baseline_images=['patheffect2'], remove_text=True,
style='mpl20')
def test_patheffect2():
ax2 = plt.subplot(111)
arr = np.arange(25).reshape((5, 5))
ax2.imshow(arr)
cntr = ax2.contour(arr, colors="k")
plt.setp(cntr.collections,
path_effects=[path_effects.withStroke(linewidth=3,
foreground="w")])
clbls = ax2.clabel(cntr, fmt="%2.0f", use_clabeltext=True)
plt.setp(clbls,
path_effects=[path_effects.withStroke(linewidth=3,
foreground="w")])
@image_comparison(baseline_images=['patheffect3'])
def test_patheffect3():
p1, = plt.plot([1, 3, 5, 4, 3], 'o-b', lw=4)
p1.set_path_effects([path_effects.SimpleLineShadow(),
path_effects.Normal()])
plt.title(r'testing$^{123}$',
path_effects=[path_effects.withStroke(linewidth=1, foreground="r")])
leg = plt.legend([p1], [r'Line 1$^2$'], fancybox=True, loc=2)
leg.legendPatch.set_path_effects([path_effects.withSimplePatchShadow()])
text = plt.text(2, 3, 'Drop test', color='white',
bbox={'boxstyle': 'circle,pad=0.1', 'color': 'red'})
pe = [path_effects.Stroke(linewidth=3.75, foreground='k'),
path_effects.withSimplePatchShadow((6, -3), shadow_rgbFace='blue')]
text.set_path_effects(pe)
text.get_bbox_patch().set_path_effects(pe)
pe = [path_effects.PathPatchEffect(offset=(4, -4), hatch='xxxx',
facecolor='gray'),
path_effects.PathPatchEffect(edgecolor='white', facecolor='black',
lw=1.1)]
t = plt.gcf().text(0.02, 0.1, 'Hatch shadow', fontsize=75, weight=1000,
va='center')
t.set_path_effects(pe)
@image_comparison(baseline_images=['stroked_text'], extensions=['png'])
def test_patheffects_stroked_text():
text_chunks = [
'A B C D E F G H I J K L',
'M N O P Q R S T U V W',
'X Y Z a b c d e f g h i j',
'k l m n o p q r s t u v',
'w x y z 0123456789',
r"!@#$%^&*()-=_+[]\;'",
',./{}|:"<>?'
]
font_size = 50
ax = plt.axes([0, 0, 1, 1])
for i, chunk in enumerate(text_chunks):
text = ax.text(x=0.01, y=(0.9 - i * 0.13), s=chunk,
fontdict={'ha': 'left', 'va': 'center',
'size': font_size, 'color': 'white'})
text.set_path_effects([path_effects.Stroke(linewidth=font_size / 10,
foreground='black'),
path_effects.Normal()])
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.axis('off')
@pytest.mark.xfail
def test_PathEffect_points_to_pixels():
fig = plt.figure(dpi=150)
p1, = plt.plot(range(10))
p1.set_path_effects([path_effects.SimpleLineShadow(),
path_effects.Normal()])
renderer = fig.canvas.get_renderer()
pe_renderer = path_effects.SimpleLineShadow().get_proxy_renderer(renderer)
assert isinstance(pe_renderer, path_effects.PathEffectRenderer)
# Confirm that using a path effects renderer maintains point sizes
# appropriately. Otherwise rendered font would be the wrong size.
assert renderer.points_to_pixels(15) == pe_renderer.points_to_pixels(15)
def test_SimplePatchShadow_offset():
pe = path_effects.SimplePatchShadow(offset=(4, 5))
assert pe._offset == (4, 5)
@image_comparison(baseline_images=['collection'], tol=0.02)
def test_collection():
x, y = np.meshgrid(np.linspace(0, 10, 150), np.linspace(-5, 5, 100))
data = np.sin(x) + np.cos(y)
cs = plt.contour(data)
pe = [path_effects.PathPatchEffect(edgecolor='black', facecolor='none',
linewidth=12),
path_effects.Stroke(linewidth=5)]
for collection in cs.collections:
collection.set_path_effects(pe)
for text in plt.clabel(cs, colors='white'):
text.set_path_effects([path_effects.withStroke(foreground='k',
linewidth=3)])
text.set_bbox({'boxstyle': 'sawtooth', 'facecolor': 'none',
'edgecolor': 'blue'})
| 5,412 | 37.390071 | 78 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_cbook.py | from __future__ import absolute_import, division, print_function
import itertools
import pickle
from weakref import ref
import warnings
import six
from datetime import datetime
import numpy as np
from numpy.testing.utils import (assert_array_equal, assert_approx_equal,
assert_array_almost_equal)
import pytest
import matplotlib.cbook as cbook
import matplotlib.colors as mcolors
from matplotlib.cbook import delete_masked_points as dmp
def test_is_hashable():
s = 'string'
assert cbook.is_hashable(s)
lst = ['list', 'of', 'stings']
assert not cbook.is_hashable(lst)
def test_restrict_dict():
d = {'foo': 'bar', 1: 2}
with pytest.warns(cbook.deprecation.MatplotlibDeprecationWarning) as rec:
d1 = cbook.restrict_dict(d, ['foo', 1])
assert d1 == d
d2 = cbook.restrict_dict(d, ['bar', 2])
assert d2 == {}
d3 = cbook.restrict_dict(d, {'foo': 1})
assert d3 == {'foo': 'bar'}
d4 = cbook.restrict_dict(d, {})
assert d4 == {}
d5 = cbook.restrict_dict(d, {'foo', 2})
assert d5 == {'foo': 'bar'}
assert len(rec) == 5
# check that d was not modified
assert d == {'foo': 'bar', 1: 2}
class Test_delete_masked_points(object):
def setup_method(self):
self.mask1 = [False, False, True, True, False, False]
self.arr0 = np.arange(1.0, 7.0)
self.arr1 = [1, 2, 3, np.nan, np.nan, 6]
self.arr2 = np.array(self.arr1)
self.arr3 = np.ma.array(self.arr2, mask=self.mask1)
self.arr_s = ['a', 'b', 'c', 'd', 'e', 'f']
self.arr_s2 = np.array(self.arr_s)
self.arr_dt = [datetime(2008, 1, 1), datetime(2008, 1, 2),
datetime(2008, 1, 3), datetime(2008, 1, 4),
datetime(2008, 1, 5), datetime(2008, 1, 6)]
self.arr_dt2 = np.array(self.arr_dt)
self.arr_colors = ['r', 'g', 'b', 'c', 'm', 'y']
self.arr_rgba = mcolors.to_rgba_array(self.arr_colors)
def test_bad_first_arg(self):
with pytest.raises(ValueError):
dmp('a string', self.arr0)
def test_string_seq(self):
actual = dmp(self.arr_s, self.arr1)
ind = [0, 1, 2, 5]
expected = (self.arr_s2.take(ind), self.arr2.take(ind))
assert_array_equal(actual[0], expected[0])
assert_array_equal(actual[1], expected[1])
def test_datetime(self):
actual = dmp(self.arr_dt, self.arr3)
ind = [0, 1, 5]
expected = (self.arr_dt2.take(ind),
self.arr3.take(ind).compressed())
assert_array_equal(actual[0], expected[0])
assert_array_equal(actual[1], expected[1])
def test_rgba(self):
actual = dmp(self.arr3, self.arr_rgba)
ind = [0, 1, 5]
expected = (self.arr3.take(ind).compressed(),
self.arr_rgba.take(ind, axis=0))
assert_array_equal(actual[0], expected[0])
assert_array_equal(actual[1], expected[1])
class Test_boxplot_stats(object):
def setup(self):
np.random.seed(937)
self.nrows = 37
self.ncols = 4
self.data = np.random.lognormal(size=(self.nrows, self.ncols),
mean=1.5, sigma=1.75)
self.known_keys = sorted([
'mean', 'med', 'q1', 'q3', 'iqr',
'cilo', 'cihi', 'whislo', 'whishi',
'fliers', 'label'
])
self.std_results = cbook.boxplot_stats(self.data)
self.known_nonbootstrapped_res = {
'cihi': 6.8161283264444847,
'cilo': -0.1489815330368689,
'iqr': 13.492709959447094,
'mean': 13.00447442387868,
'med': 3.3335733967038079,
'fliers': np.array([
92.55467075, 87.03819018, 42.23204914, 39.29390996
]),
'q1': 1.3597529879465153,
'q3': 14.85246294739361,
'whishi': 27.899688243699629,
'whislo': 0.042143774965502923
}
self.known_bootstrapped_ci = {
'cihi': 8.939577523357828,
'cilo': 1.8692703958676578,
}
self.known_whis3_res = {
'whishi': 42.232049135969874,
'whislo': 0.042143774965502923,
'fliers': np.array([92.55467075, 87.03819018]),
}
self.known_res_percentiles = {
'whislo': 0.1933685896907924,
'whishi': 42.232049135969874
}
self.known_res_range = {
'whislo': 0.042143774965502923,
'whishi': 92.554670752188699
}
def test_form_main_list(self):
assert isinstance(self.std_results, list)
def test_form_each_dict(self):
for res in self.std_results:
assert isinstance(res, dict)
def test_form_dict_keys(self):
for res in self.std_results:
assert set(res) <= set(self.known_keys)
def test_results_baseline(self):
res = self.std_results[0]
for key, value in self.known_nonbootstrapped_res.items():
assert_array_almost_equal(res[key], value)
def test_results_bootstrapped(self):
results = cbook.boxplot_stats(self.data, bootstrap=10000)
res = results[0]
for key, value in self.known_bootstrapped_ci.items():
assert_approx_equal(res[key], value)
def test_results_whiskers_float(self):
results = cbook.boxplot_stats(self.data, whis=3)
res = results[0]
for key, value in self.known_whis3_res.items():
assert_array_almost_equal(res[key], value)
def test_results_whiskers_range(self):
results = cbook.boxplot_stats(self.data, whis='range')
res = results[0]
for key, value in self.known_res_range.items():
assert_array_almost_equal(res[key], value)
def test_results_whiskers_percentiles(self):
results = cbook.boxplot_stats(self.data, whis=[5, 95])
res = results[0]
for key, value in self.known_res_percentiles.items():
assert_array_almost_equal(res[key], value)
def test_results_withlabels(self):
labels = ['Test1', 2, 'ardvark', 4]
results = cbook.boxplot_stats(self.data, labels=labels)
res = results[0]
for lab, res in zip(labels, results):
assert res['label'] == lab
results = cbook.boxplot_stats(self.data)
for res in results:
assert 'label' not in res
def test_label_error(self):
labels = [1, 2]
with pytest.raises(ValueError):
results = cbook.boxplot_stats(self.data, labels=labels)
def test_bad_dims(self):
data = np.random.normal(size=(34, 34, 34))
with pytest.raises(ValueError):
results = cbook.boxplot_stats(data)
def test_boxplot_stats_autorange_false(self):
x = np.zeros(shape=140)
x = np.hstack([-25, x, 25])
bstats_false = cbook.boxplot_stats(x, autorange=False)
bstats_true = cbook.boxplot_stats(x, autorange=True)
assert bstats_false[0]['whislo'] == 0
assert bstats_false[0]['whishi'] == 0
assert_array_almost_equal(bstats_false[0]['fliers'], [-25, 25])
assert bstats_true[0]['whislo'] == -25
assert bstats_true[0]['whishi'] == 25
assert_array_almost_equal(bstats_true[0]['fliers'], [])
class Test_callback_registry(object):
def setup(self):
self.signal = 'test'
self.callbacks = cbook.CallbackRegistry()
def connect(self, s, func):
return self.callbacks.connect(s, func)
def is_empty(self):
assert self.callbacks._func_cid_map == {}
assert self.callbacks.callbacks == {}
def is_not_empty(self):
assert self.callbacks._func_cid_map != {}
assert self.callbacks.callbacks != {}
def test_callback_complete(self):
# ensure we start with an empty registry
self.is_empty()
# create a class for testing
mini_me = Test_callback_registry()
# test that we can add a callback
cid1 = self.connect(self.signal, mini_me.dummy)
assert type(cid1) == int
self.is_not_empty()
# test that we don't add a second callback
cid2 = self.connect(self.signal, mini_me.dummy)
assert cid1 == cid2
self.is_not_empty()
assert len(self.callbacks._func_cid_map) == 1
assert len(self.callbacks.callbacks) == 1
del mini_me
# check we now have no callbacks registered
self.is_empty()
def dummy(self):
pass
def test_pickling(self):
assert hasattr(pickle.loads(pickle.dumps(cbook.CallbackRegistry())),
"callbacks")
def raising_cb_reg(func):
class TestException(Exception):
pass
def raising_function():
raise RuntimeError
def transformer(excp):
if isinstance(excp, RuntimeError):
raise TestException
raise excp
# default behavior
cb = cbook.CallbackRegistry()
cb.connect('foo', raising_function)
# old default
cb_old = cbook.CallbackRegistry(exception_handler=None)
cb_old.connect('foo', raising_function)
# filter
cb_filt = cbook.CallbackRegistry(exception_handler=transformer)
cb_filt.connect('foo', raising_function)
return pytest.mark.parametrize('cb, excp',
[[cb, None],
[cb_old, RuntimeError],
[cb_filt, TestException]])(func)
@raising_cb_reg
def test_callbackregistry_process_exception(cb, excp):
if excp is not None:
with pytest.raises(excp):
cb.process('foo')
else:
cb.process('foo')
def test_sanitize_sequence():
d = {'a': 1, 'b': 2, 'c': 3}
k = ['a', 'b', 'c']
v = [1, 2, 3]
i = [('a', 1), ('b', 2), ('c', 3)]
assert k == sorted(cbook.sanitize_sequence(d.keys()))
assert v == sorted(cbook.sanitize_sequence(d.values()))
assert i == sorted(cbook.sanitize_sequence(d.items()))
assert i == cbook.sanitize_sequence(i)
assert k == cbook.sanitize_sequence(k)
fail_mapping = (
({'a': 1}, {'forbidden': ('a')}),
({'a': 1}, {'required': ('b')}),
({'a': 1, 'b': 2}, {'required': ('a'), 'allowed': ()})
)
warn_passing_mapping = (
({'a': 1, 'b': 2}, {'a': 1}, {'alias_mapping': {'a': ['b']}}, 1),
({'a': 1, 'b': 2}, {'a': 1},
{'alias_mapping': {'a': ['b']}, 'allowed': ('a',)}, 1),
({'a': 1, 'b': 2}, {'a': 2}, {'alias_mapping': {'a': ['a', 'b']}}, 1),
({'a': 1, 'b': 2, 'c': 3}, {'a': 1, 'c': 3},
{'alias_mapping': {'a': ['b']}, 'required': ('a', )}, 1),
)
pass_mapping = (
({'a': 1, 'b': 2}, {'a': 1, 'b': 2}, {}),
({'b': 2}, {'a': 2}, {'alias_mapping': {'a': ['a', 'b']}}),
({'b': 2}, {'a': 2},
{'alias_mapping': {'a': ['b']}, 'forbidden': ('b', )}),
({'a': 1, 'c': 3}, {'a': 1, 'c': 3},
{'required': ('a', ), 'allowed': ('c', )}),
({'a': 1, 'c': 3}, {'a': 1, 'c': 3},
{'required': ('a', 'c'), 'allowed': ('c', )}),
({'a': 1, 'c': 3}, {'a': 1, 'c': 3},
{'required': ('a', 'c'), 'allowed': ('a', 'c')}),
({'a': 1, 'c': 3}, {'a': 1, 'c': 3},
{'required': ('a', 'c'), 'allowed': ()}),
({'a': 1, 'c': 3}, {'a': 1, 'c': 3}, {'required': ('a', 'c')}),
({'a': 1, 'c': 3}, {'a': 1, 'c': 3}, {'allowed': ('a', 'c')}),
)
@pytest.mark.parametrize('inp, kwargs_to_norm', fail_mapping)
def test_normalize_kwargs_fail(inp, kwargs_to_norm):
with pytest.raises(TypeError):
cbook.normalize_kwargs(inp, **kwargs_to_norm)
@pytest.mark.parametrize('inp, expected, kwargs_to_norm, warn_count',
warn_passing_mapping)
def test_normalize_kwargs_warn(inp, expected, kwargs_to_norm, warn_count):
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
assert expected == cbook.normalize_kwargs(inp, **kwargs_to_norm)
assert len(w) == warn_count
@pytest.mark.parametrize('inp, expected, kwargs_to_norm',
pass_mapping)
def test_normalize_kwargs_pass(inp, expected, kwargs_to_norm):
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
assert expected == cbook.normalize_kwargs(inp, **kwargs_to_norm)
assert len(w) == 0
def test_to_prestep():
x = np.arange(4)
y1 = np.arange(4)
y2 = np.arange(4)[::-1]
xs, y1s, y2s = cbook.pts_to_prestep(x, y1, y2)
x_target = np.asarray([0, 0, 1, 1, 2, 2, 3], dtype='float')
y1_target = np.asarray([0, 1, 1, 2, 2, 3, 3], dtype='float')
y2_target = np.asarray([3, 2, 2, 1, 1, 0, 0], dtype='float')
assert_array_equal(x_target, xs)
assert_array_equal(y1_target, y1s)
assert_array_equal(y2_target, y2s)
xs, y1s = cbook.pts_to_prestep(x, y1)
assert_array_equal(x_target, xs)
assert_array_equal(y1_target, y1s)
def test_to_prestep_empty():
steps = cbook.pts_to_prestep([], [])
assert steps.shape == (2, 0)
def test_to_poststep():
x = np.arange(4)
y1 = np.arange(4)
y2 = np.arange(4)[::-1]
xs, y1s, y2s = cbook.pts_to_poststep(x, y1, y2)
x_target = np.asarray([0, 1, 1, 2, 2, 3, 3], dtype='float')
y1_target = np.asarray([0, 0, 1, 1, 2, 2, 3], dtype='float')
y2_target = np.asarray([3, 3, 2, 2, 1, 1, 0], dtype='float')
assert_array_equal(x_target, xs)
assert_array_equal(y1_target, y1s)
assert_array_equal(y2_target, y2s)
xs, y1s = cbook.pts_to_poststep(x, y1)
assert_array_equal(x_target, xs)
assert_array_equal(y1_target, y1s)
def test_to_poststep_empty():
steps = cbook.pts_to_poststep([], [])
assert steps.shape == (2, 0)
def test_to_midstep():
x = np.arange(4)
y1 = np.arange(4)
y2 = np.arange(4)[::-1]
xs, y1s, y2s = cbook.pts_to_midstep(x, y1, y2)
x_target = np.asarray([0, .5, .5, 1.5, 1.5, 2.5, 2.5, 3], dtype='float')
y1_target = np.asarray([0, 0, 1, 1, 2, 2, 3, 3], dtype='float')
y2_target = np.asarray([3, 3, 2, 2, 1, 1, 0, 0], dtype='float')
assert_array_equal(x_target, xs)
assert_array_equal(y1_target, y1s)
assert_array_equal(y2_target, y2s)
xs, y1s = cbook.pts_to_midstep(x, y1)
assert_array_equal(x_target, xs)
assert_array_equal(y1_target, y1s)
def test_to_midstep_empty():
steps = cbook.pts_to_midstep([], [])
assert steps.shape == (2, 0)
@pytest.mark.parametrize(
"args",
[(np.arange(12).reshape(3, 4), 'a'),
(np.arange(12), 'a'),
(np.arange(12), np.arange(3))])
def test_step_fails(args):
with pytest.raises(ValueError):
cbook.pts_to_prestep(*args)
def test_grouper():
class dummy():
pass
a, b, c, d, e = objs = [dummy() for j in range(5)]
g = cbook.Grouper()
g.join(*objs)
assert set(list(g)[0]) == set(objs)
assert set(g.get_siblings(a)) == set(objs)
for other in objs[1:]:
assert g.joined(a, other)
g.remove(a)
for other in objs[1:]:
assert not g.joined(a, other)
for A, B in itertools.product(objs[1:], objs[1:]):
assert g.joined(A, B)
def test_grouper_private():
class dummy():
pass
objs = [dummy() for j in range(5)]
g = cbook.Grouper()
g.join(*objs)
# reach in and touch the internals !
mapping = g._mapping
for o in objs:
assert ref(o) in mapping
base_set = mapping[ref(objs[0])]
for o in objs[1:]:
assert mapping[ref(o)] is base_set
def test_flatiter():
x = np.arange(5)
it = x.flat
assert 0 == next(it)
assert 1 == next(it)
ret = cbook.safe_first_element(it)
assert ret == 0
assert 0 == next(it)
assert 1 == next(it)
class TestFuncParser(object):
x_test = np.linspace(0.01, 0.5, 3)
validstrings = ['linear', 'quadratic', 'cubic', 'sqrt', 'cbrt',
'log', 'log10', 'log2', 'x**{1.5}', 'root{2.5}(x)',
'log{2}(x)',
'log(x+{0.5})', 'log10(x+{0.1})', 'log{2}(x+{0.1})',
'log{2}(x+{0})']
results = [(lambda x: x),
np.square,
(lambda x: x**3),
np.sqrt,
(lambda x: x**(1. / 3)),
np.log,
np.log10,
np.log2,
(lambda x: x**1.5),
(lambda x: x**(1 / 2.5)),
(lambda x: np.log2(x)),
(lambda x: np.log(x + 0.5)),
(lambda x: np.log10(x + 0.1)),
(lambda x: np.log2(x + 0.1)),
(lambda x: np.log2(x))]
bounded_list = [True, True, True, True, True,
False, False, False, True, True,
False,
True, True, True,
False]
@pytest.mark.parametrize("string, func",
zip(validstrings, results),
ids=validstrings)
def test_values(self, string, func):
func_parser = cbook._StringFuncParser(string)
f = func_parser.function
assert_array_almost_equal(f(self.x_test), func(self.x_test))
@pytest.mark.parametrize("string", validstrings, ids=validstrings)
def test_inverse(self, string):
func_parser = cbook._StringFuncParser(string)
f = func_parser.func_info
fdir = f.function
finv = f.inverse
assert_array_almost_equal(finv(fdir(self.x_test)), self.x_test)
@pytest.mark.parametrize("string", validstrings, ids=validstrings)
def test_get_inverse(self, string):
func_parser = cbook._StringFuncParser(string)
finv1 = func_parser.inverse
finv2 = func_parser.func_info.inverse
assert_array_almost_equal(finv1(self.x_test), finv2(self.x_test))
@pytest.mark.parametrize("string, bounded",
zip(validstrings, bounded_list),
ids=validstrings)
def test_bounded(self, string, bounded):
func_parser = cbook._StringFuncParser(string)
b = func_parser.is_bounded_0_1
assert_array_equal(b, bounded)
| 18,146 | 31.005291 | 77 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_sankey.py | from __future__ import absolute_import, division, print_function
from matplotlib.sankey import Sankey
def test_sankey():
# lets just create a sankey instance and check the code runs
sankey = Sankey()
sankey.add()
| 228 | 21.9 | 64 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_style.py | from __future__ import absolute_import, division, print_function
import os
import shutil
import tempfile
import warnings
from collections import OrderedDict
from contextlib import contextmanager
import pytest
import matplotlib as mpl
from matplotlib import pyplot as plt, style
from matplotlib.style.core import USER_LIBRARY_PATHS, STYLE_EXTENSION
import six
PARAM = 'image.cmap'
VALUE = 'pink'
DUMMY_SETTINGS = {PARAM: VALUE}
@contextmanager
def temp_style(style_name, settings=None):
"""Context manager to create a style sheet in a temporary directory."""
if not settings:
settings = DUMMY_SETTINGS
temp_file = '%s.%s' % (style_name, STYLE_EXTENSION)
# Write style settings to file in the temp directory.
tempdir = tempfile.mkdtemp()
with open(os.path.join(tempdir, temp_file), 'w') as f:
for k, v in six.iteritems(settings):
f.write('%s: %s' % (k, v))
# Add temp directory to style path and reload so we can access this style.
USER_LIBRARY_PATHS.append(tempdir)
style.reload_library()
try:
yield
finally:
shutil.rmtree(tempdir)
style.reload_library()
def test_invalid_rc_warning_includes_filename():
SETTINGS = {'foo': 'bar'}
basename = 'basename'
with warnings.catch_warnings(record=True) as warns:
with temp_style(basename, SETTINGS):
# style.reload_library() in temp_style() triggers the warning
pass
for w in warns:
assert basename in str(w.message)
def test_available():
with temp_style('_test_', DUMMY_SETTINGS):
assert '_test_' in style.available
def test_use():
mpl.rcParams[PARAM] = 'gray'
with temp_style('test', DUMMY_SETTINGS):
with style.context('test'):
assert mpl.rcParams[PARAM] == VALUE
@pytest.mark.network
def test_use_url():
with temp_style('test', DUMMY_SETTINGS):
with style.context('https://gist.github.com/adrn/6590261/raw'):
assert mpl.rcParams['axes.facecolor'] == "#adeade"
def test_context():
mpl.rcParams[PARAM] = 'gray'
with temp_style('test', DUMMY_SETTINGS):
with style.context('test'):
assert mpl.rcParams[PARAM] == VALUE
# Check that this value is reset after the exiting the context.
assert mpl.rcParams[PARAM] == 'gray'
def test_context_with_dict():
original_value = 'gray'
other_value = 'blue'
mpl.rcParams[PARAM] = original_value
with style.context({PARAM: other_value}):
assert mpl.rcParams[PARAM] == other_value
assert mpl.rcParams[PARAM] == original_value
def test_context_with_dict_after_namedstyle():
# Test dict after style name where dict modifies the same parameter.
original_value = 'gray'
other_value = 'blue'
mpl.rcParams[PARAM] = original_value
with temp_style('test', DUMMY_SETTINGS):
with style.context(['test', {PARAM: other_value}]):
assert mpl.rcParams[PARAM] == other_value
assert mpl.rcParams[PARAM] == original_value
def test_context_with_dict_before_namedstyle():
# Test dict before style name where dict modifies the same parameter.
original_value = 'gray'
other_value = 'blue'
mpl.rcParams[PARAM] = original_value
with temp_style('test', DUMMY_SETTINGS):
with style.context([{PARAM: other_value}, 'test']):
assert mpl.rcParams[PARAM] == VALUE
assert mpl.rcParams[PARAM] == original_value
def test_context_with_union_of_dict_and_namedstyle():
# Test dict after style name where dict modifies the a different parameter.
original_value = 'gray'
other_param = 'text.usetex'
other_value = True
d = {other_param: other_value}
mpl.rcParams[PARAM] = original_value
mpl.rcParams[other_param] = (not other_value)
with temp_style('test', DUMMY_SETTINGS):
with style.context(['test', d]):
assert mpl.rcParams[PARAM] == VALUE
assert mpl.rcParams[other_param] == other_value
assert mpl.rcParams[PARAM] == original_value
assert mpl.rcParams[other_param] == (not other_value)
def test_context_with_badparam():
original_value = 'gray'
other_value = 'blue'
d = OrderedDict([(PARAM, original_value), ('badparam', None)])
with style.context({PARAM: other_value}):
assert mpl.rcParams[PARAM] == other_value
x = style.context([d])
with pytest.raises(KeyError):
with x:
pass
assert mpl.rcParams[PARAM] == other_value
@pytest.mark.parametrize('equiv_styles',
[('mpl20', 'default'),
('mpl15', 'classic')],
ids=['mpl20', 'mpl15'])
def test_alias(equiv_styles):
rc_dicts = []
for sty in equiv_styles:
with style.context(sty):
rc_dicts.append(dict(mpl.rcParams))
rc_base = rc_dicts[0]
for nm, rc in zip(equiv_styles[1:], rc_dicts[1:]):
assert rc_base == rc
def test_xkcd_no_cm():
assert mpl.rcParams["path.sketch"] is None
plt.xkcd()
assert mpl.rcParams["path.sketch"] == (1, 100, 2)
def test_xkcd_cm():
assert mpl.rcParams["path.sketch"] is None
with plt.xkcd():
assert mpl.rcParams["path.sketch"] == (1, 100, 2)
assert mpl.rcParams["path.sketch"] is None
| 5,299 | 29.635838 | 79 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_path.py | from __future__ import absolute_import, division, print_function
import copy
import numpy as np
from numpy.testing import assert_array_equal
import pytest
from matplotlib.path import Path
from matplotlib.patches import Polygon
from matplotlib.testing.decorators import image_comparison
import matplotlib.pyplot as plt
from matplotlib import transforms
def test_readonly_path():
path = Path.unit_circle()
def modify_vertices():
path.vertices = path.vertices * 2.0
with pytest.raises(AttributeError):
modify_vertices()
def test_point_in_path():
# Test #1787
verts2 = [(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]
path = Path(verts2, closed=True)
points = [(0.5, 0.5), (1.5, 0.5)]
ret = path.contains_points(points)
assert ret.dtype == 'bool'
assert np.all(ret == [True, False])
def test_contains_points_negative_radius():
path = Path.unit_circle()
points = [(0.0, 0.0), (1.25, 0.0), (0.9, 0.9)]
expected = [True, False, False]
result = path.contains_points(points, radius=-0.5)
assert np.all(result == expected)
def test_point_in_path_nan():
box = np.array([[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]])
p = Path(box)
test = np.array([[np.nan, 0.5]])
contains = p.contains_points(test)
assert len(contains) == 1
assert not contains[0]
def test_nonlinear_containment():
fig, ax = plt.subplots()
ax.set(xscale="log", ylim=(0, 1))
polygon = ax.axvspan(1, 10)
assert polygon.get_path().contains_point(
ax.transData.transform_point((5, .5)), ax.transData)
assert not polygon.get_path().contains_point(
ax.transData.transform_point((.5, .5)), ax.transData)
assert not polygon.get_path().contains_point(
ax.transData.transform_point((50, .5)), ax.transData)
@image_comparison(baseline_images=['path_clipping'],
extensions=['svg'], remove_text=True)
def test_path_clipping():
fig = plt.figure(figsize=(6.0, 6.2))
for i, xy in enumerate([
[(200, 200), (200, 350), (400, 350), (400, 200)],
[(200, 200), (200, 350), (400, 350), (400, 100)],
[(200, 100), (200, 350), (400, 350), (400, 100)],
[(200, 100), (200, 415), (400, 350), (400, 100)],
[(200, 100), (200, 415), (400, 415), (400, 100)],
[(200, 415), (400, 415), (400, 100), (200, 100)],
[(400, 415), (400, 100), (200, 100), (200, 415)]]):
ax = fig.add_subplot(4, 2, i+1)
bbox = [0, 140, 640, 260]
ax.set_xlim(bbox[0], bbox[0] + bbox[2])
ax.set_ylim(bbox[1], bbox[1] + bbox[3])
ax.add_patch(Polygon(
xy, facecolor='none', edgecolor='red', closed=True))
@image_comparison(baseline_images=['semi_log_with_zero'], extensions=['png'],
style='mpl20')
def test_log_transform_with_zero():
x = np.arange(-10, 10)
y = (1.0 - 1.0/(x**2+1))**20
fig, ax = plt.subplots()
ax.semilogy(x, y, "-o", lw=15, markeredgecolor='k')
ax.set_ylim(1e-7, 1)
ax.grid(True)
def test_make_compound_path_empty():
# We should be able to make a compound path with no arguments.
# This makes it easier to write generic path based code.
r = Path.make_compound_path()
assert r.vertices.shape == (0, 2)
@image_comparison(baseline_images=['xkcd'], remove_text=True)
def test_xkcd():
np.random.seed(0)
x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)
with plt.xkcd():
fig, ax = plt.subplots()
ax.plot(x, y)
@image_comparison(baseline_images=['marker_paths'], extensions=['pdf'],
remove_text=True)
def test_marker_paths_pdf():
N = 7
plt.errorbar(np.arange(N),
np.ones(N) + 4,
np.ones(N))
plt.xlim(-1, N)
plt.ylim(-1, 7)
@image_comparison(baseline_images=['nan_path'], style='default',
remove_text=True, extensions=['pdf', 'svg', 'eps', 'png'])
def test_nan_isolated_points():
y0 = [0, np.nan, 2, np.nan, 4, 5, 6]
y1 = [np.nan, 7, np.nan, 9, 10, np.nan, 12]
fig, ax = plt.subplots()
ax.plot(y0, '-o')
ax.plot(y1, '-o')
def test_path_no_doubled_point_in_to_polygon():
hand = np.array(
[[1.64516129, 1.16145833],
[1.64516129, 1.59375],
[1.35080645, 1.921875],
[1.375, 2.18229167],
[1.68548387, 1.9375],
[1.60887097, 2.55208333],
[1.68548387, 2.69791667],
[1.76209677, 2.56770833],
[1.83064516, 1.97395833],
[1.89516129, 2.75],
[1.9516129, 2.84895833],
[2.01209677, 2.76041667],
[1.99193548, 1.99479167],
[2.11290323, 2.63020833],
[2.2016129, 2.734375],
[2.25403226, 2.60416667],
[2.14919355, 1.953125],
[2.30645161, 2.36979167],
[2.39112903, 2.36979167],
[2.41532258, 2.1875],
[2.1733871, 1.703125],
[2.07782258, 1.16666667]])
(r0, c0, r1, c1) = (1.0, 1.5, 2.1, 2.5)
poly = Path(np.vstack((hand[:, 1], hand[:, 0])).T, closed=True)
clip_rect = transforms.Bbox([[r0, c0], [r1, c1]])
poly_clipped = poly.clip_to_bbox(clip_rect).to_polygons()[0]
assert np.all(poly_clipped[-2] != poly_clipped[-1])
assert np.all(poly_clipped[-1] == poly_clipped[0])
def test_path_to_polygons():
data = [[10, 10], [20, 20]]
p = Path(data)
assert_array_equal(p.to_polygons(width=40, height=40), [])
assert_array_equal(p.to_polygons(width=40, height=40, closed_only=False),
[data])
assert_array_equal(p.to_polygons(), [])
assert_array_equal(p.to_polygons(closed_only=False), [data])
data = [[10, 10], [20, 20], [30, 30]]
closed_data = [[10, 10], [20, 20], [30, 30], [10, 10]]
p = Path(data)
assert_array_equal(p.to_polygons(width=40, height=40), [closed_data])
assert_array_equal(p.to_polygons(width=40, height=40, closed_only=False),
[data])
assert_array_equal(p.to_polygons(), [closed_data])
assert_array_equal(p.to_polygons(closed_only=False), [data])
def test_path_deepcopy():
# Should not raise any error
verts = [[0, 0], [1, 1]]
codes = [Path.MOVETO, Path.LINETO]
path1 = Path(verts)
path2 = Path(verts, codes)
copy.deepcopy(path1)
copy.deepcopy(path2)
@pytest.mark.parametrize('offset', range(-720, 361, 45))
def test_full_arc(offset):
low = offset
high = 360 + offset
path = Path.arc(low, high)
mins = np.min(path.vertices, axis=0)
maxs = np.max(path.vertices, axis=0)
np.testing.assert_allclose(mins, -1)
assert np.allclose(maxs, 1)
| 6,644 | 29.067873 | 77 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_units.py | from matplotlib.cbook import iterable
import matplotlib.pyplot as plt
from matplotlib.testing.decorators import image_comparison
import matplotlib.units as munits
import numpy as np
import datetime
try:
# mock in python 3.3+
from unittest.mock import MagicMock
except ImportError:
from mock import MagicMock
# Basic class that wraps numpy array and has units
class Quantity(object):
def __init__(self, data, units):
self.magnitude = data
self.units = units
def to(self, new_units):
factors = {('hours', 'seconds'): 3600, ('minutes', 'hours'): 1 / 60,
('minutes', 'seconds'): 60, ('feet', 'miles'): 1 / 5280.,
('feet', 'inches'): 12, ('miles', 'inches'): 12 * 5280}
if self.units != new_units:
mult = factors[self.units, new_units]
return Quantity(mult * self.magnitude, new_units)
else:
return Quantity(self.magnitude, self.units)
def __getattr__(self, attr):
return getattr(self.magnitude, attr)
def __getitem__(self, item):
if iterable(self.magnitude):
return Quantity(self.magnitude[item], self.units)
else:
return Quantity(self.magnitude, self.units)
def __array__(self):
return np.asarray(self.magnitude)
# Tests that the conversion machinery works properly for classes that
# work as a facade over numpy arrays (like pint)
@image_comparison(baseline_images=['plot_pint'],
extensions=['png'], remove_text=False, style='mpl20')
def test_numpy_facade():
# Create an instance of the conversion interface and
# mock so we can check methods called
qc = munits.ConversionInterface()
def convert(value, unit, axis):
if hasattr(value, 'units'):
return value.to(unit).magnitude
elif iterable(value):
try:
return [v.to(unit).magnitude for v in value]
except AttributeError:
return [Quantity(v, axis.get_units()).to(unit).magnitude
for v in value]
else:
return Quantity(value, axis.get_units()).to(unit).magnitude
qc.convert = MagicMock(side_effect=convert)
qc.axisinfo = MagicMock(side_effect=lambda u, a: munits.AxisInfo(label=u))
qc.default_units = MagicMock(side_effect=lambda x, a: x.units)
# Register the class
munits.registry[Quantity] = qc
# Simple test
y = Quantity(np.linspace(0, 30), 'miles')
x = Quantity(np.linspace(0, 5), 'hours')
fig, ax = plt.subplots()
fig.subplots_adjust(left=0.15) # Make space for label
ax.plot(x, y, 'tab:blue')
ax.axhline(Quantity(26400, 'feet'), color='tab:red')
ax.axvline(Quantity(120, 'minutes'), color='tab:green')
ax.yaxis.set_units('inches')
ax.xaxis.set_units('seconds')
assert qc.convert.called
assert qc.axisinfo.called
assert qc.default_units.called
# Tests gh-8908
@image_comparison(baseline_images=['plot_masked_units'],
extensions=['png'], remove_text=True, style='mpl20')
def test_plot_masked_units():
data = np.linspace(-5, 5)
data_masked = np.ma.array(data, mask=(data > -2) & (data < 2))
data_masked_units = Quantity(data_masked, 'meters')
fig, ax = plt.subplots()
ax.plot(data_masked_units)
@image_comparison(baseline_images=['jpl_bar_units'], extensions=['png'],
savefig_kwarg={'dpi': 120}, style='mpl20')
def test_jpl_bar_units():
from datetime import datetime
import matplotlib.testing.jpl_units as units
units.register()
day = units.Duration("ET", 24.0 * 60.0 * 60.0)
x = [0*units.km, 1*units.km, 2*units.km]
w = [1*day, 2*day, 3*day]
b = units.Epoch("ET", dt=datetime(2009, 4, 25))
fig, ax = plt.subplots()
ax.bar(x, w, bottom=b)
ax.set_ylim([b-1*day, b+w[-1]+1*day])
@image_comparison(baseline_images=['jpl_barh_units'], extensions=['png'],
savefig_kwarg={'dpi': 120}, style='mpl20')
def test_jpl_barh_units():
from datetime import datetime
import matplotlib.testing.jpl_units as units
units.register()
day = units.Duration("ET", 24.0 * 60.0 * 60.0)
x = [0*units.km, 1*units.km, 2*units.km]
w = [1*day, 2*day, 3*day]
b = units.Epoch("ET", dt=datetime(2009, 4, 25))
fig, ax = plt.subplots()
ax.barh(x, w, left=b)
ax.set_xlim([b-1*day, b+w[-1]+1*day])
| 4,425 | 32.278195 | 78 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_marker.py | import numpy as np
from matplotlib import markers
import pytest
def test_markers_valid():
marker_style = markers.MarkerStyle()
mrk_array = np.array([[-0.5, 0],
[0.5, 0]])
# Checking this doesn't fail.
marker_style.set_marker(mrk_array)
def test_markers_invalid():
marker_style = markers.MarkerStyle()
mrk_array = np.array([[-0.5, 0, 1, 2, 3]])
# Checking this does fail.
with pytest.raises(ValueError):
marker_style.set_marker(mrk_array)
| 509 | 23.285714 | 46 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/tests/test_backend_qt4.py | from __future__ import absolute_import, division, print_function
from matplotlib import pyplot as plt
from matplotlib._pylab_helpers import Gcf
import matplotlib
import copy
import pytest
try:
# mock in python 3.3+
from unittest import mock
except ImportError:
import mock
with matplotlib.rc_context(rc={'backend': 'Qt4Agg'}):
qt_compat = pytest.importorskip('matplotlib.backends.qt_compat')
from matplotlib.backends.backend_qt4 import (
MODIFIER_KEYS, SUPER, ALT, CTRL, SHIFT) # noqa
QtCore = qt_compat.QtCore
_, ControlModifier, ControlKey = MODIFIER_KEYS[CTRL]
_, AltModifier, AltKey = MODIFIER_KEYS[ALT]
_, SuperModifier, SuperKey = MODIFIER_KEYS[SUPER]
_, ShiftModifier, ShiftKey = MODIFIER_KEYS[SHIFT]
try:
py_qt_ver = int(QtCore.PYQT_VERSION_STR.split('.')[0])
except AttributeError:
py_qt_ver = QtCore.__version_info__[0]
if py_qt_ver != 4:
pytestmark = pytest.mark.xfail(reason='Qt4 is not available')
@pytest.mark.backend('Qt4Agg')
def test_fig_close():
# save the state of Gcf.figs
init_figs = copy.copy(Gcf.figs)
# make a figure using pyplot interface
fig = plt.figure()
# simulate user clicking the close button by reaching in
# and calling close on the underlying Qt object
fig.canvas.manager.window.close()
# assert that we have removed the reference to the FigureManager
# that got added by plt.figure()
assert init_figs == Gcf.figs
@pytest.mark.parametrize(
'qt_key, qt_mods, answer',
[
(QtCore.Qt.Key_A, ShiftModifier, 'A'),
(QtCore.Qt.Key_A, QtCore.Qt.NoModifier, 'a'),
(QtCore.Qt.Key_A, ControlModifier, 'ctrl+a'),
(QtCore.Qt.Key_Aacute, ShiftModifier,
'\N{LATIN CAPITAL LETTER A WITH ACUTE}'),
(QtCore.Qt.Key_Aacute, QtCore.Qt.NoModifier,
'\N{LATIN SMALL LETTER A WITH ACUTE}'),
(ControlKey, AltModifier, 'alt+control'),
(AltKey, ControlModifier, 'ctrl+alt'),
(QtCore.Qt.Key_Aacute, (ControlModifier | AltModifier | SuperModifier),
'ctrl+alt+super+\N{LATIN SMALL LETTER A WITH ACUTE}'),
(QtCore.Qt.Key_Backspace, QtCore.Qt.NoModifier, 'backspace'),
(QtCore.Qt.Key_Backspace, ControlModifier, 'ctrl+backspace'),
(QtCore.Qt.Key_Play, QtCore.Qt.NoModifier, None),
],
ids=[
'shift',
'lower',
'control',
'unicode_upper',
'unicode_lower',
'alt_control',
'control_alt',
'modifier_order',
'backspace',
'backspace_mod',
'non_unicode_key',
]
)
@pytest.mark.backend('Qt4Agg')
def test_correct_key(qt_key, qt_mods, answer):
"""
Make a figure
Send a key_press_event event (using non-public, qt4 backend specific api)
Catch the event
Assert sent and caught keys are the same
"""
qt_canvas = plt.figure().canvas
event = mock.Mock()
event.isAutoRepeat.return_value = False
event.key.return_value = qt_key
event.modifiers.return_value = qt_mods
def receive(event):
assert event.key == answer
qt_canvas.mpl_connect('key_press_event', receive)
qt_canvas.keyPressEvent(event)
| 3,153 | 29.326923 | 79 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/cbook/_backports.py | from __future__ import absolute_import
import os
import sys
import numpy as np
# Copy-pasted from Python 3.4's shutil.
def which(cmd, mode=os.F_OK | os.X_OK, path=None):
"""Given a command, mode, and a PATH string, return the path which
conforms to the given mode on the PATH, or None if there is no such
file.
`mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
of os.environ.get("PATH"), or can be overridden with a custom search
path.
"""
# Check that a given file can be accessed with the correct mode.
# Additionally check that `file` is not a directory, as on Windows
# directories pass the os.access check.
def _access_check(fn, mode):
return (os.path.exists(fn) and os.access(fn, mode)
and not os.path.isdir(fn))
# If we're given a path with a directory part, look it up directly rather
# than referring to PATH directories. This includes checking relative to the
# current directory, e.g. ./script
if os.path.dirname(cmd):
if _access_check(cmd, mode):
return cmd
return None
if path is None:
path = os.environ.get("PATH", os.defpath)
if not path:
return None
path = path.split(os.pathsep)
if sys.platform == "win32":
# The current directory takes precedence on Windows.
if not os.curdir in path:
path.insert(0, os.curdir)
# PATHEXT is necessary to check on Windows.
pathext = os.environ.get("PATHEXT", "").split(os.pathsep)
# See if the given file matches any of the expected path extensions.
# This will allow us to short circuit when given "python.exe".
# If it does match, only test that one, otherwise we have to try
# others.
if any(cmd.lower().endswith(ext.lower()) for ext in pathext):
files = [cmd]
else:
files = [cmd + ext for ext in pathext]
else:
# On other platforms you don't have things like PATHEXT to tell you
# what file suffixes are executable, so just pass on cmd as-is.
files = [cmd]
seen = set()
for dir in path:
normdir = os.path.normcase(dir)
if not normdir in seen:
seen.add(normdir)
for thefile in files:
name = os.path.join(dir, thefile)
if _access_check(name, mode):
return name
return None
# Copy-pasted from numpy.lib.stride_tricks 1.11.2.
def _maybe_view_as_subclass(original_array, new_array):
if type(original_array) is not type(new_array):
# if input was an ndarray subclass and subclasses were OK,
# then view the result as that subclass.
new_array = new_array.view(type=type(original_array))
# Since we have done something akin to a view from original_array, we
# should let the subclass finalize (if it has it implemented, i.e., is
# not None).
if new_array.__array_finalize__:
new_array.__array_finalize__(original_array)
return new_array
# Copy-pasted from numpy.lib.stride_tricks 1.11.2.
def _broadcast_to(array, shape, subok, readonly):
shape = tuple(shape) if np.iterable(shape) else (shape,)
array = np.array(array, copy=False, subok=subok)
if not shape and array.shape:
raise ValueError('cannot broadcast a non-scalar to a scalar array')
if any(size < 0 for size in shape):
raise ValueError('all elements of broadcast shape must be non-'
'negative')
needs_writeable = not readonly and array.flags.writeable
extras = ['reduce_ok'] if needs_writeable else []
op_flag = 'readwrite' if needs_writeable else 'readonly'
broadcast = np.nditer(
(array,), flags=['multi_index', 'refs_ok', 'zerosize_ok'] + extras,
op_flags=[op_flag], itershape=shape, order='C').itviews[0]
result = _maybe_view_as_subclass(array, broadcast)
if needs_writeable and not result.flags.writeable:
result.flags.writeable = True
return result
# Copy-pasted from numpy.lib.stride_tricks 1.11.2.
def broadcast_to(array, shape, subok=False):
"""Broadcast an array to a new shape.
Parameters
----------
array : array_like
The array to broadcast.
shape : tuple
The shape of the desired array.
subok : bool, optional
If True, then sub-classes will be passed-through, otherwise
the returned array will be forced to be a base-class array (default).
Returns
-------
broadcast : array
A readonly view on the original array with the given shape. It is
typically not contiguous. Furthermore, more than one element of a
broadcasted array may refer to a single memory location.
Raises
------
ValueError
If the array is not compatible with the new shape according to NumPy's
broadcasting rules.
Notes
-----
.. versionadded:: 1.10.0
Examples
--------
>>> x = np.array([1, 2, 3])
>>> np.broadcast_to(x, (3, 3))
array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])
"""
return _broadcast_to(array, shape, subok=subok, readonly=True)
| 5,218 | 34.263514 | 80 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/cbook/deprecation.py | import functools
import textwrap
import warnings
class MatplotlibDeprecationWarning(UserWarning):
"""
A class for issuing deprecation warnings for Matplotlib users.
In light of the fact that Python builtin DeprecationWarnings are ignored
by default as of Python 2.7 (see link below), this class was put in to
allow for the signaling of deprecation, but via UserWarnings which are not
ignored by default.
https://docs.python.org/dev/whatsnew/2.7.html#the-future-for-python-2-x
"""
pass
mplDeprecation = MatplotlibDeprecationWarning
def _generate_deprecation_message(since, message='', name='',
alternative='', pending=False,
obj_type='attribute',
addendum=''):
if not message:
if pending:
message = (
'The %(name)s %(obj_type)s will be deprecated in a '
'future version.')
else:
message = (
'The %(name)s %(obj_type)s was deprecated in version '
'%(since)s.')
altmessage = ''
if alternative:
altmessage = ' Use %s instead.' % alternative
message = ((message % {
'func': name,
'name': name,
'alternative': alternative,
'obj_type': obj_type,
'since': since}) +
altmessage)
if addendum:
message += addendum
return message
def warn_deprecated(
since, message='', name='', alternative='', pending=False,
obj_type='attribute', addendum=''):
"""
Used to 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,
and `%(alternative)s` may be used in the deprecation message
to insert the name of an alternative to the deprecated
function. `%(obj_type)s` may be used to insert a friendly name
for the type of object being deprecated.
name : str, optional
The name of the deprecated object.
alternative : str, optional
An alternative function that the user may use in place of the
deprecated function. The deprecation warning will tell the user
about this alternative if provided.
pending : bool, optional
If True, uses a PendingDeprecationWarning instead of a
DeprecationWarning.
obj_type : str, optional
The object type being deprecated.
addendum : str, optional
Additional text appended directly to the final message.
Examples
--------
Basic example::
# To warn of the deprecation of "matplotlib.name_of_module"
warn_deprecated('1.4.0', name='matplotlib.name_of_module',
obj_type='module')
"""
message = _generate_deprecation_message(
since, message, name, alternative, pending, obj_type)
warnings.warn(message, mplDeprecation, stacklevel=1)
def deprecated(since, message='', name='', alternative='', pending=False,
obj_type=None, addendum=''):
"""
Decorator to 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 the object,
and `%(alternative)s` may be used in the deprecation message
to insert the name of an alternative to the deprecated
object. `%(obj_type)s` may be used to insert a friendly name
for the type of object being deprecated.
name : str, optional
The name of the deprecated object; if not provided the name
is automatically determined from the passed in object,
though this is useful in the case of renamed functions, where
the new function is just assigned to the name of the
deprecated function. For example::
def new_function():
...
oldFunction = new_function
alternative : str, optional
An alternative object that the user may use in place of the
deprecated object. The deprecation warning will tell the user
about this alternative if provided.
pending : bool, optional
If True, uses a PendingDeprecationWarning instead of a
DeprecationWarning.
addendum : str, optional
Additional text appended directly to the final message.
Examples
--------
Basic example::
@deprecated('1.4.0')
def the_function_to_deprecate():
pass
"""
def deprecate(obj, message=message, name=name, alternative=alternative,
pending=pending, addendum=addendum):
if not name:
name = obj.__name__
if isinstance(obj, type):
obj_type = "class"
old_doc = obj.__doc__
func = obj.__init__
def finalize(wrapper, new_doc):
try:
obj.__doc__ = new_doc
except (AttributeError, TypeError):
# cls.__doc__ is not writeable on Py2.
# TypeError occurs on PyPy
pass
obj.__init__ = wrapper
return obj
else:
obj_type = "function"
if isinstance(obj, classmethod):
func = obj.__func__
old_doc = func.__doc__
def finalize(wrapper, new_doc):
wrapper = functools.wraps(func)(wrapper)
wrapper.__doc__ = new_doc
return classmethod(wrapper)
else:
func = obj
old_doc = func.__doc__
def finalize(wrapper, new_doc):
wrapper = functools.wraps(func)(wrapper)
wrapper.__doc__ = new_doc
return wrapper
message = _generate_deprecation_message(
since, message, name, alternative, pending,
obj_type, addendum)
def wrapper(*args, **kwargs):
warnings.warn(message, mplDeprecation, stacklevel=2)
return func(*args, **kwargs)
old_doc = textwrap.dedent(old_doc or '').strip('\n')
message = message.strip()
new_doc = (('\n.. deprecated:: %(since)s'
'\n %(message)s\n\n' %
{'since': since, 'message': message}) + old_doc)
if not old_doc:
# This is to prevent a spurious 'unexected unindent' warning from
# docutils when the original docstring was blank.
new_doc += r'\ '
return finalize(wrapper, new_doc)
return deprecate
| 7,068 | 30.699552 | 78 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/cbook/__init__.py | """
A collection of utility functions and classes. Originally, many
(but not all) were from the Python Cookbook -- hence the name cbook.
This module is safe to import from anywhere within matplotlib;
it imports matplotlib only at runtime.
"""
from __future__ import absolute_import, division, print_function
import six
from six.moves import xrange, zip
import bz2
import collections
import contextlib
import datetime
import errno
import functools
import glob
import gzip
import io
from itertools import repeat
import locale
import numbers
import operator
import os
import re
import sys
import time
import traceback
import types
import warnings
from weakref import ref, WeakKeyDictionary
import numpy as np
import matplotlib
from .deprecation import deprecated, warn_deprecated
from .deprecation import mplDeprecation, MatplotlibDeprecationWarning
def unicode_safe(s):
if isinstance(s, bytes):
try:
# On some systems, locale.getpreferredencoding returns None,
# which can break unicode; and the sage project reports that
# some systems have incorrect locale specifications, e.g.,
# an encoding instead of a valid locale name. Another
# pathological case that has been reported is an empty string.
# On some systems, getpreferredencoding sets the locale, which has
# side effects. Passing False eliminates those side effects.
preferredencoding = locale.getpreferredencoding(
matplotlib.rcParams['axes.formatter.use_locale']).strip()
if not preferredencoding:
preferredencoding = None
except (ValueError, ImportError, AttributeError):
preferredencoding = None
if preferredencoding is None:
return six.text_type(s)
else:
return six.text_type(s, preferredencoding)
return s
@deprecated('2.1')
class converter(object):
"""
Base class for handling string -> python type with support for
missing values
"""
def __init__(self, missing='Null', missingval=None):
self.missing = missing
self.missingval = missingval
def __call__(self, s):
if s == self.missing:
return self.missingval
return s
def is_missing(self, s):
return not s.strip() or s == self.missing
@deprecated('2.1')
class tostr(converter):
"""convert to string or None"""
def __init__(self, missing='Null', missingval=''):
converter.__init__(self, missing=missing, missingval=missingval)
@deprecated('2.1')
class todatetime(converter):
"""convert to a datetime or None"""
def __init__(self, fmt='%Y-%m-%d', missing='Null', missingval=None):
'use a :func:`time.strptime` format string for conversion'
converter.__init__(self, missing, missingval)
self.fmt = fmt
def __call__(self, s):
if self.is_missing(s):
return self.missingval
tup = time.strptime(s, self.fmt)
return datetime.datetime(*tup[:6])
@deprecated('2.1')
class todate(converter):
"""convert to a date or None"""
def __init__(self, fmt='%Y-%m-%d', missing='Null', missingval=None):
"""use a :func:`time.strptime` format string for conversion"""
converter.__init__(self, missing, missingval)
self.fmt = fmt
def __call__(self, s):
if self.is_missing(s):
return self.missingval
tup = time.strptime(s, self.fmt)
return datetime.date(*tup[:3])
@deprecated('2.1')
class tofloat(converter):
"""convert to a float or None"""
def __init__(self, missing='Null', missingval=None):
converter.__init__(self, missing)
self.missingval = missingval
def __call__(self, s):
if self.is_missing(s):
return self.missingval
return float(s)
@deprecated('2.1')
class toint(converter):
"""convert to an int or None"""
def __init__(self, missing='Null', missingval=None):
converter.__init__(self, missing)
def __call__(self, s):
if self.is_missing(s):
return self.missingval
return int(s)
class _BoundMethodProxy(object):
"""
Our own proxy object which enables weak references to bound and unbound
methods and arbitrary callables. Pulls information about the function,
class, and instance out of a bound method. Stores a weak reference to the
instance to support garbage collection.
@organization: IBM Corporation
@copyright: Copyright (c) 2005, 2006 IBM Corporation
@license: The BSD License
Minor bugfixes by Michael Droettboom
"""
def __init__(self, cb):
self._hash = hash(cb)
self._destroy_callbacks = []
try:
try:
if six.PY3:
self.inst = ref(cb.__self__, self._destroy)
else:
self.inst = ref(cb.im_self, self._destroy)
except TypeError:
self.inst = None
if six.PY3:
self.func = cb.__func__
self.klass = cb.__self__.__class__
else:
self.func = cb.im_func
self.klass = cb.im_class
except AttributeError:
self.inst = None
self.func = cb
self.klass = None
def add_destroy_callback(self, callback):
self._destroy_callbacks.append(_BoundMethodProxy(callback))
def _destroy(self, wk):
for callback in self._destroy_callbacks:
try:
callback(self)
except ReferenceError:
pass
def __getstate__(self):
d = self.__dict__.copy()
# de-weak reference inst
inst = d['inst']
if inst is not None:
d['inst'] = inst()
return d
def __setstate__(self, statedict):
self.__dict__ = statedict
inst = statedict['inst']
# turn inst back into a weakref
if inst is not None:
self.inst = ref(inst)
def __call__(self, *args, **kwargs):
"""
Proxy for a call to the weak referenced object. Take
arbitrary params to pass to the callable.
Raises `ReferenceError`: When the weak reference refers to
a dead object
"""
if self.inst is not None and self.inst() is None:
raise ReferenceError
elif self.inst is not None:
# build a new instance method with a strong reference to the
# instance
mtd = types.MethodType(self.func, self.inst())
else:
# not a bound method, just return the func
mtd = self.func
# invoke the callable and return the result
return mtd(*args, **kwargs)
def __eq__(self, other):
"""
Compare the held function and instance with that held by
another proxy.
"""
try:
if self.inst is None:
return self.func == other.func and other.inst is None
else:
return self.func == other.func and self.inst() == other.inst()
except Exception:
return False
def __ne__(self, other):
"""
Inverse of __eq__.
"""
return not self.__eq__(other)
def __hash__(self):
return self._hash
def _exception_printer(exc):
traceback.print_exc()
class CallbackRegistry(object):
"""Handle registering and disconnecting for a set of signals and callbacks:
>>> def oneat(x):
... print('eat', x)
>>> def ondrink(x):
... print('drink', x)
>>> from matplotlib.cbook import CallbackRegistry
>>> callbacks = CallbackRegistry()
>>> id_eat = callbacks.connect('eat', oneat)
>>> id_drink = callbacks.connect('drink', ondrink)
>>> callbacks.process('drink', 123)
drink 123
>>> callbacks.process('eat', 456)
eat 456
>>> callbacks.process('be merry', 456) # nothing will be called
>>> callbacks.disconnect(id_eat)
>>> callbacks.process('eat', 456) # nothing will be called
In practice, one should always disconnect all callbacks when they
are no longer needed to avoid dangling references (and thus memory
leaks). However, real code in matplotlib rarely does so, and due
to its design, it is rather difficult to place this kind of code.
To get around this, and prevent this class of memory leaks, we
instead store weak references to bound methods only, so when the
destination object needs to die, the CallbackRegistry won't keep
it alive. The Python stdlib weakref module can not create weak
references to bound methods directly, so we need to create a proxy
object to handle weak references to bound methods (or regular free
functions). This technique was shared by Peter Parente on his
`"Mindtrove" blog
<http://mindtrove.info/python-weak-references/>`_.
Parameters
----------
exception_handler : callable, optional
If provided must have signature ::
def handler(exc: Exception) -> None:
If not None this function will be called with any `Exception`
subclass raised by the callbacks in `CallbackRegistry.process`.
The handler may either consume the exception or re-raise.
The callable must be pickle-able.
The default handler is ::
def h(exc):
traceback.print_exc()
"""
def __init__(self, exception_handler=_exception_printer):
self.exception_handler = exception_handler
self.callbacks = dict()
self._cid = 0
self._func_cid_map = {}
# In general, callbacks may not be pickled; thus, we simply recreate an
# empty dictionary at unpickling. In order to ensure that `__setstate__`
# (which just defers to `__init__`) is called, `__getstate__` must
# return a truthy value (for pickle protocol>=3, i.e. Py3, the
# *actual* behavior is that `__setstate__` will be called as long as
# `__getstate__` does not return `None`, but this is undocumented -- see
# http://bugs.python.org/issue12290).
def __getstate__(self):
return {'exception_handler': self.exception_handler}
def __setstate__(self, state):
self.__init__(**state)
def connect(self, s, func):
"""Register *func* to be called when signal *s* is generated.
"""
self._func_cid_map.setdefault(s, WeakKeyDictionary())
# Note proxy not needed in python 3.
# TODO rewrite this when support for python2.x gets dropped.
proxy = _BoundMethodProxy(func)
if proxy in self._func_cid_map[s]:
return self._func_cid_map[s][proxy]
proxy.add_destroy_callback(self._remove_proxy)
self._cid += 1
cid = self._cid
self._func_cid_map[s][proxy] = cid
self.callbacks.setdefault(s, dict())
self.callbacks[s][cid] = proxy
return cid
def _remove_proxy(self, proxy):
for signal, proxies in list(six.iteritems(self._func_cid_map)):
try:
del self.callbacks[signal][proxies[proxy]]
except KeyError:
pass
if len(self.callbacks[signal]) == 0:
del self.callbacks[signal]
del self._func_cid_map[signal]
def disconnect(self, cid):
"""Disconnect the callback registered with callback id *cid*.
"""
for eventname, callbackd in list(six.iteritems(self.callbacks)):
try:
del callbackd[cid]
except KeyError:
continue
else:
for signal, functions in list(
six.iteritems(self._func_cid_map)):
for function, value in list(six.iteritems(functions)):
if value == cid:
del functions[function]
return
def process(self, s, *args, **kwargs):
"""
Process signal *s*.
All of the functions registered to receive callbacks on *s* will be
called with ``*args`` and ``**kwargs``.
"""
if s in self.callbacks:
for cid, proxy in list(six.iteritems(self.callbacks[s])):
try:
proxy(*args, **kwargs)
except ReferenceError:
self._remove_proxy(proxy)
# this does not capture KeyboardInterrupt, SystemExit,
# and GeneratorExit
except Exception as exc:
if self.exception_handler is not None:
self.exception_handler(exc)
else:
raise
class silent_list(list):
"""
override repr when returning a list of matplotlib artists to
prevent long, meaningless output. This is meant to be used for a
homogeneous list of a given type
"""
def __init__(self, type, seq=None):
self.type = type
if seq is not None:
self.extend(seq)
def __repr__(self):
return '<a list of %d %s objects>' % (len(self), self.type)
def __str__(self):
return repr(self)
def __getstate__(self):
# store a dictionary of this SilentList's state
return {'type': self.type, 'seq': self[:]}
def __setstate__(self, state):
self.type = state['type']
self.extend(state['seq'])
class IgnoredKeywordWarning(UserWarning):
"""
A class for issuing warnings about keyword arguments that will be ignored
by matplotlib
"""
pass
def local_over_kwdict(local_var, kwargs, *keys):
"""
Enforces the priority of a local variable over potentially conflicting
argument(s) from a kwargs dict. The following possible output values are
considered in order of priority:
local_var > kwargs[keys[0]] > ... > kwargs[keys[-1]]
The first of these whose value is not None will be returned. If all are
None then None will be returned. Each key in keys will be removed from the
kwargs dict in place.
Parameters
----------
local_var: any object
The local variable (highest priority)
kwargs: dict
Dictionary of keyword arguments; modified in place
keys: str(s)
Name(s) of keyword arguments to process, in descending order of
priority
Returns
-------
out: any object
Either local_var or one of kwargs[key] for key in keys
Raises
------
IgnoredKeywordWarning
For each key in keys that is removed from kwargs but not used as
the output value
"""
out = local_var
for key in keys:
kwarg_val = kwargs.pop(key, None)
if kwarg_val is not None:
if out is None:
out = kwarg_val
else:
warnings.warn('"%s" keyword argument will be ignored' % key,
IgnoredKeywordWarning)
return out
def strip_math(s):
"""remove latex formatting from mathtext"""
remove = (r'\mathdefault', r'\rm', r'\cal', r'\tt', r'\it', '\\', '{', '}')
s = s[1:-1]
for r in remove:
s = s.replace(r, '')
return s
class Bunch(object):
"""
Often we want to just collect a bunch of stuff together, naming each
item of the bunch; a dictionary's OK for that, but a small do- nothing
class is even handier, and prettier to use. Whenever you want to
group a few variables::
>>> point = Bunch(datum=2, squared=4, coord=12)
>>> point.datum
By: Alex Martelli
From: https://code.activestate.com/recipes/121294/
"""
def __init__(self, **kwds):
self.__dict__.update(kwds)
def __repr__(self):
return 'Bunch(%s)' % ', '.join(
'%s=%s' % kv for kv in six.iteritems(vars(self)))
@deprecated('2.1')
def unique(x):
"""Return a list of unique elements of *x*"""
return list(set(x))
def iterable(obj):
"""return true if *obj* is iterable"""
try:
iter(obj)
except TypeError:
return False
return True
@deprecated('2.1')
def is_string_like(obj):
"""Return True if *obj* looks like a string"""
# (np.str_ == np.unicode_ on Py3).
return isinstance(obj, (six.string_types, np.str_, np.unicode_))
@deprecated('2.1')
def is_sequence_of_strings(obj):
"""Returns true if *obj* is iterable and contains strings"""
if not iterable(obj):
return False
if is_string_like(obj) and not isinstance(obj, np.ndarray):
try:
obj = obj.values
except AttributeError:
# not pandas
return False
for o in obj:
if not is_string_like(o):
return False
return True
def is_hashable(obj):
"""Returns true if *obj* can be hashed"""
try:
hash(obj)
except TypeError:
return False
return True
def is_writable_file_like(obj):
"""return true if *obj* looks like a file object with a *write* method"""
return callable(getattr(obj, 'write', None))
def file_requires_unicode(x):
"""
Returns `True` if the given writable file-like object requires Unicode
to be written to it.
"""
try:
x.write(b'')
except TypeError:
return True
else:
return False
@deprecated('2.1')
def is_scalar(obj):
"""return true if *obj* is not string like and is not iterable"""
return not isinstance(obj, six.string_types) and not iterable(obj)
def is_numlike(obj):
"""return true if *obj* looks like a number"""
return isinstance(obj, (numbers.Number, np.number))
def to_filehandle(fname, flag='rU', return_opened=False, encoding=None):
"""
*fname* can be an `os.PathLike` or a file handle. Support for gzipped
files is automatic, if the filename ends in .gz. *flag* is a
read/write flag for :func:`file`
"""
if hasattr(os, "PathLike") and isinstance(fname, os.PathLike):
return to_filehandle(
os.fspath(fname),
flag=flag, return_opened=return_opened, encoding=encoding)
if isinstance(fname, six.string_types):
if fname.endswith('.gz'):
# get rid of 'U' in flag for gzipped files.
flag = flag.replace('U', '')
fh = gzip.open(fname, flag)
elif fname.endswith('.bz2'):
# get rid of 'U' in flag for bz2 files
flag = flag.replace('U', '')
fh = bz2.BZ2File(fname, flag)
else:
fh = io.open(fname, flag, encoding=encoding)
opened = True
elif hasattr(fname, 'seek'):
fh = fname
opened = False
else:
raise ValueError('fname must be a PathLike or file handle')
if return_opened:
return fh, opened
return fh
@contextlib.contextmanager
def open_file_cm(path_or_file, mode="r", encoding=None):
r"""Pass through file objects and context-manage `.PathLike`\s."""
fh, opened = to_filehandle(path_or_file, mode, True, encoding)
if opened:
with fh:
yield fh
else:
yield fh
def is_scalar_or_string(val):
"""Return whether the given object is a scalar or string like."""
return isinstance(val, six.string_types) or not iterable(val)
def _string_to_bool(s):
"""Parses the string argument as a boolean"""
if not isinstance(s, six.string_types):
return bool(s)
warn_deprecated("2.2", "Passing one of 'on', 'true', 'off', 'false' as a "
"boolean is deprecated; use an actual boolean "
"(True/False) instead.")
if s.lower() in ['on', 'true']:
return True
if s.lower() in ['off', 'false']:
return False
raise ValueError('String "%s" must be one of: '
'"on", "off", "true", or "false"' % s)
def get_sample_data(fname, asfileobj=True):
"""
Return a sample data file. *fname* is a path relative to the
`mpl-data/sample_data` directory. If *asfileobj* is `True`
return a file object, otherwise just a file path.
Set the rc parameter examples.directory to the directory where we should
look, if sample_data files are stored in a location different than
default (which is 'mpl-data/sample_data` at the same level of 'matplotlib`
Python module files).
If the filename ends in .gz, the file is implicitly ungzipped.
"""
if matplotlib.rcParams['examples.directory']:
root = matplotlib.rcParams['examples.directory']
else:
root = os.path.join(matplotlib._get_data_path(), 'sample_data')
path = os.path.join(root, fname)
if asfileobj:
if (os.path.splitext(fname)[-1].lower() in
('.csv', '.xrc', '.txt')):
mode = 'r'
else:
mode = 'rb'
base, ext = os.path.splitext(fname)
if ext == '.gz':
return gzip.open(path, mode)
else:
return open(path, mode)
else:
return path
def flatten(seq, scalarp=is_scalar_or_string):
"""
Returns a generator of flattened nested containers
For example:
>>> from matplotlib.cbook import flatten
>>> l = (('John', ['Hunter']), (1, 23), [[([42, (5, 23)], )]])
>>> print(list(flatten(l)))
['John', 'Hunter', 1, 23, 42, 5, 23]
By: Composite of Holger Krekel and Luther Blissett
From: https://code.activestate.com/recipes/121294/
and Recipe 1.12 in cookbook
"""
for item in seq:
if scalarp(item) or item is None:
yield item
else:
for subitem in flatten(item, scalarp):
yield subitem
@deprecated('2.1', "sorted(..., key=itemgetter(...))")
class Sorter(object):
"""
Sort by attribute or item
Example usage::
sort = Sorter()
list = [(1, 2), (4, 8), (0, 3)]
dict = [{'a': 3, 'b': 4}, {'a': 5, 'b': 2}, {'a': 0, 'b': 0},
{'a': 9, 'b': 9}]
sort(list) # default sort
sort(list, 1) # sort by index 1
sort(dict, 'a') # sort a list of dicts by key 'a'
"""
def _helper(self, data, aux, inplace):
aux.sort()
result = [data[i] for junk, i in aux]
if inplace:
data[:] = result
return result
def byItem(self, data, itemindex=None, inplace=1):
if itemindex is None:
if inplace:
data.sort()
result = data
else:
result = sorted(data)
return result
else:
aux = [(data[i][itemindex], i) for i in range(len(data))]
return self._helper(data, aux, inplace)
def byAttribute(self, data, attributename, inplace=1):
aux = [(getattr(data[i], attributename), i) for i in range(len(data))]
return self._helper(data, aux, inplace)
# a couple of handy synonyms
sort = byItem
__call__ = byItem
@deprecated('2.1')
class Xlator(dict):
"""
All-in-one multiple-string-substitution class
Example usage::
text = "Larry Wall is the creator of Perl"
adict = {
"Larry Wall" : "Guido van Rossum",
"creator" : "Benevolent Dictator for Life",
"Perl" : "Python",
}
print(multiple_replace(adict, text))
xlat = Xlator(adict)
print(xlat.xlat(text))
"""
def _make_regex(self):
""" Build re object based on the keys of the current dictionary """
return re.compile("|".join(map(re.escape, self)))
def __call__(self, match):
""" Handler invoked for each regex *match* """
return self[match.group(0)]
def xlat(self, text):
""" Translate *text*, returns the modified text. """
return self._make_regex().sub(self, text)
@deprecated('2.1')
def soundex(name, len=4):
""" soundex module conforming to Odell-Russell algorithm """
# digits holds the soundex values for the alphabet
soundex_digits = '01230120022455012623010202'
sndx = ''
fc = ''
# Translate letters in name to soundex digits
for c in name.upper():
if c.isalpha():
if not fc:
fc = c # Remember first letter
d = soundex_digits[ord(c) - ord('A')]
# Duplicate consecutive soundex digits are skipped
if not sndx or (d != sndx[-1]):
sndx += d
# Replace first digit with first letter
sndx = fc + sndx[1:]
# Remove all 0s from the soundex code
sndx = sndx.replace('0', '')
# Return soundex code truncated or 0-padded to len characters
return (sndx + (len * '0'))[:len]
@deprecated('2.1')
class Null(object):
""" Null objects always and reliably "do nothing." """
def __init__(self, *args, **kwargs):
pass
def __call__(self, *args, **kwargs):
return self
def __str__(self):
return "Null()"
def __repr__(self):
return "Null()"
if six.PY3:
def __bool__(self):
return 0
else:
def __nonzero__(self):
return 0
def __getattr__(self, name):
return self
def __setattr__(self, name, value):
return self
def __delattr__(self, name):
return self
def mkdirs(newdir, mode=0o777):
"""
make directory *newdir* recursively, and set *mode*. Equivalent to ::
> mkdir -p NEWDIR
> chmod MODE NEWDIR
"""
# this functionality is now in core python as of 3.2
# LPY DROP
if six.PY3:
os.makedirs(newdir, mode=mode, exist_ok=True)
else:
try:
os.makedirs(newdir, mode=mode)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
class GetRealpathAndStat(object):
def __init__(self):
self._cache = {}
def __call__(self, path):
result = self._cache.get(path)
if result is None:
realpath = os.path.realpath(path)
if sys.platform == 'win32':
stat_key = realpath
else:
stat = os.stat(realpath)
stat_key = (stat.st_ino, stat.st_dev)
result = realpath, stat_key
self._cache[path] = result
return result
get_realpath_and_stat = GetRealpathAndStat()
@deprecated('2.1')
def dict_delall(d, keys):
"""delete all of the *keys* from the :class:`dict` *d*"""
for key in keys:
try:
del d[key]
except KeyError:
pass
@deprecated('2.1')
class RingBuffer(object):
""" class that implements a not-yet-full buffer """
def __init__(self, size_max):
self.max = size_max
self.data = []
class __Full:
""" class that implements a full buffer """
def append(self, x):
""" Append an element overwriting the oldest one. """
self.data[self.cur] = x
self.cur = (self.cur + 1) % self.max
def get(self):
""" return list of elements in correct order """
return self.data[self.cur:] + self.data[:self.cur]
def append(self, x):
"""append an element at the end of the buffer"""
self.data.append(x)
if len(self.data) == self.max:
self.cur = 0
# Permanently change self's class from non-full to full
self.__class__ = __Full
def get(self):
""" Return a list of elements from the oldest to the newest. """
return self.data
def __get_item__(self, i):
return self.data[i % len(self.data)]
@deprecated('2.1')
def get_split_ind(seq, N):
"""
*seq* is a list of words. Return the index into seq such that::
len(' '.join(seq[:ind])<=N
.
"""
s_len = 0
# todo: use Alex's xrange pattern from the cbook for efficiency
for (word, ind) in zip(seq, xrange(len(seq))):
s_len += len(word) + 1 # +1 to account for the len(' ')
if s_len >= N:
return ind
return len(seq)
@deprecated('2.1', alternative='textwrap.TextWrapper')
def wrap(prefix, text, cols):
"""wrap *text* with *prefix* at length *cols*"""
pad = ' ' * len(prefix.expandtabs())
available = cols - len(pad)
seq = text.split(' ')
Nseq = len(seq)
ind = 0
lines = []
while ind < Nseq:
lastInd = ind
ind += get_split_ind(seq[ind:], available)
lines.append(seq[lastInd:ind])
# add the prefix to the first line, pad with spaces otherwise
ret = prefix + ' '.join(lines[0]) + '\n'
for line in lines[1:]:
ret += pad + ' '.join(line) + '\n'
return ret
# A regular expression used to determine the amount of space to
# remove. It looks for the first sequence of spaces immediately
# following the first newline, or at the beginning of the string.
_find_dedent_regex = re.compile(r"(?:(?:\n\r?)|^)( *)\S")
# A cache to hold the regexs that actually remove the indent.
_dedent_regex = {}
def dedent(s):
"""
Remove excess indentation from docstring *s*.
Discards any leading blank lines, then removes up to n whitespace
characters from each line, where n is the number of leading
whitespace characters in the first line. It differs from
textwrap.dedent in its deletion of leading blank lines and its use
of the first non-blank line to determine the indentation.
It is also faster in most cases.
"""
# This implementation has a somewhat obtuse use of regular
# expressions. However, this function accounted for almost 30% of
# matplotlib startup time, so it is worthy of optimization at all
# costs.
if not s: # includes case of s is None
return ''
match = _find_dedent_regex.match(s)
if match is None:
return s
# This is the number of spaces to remove from the left-hand side.
nshift = match.end(1) - match.start(1)
if nshift == 0:
return s
# Get a regex that will remove *up to* nshift spaces from the
# beginning of each line. If it isn't in the cache, generate it.
unindent = _dedent_regex.get(nshift, None)
if unindent is None:
unindent = re.compile("\n\r? {0,%d}" % nshift)
_dedent_regex[nshift] = unindent
result = unindent.sub("\n", s).strip()
return result
def listFiles(root, patterns='*', recurse=1, return_folders=0):
"""
Recursively list files
from Parmar and Martelli in the Python Cookbook
"""
import os.path
import fnmatch
# Expand patterns from semicolon-separated string to list
pattern_list = patterns.split(';')
results = []
for dirname, dirs, files in os.walk(root):
# Append to results all relevant files (and perhaps folders)
for name in files:
fullname = os.path.normpath(os.path.join(dirname, name))
if return_folders or os.path.isfile(fullname):
for pattern in pattern_list:
if fnmatch.fnmatch(name, pattern):
results.append(fullname)
break
# Block recursion if recursion was disallowed
if not recurse:
break
return results
@deprecated('2.1')
def get_recursive_filelist(args):
"""
Recurse all the files and dirs in *args* ignoring symbolic links
and return the files as a list of strings
"""
files = []
for arg in args:
if os.path.isfile(arg):
files.append(arg)
continue
if os.path.isdir(arg):
newfiles = listFiles(arg, recurse=1, return_folders=1)
files.extend(newfiles)
return [f for f in files if not os.path.islink(f)]
@deprecated('2.1')
def pieces(seq, num=2):
"""Break up the *seq* into *num* tuples"""
start = 0
while 1:
item = seq[start:start + num]
if not len(item):
break
yield item
start += num
@deprecated('2.1')
def exception_to_str(s=None):
if six.PY3:
sh = io.StringIO()
else:
sh = io.BytesIO()
if s is not None:
print(s, file=sh)
traceback.print_exc(file=sh)
return sh.getvalue()
@deprecated('2.1')
def allequal(seq):
"""
Return *True* if all elements of *seq* compare equal. If *seq* is
0 or 1 length, return *True*
"""
if len(seq) < 2:
return True
val = seq[0]
for i in xrange(1, len(seq)):
thisval = seq[i]
if thisval != val:
return False
return True
@deprecated('2.1')
def alltrue(seq):
"""
Return *True* if all elements of *seq* evaluate to *True*. If
*seq* is empty, return *False*.
"""
if not len(seq):
return False
for val in seq:
if not val:
return False
return True
@deprecated('2.1')
def onetrue(seq):
"""
Return *True* if one element of *seq* is *True*. It *seq* is
empty, return *False*.
"""
if not len(seq):
return False
for val in seq:
if val:
return True
return False
@deprecated('2.1')
def allpairs(x):
"""
return all possible pairs in sequence *x*
"""
return [(s, f) for i, f in enumerate(x) for s in x[i + 1:]]
class maxdict(dict):
"""
A dictionary with a maximum size; this doesn't override all the
relevant methods to constrain the size, just setitem, so use with
caution
"""
def __init__(self, maxsize):
dict.__init__(self)
self.maxsize = maxsize
self._killkeys = []
def __setitem__(self, k, v):
if k not in self:
if len(self) >= self.maxsize:
del self[self._killkeys[0]]
del self._killkeys[0]
self._killkeys.append(k)
dict.__setitem__(self, k, v)
class Stack(object):
"""
Implement a stack where elements can be pushed on and you can move
back and forth. But no pop. Should mimic home / back / forward
in a browser
"""
def __init__(self, default=None):
self.clear()
self._default = default
def __call__(self):
"""return the current element, or None"""
if not len(self._elements):
return self._default
else:
return self._elements[self._pos]
def __len__(self):
return self._elements.__len__()
def __getitem__(self, ind):
return self._elements.__getitem__(ind)
def forward(self):
"""move the position forward and return the current element"""
n = len(self._elements)
if self._pos < n - 1:
self._pos += 1
return self()
def back(self):
"""move the position back and return the current element"""
if self._pos > 0:
self._pos -= 1
return self()
def push(self, o):
"""
push object onto stack at current position - all elements
occurring later than the current position are discarded
"""
self._elements = self._elements[:self._pos + 1]
self._elements.append(o)
self._pos = len(self._elements) - 1
return self()
def home(self):
"""push the first element onto the top of the stack"""
if not len(self._elements):
return
self.push(self._elements[0])
return self()
def empty(self):
return len(self._elements) == 0
def clear(self):
"""empty the stack"""
self._pos = -1
self._elements = []
def bubble(self, o):
"""
raise *o* to the top of the stack and return *o*. *o* must be
in the stack
"""
if o not in self._elements:
raise ValueError('Unknown element o')
old = self._elements[:]
self.clear()
bubbles = []
for thiso in old:
if thiso == o:
bubbles.append(thiso)
else:
self.push(thiso)
for thiso in bubbles:
self.push(o)
return o
def remove(self, o):
'remove element *o* from the stack'
if o not in self._elements:
raise ValueError('Unknown element o')
old = self._elements[:]
self.clear()
for thiso in old:
if thiso == o:
continue
else:
self.push(thiso)
@deprecated('2.1')
def finddir(o, match, case=False):
"""
return all attributes of *o* which match string in match. if case
is True require an exact case match.
"""
if case:
names = [(name, name) for name in dir(o)
if isinstance(name, six.string_types)]
else:
names = [(name.lower(), name) for name in dir(o)
if isinstance(name, six.string_types)]
match = match.lower()
return [orig for name, orig in names if name.find(match) >= 0]
@deprecated('2.1')
def reverse_dict(d):
"""reverse the dictionary -- may lose data if values are not unique!"""
return {v: k for k, v in six.iteritems(d)}
@deprecated('2.1')
def restrict_dict(d, keys):
"""
Return a dictionary that contains those keys that appear in both
d and keys, with values from d.
"""
return {k: v for k, v in six.iteritems(d) if k in keys}
def report_memory(i=0): # argument may go away
"""return the memory consumed by process"""
from matplotlib.compat.subprocess import Popen, PIPE
pid = os.getpid()
if sys.platform == 'sunos5':
try:
a2 = Popen(str('ps -p %d -o osz') % pid, shell=True,
stdout=PIPE).stdout.readlines()
except OSError:
raise NotImplementedError(
"report_memory works on Sun OS only if "
"the 'ps' program is found")
mem = int(a2[-1].strip())
elif sys.platform.startswith('linux'):
try:
a2 = Popen(str('ps -p %d -o rss,sz') % pid, shell=True,
stdout=PIPE).stdout.readlines()
except OSError:
raise NotImplementedError(
"report_memory works on Linux only if "
"the 'ps' program is found")
mem = int(a2[1].split()[1])
elif sys.platform.startswith('darwin'):
try:
a2 = Popen(str('ps -p %d -o rss,vsz') % pid, shell=True,
stdout=PIPE).stdout.readlines()
except OSError:
raise NotImplementedError(
"report_memory works on Mac OS only if "
"the 'ps' program is found")
mem = int(a2[1].split()[0])
elif sys.platform.startswith('win'):
try:
a2 = Popen([str("tasklist"), "/nh", "/fi", "pid eq %d" % pid],
stdout=PIPE).stdout.read()
except OSError:
raise NotImplementedError(
"report_memory works on Windows only if "
"the 'tasklist' program is found")
mem = int(a2.strip().split()[-2].replace(',', ''))
else:
raise NotImplementedError(
"We don't have a memory monitor for %s" % sys.platform)
return mem
_safezip_msg = 'In safezip, len(args[0])=%d but len(args[%d])=%d'
def safezip(*args):
"""make sure *args* are equal len before zipping"""
Nx = len(args[0])
for i, arg in enumerate(args[1:]):
if len(arg) != Nx:
raise ValueError(_safezip_msg % (Nx, i + 1, len(arg)))
return list(zip(*args))
@deprecated('2.1')
def issubclass_safe(x, klass):
"""return issubclass(x, klass) and return False on a TypeError"""
try:
return issubclass(x, klass)
except TypeError:
return False
def safe_masked_invalid(x, copy=False):
x = np.array(x, subok=True, copy=copy)
if not x.dtype.isnative:
# Note that the argument to `byteswap` is 'inplace',
# thus if we have already made a copy, do the byteswap in
# place, else make a copy with the byte order swapped.
# Be explicit that we are swapping the byte order of the dtype
x = x.byteswap(copy).newbyteorder('S')
try:
xm = np.ma.masked_invalid(x, copy=False)
xm.shrink_mask()
except TypeError:
return x
return xm
def print_cycles(objects, outstream=sys.stdout, show_progress=False):
"""
*objects*
A list of objects to find cycles in. It is often useful to
pass in gc.garbage to find the cycles that are preventing some
objects from being garbage collected.
*outstream*
The stream for output.
*show_progress*
If True, print the number of objects reached as they are found.
"""
import gc
from types import FrameType
def print_path(path):
for i, step in enumerate(path):
# next "wraps around"
next = path[(i + 1) % len(path)]
outstream.write(" %s -- " % str(type(step)))
if isinstance(step, dict):
for key, val in six.iteritems(step):
if val is next:
outstream.write("[%s]" % repr(key))
break
if key is next:
outstream.write("[key] = %s" % repr(val))
break
elif isinstance(step, list):
outstream.write("[%d]" % step.index(next))
elif isinstance(step, tuple):
outstream.write("( tuple )")
else:
outstream.write(repr(step))
outstream.write(" ->\n")
outstream.write("\n")
def recurse(obj, start, all, current_path):
if show_progress:
outstream.write("%d\r" % len(all))
all[id(obj)] = None
referents = gc.get_referents(obj)
for referent in referents:
# If we've found our way back to the start, this is
# a cycle, so print it out
if referent is start:
print_path(current_path)
# Don't go back through the original list of objects, or
# through temporary references to the object, since those
# are just an artifact of the cycle detector itself.
elif referent is objects or isinstance(referent, FrameType):
continue
# We haven't seen this object before, so recurse
elif id(referent) not in all:
recurse(referent, start, all, current_path + [obj])
for obj in objects:
outstream.write("Examining: %r\n" % (obj,))
recurse(obj, obj, {}, [])
class Grouper(object):
"""
This class provides a lightweight way to group arbitrary objects
together into disjoint sets when a full-blown graph data structure
would be overkill.
Objects can be joined using :meth:`join`, tested for connectedness
using :meth:`joined`, and all disjoint sets can be retrieved by
using the object as an iterator.
The objects being joined must be hashable and weak-referenceable.
For example:
>>> from matplotlib.cbook import Grouper
>>> class Foo(object):
... def __init__(self, s):
... self.s = s
... def __repr__(self):
... return self.s
...
>>> a, b, c, d, e, f = [Foo(x) for x in 'abcdef']
>>> grp = Grouper()
>>> grp.join(a, b)
>>> grp.join(b, c)
>>> grp.join(d, e)
>>> sorted(map(tuple, grp))
[(a, b, c), (d, e)]
>>> grp.joined(a, b)
True
>>> grp.joined(a, c)
True
>>> grp.joined(a, d)
False
"""
def __init__(self, init=()):
mapping = self._mapping = {}
for x in init:
mapping[ref(x)] = [ref(x)]
def __contains__(self, item):
return ref(item) in self._mapping
def clean(self):
"""
Clean dead weak references from the dictionary
"""
mapping = self._mapping
to_drop = [key for key in mapping if key() is None]
for key in to_drop:
val = mapping.pop(key)
val.remove(key)
def join(self, a, *args):
"""
Join given arguments into the same set. Accepts one or more
arguments.
"""
mapping = self._mapping
set_a = mapping.setdefault(ref(a), [ref(a)])
for arg in args:
set_b = mapping.get(ref(arg))
if set_b is None:
set_a.append(ref(arg))
mapping[ref(arg)] = set_a
elif set_b is not set_a:
if len(set_b) > len(set_a):
set_a, set_b = set_b, set_a
set_a.extend(set_b)
for elem in set_b:
mapping[elem] = set_a
self.clean()
def joined(self, a, b):
"""
Returns True if *a* and *b* are members of the same set.
"""
self.clean()
mapping = self._mapping
try:
return mapping[ref(a)] is mapping[ref(b)]
except KeyError:
return False
def remove(self, a):
self.clean()
mapping = self._mapping
seta = mapping.pop(ref(a), None)
if seta is not None:
seta.remove(ref(a))
def __iter__(self):
"""
Iterate over each of the disjoint sets as a list.
The iterator is invalid if interleaved with calls to join().
"""
self.clean()
token = object()
# Mark each group as we come across if by appending a token,
# and don't yield it twice
for group in six.itervalues(self._mapping):
if group[-1] is not token:
yield [x() for x in group]
group.append(token)
# Cleanup the tokens
for group in six.itervalues(self._mapping):
if group[-1] is token:
del group[-1]
def get_siblings(self, a):
"""
Returns all of the items joined with *a*, including itself.
"""
self.clean()
siblings = self._mapping.get(ref(a), [ref(a)])
return [x() for x in siblings]
def simple_linear_interpolation(a, steps):
"""
Resample an array with ``steps - 1`` points between original point pairs.
Parameters
----------
a : array, shape (n, ...)
steps : int
Returns
-------
array, shape ``((n - 1) * steps + 1, ...)``
Along each column of *a*, ``(steps - 1)`` points are introduced between
each original values; the values are linearly interpolated.
"""
fps = a.reshape((len(a), -1))
xp = np.arange(len(a)) * steps
x = np.arange((len(a) - 1) * steps + 1)
return (np.column_stack([np.interp(x, xp, fp) for fp in fps.T])
.reshape((len(x),) + a.shape[1:]))
@deprecated('2.1', alternative='shutil.rmtree')
def recursive_remove(path):
if os.path.isdir(path):
for fname in (glob.glob(os.path.join(path, '*')) +
glob.glob(os.path.join(path, '.*'))):
if os.path.isdir(fname):
recursive_remove(fname)
os.removedirs(fname)
else:
os.remove(fname)
# os.removedirs(path)
else:
os.remove(path)
def delete_masked_points(*args):
"""
Find all masked and/or non-finite points in a set of arguments,
and return the arguments with only the unmasked points remaining.
Arguments can be in any of 5 categories:
1) 1-D masked arrays
2) 1-D ndarrays
3) ndarrays with more than one dimension
4) other non-string iterables
5) anything else
The first argument must be in one of the first four categories;
any argument with a length differing from that of the first
argument (and hence anything in category 5) then will be
passed through unchanged.
Masks are obtained from all arguments of the correct length
in categories 1, 2, and 4; a point is bad if masked in a masked
array or if it is a nan or inf. No attempt is made to
extract a mask from categories 2, 3, and 4 if :meth:`np.isfinite`
does not yield a Boolean array.
All input arguments that are not passed unchanged are returned
as ndarrays after removing the points or rows corresponding to
masks in any of the arguments.
A vastly simpler version of this function was originally
written as a helper for Axes.scatter().
"""
if not len(args):
return ()
if (isinstance(args[0], six.string_types) or not iterable(args[0])):
raise ValueError("First argument must be a sequence")
nrecs = len(args[0])
margs = []
seqlist = [False] * len(args)
for i, x in enumerate(args):
if (not isinstance(x, six.string_types) and iterable(x)
and len(x) == nrecs):
seqlist[i] = True
if isinstance(x, np.ma.MaskedArray):
if x.ndim > 1:
raise ValueError("Masked arrays must be 1-D")
else:
x = np.asarray(x)
margs.append(x)
masks = [] # list of masks that are True where good
for i, x in enumerate(margs):
if seqlist[i]:
if x.ndim > 1:
continue # Don't try to get nan locations unless 1-D.
if isinstance(x, np.ma.MaskedArray):
masks.append(~np.ma.getmaskarray(x)) # invert the mask
xd = x.data
else:
xd = x
try:
mask = np.isfinite(xd)
if isinstance(mask, np.ndarray):
masks.append(mask)
except: # Fixme: put in tuple of possible exceptions?
pass
if len(masks):
mask = np.logical_and.reduce(masks)
igood = mask.nonzero()[0]
if len(igood) < nrecs:
for i, x in enumerate(margs):
if seqlist[i]:
margs[i] = x.take(igood, axis=0)
for i, x in enumerate(margs):
if seqlist[i] and isinstance(x, np.ma.MaskedArray):
margs[i] = x.filled()
return margs
def boxplot_stats(X, whis=1.5, bootstrap=None, labels=None,
autorange=False):
"""
Returns list of dictionaries of statistics used to draw a series
of box and whisker plots. The `Returns` section enumerates the
required keys of the dictionary. Users can skip this function and
pass a user-defined set of dictionaries to the new `axes.bxp` method
instead of relying on MPL to do the calculations.
Parameters
----------
X : array-like
Data that will be represented in the boxplots. Should have 2 or
fewer dimensions.
whis : float, string, or sequence (default = 1.5)
As a float, determines the reach of the whiskers to the beyond the
first and third quartiles. In other words, where IQR is the
interquartile range (`Q3-Q1`), the upper whisker will extend to last
datum less than `Q3 + whis*IQR`). Similarly, the lower whisker will
extend to the first datum greater than `Q1 - whis*IQR`.
Beyond the whiskers, data are considered outliers
and are plotted as individual points. This can be set this to an
ascending sequence of percentile (e.g., [5, 95]) to set the
whiskers at specific percentiles of the data. Finally, `whis`
can be the string ``'range'`` to force the whiskers to the
minimum and maximum of the data. In the edge case that the 25th
and 75th percentiles are equivalent, `whis` can be automatically
set to ``'range'`` via the `autorange` option.
bootstrap : int, optional
Number of times the confidence intervals around the median
should be bootstrapped (percentile method).
labels : array-like, optional
Labels for each dataset. Length must be compatible with
dimensions of `X`.
autorange : bool, optional (False)
When `True` and the data are distributed such that the 25th and
75th percentiles are equal, ``whis`` is set to ``'range'`` such
that the whisker ends are at the minimum and maximum of the
data.
Returns
-------
bxpstats : list of dict
A list of dictionaries containing the results for each column
of data. Keys of each dictionary are the following:
======== ===================================
Key Value Description
======== ===================================
label tick label for the boxplot
mean arithemetic mean value
med 50th percentile
q1 first quartile (25th percentile)
q3 third quartile (75th percentile)
cilo lower notch around the median
cihi upper notch around the median
whislo end of the lower whisker
whishi end of the upper whisker
fliers outliers
======== ===================================
Notes
-----
Non-bootstrapping approach to confidence interval uses Gaussian-
based asymptotic approximation:
.. math::
\\mathrm{med} \\pm 1.57 \\times \\frac{\\mathrm{iqr}}{\\sqrt{N}}
General approach from:
McGill, R., Tukey, J.W., and Larsen, W.A. (1978) "Variations of
Boxplots", The American Statistician, 32:12-16.
"""
def _bootstrap_median(data, N=5000):
# determine 95% confidence intervals of the median
M = len(data)
percentiles = [2.5, 97.5]
bs_index = np.random.randint(M, size=(N, M))
bsData = data[bs_index]
estimate = np.median(bsData, axis=1, overwrite_input=True)
CI = np.percentile(estimate, percentiles)
return CI
def _compute_conf_interval(data, med, iqr, bootstrap):
if bootstrap is not None:
# Do a bootstrap estimate of notch locations.
# get conf. intervals around median
CI = _bootstrap_median(data, N=bootstrap)
notch_min = CI[0]
notch_max = CI[1]
else:
N = len(data)
notch_min = med - 1.57 * iqr / np.sqrt(N)
notch_max = med + 1.57 * iqr / np.sqrt(N)
return notch_min, notch_max
# output is a list of dicts
bxpstats = []
# convert X to a list of lists
X = _reshape_2D(X, "X")
ncols = len(X)
if labels is None:
labels = repeat(None)
elif len(labels) != ncols:
raise ValueError("Dimensions of labels and X must be compatible")
input_whis = whis
for ii, (x, label) in enumerate(zip(X, labels), start=0):
# empty dict
stats = {}
if label is not None:
stats['label'] = label
# restore whis to the input values in case it got changed in the loop
whis = input_whis
# note tricksyness, append up here and then mutate below
bxpstats.append(stats)
# if empty, bail
if len(x) == 0:
stats['fliers'] = np.array([])
stats['mean'] = np.nan
stats['med'] = np.nan
stats['q1'] = np.nan
stats['q3'] = np.nan
stats['cilo'] = np.nan
stats['cihi'] = np.nan
stats['whislo'] = np.nan
stats['whishi'] = np.nan
stats['med'] = np.nan
continue
# up-convert to an array, just to be safe
x = np.asarray(x)
# arithmetic mean
stats['mean'] = np.mean(x)
# medians and quartiles
q1, med, q3 = np.percentile(x, [25, 50, 75])
# interquartile range
stats['iqr'] = q3 - q1
if stats['iqr'] == 0 and autorange:
whis = 'range'
# conf. interval around median
stats['cilo'], stats['cihi'] = _compute_conf_interval(
x, med, stats['iqr'], bootstrap
)
# lowest/highest non-outliers
if np.isscalar(whis):
if np.isreal(whis):
loval = q1 - whis * stats['iqr']
hival = q3 + whis * stats['iqr']
elif whis in ['range', 'limit', 'limits', 'min/max']:
loval = np.min(x)
hival = np.max(x)
else:
raise ValueError('whis must be a float, valid string, or list '
'of percentiles')
else:
loval = np.percentile(x, whis[0])
hival = np.percentile(x, whis[1])
# get high extreme
wiskhi = np.compress(x <= hival, x)
if len(wiskhi) == 0 or np.max(wiskhi) < q3:
stats['whishi'] = q3
else:
stats['whishi'] = np.max(wiskhi)
# get low extreme
wisklo = np.compress(x >= loval, x)
if len(wisklo) == 0 or np.min(wisklo) > q1:
stats['whislo'] = q1
else:
stats['whislo'] = np.min(wisklo)
# compute a single array of outliers
stats['fliers'] = np.hstack([
np.compress(x < stats['whislo'], x),
np.compress(x > stats['whishi'], x)
])
# add in the remaining stats
stats['q1'], stats['med'], stats['q3'] = q1, med, q3
return bxpstats
# FIXME I don't think this is used anywhere
@deprecated('2.1')
def unmasked_index_ranges(mask, compressed=True):
"""
Find index ranges where *mask* is *False*.
*mask* will be flattened if it is not already 1-D.
Returns Nx2 :class:`numpy.ndarray` with each row the start and stop
indices for slices of the compressed :class:`numpy.ndarray`
corresponding to each of *N* uninterrupted runs of unmasked
values. If optional argument *compressed* is *False*, it returns
the start and stop indices into the original :class:`numpy.ndarray`,
not the compressed :class:`numpy.ndarray`. Returns *None* if there
are no unmasked values.
Example::
y = ma.array(np.arange(5), mask = [0,0,1,0,0])
ii = unmasked_index_ranges(ma.getmaskarray(y))
# returns array [[0,2,] [2,4,]]
y.compressed()[ii[1,0]:ii[1,1]]
# returns array [3,4,]
ii = unmasked_index_ranges(ma.getmaskarray(y), compressed=False)
# returns array [[0, 2], [3, 5]]
y.filled()[ii[1,0]:ii[1,1]]
# returns array [3,4,]
Prior to the transforms refactoring, this was used to support
masked arrays in Line2D.
"""
mask = mask.reshape(mask.size)
m = np.concatenate(((1,), mask, (1,)))
indices = np.arange(len(mask) + 1)
mdif = m[1:] - m[:-1]
i0 = np.compress(mdif == -1, indices)
i1 = np.compress(mdif == 1, indices)
assert len(i0) == len(i1)
if len(i1) == 0:
return None # Maybe this should be np.zeros((0,2), dtype=int)
if not compressed:
return np.concatenate((i0[:, np.newaxis], i1[:, np.newaxis]), axis=1)
seglengths = i1 - i0
breakpoints = np.cumsum(seglengths)
ic0 = np.concatenate(((0,), breakpoints[:-1]))
ic1 = breakpoints
return np.concatenate((ic0[:, np.newaxis], ic1[:, np.newaxis]), axis=1)
# The ls_mapper maps short codes for line style to their full name used by
# backends; the reverse mapper is for mapping full names to short ones.
ls_mapper = {'-': 'solid', '--': 'dashed', '-.': 'dashdot', ':': 'dotted'}
ls_mapper_r = {v: k for k, v in six.iteritems(ls_mapper)}
@deprecated('2.2')
def align_iterators(func, *iterables):
"""
This generator takes a bunch of iterables that are ordered by func
It sends out ordered tuples::
(func(row), [rows from all iterators matching func(row)])
It is used by :func:`matplotlib.mlab.recs_join` to join record arrays
"""
class myiter:
def __init__(self, it):
self.it = it
self.key = self.value = None
self.iternext()
def iternext(self):
try:
self.value = next(self.it)
self.key = func(self.value)
except StopIteration:
self.value = self.key = None
def __call__(self, key):
retval = None
if key == self.key:
retval = self.value
self.iternext()
elif self.key and key > self.key:
raise ValueError("Iterator has been left behind")
return retval
# This can be made more efficient by not computing the minimum key for each
# iteration
iters = [myiter(it) for it in iterables]
minvals = minkey = True
while True:
minvals = ([_f for _f in [it.key for it in iters] if _f])
if minvals:
minkey = min(minvals)
yield (minkey, [it(minkey) for it in iters])
else:
break
def contiguous_regions(mask):
"""
Return a list of (ind0, ind1) such that mask[ind0:ind1].all() is
True and we cover all such regions
"""
mask = np.asarray(mask, dtype=bool)
if not mask.size:
return []
# Find the indices of region changes, and correct offset
idx, = np.nonzero(mask[:-1] != mask[1:])
idx += 1
# List operations are faster for moderately sized arrays
idx = idx.tolist()
# Add first and/or last index if needed
if mask[0]:
idx = [0] + idx
if mask[-1]:
idx.append(len(mask))
return list(zip(idx[::2], idx[1::2]))
def is_math_text(s):
# Did we find an even number of non-escaped dollar signs?
# If so, treat is as math text.
try:
s = six.text_type(s)
except UnicodeDecodeError:
raise ValueError(
"matplotlib display text must have all code points < 128 or use "
"Unicode strings")
dollar_count = s.count(r'$') - s.count(r'\$')
even_dollars = (dollar_count > 0 and dollar_count % 2 == 0)
return even_dollars
def _to_unmasked_float_array(x):
"""
Convert a sequence to a float array; if input was a masked array, masked
values are converted to nans.
"""
if hasattr(x, 'mask'):
return np.ma.asarray(x, float).filled(np.nan)
else:
return np.asarray(x, float)
def _check_1d(x):
'''
Converts a sequence of less than 1 dimension, to an array of 1
dimension; leaves everything else untouched.
'''
if not hasattr(x, 'shape') or len(x.shape) < 1:
return np.atleast_1d(x)
else:
try:
x[:, None]
return x
except (IndexError, TypeError):
return np.atleast_1d(x)
def _reshape_2D(X, name):
"""
Use Fortran ordering to convert ndarrays and lists of iterables to lists of
1D arrays.
Lists of iterables are converted by applying `np.asarray` to each of their
elements. 1D ndarrays are returned in a singleton list containing them.
2D ndarrays are converted to the list of their *columns*.
*name* is used to generate the error message for invalid inputs.
"""
# Iterate over columns for ndarrays, over rows otherwise.
X = np.atleast_1d(X.T if isinstance(X, np.ndarray) else np.asarray(X))
if X.ndim == 1 and X.dtype.type != np.object_:
# 1D array of scalars: directly return it.
return [X]
elif X.ndim in [1, 2]:
# 2D array, or 1D array of iterables: flatten them first.
return [np.reshape(x, -1) for x in X]
else:
raise ValueError("{} must have 2 or fewer dimensions".format(name))
def violin_stats(X, method, points=100):
"""
Returns a list of dictionaries of data which can be used to draw a series
of violin plots. See the `Returns` section below to view the required keys
of the dictionary. Users can skip this function and pass a user-defined set
of dictionaries to the `axes.vplot` method instead of using MPL to do the
calculations.
Parameters
----------
X : array-like
Sample data that will be used to produce the gaussian kernel density
estimates. Must have 2 or fewer dimensions.
method : callable
The method used to calculate the kernel density estimate for each
column of data. When called via `method(v, coords)`, it should
return a vector of the values of the KDE evaluated at the values
specified in coords.
points : scalar, default = 100
Defines the number of points to evaluate each of the gaussian kernel
density estimates at.
Returns
-------
A list of dictionaries containing the results for each column of data.
The dictionaries contain at least the following:
- coords: A list of scalars containing the coordinates this particular
kernel density estimate was evaluated at.
- vals: A list of scalars containing the values of the kernel density
estimate at each of the coordinates given in `coords`.
- mean: The mean value for this column of data.
- median: The median value for this column of data.
- min: The minimum value for this column of data.
- max: The maximum value for this column of data.
"""
# List of dictionaries describing each of the violins.
vpstats = []
# Want X to be a list of data sequences
X = _reshape_2D(X, "X")
for x in X:
# Dictionary of results for this distribution
stats = {}
# Calculate basic stats for the distribution
min_val = np.min(x)
max_val = np.max(x)
# Evaluate the kernel density estimate
coords = np.linspace(min_val, max_val, points)
stats['vals'] = method(x, coords)
stats['coords'] = coords
# Store additional statistics for this distribution
stats['mean'] = np.mean(x)
stats['median'] = np.median(x)
stats['min'] = min_val
stats['max'] = max_val
# Append to output
vpstats.append(stats)
return vpstats
class _NestedClassGetter(object):
# recipe from http://stackoverflow.com/a/11493777/741316
"""
When called with the containing class as the first argument,
and the name of the nested class as the second argument,
returns an instance of the nested class.
"""
def __call__(self, containing_class, class_name):
nested_class = getattr(containing_class, class_name)
# make an instance of a simple object (this one will do), for which we
# can change the __class__ later on.
nested_instance = _NestedClassGetter()
# set the class of the instance, the __init__ will never be called on
# the class but the original state will be set later on by pickle.
nested_instance.__class__ = nested_class
return nested_instance
class _InstanceMethodPickler(object):
"""
Pickle cannot handle instancemethod saving. _InstanceMethodPickler
provides a solution to this.
"""
def __init__(self, instancemethod):
"""Takes an instancemethod as its only argument."""
if six.PY3:
self.parent_obj = instancemethod.__self__
self.instancemethod_name = instancemethod.__func__.__name__
else:
self.parent_obj = instancemethod.im_self
self.instancemethod_name = instancemethod.im_func.__name__
def get_instancemethod(self):
return getattr(self.parent_obj, self.instancemethod_name)
def pts_to_prestep(x, *args):
"""
Convert continuous line to pre-steps.
Given a set of ``N`` points, convert to ``2N - 1`` points, which when
connected linearly give a step function which changes values at the
beginning of the intervals.
Parameters
----------
x : array
The x location of the steps. May be empty.
y1, ..., yp : array
y arrays to be turned into steps; all must be the same length as ``x``.
Returns
-------
out : array
The x and y values converted to steps in the same order as the input;
can be unpacked as ``x_out, y1_out, ..., yp_out``. If the input is
length ``N``, each of these arrays will be length ``2N + 1``. For
``N=0``, the length will be 0.
Examples
--------
>> x_s, y1_s, y2_s = pts_to_prestep(x, y1, y2)
"""
steps = np.zeros((1 + len(args), max(2 * len(x) - 1, 0)))
# In all `pts_to_*step` functions, only assign *once* using `x` and `args`,
# as converting to an array may be expensive.
steps[0, 0::2] = x
steps[0, 1::2] = steps[0, 0:-2:2]
steps[1:, 0::2] = args
steps[1:, 1::2] = steps[1:, 2::2]
return steps
def pts_to_poststep(x, *args):
"""
Convert continuous line to post-steps.
Given a set of ``N`` points convert to ``2N + 1`` points, which when
connected linearly give a step function which changes values at the end of
the intervals.
Parameters
----------
x : array
The x location of the steps. May be empty.
y1, ..., yp : array
y arrays to be turned into steps; all must be the same length as ``x``.
Returns
-------
out : array
The x and y values converted to steps in the same order as the input;
can be unpacked as ``x_out, y1_out, ..., yp_out``. If the input is
length ``N``, each of these arrays will be length ``2N + 1``. For
``N=0``, the length will be 0.
Examples
--------
>> x_s, y1_s, y2_s = pts_to_poststep(x, y1, y2)
"""
steps = np.zeros((1 + len(args), max(2 * len(x) - 1, 0)))
steps[0, 0::2] = x
steps[0, 1::2] = steps[0, 2::2]
steps[1:, 0::2] = args
steps[1:, 1::2] = steps[1:, 0:-2:2]
return steps
def pts_to_midstep(x, *args):
"""
Convert continuous line to mid-steps.
Given a set of ``N`` points convert to ``2N`` points which when connected
linearly give a step function which changes values at the middle of the
intervals.
Parameters
----------
x : array
The x location of the steps. May be empty.
y1, ..., yp : array
y arrays to be turned into steps; all must be the same length as ``x``.
Returns
-------
out : array
The x and y values converted to steps in the same order as the input;
can be unpacked as ``x_out, y1_out, ..., yp_out``. If the input is
length ``N``, each of these arrays will be length ``2N``.
Examples
--------
>> x_s, y1_s, y2_s = pts_to_midstep(x, y1, y2)
"""
steps = np.zeros((1 + len(args), 2 * len(x)))
x = np.asanyarray(x)
steps[0, 1:-1:2] = steps[0, 2::2] = (x[:-1] + x[1:]) / 2
steps[0, :1] = x[:1] # Also works for zero-sized input.
steps[0, -1:] = x[-1:]
steps[1:, 0::2] = args
steps[1:, 1::2] = steps[1:, 0::2]
return steps
STEP_LOOKUP_MAP = {'default': lambda x, y: (x, y),
'steps': pts_to_prestep,
'steps-pre': pts_to_prestep,
'steps-post': pts_to_poststep,
'steps-mid': pts_to_midstep}
def index_of(y):
"""
A helper function to get the index of an input to plot
against if x values are not explicitly given.
Tries to get `y.index` (works if this is a pd.Series), if that
fails, return np.arange(y.shape[0]).
This will be extended in the future to deal with more types of
labeled data.
Parameters
----------
y : scalar or array-like
The proposed y-value
Returns
-------
x, y : ndarray
The x and y values to plot.
"""
try:
return y.index.values, y.values
except AttributeError:
y = _check_1d(y)
return np.arange(y.shape[0], dtype=float), y
def safe_first_element(obj):
if isinstance(obj, collections.Iterator):
# needed to accept `array.flat` as input.
# np.flatiter reports as an instance of collections.Iterator
# but can still be indexed via [].
# This has the side effect of re-setting the iterator, but
# that is acceptable.
try:
return obj[0]
except TypeError:
pass
raise RuntimeError("matplotlib does not support generators "
"as input")
return next(iter(obj))
def sanitize_sequence(data):
"""Converts dictview object to list"""
return list(data) if isinstance(data, collections.MappingView) else data
def normalize_kwargs(kw, alias_mapping=None, required=(), forbidden=(),
allowed=None):
"""Helper function to normalize kwarg inputs
The order they are resolved are:
1. aliasing
2. required
3. forbidden
4. allowed
This order means that only the canonical names need appear in
`allowed`, `forbidden`, `required`
Parameters
----------
alias_mapping, dict, optional
A mapping between a canonical name to a list of
aliases, in order of precedence from lowest to highest.
If the canonical value is not in the list it is assumed to have
the highest priority.
required : iterable, optional
A tuple of fields that must be in kwargs.
forbidden : iterable, optional
A list of keys which may not be in kwargs
allowed : tuple, optional
A tuple of allowed fields. If this not None, then raise if
`kw` contains any keys not in the union of `required`
and `allowed`. To allow only the required fields pass in
``()`` for `allowed`
Raises
------
TypeError
To match what python raises if invalid args/kwargs are passed to
a callable.
"""
# deal with default value of alias_mapping
if alias_mapping is None:
alias_mapping = dict()
# make a local so we can pop
kw = dict(kw)
# output dictionary
ret = dict()
# hit all alias mappings
for canonical, alias_list in six.iteritems(alias_mapping):
# the alias lists are ordered from lowest to highest priority
# so we know to use the last value in this list
tmp = []
seen = []
for a in alias_list:
try:
tmp.append(kw.pop(a))
seen.append(a)
except KeyError:
pass
# if canonical is not in the alias_list assume highest priority
if canonical not in alias_list:
try:
tmp.append(kw.pop(canonical))
seen.append(canonical)
except KeyError:
pass
# if we found anything in this set of aliases put it in the return
# dict
if tmp:
ret[canonical] = tmp[-1]
if len(tmp) > 1:
warnings.warn("Saw kwargs {seen!r} which are all aliases for "
"{canon!r}. Kept value from {used!r}".format(
seen=seen, canon=canonical, used=seen[-1]))
# at this point we know that all keys which are aliased are removed, update
# the return dictionary from the cleaned local copy of the input
ret.update(kw)
fail_keys = [k for k in required if k not in ret]
if fail_keys:
raise TypeError("The required keys {keys!r} "
"are not in kwargs".format(keys=fail_keys))
fail_keys = [k for k in forbidden if k in ret]
if fail_keys:
raise TypeError("The forbidden keys {keys!r} "
"are in kwargs".format(keys=fail_keys))
if allowed is not None:
allowed_set = set(required) | set(allowed)
fail_keys = [k for k in ret if k not in allowed_set]
if fail_keys:
raise TypeError("kwargs contains {keys!r} which are not in "
"the required {req!r} or "
"allowed {allow!r} keys".format(
keys=fail_keys, req=required,
allow=allowed))
return ret
def get_label(y, default_name):
try:
return y.name
except AttributeError:
return default_name
_lockstr = """\
LOCKERROR: matplotlib is trying to acquire the lock
{!r}
and has failed. This maybe due to any other process holding this
lock. If you are sure no other matplotlib process is running try
removing these folders and trying again.
"""
class Locked(object):
"""
Context manager to handle locks.
Based on code from conda.
(c) 2012-2013 Continuum Analytics, Inc. / https://www.continuum.io/
All Rights Reserved
conda is distributed under the terms of the BSD 3-clause license.
Consult LICENSE_CONDA or https://opensource.org/licenses/BSD-3-Clause.
"""
LOCKFN = '.matplotlib_lock'
class TimeoutError(RuntimeError):
pass
def __init__(self, path):
self.path = path
self.end = "-" + str(os.getpid())
self.lock_path = os.path.join(self.path, self.LOCKFN + self.end)
self.pattern = os.path.join(self.path, self.LOCKFN + '-*')
self.remove = True
def __enter__(self):
retries = 50
sleeptime = 0.1
while retries:
files = glob.glob(self.pattern)
if files and not files[0].endswith(self.end):
time.sleep(sleeptime)
retries -= 1
else:
break
else:
err_str = _lockstr.format(self.pattern)
raise self.TimeoutError(err_str)
if not files:
try:
os.makedirs(self.lock_path)
except OSError:
pass
else: # PID lock already here --- someone else will remove it.
self.remove = False
def __exit__(self, exc_type, exc_value, traceback):
if self.remove:
for path in self.lock_path, self.path:
try:
os.rmdir(path)
except OSError:
pass
class _FuncInfo(object):
"""
Class used to store a function.
"""
def __init__(self, function, inverse, bounded_0_1=True, check_params=None):
"""
Parameters
----------
function : callable
A callable implementing the function receiving the variable as
first argument and any additional parameters in a list as second
argument.
inverse : callable
A callable implementing the inverse function receiving the variable
as first argument and any additional parameters in a list as
second argument. It must satisfy 'inverse(function(x, p), p) == x'.
bounded_0_1: bool or callable
A boolean indicating whether the function is bounded in the [0,1]
interval, or a callable taking a list of values for the additional
parameters, and returning a boolean indicating whether the function
is bounded in the [0,1] interval for that combination of
parameters. Default True.
check_params: callable or None
A callable taking a list of values for the additional parameters
and returning a boolean indicating whether that combination of
parameters is valid. It is only required if the function has
additional parameters and some of them are restricted.
Default None.
"""
self.function = function
self.inverse = inverse
if callable(bounded_0_1):
self._bounded_0_1 = bounded_0_1
else:
self._bounded_0_1 = lambda x: bounded_0_1
if check_params is None:
self._check_params = lambda x: True
elif callable(check_params):
self._check_params = check_params
else:
raise ValueError("Invalid 'check_params' argument.")
def is_bounded_0_1(self, params=None):
"""
Returns a boolean indicating if the function is bounded in the [0,1]
interval for a particular set of additional parameters.
Parameters
----------
params : list
The list of additional parameters. Default None.
Returns
-------
out : bool
True if the function is bounded in the [0,1] interval for
parameters 'params'. Otherwise False.
"""
return self._bounded_0_1(params)
def check_params(self, params=None):
"""
Returns a boolean indicating if the set of additional parameters is
valid.
Parameters
----------
params : list
The list of additional parameters. Default None.
Returns
-------
out : bool
True if 'params' is a valid set of additional parameters for the
function. Otherwise False.
"""
return self._check_params(params)
class _StringFuncParser(object):
"""
A class used to convert predefined strings into
_FuncInfo objects, or to directly obtain _FuncInfo
properties.
"""
_funcs = {}
_funcs['linear'] = _FuncInfo(lambda x: x,
lambda x: x,
True)
_funcs['quadratic'] = _FuncInfo(np.square,
np.sqrt,
True)
_funcs['cubic'] = _FuncInfo(lambda x: x**3,
lambda x: x**(1. / 3),
True)
_funcs['sqrt'] = _FuncInfo(np.sqrt,
np.square,
True)
_funcs['cbrt'] = _FuncInfo(lambda x: x**(1. / 3),
lambda x: x**3,
True)
_funcs['log10'] = _FuncInfo(np.log10,
lambda x: (10**(x)),
False)
_funcs['log'] = _FuncInfo(np.log,
np.exp,
False)
_funcs['log2'] = _FuncInfo(np.log2,
lambda x: (2**x),
False)
_funcs['x**{p}'] = _FuncInfo(lambda x, p: x**p[0],
lambda x, p: x**(1. / p[0]),
True)
_funcs['root{p}(x)'] = _FuncInfo(lambda x, p: x**(1. / p[0]),
lambda x, p: x**p,
True)
_funcs['log{p}(x)'] = _FuncInfo(lambda x, p: (np.log(x) /
np.log(p[0])),
lambda x, p: p[0]**(x),
False,
lambda p: p[0] > 0)
_funcs['log10(x+{p})'] = _FuncInfo(lambda x, p: np.log10(x + p[0]),
lambda x, p: 10**x - p[0],
lambda p: p[0] > 0)
_funcs['log(x+{p})'] = _FuncInfo(lambda x, p: np.log(x + p[0]),
lambda x, p: np.exp(x) - p[0],
lambda p: p[0] > 0)
_funcs['log{p}(x+{p})'] = _FuncInfo(lambda x, p: (np.log(x + p[1]) /
np.log(p[0])),
lambda x, p: p[0]**(x) - p[1],
lambda p: p[1] > 0,
lambda p: p[0] > 0)
def __init__(self, str_func):
"""
Parameters
----------
str_func : string
String to be parsed.
"""
if not isinstance(str_func, six.string_types):
raise ValueError("'%s' must be a string." % str_func)
self._str_func = six.text_type(str_func)
self._key, self._params = self._get_key_params()
self._func = self._parse_func()
def _parse_func(self):
"""
Parses the parameters to build a new _FuncInfo object,
replacing the relevant parameters if necessary in the lambda
functions.
"""
func = self._funcs[self._key]
if not self._params:
func = _FuncInfo(func.function, func.inverse,
func.is_bounded_0_1())
else:
m = func.function
function = (lambda x, m=m: m(x, self._params))
m = func.inverse
inverse = (lambda x, m=m: m(x, self._params))
is_bounded_0_1 = func.is_bounded_0_1(self._params)
func = _FuncInfo(function, inverse,
is_bounded_0_1)
return func
@property
def func_info(self):
"""
Returns the _FuncInfo object.
"""
return self._func
@property
def function(self):
"""
Returns the callable for the direct function.
"""
return self._func.function
@property
def inverse(self):
"""
Returns the callable for the inverse function.
"""
return self._func.inverse
@property
def is_bounded_0_1(self):
"""
Returns a boolean indicating if the function is bounded
in the [0-1 interval].
"""
return self._func.is_bounded_0_1()
def _get_key_params(self):
str_func = self._str_func
# Checking if it comes with parameters
regex = r'\{(.*?)\}'
params = re.findall(regex, str_func)
for i, param in enumerate(params):
try:
params[i] = float(param)
except ValueError:
raise ValueError("Parameter %i is '%s', which is "
"not a number." %
(i, param))
str_func = re.sub(regex, '{p}', str_func)
try:
func = self._funcs[str_func]
except (ValueError, KeyError):
raise ValueError("'%s' is an invalid string. The only strings "
"recognized as functions are %s." %
(str_func, list(self._funcs)))
# Checking that the parameters are valid
if not func.check_params(params):
raise ValueError("%s are invalid values for the parameters "
"in %s." %
(params, str_func))
return str_func, params
def _topmost_artist(
artists,
_cached_max=functools.partial(max, key=operator.attrgetter("zorder"))):
"""Get the topmost artist of a list.
In case of a tie, return the *last* of the tied artists, as it will be
drawn on top of the others. `max` returns the first maximum in case of ties
(on Py2 this is undocumented but true), so we need to iterate over the list
in reverse order.
"""
return _cached_max(reversed(artists))
def _str_equal(obj, s):
"""Return whether *obj* is a string equal to string *s*.
This helper solely exists to handle the case where *obj* is a numpy array,
because in such cases, a naive ``obj == s`` would yield an array, which
cannot be used in a boolean context.
"""
return isinstance(obj, six.string_types) and obj == s
def _str_lower_equal(obj, s):
"""Return whether *obj* is a string equal, when lowercased, to string *s*.
This helper solely exists to handle the case where *obj* is a numpy array,
because in such cases, a naive ``obj == s`` would yield an array, which
cannot be used in a boolean context.
"""
return isinstance(obj, six.string_types) and obj.lower() == s
| 87,491 | 29.883163 | 79 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/axes/_axes.py | from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
from six.moves import xrange, zip, zip_longest
import functools
import itertools
import logging
import math
import warnings
import numpy as np
from numpy import ma
import matplotlib
from matplotlib import _preprocess_data
import matplotlib.cbook as cbook
import matplotlib.collections as mcoll
import matplotlib.colors as mcolors
import matplotlib.contour as mcontour
import matplotlib.category as _ # <-registers a category unit converter
import matplotlib.dates as _ # <-registers a date unit converter
import matplotlib.docstring as docstring
import matplotlib.image as mimage
import matplotlib.legend as mlegend
import matplotlib.lines as mlines
import matplotlib.markers as mmarkers
import matplotlib.mlab as mlab
import matplotlib.path as mpath
import matplotlib.patches as mpatches
import matplotlib.quiver as mquiver
import matplotlib.stackplot as mstack
import matplotlib.streamplot as mstream
import matplotlib.table as mtable
import matplotlib.text as mtext
import matplotlib.ticker as mticker
import matplotlib.transforms as mtransforms
import matplotlib.tri as mtri
from matplotlib.cbook import (
_backports, mplDeprecation, warn_deprecated,
STEP_LOOKUP_MAP, iterable, safe_first_element)
from matplotlib.container import BarContainer, ErrorbarContainer, StemContainer
from matplotlib.axes._base import _AxesBase, _process_plot_format
_log = logging.getLogger(__name__)
rcParams = matplotlib.rcParams
_alias_map = {'color': ['c'],
'linewidth': ['lw'],
'linestyle': ['ls'],
'facecolor': ['fc'],
'edgecolor': ['ec'],
'markerfacecolor': ['mfc'],
'markeredgecolor': ['mec'],
'markeredgewidth': ['mew'],
'markersize': ['ms'],
}
def _plot_args_replacer(args, data):
if len(args) == 1:
return ["y"]
elif len(args) == 2:
# this can be two cases: x,y or y,c
if not args[1] in data:
# this is not in data, so just assume that it is something which
# will not get replaced (color spec or array like).
return ["y", "c"]
# it's data, but could be a color code like 'ro' or 'b--'
# -> warn the user in that case...
try:
_process_plot_format(args[1])
except ValueError:
pass
else:
warnings.warn(
"Second argument {!r} is ambiguous: could be a color spec but "
"is in data; using as data. Either rename the entry in data "
"or use three arguments to plot.".format(args[1]),
RuntimeWarning, stacklevel=3)
return ["x", "y"]
elif len(args) == 3:
return ["x", "y", "c"]
else:
raise ValueError("Using arbitrary long args with data is not "
"supported due to ambiguity of arguments.\nUse "
"multiple plotting calls instead.")
# The axes module contains all the wrappers to plotting functions.
# All the other methods should go in the _AxesBase class.
class Axes(_AxesBase):
"""
The :class:`Axes` contains most of the figure elements:
:class:`~matplotlib.axis.Axis`, :class:`~matplotlib.axis.Tick`,
:class:`~matplotlib.lines.Line2D`, :class:`~matplotlib.text.Text`,
:class:`~matplotlib.patches.Polygon`, etc., and sets the
coordinate system.
The :class:`Axes` instance supports callbacks through a callbacks
attribute which is a :class:`~matplotlib.cbook.CallbackRegistry`
instance. The events you can connect to are 'xlim_changed' and
'ylim_changed' and the callback will be called with func(*ax*)
where *ax* is the :class:`Axes` instance.
"""
### Labelling, legend and texts
aname = 'Axes'
def get_title(self, loc="center"):
"""
Get an axes title.
Get one of the three available axes titles. The available titles
are positioned above the axes in the center, flush with the left
edge, and flush with the right edge.
Parameters
----------
loc : {'center', 'left', 'right'}, str, optional
Which title to get, defaults to 'center'.
Returns
-------
title : str
The title text string.
"""
try:
title = {'left': self._left_title,
'center': self.title,
'right': self._right_title}[loc.lower()]
except KeyError:
raise ValueError("'%s' is not a valid location" % loc)
return title.get_text()
def set_title(self, label, fontdict=None, loc="center", pad=None,
**kwargs):
"""
Set a title for the axes.
Set one of the three available axes titles. The available titles
are positioned above the axes in the center, flush with the left
edge, and flush with the right edge.
Parameters
----------
label : str
Text to use for the title
fontdict : dict
A dictionary controlling the appearance of the title text,
the default `fontdict` is::
{'fontsize': rcParams['axes.titlesize'],
'fontweight' : rcParams['axes.titleweight'],
'verticalalignment': 'baseline',
'horizontalalignment': loc}
loc : {'center', 'left', 'right'}, str, optional
Which title to set, defaults to 'center'
pad : float
The offset of the title from the top of the axes, in points.
Default is ``None`` to use rcParams['axes.titlepad'].
Returns
-------
text : :class:`~matplotlib.text.Text`
The matplotlib text instance representing the title
Other Parameters
----------------
**kwargs : `~matplotlib.text.Text` properties
Other keyword arguments are text properties, see
:class:`~matplotlib.text.Text` for a list of valid text
properties.
"""
try:
title = {'left': self._left_title,
'center': self.title,
'right': self._right_title}[loc.lower()]
except KeyError:
raise ValueError("'%s' is not a valid location" % loc)
default = {
'fontsize': rcParams['axes.titlesize'],
'fontweight': rcParams['axes.titleweight'],
'verticalalignment': 'baseline',
'horizontalalignment': loc.lower()}
if pad is None:
pad = rcParams['axes.titlepad']
self._set_title_offset_trans(float(pad))
title.set_text(label)
title.update(default)
if fontdict is not None:
title.update(fontdict)
title.update(kwargs)
return title
def get_xlabel(self):
"""
Get the xlabel text string.
"""
label = self.xaxis.get_label()
return label.get_text()
def set_xlabel(self, xlabel, fontdict=None, labelpad=None, **kwargs):
"""
Set the label for the x-axis.
Parameters
----------
xlabel : str
The label text.
labelpad : scalar, optional, default: None
Spacing in points between the label and the x-axis.
Other Parameters
----------------
**kwargs : `.Text` properties
`.Text` properties control the appearance of the label.
See also
--------
text : for information on how override and the optional args work
"""
if labelpad is not None:
self.xaxis.labelpad = labelpad
return self.xaxis.set_label_text(xlabel, fontdict, **kwargs)
def get_ylabel(self):
"""
Get the ylabel text string.
"""
label = self.yaxis.get_label()
return label.get_text()
def set_ylabel(self, ylabel, fontdict=None, labelpad=None, **kwargs):
"""
Set the label for the y-axis.
Parameters
----------
ylabel : str
The label text.
labelpad : scalar, optional, default: None
Spacing in points between the label and the y-axis.
Other Parameters
----------------
**kwargs : `.Text` properties
`.Text` properties control the appearance of the label.
See also
--------
text : for information on how override and the optional args work
"""
if labelpad is not None:
self.yaxis.labelpad = labelpad
return self.yaxis.set_label_text(ylabel, fontdict, **kwargs)
def get_legend_handles_labels(self, legend_handler_map=None):
"""
Return handles and labels for legend
``ax.legend()`` is equivalent to ::
h, l = ax.get_legend_handles_labels()
ax.legend(h, l)
"""
# pass through to legend.
handles, labels = mlegend._get_legend_handles_labels([self],
legend_handler_map)
return handles, labels
@docstring.dedent_interpd
def legend(self, *args, **kwargs):
"""
Places a legend on the axes.
Call signatures::
legend()
legend(labels)
legend(handles, labels)
The call signatures correspond to three different ways how to use
this method.
**1. Automatic detection of elements to be shown in the legend**
The elements to be added to the legend are automatically determined,
when you do not pass in any extra arguments.
In this case, the labels are taken from the artist. You can specify
them either at artist creation or by calling the
:meth:`~.Artist.set_label` method on the artist::
line, = ax.plot([1, 2, 3], label='Inline label')
ax.legend()
or::
line.set_label('Label via method')
line, = ax.plot([1, 2, 3])
ax.legend()
Specific lines can be excluded from the automatic legend element
selection by defining a label starting with an underscore.
This is default for all artists, so calling `Axes.legend` without
any arguments and without setting the labels manually will result in
no legend being drawn.
**2. Labeling existing plot elements**
To make a legend for lines which already exist on the axes
(via plot for instance), simply call this function with an iterable
of strings, one for each legend item. For example::
ax.plot([1, 2, 3])
ax.legend(['A simple line'])
Note: This way of using is discouraged, because the relation between
plot elements and labels is only implicit by their order and can
easily be mixed up.
**3. Explicitly defining the elements in the legend**
For full control of which artists have a legend entry, it is possible
to pass an iterable of legend artists followed by an iterable of
legend labels respectively::
legend((line1, line2, line3), ('label1', 'label2', 'label3'))
Parameters
----------
handles : sequence of `.Artist`, optional
A list of Artists (lines, patches) to be added to the legend.
Use this together with *labels*, if you need full control on what
is shown in the legend and the automatic mechanism described above
is not sufficient.
The length of handles and labels should be the same in this
case. If they are not, they are truncated to the smaller length.
labels : sequence of strings, optional
A list of labels to show next to the artists.
Use this together with *handles*, if you need full control on what
is shown in the legend and the automatic mechanism described above
is not sufficient.
Other Parameters
----------------
loc : int or string or pair of floats, default: 'upper right'
The location of the legend. Possible codes are:
=============== =============
Location String Location Code
=============== =============
'best' 0
'upper right' 1
'upper left' 2
'lower left' 3
'lower right' 4
'right' 5
'center left' 6
'center right' 7
'lower center' 8
'upper center' 9
'center' 10
=============== =============
Alternatively can be a 2-tuple giving ``x, y`` of the lower-left
corner of the legend in axes coordinates (in which case
``bbox_to_anchor`` will be ignored).
bbox_to_anchor : `.BboxBase` or pair of floats
Specify any arbitrary location for the legend in `bbox_transform`
coordinates (default Axes coordinates).
For example, to put the legend's upper right hand corner in the
center of the axes the following keywords can be used::
loc='upper right', bbox_to_anchor=(0.5, 0.5)
ncol : integer
The number of columns that the legend has. Default is 1.
prop : None or :class:`matplotlib.font_manager.FontProperties` or dict
The font properties of the legend. If None (default), the current
:data:`matplotlib.rcParams` will be used.
fontsize : int or float or {'xx-small', 'x-small', 'small', 'medium', \
'large', 'x-large', 'xx-large'}
Controls the font size of the legend. If the value is numeric the
size will be the absolute font size in points. String values are
relative to the current default font size. This argument is only
used if `prop` is not specified.
numpoints : None or int
The number of marker points in the legend when creating a legend
entry for a `.Line2D` (line).
Default is ``None``, which will take the value from
:rc:`legend.numpoints`.
scatterpoints : None or int
The number of marker points in the legend when creating
a legend entry for a `.PathCollection` (scatter plot).
Default is ``None``, which will take the value from
:rc:`legend.scatterpoints`.
scatteryoffsets : iterable of floats
The vertical offset (relative to the font size) for the markers
created for a scatter plot legend entry. 0.0 is at the base the
legend text, and 1.0 is at the top. To draw all markers at the
same height, set to ``[0.5]``. Default is ``[0.375, 0.5, 0.3125]``.
markerscale : None or int or float
The relative size of legend markers compared with the originally
drawn ones.
Default is ``None``, which will take the value from
:rc:`legend.markerscale`.
markerfirst : bool
If *True*, legend marker is placed to the left of the legend label.
If *False*, legend marker is placed to the right of the legend
label.
Default is *True*.
frameon : None or bool
Control whether the legend should be drawn on a patch
(frame).
Default is ``None``, which will take the value from
:rc:`legend.frameon`.
fancybox : None or bool
Control whether round edges should be enabled around the
:class:`~matplotlib.patches.FancyBboxPatch` which makes up the
legend's background.
Default is ``None``, which will take the value from
:rc:`legend.fancybox`.
shadow : None or bool
Control whether to draw a shadow behind the legend.
Default is ``None``, which will take the value from
:rc:`legend.shadow`.
framealpha : None or float
Control the alpha transparency of the legend's background.
Default is ``None``, which will take the value from
:rc:`legend.framealpha`. If shadow is activated and
*framealpha* is ``None``, the default value is ignored.
facecolor : None or "inherit" or a color spec
Control the legend's background color.
Default is ``None``, which will take the value from
:rc:`legend.facecolor`. If ``"inherit"``, it will take
:rc:`axes.facecolor`.
edgecolor : None or "inherit" or a color spec
Control the legend's background patch edge color.
Default is ``None``, which will take the value from
:rc:`legend.edgecolor` If ``"inherit"``, it will take
:rc:`axes.edgecolor`.
mode : {"expand", None}
If `mode` is set to ``"expand"`` the legend will be horizontally
expanded to fill the axes area (or `bbox_to_anchor` if defines
the legend's size).
bbox_transform : None or :class:`matplotlib.transforms.Transform`
The transform for the bounding box (`bbox_to_anchor`). For a value
of ``None`` (default) the Axes'
:data:`~matplotlib.axes.Axes.transAxes` transform will be used.
title : str or None
The legend's title. Default is no title (``None``).
borderpad : float or None
The fractional whitespace inside the legend border.
Measured in font-size units.
Default is ``None``, which will take the value from
:rc:`legend.borderpad`.
labelspacing : float or None
The vertical space between the legend entries.
Measured in font-size units.
Default is ``None``, which will take the value from
:rc:`legend.labelspacing`.
handlelength : float or None
The length of the legend handles.
Measured in font-size units.
Default is ``None``, which will take the value from
:rc:`legend.handlelength`.
handletextpad : float or None
The pad between the legend handle and text.
Measured in font-size units.
Default is ``None``, which will take the value from
:rc:`legend.handletextpad`.
borderaxespad : float or None
The pad between the axes and legend border.
Measured in font-size units.
Default is ``None``, which will take the value from
:rc:`legend.borderaxespad`.
columnspacing : float or None
The spacing between columns.
Measured in font-size units.
Default is ``None``, which will take the value from
:rc:`legend.columnspacing`.
handler_map : dict or None
The custom dictionary mapping instances or types to a legend
handler. This `handler_map` updates the default handler map
found at :func:`matplotlib.legend.Legend.get_legend_handler_map`.
Returns
-------
:class:`matplotlib.legend.Legend` instance
Notes
-----
Not all kinds of artist are supported by the legend command. See
:ref:`sphx_glr_tutorials_intermediate_legend_guide.py` for details.
Examples
--------
.. plot:: gallery/api/legend.py
"""
handles, labels, extra_args, kwargs = mlegend._parse_legend_args(
[self],
*args,
**kwargs)
if len(extra_args):
raise TypeError('legend only accepts two non-keyword arguments')
self.legend_ = mlegend.Legend(self, handles, labels, **kwargs)
self.legend_._remove_method = lambda h: setattr(self, 'legend_', None)
return self.legend_
def text(self, x, y, s, fontdict=None, withdash=False, **kwargs):
"""
Add text to the axes.
Add the text *s* to the axes at location *x*, *y* in data coordinates.
Parameters
----------
x, y : scalars
The position to place the text. By default, this is in data
coordinates. The coordinate system can be changed using the
*transform* parameter.
s : str
The text.
fontdict : dictionary, optional, default: None
A dictionary to override the default text properties. If fontdict
is None, the defaults are determined by your rc parameters.
withdash : boolean, optional, default: False
Creates a `~matplotlib.text.TextWithDash` instance instead of a
`~matplotlib.text.Text` instance.
Returns
-------
text : `.Text`
The created `.Text` instance.
Other Parameters
----------------
**kwargs : `~matplotlib.text.Text` properties.
Other miscellaneous text parameters.
Examples
--------
Individual keyword arguments can be used to override any given
parameter::
>>> text(x, y, s, fontsize=12)
The default transform specifies that text is in data coords,
alternatively, you can specify text in axis coords (0,0 is
lower-left and 1,1 is upper-right). The example below places
text in the center of the axes::
>>> text(0.5, 0.5, 'matplotlib', horizontalalignment='center',
... verticalalignment='center', transform=ax.transAxes)
You can put a rectangular box around the text instance (e.g., to
set a background color) by using the keyword `bbox`. `bbox` is
a dictionary of `~matplotlib.patches.Rectangle`
properties. For example::
>>> text(x, y, s, bbox=dict(facecolor='red', alpha=0.5))
"""
default = {
'verticalalignment': 'baseline',
'horizontalalignment': 'left',
'transform': self.transData,
'clip_on': False}
# At some point if we feel confident that TextWithDash
# is robust as a drop-in replacement for Text and that
# the performance impact of the heavier-weight class
# isn't too significant, it may make sense to eliminate
# the withdash kwarg and simply delegate whether there's
# a dash to TextWithDash and dashlength.
if withdash:
t = mtext.TextWithDash(
x=x, y=y, text=s)
else:
t = mtext.Text(
x=x, y=y, text=s)
t.update(default)
if fontdict is not None:
t.update(fontdict)
t.update(kwargs)
t.set_clip_path(self.patch)
self._add_text(t)
return t
@docstring.dedent_interpd
def annotate(self, *args, **kwargs):
a = mtext.Annotation(*args, **kwargs)
a.set_transform(mtransforms.IdentityTransform())
if 'clip_on' in kwargs:
a.set_clip_path(self.patch)
self._add_text(a)
return a
annotate.__doc__ = mtext.Annotation.__init__.__doc__
#### Lines and spans
@docstring.dedent_interpd
def axhline(self, y=0, xmin=0, xmax=1, **kwargs):
"""
Add a horizontal line across the axis.
Parameters
----------
y : scalar, optional, default: 0
y position in data coordinates of the horizontal line.
xmin : scalar, optional, default: 0
Should be between 0 and 1, 0 being the far left of the plot, 1 the
far right of the plot.
xmax : scalar, optional, default: 1
Should be between 0 and 1, 0 being the far left of the plot, 1 the
far right of the plot.
Returns
-------
:class:`~matplotlib.lines.Line2D`
Other Parameters
----------------
**kwargs :
Valid kwargs are :class:`~matplotlib.lines.Line2D` properties,
with the exception of 'transform':
%(Line2D)s
See also
--------
hlines : Add horizontal lines in data coordinates.
axhspan : Add a horizontal span (rectangle) across the axis.
Examples
--------
* draw a thick red hline at 'y' = 0 that spans the xrange::
>>> axhline(linewidth=4, color='r')
* draw a default hline at 'y' = 1 that spans the xrange::
>>> axhline(y=1)
* draw a default hline at 'y' = .5 that spans the middle half of
the xrange::
>>> axhline(y=.5, xmin=0.25, xmax=0.75)
"""
if "transform" in kwargs:
raise ValueError(
"'transform' is not allowed as a kwarg;"
+ "axhline generates its own transform.")
ymin, ymax = self.get_ybound()
# We need to strip away the units for comparison with
# non-unitized bounds
self._process_unit_info(ydata=y, kwargs=kwargs)
yy = self.convert_yunits(y)
scaley = (yy < ymin) or (yy > ymax)
trans = self.get_yaxis_transform(which='grid')
l = mlines.Line2D([xmin, xmax], [y, y], transform=trans, **kwargs)
self.add_line(l)
self.autoscale_view(scalex=False, scaley=scaley)
return l
@docstring.dedent_interpd
def axvline(self, x=0, ymin=0, ymax=1, **kwargs):
"""
Add a vertical line across the axes.
Parameters
----------
x : scalar, optional, default: 0
x position in data coordinates of the vertical line.
ymin : scalar, optional, default: 0
Should be between 0 and 1, 0 being the bottom of the plot, 1 the
top of the plot.
ymax : scalar, optional, default: 1
Should be between 0 and 1, 0 being the bottom of the plot, 1 the
top of the plot.
Returns
-------
:class:`~matplotlib.lines.Line2D`
Other Parameters
----------------
**kwargs :
Valid kwargs are :class:`~matplotlib.lines.Line2D` properties,
with the exception of 'transform':
%(Line2D)s
Examples
--------
* draw a thick red vline at *x* = 0 that spans the yrange::
>>> axvline(linewidth=4, color='r')
* draw a default vline at *x* = 1 that spans the yrange::
>>> axvline(x=1)
* draw a default vline at *x* = .5 that spans the middle half of
the yrange::
>>> axvline(x=.5, ymin=0.25, ymax=0.75)
See also
--------
vlines : Add vertical lines in data coordinates.
axvspan : Add a vertical span (rectangle) across the axis.
"""
if "transform" in kwargs:
raise ValueError(
"'transform' is not allowed as a kwarg;"
+ "axvline generates its own transform.")
xmin, xmax = self.get_xbound()
# We need to strip away the units for comparison with
# non-unitized bounds
self._process_unit_info(xdata=x, kwargs=kwargs)
xx = self.convert_xunits(x)
scalex = (xx < xmin) or (xx > xmax)
trans = self.get_xaxis_transform(which='grid')
l = mlines.Line2D([x, x], [ymin, ymax], transform=trans, **kwargs)
self.add_line(l)
self.autoscale_view(scalex=scalex, scaley=False)
return l
@docstring.dedent_interpd
def axhspan(self, ymin, ymax, xmin=0, xmax=1, **kwargs):
"""
Add a horizontal span (rectangle) across the axis.
Draw a horizontal span (rectangle) from *ymin* to *ymax*.
With the default values of *xmin* = 0 and *xmax* = 1, this
always spans the xrange, regardless of the xlim settings, even
if you change them, e.g., with the :meth:`set_xlim` command.
That is, the horizontal extent is in axes coords: 0=left,
0.5=middle, 1.0=right but the *y* location is in data
coordinates.
Parameters
----------
ymin : float
Lower limit of the horizontal span in data units.
ymax : float
Upper limit of the horizontal span in data units.
xmin : float, optional, default: 0
Lower limit of the vertical span in axes (relative
0-1) units.
xmax : float, optional, default: 1
Upper limit of the vertical span in axes (relative
0-1) units.
Returns
-------
Polygon : `~matplotlib.patches.Polygon`
Other Parameters
----------------
**kwargs : `~matplotlib.patches.Polygon` properties.
%(Polygon)s
See Also
--------
axvspan : Add a vertical span across the axes.
"""
trans = self.get_yaxis_transform(which='grid')
# process the unit information
self._process_unit_info([xmin, xmax], [ymin, ymax], kwargs=kwargs)
# first we need to strip away the units
xmin, xmax = self.convert_xunits([xmin, xmax])
ymin, ymax = self.convert_yunits([ymin, ymax])
verts = (xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin)
p = mpatches.Polygon(verts, **kwargs)
p.set_transform(trans)
self.add_patch(p)
self.autoscale_view(scalex=False)
return p
def axvspan(self, xmin, xmax, ymin=0, ymax=1, **kwargs):
"""
Add a vertical span (rectangle) across the axes.
Draw a vertical span (rectangle) from `xmin` to `xmax`. With
the default values of `ymin` = 0 and `ymax` = 1. This always
spans the yrange, regardless of the ylim settings, even if you
change them, e.g., with the :meth:`set_ylim` command. That is,
the vertical extent is in axes coords: 0=bottom, 0.5=middle,
1.0=top but the y location is in data coordinates.
Parameters
----------
xmin : scalar
Number indicating the first X-axis coordinate of the vertical
span rectangle in data units.
xmax : scalar
Number indicating the second X-axis coordinate of the vertical
span rectangle in data units.
ymin : scalar, optional
Number indicating the first Y-axis coordinate of the vertical
span rectangle in relative Y-axis units (0-1). Default to 0.
ymax : scalar, optional
Number indicating the second Y-axis coordinate of the vertical
span rectangle in relative Y-axis units (0-1). Default to 1.
Returns
-------
rectangle : matplotlib.patches.Polygon
Vertical span (rectangle) from (xmin, ymin) to (xmax, ymax).
Other Parameters
----------------
**kwargs
Optional parameters are properties of the class
matplotlib.patches.Polygon.
See Also
--------
axhspan : Add a horizontal span across the axes.
Examples
--------
Draw a vertical, green, translucent rectangle from x = 1.25 to
x = 1.55 that spans the yrange of the axes.
>>> axvspan(1.25, 1.55, facecolor='g', alpha=0.5)
"""
trans = self.get_xaxis_transform(which='grid')
# process the unit information
self._process_unit_info([xmin, xmax], [ymin, ymax], kwargs=kwargs)
# first we need to strip away the units
xmin, xmax = self.convert_xunits([xmin, xmax])
ymin, ymax = self.convert_yunits([ymin, ymax])
verts = [(xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin)]
p = mpatches.Polygon(verts, **kwargs)
p.set_transform(trans)
self.add_patch(p)
self.autoscale_view(scaley=False)
return p
@_preprocess_data(replace_names=["y", "xmin", "xmax", "colors"],
label_namer="y")
def hlines(self, y, xmin, xmax, colors='k', linestyles='solid',
label='', **kwargs):
"""
Plot horizontal lines at each *y* from *xmin* to *xmax*.
Parameters
----------
y : scalar or sequence of scalar
y-indexes where to plot the lines.
xmin, xmax : scalar or 1D array_like
Respective beginning and end of each line. If scalars are
provided, all lines will have same length.
colors : array_like of colors, optional, default: 'k'
linestyles : ['solid' | 'dashed' | 'dashdot' | 'dotted'], optional
label : string, optional, default: ''
Returns
-------
lines : `~matplotlib.collections.LineCollection`
Other Parameters
----------------
**kwargs : `~matplotlib.collections.LineCollection` properties.
See also
--------
vlines : vertical lines
axhline: horizontal line across the axes
"""
# We do the conversion first since not all unitized data is uniform
# process the unit information
self._process_unit_info([xmin, xmax], y, kwargs=kwargs)
y = self.convert_yunits(y)
xmin = self.convert_xunits(xmin)
xmax = self.convert_xunits(xmax)
if not iterable(y):
y = [y]
if not iterable(xmin):
xmin = [xmin]
if not iterable(xmax):
xmax = [xmax]
y, xmin, xmax = cbook.delete_masked_points(y, xmin, xmax)
y = np.ravel(y)
xmin = np.resize(xmin, y.shape)
xmax = np.resize(xmax, y.shape)
verts = [((thisxmin, thisy), (thisxmax, thisy))
for thisxmin, thisxmax, thisy in zip(xmin, xmax, y)]
lines = mcoll.LineCollection(verts, colors=colors,
linestyles=linestyles, label=label)
self.add_collection(lines, autolim=False)
lines.update(kwargs)
if len(y) > 0:
minx = min(xmin.min(), xmax.min())
maxx = max(xmin.max(), xmax.max())
miny = y.min()
maxy = y.max()
corners = (minx, miny), (maxx, maxy)
self.update_datalim(corners)
self.autoscale_view()
return lines
@_preprocess_data(replace_names=["x", "ymin", "ymax", "colors"],
label_namer="x")
def vlines(self, x, ymin, ymax, colors='k', linestyles='solid',
label='', **kwargs):
"""
Plot vertical lines.
Plot vertical lines at each *x* from *ymin* to *ymax*.
Parameters
----------
x : scalar or 1D array_like
x-indexes where to plot the lines.
ymin, ymax : scalar or 1D array_like
Respective beginning and end of each line. If scalars are
provided, all lines will have same length.
colors : array_like of colors, optional, default: 'k'
linestyles : ['solid' | 'dashed' | 'dashdot' | 'dotted'], optional
label : string, optional, default: ''
Returns
-------
lines : `~matplotlib.collections.LineCollection`
Other Parameters
----------------
**kwargs : `~matplotlib.collections.LineCollection` properties.
See also
--------
hlines : horizontal lines
axvline: vertical line across the axes
"""
self._process_unit_info(xdata=x, ydata=[ymin, ymax], kwargs=kwargs)
# We do the conversion first since not all unitized data is uniform
x = self.convert_xunits(x)
ymin = self.convert_yunits(ymin)
ymax = self.convert_yunits(ymax)
if not iterable(x):
x = [x]
if not iterable(ymin):
ymin = [ymin]
if not iterable(ymax):
ymax = [ymax]
x, ymin, ymax = cbook.delete_masked_points(x, ymin, ymax)
x = np.ravel(x)
ymin = np.resize(ymin, x.shape)
ymax = np.resize(ymax, x.shape)
verts = [((thisx, thisymin), (thisx, thisymax))
for thisx, thisymin, thisymax in zip(x, ymin, ymax)]
lines = mcoll.LineCollection(verts, colors=colors,
linestyles=linestyles, label=label)
self.add_collection(lines, autolim=False)
lines.update(kwargs)
if len(x) > 0:
minx = x.min()
maxx = x.max()
miny = min(ymin.min(), ymax.min())
maxy = max(ymin.max(), ymax.max())
corners = (minx, miny), (maxx, maxy)
self.update_datalim(corners)
self.autoscale_view()
return lines
@_preprocess_data(replace_names=["positions", "lineoffsets",
"linelengths", "linewidths",
"colors", "linestyles"],
label_namer=None)
@docstring.dedent_interpd
def eventplot(self, positions, orientation='horizontal', lineoffsets=1,
linelengths=1, linewidths=None, colors=None,
linestyles='solid', **kwargs):
"""
Plot identical parallel lines at the given positions.
*positions* should be a 1D or 2D array-like object, with each row
corresponding to a row or column of lines.
This type of plot is commonly used in neuroscience for representing
neural events, where it is usually called a spike raster, dot raster,
or raster plot.
However, it is useful in any situation where you wish to show the
timing or position of multiple sets of discrete events, such as the
arrival times of people to a business on each day of the month or the
date of hurricanes each year of the last century.
Parameters
----------
positions : 1D or 2D array-like object
Each value is an event. If *positions* is a 2D array-like, each
row corresponds to a row or a column of lines (depending on the
*orientation* parameter).
orientation : {'horizontal', 'vertical'}, optional
Controls the direction of the event collections:
- 'horizontal' : the lines are arranged horizontally in rows,
and are vertical.
- 'vertical' : the lines are arranged vertically in columns,
and are horizontal.
lineoffsets : scalar or sequence of scalars, optional, default: 1
The offset of the center of the lines from the origin, in the
direction orthogonal to *orientation*.
linelengths : scalar or sequence of scalars, optional, default: 1
The total height of the lines (i.e. the lines stretches from
``lineoffset - linelength/2`` to ``lineoffset + linelength/2``).
linewidths : scalar, scalar sequence or None, optional, default: None
The line width(s) of the event lines, in points. If it is None,
defaults to its rcParams setting.
colors : color, sequence of colors or None, optional, default: None
The color(s) of the event lines. If it is None, defaults to its
rcParams setting.
linestyles : str or tuple or a sequence of such values, optional
Default is 'solid'. Valid strings are ['solid', 'dashed',
'dashdot', 'dotted', '-', '--', '-.', ':']. Dash tuples
should be of the form::
(offset, onoffseq),
where *onoffseq* is an even length tuple of on and off ink
in points.
**kwargs : optional
Other keyword arguments are line collection properties. See
:class:`~matplotlib.collections.LineCollection` for a list of
the valid properties.
Returns
-------
A list of :class:`matplotlib.collections.EventCollection` objects that
were added.
Notes
-----
For *linelengths*, *linewidths*, *colors*, and *linestyles*, if only
a single value is given, that value is applied to all lines. If an
array-like is given, it must have the same length as *positions*, and
each value will be applied to the corresponding row of the array.
Examples
--------
.. plot:: gallery/lines_bars_and_markers/eventplot_demo.py
"""
self._process_unit_info(xdata=positions,
ydata=[lineoffsets, linelengths],
kwargs=kwargs)
# We do the conversion first since not all unitized data is uniform
positions = self.convert_xunits(positions)
lineoffsets = self.convert_yunits(lineoffsets)
linelengths = self.convert_yunits(linelengths)
if not iterable(positions):
positions = [positions]
elif any(iterable(position) for position in positions):
positions = [np.asanyarray(position) for position in positions]
else:
positions = [np.asanyarray(positions)]
if len(positions) == 0:
return []
# prevent 'singular' keys from **kwargs dict from overriding the effect
# of 'plural' keyword arguments (e.g. 'color' overriding 'colors')
colors = cbook.local_over_kwdict(colors, kwargs, 'color')
linewidths = cbook.local_over_kwdict(linewidths, kwargs, 'linewidth')
linestyles = cbook.local_over_kwdict(linestyles, kwargs, 'linestyle')
if not iterable(lineoffsets):
lineoffsets = [lineoffsets]
if not iterable(linelengths):
linelengths = [linelengths]
if not iterable(linewidths):
linewidths = [linewidths]
if not iterable(colors):
colors = [colors]
if hasattr(linestyles, 'lower') or not iterable(linestyles):
linestyles = [linestyles]
lineoffsets = np.asarray(lineoffsets)
linelengths = np.asarray(linelengths)
linewidths = np.asarray(linewidths)
if len(lineoffsets) == 0:
lineoffsets = [None]
if len(linelengths) == 0:
linelengths = [None]
if len(linewidths) == 0:
lineoffsets = [None]
if len(linewidths) == 0:
lineoffsets = [None]
if len(colors) == 0:
colors = [None]
try:
# Early conversion of the colors into RGBA values to take care
# of cases like colors='0.5' or colors='C1'. (Issue #8193)
colors = mcolors.to_rgba_array(colors)
except ValueError:
# Will fail if any element of *colors* is None. But as long
# as len(colors) == 1 or len(positions), the rest of the
# code should process *colors* properly.
pass
if len(lineoffsets) == 1 and len(positions) != 1:
lineoffsets = np.tile(lineoffsets, len(positions))
lineoffsets[0] = 0
lineoffsets = np.cumsum(lineoffsets)
if len(linelengths) == 1:
linelengths = np.tile(linelengths, len(positions))
if len(linewidths) == 1:
linewidths = np.tile(linewidths, len(positions))
if len(colors) == 1:
colors = list(colors)
colors = colors * len(positions)
if len(linestyles) == 1:
linestyles = [linestyles] * len(positions)
if len(lineoffsets) != len(positions):
raise ValueError('lineoffsets and positions are unequal sized '
'sequences')
if len(linelengths) != len(positions):
raise ValueError('linelengths and positions are unequal sized '
'sequences')
if len(linewidths) != len(positions):
raise ValueError('linewidths and positions are unequal sized '
'sequences')
if len(colors) != len(positions):
raise ValueError('colors and positions are unequal sized '
'sequences')
if len(linestyles) != len(positions):
raise ValueError('linestyles and positions are unequal sized '
'sequences')
colls = []
for position, lineoffset, linelength, linewidth, color, linestyle in \
zip(positions, lineoffsets, linelengths, linewidths,
colors, linestyles):
coll = mcoll.EventCollection(position,
orientation=orientation,
lineoffset=lineoffset,
linelength=linelength,
linewidth=linewidth,
color=color,
linestyle=linestyle)
self.add_collection(coll, autolim=False)
coll.update(kwargs)
colls.append(coll)
if len(positions) > 0:
# try to get min/max
min_max = [(np.min(_p), np.max(_p)) for _p in positions
if len(_p) > 0]
# if we have any non-empty positions, try to autoscale
if len(min_max) > 0:
mins, maxes = zip(*min_max)
minpos = np.min(mins)
maxpos = np.max(maxes)
minline = (lineoffsets - linelengths).min()
maxline = (lineoffsets + linelengths).max()
if (orientation is not None and
orientation.lower() == "vertical"):
corners = (minline, minpos), (maxline, maxpos)
else: # "horizontal", None or "none" (see EventCollection)
corners = (minpos, minline), (maxpos, maxline)
self.update_datalim(corners)
self.autoscale_view()
return colls
# ### Basic plotting
# The label_naming happens in `matplotlib.axes._base._plot_args`
@_preprocess_data(replace_names=["x", "y"],
positional_parameter_names=_plot_args_replacer,
label_namer=None)
@docstring.dedent_interpd
def plot(self, *args, **kwargs):
"""
Plot y versus x as lines and/or markers.
Call signatures::
plot([x], y, [fmt], data=None, **kwargs)
plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)
The coordinates of the points or line nodes are given by *x*, *y*.
The optional parameter *fmt* is a convenient way for defining basic
formatting like color, marker and linestyle. It's a shortcut string
notation described in the *Notes* section below.
>>> plot(x, y) # plot x and y using default line style and color
>>> plot(x, y, 'bo') # plot x and y using blue circle markers
>>> plot(y) # plot y using x as index array 0..N-1
>>> plot(y, 'r+') # ditto, but with red plusses
You can use `.Line2D` properties as keyword arguments for more
control on the appearance. Line properties and *fmt* can be mixed.
The following two calls yield identical results:
>>> plot(x, y, 'go--', linewidth=2, markersize=12)
>>> plot(x, y, color='green', marker='o', linestyle='dashed',
linewidth=2, markersize=12)
When conflicting with *fmt*, keyword arguments take precedence.
**Plotting labelled data**
There's a convenient way for plotting objects with labelled data (i.e.
data that can be accessed by index ``obj['y']``). Instead of giving
the data in *x* and *y*, you can provide the object in the *data*
parameter and just give the labels for *x* and *y*::
>>> plot('xlabel', 'ylabel', data=obj)
All indexable objects are supported. This could e.g. be a `dict`, a
`pandas.DataFame` or a structured numpy array.
**Plotting multiple sets of data**
There are various ways to plot multiple sets of data.
- The most straight forward way is just to call `plot` multiple times.
Example:
>>> plot(x1, y1, 'bo')
>>> plot(x2, y2, 'go')
- Alternatively, if your data is already a 2d array, you can pass it
directly to *x*, *y*. A separate data set will be drawn for every
column.
Example: an array ``a`` where the first column represents the *x*
values and the other columns are the *y* columns::
>>> plot(a[0], a[1:])
- The third way is to specify multiple sets of *[x]*, *y*, *[fmt]*
groups::
>>> plot(x1, y1, 'g^', x2, y2, 'g-')
In this case, any additional keyword argument applies to all
datasets. Also this syntax cannot be combined with the *data*
parameter.
By default, each line is assigned a different style specified by a
'style cycle'. The *fmt* and line property parameters are only
necessary if you want explicit deviations from these defaults.
Alternatively, you can also change the style cycle using the
'axes.prop_cycle' rcParam.
Parameters
----------
x, y : array-like or scalar
The horizontal / vertical coordinates of the data points.
*x* values are optional. If not given, they default to
``[0, ..., N-1]``.
Commonly, these parameters are arrays of length N. However,
scalars are supported as well (equivalent to an array with
constant value).
The parameters can also be 2-dimensional. Then, the columns
represent separate data sets.
fmt : str, optional
A format string, e.g. 'ro' for red circles. See the *Notes*
section for a full description of the format strings.
Format strings are just an abbreviation for quickly setting
basic line properties. All of these and more can also be
controlled by keyword arguments.
data : indexable object, optional
An object with labelled data. If given, provide the label names to
plot in *x* and *y*.
.. note::
Technically there's a slight ambiguity in calls where the
second label is a valid *fmt*. `plot('n', 'o', data=obj)`
could be `plt(x, y)` or `plt(y, fmt)`. In such cases,
the former interpretation is chosen, but a warning is issued.
You may suppress the warning by adding an empty format string
`plot('n', 'o', '', data=obj)`.
Other Parameters
----------------
scalex, scaley : bool, optional, default: True
These parameters determined if the view limits are adapted to
the data limits. The values are passed on to `autoscale_view`.
**kwargs : `.Line2D` properties, optional
*kwargs* are used to specify properties like a line label (for
auto legends), linewidth, antialiasing, marker face color.
Example::
>>> plot([1,2,3], [1,2,3], 'go-', label='line 1', linewidth=2)
>>> plot([1,2,3], [1,4,9], 'rs', label='line 2')
If you make multiple lines with one plot command, the kwargs
apply to all those lines.
Here is a list of available `.Line2D` properties:
%(Line2D)s
Returns
-------
lines
A list of `.Line2D` objects representing the plotted data.
See Also
--------
scatter : XY scatter plot with markers of variing size and/or color (
sometimes also called bubble chart).
Notes
-----
**Format Strings**
A format string consists of a part for color, marker and line::
fmt = '[color][marker][line]'
Each of them is optional. If not provided, the value from the style
cycle is used. Exception: If ``line`` is given, but no ``marker``,
the data will be a line without markers.
**Colors**
The following color abbreviations are supported:
============= ===============================
character color
============= ===============================
``'b'`` blue
``'g'`` green
``'r'`` red
``'c'`` cyan
``'m'`` magenta
``'y'`` yellow
``'k'`` black
``'w'`` white
============= ===============================
If the color is the only part of the format string, you can
additionally use any `matplotlib.colors` spec, e.g. full names
(``'green'``) or hex strings (``'#008000'``).
**Markers**
============= ===============================
character description
============= ===============================
``'.'`` point marker
``','`` pixel marker
``'o'`` circle marker
``'v'`` triangle_down marker
``'^'`` triangle_up marker
``'<'`` triangle_left marker
``'>'`` triangle_right marker
``'1'`` tri_down marker
``'2'`` tri_up marker
``'3'`` tri_left marker
``'4'`` tri_right marker
``'s'`` square marker
``'p'`` pentagon marker
``'*'`` star marker
``'h'`` hexagon1 marker
``'H'`` hexagon2 marker
``'+'`` plus marker
``'x'`` x marker
``'D'`` diamond marker
``'d'`` thin_diamond marker
``'|'`` vline marker
``'_'`` hline marker
============= ===============================
**Line Styles**
============= ===============================
character description
============= ===============================
``'-'`` solid line style
``'--'`` dashed line style
``'-.'`` dash-dot line style
``':'`` dotted line style
============= ===============================
Example format strings::
'b' # blue markers with default shape
'ro' # red circles
'g-' # green solid line
'--' # dashed line with default color
'k^:' # black triangle_up markers connected by a dotted line
"""
scalex = kwargs.pop('scalex', True)
scaley = kwargs.pop('scaley', True)
if not self._hold:
self.cla()
lines = []
kwargs = cbook.normalize_kwargs(kwargs, _alias_map)
for line in self._get_lines(*args, **kwargs):
self.add_line(line)
lines.append(line)
self.autoscale_view(scalex=scalex, scaley=scaley)
return lines
@_preprocess_data(replace_names=["x", "y"], label_namer="y")
@docstring.dedent_interpd
def plot_date(self, x, y, fmt='o', tz=None, xdate=True, ydate=False,
**kwargs):
"""
Plot data that contains dates.
Similar to `.plot`, this plots *y* vs. *x* as lines or markers.
However, the axis labels are formatted as dates depending on *xdate*
and *ydate*.
Parameters
----------
x, y : array-like
The coordinates of the data points. If *xdate* or *ydate* is
*True*, the respective values *x* or *y* are interpreted as
:ref:`Matplotlib dates <date-format>`.
fmt : str, optional
The plot format string. For details, see the corresponding
parameter in `.plot`.
tz : [ *None* | timezone string | :class:`tzinfo` instance]
The time zone to use in labeling dates. If *None*, defaults to
rcParam ``timezone``.
xdate : bool, optional, default: True
If *True*, the *x*-axis will be interpreted as Matplotlib dates.
ydate : bool, optional, default: False
If *True*, the *y*-axis will be interpreted as Matplotlib dates.
Returns
-------
lines
A list of `~.Line2D` objects representing the plotted data.
Other Parameters
----------------
**kwargs
Keyword arguments control the :class:`~matplotlib.lines.Line2D`
properties:
%(Line2D)s
See Also
--------
matplotlib.dates : Helper functions on dates.
matplotlib.dates.date2num : Convert dates to num.
matplotlib.dates.num2date : Convert num to dates.
matplotlib.dates.drange : Create an equally spaced sequence of dates.
Notes
-----
If you are using custom date tickers and formatters, it may be
necessary to set the formatters/locators after the call to
`.plot_date`. `.plot_date` will set the default tick locator to
`.AutoDateLocator` (if the tick locator is not already set to a
`.DateLocator` instance) and the default tick formatter to
`.AutoDateFormatter` (if the tick formatter is not already set to a
`.DateFormatter` instance).
"""
if not self._hold:
self.cla()
if xdate:
self.xaxis_date(tz)
if ydate:
self.yaxis_date(tz)
ret = self.plot(x, y, fmt, **kwargs)
self.autoscale_view()
return ret
# @_preprocess_data() # let 'plot' do the unpacking..
@docstring.dedent_interpd
def loglog(self, *args, **kwargs):
"""
Make a plot with log scaling on both the x and y axis.
Call signatures::
loglog([x], y, [fmt], data=None, **kwargs)
loglog([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)
This is just a thin wrapper around `.plot` which additionally changes
both the x-axis and the y-axis to log scaling. All of the concepts and
parameters of plot can be used here as well.
The additional parameters *basex/y*, *subsx/y* and *nonposx/y* control
the x/y-axis properties. They are just forwarded to `.Axes.set_xscale`
and `.Axes.set_yscale`.
Parameters
----------
basex, basey : scalar, optional, default 10
Base of the x/y logarithm.
subsx, subsy : sequence, optional
The location of the minor x/y ticks. If *None*, reasonable
locations are automatically chosen depending on the number of
decades in the plot.
See `.Axes.set_xscale` / `.Axes.set_yscale` for details.
nonposx, nonposy : {'mask', 'clip'}, optional, default 'mask'
Non-positive values in x or y can be masked as invalid, or clipped
to a very small positive number.
Returns
-------
lines
A list of `~.Line2D` objects representing the plotted data.
Other Parameters
----------------
**kwargs
All parameters supported by `.plot`.
"""
if not self._hold:
self.cla()
dx = {k: kwargs.pop(k) for k in ['basex', 'subsx', 'nonposx']
if k in kwargs}
dy = {k: kwargs.pop(k) for k in ['basey', 'subsy', 'nonposy']
if k in kwargs}
self.set_xscale('log', **dx)
self.set_yscale('log', **dy)
b = self._hold
self._hold = True # we've already processed the hold
l = self.plot(*args, **kwargs)
self._hold = b # restore the hold
return l
# @_preprocess_data() # let 'plot' do the unpacking..
@docstring.dedent_interpd
def semilogx(self, *args, **kwargs):
"""
Make a plot with log scaling on the x axis.
Call signatures::
semilogx([x], y, [fmt], data=None, **kwargs)
semilogx([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)
This is just a thin wrapper around `.plot` which additionally changes
the x-axis to log scaling. All of the concepts and parameters of plot
can be used here as well.
The additional parameters *basex*, *subsx* and *nonposx* control the
x-axis properties. They are just forwarded to `.Axes.set_xscale`.
Parameters
----------
basex : scalar, optional, default 10
Base of the x logarithm.
subsx : array_like, optional
The location of the minor xticks. If *None*, reasonable locations
are automatically chosen depending on the number of decades in the
plot. See `.Axes.set_xscale` for details.
nonposx : {'mask', 'clip'}, optional, default 'mask'
Non-positive values in x can be masked as invalid, or clipped to a
very small positive number.
Returns
-------
lines
A list of `~.Line2D` objects representing the plotted data.
Other Parameters
----------------
**kwargs
All parameters supported by `.plot`.
"""
if not self._hold:
self.cla()
d = {k: kwargs.pop(k) for k in ['basex', 'subsx', 'nonposx']
if k in kwargs}
self.set_xscale('log', **d)
b = self._hold
self._hold = True # we've already processed the hold
l = self.plot(*args, **kwargs)
self._hold = b # restore the hold
return l
# @_preprocess_data() # let 'plot' do the unpacking..
@docstring.dedent_interpd
def semilogy(self, *args, **kwargs):
"""
Make a plot with log scaling on the y axis.
Call signatures::
semilogy([x], y, [fmt], data=None, **kwargs)
semilogy([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)
This is just a thin wrapper around `.plot` which additionally changes
the y-axis to log scaling. All of the concepts and parameters of plot
can be used here as well.
The additional parameters *basey*, *subsy* and *nonposy* control the
y-axis properties. They are just forwarded to `.Axes.set_yscale`.
Parameters
----------
basey : scalar, optional, default 10
Base of the y logarithm.
subsy : array_like, optional
The location of the minor yticks. If *None*, reasonable locations
are automatically chosen depending on the number of decades in the
plot. See `.Axes.set_yscale` for details.
nonposy : {'mask', 'clip'}, optional, default 'mask'
Non-positive values in y can be masked as invalid, or clipped to a
very small positive number.
Returns
-------
lines
A list of `~.Line2D` objects representing the plotted data.
Other Parameters
----------------
**kwargs
All parameters supported by `.plot`.
"""
if not self._hold:
self.cla()
d = {k: kwargs.pop(k) for k in ['basey', 'subsy', 'nonposy']
if k in kwargs}
self.set_yscale('log', **d)
b = self._hold
self._hold = True # we've already processed the hold
l = self.plot(*args, **kwargs)
self._hold = b # restore the hold
return l
@_preprocess_data(replace_names=["x"], label_namer="x")
def acorr(self, x, **kwargs):
"""
Plot the autocorrelation of *x*.
Parameters
----------
x : sequence of scalar
hold : bool, optional, *deprecated*, default: True
detrend : callable, optional, default: `mlab.detrend_none`
*x* is detrended by the *detrend* callable. Default is no
normalization.
normed : bool, optional, default: True
If ``True``, input vectors are normalised to unit length.
usevlines : bool, optional, default: True
If ``True``, `Axes.vlines` is used to plot the vertical lines from
the origin to the acorr. Otherwise, `Axes.plot` is used.
maxlags : integer, optional, default: 10
Number of lags to show. If ``None``, will return all
``2 * len(x) - 1`` lags.
Returns
-------
lags : array (lenth ``2*maxlags+1``)
lag vector.
c : array (length ``2*maxlags+1``)
auto correlation vector.
line : `.LineCollection` or `.Line2D`
`.Artist` added to the axes of the correlation.
`.LineCollection` if *usevlines* is True
`.Line2D` if *usevlines* is False
b : `.Line2D` or None
Horizontal line at 0 if *usevlines* is True
None *usevlines* is False
Other Parameters
----------------
linestyle : `~matplotlib.lines.Line2D` prop, optional, default: None
Only used if usevlines is ``False``.
marker : string, optional, default: 'o'
Notes
-----
The cross correlation is performed with :func:`numpy.correlate` with
``mode = 2``.
"""
if "hold" in kwargs:
warnings.warn("the 'hold' kwarg is deprecated", mplDeprecation)
return self.xcorr(x, x, **kwargs)
@_preprocess_data(replace_names=["x", "y"], label_namer="y")
def xcorr(self, x, y, normed=True, detrend=mlab.detrend_none,
usevlines=True, maxlags=10, **kwargs):
"""
Plot the cross correlation between *x* and *y*.
The correlation with lag k is defined as sum_n x[n+k] * conj(y[n]).
Parameters
----------
x : sequence of scalars of length n
y : sequence of scalars of length n
hold : bool, optional, *deprecated*, default: True
detrend : callable, optional, default: `mlab.detrend_none`
*x* is detrended by the *detrend* callable. Default is no
normalization.
normed : bool, optional, default: True
If ``True``, input vectors are normalised to unit length.
usevlines : bool, optional, default: True
If ``True``, `Axes.vlines` is used to plot the vertical lines from
the origin to the acorr. Otherwise, `Axes.plot` is used.
maxlags : int, optional
Number of lags to show. If None, will return all ``2 * len(x) - 1``
lags. Default is 10.
Returns
-------
lags : array (lenth ``2*maxlags+1``)
lag vector.
c : array (length ``2*maxlags+1``)
auto correlation vector.
line : `.LineCollection` or `.Line2D`
`.Artist` added to the axes of the correlation
`.LineCollection` if *usevlines* is True
`.Line2D` if *usevlines* is False
b : `.Line2D` or None
Horizontal line at 0 if *usevlines* is True
None *usevlines* is False
Other Parameters
----------------
linestyle : `~matplotlib.lines.Line2D` property, optional
Only used if usevlines is ``False``.
marker : string, optional
Default is 'o'.
Notes
-----
The cross correlation is performed with :func:`numpy.correlate` with
``mode = 2``.
"""
if "hold" in kwargs:
warnings.warn("the 'hold' kwarg is deprecated", mplDeprecation)
Nx = len(x)
if Nx != len(y):
raise ValueError('x and y must be equal length')
x = detrend(np.asarray(x))
y = detrend(np.asarray(y))
correls = np.correlate(x, y, mode=2)
if normed:
correls /= np.sqrt(np.dot(x, x) * np.dot(y, y))
if maxlags is None:
maxlags = Nx - 1
if maxlags >= Nx or maxlags < 1:
raise ValueError('maxlags must be None or strictly '
'positive < %d' % Nx)
lags = np.arange(-maxlags, maxlags + 1)
correls = correls[Nx - 1 - maxlags:Nx + maxlags]
if usevlines:
a = self.vlines(lags, [0], correls, **kwargs)
# Make label empty so only vertical lines get a legend entry
kwargs.pop('label', '')
b = self.axhline(**kwargs)
else:
kwargs.setdefault('marker', 'o')
kwargs.setdefault('linestyle', 'None')
a, = self.plot(lags, correls, **kwargs)
b = None
return lags, correls, a, b
#### Specialized plotting
@_preprocess_data(replace_names=["x", "y"], label_namer="y")
def step(self, x, y, *args, **kwargs):
"""
Make a step plot.
Call signatures::
step(x, y, [fmt], *, data=None, where='pre', **kwargs)
step(x, y, [fmt], x2, y2, [fmt2], ..., *, where='pre', **kwargs)
This is just a thin wrapper around `.plot` which changes some
formatting options. Most of the concepts and parameters of plot can be
used here as well.
Parameters
----------
x : array_like
1-D sequence of x positions. It is assumed, but not checked, that
it is uniformly increasing.
y : array_like
1-D sequence of y levels.
fmt : str, optional
A format string, e.g. 'g' for a green line. See `.plot` for a more
detailed description.
Note: While full format strings are accepted, it is recommended to
only specify the color. Line styles are currently ignored (use
the keyword argument *linestyle* instead). Markers are accepted
and plotted on the given positions, however, this is a rarely
needed feature for step plots.
data : indexable object, optional
An object with labelled data. If given, provide the label names to
plot in *x* and *y*.
where : {'pre', 'post', 'mid'}, optional, default 'pre'
Define where the steps should be placed:
- 'pre': The y value is continued constantly to the left from
every *x* position, i.e. the interval ``(x[i-1], x[i]]`` has the
value ``y[i]``.
- 'post': The y value is continued constantly to the right from
every *x* position, i.e. the interval ``[x[i], x[i+1])`` has the
value ``y[i]``.
- 'mid': Steps occur half-way between the *x* positions.
Returns
-------
lines
A list of `.Line2D` objects representing the plotted data.
Other Parameters
----------------
**kwargs
Additional parameters are the same as those for `.plot`.
Notes
-----
.. [notes section required to get data note injection right]
"""
where = kwargs.pop('where', 'pre')
if where not in ('pre', 'post', 'mid'):
raise ValueError("'where' argument to step must be "
"'pre', 'post' or 'mid'")
usr_linestyle = kwargs.pop('linestyle', '')
kwargs['linestyle'] = 'steps-' + where + usr_linestyle
return self.plot(x, y, *args, **kwargs)
@_preprocess_data(replace_names=["x", "left",
"height", "width",
"y", "bottom",
"color", "edgecolor", "linewidth",
"tick_label", "xerr", "yerr",
"ecolor"],
label_namer=None,
replace_all_args=True
)
@docstring.dedent_interpd
def bar(self, *args, **kwargs):
r"""
Make a bar plot.
Call signatures::
bar(x, height, *, align='center', **kwargs)
bar(x, height, width, *, align='center', **kwargs)
bar(x, height, width, bottom, *, align='center', **kwargs)
The bars are positioned at *x* with the given *align* ment. Their
dimensions are given by *width* and *height*. The vertical baseline
is *bottom* (default 0).
Each of *x*, *height*, *width*, and *bottom* may either be a scalar
applying to all bars, or it may be a sequence of length N providing a
separate value for each bar.
Parameters
----------
x : sequence of scalars
The x coordinates of the bars. See also *align* for the
alignment of the bars to the coordinates.
height : scalar or sequence of scalars
The height(s) of the bars.
width : scalar or array-like, optional
The width(s) of the bars (default: 0.8).
bottom : scalar or array-like, optional
The y coordinate(s) of the bars bases (default: 0).
align : {'center', 'edge'}, optional, default: 'center'
Alignment of the bars to the *x* coordinates:
- 'center': Center the base on the *x* positions.
- 'edge': Align the left edges of the bars with the *x* positions.
To align the bars on the right edge pass a negative *width* and
``align='edge'``.
Returns
-------
`.BarContainer`
Container with all the bars and optionally errorbars.
Other Parameters
----------------
color : scalar or array-like, optional
The colors of the bar faces.
edgecolor : scalar or array-like, optional
The colors of the bar edges.
linewidth : scalar or array-like, optional
Width of the bar edge(s). If 0, don't draw edges.
tick_label : string or array-like, optional
The tick labels of the bars.
Default: None (Use default numeric labels.)
xerr, yerr : scalar or array-like of shape(N,) or shape(2,N), optional
If not *None*, add horizontal / vertical errorbars to the bar tips.
The values are +/- sizes relative to the data:
- scalar: symmetric +/- values for all bars
- shape(N,): symmetric +/- values for each bar
- shape(2,N): separate + and - values for each bar
Default: None
ecolor : scalar or array-like, optional, default: 'black'
The line color of the errorbars.
capsize : scalar, optional
The length of the error bar caps in points.
Default: None, which will take the value from
:rc:`errorbar.capsize`.
error_kw : dict, optional
Dictionary of kwargs to be passed to the `~.Axes.errorbar`
method. Values of *ecolor* or *capsize* defined here take
precedence over the independent kwargs.
log : bool, optional, default: False
If *True*, set the y-axis to be log scale.
orientation : {'vertical', 'horizontal'}, optional
*This is for internal use only.* Please use `barh` for
horizontal bar plots. Default: 'vertical'.
See also
--------
barh: Plot a horizontal bar plot.
Notes
-----
The optional arguments *color*, *edgecolor*, *linewidth*,
*xerr*, and *yerr* can be either scalars or sequences of
length equal to the number of bars. This enables you to use
bar as the basis for stacked bar charts, or candlestick plots.
Detail: *xerr* and *yerr* are passed directly to
:meth:`errorbar`, so they can also have shape 2xN for
independent specification of lower and upper errors.
Other optional kwargs:
%(Rectangle)s
"""
kwargs = cbook.normalize_kwargs(kwargs, mpatches._patch_alias_map)
# this is using the lambdas to do the arg/kwarg unpacking rather
# than trying to re-implement all of that logic our selves.
matchers = [
(lambda x, height, width=0.8, bottom=None, **kwargs:
(False, x, height, width, bottom, kwargs)),
(lambda left, height, width=0.8, bottom=None, **kwargs:
(True, left, height, width, bottom, kwargs)),
]
exps = []
for matcher in matchers:
try:
dp, x, height, width, y, kwargs = matcher(*args, **kwargs)
except TypeError as e:
# This can only come from a no-match as there is
# no other logic in the matchers.
exps.append(e)
else:
break
else:
raise exps[0]
# if we matched the second-case, then the user passed in
# left=val as a kwarg which we want to deprecate
if dp:
warnings.warn(
"The *left* kwarg to `bar` is deprecated use *x* instead. "
"Support for *left* will be removed in Matplotlib 3.0",
mplDeprecation, stacklevel=2)
if not self._hold:
self.cla()
color = kwargs.pop('color', None)
if color is None:
color = self._get_patches_for_fill.get_next_color()
edgecolor = kwargs.pop('edgecolor', None)
linewidth = kwargs.pop('linewidth', None)
# Because xerr and yerr will be passed to errorbar,
# most dimension checking and processing will be left
# to the errorbar method.
xerr = kwargs.pop('xerr', None)
yerr = kwargs.pop('yerr', None)
error_kw = kwargs.pop('error_kw', dict())
ecolor = kwargs.pop('ecolor', 'k')
capsize = kwargs.pop('capsize', rcParams["errorbar.capsize"])
error_kw.setdefault('ecolor', ecolor)
error_kw.setdefault('capsize', capsize)
if rcParams['_internal.classic_mode']:
align = kwargs.pop('align', 'edge')
else:
align = kwargs.pop('align', 'center')
orientation = kwargs.pop('orientation', 'vertical')
log = kwargs.pop('log', False)
label = kwargs.pop('label', '')
tick_labels = kwargs.pop('tick_label', None)
adjust_ylim = False
adjust_xlim = False
if orientation == 'vertical':
if y is None:
if self.get_yscale() == 'log':
adjust_ylim = True
y = 0
elif orientation == 'horizontal':
if x is None:
if self.get_xscale() == 'log':
adjust_xlim = True
x = 0
if orientation == 'vertical':
self._process_unit_info(xdata=x, ydata=height, kwargs=kwargs)
if log:
self.set_yscale('log', nonposy='clip')
elif orientation == 'horizontal':
self._process_unit_info(xdata=width, ydata=y, kwargs=kwargs)
if log:
self.set_xscale('log', nonposx='clip')
else:
raise ValueError('invalid orientation: %s' % orientation)
# lets do some conversions now since some types cannot be
# subtracted uniformly
if self.xaxis is not None:
x = self.convert_xunits(x)
width = self.convert_xunits(width)
if xerr is not None:
xerr = self.convert_xunits(xerr)
if self.yaxis is not None:
y = self.convert_yunits(y)
height = self.convert_yunits(height)
if yerr is not None:
yerr = self.convert_yunits(yerr)
x, height, width, y, linewidth = np.broadcast_arrays(
# Make args iterable too.
np.atleast_1d(x), height, width, y, linewidth)
# Now that units have been converted, set the tick locations.
if orientation == 'vertical':
tick_label_axis = self.xaxis
tick_label_position = x
elif orientation == 'horizontal':
tick_label_axis = self.yaxis
tick_label_position = y
linewidth = itertools.cycle(np.atleast_1d(linewidth))
color = itertools.chain(itertools.cycle(mcolors.to_rgba_array(color)),
# Fallback if color == "none".
itertools.repeat([0, 0, 0, 0]))
if edgecolor is None:
edgecolor = itertools.repeat(None)
else:
edgecolor = itertools.chain(
itertools.cycle(mcolors.to_rgba_array(edgecolor)),
# Fallback if edgecolor == "none".
itertools.repeat([0, 0, 0, 0]))
# We will now resolve the alignment and really have
# left, bottom, width, height vectors
if align == 'center':
if orientation == 'vertical':
left = x - width / 2
bottom = y
elif orientation == 'horizontal':
bottom = y - height / 2
left = x
elif align == 'edge':
left = x
bottom = y
else:
raise ValueError('invalid alignment: %s' % align)
patches = []
args = zip(left, bottom, width, height, color, edgecolor, linewidth)
for l, b, w, h, c, e, lw in args:
r = mpatches.Rectangle(
xy=(l, b), width=w, height=h,
facecolor=c,
edgecolor=e,
linewidth=lw,
label='_nolegend_',
)
r.update(kwargs)
r.get_path()._interpolation_steps = 100
if orientation == 'vertical':
r.sticky_edges.y.append(b)
elif orientation == 'horizontal':
r.sticky_edges.x.append(l)
self.add_patch(r)
patches.append(r)
holdstate = self._hold
self._hold = True # ensure hold is on before plotting errorbars
if xerr is not None or yerr is not None:
if orientation == 'vertical':
# using list comps rather than arrays to preserve unit info
ex = [l + 0.5 * w for l, w in zip(left, width)]
ey = [b + h for b, h in zip(bottom, height)]
elif orientation == 'horizontal':
# using list comps rather than arrays to preserve unit info
ex = [l + w for l, w in zip(left, width)]
ey = [b + 0.5 * h for b, h in zip(bottom, height)]
error_kw.setdefault("label", '_nolegend_')
errorbar = self.errorbar(ex, ey,
yerr=yerr, xerr=xerr,
fmt='none', **error_kw)
else:
errorbar = None
self._hold = holdstate # restore previous hold state
if adjust_xlim:
xmin, xmax = self.dataLim.intervalx
xmin = min(w for w in width if w > 0)
if xerr is not None:
xmin = xmin - np.max(xerr)
xmin = max(xmin * 0.9, 1e-100)
self.dataLim.intervalx = (xmin, xmax)
if adjust_ylim:
ymin, ymax = self.dataLim.intervaly
ymin = min(h for h in height if h > 0)
if yerr is not None:
ymin = ymin - np.max(yerr)
ymin = max(ymin * 0.9, 1e-100)
self.dataLim.intervaly = (ymin, ymax)
self.autoscale_view()
bar_container = BarContainer(patches, errorbar, label=label)
self.add_container(bar_container)
if tick_labels is not None:
tick_labels = _backports.broadcast_to(tick_labels, len(patches))
tick_label_axis.set_ticks(tick_label_position)
tick_label_axis.set_ticklabels(tick_labels)
return bar_container
@docstring.dedent_interpd
def barh(self, *args, **kwargs):
r"""
Make a horizontal bar plot.
Call signatures::
bar(y, width, *, align='center', **kwargs)
bar(y, width, height, *, align='center', **kwargs)
bar(y, width, height, left, *, align='center', **kwargs)
The bars are positioned at *y* with the given *align*. Their
dimensions are given by *width* and *height*. The horizontal baseline
is *left* (default 0).
Each of *y*, *width*, *height*, and *left* may either be a scalar
applying to all bars, or it may be a sequence of length N providing a
separate value for each bar.
Parameters
----------
y : scalar or array-like
The y coordinates of the bars. See also *align* for the
alignment of the bars to the coordinates.
width : scalar or array-like
The width(s) of the bars.
height : sequence of scalars, optional, default: 0.8
The heights of the bars.
left : sequence of scalars
The x coordinates of the left sides of the bars (default: 0).
align : {'center', 'edge'}, optional, default: 'center'
Alignment of the base to the *y* coordinates*:
- 'center': Center the bars on the *y* positions.
- 'edge': Align the bottom edges of the bars with the *y*
positions.
To align the bars on the top edge pass a negative *height* and
``align='edge'``.
Returns
-------
`.BarContainer`
Container with all the bars and optionally errorbars.
Other Parameters
----------------
color : scalar or array-like, optional
The colors of the bar faces.
edgecolor : scalar or array-like, optional
The colors of the bar edges.
linewidth : scalar or array-like, optional
Width of the bar edge(s). If 0, don't draw edges.
tick_label : string or array-like, optional
The tick labels of the bars.
Default: None (Use default numeric labels.)
xerr, yerr : scalar or array-like of shape(N,) or shape(2,N), optional
If not ``None``, add horizontal / vertical errorbars to the
bar tips. The values are +/- sizes relative to the data:
- scalar: symmetric +/- values for all bars
- shape(N,): symmetric +/- values for each bar
- shape(2,N): separate + and - values for each bar
Default: None
ecolor : scalar or array-like, optional, default: 'black'
The line color of the errorbars.
capsize : scalar, optional
The length of the error bar caps in points.
Default: None, which will take the value from
:rc:`errorbar.capsize`.
error_kw : dict, optional
Dictionary of kwargs to be passed to the `~.Axes.errorbar`
method. Values of *ecolor* or *capsize* defined here take
precedence over the independent kwargs.
log : bool, optional, default: False
If ``True``, set the x-axis to be log scale.
See also
--------
bar: Plot a vertical bar plot.
Notes
-----
The optional arguments *color*, *edgecolor*, *linewidth*,
*xerr*, and *yerr* can be either scalars or sequences of
length equal to the number of bars. This enables you to use
bar as the basis for stacked bar charts, or candlestick plots.
Detail: *xerr* and *yerr* are passed directly to
:meth:`errorbar`, so they can also have shape 2xN for
independent specification of lower and upper errors.
Other optional kwargs:
%(Rectangle)s
"""
# this is using the lambdas to do the arg/kwarg unpacking rather
# than trying to re-implement all of that logic our selves.
matchers = [
(lambda y, width, height=0.8, left=None, **kwargs:
(False, y, width, height, left, kwargs)),
(lambda bottom, width, height=0.8, left=None, **kwargs:
(True, bottom, width, height, left, kwargs)),
]
excs = []
for matcher in matchers:
try:
dp, y, width, height, left, kwargs = matcher(*args, **kwargs)
except TypeError as e:
# This can only come from a no-match as there is
# no other logic in the matchers.
excs.append(e)
else:
break
else:
raise excs[0]
if dp:
warnings.warn(
"The *bottom* kwarg to `barh` is deprecated use *y* instead. "
"Support for *bottom* will be removed in Matplotlib 3.0",
mplDeprecation, stacklevel=2)
kwargs.setdefault('orientation', 'horizontal')
patches = self.bar(x=left, height=height, width=width,
bottom=y, **kwargs)
return patches
@_preprocess_data(label_namer=None)
@docstring.dedent_interpd
def broken_barh(self, xranges, yrange, **kwargs):
"""
Plot a horizontal sequence of rectangles.
A rectangle is drawn for each element of *xranges*. All rectangles
have the same vertical position and size defined by *yrange*.
This is a convenience function for instantiating a
`.BrokenBarHCollection`, adding it to the axes and autoscaling the
view.
Parameters
----------
xranges : sequence of tuples (*xmin*, *xwidth*)
The x-positions and extends of the rectangles. For each tuple
(*xmin*, *xwidth*) a rectangle is drawn from *xmin* to *xmin* +
*xwidth*.
yranges : (*ymin*, *ymax*)
The y-position and extend for all the rectangles.
Other Parameters
----------------
**kwargs : :class:`.BrokenBarHCollection` properties
Each *kwarg* can be either a single argument applying to all
rectangles, e.g.::
facecolors='black'
or a sequence of arguments over which is cycled, e.g.::
facecolors=('black', 'blue')
would create interleaving black and blue rectangles.
Supported keywords:
%(BrokenBarHCollection)s
Returns
-------
:class:`matplotlib.collections.BrokenBarHCollection`
Notes
-----
.. [Notes section required for data comment. See #10189.]
"""
# process the unit information
if len(xranges):
xdata = cbook.safe_first_element(xranges)
else:
xdata = None
if len(yrange):
ydata = cbook.safe_first_element(yrange)
else:
ydata = None
self._process_unit_info(xdata=xdata,
ydata=ydata,
kwargs=kwargs)
xranges = self.convert_xunits(xranges)
yrange = self.convert_yunits(yrange)
col = mcoll.BrokenBarHCollection(xranges, yrange, **kwargs)
self.add_collection(col, autolim=True)
self.autoscale_view()
return col
@_preprocess_data(replace_all_args=True, label_namer=None)
def stem(self, *args, **kwargs):
"""
Create a stem plot.
A stem plot plots vertical lines at each *x* location from the baseline
to *y*, and places a marker there.
Call signature::
stem([x,] y, linefmt=None, markerfmt=None, basefmt=None)
The x-positions are optional. The formats may be provided either as
positional or as keyword-arguments.
Parameters
----------
x : array-like, optional
The x-positions of the stems. Default: (0, 1, ..., len(y) - 1).
y : array-like
The y-values of the stem heads.
linefmt : str, optional
A string defining the properties of the vertical lines. Usually,
this will be a color or a color and a linestyle:
========= =============
Character Line Style
========= =============
``'-'`` solid line
``'--'`` dashed line
``'-.'`` dash-dot line
``':'`` dotted line
========= =============
Default: 'C0-', i.e. solid line with the first color of the color
cycle.
Note: While it is technically possible to specify valid formats
other than color or color and linestyle (e.g. 'rx' or '-.'), this
is beyond the intention of the method and will most likely not
result in a reasonable reasonable plot.
markerfmt : str, optional
A string defining the properties of the markers at the stem heads.
Default: 'C0o', i.e. filled circles with the first color of the
color cycle.
basefmt : str, optional
A format string defining the properties of the baseline.
Default: 'C3-' ('C2-' in classic mode).
bottom : float, optional, default: 0
The y-position of the baseline.
label : str, optional, default: None
The label to use for the stems in legends.
Other Parameters
----------------
**kwargs
No other parameters are supported. They are currently ignored
silently for backward compatibility. This behavior is deprecated.
Future versions will not accept any other parameters and will
raise a TypeError instead.
Returns
-------
:class:`~matplotlib.container.StemContainer`
The stemcontainer may be treated like a tuple
(*markerline*, *stemlines*, *baseline*)
Notes
-----
.. seealso::
The MATLAB function
`stem <http://www.mathworks.com/help/techdoc/ref/stem.html>`_
which inspired this method.
"""
# kwargs handling
# We would like to have a signature with explicit kewords:
# stem(*args, linefmt=None, markerfmt=None, basefmt=None,
# bottom=0, label=None)
# Unfortunately, this is not supported in Python 2.x. There, *args
# can only exist after keyword arguments.
linefmt = kwargs.pop('linefmt', None)
markerfmt = kwargs.pop('markerfmt', None)
basefmt = kwargs.pop('basefmt', None)
bottom = kwargs.pop('bottom', None)
if bottom is None:
bottom = 0
label = kwargs.pop('label', None)
if kwargs:
warn_deprecated(since='2.2',
message="stem() got an unexpected keyword "
"argument '%s'. This will raise a "
"TypeError in future versions." % (
next(k for k in kwargs), )
)
remember_hold = self._hold
if not self._hold:
self.cla()
self._hold = True
# Assume there's at least one data array
y = np.asarray(args[0])
args = args[1:]
# Try a second one
try:
second = np.asarray(args[0], dtype=float)
x, y = y, second
args = args[1:]
except (IndexError, ValueError):
# The second array doesn't make sense, or it doesn't exist
second = np.arange(len(y))
x = second
# defaults for formats
if linefmt is None:
try:
# fallback to positional argument
linefmt = args[0]
except IndexError:
linecolor = 'C0'
linemarker = 'None'
linestyle = '-'
else:
linestyle, linemarker, linecolor = \
_process_plot_format(linefmt)
else:
linestyle, linemarker, linecolor = _process_plot_format(linefmt)
if markerfmt is None:
try:
# fallback to positional argument
markerfmt = args[1]
except IndexError:
markercolor = 'C0'
markermarker = 'o'
markerstyle = 'None'
else:
markerstyle, markermarker, markercolor = \
_process_plot_format(markerfmt)
else:
markerstyle, markermarker, markercolor = \
_process_plot_format(markerfmt)
if basefmt is None:
try:
# fallback to positional argument
basefmt = args[2]
except IndexError:
if rcParams['_internal.classic_mode']:
basecolor = 'C2'
else:
basecolor = 'C3'
basemarker = 'None'
basestyle = '-'
else:
basestyle, basemarker, basecolor = \
_process_plot_format(basefmt)
else:
basestyle, basemarker, basecolor = _process_plot_format(basefmt)
markerline, = self.plot(x, y, color=markercolor, linestyle=markerstyle,
marker=markermarker, label="_nolegend_")
stemlines = []
for thisx, thisy in zip(x, y):
l, = self.plot([thisx, thisx], [bottom, thisy],
color=linecolor, linestyle=linestyle,
marker=linemarker, label="_nolegend_")
stemlines.append(l)
baseline, = self.plot([np.min(x), np.max(x)], [bottom, bottom],
color=basecolor, linestyle=basestyle,
marker=basemarker, label="_nolegend_")
self._hold = remember_hold
stem_container = StemContainer((markerline, stemlines, baseline),
label=label)
self.add_container(stem_container)
return stem_container
@_preprocess_data(replace_names=["x", "explode", "labels", "colors"],
label_namer=None)
def pie(self, x, explode=None, labels=None, colors=None,
autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1,
startangle=None, radius=None, counterclock=True,
wedgeprops=None, textprops=None, center=(0, 0),
frame=False, rotatelabels=False):
"""
Plot a pie chart.
Make a pie chart of array *x*. The fractional area of each wedge is
given by ``x/sum(x)``. If ``sum(x) < 1``, then the values of *x* give
the fractional area directly and the array will not be normalized. The
resulting pie will have an empty wedge of size ``1 - sum(x)``.
The wedges are plotted counterclockwise, by default starting from the
x-axis.
Parameters
----------
x : array-like
The wedge sizes.
explode : array-like, optional, default: None
If not *None*, is a ``len(x)`` array which specifies the fraction
of the radius with which to offset each wedge.
labels : list, optional, default: None
A sequence of strings providing the labels for each wedge
colors : array-like, optional, default: None
A sequence of matplotlib color args through which the pie chart
will cycle. If *None*, will use the colors in the currently
active cycle.
autopct : None (default), string, or function, optional
If not *None*, is a string or function used to label the wedges
with their numeric value. The label will be placed inside the
wedge. If it is a format string, the label will be ``fmt%pct``.
If it is a function, it will be called.
pctdistance : float, optional, default: 0.6
The ratio between the center of each pie slice and the start of
the text generated by *autopct*. Ignored if *autopct* is *None*.
shadow : bool, optional, default: False
Draw a shadow beneath the pie.
labeldistance : float, optional, default: 1.1
The radial distance at which the pie labels are drawn
startangle : float, optional, default: None
If not *None*, rotates the start of the pie chart by *angle*
degrees counterclockwise from the x-axis.
radius : float, optional, default: None
The radius of the pie, if *radius* is *None* it will be set to 1.
counterclock : bool, optional, default: True
Specify fractions direction, clockwise or counterclockwise.
wedgeprops : dict, optional, default: None
Dict of arguments passed to the wedge objects making the pie.
For example, you can pass in ``wedgeprops = {'linewidth': 3}``
to set the width of the wedge border lines equal to 3.
For more details, look at the doc/arguments of the wedge object.
By default ``clip_on=False``.
textprops : dict, optional, default: None
Dict of arguments to pass to the text objects.
center : list of float, optional, default: (0, 0)
Center position of the chart. Takes value (0, 0) or is a sequence
of 2 scalars.
frame : bool, optional, default: False
Plot axes frame with the chart if true.
rotatelabels : bool, optional, default: False
Rotate each label to the angle of the corresponding slice if true.
Returns
-------
patches : list
A sequence of :class:`matplotlib.patches.Wedge` instances
texts : list
A list of the label :class:`matplotlib.text.Text` instances.
autotexts : list
A list of :class:`~matplotlib.text.Text` instances for the numeric
labels. This will only be returned if the parameter *autopct* is
not *None*.
Notes
-----
The pie chart will probably look best if the figure and axes are
square, or the Axes aspect is equal.
"""
x = np.array(x, np.float32)
sx = x.sum()
if sx > 1:
x /= sx
if labels is None:
labels = [''] * len(x)
if explode is None:
explode = [0] * len(x)
if len(x) != len(labels):
raise ValueError("'label' must be of length 'x'")
if len(x) != len(explode):
raise ValueError("'explode' must be of length 'x'")
if colors is None:
get_next_color = self._get_patches_for_fill.get_next_color
else:
color_cycle = itertools.cycle(colors)
def get_next_color():
return next(color_cycle)
if radius is None:
radius = 1
# Starting theta1 is the start fraction of the circle
if startangle is None:
theta1 = 0
else:
theta1 = startangle / 360.0
# set default values in wedge_prop
if wedgeprops is None:
wedgeprops = {}
wedgeprops.setdefault('clip_on', False)
if textprops is None:
textprops = {}
textprops.setdefault('clip_on', False)
texts = []
slices = []
autotexts = []
i = 0
for frac, label, expl in zip(x, labels, explode):
x, y = center
theta2 = (theta1 + frac) if counterclock else (theta1 - frac)
thetam = 2 * np.pi * 0.5 * (theta1 + theta2)
x += expl * math.cos(thetam)
y += expl * math.sin(thetam)
w = mpatches.Wedge((x, y), radius, 360. * min(theta1, theta2),
360. * max(theta1, theta2),
facecolor=get_next_color(),
**wedgeprops)
slices.append(w)
self.add_patch(w)
w.set_label(label)
if shadow:
# make sure to add a shadow after the call to
# add_patch so the figure and transform props will be
# set
shad = mpatches.Shadow(w, -0.02, -0.02)
shad.set_zorder(0.9 * w.get_zorder())
shad.set_label('_nolegend_')
self.add_patch(shad)
xt = x + labeldistance * radius * math.cos(thetam)
yt = y + labeldistance * radius * math.sin(thetam)
label_alignment_h = xt > 0 and 'left' or 'right'
label_alignment_v = 'center'
label_rotation = 'horizontal'
if rotatelabels:
label_alignment_v = yt > 0 and 'bottom' or 'top'
label_rotation = np.rad2deg(thetam) + (0 if xt > 0 else 180)
t = self.text(xt, yt, label,
size=rcParams['xtick.labelsize'],
horizontalalignment=label_alignment_h,
verticalalignment=label_alignment_v,
rotation=label_rotation,
**textprops)
texts.append(t)
if autopct is not None:
xt = x + pctdistance * radius * math.cos(thetam)
yt = y + pctdistance * radius * math.sin(thetam)
if isinstance(autopct, six.string_types):
s = autopct % (100. * frac)
elif callable(autopct):
s = autopct(100. * frac)
else:
raise TypeError(
'autopct must be callable or a format string')
t = self.text(xt, yt, s,
horizontalalignment='center',
verticalalignment='center',
**textprops)
autotexts.append(t)
theta1 = theta2
i += 1
if not frame:
self.set_frame_on(False)
self.set_xlim((-1.25 + center[0],
1.25 + center[0]))
self.set_ylim((-1.25 + center[1],
1.25 + center[1]))
self.set_xticks([])
self.set_yticks([])
if autopct is None:
return slices, texts
else:
return slices, texts, autotexts
@_preprocess_data(replace_names=["x", "y", "xerr", "yerr"],
label_namer="y")
@docstring.dedent_interpd
def errorbar(self, x, y, yerr=None, xerr=None,
fmt='', ecolor=None, elinewidth=None, capsize=None,
barsabove=False, lolims=False, uplims=False,
xlolims=False, xuplims=False, errorevery=1, capthick=None,
**kwargs):
"""
Plot y versus x as lines and/or markers with attached errorbars.
*x*, *y* define the data locations, *xerr*, *yerr* define the errorbar
sizes. By default, this draws the data markers/lines as well the
errorbars. Use fmt='none' to draw errorbars without any data markers.
Parameters
----------
x, y : scalar or array-like
The data positions.
xerr, yerr : scalar or array-like, shape(N,) or shape(2,N), optional
The errorbar sizes:
- scalar: Symmetric +/- values for all data points.
- shape(N,): Symmetric +/-values for each data point.
- shape(2,N): Separate + and - values for each data point.
- *None*: No errorbar.
fmt : plot format string, optional, default: ''
The format for the data points / data lines. See `.plot` for
details.
Use 'none' (case insensitive) to plot errorbars without any data
markers.
ecolor : mpl color, optional, default: None
A matplotlib color arg which gives the color the errorbar lines.
If None, use the color of the line connecting the markers.
elinewidth : scalar, optional, default: None
The linewidth of the errorbar lines. If None, the linewidth of
the current style is used.
capsize : scalar, optional, default: None
The length of the error bar caps in points. If None, it will take
the value from :rc:`errorbar.capsize`.
capthick : scalar, optional, default: None
An alias to the keyword argument *markeredgewidth* (a.k.a. *mew*).
This setting is a more sensible name for the property that
controls the thickness of the error bar cap in points. For
backwards compatibility, if *mew* or *markeredgewidth* are given,
then they will over-ride *capthick*. This may change in future
releases.
barsabove : bool, optional, default: False
If True, will plot the errorbars above the plot
symbols. Default is below.
lolims, uplims, xlolims, xuplims : bool, optional, default: None
These arguments can be used to indicate that a value gives only
upper/lower limits. In that case a caret symbol is used to
indicate this. *lims*-arguments may be of the same type as *xerr*
and *yerr*. To use limits with inverted axes, :meth:`set_xlim`
or :meth:`set_ylim` must be called before :meth:`errorbar`.
errorevery : positive integer, optional, default: 1
Subsamples the errorbars. e.g., if errorevery=5, errorbars for
every 5-th datapoint will be plotted. The data plot itself still
shows all data points.
Returns
-------
:class:`~.container.ErrorbarContainer`
The container contains:
- plotline: :class:`~matplotlib.lines.Line2D` instance of
x, y plot markers and/or line.
- caplines: A tuple of :class:`~matplotlib.lines.Line2D` instances
of the error bar caps.
- barlinecols: A tuple of
:class:`~matplotlib.collections.LineCollection` with the
horizontal and vertical error ranges.
Other Parameters
----------------
**kwargs :
All other keyword arguments are passed on to the plot
command for the markers. For example, this code makes big red
squares with thick green edges::
x,y,yerr = rand(3,10)
errorbar(x, y, yerr, marker='s', mfc='red',
mec='green', ms=20, mew=4)
where *mfc*, *mec*, *ms* and *mew* are aliases for the longer
property names, *markerfacecolor*, *markeredgecolor*, *markersize*
and *markeredgewidth*.
Valid kwargs for the marker properties are `.Lines2D` properties:
%(Line2D)s
Notes
-----
.. [Notes section required for data comment. See #10189.]
"""
kwargs = cbook.normalize_kwargs(kwargs, _alias_map)
# anything that comes in as 'None', drop so the default thing
# happens down stream
kwargs = {k: v for k, v in kwargs.items() if v is not None}
kwargs.setdefault('zorder', 2)
if errorevery < 1:
raise ValueError(
'errorevery has to be a strictly positive integer')
self._process_unit_info(xdata=x, ydata=y, kwargs=kwargs)
if not self._hold:
self.cla()
holdstate = self._hold
self._hold = True
plot_line = (fmt.lower() != 'none')
label = kwargs.pop("label", None)
if fmt == '':
fmt_style_kwargs = {}
else:
fmt_style_kwargs = {k: v for k, v in
zip(('linestyle', 'marker', 'color'),
_process_plot_format(fmt)) if v is not None}
if fmt == 'none':
# Remove alpha=0 color that _process_plot_format returns
fmt_style_kwargs.pop('color')
if ('color' in kwargs or 'color' in fmt_style_kwargs or
ecolor is not None):
base_style = {}
if 'color' in kwargs:
base_style['color'] = kwargs.pop('color')
else:
base_style = next(self._get_lines.prop_cycler)
base_style['label'] = '_nolegend_'
base_style.update(fmt_style_kwargs)
if 'color' not in base_style:
base_style['color'] = 'C0'
if ecolor is None:
ecolor = base_style['color']
# make sure all the args are iterable; use lists not arrays to
# preserve units
if not iterable(x):
x = [x]
if not iterable(y):
y = [y]
if xerr is not None:
if not iterable(xerr):
xerr = [xerr] * len(x)
if yerr is not None:
if not iterable(yerr):
yerr = [yerr] * len(y)
# make the style dict for the 'normal' plot line
plot_line_style = dict(base_style)
plot_line_style.update(**kwargs)
if barsabove:
plot_line_style['zorder'] = kwargs['zorder'] - .1
else:
plot_line_style['zorder'] = kwargs['zorder'] + .1
# make the style dict for the line collections (the bars)
eb_lines_style = dict(base_style)
eb_lines_style.pop('marker', None)
eb_lines_style.pop('linestyle', None)
eb_lines_style['color'] = ecolor
if elinewidth:
eb_lines_style['linewidth'] = elinewidth
elif 'linewidth' in kwargs:
eb_lines_style['linewidth'] = kwargs['linewidth']
for key in ('transform', 'alpha', 'zorder', 'rasterized'):
if key in kwargs:
eb_lines_style[key] = kwargs[key]
# set up cap style dictionary
eb_cap_style = dict(base_style)
# eject any marker information from format string
eb_cap_style.pop('marker', None)
eb_lines_style.pop('markerfacecolor', None)
eb_lines_style.pop('markeredgewidth', None)
eb_lines_style.pop('markeredgecolor', None)
eb_cap_style.pop('ls', None)
eb_cap_style['linestyle'] = 'none'
if capsize is None:
capsize = rcParams["errorbar.capsize"]
if capsize > 0:
eb_cap_style['markersize'] = 2. * capsize
if capthick is not None:
eb_cap_style['markeredgewidth'] = capthick
# For backwards-compat, allow explicit setting of
# 'markeredgewidth' to over-ride capthick.
for key in ('markeredgewidth', 'transform', 'alpha',
'zorder', 'rasterized'):
if key in kwargs:
eb_cap_style[key] = kwargs[key]
eb_cap_style['color'] = ecolor
data_line = None
if plot_line:
data_line = mlines.Line2D(x, y, **plot_line_style)
self.add_line(data_line)
barcols = []
caplines = []
# arrays fine here, they are booleans and hence not units
def _bool_asarray_helper(d, expected):
if not iterable(d):
return np.asarray([d] * expected, bool)
else:
return np.asarray(d, bool)
lolims = _bool_asarray_helper(lolims, len(x))
uplims = _bool_asarray_helper(uplims, len(x))
xlolims = _bool_asarray_helper(xlolims, len(x))
xuplims = _bool_asarray_helper(xuplims, len(x))
everymask = np.arange(len(x)) % errorevery == 0
def xywhere(xs, ys, mask):
"""
return xs[mask], ys[mask] where mask is True but xs and
ys are not arrays
"""
assert len(xs) == len(ys)
assert len(xs) == len(mask)
xs = [thisx for thisx, b in zip(xs, mask) if b]
ys = [thisy for thisy, b in zip(ys, mask) if b]
return xs, ys
def extract_err(err, data):
'''private function to compute error bars
Parameters
----------
err : iterable
xerr or yerr from errorbar
data : iterable
x or y from errorbar
'''
try:
a, b = err
except (TypeError, ValueError):
pass
else:
if iterable(a) and iterable(b):
# using list comps rather than arrays to preserve units
low = [thisx - thiserr for (thisx, thiserr)
in cbook.safezip(data, a)]
high = [thisx + thiserr for (thisx, thiserr)
in cbook.safezip(data, b)]
return low, high
# Check if xerr is scalar or symmetric. Asymmetric is handled
# above. This prevents Nx2 arrays from accidentally
# being accepted, when the user meant the 2xN transpose.
# special case for empty lists
if len(err) > 1:
fe = safe_first_element(err)
if (len(err) != len(data) or np.size(fe) > 1):
raise ValueError("err must be [ scalar | N, Nx1 "
"or 2xN array-like ]")
# using list comps rather than arrays to preserve units
low = [thisx - thiserr for (thisx, thiserr)
in cbook.safezip(data, err)]
high = [thisx + thiserr for (thisx, thiserr)
in cbook.safezip(data, err)]
return low, high
if xerr is not None:
left, right = extract_err(xerr, x)
# select points without upper/lower limits in x and
# draw normal errorbars for these points
noxlims = ~(xlolims | xuplims)
if noxlims.any() or len(noxlims) == 0:
yo, _ = xywhere(y, right, noxlims & everymask)
lo, ro = xywhere(left, right, noxlims & everymask)
barcols.append(self.hlines(yo, lo, ro, **eb_lines_style))
if capsize > 0:
caplines.append(mlines.Line2D(lo, yo, marker='|',
**eb_cap_style))
caplines.append(mlines.Line2D(ro, yo, marker='|',
**eb_cap_style))
if xlolims.any():
yo, _ = xywhere(y, right, xlolims & everymask)
lo, ro = xywhere(x, right, xlolims & everymask)
barcols.append(self.hlines(yo, lo, ro, **eb_lines_style))
rightup, yup = xywhere(right, y, xlolims & everymask)
if self.xaxis_inverted():
marker = mlines.CARETLEFTBASE
else:
marker = mlines.CARETRIGHTBASE
caplines.append(
mlines.Line2D(rightup, yup, ls='None', marker=marker,
**eb_cap_style))
if capsize > 0:
xlo, ylo = xywhere(x, y, xlolims & everymask)
caplines.append(mlines.Line2D(xlo, ylo, marker='|',
**eb_cap_style))
if xuplims.any():
yo, _ = xywhere(y, right, xuplims & everymask)
lo, ro = xywhere(left, x, xuplims & everymask)
barcols.append(self.hlines(yo, lo, ro, **eb_lines_style))
leftlo, ylo = xywhere(left, y, xuplims & everymask)
if self.xaxis_inverted():
marker = mlines.CARETRIGHTBASE
else:
marker = mlines.CARETLEFTBASE
caplines.append(
mlines.Line2D(leftlo, ylo, ls='None', marker=marker,
**eb_cap_style))
if capsize > 0:
xup, yup = xywhere(x, y, xuplims & everymask)
caplines.append(mlines.Line2D(xup, yup, marker='|',
**eb_cap_style))
if yerr is not None:
lower, upper = extract_err(yerr, y)
# select points without upper/lower limits in y and
# draw normal errorbars for these points
noylims = ~(lolims | uplims)
if noylims.any() or len(noylims) == 0:
xo, _ = xywhere(x, lower, noylims & everymask)
lo, uo = xywhere(lower, upper, noylims & everymask)
barcols.append(self.vlines(xo, lo, uo, **eb_lines_style))
if capsize > 0:
caplines.append(mlines.Line2D(xo, lo, marker='_',
**eb_cap_style))
caplines.append(mlines.Line2D(xo, uo, marker='_',
**eb_cap_style))
if lolims.any():
xo, _ = xywhere(x, lower, lolims & everymask)
lo, uo = xywhere(y, upper, lolims & everymask)
barcols.append(self.vlines(xo, lo, uo, **eb_lines_style))
xup, upperup = xywhere(x, upper, lolims & everymask)
if self.yaxis_inverted():
marker = mlines.CARETDOWNBASE
else:
marker = mlines.CARETUPBASE
caplines.append(
mlines.Line2D(xup, upperup, ls='None', marker=marker,
**eb_cap_style))
if capsize > 0:
xlo, ylo = xywhere(x, y, lolims & everymask)
caplines.append(mlines.Line2D(xlo, ylo, marker='_',
**eb_cap_style))
if uplims.any():
xo, _ = xywhere(x, lower, uplims & everymask)
lo, uo = xywhere(lower, y, uplims & everymask)
barcols.append(self.vlines(xo, lo, uo, **eb_lines_style))
xlo, lowerlo = xywhere(x, lower, uplims & everymask)
if self.yaxis_inverted():
marker = mlines.CARETUPBASE
else:
marker = mlines.CARETDOWNBASE
caplines.append(
mlines.Line2D(xlo, lowerlo, ls='None', marker=marker,
**eb_cap_style))
if capsize > 0:
xup, yup = xywhere(x, y, uplims & everymask)
caplines.append(mlines.Line2D(xup, yup, marker='_',
**eb_cap_style))
for l in caplines:
self.add_line(l)
self.autoscale_view()
self._hold = holdstate
errorbar_container = ErrorbarContainer((data_line, tuple(caplines),
tuple(barcols)),
has_xerr=(xerr is not None),
has_yerr=(yerr is not None),
label=label)
self.containers.append(errorbar_container)
return errorbar_container # (l0, caplines, barcols)
@_preprocess_data(label_namer=None)
def boxplot(self, x, notch=None, sym=None, vert=None, whis=None,
positions=None, widths=None, patch_artist=None,
bootstrap=None, usermedians=None, conf_intervals=None,
meanline=None, showmeans=None, showcaps=None,
showbox=None, showfliers=None, boxprops=None,
labels=None, flierprops=None, medianprops=None,
meanprops=None, capprops=None, whiskerprops=None,
manage_xticks=True, autorange=False, zorder=None):
"""
Make a box and whisker plot.
Make a box and whisker plot for each column of ``x`` or each
vector in sequence ``x``. The box extends from the lower to
upper quartile values of the data, with a line at the median.
The whiskers extend from the box to show the range of the
data. Flier points are those past the end of the whiskers.
Parameters
----------
x : Array or a sequence of vectors.
The input data.
notch : bool, optional (False)
If `True`, will produce a notched box plot. Otherwise, a
rectangular boxplot is produced. The notches represent the
confidence interval (CI) around the median. See the entry
for the ``bootstrap`` parameter for information regarding
how the locations of the notches are computed.
.. note::
In cases where the values of the CI are less than the
lower quartile or greater than the upper quartile, the
notches will extend beyond the box, giving it a
distinctive "flipped" appearance. This is expected
behavior and consistent with other statistical
visualization packages.
sym : str, optional
The default symbol for flier points. Enter an empty string
('') if you don't want to show fliers. If `None`, then the
fliers default to 'b+' If you want more control use the
flierprops kwarg.
vert : bool, optional (True)
If `True` (default), makes the boxes vertical. If `False`,
everything is drawn horizontally.
whis : float, sequence, or string (default = 1.5)
As a float, determines the reach of the whiskers to the beyond the
first and third quartiles. In other words, where IQR is the
interquartile range (`Q3-Q1`), the upper whisker will extend to
last datum less than `Q3 + whis*IQR`). Similarly, the lower whisker
will extend to the first datum greater than `Q1 - whis*IQR`.
Beyond the whiskers, data
are considered outliers and are plotted as individual
points. Set this to an unreasonably high value to force the
whiskers to show the min and max values. Alternatively, set
this to an ascending sequence of percentile (e.g., [5, 95])
to set the whiskers at specific percentiles of the data.
Finally, ``whis`` can be the string ``'range'`` to force the
whiskers to the min and max of the data.
bootstrap : int, optional
Specifies whether to bootstrap the confidence intervals
around the median for notched boxplots. If ``bootstrap`` is
None, no bootstrapping is performed, and notches are
calculated using a Gaussian-based asymptotic approximation
(see McGill, R., Tukey, J.W., and Larsen, W.A., 1978, and
Kendall and Stuart, 1967). Otherwise, bootstrap specifies
the number of times to bootstrap the median to determine its
95% confidence intervals. Values between 1000 and 10000 are
recommended.
usermedians : array-like, optional
An array or sequence whose first dimension (or length) is
compatible with ``x``. This overrides the medians computed
by matplotlib for each element of ``usermedians`` that is not
`None`. When an element of ``usermedians`` is None, the median
will be computed by matplotlib as normal.
conf_intervals : array-like, optional
Array or sequence whose first dimension (or length) is
compatible with ``x`` and whose second dimension is 2. When
the an element of ``conf_intervals`` is not None, the
notch locations computed by matplotlib are overridden
(provided ``notch`` is `True`). When an element of
``conf_intervals`` is `None`, the notches are computed by the
method specified by the other kwargs (e.g., ``bootstrap``).
positions : array-like, optional
Sets the positions of the boxes. The ticks and limits are
automatically set to match the positions. Defaults to
`range(1, N+1)` where N is the number of boxes to be drawn.
widths : scalar or array-like
Sets the width of each box either with a scalar or a
sequence. The default is 0.5, or ``0.15*(distance between
extreme positions)``, if that is smaller.
patch_artist : bool, optional (False)
If `False` produces boxes with the Line2D artist. Otherwise,
boxes and drawn with Patch artists.
labels : sequence, optional
Labels for each dataset. Length must be compatible with
dimensions of ``x``.
manage_xticks : bool, optional (True)
If the function should adjust the xlim and xtick locations.
autorange : bool, optional (False)
When `True` and the data are distributed such that the 25th and
75th percentiles are equal, ``whis`` is set to ``'range'`` such
that the whisker ends are at the minimum and maximum of the
data.
meanline : bool, optional (False)
If `True` (and ``showmeans`` is `True`), will try to render
the mean as a line spanning the full width of the box
according to ``meanprops`` (see below). Not recommended if
``shownotches`` is also True. Otherwise, means will be shown
as points.
zorder : scalar, optional (None)
Sets the zorder of the boxplot.
Other Parameters
----------------
showcaps : bool, optional (True)
Show the caps on the ends of whiskers.
showbox : bool, optional (True)
Show the central box.
showfliers : bool, optional (True)
Show the outliers beyond the caps.
showmeans : bool, optional (False)
Show the arithmetic means.
capprops : dict, optional (None)
Specifies the style of the caps.
boxprops : dict, optional (None)
Specifies the style of the box.
whiskerprops : dict, optional (None)
Specifies the style of the whiskers.
flierprops : dict, optional (None)
Specifies the style of the fliers.
medianprops : dict, optional (None)
Specifies the style of the median.
meanprops : dict, optional (None)
Specifies the style of the mean.
Returns
-------
result : dict
A dictionary mapping each component of the boxplot to a list
of the :class:`matplotlib.lines.Line2D` instances
created. That dictionary has the following keys (assuming
vertical boxplots):
- ``boxes``: the main body of the boxplot showing the
quartiles and the median's confidence intervals if
enabled.
- ``medians``: horizontal lines at the median of each box.
- ``whiskers``: the vertical lines extending to the most
extreme, non-outlier data points.
- ``caps``: the horizontal lines at the ends of the
whiskers.
- ``fliers``: points representing data that extend beyond
the whiskers (fliers).
- ``means``: points or lines representing the means.
Notes
-----
.. [Notes section required for data comment. See #10189.]
"""
# If defined in matplotlibrc, apply the value from rc file
# Overridden if argument is passed
if whis is None:
whis = rcParams['boxplot.whiskers']
if bootstrap is None:
bootstrap = rcParams['boxplot.bootstrap']
bxpstats = cbook.boxplot_stats(x, whis=whis, bootstrap=bootstrap,
labels=labels, autorange=autorange)
if notch is None:
notch = rcParams['boxplot.notch']
if vert is None:
vert = rcParams['boxplot.vertical']
if patch_artist is None:
patch_artist = rcParams['boxplot.patchartist']
if meanline is None:
meanline = rcParams['boxplot.meanline']
if showmeans is None:
showmeans = rcParams['boxplot.showmeans']
if showcaps is None:
showcaps = rcParams['boxplot.showcaps']
if showbox is None:
showbox = rcParams['boxplot.showbox']
if showfliers is None:
showfliers = rcParams['boxplot.showfliers']
def _update_dict(dictionary, rc_name, properties):
""" Loads properties in the dictionary from rc file if not already
in the dictionary"""
rc_str = 'boxplot.{0}.{1}'
if dictionary is None:
dictionary = dict()
for prop_dict in properties:
dictionary.setdefault(prop_dict,
rcParams[rc_str.format(rc_name, prop_dict)])
return dictionary
# Common property dictionnaries loading from rc
flier_props = ['color', 'marker', 'markerfacecolor', 'markeredgecolor',
'markersize', 'linestyle', 'linewidth']
default_props = ['color', 'linewidth', 'linestyle']
boxprops = _update_dict(boxprops, 'boxprops', default_props)
whiskerprops = _update_dict(whiskerprops, 'whiskerprops',
default_props)
capprops = _update_dict(capprops, 'capprops', default_props)
medianprops = _update_dict(medianprops, 'medianprops', default_props)
meanprops = _update_dict(meanprops, 'meanprops', default_props)
flierprops = _update_dict(flierprops, 'flierprops', flier_props)
if patch_artist:
boxprops['linestyle'] = 'solid'
boxprops['edgecolor'] = boxprops.pop('color')
# if non-default sym value, put it into the flier dictionary
# the logic for providing the default symbol ('b+') now lives
# in bxp in the initial value of final_flierprops
# handle all of the `sym` related logic here so we only have to pass
# on the flierprops dict.
if sym is not None:
# no-flier case, which should really be done with
# 'showfliers=False' but none-the-less deal with it to keep back
# compatibility
if sym == '':
# blow away existing dict and make one for invisible markers
flierprops = dict(linestyle='none', marker='', color='none')
# turn the fliers off just to be safe
showfliers = False
# now process the symbol string
else:
# process the symbol string
# discarded linestyle
_, marker, color = _process_plot_format(sym)
# if we have a marker, use it
if marker is not None:
flierprops['marker'] = marker
# if we have a color, use it
if color is not None:
# assume that if color is passed in the user want
# filled symbol, if the users want more control use
# flierprops
flierprops['color'] = color
flierprops['markerfacecolor'] = color
flierprops['markeredgecolor'] = color
# replace medians if necessary:
if usermedians is not None:
if (len(np.ravel(usermedians)) != len(bxpstats) or
np.shape(usermedians)[0] != len(bxpstats)):
raise ValueError('usermedians length not compatible with x')
else:
# reassign medians as necessary
for stats, med in zip(bxpstats, usermedians):
if med is not None:
stats['med'] = med
if conf_intervals is not None:
if np.shape(conf_intervals)[0] != len(bxpstats):
err_mess = 'conf_intervals length not compatible with x'
raise ValueError(err_mess)
else:
for stats, ci in zip(bxpstats, conf_intervals):
if ci is not None:
if len(ci) != 2:
raise ValueError('each confidence interval must '
'have two values')
else:
if ci[0] is not None:
stats['cilo'] = ci[0]
if ci[1] is not None:
stats['cihi'] = ci[1]
artists = self.bxp(bxpstats, positions=positions, widths=widths,
vert=vert, patch_artist=patch_artist,
shownotches=notch, showmeans=showmeans,
showcaps=showcaps, showbox=showbox,
boxprops=boxprops, flierprops=flierprops,
medianprops=medianprops, meanprops=meanprops,
meanline=meanline, showfliers=showfliers,
capprops=capprops, whiskerprops=whiskerprops,
manage_xticks=manage_xticks, zorder=zorder)
return artists
def bxp(self, bxpstats, positions=None, widths=None, vert=True,
patch_artist=False, shownotches=False, showmeans=False,
showcaps=True, showbox=True, showfliers=True,
boxprops=None, whiskerprops=None, flierprops=None,
medianprops=None, capprops=None, meanprops=None,
meanline=False, manage_xticks=True, zorder=None):
"""
Drawing function for box and whisker plots.
Make a box and whisker plot for each column of *x* or each
vector in sequence *x*. The box extends from the lower to
upper quartile values of the data, with a line at the median.
The whiskers extend from the box to show the range of the
data. Flier points are those past the end of the whiskers.
Parameters
----------
bxpstats : list of dicts
A list of dictionaries containing stats for each boxplot.
Required keys are:
- ``med``: The median (scalar float).
- ``q1``: The first quartile (25th percentile) (scalar
float).
- ``q3``: The third quartile (75th percentile) (scalar
float).
- ``whislo``: Lower bound of the lower whisker (scalar
float).
- ``whishi``: Upper bound of the upper whisker (scalar
float).
Optional keys are:
- ``mean``: The mean (scalar float). Needed if
``showmeans=True``.
- ``fliers``: Data beyond the whiskers (sequence of floats).
Needed if ``showfliers=True``.
- ``cilo`` & ``cihi``: Lower and upper confidence intervals
about the median. Needed if ``shownotches=True``.
- ``label``: Name of the dataset (string). If available,
this will be used a tick label for the boxplot
positions : array-like, default = [1, 2, ..., n]
Sets the positions of the boxes. The ticks and limits
are automatically set to match the positions.
widths : array-like, default = None
Either a scalar or a vector and sets the width of each
box. The default is ``0.15*(distance between extreme
positions)``, clipped to no less than 0.15 and no more than
0.5.
vert : bool, default = False
If `True` (default), makes the boxes vertical. If `False`,
makes horizontal boxes.
patch_artist : bool, default = False
If `False` produces boxes with the
`~matplotlib.lines.Line2D` artist. If `True` produces boxes
with the `~matplotlib.patches.Patch` artist.
shownotches : bool, default = False
If `False` (default), produces a rectangular box plot.
If `True`, will produce a notched box plot
showmeans : bool, default = False
If `True`, will toggle on the rendering of the means
showcaps : bool, default = True
If `True`, will toggle on the rendering of the caps
showbox : bool, default = True
If `True`, will toggle on the rendering of the box
showfliers : bool, default = True
If `True`, will toggle on the rendering of the fliers
boxprops : dict or None (default)
If provided, will set the plotting style of the boxes
whiskerprops : dict or None (default)
If provided, will set the plotting style of the whiskers
capprops : dict or None (default)
If provided, will set the plotting style of the caps
flierprops : dict or None (default)
If provided will set the plotting style of the fliers
medianprops : dict or None (default)
If provided, will set the plotting style of the medians
meanprops : dict or None (default)
If provided, will set the plotting style of the means
meanline : bool, default = False
If `True` (and *showmeans* is `True`), will try to render the mean
as a line spanning the full width of the box according to
*meanprops*. Not recommended if *shownotches* is also True.
Otherwise, means will be shown as points.
manage_xticks : bool, default = True
If the function should adjust the xlim and xtick locations.
zorder : scalar, default = None
The zorder of the resulting boxplot
Returns
-------
result : dict
A dictionary mapping each component of the boxplot to a list
of the :class:`matplotlib.lines.Line2D` instances
created. That dictionary has the following keys (assuming
vertical boxplots):
- ``boxes``: the main body of the boxplot showing the
quartiles and the median's confidence intervals if
enabled.
- ``medians``: horizontal lines at the median of each box.
- ``whiskers``: the vertical lines extending to the most
extreme, non-outlier data points.
- ``caps``: the horizontal lines at the ends of the
whiskers.
- ``fliers``: points representing data that extend beyond
the whiskers (fliers).
- ``means``: points or lines representing the means.
Examples
--------
.. plot:: gallery/statistics/bxp.py
"""
# lists of artists to be output
whiskers = []
caps = []
boxes = []
medians = []
means = []
fliers = []
# empty list of xticklabels
datalabels = []
# Use default zorder if none specified
if zorder is None:
zorder = mlines.Line2D.zorder
zdelta = 0.1
# box properties
if patch_artist:
final_boxprops = dict(
linestyle=rcParams['boxplot.boxprops.linestyle'],
edgecolor=rcParams['boxplot.boxprops.color'],
facecolor=rcParams['patch.facecolor'],
linewidth=rcParams['boxplot.boxprops.linewidth']
)
if rcParams['_internal.classic_mode']:
final_boxprops['facecolor'] = 'white'
else:
final_boxprops = dict(
linestyle=rcParams['boxplot.boxprops.linestyle'],
color=rcParams['boxplot.boxprops.color'],
)
final_boxprops['zorder'] = zorder
if boxprops is not None:
final_boxprops.update(boxprops)
# other (cap, whisker) properties
final_whiskerprops = dict(
linestyle=rcParams['boxplot.whiskerprops.linestyle'],
linewidth=rcParams['boxplot.whiskerprops.linewidth'],
color=rcParams['boxplot.whiskerprops.color'],
)
final_capprops = dict(
linestyle=rcParams['boxplot.capprops.linestyle'],
linewidth=rcParams['boxplot.capprops.linewidth'],
color=rcParams['boxplot.capprops.color'],
)
final_capprops['zorder'] = zorder
if capprops is not None:
final_capprops.update(capprops)
final_whiskerprops['zorder'] = zorder
if whiskerprops is not None:
final_whiskerprops.update(whiskerprops)
# set up the default flier properties
final_flierprops = dict(
linestyle=rcParams['boxplot.flierprops.linestyle'],
linewidth=rcParams['boxplot.flierprops.linewidth'],
color=rcParams['boxplot.flierprops.color'],
marker=rcParams['boxplot.flierprops.marker'],
markerfacecolor=rcParams['boxplot.flierprops.markerfacecolor'],
markeredgecolor=rcParams['boxplot.flierprops.markeredgecolor'],
markersize=rcParams['boxplot.flierprops.markersize'],
)
final_flierprops['zorder'] = zorder
# flier (outlier) properties
if flierprops is not None:
final_flierprops.update(flierprops)
# median line properties
final_medianprops = dict(
linestyle=rcParams['boxplot.medianprops.linestyle'],
linewidth=rcParams['boxplot.medianprops.linewidth'],
color=rcParams['boxplot.medianprops.color'],
)
final_medianprops['zorder'] = zorder + zdelta
if medianprops is not None:
final_medianprops.update(medianprops)
# mean (line or point) properties
if meanline:
final_meanprops = dict(
linestyle=rcParams['boxplot.meanprops.linestyle'],
linewidth=rcParams['boxplot.meanprops.linewidth'],
color=rcParams['boxplot.meanprops.color'],
)
else:
final_meanprops = dict(
linestyle='',
marker=rcParams['boxplot.meanprops.marker'],
markerfacecolor=rcParams['boxplot.meanprops.markerfacecolor'],
markeredgecolor=rcParams['boxplot.meanprops.markeredgecolor'],
markersize=rcParams['boxplot.meanprops.markersize'],
)
final_meanprops['zorder'] = zorder + zdelta
if meanprops is not None:
final_meanprops.update(meanprops)
def to_vc(xs, ys):
# convert arguments to verts and codes, append (0, 0) (ignored).
verts = np.append(np.column_stack([xs, ys]), [(0, 0)], 0)
codes = ([mpath.Path.MOVETO]
+ [mpath.Path.LINETO] * (len(verts) - 2)
+ [mpath.Path.CLOSEPOLY])
return verts, codes
def patch_list(xs, ys, **kwargs):
verts, codes = to_vc(xs, ys)
path = mpath.Path(verts, codes)
patch = mpatches.PathPatch(path, **kwargs)
self.add_artist(patch)
return [patch]
# vertical or horizontal plot?
if vert:
def doplot(*args, **kwargs):
return self.plot(*args, **kwargs)
def dopatch(xs, ys, **kwargs):
return patch_list(xs, ys, **kwargs)
else:
def doplot(*args, **kwargs):
shuffled = []
for i in xrange(0, len(args), 2):
shuffled.extend([args[i + 1], args[i]])
return self.plot(*shuffled, **kwargs)
def dopatch(xs, ys, **kwargs):
xs, ys = ys, xs # flip X, Y
return patch_list(xs, ys, **kwargs)
# input validation
N = len(bxpstats)
datashape_message = ("List of boxplot statistics and `{0}` "
"values must have same the length")
# check position
if positions is None:
positions = list(xrange(1, N + 1))
elif len(positions) != N:
raise ValueError(datashape_message.format("positions"))
# width
if widths is None:
widths = [np.clip(0.15 * np.ptp(positions), 0.15, 0.5)] * N
elif np.isscalar(widths):
widths = [widths] * N
elif len(widths) != N:
raise ValueError(datashape_message.format("widths"))
# check and save the `hold` state of the current axes
if not self._hold:
self.cla()
holdStatus = self._hold
for pos, width, stats in zip(positions, widths, bxpstats):
# try to find a new label
datalabels.append(stats.get('label', pos))
# whisker coords
whisker_x = np.ones(2) * pos
whiskerlo_y = np.array([stats['q1'], stats['whislo']])
whiskerhi_y = np.array([stats['q3'], stats['whishi']])
# cap coords
cap_left = pos - width * 0.25
cap_right = pos + width * 0.25
cap_x = np.array([cap_left, cap_right])
cap_lo = np.ones(2) * stats['whislo']
cap_hi = np.ones(2) * stats['whishi']
# box and median coords
box_left = pos - width * 0.5
box_right = pos + width * 0.5
med_y = [stats['med'], stats['med']]
# notched boxes
if shownotches:
box_x = [box_left, box_right, box_right, cap_right, box_right,
box_right, box_left, box_left, cap_left, box_left,
box_left]
box_y = [stats['q1'], stats['q1'], stats['cilo'],
stats['med'], stats['cihi'], stats['q3'],
stats['q3'], stats['cihi'], stats['med'],
stats['cilo'], stats['q1']]
med_x = cap_x
# plain boxes
else:
box_x = [box_left, box_right, box_right, box_left, box_left]
box_y = [stats['q1'], stats['q1'], stats['q3'], stats['q3'],
stats['q1']]
med_x = [box_left, box_right]
# maybe draw the box:
if showbox:
if patch_artist:
boxes.extend(dopatch(box_x, box_y, **final_boxprops))
else:
boxes.extend(doplot(box_x, box_y, **final_boxprops))
# draw the whiskers
whiskers.extend(doplot(
whisker_x, whiskerlo_y, **final_whiskerprops
))
whiskers.extend(doplot(
whisker_x, whiskerhi_y, **final_whiskerprops
))
# maybe draw the caps:
if showcaps:
caps.extend(doplot(cap_x, cap_lo, **final_capprops))
caps.extend(doplot(cap_x, cap_hi, **final_capprops))
# draw the medians
medians.extend(doplot(med_x, med_y, **final_medianprops))
# maybe draw the means
if showmeans:
if meanline:
means.extend(doplot(
[box_left, box_right], [stats['mean'], stats['mean']],
**final_meanprops
))
else:
means.extend(doplot(
[pos], [stats['mean']], **final_meanprops
))
# maybe draw the fliers
if showfliers:
# fliers coords
flier_x = np.ones(len(stats['fliers'])) * pos
flier_y = stats['fliers']
fliers.extend(doplot(
flier_x, flier_y, **final_flierprops
))
# fix our axes/ticks up a little
if vert:
setticks = self.set_xticks
setlim = self.set_xlim
setlabels = self.set_xticklabels
else:
setticks = self.set_yticks
setlim = self.set_ylim
setlabels = self.set_yticklabels
if manage_xticks:
newlimits = min(positions) - 0.5, max(positions) + 0.5
setlim(newlimits)
setticks(positions)
setlabels(datalabels)
# reset hold status
self._hold = holdStatus
return dict(whiskers=whiskers, caps=caps, boxes=boxes,
medians=medians, fliers=fliers, means=means)
@_preprocess_data(replace_names=["x", "y", "s", "linewidths",
"edgecolors", "c", "facecolor",
"facecolors", "color"],
label_namer="y")
def scatter(self, x, y, s=None, c=None, marker=None, cmap=None, norm=None,
vmin=None, vmax=None, alpha=None, linewidths=None,
verts=None, edgecolors=None,
**kwargs):
"""
A scatter plot of *y* vs *x* with varying marker size and/or color.
Parameters
----------
x, y : array_like, shape (n, )
The data positions.
s : scalar or array_like, shape (n, ), optional
The marker size in points**2.
Default is ``rcParams['lines.markersize'] ** 2``.
c : color, sequence, or sequence of color, optional, default: 'b'
The marker color. Possible values:
- A single color format string.
- A sequence of color specifications of length n.
- A sequence of n numbers to be mapped to colors using *cmap* and
*norm*.
- A 2-D array in which the rows are RGB or RGBA.
Note that *c* should not be a single numeric RGB or RGBA sequence
because that is indistinguishable from an array of values to be
colormapped. If you want to specify the same RGB or RGBA value for
all points, use a 2-D array with a single row.
marker : `~matplotlib.markers.MarkerStyle`, optional, default: 'o'
The marker style. *marker* can be either an instance of the class
or the text shorthand for a particular marker.
See `~matplotlib.markers` for more information marker styles.
cmap : `~matplotlib.colors.Colormap`, optional, default: None
A `.Colormap` instance or registered colormap name. *cmap* is only
used if *c* is an array of floats. If ``None``, defaults to rc
``image.cmap``.
norm : `~matplotlib.colors.Normalize`, optional, default: None
A `.Normalize` instance is used to scale luminance data to 0, 1.
*norm* is only used if *c* is an array of floats. If *None*, use
the default `.colors.Normalize`.
vmin, vmax : scalar, optional, default: None
*vmin* and *vmax* are used in conjunction with *norm* to normalize
luminance data. If None, the respective min and max of the color
array is used. *vmin* and *vmax* are ignored if you pass a *norm*
instance.
alpha : scalar, optional, default: None
The alpha blending value, between 0 (transparent) and 1 (opaque).
linewidths : scalar or array_like, optional, default: None
The linewidth of the marker edges. Note: The default *edgecolors*
is 'face'. You may want to change this as well.
If *None*, defaults to rcParams ``lines.linewidth``.
verts : sequence of (x, y), optional
If *marker* is *None*, these vertices will be used to construct
the marker. The center of the marker is located at (0, 0) in
normalized units. The overall marker is rescaled by *s*.
edgecolors : color or sequence of color, optional, default: 'face'
The edge color of the marker. Possible values:
- 'face': The edge color will always be the same as the face color.
- 'none': No patch boundary will be drawn.
- A matplotib color.
For non-filled markers, the *edgecolors* kwarg is ignored and
forced to 'face' internally.
Returns
-------
paths : `~matplotlib.collections.PathCollection`
Other Parameters
----------------
**kwargs : `~matplotlib.collections.Collection` properties
See Also
--------
plot : To plot scatter plots when markers are identical in size and
color.
Notes
-----
* The `.plot` function will be faster for scatterplots where markers
don't vary in size or color.
* Any or all of *x*, *y*, *s*, and *c* may be masked arrays, in which
case all masks will be combined and only unmasked points will be
plotted.
* Fundamentally, scatter works with 1-D arrays; *x*, *y*, *s*, and *c*
may be input as 2-D arrays, but within scatter they will be
flattened. The exception is *c*, which will be flattened only if its
size matches the size of *x* and *y*.
"""
if not self._hold:
self.cla()
# Process **kwargs to handle aliases, conflicts with explicit kwargs:
facecolors = None
edgecolors = kwargs.pop('edgecolor', edgecolors)
fc = kwargs.pop('facecolors', None)
fc = kwargs.pop('facecolor', fc)
if fc is not None:
facecolors = fc
co = kwargs.pop('color', None)
if co is not None:
try:
mcolors.to_rgba_array(co)
except ValueError:
raise ValueError("'color' kwarg must be an mpl color"
" spec or sequence of color specs.\n"
"For a sequence of values to be"
" color-mapped, use the 'c' kwarg instead.")
if edgecolors is None:
edgecolors = co
if facecolors is None:
facecolors = co
if c is not None:
raise ValueError("Supply a 'c' kwarg or a 'color' kwarg"
" but not both; they differ but"
" their functionalities overlap.")
if c is None:
if facecolors is not None:
c = facecolors
else:
if rcParams['_internal.classic_mode']:
c = 'b' # The original default
else:
c = self._get_patches_for_fill.get_next_color()
c_none = True
else:
c_none = False
if edgecolors is None and not rcParams['_internal.classic_mode']:
edgecolors = 'face'
self._process_unit_info(xdata=x, ydata=y, kwargs=kwargs)
x = self.convert_xunits(x)
y = self.convert_yunits(y)
# np.ma.ravel yields an ndarray, not a masked array,
# unless its argument is a masked array.
xy_shape = (np.shape(x), np.shape(y))
x = np.ma.ravel(x)
y = np.ma.ravel(y)
if x.size != y.size:
raise ValueError("x and y must be the same size")
if s is None:
if rcParams['_internal.classic_mode']:
s = 20
else:
s = rcParams['lines.markersize'] ** 2.0
s = np.ma.ravel(s) # This doesn't have to match x, y in size.
# After this block, c_array will be None unless
# c is an array for mapping. The potential ambiguity
# with a sequence of 3 or 4 numbers is resolved in
# favor of mapping, not rgb or rgba.
if c_none or co is not None:
c_array = None
else:
try:
c_array = np.asanyarray(c, dtype=float)
if c_array.shape in xy_shape:
c = np.ma.ravel(c_array)
else:
# Wrong size; it must not be intended for mapping.
c_array = None
except ValueError:
# Failed to make a floating-point array; c must be color specs.
c_array = None
if c_array is None:
try:
# must be acceptable as PathCollection facecolors
colors = mcolors.to_rgba_array(c)
except ValueError:
# c not acceptable as PathCollection facecolor
raise ValueError("c of shape {} not acceptable as a color "
"sequence for x with size {}, y with size {}"
.format(c.shape, x.size, y.size))
else:
colors = None # use cmap, norm after collection is created
# `delete_masked_points` only modifies arguments of the same length as
# `x`.
x, y, s, c, colors, edgecolors, linewidths =\
cbook.delete_masked_points(
x, y, s, c, colors, edgecolors, linewidths)
scales = s # Renamed for readability below.
# to be API compatible
if marker is None and verts is not None:
marker = (verts, 0)
verts = None
# load default marker from rcParams
if marker is None:
marker = rcParams['scatter.marker']
if isinstance(marker, mmarkers.MarkerStyle):
marker_obj = marker
else:
marker_obj = mmarkers.MarkerStyle(marker)
path = marker_obj.get_path().transformed(
marker_obj.get_transform())
if not marker_obj.is_filled():
edgecolors = 'face'
linewidths = rcParams['lines.linewidth']
offsets = np.column_stack([x, y])
collection = mcoll.PathCollection(
(path,), scales,
facecolors=colors,
edgecolors=edgecolors,
linewidths=linewidths,
offsets=offsets,
transOffset=kwargs.pop('transform', self.transData),
alpha=alpha
)
collection.set_transform(mtransforms.IdentityTransform())
collection.update(kwargs)
if colors is None:
if norm is not None and not isinstance(norm, mcolors.Normalize):
raise ValueError(
"'norm' must be an instance of 'mcolors.Normalize'")
collection.set_array(np.asarray(c))
collection.set_cmap(cmap)
collection.set_norm(norm)
if vmin is not None or vmax is not None:
collection.set_clim(vmin, vmax)
else:
collection.autoscale_None()
# Classic mode only:
# ensure there are margins to allow for the
# finite size of the symbols. In v2.x, margins
# are present by default, so we disable this
# scatter-specific override.
if rcParams['_internal.classic_mode']:
if self._xmargin < 0.05 and x.size > 0:
self.set_xmargin(0.05)
if self._ymargin < 0.05 and x.size > 0:
self.set_ymargin(0.05)
self.add_collection(collection)
self.autoscale_view()
return collection
@_preprocess_data(replace_names=["x", "y"], label_namer="y")
@docstring.dedent_interpd
def hexbin(self, x, y, C=None, gridsize=100, bins=None,
xscale='linear', yscale='linear', extent=None,
cmap=None, norm=None, vmin=None, vmax=None,
alpha=None, linewidths=None, edgecolors='face',
reduce_C_function=np.mean, mincnt=None, marginals=False,
**kwargs):
"""
Make a hexagonal binning plot.
Make a hexagonal binning plot of *x* versus *y*, where *x*,
*y* are 1-D sequences of the same length, *N*. If *C* is *None*
(the default), this is a histogram of the number of occurrences
of the observations at (x[i],y[i]).
If *C* is specified, it specifies values at the coordinate
(x[i],y[i]). These values are accumulated for each hexagonal
bin and then reduced according to *reduce_C_function*, which
defaults to numpy's mean function (np.mean). (If *C* is
specified, it must also be a 1-D sequence of the same length
as *x* and *y*.)
Parameters
----------
x, y : array or masked array
C : array or masked array, optional, default is *None*
gridsize : int or (int, int), optional, default is 100
The number of hexagons in the *x*-direction, default is
100. The corresponding number of hexagons in the
*y*-direction is chosen such that the hexagons are
approximately regular. Alternatively, gridsize can be a
tuple with two elements specifying the number of hexagons
in the *x*-direction and the *y*-direction.
bins : {'log'} or int or sequence, optional, default is *None*
If *None*, no binning is applied; the color of each hexagon
directly corresponds to its count value.
If 'log', use a logarithmic scale for the color
map. Internally, :math:`log_{10}(i+1)` is used to
determine the hexagon color.
If an integer, divide the counts in the specified number
of bins, and color the hexagons accordingly.
If a sequence of values, the values of the lower bound of
the bins to be used.
xscale : {'linear', 'log'}, optional, default is 'linear'
Use a linear or log10 scale on the horizontal axis.
yscale : {'linear', 'log'}, optional, default is 'linear'
Use a linear or log10 scale on the vertical axis.
mincnt : int > 0, optional, default is *None*
If not *None*, only display cells with more than *mincnt*
number of points in the cell
marginals : bool, optional, default is *False*
if marginals is *True*, plot the marginal density as
colormapped rectagles along the bottom of the x-axis and
left of the y-axis
extent : scalar, optional, default is *None*
The limits of the bins. The default assigns the limits
based on *gridsize*, *x*, *y*, *xscale* and *yscale*.
If *xscale* or *yscale* is set to 'log', the limits are
expected to be the exponent for a power of 10. E.g. for
x-limits of 1 and 50 in 'linear' scale and y-limits
of 10 and 1000 in 'log' scale, enter (1, 50, 1, 3).
Order of scalars is (left, right, bottom, top).
Other Parameters
----------------
cmap : object, optional, default is *None*
a :class:`matplotlib.colors.Colormap` instance. If *None*,
defaults to rc ``image.cmap``.
norm : object, optional, default is *None*
:class:`matplotlib.colors.Normalize` instance is used to
scale luminance data to 0,1.
vmin, vmax : scalar, optional, default is *None*
*vmin* and *vmax* are used in conjunction with *norm* to
normalize luminance data. If *None*, the min and max of the
color array *C* are used. Note if you pass a norm instance
your settings for *vmin* and *vmax* will be ignored.
alpha : scalar between 0 and 1, optional, default is *None*
the alpha value for the patches
linewidths : scalar, optional, default is *None*
If *None*, defaults to 1.0.
edgecolors : {'face', 'none', *None*} or color, optional
If 'face' (the default), draws the edges in the same color as the
fill color.
If 'none', no edge is drawn; this can sometimes lead to unsightly
unpainted pixels between the hexagons.
If *None*, draws outlines in the default color.
If a matplotlib color arg, draws outlines in the specified color.
Returns
-------
object
a :class:`~matplotlib.collections.PolyCollection` instance; use
:meth:`~matplotlib.collections.PolyCollection.get_array` on
this :class:`~matplotlib.collections.PolyCollection` to get
the counts in each hexagon.
If *marginals* is *True*, horizontal
bar and vertical bar (both PolyCollections) will be attached
to the return collection as attributes *hbar* and *vbar*.
Notes
-----
The standard descriptions of all the
:class:`~matplotlib.collections.Collection` parameters:
%(Collection)s
"""
if not self._hold:
self.cla()
self._process_unit_info(xdata=x, ydata=y, kwargs=kwargs)
x, y, C = cbook.delete_masked_points(x, y, C)
# Set the size of the hexagon grid
if iterable(gridsize):
nx, ny = gridsize
else:
nx = gridsize
ny = int(nx / math.sqrt(3))
# Count the number of data in each hexagon
x = np.array(x, float)
y = np.array(y, float)
if xscale == 'log':
if np.any(x <= 0.0):
raise ValueError("x contains non-positive values, so can not"
" be log-scaled")
x = np.log10(x)
if yscale == 'log':
if np.any(y <= 0.0):
raise ValueError("y contains non-positive values, so can not"
" be log-scaled")
y = np.log10(y)
if extent is not None:
xmin, xmax, ymin, ymax = extent
else:
xmin, xmax = (np.min(x), np.max(x)) if len(x) else (0, 1)
ymin, ymax = (np.min(y), np.max(y)) if len(y) else (0, 1)
# to avoid issues with singular data, expand the min/max pairs
xmin, xmax = mtransforms.nonsingular(xmin, xmax, expander=0.1)
ymin, ymax = mtransforms.nonsingular(ymin, ymax, expander=0.1)
# In the x-direction, the hexagons exactly cover the region from
# xmin to xmax. Need some padding to avoid roundoff errors.
padding = 1.e-9 * (xmax - xmin)
xmin -= padding
xmax += padding
sx = (xmax - xmin) / nx
sy = (ymax - ymin) / ny
if marginals:
xorig = x.copy()
yorig = y.copy()
x = (x - xmin) / sx
y = (y - ymin) / sy
ix1 = np.round(x).astype(int)
iy1 = np.round(y).astype(int)
ix2 = np.floor(x).astype(int)
iy2 = np.floor(y).astype(int)
nx1 = nx + 1
ny1 = ny + 1
nx2 = nx
ny2 = ny
n = nx1 * ny1 + nx2 * ny2
d1 = (x - ix1) ** 2 + 3.0 * (y - iy1) ** 2
d2 = (x - ix2 - 0.5) ** 2 + 3.0 * (y - iy2 - 0.5) ** 2
bdist = (d1 < d2)
if C is None:
lattice1 = np.zeros((nx1, ny1))
lattice2 = np.zeros((nx2, ny2))
cond1 = (0 <= ix1) * (ix1 < nx1) * (0 <= iy1) * (iy1 < ny1)
cond2 = (0 <= ix2) * (ix2 < nx2) * (0 <= iy2) * (iy2 < ny2)
cond1 *= bdist
cond2 *= np.logical_not(bdist)
ix1, iy1 = ix1[cond1], iy1[cond1]
ix2, iy2 = ix2[cond2], iy2[cond2]
for ix, iy in zip(ix1, iy1):
lattice1[ix, iy] += 1
for ix, iy in zip(ix2, iy2):
lattice2[ix, iy] += 1
# threshold
if mincnt is not None:
lattice1[lattice1 < mincnt] = np.nan
lattice2[lattice2 < mincnt] = np.nan
accum = np.hstack((lattice1.ravel(),
lattice2.ravel()))
good_idxs = ~np.isnan(accum)
else:
if mincnt is None:
mincnt = 0
# create accumulation arrays
lattice1 = np.empty((nx1, ny1), dtype=object)
for i in xrange(nx1):
for j in xrange(ny1):
lattice1[i, j] = []
lattice2 = np.empty((nx2, ny2), dtype=object)
for i in xrange(nx2):
for j in xrange(ny2):
lattice2[i, j] = []
for i in xrange(len(x)):
if bdist[i]:
if 0 <= ix1[i] < nx1 and 0 <= iy1[i] < ny1:
lattice1[ix1[i], iy1[i]].append(C[i])
else:
if 0 <= ix2[i] < nx2 and 0 <= iy2[i] < ny2:
lattice2[ix2[i], iy2[i]].append(C[i])
for i in xrange(nx1):
for j in xrange(ny1):
vals = lattice1[i, j]
if len(vals) > mincnt:
lattice1[i, j] = reduce_C_function(vals)
else:
lattice1[i, j] = np.nan
for i in xrange(nx2):
for j in xrange(ny2):
vals = lattice2[i, j]
if len(vals) > mincnt:
lattice2[i, j] = reduce_C_function(vals)
else:
lattice2[i, j] = np.nan
accum = np.hstack((lattice1.astype(float).ravel(),
lattice2.astype(float).ravel()))
good_idxs = ~np.isnan(accum)
offsets = np.zeros((n, 2), float)
offsets[:nx1 * ny1, 0] = np.repeat(np.arange(nx1), ny1)
offsets[:nx1 * ny1, 1] = np.tile(np.arange(ny1), nx1)
offsets[nx1 * ny1:, 0] = np.repeat(np.arange(nx2) + 0.5, ny2)
offsets[nx1 * ny1:, 1] = np.tile(np.arange(ny2), nx2) + 0.5
offsets[:, 0] *= sx
offsets[:, 1] *= sy
offsets[:, 0] += xmin
offsets[:, 1] += ymin
# remove accumulation bins with no data
offsets = offsets[good_idxs, :]
accum = accum[good_idxs]
polygon = np.zeros((6, 2), float)
polygon[:, 0] = sx * np.array([0.5, 0.5, 0.0, -0.5, -0.5, 0.0])
polygon[:, 1] = sy * np.array([-0.5, 0.5, 1.0, 0.5, -0.5, -1.0]) / 3.0
if linewidths is None:
linewidths = [1.0]
if xscale == 'log' or yscale == 'log':
polygons = np.expand_dims(polygon, 0) + np.expand_dims(offsets, 1)
if xscale == 'log':
polygons[:, :, 0] = 10.0 ** polygons[:, :, 0]
xmin = 10.0 ** xmin
xmax = 10.0 ** xmax
self.set_xscale(xscale)
if yscale == 'log':
polygons[:, :, 1] = 10.0 ** polygons[:, :, 1]
ymin = 10.0 ** ymin
ymax = 10.0 ** ymax
self.set_yscale(yscale)
collection = mcoll.PolyCollection(
polygons,
edgecolors=edgecolors,
linewidths=linewidths,
)
else:
collection = mcoll.PolyCollection(
[polygon],
edgecolors=edgecolors,
linewidths=linewidths,
offsets=offsets,
transOffset=mtransforms.IdentityTransform(),
offset_position="data"
)
if isinstance(norm, mcolors.LogNorm):
if (accum == 0).any():
# make sure we have not zeros
accum += 1
# autoscale the norm with curren accum values if it hasn't
# been set
if norm is not None:
if norm.vmin is None and norm.vmax is None:
norm.autoscale(accum)
# Transform accum if needed
if bins == 'log':
accum = np.log10(accum + 1)
elif bins is not None:
if not iterable(bins):
minimum, maximum = min(accum), max(accum)
bins -= 1 # one less edge than bins
bins = minimum + (maximum - minimum) * np.arange(bins) / bins
bins = np.sort(bins)
accum = bins.searchsorted(accum)
if norm is not None and not isinstance(norm, mcolors.Normalize):
raise ValueError(
"'norm' must be an instance of 'mcolors.Normalize'")
collection.set_array(accum)
collection.set_cmap(cmap)
collection.set_norm(norm)
collection.set_alpha(alpha)
collection.update(kwargs)
if vmin is not None or vmax is not None:
collection.set_clim(vmin, vmax)
else:
collection.autoscale_None()
corners = ((xmin, ymin), (xmax, ymax))
self.update_datalim(corners)
collection.sticky_edges.x[:] = [xmin, xmax]
collection.sticky_edges.y[:] = [ymin, ymax]
self.autoscale_view(tight=True)
# add the collection last
self.add_collection(collection, autolim=False)
if not marginals:
return collection
if C is None:
C = np.ones(len(x))
def coarse_bin(x, y, coarse):
ind = coarse.searchsorted(x).clip(0, len(coarse) - 1)
mus = np.zeros(len(coarse))
for i in range(len(coarse)):
yi = y[ind == i]
if len(yi) > 0:
mu = reduce_C_function(yi)
else:
mu = np.nan
mus[i] = mu
return mus
coarse = np.linspace(xmin, xmax, gridsize)
xcoarse = coarse_bin(xorig, C, coarse)
valid = ~np.isnan(xcoarse)
verts, values = [], []
for i, val in enumerate(xcoarse):
thismin = coarse[i]
if i < len(coarse) - 1:
thismax = coarse[i + 1]
else:
thismax = thismin + np.diff(coarse)[-1]
if not valid[i]:
continue
verts.append([(thismin, 0),
(thismin, 0.05),
(thismax, 0.05),
(thismax, 0)])
values.append(val)
values = np.array(values)
trans = self.get_xaxis_transform(which='grid')
hbar = mcoll.PolyCollection(verts, transform=trans, edgecolors='face')
hbar.set_array(values)
hbar.set_cmap(cmap)
hbar.set_norm(norm)
hbar.set_alpha(alpha)
hbar.update(kwargs)
self.add_collection(hbar, autolim=False)
coarse = np.linspace(ymin, ymax, gridsize)
ycoarse = coarse_bin(yorig, C, coarse)
valid = ~np.isnan(ycoarse)
verts, values = [], []
for i, val in enumerate(ycoarse):
thismin = coarse[i]
if i < len(coarse) - 1:
thismax = coarse[i + 1]
else:
thismax = thismin + np.diff(coarse)[-1]
if not valid[i]:
continue
verts.append([(0, thismin), (0.0, thismax),
(0.05, thismax), (0.05, thismin)])
values.append(val)
values = np.array(values)
trans = self.get_yaxis_transform(which='grid')
vbar = mcoll.PolyCollection(verts, transform=trans, edgecolors='face')
vbar.set_array(values)
vbar.set_cmap(cmap)
vbar.set_norm(norm)
vbar.set_alpha(alpha)
vbar.update(kwargs)
self.add_collection(vbar, autolim=False)
collection.hbar = hbar
collection.vbar = vbar
def on_changed(collection):
hbar.set_cmap(collection.get_cmap())
hbar.set_clim(collection.get_clim())
vbar.set_cmap(collection.get_cmap())
vbar.set_clim(collection.get_clim())
collection.callbacksSM.connect('changed', on_changed)
return collection
@docstring.dedent_interpd
def arrow(self, x, y, dx, dy, **kwargs):
"""
Add an arrow to the axes.
This draws an arrow from ``(x, y)`` to ``(x+dx, y+dy)``.
Parameters
----------
x, y : float
The x/y-coordinate of the arrow base.
dx, dy : float
The length of the arrow along x/y-direction.
Returns
-------
arrow : `.FancyArrow`
The created `.FancyArrow` object.
Other Parameters
----------------
**kwargs
Optional kwargs (inherited from `.FancyArrow` patch) control the
arrow construction and properties:
%(FancyArrow)s
Notes
-----
The resulting arrow is affected by the axes aspect ratio and limits.
This may produce an arrow whose head is not square with its stem. To
create an arrow whose head is square with its stem,
use :meth:`annotate` for example:
>>> ax.annotate("", xy=(0.5, 0.5), xytext=(0, 0),
... arrowprops=dict(arrowstyle="->"))
"""
# Strip away units for the underlying patch since units
# do not make sense to most patch-like code
x = self.convert_xunits(x)
y = self.convert_yunits(y)
dx = self.convert_xunits(dx)
dy = self.convert_yunits(dy)
a = mpatches.FancyArrow(x, y, dx, dy, **kwargs)
self.add_artist(a)
return a
def quiverkey(self, *args, **kw):
qk = mquiver.QuiverKey(*args, **kw)
self.add_artist(qk)
return qk
quiverkey.__doc__ = mquiver.QuiverKey.quiverkey_doc
# Handle units for x and y, if they've been passed
def _quiver_units(self, args, kw):
if len(args) > 3:
x, y = args[0:2]
self._process_unit_info(xdata=x, ydata=y, kwargs=kw)
x = self.convert_xunits(x)
y = self.convert_yunits(y)
return (x, y) + args[2:]
return args
# args can by a combination if X, Y, U, V, C and all should be replaced
@_preprocess_data(replace_all_args=True, label_namer=None)
def quiver(self, *args, **kw):
if not self._hold:
self.cla()
# Make sure units are handled for x and y values
args = self._quiver_units(args, kw)
q = mquiver.Quiver(self, *args, **kw)
self.add_collection(q, autolim=True)
self.autoscale_view()
return q
quiver.__doc__ = mquiver.Quiver.quiver_doc
# args can by either Y or y1,y2,... and all should be replaced
@_preprocess_data(replace_all_args=True, label_namer=None)
def stackplot(self, x, *args, **kwargs):
return mstack.stackplot(self, x, *args, **kwargs)
stackplot.__doc__ = mstack.stackplot.__doc__
@_preprocess_data(replace_names=["x", "y", "u", "v", "start_points"],
label_namer=None)
def streamplot(self, x, y, u, v, density=1, linewidth=None, color=None,
cmap=None, norm=None, arrowsize=1, arrowstyle='-|>',
minlength=0.1, transform=None, zorder=None,
start_points=None, maxlength=4.0,
integration_direction='both'):
if not self._hold:
self.cla()
stream_container = mstream.streamplot(
self, x, y, u, v,
density=density,
linewidth=linewidth,
color=color,
cmap=cmap,
norm=norm,
arrowsize=arrowsize,
arrowstyle=arrowstyle,
minlength=minlength,
start_points=start_points,
transform=transform,
zorder=zorder,
maxlength=maxlength,
integration_direction=integration_direction)
return stream_container
streamplot.__doc__ = mstream.streamplot.__doc__
# args can be some combination of X, Y, U, V, C and all should be replaced
@_preprocess_data(replace_all_args=True, label_namer=None)
@docstring.dedent_interpd
def barbs(self, *args, **kw):
"""
%(barbs_doc)s
"""
if not self._hold:
self.cla()
# Make sure units are handled for x and y values
args = self._quiver_units(args, kw)
b = mquiver.Barbs(self, *args, **kw)
self.add_collection(b, autolim=True)
self.autoscale_view()
return b
@_preprocess_data(replace_names=["x", "y"], label_namer=None,
positional_parameter_names=["x", "y", "c"])
def fill(self, *args, **kwargs):
"""
Plot filled polygons.
Parameters
----------
args : sequence of x, y, [color]
Each polygon is defined by the lists of *x* and *y* positions of
its nodes, optionally followed by by a *color* specifier. See
:mod:`matplotlib.colors` for supported color specifiers. The
standard color cycle is used for polygons without a color
specifier.
You can plot multiple polygons by providing multiple *x*, *y*,
*[color]* groups.
For example, each of the following is legal::
ax.fill(x, y) # a polygon with default color
ax.fill(x, y, "b") # a blue polygon
ax.fill(x, y, x2, y2) # two polygons
ax.fill(x, y, "b", x2, y2, "r") # a blue and a red polygon
Returns
-------
a list of :class:`~matplotlib.patches.Polygon`
Other Parameters
----------------
**kwargs : :class:`~matplotlib.patches.Polygon` properties
Notes
-----
Use :meth:`fill_between` if you would like to fill the region between
two curves.
"""
if not self._hold:
self.cla()
kwargs = cbook.normalize_kwargs(kwargs, _alias_map)
patches = []
for poly in self._get_patches_for_fill(*args, **kwargs):
self.add_patch(poly)
patches.append(poly)
self.autoscale_view()
return patches
@_preprocess_data(replace_names=["x", "y1", "y2", "where"],
label_namer=None)
@docstring.dedent_interpd
def fill_between(self, x, y1, y2=0, where=None, interpolate=False,
step=None, **kwargs):
"""
Fill the area between two horizontal curves.
The curves are defined by the points (*x*, *y1*) and (*x*, *y2*). This
creates one or multiple polygons describing the filled area.
You may exclude some horizontal sections from filling using *where*.
By default, the edges connect the given points directly. Use *step* if
the filling should be a step function, i.e. constant in between *x*.
Parameters
----------
x : array (length N)
The x coordinates of the nodes defining the curves.
y1 : array (length N) or scalar
The y coordinates of the nodes defining the first curve.
y2 : array (length N) or scalar, optional, default: 0
The y coordinates of the nodes defining the second curve.
where : array of bool (length N), optional, default: None
Define *where* to exclude some horizontal regions from being
filled. The filled regions are defined by the coordinates
``x[where]``. More precisely, fill between ``x[i]`` and ``x[i+1]``
if ``where[i] and where[i+1]``. Note that this definition implies
that an isolated *True* value between two *False* values in
*where* will not result in filling. Both sides of the *True*
position remain unfilled due to the adjacent *False* values.
interpolate : bool, optional
This option is only relvant if *where* is used and the two curves
are crossing each other.
Semantically, *where* is often used for *y1* > *y2* or similar.
By default, the nodes of the polygon defining the filled region
will only be placed at the positions in the *x* array. Such a
polygon cannot describe the above semantics close to the
intersection. The x-sections containing the intersecion are
simply clipped.
Setting *interpolate* to *True* will calculate the actual
interscection point and extend the filled region up to this point.
step : {'pre', 'post', 'mid'}, optional
Define *step* if the filling should be a step function,
i.e. constant in between *x*. The value determines where the
step will occur:
- 'pre': The y value is continued constantly to the left from
every *x* position, i.e. the interval ``(x[i-1], x[i]]`` has the
value ``y[i]``.
- 'post': The y value is continued constantly to the right from
every *x* position, i.e. the interval ``[x[i], x[i+1])`` has the
value ``y[i]``.
- 'mid': Steps occur half-way between the *x* positions.
Other Parameters
----------------
**kwargs
All other keyword arguments are passed on to `.PolyCollection`.
They control the `.Polygon` properties:
%(PolyCollection)s
Returns
-------
`.PolyCollection`
A `.PolyCollection` containing the plotted polygons.
See Also
--------
fill_betweenx : Fill between two sets of x-values.
Notes
-----
.. [notes section required to get data note injection right]
"""
if not rcParams['_internal.classic_mode']:
color_aliases = mcoll._color_aliases
kwargs = cbook.normalize_kwargs(kwargs, color_aliases)
if not any(c in kwargs for c in ('color', 'facecolors')):
fc = self._get_patches_for_fill.get_next_color()
kwargs['facecolors'] = fc
# Handle united data, such as dates
self._process_unit_info(xdata=x, ydata=y1, kwargs=kwargs)
self._process_unit_info(ydata=y2)
# Convert the arrays so we can work with them
x = ma.masked_invalid(self.convert_xunits(x))
y1 = ma.masked_invalid(self.convert_yunits(y1))
y2 = ma.masked_invalid(self.convert_yunits(y2))
for name, array in [('x', x), ('y1', y1), ('y2', y2)]:
if array.ndim > 1:
raise ValueError('Input passed into argument "%r"' % name +
'is not 1-dimensional.')
if where is None:
where = True
where = where & ~functools.reduce(np.logical_or,
map(np.ma.getmask, [x, y1, y2]))
x, y1, y2 = np.broadcast_arrays(np.atleast_1d(x), y1, y2)
polys = []
for ind0, ind1 in cbook.contiguous_regions(where):
xslice = x[ind0:ind1]
y1slice = y1[ind0:ind1]
y2slice = y2[ind0:ind1]
if step is not None:
step_func = STEP_LOOKUP_MAP["steps-" + step]
xslice, y1slice, y2slice = step_func(xslice, y1slice, y2slice)
if not len(xslice):
continue
N = len(xslice)
X = np.zeros((2 * N + 2, 2), float)
if interpolate:
def get_interp_point(ind):
im1 = max(ind - 1, 0)
x_values = x[im1:ind + 1]
diff_values = y1[im1:ind + 1] - y2[im1:ind + 1]
y1_values = y1[im1:ind + 1]
if len(diff_values) == 2:
if np.ma.is_masked(diff_values[1]):
return x[im1], y1[im1]
elif np.ma.is_masked(diff_values[0]):
return x[ind], y1[ind]
diff_order = diff_values.argsort()
diff_root_x = np.interp(
0, diff_values[diff_order], x_values[diff_order])
x_order = x_values.argsort()
diff_root_y = np.interp(diff_root_x, x_values[x_order],
y1_values[x_order])
return diff_root_x, diff_root_y
start = get_interp_point(ind0)
end = get_interp_point(ind1)
else:
# the purpose of the next two lines is for when y2 is a
# scalar like 0 and we want the fill to go all the way
# down to 0 even if none of the y1 sample points do
start = xslice[0], y2slice[0]
end = xslice[-1], y2slice[-1]
X[0] = start
X[N + 1] = end
X[1:N + 1, 0] = xslice
X[1:N + 1, 1] = y1slice
X[N + 2:, 0] = xslice[::-1]
X[N + 2:, 1] = y2slice[::-1]
polys.append(X)
collection = mcoll.PolyCollection(polys, **kwargs)
# now update the datalim and autoscale
XY1 = np.array([x[where], y1[where]]).T
XY2 = np.array([x[where], y2[where]]).T
self.dataLim.update_from_data_xy(XY1, self.ignore_existing_data_limits,
updatex=True, updatey=True)
self.ignore_existing_data_limits = False
self.dataLim.update_from_data_xy(XY2, self.ignore_existing_data_limits,
updatex=False, updatey=True)
self.add_collection(collection, autolim=False)
self.autoscale_view()
return collection
@_preprocess_data(replace_names=["y", "x1", "x2", "where"],
label_namer=None)
@docstring.dedent_interpd
def fill_betweenx(self, y, x1, x2=0, where=None,
step=None, interpolate=False, **kwargs):
"""
Fill the area between two vertical curves.
The curves are defined by the points (*x1*, *y*) and (*x2*, *y*). This
creates one or multiple polygons describing the filled area.
You may exclude some vertical sections from filling using *where*.
By default, the edges connect the given points directly. Use *step* if
the filling should be a step function, i.e. constant in between *y*.
Parameters
----------
y : array (length N)
The y coordinates of the nodes defining the curves.
x1 : array (length N) or scalar
The x coordinates of the nodes defining the first curve.
x2 : array (length N) or scalar, optional, default: 0
The x coordinates of the nodes defining the second curve.
where : array of bool (length N), optional, default: None
Define *where* to exclude some vertical regions from being
filled. The filled regions are defined by the coordinates
``y[where]``. More precisely, fill between ``y[i]`` and ``y[i+1]``
if ``where[i] and where[i+1]``. Note that this definition implies
that an isolated *True* value between two *False* values in
*where* will not result in filling. Both sides of the *True*
position remain unfilled due to the adjacent *False* values.
interpolate : bool, optional
This option is only relvant if *where* is used and the two curves
are crossing each other.
Semantically, *where* is often used for *x1* > *x2* or similar.
By default, the nodes of the polygon defining the filled region
will only be placed at the positions in the *y* array. Such a
polygon cannot describe the above semantics close to the
intersection. The y-sections containing the intersecion are
simply clipped.
Setting *interpolate* to *True* will calculate the actual
interscection point and extend the filled region up to this point.
step : {'pre', 'post', 'mid'}, optional
Define *step* if the filling should be a step function,
i.e. constant in between *y*. The value determines where the
step will occur:
- 'pre': The y value is continued constantly to the left from
every *x* position, i.e. the interval ``(x[i-1], x[i]]`` has the
value ``y[i]``.
- 'post': The y value is continued constantly to the right from
every *x* position, i.e. the interval ``[x[i], x[i+1])`` has the
value ``y[i]``.
- 'mid': Steps occur half-way between the *x* positions.
Other Parameters
----------------
**kwargs
All other keyword arguments are passed on to `.PolyCollection`.
They control the `.Polygon` properties:
%(PolyCollection)s
Returns
-------
`.PolyCollection`
A `.PolyCollection` containing the plotted polygons.
See Also
--------
fill_between : Fill between two sets of y-values.
Notes
-----
.. [notes section required to get data note injection right]
"""
if not rcParams['_internal.classic_mode']:
color_aliases = mcoll._color_aliases
kwargs = cbook.normalize_kwargs(kwargs, color_aliases)
if not any(c in kwargs for c in ('color', 'facecolors')):
fc = self._get_patches_for_fill.get_next_color()
kwargs['facecolors'] = fc
# Handle united data, such as dates
self._process_unit_info(ydata=y, xdata=x1, kwargs=kwargs)
self._process_unit_info(xdata=x2)
# Convert the arrays so we can work with them
y = ma.masked_invalid(self.convert_yunits(y))
x1 = ma.masked_invalid(self.convert_xunits(x1))
x2 = ma.masked_invalid(self.convert_xunits(x2))
for name, array in [('y', y), ('x1', x1), ('x2', x2)]:
if array.ndim > 1:
raise ValueError('Input passed into argument "%r"' % name +
'is not 1-dimensional.')
if where is None:
where = True
where = where & ~functools.reduce(np.logical_or,
map(np.ma.getmask, [y, x1, x2]))
y, x1, x2 = np.broadcast_arrays(np.atleast_1d(y), x1, x2)
polys = []
for ind0, ind1 in cbook.contiguous_regions(where):
yslice = y[ind0:ind1]
x1slice = x1[ind0:ind1]
x2slice = x2[ind0:ind1]
if step is not None:
step_func = STEP_LOOKUP_MAP["steps-" + step]
yslice, x1slice, x2slice = step_func(yslice, x1slice, x2slice)
if not len(yslice):
continue
N = len(yslice)
Y = np.zeros((2 * N + 2, 2), float)
if interpolate:
def get_interp_point(ind):
im1 = max(ind - 1, 0)
y_values = y[im1:ind + 1]
diff_values = x1[im1:ind + 1] - x2[im1:ind + 1]
x1_values = x1[im1:ind + 1]
if len(diff_values) == 2:
if np.ma.is_masked(diff_values[1]):
return x1[im1], y[im1]
elif np.ma.is_masked(diff_values[0]):
return x1[ind], y[ind]
diff_order = diff_values.argsort()
diff_root_y = np.interp(
0, diff_values[diff_order], y_values[diff_order])
y_order = y_values.argsort()
diff_root_x = np.interp(diff_root_y, y_values[y_order],
x1_values[y_order])
return diff_root_x, diff_root_y
start = get_interp_point(ind0)
end = get_interp_point(ind1)
else:
# the purpose of the next two lines is for when x2 is a
# scalar like 0 and we want the fill to go all the way
# down to 0 even if none of the x1 sample points do
start = x2slice[0], yslice[0]
end = x2slice[-1], yslice[-1]
Y[0] = start
Y[N + 1] = end
Y[1:N + 1, 0] = x1slice
Y[1:N + 1, 1] = yslice
Y[N + 2:, 0] = x2slice[::-1]
Y[N + 2:, 1] = yslice[::-1]
polys.append(Y)
collection = mcoll.PolyCollection(polys, **kwargs)
# now update the datalim and autoscale
X1Y = np.array([x1[where], y[where]]).T
X2Y = np.array([x2[where], y[where]]).T
self.dataLim.update_from_data_xy(X1Y, self.ignore_existing_data_limits,
updatex=True, updatey=True)
self.ignore_existing_data_limits = False
self.dataLim.update_from_data_xy(X2Y, self.ignore_existing_data_limits,
updatex=True, updatey=False)
self.add_collection(collection, autolim=False)
self.autoscale_view()
return collection
#### plotting z(x,y): imshow, pcolor and relatives, contour
@_preprocess_data(label_namer=None)
def imshow(self, X, cmap=None, norm=None, aspect=None,
interpolation=None, alpha=None, vmin=None, vmax=None,
origin=None, extent=None, shape=None, filternorm=1,
filterrad=4.0, imlim=None, resample=None, url=None, **kwargs):
"""
Display an image on the axes.
Parameters
----------
X : array_like, shape (n, m) or (n, m, 3) or (n, m, 4)
Display the image in `X` to current axes. `X` may be an
array or a PIL image. If `X` is an array, it
can have the following shapes and types:
- MxN -- values to be mapped (float or int)
- MxNx3 -- RGB (float or uint8)
- MxNx4 -- RGBA (float or uint8)
MxN arrays are mapped to colors based on the `norm` (mapping
scalar to scalar) and the `cmap` (mapping the normed scalar to
a color).
Elements of RGB and RGBA arrays represent pixels of an MxN image.
All values should be in the range [0 .. 1] for floats or
[0 .. 255] for integers. Out-of-range values will be clipped to
these bounds.
cmap : `~matplotlib.colors.Colormap`, optional, default: None
If None, default to rc `image.cmap` value. `cmap` is ignored
if `X` is 3-D, directly specifying RGB(A) values.
aspect : ['auto' | 'equal' | scalar], optional, default: None
If 'auto', changes the image aspect ratio to match that of the
axes.
If 'equal', and `extent` is None, changes the axes aspect ratio to
match that of the image. If `extent` is not `None`, the axes
aspect ratio is changed to match that of the extent.
If None, default to rc ``image.aspect`` value.
interpolation : string, optional, default: None
Acceptable values are 'none', 'nearest', 'bilinear', 'bicubic',
'spline16', 'spline36', 'hanning', 'hamming', 'hermite', 'kaiser',
'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell', 'sinc',
'lanczos'
If `interpolation` is None, default to rc `image.interpolation`.
See also the `filternorm` and `filterrad` parameters.
If `interpolation` is 'none', then no interpolation is performed
on the Agg, ps and pdf backends. Other backends will fall back to
'nearest'.
norm : `~matplotlib.colors.Normalize`, optional, default: None
A `~matplotlib.colors.Normalize` instance is used to scale
a 2-D float `X` input to the (0, 1) range for input to the
`cmap`. If `norm` is None, use the default func:`normalize`.
If `norm` is an instance of `~matplotlib.colors.NoNorm`,
`X` must be an array of integers that index directly into
the lookup table of the `cmap`.
vmin, vmax : scalar, optional, default: None
`vmin` and `vmax` are used in conjunction with norm to normalize
luminance data. Note if you pass a `norm` instance, your
settings for `vmin` and `vmax` will be ignored.
alpha : scalar, optional, default: None
The alpha blending value, between 0 (transparent) and 1 (opaque).
The ``alpha`` argument is ignored for RGBA input data.
origin : ['upper' | 'lower'], optional, default: None
Place the [0,0] index of the array in the upper left or lower left
corner of the axes. If None, default to rc `image.origin`.
extent : scalars (left, right, bottom, top), optional, default: None
The location, in data-coordinates, of the lower-left and
upper-right corners. If `None`, the image is positioned such that
the pixel centers fall on zero-based (row, column) indices.
shape : scalars (columns, rows), optional, default: None
For raw buffer images
filternorm : scalar, optional, default: 1
A parameter for the antigrain image resize filter. From the
antigrain documentation, if `filternorm` = 1, the filter
normalizes integer values and corrects the rounding errors. It
doesn't do anything with the source floating point values, it
corrects only integers according to the rule of 1.0 which means
that any sum of pixel weights must be equal to 1.0. So, the
filter function must produce a graph of the proper shape.
filterrad : scalar, optional, default: 4.0
The filter radius for filters that have a radius parameter, i.e.
when interpolation is one of: 'sinc', 'lanczos' or 'blackman'
Returns
-------
image : `~matplotlib.image.AxesImage`
Other Parameters
----------------
**kwargs : `~matplotlib.artist.Artist` properties.
See also
--------
matshow : Plot a matrix or an array as an image.
Notes
-----
Unless *extent* is used, pixel centers will be located at integer
coordinates. In other words: the origin will coincide with the center
of pixel (0, 0).
Two typical representations are used for RGB images with an alpha
channel:
- Straight (unassociated) alpha: R, G, and B channels represent the
color of the pixel, disregarding its opacity.
- Premultiplied (associated) alpha: R, G, and B channels represent
the color of the pixel, adjusted for its opacity by multiplication.
`~matplotlib.pyplot.imshow` expects RGB images adopting the straight
(unassociated) alpha representation.
"""
if not self._hold:
self.cla()
if norm is not None and not isinstance(norm, mcolors.Normalize):
raise ValueError(
"'norm' must be an instance of 'mcolors.Normalize'")
if aspect is None:
aspect = rcParams['image.aspect']
self.set_aspect(aspect)
im = mimage.AxesImage(self, cmap, norm, interpolation, origin, extent,
filternorm=filternorm, filterrad=filterrad,
resample=resample, **kwargs)
im.set_data(X)
im.set_alpha(alpha)
if im.get_clip_path() is None:
# image does not already have clipping set, clip to axes patch
im.set_clip_path(self.patch)
#if norm is None and shape is None:
# im.set_clim(vmin, vmax)
if vmin is not None or vmax is not None:
im.set_clim(vmin, vmax)
else:
im.autoscale_None()
im.set_url(url)
# update ax.dataLim, and, if autoscaling, set viewLim
# to tightly fit the image, regardless of dataLim.
im.set_extent(im.get_extent())
self.add_image(im)
return im
@staticmethod
def _pcolorargs(funcname, *args, **kw):
# This takes one kwarg, allmatch.
# If allmatch is True, then the incoming X, Y, C must
# have matching dimensions, taking into account that
# X and Y can be 1-D rather than 2-D. This perfect
# match is required for Gouroud shading. For flat
# shading, X and Y specify boundaries, so we need
# one more boundary than color in each direction.
# For convenience, and consistent with Matlab, we
# discard the last row and/or column of C if necessary
# to meet this condition. This is done if allmatch
# is False.
allmatch = kw.pop("allmatch", False)
if len(args) == 1:
C = np.asanyarray(args[0])
numRows, numCols = C.shape
if allmatch:
X, Y = np.meshgrid(np.arange(numCols), np.arange(numRows))
else:
X, Y = np.meshgrid(np.arange(numCols + 1),
np.arange(numRows + 1))
C = cbook.safe_masked_invalid(C)
return X, Y, C
if len(args) == 3:
# Check x and y for bad data...
C = np.asanyarray(args[2])
X, Y = [cbook.safe_masked_invalid(a) for a in args[:2]]
if funcname == 'pcolormesh':
if np.ma.is_masked(X) or np.ma.is_masked(Y):
raise ValueError(
'x and y arguments to pcolormesh cannot have '
'non-finite values or be of type '
'numpy.ma.core.MaskedArray with masked values')
# safe_masked_invalid() returns an ndarray for dtypes other
# than floating point.
if isinstance(X, np.ma.core.MaskedArray):
X = X.data # strip mask as downstream doesn't like it...
if isinstance(Y, np.ma.core.MaskedArray):
Y = Y.data
numRows, numCols = C.shape
else:
raise TypeError(
'Illegal arguments to %s; see help(%s)' % (funcname, funcname))
Nx = X.shape[-1]
Ny = Y.shape[0]
if X.ndim != 2 or X.shape[0] == 1:
x = X.reshape(1, Nx)
X = x.repeat(Ny, axis=0)
if Y.ndim != 2 or Y.shape[1] == 1:
y = Y.reshape(Ny, 1)
Y = y.repeat(Nx, axis=1)
if X.shape != Y.shape:
raise TypeError(
'Incompatible X, Y inputs to %s; see help(%s)' % (
funcname, funcname))
if allmatch:
if not (Nx == numCols and Ny == numRows):
raise TypeError('Dimensions of C %s are incompatible with'
' X (%d) and/or Y (%d); see help(%s)' % (
C.shape, Nx, Ny, funcname))
else:
if not (numCols in (Nx, Nx - 1) and numRows in (Ny, Ny - 1)):
raise TypeError('Dimensions of C %s are incompatible with'
' X (%d) and/or Y (%d); see help(%s)' % (
C.shape, Nx, Ny, funcname))
C = C[:Ny - 1, :Nx - 1]
C = cbook.safe_masked_invalid(C)
return X, Y, C
@_preprocess_data(label_namer=None)
@docstring.dedent_interpd
def pcolor(self, *args, **kwargs):
"""
Create a pseudocolor plot of a 2-D array.
Call signatures::
pcolor(C, **kwargs)
pcolor(X, Y, C, **kwargs)
pcolor can be very slow for large arrays; consider
using the similar but much faster
:func:`~matplotlib.pyplot.pcolormesh` instead.
Parameters
----------
C : array_like
An array of color values.
X, Y : array_like, optional
If given, specify the (x, y) coordinates of the colored
quadrilaterals; the quadrilateral for ``C[i,j]`` has corners at::
(X[i, j], Y[i, j]),
(X[i, j+1], Y[i, j+1]),
(X[i+1, j], Y[i+1, j]),
(X[i+1, j+1], Y[i+1, j+1])
Ideally the dimensions of ``X`` and ``Y`` should be one greater
than those of ``C``; if the dimensions are the same, then the last
row and column of ``C`` will be ignored.
Note that the column index corresponds to the
x-coordinate, and the row index corresponds to y; for
details, see the :ref:`Grid Orientation
<axes-pcolor-grid-orientation>` section below.
If either or both of ``X`` and ``Y`` are 1-D arrays or column
vectors, they will be expanded as needed into the appropriate 2-D
arrays, making a rectangular grid.
cmap : `~matplotlib.colors.Colormap`, optional, default: None
If `None`, default to rc settings.
norm : `matplotlib.colors.Normalize`, optional, default: None
An instance is used to scale luminance data to (0, 1).
If `None`, defaults to :func:`normalize`.
vmin, vmax : scalar, optional, default: None
``vmin`` and ``vmax`` are used in conjunction with ``norm`` to
normalize luminance data. If either is `None`, it is autoscaled to
the respective min or max of the color array ``C``. If not `None`,
``vmin`` or ``vmax`` passed in here override any pre-existing
values supplied in the ``norm`` instance.
edgecolors : {None, 'none', color, color sequence}
If None, the rc setting is used by default.
If 'none', edges will not be visible.
An mpl color or sequence of colors will set the edge color.
alpha : scalar, optional, default: None
The alpha blending value, between 0 (transparent) and 1 (opaque).
snap : bool, optional, default: False
Whether to snap the mesh to pixel boundaries.
Returns
-------
collection : `matplotlib.collections.Collection`
Other Parameters
----------------
antialiaseds : bool, optional, default: False
The default ``antialiaseds`` is False if the default
``edgecolors="none"`` is used. This eliminates artificial lines
at patch boundaries, and works regardless of the value of alpha.
If ``edgecolors`` is not "none", then the default ``antialiaseds``
is taken from :rc:`patch.antialiased`, which defaults to True.
Stroking the edges may be preferred if ``alpha`` is 1, but will
cause artifacts otherwise.
**kwargs :
Any unused keyword arguments are passed along to the
`~matplotlib.collections.PolyCollection` constructor:
%(PolyCollection)s
See Also
--------
pcolormesh : for an explanation of the differences between
pcolor and pcolormesh.
Notes
-----
.. _axes-pcolor-grid-orientation:
``X``, ``Y`` and ``C`` may be masked arrays. If either C[i, j], or one
of the vertices surrounding C[i,j] (``X`` or ``Y`` at [i, j], [i+1, j],
[i, j+1], [i+1, j+1]) is masked, nothing is plotted.
The grid orientation follows the MATLAB convention: an array ``C`` with
shape (nrows, ncolumns) is plotted with the column number as ``X`` and
the row number as ``Y``, increasing up; hence it is plotted the way the
array would be printed, except that the ``Y`` axis is reversed. That
is, ``C`` is taken as ``C`` (y, x).
Similarly for :func:`meshgrid`::
x = np.arange(5)
y = np.arange(3)
X, Y = np.meshgrid(x, y)
is equivalent to::
X = array([[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]])
Y = array([[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1],
[2, 2, 2, 2, 2]])
so if you have::
C = rand(len(x), len(y))
then you need to transpose C::
pcolor(X, Y, C.T)
or::
pcolor(C.T)
MATLAB :func:`pcolor` always discards the last row and column of ``C``,
but Matplotlib displays the last row and column if ``X`` and ``Y`` are
not specified, or if ``X`` and ``Y`` have one more row and column than
``C``.
"""
if not self._hold:
self.cla()
alpha = kwargs.pop('alpha', None)
norm = kwargs.pop('norm', None)
cmap = kwargs.pop('cmap', None)
vmin = kwargs.pop('vmin', None)
vmax = kwargs.pop('vmax', None)
X, Y, C = self._pcolorargs('pcolor', *args, allmatch=False)
Ny, Nx = X.shape
# unit conversion allows e.g. datetime objects as axis values
self._process_unit_info(xdata=X, ydata=Y, kwargs=kwargs)
X = self.convert_xunits(X)
Y = self.convert_yunits(Y)
# convert to MA, if necessary.
C = ma.asarray(C)
X = ma.asarray(X)
Y = ma.asarray(Y)
mask = ma.getmaskarray(X) + ma.getmaskarray(Y)
xymask = (mask[0:-1, 0:-1] + mask[1:, 1:] +
mask[0:-1, 1:] + mask[1:, 0:-1])
# don't plot if C or any of the surrounding vertices are masked.
mask = ma.getmaskarray(C) + xymask
newaxis = np.newaxis
compress = np.compress
ravelmask = (mask == 0).ravel()
X1 = compress(ravelmask, ma.filled(X[0:-1, 0:-1]).ravel())
Y1 = compress(ravelmask, ma.filled(Y[0:-1, 0:-1]).ravel())
X2 = compress(ravelmask, ma.filled(X[1:, 0:-1]).ravel())
Y2 = compress(ravelmask, ma.filled(Y[1:, 0:-1]).ravel())
X3 = compress(ravelmask, ma.filled(X[1:, 1:]).ravel())
Y3 = compress(ravelmask, ma.filled(Y[1:, 1:]).ravel())
X4 = compress(ravelmask, ma.filled(X[0:-1, 1:]).ravel())
Y4 = compress(ravelmask, ma.filled(Y[0:-1, 1:]).ravel())
npoly = len(X1)
xy = np.concatenate((X1[:, newaxis], Y1[:, newaxis],
X2[:, newaxis], Y2[:, newaxis],
X3[:, newaxis], Y3[:, newaxis],
X4[:, newaxis], Y4[:, newaxis],
X1[:, newaxis], Y1[:, newaxis]),
axis=1)
verts = xy.reshape((npoly, 5, 2))
C = compress(ravelmask, ma.filled(C[0:Ny - 1, 0:Nx - 1]).ravel())
linewidths = (0.25,)
if 'linewidth' in kwargs:
kwargs['linewidths'] = kwargs.pop('linewidth')
kwargs.setdefault('linewidths', linewidths)
if 'edgecolor' in kwargs:
kwargs['edgecolors'] = kwargs.pop('edgecolor')
ec = kwargs.setdefault('edgecolors', 'none')
# aa setting will default via collections to patch.antialiased
# unless the boundary is not stroked, in which case the
# default will be False; with unstroked boundaries, aa
# makes artifacts that are often disturbing.
if 'antialiased' in kwargs:
kwargs['antialiaseds'] = kwargs.pop('antialiased')
if 'antialiaseds' not in kwargs and (
isinstance(ec, six.string_types) and ec.lower() == "none"):
kwargs['antialiaseds'] = False
kwargs.setdefault('snap', False)
collection = mcoll.PolyCollection(verts, **kwargs)
collection.set_alpha(alpha)
collection.set_array(C)
if norm is not None and not isinstance(norm, mcolors.Normalize):
raise ValueError(
"'norm' must be an instance of 'mcolors.Normalize'")
collection.set_cmap(cmap)
collection.set_norm(norm)
collection.set_clim(vmin, vmax)
collection.autoscale_None()
self.grid(False)
x = X.compressed()
y = Y.compressed()
# Transform from native to data coordinates?
t = collection._transform
if (not isinstance(t, mtransforms.Transform) and
hasattr(t, '_as_mpl_transform')):
t = t._as_mpl_transform(self.axes)
if t and any(t.contains_branch_seperately(self.transData)):
trans_to_data = t - self.transData
pts = np.vstack([x, y]).T.astype(float)
transformed_pts = trans_to_data.transform(pts)
x = transformed_pts[..., 0]
y = transformed_pts[..., 1]
self.add_collection(collection, autolim=False)
minx = np.min(x)
maxx = np.max(x)
miny = np.min(y)
maxy = np.max(y)
collection.sticky_edges.x[:] = [minx, maxx]
collection.sticky_edges.y[:] = [miny, maxy]
corners = (minx, miny), (maxx, maxy)
self.update_datalim(corners)
self.autoscale_view()
return collection
@_preprocess_data(label_namer=None)
@docstring.dedent_interpd
def pcolormesh(self, *args, **kwargs):
"""
Plot a quadrilateral mesh.
Call signatures::
pcolormesh(C)
pcolormesh(X, Y, C)
pcolormesh(C, **kwargs)
Create a pseudocolor plot of a 2-D array.
pcolormesh is similar to :func:`~matplotlib.pyplot.pcolor`,
but uses a different mechanism and returns a different
object; pcolor returns a
:class:`~matplotlib.collections.PolyCollection` but pcolormesh
returns a
:class:`~matplotlib.collections.QuadMesh`. It is much faster,
so it is almost always preferred for large arrays.
*C* may be a masked array, but *X* and *Y* may not. Masked
array support is implemented via *cmap* and *norm*; in
contrast, :func:`~matplotlib.pyplot.pcolor` simply does not
draw quadrilaterals with masked colors or vertices.
Other Parameters
----------------
cmap : Colormap, optional
A :class:`matplotlib.colors.Colormap` instance. If ``None``, use
rc settings.
norm : Normalize, optional
A :class:`matplotlib.colors.Normalize` instance is used to
scale luminance data to 0,1. If ``None``, defaults to
:func:`normalize`.
vmin, vmax : scalar, optional
*vmin* and *vmax* are used in conjunction with *norm* to
normalize luminance data. If either is ``None``, it is autoscaled
to the respective min or max of the color array *C*.
If not ``None``, *vmin* or *vmax* passed in here override any
pre-existing values supplied in the *norm* instance.
shading : [ 'flat' | 'gouraud' ], optional
'flat' indicates a solid color for each quad. When
'gouraud', each quad will be Gouraud shaded. When gouraud
shading, *edgecolors* is ignored.
edgecolors : string, color, color sequence, optional
- If ``None``, the rc setting is used by default.
- If ``'None'``, edges will not be visible.
- If ``'face'``, edges will have the same color as the faces.
An mpl color or sequence of colors will also set the edge color.
alpha : scalar, optional
Alpha blending value. Must be between 0 and 1.
Returns
-------
matplotlib.collections.QuadMesh
See Also
--------
matplotlib.pyplot.pcolor :
For an explanation of the grid orientation
(:ref:`Grid Orientation <axes-pcolor-grid-orientation>`)
and the expansion of 1-D *X* and/or *Y* to 2-D arrays.
Notes
-----
kwargs can be used to control the
:class:`matplotlib.collections.QuadMesh` properties:
%(QuadMesh)s
"""
if not self._hold:
self.cla()
alpha = kwargs.pop('alpha', None)
norm = kwargs.pop('norm', None)
cmap = kwargs.pop('cmap', None)
vmin = kwargs.pop('vmin', None)
vmax = kwargs.pop('vmax', None)
shading = kwargs.pop('shading', 'flat').lower()
antialiased = kwargs.pop('antialiased', False)
kwargs.setdefault('edgecolors', 'None')
allmatch = (shading == 'gouraud')
X, Y, C = self._pcolorargs('pcolormesh', *args, allmatch=allmatch)
Ny, Nx = X.shape
X = X.ravel()
Y = Y.ravel()
# unit conversion allows e.g. datetime objects as axis values
self._process_unit_info(xdata=X, ydata=Y, kwargs=kwargs)
X = self.convert_xunits(X)
Y = self.convert_yunits(Y)
# convert to one dimensional arrays
C = C.ravel()
coords = np.column_stack((X, Y)).astype(float, copy=False)
collection = mcoll.QuadMesh(Nx - 1, Ny - 1, coords,
antialiased=antialiased, shading=shading,
**kwargs)
collection.set_alpha(alpha)
collection.set_array(C)
if norm is not None and not isinstance(norm, mcolors.Normalize):
raise ValueError(
"'norm' must be an instance of 'mcolors.Normalize'")
collection.set_cmap(cmap)
collection.set_norm(norm)
collection.set_clim(vmin, vmax)
collection.autoscale_None()
self.grid(False)
# Transform from native to data coordinates?
t = collection._transform
if (not isinstance(t, mtransforms.Transform) and
hasattr(t, '_as_mpl_transform')):
t = t._as_mpl_transform(self.axes)
if t and any(t.contains_branch_seperately(self.transData)):
trans_to_data = t - self.transData
coords = trans_to_data.transform(coords)
self.add_collection(collection, autolim=False)
minx, miny = np.min(coords, axis=0)
maxx, maxy = np.max(coords, axis=0)
collection.sticky_edges.x[:] = [minx, maxx]
collection.sticky_edges.y[:] = [miny, maxy]
corners = (minx, miny), (maxx, maxy)
self.update_datalim(corners)
self.autoscale_view()
return collection
@_preprocess_data(label_namer=None)
@docstring.dedent_interpd
def pcolorfast(self, *args, **kwargs):
"""
pseudocolor plot of a 2-D array
Experimental; this is a pcolor-type method that
provides the fastest possible rendering with the Agg
backend, and that can handle any quadrilateral grid.
It supports only flat shading (no outlines), it lacks
support for log scaling of the axes, and it does not
have a pyplot wrapper.
Call signatures::
ax.pcolorfast(C, **kwargs)
ax.pcolorfast(xr, yr, C, **kwargs)
ax.pcolorfast(x, y, C, **kwargs)
ax.pcolorfast(X, Y, C, **kwargs)
C is the 2D array of color values corresponding to quadrilateral
cells. Let (nr, nc) be its shape. C may be a masked array.
``ax.pcolorfast(C, **kwargs)`` is equivalent to
``ax.pcolorfast([0,nc], [0,nr], C, **kwargs)``
*xr*, *yr* specify the ranges of *x* and *y* corresponding to the
rectangular region bounding *C*. If::
xr = [x0, x1]
and::
yr = [y0,y1]
then *x* goes from *x0* to *x1* as the second index of *C* goes
from 0 to *nc*, etc. (*x0*, *y0*) is the outermost corner of
cell (0,0), and (*x1*, *y1*) is the outermost corner of cell
(*nr*-1, *nc*-1). All cells are rectangles of the same size.
This is the fastest version.
*x*, *y* are monotonic 1D arrays of length *nc* +1 and *nr* +1,
respectively, giving the x and y boundaries of the cells. Hence
the cells are rectangular but the grid may be nonuniform. The
speed is intermediate. (The grid is checked, and if found to be
uniform the fast version is used.)
*X* and *Y* are 2D arrays with shape (*nr* +1, *nc* +1) that specify
the (x,y) coordinates of the corners of the colored
quadrilaterals; the quadrilateral for C[i,j] has corners at
(X[i,j],Y[i,j]), (X[i,j+1],Y[i,j+1]), (X[i+1,j],Y[i+1,j]),
(X[i+1,j+1],Y[i+1,j+1]). The cells need not be rectangular.
This is the most general, but the slowest to render. It may
produce faster and more compact output using ps, pdf, and
svg backends, however.
Note that the column index corresponds to the x-coordinate,
and the row index corresponds to y; for details, see
:ref:`Grid Orientation <axes-pcolor-grid-orientation>`.
Optional keyword arguments:
*cmap*: [ *None* | Colormap ]
A :class:`matplotlib.colors.Colormap` instance from cm. If *None*,
use rc settings.
*norm*: [ *None* | Normalize ]
A :class:`matplotlib.colors.Normalize` instance is used to scale
luminance data to 0,1. If *None*, defaults to normalize()
*vmin*/*vmax*: [ *None* | scalar ]
*vmin* and *vmax* are used in conjunction with norm to normalize
luminance data. If either are *None*, the min and max
of the color array *C* is used. If you pass a norm instance,
*vmin* and *vmax* will be *None*.
*alpha*: ``0 <= scalar <= 1`` or *None*
the alpha blending value
Return value is an image if a regular or rectangular grid
is specified, and a :class:`~matplotlib.collections.QuadMesh`
collection in the general quadrilateral case.
"""
if not self._hold:
self.cla()
alpha = kwargs.pop('alpha', None)
norm = kwargs.pop('norm', None)
cmap = kwargs.pop('cmap', None)
vmin = kwargs.pop('vmin', None)
vmax = kwargs.pop('vmax', None)
if norm is not None and not isinstance(norm, mcolors.Normalize):
raise ValueError(
"'norm' must be an instance of 'mcolors.Normalize'")
C = args[-1]
nr, nc = C.shape
if len(args) == 1:
style = "image"
x = [0, nc]
y = [0, nr]
elif len(args) == 3:
x, y = args[:2]
x = np.asarray(x)
y = np.asarray(y)
if x.ndim == 1 and y.ndim == 1:
if x.size == 2 and y.size == 2:
style = "image"
else:
dx = np.diff(x)
dy = np.diff(y)
if (np.ptp(dx) < 0.01 * np.abs(dx.mean()) and
np.ptp(dy) < 0.01 * np.abs(dy.mean())):
style = "image"
else:
style = "pcolorimage"
elif x.ndim == 2 and y.ndim == 2:
style = "quadmesh"
else:
raise TypeError("arguments do not match valid signatures")
else:
raise TypeError("need 1 argument or 3 arguments")
if style == "quadmesh":
# convert to one dimensional arrays
# This should also be moved to the QuadMesh class
# data point in each cell is value at lower left corner
C = ma.ravel(C)
X = x.ravel()
Y = y.ravel()
Nx = nc + 1
Ny = nr + 1
# The following needs to be cleaned up; the renderer
# requires separate contiguous arrays for X and Y,
# but the QuadMesh class requires the 2D array.
coords = np.empty(((Nx * Ny), 2), np.float64)
coords[:, 0] = X
coords[:, 1] = Y
# The QuadMesh class can also be changed to
# handle relevant superclass kwargs; the initializer
# should do much more than it does now.
collection = mcoll.QuadMesh(nc, nr, coords, 0, edgecolors="None")
collection.set_alpha(alpha)
collection.set_array(C)
collection.set_cmap(cmap)
collection.set_norm(norm)
self.add_collection(collection, autolim=False)
xl, xr, yb, yt = X.min(), X.max(), Y.min(), Y.max()
ret = collection
else: # It's one of the two image styles.
xl, xr, yb, yt = x[0], x[-1], y[0], y[-1]
if style == "image":
im = mimage.AxesImage(self, cmap, norm,
interpolation='nearest',
origin='lower',
extent=(xl, xr, yb, yt),
**kwargs)
im.set_data(C)
im.set_alpha(alpha)
elif style == "pcolorimage":
im = mimage.PcolorImage(self, x, y, C,
cmap=cmap,
norm=norm,
alpha=alpha,
**kwargs)
im.set_extent((xl, xr, yb, yt))
self.add_image(im)
ret = im
if vmin is not None or vmax is not None:
ret.set_clim(vmin, vmax)
else:
ret.autoscale_None()
ret.sticky_edges.x[:] = [xl, xr]
ret.sticky_edges.y[:] = [yb, yt]
self.update_datalim(np.array([[xl, yb], [xr, yt]]))
self.autoscale_view(tight=True)
return ret
@_preprocess_data()
def contour(self, *args, **kwargs):
if not self._hold:
self.cla()
kwargs['filled'] = False
contours = mcontour.QuadContourSet(self, *args, **kwargs)
self.autoscale_view()
return contours
contour.__doc__ = mcontour.QuadContourSet._contour_doc
@_preprocess_data()
def contourf(self, *args, **kwargs):
if not self._hold:
self.cla()
kwargs['filled'] = True
contours = mcontour.QuadContourSet(self, *args, **kwargs)
self.autoscale_view()
return contours
contourf.__doc__ = mcontour.QuadContourSet._contour_doc
def clabel(self, CS, *args, **kwargs):
return CS.clabel(*args, **kwargs)
clabel.__doc__ = mcontour.ContourSet.clabel.__doc__
@docstring.dedent_interpd
def table(self, **kwargs):
"""
Add a table to the current axes.
Call signature::
table(cellText=None, cellColours=None,
cellLoc='right', colWidths=None,
rowLabels=None, rowColours=None, rowLoc='left',
colLabels=None, colColours=None, colLoc='center',
loc='bottom', bbox=None)
Returns a :class:`matplotlib.table.Table` instance. Either `cellText`
or `cellColours` must be provided. For finer grained control over
tables, use the :class:`~matplotlib.table.Table` class and add it to
the axes with :meth:`~matplotlib.axes.Axes.add_table`.
Thanks to John Gill for providing the class and table.
kwargs control the :class:`~matplotlib.table.Table`
properties:
%(Table)s
"""
return mtable.table(self, **kwargs)
#### Data analysis
@_preprocess_data(replace_names=["x", 'weights'], label_namer="x")
def hist(self, x, bins=None, range=None, density=None, weights=None,
cumulative=False, bottom=None, histtype='bar', align='mid',
orientation='vertical', rwidth=None, log=False,
color=None, label=None, stacked=False, normed=None,
**kwargs):
"""
Plot a histogram.
Compute and draw the histogram of *x*. The return value is a
tuple (*n*, *bins*, *patches*) or ([*n0*, *n1*, ...], *bins*,
[*patches0*, *patches1*,...]) if the input contains multiple
data.
Multiple data can be provided via *x* as a list of datasets
of potentially different length ([*x0*, *x1*, ...]), or as
a 2-D ndarray in which each column is a dataset. Note that
the ndarray form is transposed relative to the list form.
Masked arrays are not supported at present.
Parameters
----------
x : (n,) array or sequence of (n,) arrays
Input values, this takes either a single array or a sequence of
arrays which are not required to be of the same length
bins : integer or sequence or 'auto', optional
If an integer is given, ``bins + 1`` bin edges are calculated and
returned, consistent with :func:`numpy.histogram`.
If `bins` is a sequence, gives bin edges, including left edge of
first bin and right edge of last bin. In this case, `bins` is
returned unmodified.
All but the last (righthand-most) bin is half-open. In other
words, if `bins` is::
[1, 2, 3, 4]
then the first bin is ``[1, 2)`` (including 1, but excluding 2) and
the second ``[2, 3)``. The last bin, however, is ``[3, 4]``, which
*includes* 4.
Unequally spaced bins are supported if *bins* is a sequence.
If Numpy 1.11 is installed, may also be ``'auto'``.
Default is taken from the rcParam ``hist.bins``.
range : tuple or None, optional
The lower and upper range of the bins. Lower and upper outliers
are ignored. If not provided, *range* is ``(x.min(), x.max())``.
Range has no effect if *bins* is a sequence.
If *bins* is a sequence or *range* is specified, autoscaling
is based on the specified bin range instead of the
range of x.
Default is ``None``
density : boolean, optional
If ``True``, the first element of the return tuple will
be the counts normalized to form a probability density, i.e.,
the area (or integral) under the histogram will sum to 1.
This is achieved by dividing the count by the number of
observations times the bin width and not dividing by the total
number of observations. If *stacked* is also ``True``, the sum of
the histograms is normalized to 1.
Default is ``None`` for both *normed* and *density*. If either is
set, then that value will be used. If neither are set, then the
args will be treated as ``False``.
If both *density* and *normed* are set an error is raised.
weights : (n, ) array_like or None, optional
An array of weights, of the same shape as *x*. Each value in *x*
only contributes its associated weight towards the bin count
(instead of 1). If *normed* or *density* is ``True``,
the weights are normalized, so that the integral of the density
over the range remains 1.
Default is ``None``
cumulative : boolean, optional
If ``True``, then a histogram is computed where each bin gives the
counts in that bin plus all bins for smaller values. The last bin
gives the total number of datapoints. If *normed* or *density*
is also ``True`` then the histogram is normalized such that the
last bin equals 1. If *cumulative* evaluates to less than 0
(e.g., -1), the direction of accumulation is reversed.
In this case, if *normed* and/or *density* is also ``True``, then
the histogram is normalized such that the first bin equals 1.
Default is ``False``
bottom : array_like, scalar, or None
Location of the bottom baseline of each bin. If a scalar,
the base line for each bin is shifted by the same amount.
If an array, each bin is shifted independently and the length
of bottom must match the number of bins. If None, defaults to 0.
Default is ``None``
histtype : {'bar', 'barstacked', 'step', 'stepfilled'}, optional
The type of histogram to draw.
- 'bar' is a traditional bar-type histogram. If multiple data
are given the bars are arranged side by side.
- 'barstacked' is a bar-type histogram where multiple
data are stacked on top of each other.
- 'step' generates a lineplot that is by default
unfilled.
- 'stepfilled' generates a lineplot that is by default
filled.
Default is 'bar'
align : {'left', 'mid', 'right'}, optional
Controls how the histogram is plotted.
- 'left': bars are centered on the left bin edges.
- 'mid': bars are centered between the bin edges.
- 'right': bars are centered on the right bin edges.
Default is 'mid'
orientation : {'horizontal', 'vertical'}, optional
If 'horizontal', `~matplotlib.pyplot.barh` will be used for
bar-type histograms and the *bottom* kwarg will be the left edges.
rwidth : scalar or None, optional
The relative width of the bars as a fraction of the bin width. If
``None``, automatically compute the width.
Ignored if *histtype* is 'step' or 'stepfilled'.
Default is ``None``
log : boolean, optional
If ``True``, the histogram axis will be set to a log scale. If
*log* is ``True`` and *x* is a 1D array, empty bins will be
filtered out and only the non-empty ``(n, bins, patches)``
will be returned.
Default is ``False``
color : color or array_like of colors or None, optional
Color spec or sequence of color specs, one per dataset. Default
(``None``) uses the standard line color sequence.
Default is ``None``
label : string or None, optional
String, or sequence of strings to match multiple datasets. Bar
charts yield multiple patches per dataset, but only the first gets
the label, so that the legend command will work as expected.
default is ``None``
stacked : boolean, optional
If ``True``, multiple data are stacked on top of each other If
``False`` multiple data are arranged side by side if histtype is
'bar' or on top of each other if histtype is 'step'
Default is ``False``
normed : bool, optional
Deprecated; use the density keyword argument instead.
Returns
-------
n : array or list of arrays
The values of the histogram bins. See *normed* or *density*
and *weights* for a description of the possible semantics.
If input *x* is an array, then this is an array of length
*nbins*. If input is a sequence arrays
``[data1, data2,..]``, then this is a list of arrays with
the values of the histograms for each of the arrays in the
same order.
bins : array
The edges of the bins. Length nbins + 1 (nbins left edges and right
edge of last bin). Always a single array even when multiple data
sets are passed in.
patches : list or list of lists
Silent list of individual patches used to create the histogram
or list of such list if multiple input datasets.
Other Parameters
----------------
**kwargs : `~matplotlib.patches.Patch` properties
See also
--------
hist2d : 2D histograms
Notes
-----
.. [Notes section required for data comment. See #10189.]
"""
# Avoid shadowing the builtin.
bin_range = range
del range
if not self._hold:
self.cla()
if np.isscalar(x):
x = [x]
if bins is None:
bins = rcParams['hist.bins']
# Validate string inputs here so we don't have to clutter
# subsequent code.
if histtype not in ['bar', 'barstacked', 'step', 'stepfilled']:
raise ValueError("histtype %s is not recognized" % histtype)
if align not in ['left', 'mid', 'right']:
raise ValueError("align kwarg %s is not recognized" % align)
if orientation not in ['horizontal', 'vertical']:
raise ValueError(
"orientation kwarg %s is not recognized" % orientation)
if histtype == 'barstacked' and not stacked:
stacked = True
if density is not None and normed is not None:
raise ValueError("kwargs 'density' and 'normed' cannot be used "
"simultaneously. "
"Please only use 'density', since 'normed'"
"is deprecated.")
if normed is not None:
warnings.warn("The 'normed' kwarg is deprecated, and has been "
"replaced by the 'density' kwarg.")
# basic input validation
input_empty = np.size(x) == 0
# Massage 'x' for processing.
if input_empty:
x = [np.array([])]
else:
x = cbook._reshape_2D(x, 'x')
nx = len(x) # number of datasets
# Process unit information
# Unit conversion is done individually on each dataset
self._process_unit_info(xdata=x[0], kwargs=kwargs)
x = [self.convert_xunits(xi) for xi in x]
if bin_range is not None:
bin_range = self.convert_xunits(bin_range)
# Check whether bins or range are given explicitly.
binsgiven = (cbook.iterable(bins) or bin_range is not None)
# We need to do to 'weights' what was done to 'x'
if weights is not None:
w = cbook._reshape_2D(weights, 'weights')
else:
w = [None] * nx
if len(w) != nx:
raise ValueError('weights should have the same shape as x')
for xi, wi in zip(x, w):
if wi is not None and len(wi) != len(xi):
raise ValueError(
'weights should have the same shape as x')
if color is None:
color = [self._get_lines.get_next_color() for i in xrange(nx)]
else:
color = mcolors.to_rgba_array(color)
if len(color) != nx:
raise ValueError("color kwarg must have one color per dataset")
# If bins are not specified either explicitly or via range,
# we need to figure out the range required for all datasets,
# and supply that to np.histogram.
if not binsgiven and not input_empty:
xmin = np.inf
xmax = -np.inf
for xi in x:
if len(xi) > 0:
xmin = min(xmin, xi.min())
xmax = max(xmax, xi.max())
bin_range = (xmin, xmax)
density = bool(density) or bool(normed)
if density and not stacked:
hist_kwargs = dict(range=bin_range, density=density)
else:
hist_kwargs = dict(range=bin_range)
# List to store all the top coordinates of the histograms
tops = []
mlast = None
# Loop through datasets
for i in xrange(nx):
# this will automatically overwrite bins,
# so that each histogram uses the same bins
m, bins = np.histogram(x[i], bins, weights=w[i], **hist_kwargs)
m = m.astype(float) # causes problems later if it's an int
if mlast is None:
mlast = np.zeros(len(bins)-1, m.dtype)
if stacked:
m += mlast
mlast[:] = m
tops.append(m)
# If a stacked density plot, normalize so the area of all the stacked
# histograms together is 1
if stacked and density:
db = np.diff(bins)
for m in tops:
m[:] = (m / db) / tops[-1].sum()
if cumulative:
slc = slice(None)
if cbook.is_numlike(cumulative) and cumulative < 0:
slc = slice(None, None, -1)
if density:
tops = [(m * np.diff(bins))[slc].cumsum()[slc] for m in tops]
else:
tops = [m[slc].cumsum()[slc] for m in tops]
patches = []
# Save autoscale state for later restoration; turn autoscaling
# off so we can do it all a single time at the end, instead
# of having it done by bar or fill and then having to be redone.
_saved_autoscalex = self.get_autoscalex_on()
_saved_autoscaley = self.get_autoscaley_on()
self.set_autoscalex_on(False)
self.set_autoscaley_on(False)
if histtype.startswith('bar'):
totwidth = np.diff(bins)
if rwidth is not None:
dr = np.clip(rwidth, 0, 1)
elif (len(tops) > 1 and
((not stacked) or rcParams['_internal.classic_mode'])):
dr = 0.8
else:
dr = 1.0
if histtype == 'bar' and not stacked:
width = dr * totwidth / nx
dw = width
boffset = -0.5 * dr * totwidth * (1 - 1 / nx)
elif histtype == 'barstacked' or stacked:
width = dr * totwidth
boffset, dw = 0.0, 0.0
if align == 'mid' or align == 'edge':
boffset += 0.5 * totwidth
elif align == 'right':
boffset += totwidth
if orientation == 'horizontal':
_barfunc = self.barh
bottom_kwarg = 'left'
else: # orientation == 'vertical'
_barfunc = self.bar
bottom_kwarg = 'bottom'
for m, c in zip(tops, color):
if bottom is None:
bottom = np.zeros(len(m))
if stacked:
height = m - bottom
else:
height = m
patch = _barfunc(bins[:-1]+boffset, height, width,
align='center', log=log,
color=c, **{bottom_kwarg: bottom})
patches.append(patch)
if stacked:
bottom[:] = m
boffset += dw
elif histtype.startswith('step'):
# these define the perimeter of the polygon
x = np.zeros(4 * len(bins) - 3)
y = np.zeros(4 * len(bins) - 3)
x[0:2*len(bins)-1:2], x[1:2*len(bins)-1:2] = bins, bins[:-1]
x[2*len(bins)-1:] = x[1:2*len(bins)-1][::-1]
if bottom is None:
bottom = np.zeros(len(bins) - 1)
y[1:2*len(bins)-1:2], y[2:2*len(bins):2] = bottom, bottom
y[2*len(bins)-1:] = y[1:2*len(bins)-1][::-1]
if log:
if orientation == 'horizontal':
self.set_xscale('log', nonposx='clip')
logbase = self.xaxis._scale.base
else: # orientation == 'vertical'
self.set_yscale('log', nonposy='clip')
logbase = self.yaxis._scale.base
# Setting a minimum of 0 results in problems for log plots
if np.min(bottom) > 0:
minimum = np.min(bottom)
elif density or weights is not None:
# For data that is normed to form a probability density,
# set to minimum data value / logbase
# (gives 1 full tick-label unit for the lowest filled bin)
ndata = np.array(tops)
minimum = (np.min(ndata[ndata > 0])) / logbase
else:
# For non-normed (density = False) data,
# set the min to 1 / log base,
# again so that there is 1 full tick-label unit
# for the lowest bin
minimum = 1.0 / logbase
y[0], y[-1] = minimum, minimum
else:
minimum = 0
if align == 'left' or align == 'center':
x -= 0.5*(bins[1]-bins[0])
elif align == 'right':
x += 0.5*(bins[1]-bins[0])
# If fill kwarg is set, it will be passed to the patch collection,
# overriding this
fill = (histtype == 'stepfilled')
xvals, yvals = [], []
for m in tops:
if stacked:
# starting point for drawing polygon
y[0] = y[1]
# top of the previous polygon becomes the bottom
y[2*len(bins)-1:] = y[1:2*len(bins)-1][::-1]
# set the top of this polygon
y[1:2*len(bins)-1:2], y[2:2*len(bins):2] = (m + bottom,
m + bottom)
if log:
y[y < minimum] = minimum
if orientation == 'horizontal':
xvals.append(y.copy())
yvals.append(x.copy())
else:
xvals.append(x.copy())
yvals.append(y.copy())
# stepfill is closed, step is not
split = -1 if fill else 2 * len(bins)
# add patches in reverse order so that when stacking,
# items lower in the stack are plotted on top of
# items higher in the stack
for x, y, c in reversed(list(zip(xvals, yvals, color))):
patches.append(self.fill(
x[:split], y[:split],
closed=True if fill else None,
facecolor=c,
edgecolor=None if fill else c,
fill=fill if fill else None))
for patch_list in patches:
for patch in patch_list:
if orientation == 'vertical':
patch.sticky_edges.y.append(minimum)
elif orientation == 'horizontal':
patch.sticky_edges.x.append(minimum)
# we return patches, so put it back in the expected order
patches.reverse()
self.set_autoscalex_on(_saved_autoscalex)
self.set_autoscaley_on(_saved_autoscaley)
self.autoscale_view()
if label is None:
labels = [None]
elif isinstance(label, six.string_types):
labels = [label]
else:
labels = [six.text_type(lab) for lab in label]
for patch, lbl in zip_longest(patches, labels, fillvalue=None):
if patch:
p = patch[0]
p.update(kwargs)
if lbl is not None:
p.set_label(lbl)
for p in patch[1:]:
p.update(kwargs)
p.set_label('_nolegend_')
if nx == 1:
return tops[0], bins, cbook.silent_list('Patch', patches[0])
else:
return tops, bins, cbook.silent_list('Lists of Patches', patches)
@_preprocess_data(replace_names=["x", "y", "weights"], label_namer=None)
def hist2d(self, x, y, bins=10, range=None, normed=False, weights=None,
cmin=None, cmax=None, **kwargs):
"""
Make a 2D histogram plot.
Parameters
----------
x, y: array_like, shape (n, )
Input values
bins: [None | int | [int, int] | array_like | [array, array]]
The bin specification:
- If int, the number of bins for the two dimensions
(nx=ny=bins).
- If [int, int], the number of bins in each dimension
(nx, ny = bins).
- If array_like, the bin edges for the two dimensions
(x_edges=y_edges=bins).
- If [array, array], the bin edges in each dimension
(x_edges, y_edges = bins).
The default value is 10.
range : array_like shape(2, 2), optional, default: None
The leftmost and rightmost edges of the bins along each dimension
(if not specified explicitly in the bins parameters): [[xmin,
xmax], [ymin, ymax]]. All values outside of this range will be
considered outliers and not tallied in the histogram.
normed : boolean, optional, default: False
Normalize histogram.
weights : array_like, shape (n, ), optional, default: None
An array of values w_i weighing each sample (x_i, y_i).
cmin : scalar, optional, default: None
All bins that has count less than cmin will not be displayed and
these count values in the return value count histogram will also
be set to nan upon return
cmax : scalar, optional, default: None
All bins that has count more than cmax will not be displayed (set
to none before passing to imshow) and these count values in the
return value count histogram will also be set to nan upon return
Returns
-------
h : 2D array
The bi-dimensional histogram of samples x and y. Values in x are
histogrammed along the first dimension and values in y are
histogrammed along the second dimension.
xedges : 1D array
The bin edges along the x axis.
yedges : 1D array
The bin edges along the y axis.
image : AxesImage
Other Parameters
----------------
cmap : {Colormap, string}, optional
A :class:`matplotlib.colors.Colormap` instance. If not set, use rc
settings.
norm : Normalize, optional
A :class:`matplotlib.colors.Normalize` instance is used to
scale luminance data to ``[0, 1]``. If not set, defaults to
``Normalize()``.
vmin/vmax : {None, scalar}, optional
Arguments passed to the `Normalize` instance.
alpha : ``0 <= scalar <= 1`` or ``None``, optional
The alpha blending value.
See also
--------
hist : 1D histogram
Notes
-----
Rendering the histogram with a logarithmic color scale is
accomplished by passing a :class:`colors.LogNorm` instance to
the *norm* keyword argument. Likewise, power-law normalization
(similar in effect to gamma correction) can be accomplished with
:class:`colors.PowerNorm`.
"""
h, xedges, yedges = np.histogram2d(x, y, bins=bins, range=range,
normed=normed, weights=weights)
if cmin is not None:
h[h < cmin] = None
if cmax is not None:
h[h > cmax] = None
pc = self.pcolorfast(xedges, yedges, h.T, **kwargs)
self.set_xlim(xedges[0], xedges[-1])
self.set_ylim(yedges[0], yedges[-1])
return h, xedges, yedges, pc
@_preprocess_data(replace_names=["x"], label_namer=None)
@docstring.dedent_interpd
def psd(self, x, NFFT=None, Fs=None, Fc=None, detrend=None,
window=None, noverlap=None, pad_to=None,
sides=None, scale_by_freq=None, return_line=None, **kwargs):
r"""
Plot the power spectral density.
Call signature::
psd(x, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,
window=mlab.window_hanning, noverlap=0, pad_to=None,
sides='default', scale_by_freq=None, return_line=None, **kwargs)
The power spectral density :math:`P_{xx}` by Welch's average
periodogram method. The vector *x* is divided into *NFFT* length
segments. Each segment is detrended by function *detrend* and
windowed by function *window*. *noverlap* gives the length of
the overlap between segments. The :math:`|\mathrm{fft}(i)|^2`
of each segment :math:`i` are averaged to compute :math:`P_{xx}`,
with a scaling to correct for power loss due to windowing.
If len(*x*) < *NFFT*, it will be zero padded to *NFFT*.
Parameters
----------
x : 1-D array or sequence
Array or sequence containing the data
%(Spectral)s
%(PSD)s
noverlap : integer
The number of points of overlap between segments.
The default value is 0 (no overlap).
Fc : integer
The center frequency of *x* (defaults to 0), which offsets
the x extents of the plot to reflect the frequency range used
when a signal is acquired and then filtered and downsampled to
baseband.
return_line : bool
Whether to include the line object plotted in the returned values.
Default is False.
Returns
-------
Pxx : 1-D array
The values for the power spectrum `P_{xx}` before scaling
(real valued)
freqs : 1-D array
The frequencies corresponding to the elements in *Pxx*
line : a :class:`~matplotlib.lines.Line2D` instance
The line created by this function.
Only returned if *return_line* is True.
Other Parameters
----------------
**kwargs :
Keyword arguments control the :class:`~matplotlib.lines.Line2D`
properties:
%(Line2D)s
See Also
--------
:func:`specgram`
:func:`specgram` differs in the default overlap; in not returning
the mean of the segment periodograms; in returning the times of the
segments; and in plotting a colormap instead of a line.
:func:`magnitude_spectrum`
:func:`magnitude_spectrum` plots the magnitude spectrum.
:func:`csd`
:func:`csd` plots the spectral density between two signals.
Notes
-----
For plotting, the power is plotted as
:math:`10\log_{10}(P_{xx})` for decibels, though *Pxx* itself
is returned.
References
----------
Bendat & Piersol -- Random Data: Analysis and Measurement Procedures,
John Wiley & Sons (1986)
"""
if not self._hold:
self.cla()
if Fc is None:
Fc = 0
pxx, freqs = mlab.psd(x=x, NFFT=NFFT, Fs=Fs, detrend=detrend,
window=window, noverlap=noverlap, pad_to=pad_to,
sides=sides, scale_by_freq=scale_by_freq)
freqs += Fc
if scale_by_freq in (None, True):
psd_units = 'dB/Hz'
else:
psd_units = 'dB'
line = self.plot(freqs, 10 * np.log10(pxx), **kwargs)
self.set_xlabel('Frequency')
self.set_ylabel('Power Spectral Density (%s)' % psd_units)
self.grid(True)
vmin, vmax = self.viewLim.intervaly
intv = vmax - vmin
logi = int(np.log10(intv))
if logi == 0:
logi = .1
step = 10 * logi
ticks = np.arange(math.floor(vmin), math.ceil(vmax) + 1, step)
self.set_yticks(ticks)
if return_line is None or not return_line:
return pxx, freqs
else:
return pxx, freqs, line
@_preprocess_data(replace_names=["x", "y"], label_namer="y")
@docstring.dedent_interpd
def csd(self, x, y, NFFT=None, Fs=None, Fc=None, detrend=None,
window=None, noverlap=None, pad_to=None,
sides=None, scale_by_freq=None, return_line=None, **kwargs):
"""
Plot the cross-spectral density.
Call signature::
csd(x, y, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,
window=mlab.window_hanning, noverlap=0, pad_to=None,
sides='default', scale_by_freq=None, return_line=None, **kwargs)
The cross spectral density :math:`P_{xy}` by Welch's average
periodogram method. The vectors *x* and *y* are divided into
*NFFT* length segments. Each segment is detrended by function
*detrend* and windowed by function *window*. *noverlap* gives
the length of the overlap between segments. The product of
the direct FFTs of *x* and *y* are averaged over each segment
to compute :math:`P_{xy}`, with a scaling to correct for power
loss due to windowing.
If len(*x*) < *NFFT* or len(*y*) < *NFFT*, they will be zero
padded to *NFFT*.
Parameters
----------
x, y : 1-D arrays or sequences
Arrays or sequences containing the data
%(Spectral)s
%(PSD)s
noverlap : integer
The number of points of overlap between segments.
The default value is 0 (no overlap).
Fc : integer
The center frequency of *x* (defaults to 0), which offsets
the x extents of the plot to reflect the frequency range used
when a signal is acquired and then filtered and downsampled to
baseband.
return_line : bool
Whether to include the line object plotted in the returned values.
Default is False.
Returns
-------
Pxy : 1-D array
The values for the cross spectrum `P_{xy}` before scaling
(complex valued)
freqs : 1-D array
The frequencies corresponding to the elements in *Pxy*
line : a :class:`~matplotlib.lines.Line2D` instance
The line created by this function.
Only returned if *return_line* is True.
Other Parameters
----------------
**kwargs :
Keyword arguments control the :class:`~matplotlib.lines.Line2D`
properties:
%(Line2D)s
See Also
--------
:func:`psd`
:func:`psd` is the equivalent to setting y=x.
Notes
-----
For plotting, the power is plotted as
:math:`10\\log_{10}(P_{xy})` for decibels, though `P_{xy}` itself
is returned.
References
----------
Bendat & Piersol -- Random Data: Analysis and Measurement Procedures,
John Wiley & Sons (1986)
"""
if not self._hold:
self.cla()
if Fc is None:
Fc = 0
pxy, freqs = mlab.csd(x=x, y=y, NFFT=NFFT, Fs=Fs, detrend=detrend,
window=window, noverlap=noverlap, pad_to=pad_to,
sides=sides, scale_by_freq=scale_by_freq)
# pxy is complex
freqs += Fc
line = self.plot(freqs, 10 * np.log10(np.abs(pxy)), **kwargs)
self.set_xlabel('Frequency')
self.set_ylabel('Cross Spectrum Magnitude (dB)')
self.grid(True)
vmin, vmax = self.viewLim.intervaly
intv = vmax - vmin
step = 10 * int(np.log10(intv))
ticks = np.arange(math.floor(vmin), math.ceil(vmax) + 1, step)
self.set_yticks(ticks)
if return_line is None or not return_line:
return pxy, freqs
else:
return pxy, freqs, line
@_preprocess_data(replace_names=["x"], label_namer=None)
@docstring.dedent_interpd
def magnitude_spectrum(self, x, Fs=None, Fc=None, window=None,
pad_to=None, sides=None, scale=None,
**kwargs):
"""
Plot the magnitude spectrum.
Call signature::
magnitude_spectrum(x, Fs=2, Fc=0, window=mlab.window_hanning,
pad_to=None, sides='default', **kwargs)
Compute the magnitude spectrum of *x*. Data is padded to a
length of *pad_to* and the windowing function *window* is applied to
the signal.
Parameters
----------
x : 1-D array or sequence
Array or sequence containing the data
%(Spectral)s
%(Single_Spectrum)s
scale : [ 'default' | 'linear' | 'dB' ]
The scaling of the values in the *spec*. 'linear' is no scaling.
'dB' returns the values in dB scale, i.e., the dB amplitude
(20 * log10). 'default' is 'linear'.
Fc : integer
The center frequency of *x* (defaults to 0), which offsets
the x extents of the plot to reflect the frequency range used
when a signal is acquired and then filtered and downsampled to
baseband.
Returns
-------
spectrum : 1-D array
The values for the magnitude spectrum before scaling (real valued)
freqs : 1-D array
The frequencies corresponding to the elements in *spectrum*
line : a :class:`~matplotlib.lines.Line2D` instance
The line created by this function
Other Parameters
----------------
**kwargs :
Keyword arguments control the :class:`~matplotlib.lines.Line2D`
properties:
%(Line2D)s
See Also
--------
:func:`psd`
:func:`psd` plots the power spectral density.`.
:func:`angle_spectrum`
:func:`angle_spectrum` plots the angles of the corresponding
frequencies.
:func:`phase_spectrum`
:func:`phase_spectrum` plots the phase (unwrapped angle) of the
corresponding frequencies.
:func:`specgram`
:func:`specgram` can plot the magnitude spectrum of segments within
the signal in a colormap.
Notes
-----
.. [Notes section required for data comment. See #10189.]
"""
if not self._hold:
self.cla()
if Fc is None:
Fc = 0
if scale is None or scale == 'default':
scale = 'linear'
spec, freqs = mlab.magnitude_spectrum(x=x, Fs=Fs, window=window,
pad_to=pad_to, sides=sides)
freqs += Fc
if scale == 'linear':
Z = spec
yunits = 'energy'
elif scale == 'dB':
Z = 20. * np.log10(spec)
yunits = 'dB'
else:
raise ValueError('Unknown scale %s', scale)
lines = self.plot(freqs, Z, **kwargs)
self.set_xlabel('Frequency')
self.set_ylabel('Magnitude (%s)' % yunits)
return spec, freqs, lines[0]
@_preprocess_data(replace_names=["x"], label_namer=None)
@docstring.dedent_interpd
def angle_spectrum(self, x, Fs=None, Fc=None, window=None,
pad_to=None, sides=None, **kwargs):
"""
Plot the angle spectrum.
Call signature::
angle_spectrum(x, Fs=2, Fc=0, window=mlab.window_hanning,
pad_to=None, sides='default', **kwargs)
Compute the angle spectrum (wrapped phase spectrum) of *x*.
Data is padded to a length of *pad_to* and the windowing function
*window* is applied to the signal.
Parameters
----------
x : 1-D array or sequence
Array or sequence containing the data
%(Spectral)s
%(Single_Spectrum)s
Fc : integer
The center frequency of *x* (defaults to 0), which offsets
the x extents of the plot to reflect the frequency range used
when a signal is acquired and then filtered and downsampled to
baseband.
Returns
-------
spectrum : 1-D array
The values for the angle spectrum in radians (real valued)
freqs : 1-D array
The frequencies corresponding to the elements in *spectrum*
line : a :class:`~matplotlib.lines.Line2D` instance
The line created by this function
Other Parameters
----------------
**kwargs :
Keyword arguments control the :class:`~matplotlib.lines.Line2D`
properties:
%(Line2D)s
See Also
--------
:func:`magnitude_spectrum`
:func:`angle_spectrum` plots the magnitudes of the corresponding
frequencies.
:func:`phase_spectrum`
:func:`phase_spectrum` plots the unwrapped version of this
function.
:func:`specgram`
:func:`specgram` can plot the angle spectrum of segments within the
signal in a colormap.
Notes
-----
.. [Notes section required for data comment. See #10189.]
"""
if not self._hold:
self.cla()
if Fc is None:
Fc = 0
spec, freqs = mlab.angle_spectrum(x=x, Fs=Fs, window=window,
pad_to=pad_to, sides=sides)
freqs += Fc
lines = self.plot(freqs, spec, **kwargs)
self.set_xlabel('Frequency')
self.set_ylabel('Angle (radians)')
return spec, freqs, lines[0]
@_preprocess_data(replace_names=["x"], label_namer=None)
@docstring.dedent_interpd
def phase_spectrum(self, x, Fs=None, Fc=None, window=None,
pad_to=None, sides=None, **kwargs):
"""
Plot the phase spectrum.
Call signature::
phase_spectrum(x, Fs=2, Fc=0, window=mlab.window_hanning,
pad_to=None, sides='default', **kwargs)
Compute the phase spectrum (unwrapped angle spectrum) of *x*.
Data is padded to a length of *pad_to* and the windowing function
*window* is applied to the signal.
Parameters
----------
x : 1-D array or sequence
Array or sequence containing the data
%(Spectral)s
%(Single_Spectrum)s
Fc : integer
The center frequency of *x* (defaults to 0), which offsets
the x extents of the plot to reflect the frequency range used
when a signal is acquired and then filtered and downsampled to
baseband.
Returns
-------
spectrum : 1-D array
The values for the phase spectrum in radians (real valued)
freqs : 1-D array
The frequencies corresponding to the elements in *spectrum*
line : a :class:`~matplotlib.lines.Line2D` instance
The line created by this function
Other Parameters
----------------
**kwargs :
Keyword arguments control the :class:`~matplotlib.lines.Line2D`
properties:
%(Line2D)s
See Also
--------
:func:`magnitude_spectrum`
:func:`magnitude_spectrum` plots the magnitudes of the
corresponding frequencies.
:func:`angle_spectrum`
:func:`angle_spectrum` plots the wrapped version of this function.
:func:`specgram`
:func:`specgram` can plot the phase spectrum of segments within the
signal in a colormap.
Notes
-----
.. [Notes section required for data comment. See #10189.]
"""
if not self._hold:
self.cla()
if Fc is None:
Fc = 0
spec, freqs = mlab.phase_spectrum(x=x, Fs=Fs, window=window,
pad_to=pad_to, sides=sides)
freqs += Fc
lines = self.plot(freqs, spec, **kwargs)
self.set_xlabel('Frequency')
self.set_ylabel('Phase (radians)')
return spec, freqs, lines[0]
@_preprocess_data(replace_names=["x", "y"], label_namer=None)
@docstring.dedent_interpd
def cohere(self, x, y, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,
window=mlab.window_hanning, noverlap=0, pad_to=None,
sides='default', scale_by_freq=None, **kwargs):
"""
Plot the coherence between *x* and *y*.
Plot the coherence between *x* and *y*. Coherence is the
normalized cross spectral density:
.. math::
C_{xy} = \\frac{|P_{xy}|^2}{P_{xx}P_{yy}}
Parameters
----------
%(Spectral)s
%(PSD)s
noverlap : integer
The number of points of overlap between blocks. The
default value is 0 (no overlap).
Fc : integer
The center frequency of *x* (defaults to 0), which offsets
the x extents of the plot to reflect the frequency range used
when a signal is acquired and then filtered and downsampled to
baseband.
Returns
-------
The return value is a tuple (*Cxy*, *f*), where *f* are the
frequencies of the coherence vector.
kwargs are applied to the lines.
Other Parameters
----------------
**kwargs :
Keyword arguments control the :class:`~matplotlib.lines.Line2D`
properties:
%(Line2D)s
References
----------
Bendat & Piersol -- Random Data: Analysis and Measurement Procedures,
John Wiley & Sons (1986)
"""
if not self._hold:
self.cla()
cxy, freqs = mlab.cohere(x=x, y=y, NFFT=NFFT, Fs=Fs, detrend=detrend,
window=window, noverlap=noverlap,
scale_by_freq=scale_by_freq)
freqs += Fc
self.plot(freqs, cxy, **kwargs)
self.set_xlabel('Frequency')
self.set_ylabel('Coherence')
self.grid(True)
return cxy, freqs
@_preprocess_data(replace_names=["x"], label_namer=None)
@docstring.dedent_interpd
def specgram(self, x, NFFT=None, Fs=None, Fc=None, detrend=None,
window=None, noverlap=None,
cmap=None, xextent=None, pad_to=None, sides=None,
scale_by_freq=None, mode=None, scale=None,
vmin=None, vmax=None, **kwargs):
"""
Plot a spectrogram.
Call signature::
specgram(x, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none,
window=mlab.window_hanning, noverlap=128,
cmap=None, xextent=None, pad_to=None, sides='default',
scale_by_freq=None, mode='default', scale='default',
**kwargs)
Compute and plot a spectrogram of data in *x*. Data are split into
*NFFT* length segments and the spectrum of each section is
computed. The windowing function *window* is applied to each
segment, and the amount of overlap of each segment is
specified with *noverlap*. The spectrogram is plotted as a colormap
(using imshow).
Parameters
----------
x : 1-D array or sequence
Array or sequence containing the data.
%(Spectral)s
%(PSD)s
mode : [ 'default' | 'psd' | 'magnitude' | 'angle' | 'phase' ]
What sort of spectrum to use. Default is 'psd', which takes
the power spectral density. 'complex' returns the complex-valued
frequency spectrum. 'magnitude' returns the magnitude spectrum.
'angle' returns the phase spectrum without unwrapping. 'phase'
returns the phase spectrum with unwrapping.
noverlap : integer
The number of points of overlap between blocks. The
default value is 128.
scale : [ 'default' | 'linear' | 'dB' ]
The scaling of the values in the *spec*. 'linear' is no scaling.
'dB' returns the values in dB scale. When *mode* is 'psd',
this is dB power (10 * log10). Otherwise this is dB amplitude
(20 * log10). 'default' is 'dB' if *mode* is 'psd' or
'magnitude' and 'linear' otherwise. This must be 'linear'
if *mode* is 'angle' or 'phase'.
Fc : integer
The center frequency of *x* (defaults to 0), which offsets
the x extents of the plot to reflect the frequency range used
when a signal is acquired and then filtered and downsampled to
baseband.
cmap :
A :class:`matplotlib.colors.Colormap` instance; if *None*, use
default determined by rc
xextent : [None | (xmin, xmax)]
The image extent along the x-axis. The default sets *xmin* to the
left border of the first bin (*spectrum* column) and *xmax* to the
right border of the last bin. Note that for *noverlap>0* the width
of the bins is smaller than those of the segments.
**kwargs :
Additional kwargs are passed on to imshow which makes the
specgram image
Returns
-------
spectrum : 2-D array
Columns are the periodograms of successive segments.
freqs : 1-D array
The frequencies corresponding to the rows in *spectrum*.
t : 1-D array
The times corresponding to midpoints of segments (i.e., the columns
in *spectrum*).
im : instance of class :class:`~matplotlib.image.AxesImage`
The image created by imshow containing the spectrogram
See Also
--------
:func:`psd`
:func:`psd` differs in the default overlap; in returning the mean
of the segment periodograms; in not returning times; and in
generating a line plot instead of colormap.
:func:`magnitude_spectrum`
A single spectrum, similar to having a single segment when *mode*
is 'magnitude'. Plots a line instead of a colormap.
:func:`angle_spectrum`
A single spectrum, similar to having a single segment when *mode*
is 'angle'. Plots a line instead of a colormap.
:func:`phase_spectrum`
A single spectrum, similar to having a single segment when *mode*
is 'phase'. Plots a line instead of a colormap.
Notes
-----
The parameters *detrend* and *scale_by_freq* do only apply when *mode*
is set to 'psd'.
"""
if not self._hold:
self.cla()
if NFFT is None:
NFFT = 256 # same default as in mlab.specgram()
if Fc is None:
Fc = 0 # same default as in mlab._spectral_helper()
if noverlap is None:
noverlap = 128 # same default as in mlab.specgram()
if mode == 'complex':
raise ValueError('Cannot plot a complex specgram')
if scale is None or scale == 'default':
if mode in ['angle', 'phase']:
scale = 'linear'
else:
scale = 'dB'
elif mode in ['angle', 'phase'] and scale == 'dB':
raise ValueError('Cannot use dB scale with angle or phase mode')
spec, freqs, t = mlab.specgram(x=x, NFFT=NFFT, Fs=Fs,
detrend=detrend, window=window,
noverlap=noverlap, pad_to=pad_to,
sides=sides,
scale_by_freq=scale_by_freq,
mode=mode)
if scale == 'linear':
Z = spec
elif scale == 'dB':
if mode is None or mode == 'default' or mode == 'psd':
Z = 10. * np.log10(spec)
else:
Z = 20. * np.log10(spec)
else:
raise ValueError('Unknown scale %s', scale)
Z = np.flipud(Z)
if xextent is None:
# padding is needed for first and last segment:
pad_xextent = (NFFT-noverlap) / Fs / 2
xextent = np.min(t) - pad_xextent, np.max(t) + pad_xextent
xmin, xmax = xextent
freqs += Fc
extent = xmin, xmax, freqs[0], freqs[-1]
im = self.imshow(Z, cmap, extent=extent, vmin=vmin, vmax=vmax,
**kwargs)
self.axis('auto')
return spec, freqs, t, im
def spy(self, Z, precision=0, marker=None, markersize=None,
aspect='equal', origin="upper", **kwargs):
"""
Plot the sparsity pattern on a 2-D array.
``spy(Z)`` plots the sparsity pattern of the 2-D array *Z*.
Parameters
----------
Z : sparse array (n, m)
The array to be plotted.
precision : float, optional, default: 0
If *precision* is 0, any non-zero value will be plotted; else,
values of :math:`|Z| > precision` will be plotted.
For :class:`scipy.sparse.spmatrix` instances, there is a special
case: if *precision* is 'present', any value present in the array
will be plotted, even if it is identically zero.
origin : ["upper", "lower"], optional, default: "upper"
Place the [0,0] index of the array in the upper left or lower left
corner of the axes.
aspect : ['auto' | 'equal' | scalar], optional, default: "equal"
If 'equal', and `extent` is None, changes the axes aspect ratio to
match that of the image. If `extent` is not `None`, the axes
aspect ratio is changed to match that of the extent.
If 'auto', changes the image aspect ratio to match that of the
axes.
If None, default to rc ``image.aspect`` value.
Two plotting styles are available: image or marker. Both
are available for full arrays, but only the marker style
works for :class:`scipy.sparse.spmatrix` instances.
If *marker* and *markersize* are *None*, an image will be
returned and any remaining kwargs are passed to
:func:`~matplotlib.pyplot.imshow`; else, a
:class:`~matplotlib.lines.Line2D` object will be returned with
the value of marker determining the marker type, and any
remaining kwargs passed to the
:meth:`~matplotlib.axes.Axes.plot` method.
If *marker* and *markersize* are *None*, useful kwargs include:
* *cmap*
* *alpha*
See also
--------
imshow : for image options.
plot : for plotting options
"""
if marker is None and markersize is None and hasattr(Z, 'tocoo'):
marker = 's'
if marker is None and markersize is None:
Z = np.asarray(Z)
mask = np.abs(Z) > precision
if 'cmap' not in kwargs:
kwargs['cmap'] = mcolors.ListedColormap(['w', 'k'],
name='binary')
nr, nc = Z.shape
extent = [-0.5, nc - 0.5, nr - 0.5, -0.5]
ret = self.imshow(mask, interpolation='nearest', aspect=aspect,
extent=extent, origin=origin, **kwargs)
else:
if hasattr(Z, 'tocoo'):
c = Z.tocoo()
if precision == 'present':
y = c.row
x = c.col
else:
nonzero = np.abs(c.data) > precision
y = c.row[nonzero]
x = c.col[nonzero]
else:
Z = np.asarray(Z)
nonzero = np.abs(Z) > precision
y, x = np.nonzero(nonzero)
if marker is None:
marker = 's'
if markersize is None:
markersize = 10
marks = mlines.Line2D(x, y, linestyle='None',
marker=marker, markersize=markersize, **kwargs)
self.add_line(marks)
nr, nc = Z.shape
self.set_xlim(xmin=-0.5, xmax=nc - 0.5)
self.set_ylim(ymin=nr - 0.5, ymax=-0.5)
self.set_aspect(aspect)
ret = marks
self.title.set_y(1.05)
self.xaxis.tick_top()
self.xaxis.set_ticks_position('both')
self.xaxis.set_major_locator(mticker.MaxNLocator(nbins=9,
steps=[1, 2, 5, 10],
integer=True))
self.yaxis.set_major_locator(mticker.MaxNLocator(nbins=9,
steps=[1, 2, 5, 10],
integer=True))
return ret
def matshow(self, Z, **kwargs):
"""
Plot a matrix or array as an image.
The matrix will be shown the way it would be printed, with the first
row at the top. Row and column numbering is zero-based.
Parameters
----------
Z : array_like shape (n, m)
The matrix to be displayed.
Returns
-------
image : `~matplotlib.image.AxesImage`
Other Parameters
----------------
**kwargs : `~matplotlib.axes.Axes.imshow` arguments
Sets `origin` to 'upper', 'interpolation' to 'nearest' and
'aspect' to equal.
See also
--------
imshow : plot an image
"""
Z = np.asanyarray(Z)
nr, nc = Z.shape
kw = {'origin': 'upper',
'interpolation': 'nearest',
'aspect': 'equal'} # (already the imshow default)
kw.update(kwargs)
im = self.imshow(Z, **kw)
self.title.set_y(1.05)
self.xaxis.tick_top()
self.xaxis.set_ticks_position('both')
self.xaxis.set_major_locator(mticker.MaxNLocator(nbins=9,
steps=[1, 2, 5, 10],
integer=True))
self.yaxis.set_major_locator(mticker.MaxNLocator(nbins=9,
steps=[1, 2, 5, 10],
integer=True))
return im
@_preprocess_data(replace_names=["dataset"], label_namer=None)
def violinplot(self, dataset, positions=None, vert=True, widths=0.5,
showmeans=False, showextrema=True, showmedians=False,
points=100, bw_method=None):
"""
Make a violin plot.
Make a violin plot for each column of *dataset* or each vector in
sequence *dataset*. Each filled area extends to represent the
entire data range, with optional lines at the mean, the median,
the minimum, and the maximum.
Parameters
----------
dataset : Array or a sequence of vectors.
The input data.
positions : array-like, default = [1, 2, ..., n]
Sets the positions of the violins. The ticks and limits are
automatically set to match the positions.
vert : bool, default = True.
If true, creates a vertical violin plot.
Otherwise, creates a horizontal violin plot.
widths : array-like, default = 0.5
Either a scalar or a vector that sets the maximal width of
each violin. The default is 0.5, which uses about half of the
available horizontal space.
showmeans : bool, default = False
If `True`, will toggle rendering of the means.
showextrema : bool, default = True
If `True`, will toggle rendering of the extrema.
showmedians : bool, default = False
If `True`, will toggle rendering of the medians.
points : scalar, default = 100
Defines the number of points to evaluate each of the
gaussian kernel density estimations at.
bw_method : str, scalar or callable, optional
The method used to calculate the estimator bandwidth. This can be
'scott', 'silverman', a scalar constant or a callable. If a
scalar, this will be used directly as `kde.factor`. If a
callable, it should take a `GaussianKDE` instance as its only
parameter and return a scalar. If None (default), 'scott' is used.
Returns
-------
result : dict
A dictionary mapping each component of the violinplot to a
list of the corresponding collection instances created. The
dictionary has the following keys:
- ``bodies``: A list of the
:class:`matplotlib.collections.PolyCollection` instances
containing the filled area of each violin.
- ``cmeans``: A
:class:`matplotlib.collections.LineCollection` instance
created to identify the mean values of each of the
violin's distribution.
- ``cmins``: A
:class:`matplotlib.collections.LineCollection` instance
created to identify the bottom of each violin's
distribution.
- ``cmaxes``: A
:class:`matplotlib.collections.LineCollection` instance
created to identify the top of each violin's
distribution.
- ``cbars``: A
:class:`matplotlib.collections.LineCollection` instance
created to identify the centers of each violin's
distribution.
- ``cmedians``: A
:class:`matplotlib.collections.LineCollection` instance
created to identify the median values of each of the
violin's distribution.
Notes
-----
.. [Notes section required for data comment. See #10189.]
"""
def _kde_method(X, coords):
# fallback gracefully if the vector contains only one value
if np.all(X[0] == X):
return (X[0] == coords).astype(float)
kde = mlab.GaussianKDE(X, bw_method)
return kde.evaluate(coords)
vpstats = cbook.violin_stats(dataset, _kde_method, points=points)
return self.violin(vpstats, positions=positions, vert=vert,
widths=widths, showmeans=showmeans,
showextrema=showextrema, showmedians=showmedians)
def violin(self, vpstats, positions=None, vert=True, widths=0.5,
showmeans=False, showextrema=True, showmedians=False):
"""Drawing function for violin plots.
Draw a violin plot for each column of `vpstats`. Each filled area
extends to represent the entire data range, with optional lines at the
mean, the median, the minimum, and the maximum.
Parameters
----------
vpstats : list of dicts
A list of dictionaries containing stats for each violin plot.
Required keys are:
- ``coords``: A list of scalars containing the coordinates that
the violin's kernel density estimate were evaluated at.
- ``vals``: A list of scalars containing the values of the
kernel density estimate at each of the coordinates given
in *coords*.
- ``mean``: The mean value for this violin's dataset.
- ``median``: The median value for this violin's dataset.
- ``min``: The minimum value for this violin's dataset.
- ``max``: The maximum value for this violin's dataset.
positions : array-like, default = [1, 2, ..., n]
Sets the positions of the violins. The ticks and limits are
automatically set to match the positions.
vert : bool, default = True.
If true, plots the violins veritcally.
Otherwise, plots the violins horizontally.
widths : array-like, default = 0.5
Either a scalar or a vector that sets the maximal width of
each violin. The default is 0.5, which uses about half of the
available horizontal space.
showmeans : bool, default = False
If true, will toggle rendering of the means.
showextrema : bool, default = True
If true, will toggle rendering of the extrema.
showmedians : bool, default = False
If true, will toggle rendering of the medians.
Returns
-------
result : dict
A dictionary mapping each component of the violinplot to a
list of the corresponding collection instances created. The
dictionary has the following keys:
- ``bodies``: A list of the
:class:`matplotlib.collections.PolyCollection` instances
containing the filled area of each violin.
- ``cmeans``: A
:class:`matplotlib.collections.LineCollection` instance
created to identify the mean values of each of the
violin's distribution.
- ``cmins``: A
:class:`matplotlib.collections.LineCollection` instance
created to identify the bottom of each violin's
distribution.
- ``cmaxes``: A
:class:`matplotlib.collections.LineCollection` instance
created to identify the top of each violin's
distribution.
- ``cbars``: A
:class:`matplotlib.collections.LineCollection` instance
created to identify the centers of each violin's
distribution.
- ``cmedians``: A
:class:`matplotlib.collections.LineCollection` instance
created to identify the median values of each of the
violin's distribution.
"""
# Statistical quantities to be plotted on the violins
means = []
mins = []
maxes = []
medians = []
# Collections to be returned
artists = {}
N = len(vpstats)
datashape_message = ("List of violinplot statistics and `{0}` "
"values must have the same length")
# Validate positions
if positions is None:
positions = range(1, N + 1)
elif len(positions) != N:
raise ValueError(datashape_message.format("positions"))
# Validate widths
if np.isscalar(widths):
widths = [widths] * N
elif len(widths) != N:
raise ValueError(datashape_message.format("widths"))
# Calculate ranges for statistics lines
pmins = -0.25 * np.array(widths) + positions
pmaxes = 0.25 * np.array(widths) + positions
# Check whether we are rendering vertically or horizontally
if vert:
fill = self.fill_betweenx
perp_lines = self.hlines
par_lines = self.vlines
else:
fill = self.fill_between
perp_lines = self.vlines
par_lines = self.hlines
if rcParams['_internal.classic_mode']:
fillcolor = 'y'
edgecolor = 'r'
else:
fillcolor = edgecolor = self._get_lines.get_next_color()
# Render violins
bodies = []
for stats, pos, width in zip(vpstats, positions, widths):
# The 0.5 factor reflects the fact that we plot from v-p to
# v+p
vals = np.array(stats['vals'])
vals = 0.5 * width * vals / vals.max()
bodies += [fill(stats['coords'],
-vals + pos,
vals + pos,
facecolor=fillcolor,
alpha=0.3)]
means.append(stats['mean'])
mins.append(stats['min'])
maxes.append(stats['max'])
medians.append(stats['median'])
artists['bodies'] = bodies
# Render means
if showmeans:
artists['cmeans'] = perp_lines(means, pmins, pmaxes,
colors=edgecolor)
# Render extrema
if showextrema:
artists['cmaxes'] = perp_lines(maxes, pmins, pmaxes,
colors=edgecolor)
artists['cmins'] = perp_lines(mins, pmins, pmaxes,
colors=edgecolor)
artists['cbars'] = par_lines(positions, mins, maxes,
colors=edgecolor)
# Render medians
if showmedians:
artists['cmedians'] = perp_lines(medians,
pmins,
pmaxes,
colors=edgecolor)
return artists
def tricontour(self, *args, **kwargs):
return mtri.tricontour(self, *args, **kwargs)
tricontour.__doc__ = mtri.tricontour.__doc__
def tricontourf(self, *args, **kwargs):
return mtri.tricontourf(self, *args, **kwargs)
tricontourf.__doc__ = mtri.tricontour.__doc__
def tripcolor(self, *args, **kwargs):
return mtri.tripcolor(self, *args, **kwargs)
tripcolor.__doc__ = mtri.tripcolor.__doc__
def triplot(self, *args, **kwargs):
return mtri.triplot(self, *args, **kwargs)
triplot.__doc__ = mtri.triplot.__doc__
| 301,342 | 36.503796 | 79 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/axes/_subplots.py | from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
from six.moves import map
from matplotlib.gridspec import GridSpec, SubplotSpec
from matplotlib import docstring
import matplotlib.artist as martist
from matplotlib.axes._axes import Axes
import matplotlib._layoutbox as layoutbox
import warnings
from matplotlib.cbook import mplDeprecation
class SubplotBase(object):
"""
Base class for subplots, which are :class:`Axes` instances with
additional methods to facilitate generating and manipulating a set
of :class:`Axes` within a figure.
"""
def __init__(self, fig, *args, **kwargs):
"""
*fig* is a :class:`matplotlib.figure.Figure` instance.
*args* is the tuple (*numRows*, *numCols*, *plotNum*), where
the array of subplots in the figure has dimensions *numRows*,
*numCols*, and where *plotNum* is the number of the subplot
being created. *plotNum* starts at 1 in the upper left
corner and increases to the right.
If *numRows* <= *numCols* <= *plotNum* < 10, *args* can be the
decimal integer *numRows* * 100 + *numCols* * 10 + *plotNum*.
"""
self.figure = fig
if len(args) == 1:
if isinstance(args[0], SubplotSpec):
self._subplotspec = args[0]
else:
try:
s = str(int(args[0]))
rows, cols, num = map(int, s)
except ValueError:
raise ValueError('Single argument to subplot must be '
'a 3-digit integer')
self._subplotspec = GridSpec(rows, cols,
figure=self.figure)[num - 1]
# num - 1 for converting from MATLAB to python indexing
elif len(args) == 3:
rows, cols, num = args
rows = int(rows)
cols = int(cols)
if isinstance(num, tuple) and len(num) == 2:
num = [int(n) for n in num]
self._subplotspec = GridSpec(
rows, cols,
figure=self.figure)[(num[0] - 1):num[1]]
else:
if num < 1 or num > rows*cols:
raise ValueError(
("num must be 1 <= num <= {maxn}, not {num}"
).format(maxn=rows*cols, num=num))
self._subplotspec = GridSpec(
rows, cols, figure=self.figure)[int(num) - 1]
# num - 1 for converting from MATLAB to python indexing
else:
raise ValueError('Illegal argument(s) to subplot: %s' % (args,))
self.update_params()
# _axes_class is set in the subplot_class_factory
self._axes_class.__init__(self, fig, self.figbox, **kwargs)
# add a layout box to this, for both the full axis, and the poss
# of the axis. We need both because the axes may become smaller
# due to parasitic axes and hence no longer fill the subplotspec.
if self._subplotspec._layoutbox is None:
self._layoutbox = None
self._poslayoutbox = None
else:
name = self._subplotspec._layoutbox.name + '.ax'
name = name + layoutbox.seq_id()
self._layoutbox = layoutbox.LayoutBox(
parent=self._subplotspec._layoutbox,
name=name,
artist=self)
self._poslayoutbox = layoutbox.LayoutBox(
parent=self._layoutbox,
name=self._layoutbox.name+'.pos',
pos=True, subplot=True, artist=self)
def __reduce__(self):
# get the first axes class which does not
# inherit from a subplotbase
def not_subplotbase(c):
return issubclass(c, Axes) and not issubclass(c, SubplotBase)
axes_class = [c for c in self.__class__.mro()
if not_subplotbase(c)][0]
r = [_PicklableSubplotClassConstructor(),
(axes_class,),
self.__getstate__()]
return tuple(r)
def get_geometry(self):
"""get the subplot geometry, e.g., 2,2,3"""
rows, cols, num1, num2 = self.get_subplotspec().get_geometry()
return rows, cols, num1 + 1 # for compatibility
# COVERAGE NOTE: Never used internally or from examples
def change_geometry(self, numrows, numcols, num):
"""change subplot geometry, e.g., from 1,1,1 to 2,2,3"""
self._subplotspec = GridSpec(numrows, numcols,
figure=self.figure)[num - 1]
self.update_params()
self.set_position(self.figbox)
def get_subplotspec(self):
"""get the SubplotSpec instance associated with the subplot"""
return self._subplotspec
def set_subplotspec(self, subplotspec):
"""set the SubplotSpec instance associated with the subplot"""
self._subplotspec = subplotspec
def update_params(self):
"""update the subplot position from fig.subplotpars"""
self.figbox, self.rowNum, self.colNum, self.numRows, self.numCols = \
self.get_subplotspec().get_position(self.figure,
return_all=True)
def is_first_col(self):
return self.colNum == 0
def is_first_row(self):
return self.rowNum == 0
def is_last_row(self):
return self.rowNum == self.numRows - 1
def is_last_col(self):
return self.colNum == self.numCols - 1
# COVERAGE NOTE: Never used internally.
def label_outer(self):
"""Only show "outer" labels and tick labels.
x-labels are only kept for subplots on the last row; y-labels only for
subplots on the first column.
"""
lastrow = self.is_last_row()
firstcol = self.is_first_col()
if not lastrow:
for label in self.get_xticklabels(which="both"):
label.set_visible(False)
self.get_xaxis().get_offset_text().set_visible(False)
self.set_xlabel("")
if not firstcol:
for label in self.get_yticklabels(which="both"):
label.set_visible(False)
self.get_yaxis().get_offset_text().set_visible(False)
self.set_ylabel("")
def _make_twin_axes(self, *kl, **kwargs):
"""
Make a twinx axes of self. This is used for twinx and twiny.
"""
from matplotlib.projections import process_projection_requirements
if 'sharex' in kwargs and 'sharey' in kwargs:
# The following line is added in v2.2 to avoid breaking Seaborn,
# which currently uses this internal API.
if kwargs["sharex"] is not self and kwargs["sharey"] is not self:
raise ValueError("Twinned Axes may share only one axis.")
kl = (self.get_subplotspec(),) + kl
projection_class, kwargs, key = process_projection_requirements(
self.figure, *kl, **kwargs)
ax2 = subplot_class_factory(projection_class)(self.figure,
*kl, **kwargs)
self.figure.add_subplot(ax2)
self.set_adjustable('datalim')
ax2.set_adjustable('datalim')
if self._layoutbox is not None and ax2._layoutbox is not None:
# make the layout boxes be explicitly the same
ax2._layoutbox.constrain_same(self._layoutbox)
ax2._poslayoutbox.constrain_same(self._poslayoutbox)
self._twinned_axes.join(self, ax2)
return ax2
_subplot_classes = {}
def subplot_class_factory(axes_class=None):
# This makes a new class that inherits from SubplotBase and the
# given axes_class (which is assumed to be a subclass of Axes).
# This is perhaps a little bit roundabout to make a new class on
# the fly like this, but it means that a new Subplot class does
# not have to be created for every type of Axes.
if axes_class is None:
axes_class = Axes
new_class = _subplot_classes.get(axes_class)
if new_class is None:
new_class = type(str("%sSubplot") % (axes_class.__name__),
(SubplotBase, axes_class),
{'_axes_class': axes_class})
_subplot_classes[axes_class] = new_class
return new_class
# This is provided for backward compatibility
Subplot = subplot_class_factory()
class _PicklableSubplotClassConstructor(object):
"""
This stub class exists to return the appropriate subplot
class when __call__-ed with an axes class. This is purely to
allow Pickling of Axes and Subplots.
"""
def __call__(self, axes_class):
# create a dummy object instance
subplot_instance = _PicklableSubplotClassConstructor()
subplot_class = subplot_class_factory(axes_class)
# update the class to the desired subplot class
subplot_instance.__class__ = subplot_class
return subplot_instance
docstring.interpd.update(Axes=martist.kwdoc(Axes))
docstring.interpd.update(Subplot=martist.kwdoc(Axes))
"""
# this is some discarded code I was using to find the minimum positive
# data point for some log scaling fixes. I realized there was a
# cleaner way to do it, but am keeping this around as an example for
# how to get the data out of the axes. Might want to make something
# like this a method one day, or better yet make get_verts an Artist
# method
minx, maxx = self.get_xlim()
if minx<=0 or maxx<=0:
# find the min pos value in the data
xs = []
for line in self.lines:
xs.extend(line.get_xdata(orig=False))
for patch in self.patches:
xs.extend([x for x,y in patch.get_verts()])
for collection in self.collections:
xs.extend([x for x,y in collection.get_verts()])
posx = [x for x in xs if x>0]
if len(posx):
minx = min(posx)
maxx = max(posx)
# warning, probably breaks inverted axis
self.set_xlim((0.1*minx, maxx))
"""
| 10,335 | 37.567164 | 78 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/axes/_base.py | from __future__ import (absolute_import, division, print_function,
unicode_literals)
from collections import OrderedDict
import six
from six.moves import xrange
import itertools
import warnings
import math
from operator import attrgetter
import numpy as np
import matplotlib
from matplotlib import cbook
from matplotlib.cbook import (_check_1d, _string_to_bool, iterable,
index_of, get_label)
from matplotlib import docstring
import matplotlib.colors as mcolors
import matplotlib.lines as mlines
import matplotlib.patches as mpatches
import matplotlib.artist as martist
import matplotlib.transforms as mtransforms
import matplotlib.ticker as mticker
import matplotlib.axis as maxis
import matplotlib.scale as mscale
import matplotlib.spines as mspines
import matplotlib.font_manager as font_manager
import matplotlib.text as mtext
import matplotlib.image as mimage
from matplotlib.offsetbox import OffsetBox
from matplotlib.artist import allow_rasterization
from matplotlib.legend import Legend
from matplotlib.rcsetup import cycler
from matplotlib.rcsetup import validate_axisbelow
rcParams = matplotlib.rcParams
is_string_like = cbook.is_string_like
is_sequence_of_strings = cbook.is_sequence_of_strings
_hold_msg = """axes.hold is deprecated.
See the API Changes document (http://matplotlib.org/api/api_changes.html)
for more details."""
def _process_plot_format(fmt):
"""
Process a MATLAB style color/line style format string. Return a
(*linestyle*, *color*) tuple as a result of the processing. Default
values are ('-', 'b'). Example format strings include:
* 'ko': black circles
* '.b': blue dots
* 'r--': red dashed lines
* 'C2--': the third color in the color cycle, dashed lines
.. seealso::
:func:`~matplotlib.Line2D.lineStyles` and
:func:`~matplotlib.pyplot.colors`
for all possible styles and color format string.
"""
linestyle = None
marker = None
color = None
# Is fmt just a colorspec?
try:
color = mcolors.to_rgba(fmt)
# We need to differentiate grayscale '1.0' from tri_down marker '1'
try:
fmtint = str(int(fmt))
except ValueError:
return linestyle, marker, color # Yes
else:
if fmt != fmtint:
# user definitely doesn't want tri_down marker
return linestyle, marker, color # Yes
else:
# ignore converted color
color = None
except ValueError:
pass # No, not just a color.
# handle the multi char special cases and strip them from the
# string
if fmt.find('--') >= 0:
linestyle = '--'
fmt = fmt.replace('--', '')
if fmt.find('-.') >= 0:
linestyle = '-.'
fmt = fmt.replace('-.', '')
if fmt.find(' ') >= 0:
linestyle = 'None'
fmt = fmt.replace(' ', '')
chars = [c for c in fmt]
i = 0
while i < len(chars):
c = chars[i]
if c in mlines.lineStyles:
if linestyle is not None:
raise ValueError(
'Illegal format string "%s"; two linestyle symbols' % fmt)
linestyle = c
elif c in mlines.lineMarkers:
if marker is not None:
raise ValueError(
'Illegal format string "%s"; two marker symbols' % fmt)
marker = c
elif c in mcolors.get_named_colors_mapping():
if color is not None:
raise ValueError(
'Illegal format string "%s"; two color symbols' % fmt)
color = c
elif c == 'C' and i < len(chars) - 1:
color_cycle_number = int(chars[i + 1])
color = mcolors.to_rgba("C{}".format(color_cycle_number))
i += 1
else:
raise ValueError(
'Unrecognized character %c in format string' % c)
i += 1
if linestyle is None and marker is None:
linestyle = rcParams['lines.linestyle']
if linestyle is None:
linestyle = 'None'
if marker is None:
marker = 'None'
return linestyle, marker, color
class _process_plot_var_args(object):
"""
Process variable length arguments to the plot command, so that
plot commands like the following are supported::
plot(t, s)
plot(t1, s1, t2, s2)
plot(t1, s1, 'ko', t2, s2)
plot(t1, s1, 'ko', t2, s2, 'r--', t3, e3)
an arbitrary number of *x*, *y*, *fmt* are allowed
"""
def __init__(self, axes, command='plot'):
self.axes = axes
self.command = command
self.set_prop_cycle()
def __getstate__(self):
# note: it is not possible to pickle a itertools.cycle instance
return {'axes': self.axes, 'command': self.command}
def __setstate__(self, state):
self.__dict__ = state.copy()
self.set_prop_cycle()
def set_prop_cycle(self, *args, **kwargs):
if not (args or kwargs) or (len(args) == 1 and args[0] is None):
prop_cycler = rcParams['axes.prop_cycle']
else:
prop_cycler = cycler(*args, **kwargs)
self.prop_cycler = itertools.cycle(prop_cycler)
# This should make a copy
self._prop_keys = prop_cycler.keys
def __call__(self, *args, **kwargs):
if self.axes.xaxis is not None and self.axes.yaxis is not None:
xunits = kwargs.pop('xunits', self.axes.xaxis.units)
if self.axes.name == 'polar':
xunits = kwargs.pop('thetaunits', xunits)
yunits = kwargs.pop('yunits', self.axes.yaxis.units)
if self.axes.name == 'polar':
yunits = kwargs.pop('runits', yunits)
if xunits != self.axes.xaxis.units:
self.axes.xaxis.set_units(xunits)
if yunits != self.axes.yaxis.units:
self.axes.yaxis.set_units(yunits)
ret = self._grab_next_args(*args, **kwargs)
return ret
def get_next_color(self):
"""Return the next color in the cycle."""
if 'color' not in self._prop_keys:
return 'k'
return next(self.prop_cycler)['color']
def set_lineprops(self, line, **kwargs):
assert self.command == 'plot', 'set_lineprops only works with "plot"'
line.set(**kwargs)
def set_patchprops(self, fill_poly, **kwargs):
assert self.command == 'fill', 'set_patchprops only works with "fill"'
fill_poly.set(**kwargs)
def _xy_from_xy(self, x, y):
if self.axes.xaxis is not None and self.axes.yaxis is not None:
bx = self.axes.xaxis.update_units(x)
by = self.axes.yaxis.update_units(y)
if self.command != 'plot':
# the Line2D class can handle unitized data, with
# support for post hoc unit changes etc. Other mpl
# artists, e.g., Polygon which _process_plot_var_args
# also serves on calls to fill, cannot. So this is a
# hack to say: if you are not "plot", which is
# creating Line2D, then convert the data now to
# floats. If you are plot, pass the raw data through
# to Line2D which will handle the conversion. So
# polygons will not support post hoc conversions of
# the unit type since they are not storing the orig
# data. Hopefully we can rationalize this at a later
# date - JDH
if bx:
x = self.axes.convert_xunits(x)
if by:
y = self.axes.convert_yunits(y)
# like asanyarray, but converts scalar to array, and doesn't change
# existing compatible sequences
x = _check_1d(x)
y = _check_1d(y)
if x.shape[0] != y.shape[0]:
raise ValueError("x and y must have same first dimension, but "
"have shapes {} and {}".format(x.shape, y.shape))
if x.ndim > 2 or y.ndim > 2:
raise ValueError("x and y can be no greater than 2-D, but have "
"shapes {} and {}".format(x.shape, y.shape))
if x.ndim == 1:
x = x[:, np.newaxis]
if y.ndim == 1:
y = y[:, np.newaxis]
return x, y
def _getdefaults(self, ignore, *kwargs):
"""
Only advance the cycler if the cycler has information that
is not specified in any of the supplied tuple of dicts.
Ignore any keys specified in the `ignore` set.
Returns a copy of defaults dictionary if there are any
keys that are not found in any of the supplied dictionaries.
If the supplied dictionaries have non-None values for
everything the property cycler has, then just return
an empty dictionary. Ignored keys are excluded from the
returned dictionary.
"""
prop_keys = self._prop_keys
if ignore is None:
ignore = set()
prop_keys = prop_keys - ignore
if any(all(kw.get(k, None) is None for kw in kwargs)
for k in prop_keys):
# Need to copy this dictionary or else the next time around
# in the cycle, the dictionary could be missing entries.
default_dict = next(self.prop_cycler).copy()
for p in ignore:
default_dict.pop(p, None)
else:
default_dict = {}
return default_dict
def _setdefaults(self, defaults, *kwargs):
"""
Given a defaults dictionary, and any other dictionaries,
update those other dictionaries with information in defaults if
none of the other dictionaries contains that information.
"""
for k in defaults:
if all(kw.get(k, None) is None for kw in kwargs):
for kw in kwargs:
kw[k] = defaults[k]
def _makeline(self, x, y, kw, kwargs):
kw = kw.copy() # Don't modify the original kw.
kw.update(kwargs)
default_dict = self._getdefaults(None, kw)
self._setdefaults(default_dict, kw)
seg = mlines.Line2D(x, y, **kw)
return seg
def _makefill(self, x, y, kw, kwargs):
kw = kw.copy() # Don't modify the original kw.
kwargs = kwargs.copy()
# Ignore 'marker'-related properties as they aren't Polygon
# properties, but they are Line2D properties, and so they are
# likely to appear in the default cycler construction.
# This is done here to the defaults dictionary as opposed to the
# other two dictionaries because we do want to capture when a
# *user* explicitly specifies a marker which should be an error.
# We also want to prevent advancing the cycler if there are no
# defaults needed after ignoring the given properties.
ignores = {'marker', 'markersize', 'markeredgecolor',
'markerfacecolor', 'markeredgewidth'}
# Also ignore anything provided by *kwargs*.
for k, v in six.iteritems(kwargs):
if v is not None:
ignores.add(k)
# Only using the first dictionary to use as basis
# for getting defaults for back-compat reasons.
# Doing it with both seems to mess things up in
# various places (probably due to logic bugs elsewhere).
default_dict = self._getdefaults(ignores, kw)
self._setdefaults(default_dict, kw)
# Looks like we don't want "color" to be interpreted to
# mean both facecolor and edgecolor for some reason.
# So the "kw" dictionary is thrown out, and only its
# 'color' value is kept and translated as a 'facecolor'.
# This design should probably be revisited as it increases
# complexity.
facecolor = kw.get('color', None)
# Throw out 'color' as it is now handled as a facecolor
default_dict.pop('color', None)
# To get other properties set from the cycler
# modify the kwargs dictionary.
self._setdefaults(default_dict, kwargs)
seg = mpatches.Polygon(np.hstack((x[:, np.newaxis],
y[:, np.newaxis])),
facecolor=facecolor,
fill=kwargs.get('fill', True),
closed=kw['closed'])
self.set_patchprops(seg, **kwargs)
return seg
def _plot_args(self, tup, kwargs):
ret = []
if len(tup) > 1 and isinstance(tup[-1], six.string_types):
linestyle, marker, color = _process_plot_format(tup[-1])
tup = tup[:-1]
elif len(tup) == 3:
raise ValueError('third arg must be a format string')
else:
linestyle, marker, color = None, None, None
# Don't allow any None value; These will be up-converted
# to one element array of None which causes problems
# downstream.
if any(v is None for v in tup):
raise ValueError("x and y must not be None")
kw = {}
for k, v in zip(('linestyle', 'marker', 'color'),
(linestyle, marker, color)):
if v is not None:
kw[k] = v
if 'label' not in kwargs or kwargs['label'] is None:
kwargs['label'] = get_label(tup[-1], None)
if len(tup) == 2:
x = _check_1d(tup[0])
y = _check_1d(tup[-1])
else:
x, y = index_of(tup[-1])
x, y = self._xy_from_xy(x, y)
if self.command == 'plot':
func = self._makeline
else:
kw['closed'] = kwargs.get('closed', True)
func = self._makefill
ncx, ncy = x.shape[1], y.shape[1]
if ncx > 1 and ncy > 1 and ncx != ncy:
cbook.warn_deprecated("2.2", "cycling among columns of inputs "
"with non-matching shapes is deprecated.")
for j in xrange(max(ncx, ncy)):
seg = func(x[:, j % ncx], y[:, j % ncy], kw, kwargs)
ret.append(seg)
return ret
def _grab_next_args(self, *args, **kwargs):
while args:
this, args = args[:2], args[2:]
if args and isinstance(args[0], six.string_types):
this += args[0],
args = args[1:]
for seg in self._plot_args(this, kwargs):
yield seg
class _AxesBase(martist.Artist):
"""
"""
name = "rectilinear"
_shared_x_axes = cbook.Grouper()
_shared_y_axes = cbook.Grouper()
_twinned_axes = cbook.Grouper()
def __str__(self):
return "{0}({1[0]:g},{1[1]:g};{1[2]:g}x{1[3]:g})".format(
type(self).__name__, self._position.bounds)
def __init__(self, fig, rect,
facecolor=None, # defaults to rc axes.facecolor
frameon=True,
sharex=None, # use Axes instance's xaxis info
sharey=None, # use Axes instance's yaxis info
label='',
xscale=None,
yscale=None,
**kwargs
):
"""
Build an :class:`Axes` instance in
:class:`~matplotlib.figure.Figure` *fig* with
*rect=[left, bottom, width, height]* in
:class:`~matplotlib.figure.Figure` coordinates
Optional keyword arguments:
================ =========================================
Keyword Description
================ =========================================
*adjustable* [ 'box' | 'datalim' ]
*alpha* float: the alpha transparency (can be None)
*anchor* [ 'C', 'SW', 'S', 'SE', 'E', 'NE', 'N',
'NW', 'W' ]
*aspect* [ 'auto' | 'equal' | aspect_ratio ]
*autoscale_on* bool; whether to autoscale the *viewlim*
*axisbelow* [ bool | 'line' ] draw the grids
and ticks below or above most other artists,
or below lines but above patches
*cursor_props* a (*float*, *color*) tuple
*figure* a :class:`~matplotlib.figure.Figure`
instance
*frame_on* bool; whether to draw the axes frame
*label* the axes label
*navigate* bool
*navigate_mode* [ 'PAN' | 'ZOOM' | None ] the navigation
toolbar button status
*position* [left, bottom, width, height] in
class:`~matplotlib.figure.Figure` coords
*sharex* an class:`~matplotlib.axes.Axes` instance
to share the x-axis with
*sharey* an class:`~matplotlib.axes.Axes` instance
to share the y-axis with
*title* the title string
*visible* bool, whether the axes is visible
*xlabel* the xlabel
*xlim* (*xmin*, *xmax*) view limits
*xscale* [%(scale)s]
*xticklabels* sequence of strings
*xticks* sequence of floats
*ylabel* the ylabel strings
*ylim* (*ymin*, *ymax*) view limits
*yscale* [%(scale)s]
*yticklabels* sequence of strings
*yticks* sequence of floats
================ =========================================
""" % {'scale': ' | '.join(
[repr(x) for x in mscale.get_scale_names()])}
martist.Artist.__init__(self)
if isinstance(rect, mtransforms.Bbox):
self._position = rect
else:
self._position = mtransforms.Bbox.from_bounds(*rect)
if self._position.width < 0 or self._position.height < 0:
raise ValueError('Width and height specified must be non-negative')
self._originalPosition = self._position.frozen()
# self.set_axes(self)
self.axes = self
self._aspect = 'auto'
self._adjustable = 'box'
self._anchor = 'C'
self._sharex = sharex
self._sharey = sharey
if sharex is not None:
self._shared_x_axes.join(self, sharex)
if sharey is not None:
self._shared_y_axes.join(self, sharey)
self.set_label(label)
self.set_figure(fig)
self.set_axes_locator(kwargs.get("axes_locator", None))
self.spines = self._gen_axes_spines()
# this call may differ for non-sep axes, e.g., polar
self._init_axis()
if facecolor is None:
facecolor = rcParams['axes.facecolor']
self._facecolor = facecolor
self._frameon = frameon
self._axisbelow = rcParams['axes.axisbelow']
self._rasterization_zorder = None
self._hold = rcParams['axes.hold']
if self._hold is None:
self._hold = True
self._connected = {} # a dict from events to (id, func)
self.cla()
# funcs used to format x and y - fall back on major formatters
self.fmt_xdata = None
self.fmt_ydata = None
self._cachedRenderer = None
self.set_navigate(True)
self.set_navigate_mode(None)
if xscale:
self.set_xscale(xscale)
if yscale:
self.set_yscale(yscale)
if len(kwargs):
self.update(kwargs)
if self.xaxis is not None:
self._xcid = self.xaxis.callbacks.connect(
'units finalize', lambda: self._on_units_changed(scalex=True))
if self.yaxis is not None:
self._ycid = self.yaxis.callbacks.connect(
'units finalize', lambda: self._on_units_changed(scaley=True))
self.tick_params(
top=rcParams['xtick.top'] and rcParams['xtick.minor.top'],
bottom=rcParams['xtick.bottom'] and rcParams['xtick.minor.bottom'],
labeltop=(rcParams['xtick.labeltop'] and
rcParams['xtick.minor.top']),
labelbottom=(rcParams['xtick.labelbottom'] and
rcParams['xtick.minor.bottom']),
left=rcParams['ytick.left'] and rcParams['ytick.minor.left'],
right=rcParams['ytick.right'] and rcParams['ytick.minor.right'],
labelleft=(rcParams['ytick.labelleft'] and
rcParams['ytick.minor.left']),
labelright=(rcParams['ytick.labelright'] and
rcParams['ytick.minor.right']),
which='minor')
self.tick_params(
top=rcParams['xtick.top'] and rcParams['xtick.major.top'],
bottom=rcParams['xtick.bottom'] and rcParams['xtick.major.bottom'],
labeltop=(rcParams['xtick.labeltop'] and
rcParams['xtick.major.top']),
labelbottom=(rcParams['xtick.labelbottom'] and
rcParams['xtick.major.bottom']),
left=rcParams['ytick.left'] and rcParams['ytick.major.left'],
right=rcParams['ytick.right'] and rcParams['ytick.major.right'],
labelleft=(rcParams['ytick.labelleft'] and
rcParams['ytick.major.left']),
labelright=(rcParams['ytick.labelright'] and
rcParams['ytick.major.right']),
which='major')
self._layoutbox = None
self._poslayoutbox = None
def __getstate__(self):
# The renderer should be re-created by the figure, and then cached at
# that point.
state = super(_AxesBase, self).__getstate__()
state['_cachedRenderer'] = None
state.pop('_layoutbox')
state.pop('_poslayoutbox')
return state
def __setstate__(self, state):
self.__dict__ = state
# put the _remove_method back on all artists contained within the axes
for container_name in ['lines', 'collections', 'tables', 'patches',
'texts', 'images']:
container = getattr(self, container_name)
for artist in container:
artist._remove_method = container.remove
self._stale = True
self._layoutbox = None
self._poslayoutbox = None
def get_window_extent(self, *args, **kwargs):
"""
get the axes bounding box in display space; *args* and
*kwargs* are empty
"""
bbox = self.bbox
x_pad = self.xaxis.get_tick_padding()
y_pad = self.yaxis.get_tick_padding()
return mtransforms.Bbox([[bbox.x0 - x_pad, bbox.y0 - y_pad],
[bbox.x1 + x_pad, bbox.y1 + y_pad]])
def _init_axis(self):
"move this out of __init__ because non-separable axes don't use it"
self.xaxis = maxis.XAxis(self)
self.spines['bottom'].register_axis(self.xaxis)
self.spines['top'].register_axis(self.xaxis)
self.yaxis = maxis.YAxis(self)
self.spines['left'].register_axis(self.yaxis)
self.spines['right'].register_axis(self.yaxis)
self._update_transScale()
def set_figure(self, fig):
"""
Set the `.Figure` for this `.Axes`.
.. ACCEPTS: `.Figure`
Parameters
----------
fig : `.Figure`
"""
martist.Artist.set_figure(self, fig)
self.bbox = mtransforms.TransformedBbox(self._position,
fig.transFigure)
# these will be updated later as data is added
self.dataLim = mtransforms.Bbox.null()
self.viewLim = mtransforms.Bbox.unit()
self.transScale = mtransforms.TransformWrapper(
mtransforms.IdentityTransform())
self._set_lim_and_transforms()
def _set_lim_and_transforms(self):
"""
set the *_xaxis_transform*, *_yaxis_transform*,
*transScale*, *transData*, *transLimits* and *transAxes*
transformations.
.. note::
This method is primarily used by rectilinear projections
of the :class:`~matplotlib.axes.Axes` class, and is meant
to be overridden by new kinds of projection axes that need
different transformations and limits. (See
:class:`~matplotlib.projections.polar.PolarAxes` for an
example.
"""
self.transAxes = mtransforms.BboxTransformTo(self.bbox)
# Transforms the x and y axis separately by a scale factor.
# It is assumed that this part will have non-linear components
# (e.g., for a log scale).
self.transScale = mtransforms.TransformWrapper(
mtransforms.IdentityTransform())
# An affine transformation on the data, generally to limit the
# range of the axes
self.transLimits = mtransforms.BboxTransformFrom(
mtransforms.TransformedBbox(self.viewLim, self.transScale))
# The parentheses are important for efficiency here -- they
# group the last two (which are usually affines) separately
# from the first (which, with log-scaling can be non-affine).
self.transData = self.transScale + (self.transLimits + self.transAxes)
self._xaxis_transform = mtransforms.blended_transform_factory(
self.transData, self.transAxes)
self._yaxis_transform = mtransforms.blended_transform_factory(
self.transAxes, self.transData)
def get_xaxis_transform(self, which='grid'):
"""
Get the transformation used for drawing x-axis labels, ticks
and gridlines. The x-direction is in data coordinates and the
y-direction is in axis coordinates.
.. note::
This transformation is primarily used by the
:class:`~matplotlib.axis.Axis` class, and is meant to be
overridden by new kinds of projections that may need to
place axis elements in different locations.
"""
if which == 'grid':
return self._xaxis_transform
elif which == 'tick1':
# for cartesian projection, this is bottom spine
return self.spines['bottom'].get_spine_transform()
elif which == 'tick2':
# for cartesian projection, this is top spine
return self.spines['top'].get_spine_transform()
else:
raise ValueError('unknown value for which')
def get_xaxis_text1_transform(self, pad_points):
"""
Get the transformation used for drawing x-axis labels, which
will add the given amount of padding (in points) between the
axes and the label. The x-direction is in data coordinates
and the y-direction is in axis coordinates. Returns a
3-tuple of the form::
(transform, valign, halign)
where *valign* and *halign* are requested alignments for the
text.
.. note::
This transformation is primarily used by the
:class:`~matplotlib.axis.Axis` class, and is meant to be
overridden by new kinds of projections that may need to
place axis elements in different locations.
"""
labels_align = matplotlib.rcParams["xtick.alignment"]
return (self.get_xaxis_transform(which='tick1') +
mtransforms.ScaledTranslation(0, -1 * pad_points / 72.0,
self.figure.dpi_scale_trans),
"top", labels_align)
def get_xaxis_text2_transform(self, pad_points):
"""
Get the transformation used for drawing the secondary x-axis
labels, which will add the given amount of padding (in points)
between the axes and the label. The x-direction is in data
coordinates and the y-direction is in axis coordinates.
Returns a 3-tuple of the form::
(transform, valign, halign)
where *valign* and *halign* are requested alignments for the
text.
.. note::
This transformation is primarily used by the
:class:`~matplotlib.axis.Axis` class, and is meant to be
overridden by new kinds of projections that may need to
place axis elements in different locations.
"""
labels_align = matplotlib.rcParams["xtick.alignment"]
return (self.get_xaxis_transform(which='tick2') +
mtransforms.ScaledTranslation(0, pad_points / 72.0,
self.figure.dpi_scale_trans),
"bottom", labels_align)
def get_yaxis_transform(self, which='grid'):
"""
Get the transformation used for drawing y-axis labels, ticks
and gridlines. The x-direction is in axis coordinates and the
y-direction is in data coordinates.
.. note::
This transformation is primarily used by the
:class:`~matplotlib.axis.Axis` class, and is meant to be
overridden by new kinds of projections that may need to
place axis elements in different locations.
"""
if which == 'grid':
return self._yaxis_transform
elif which == 'tick1':
# for cartesian projection, this is bottom spine
return self.spines['left'].get_spine_transform()
elif which == 'tick2':
# for cartesian projection, this is top spine
return self.spines['right'].get_spine_transform()
else:
raise ValueError('unknown value for which')
def get_yaxis_text1_transform(self, pad_points):
"""
Get the transformation used for drawing y-axis labels, which
will add the given amount of padding (in points) between the
axes and the label. The x-direction is in axis coordinates
and the y-direction is in data coordinates. Returns a 3-tuple
of the form::
(transform, valign, halign)
where *valign* and *halign* are requested alignments for the
text.
.. note::
This transformation is primarily used by the
:class:`~matplotlib.axis.Axis` class, and is meant to be
overridden by new kinds of projections that may need to
place axis elements in different locations.
"""
labels_align = matplotlib.rcParams["ytick.alignment"]
return (self.get_yaxis_transform(which='tick1') +
mtransforms.ScaledTranslation(-1 * pad_points / 72.0, 0,
self.figure.dpi_scale_trans),
labels_align, "right")
def get_yaxis_text2_transform(self, pad_points):
"""
Get the transformation used for drawing the secondary y-axis
labels, which will add the given amount of padding (in points)
between the axes and the label. The x-direction is in axis
coordinates and the y-direction is in data coordinates.
Returns a 3-tuple of the form::
(transform, valign, halign)
where *valign* and *halign* are requested alignments for the
text.
.. note::
This transformation is primarily used by the
:class:`~matplotlib.axis.Axis` class, and is meant to be
overridden by new kinds of projections that may need to
place axis elements in different locations.
"""
labels_align = matplotlib.rcParams["ytick.alignment"]
return (self.get_yaxis_transform(which='tick2') +
mtransforms.ScaledTranslation(pad_points / 72.0, 0,
self.figure.dpi_scale_trans),
labels_align, "left")
def _update_transScale(self):
self.transScale.set(
mtransforms.blended_transform_factory(
self.xaxis.get_transform(), self.yaxis.get_transform()))
if hasattr(self, "lines"):
for line in self.lines:
try:
line._transformed_path.invalidate()
except AttributeError:
pass
def get_position(self, original=False):
"""
Get a copy of the axes rectangle as a `.Bbox`.
Parameters
----------
original : bool
If ``True``, return the original position. Otherwise return the
active position. For an explanation of the positions see
`.set_position`.
Returns
-------
pos : `.Bbox`
"""
if original:
return self._originalPosition.frozen()
else:
return self._position.frozen()
def set_position(self, pos, which='both'):
"""
Set the axes position.
Axes have two position attributes. The 'original' position is the
position allocated for the Axes. The 'active' position is the
position the Axes is actually drawn at. These positions are usually
the same unless a fixed aspect is set to the Axes. See `.set_aspect`
for details.
Parameters
----------
pos : [left, bottom, width, height] or `~matplotlib.transforms.Bbox`
The new position of the in `.Figure` coordinates.
which : ['both' | 'active' | 'original'], optional
Determines which position variables to change.
"""
self._set_position(pos, which='both')
# because this is being called externally to the library we
# zero the constrained layout parts.
self._layoutbox = None
self._poslayoutbox = None
def _set_position(self, pos, which='both'):
"""
private version of set_position. Call this internally
to get the same functionality of `get_position`, but not
to take the axis out of the constrained_layout
hierarchy.
"""
if not isinstance(pos, mtransforms.BboxBase):
pos = mtransforms.Bbox.from_bounds(*pos)
for ax in self._twinned_axes.get_siblings(self):
if which in ('both', 'active'):
ax._position.set(pos)
if which in ('both', 'original'):
ax._originalPosition.set(pos)
self.stale = True
def reset_position(self):
"""
Reset the active position to the original position.
This resets the a possible position change due to aspect constraints.
For an explanation of the positions see `.set_position`.
"""
for ax in self._twinned_axes.get_siblings(self):
pos = ax.get_position(original=True)
ax.set_position(pos, which='active')
def set_axes_locator(self, locator):
"""
Set the axes locator.
.. ACCEPTS: a callable object which takes an axes instance and
renderer and returns a bbox.
Parameters
----------
locator : callable
A locator function, which takes an axes and a renderer and returns
a bbox.
"""
self._axes_locator = locator
self.stale = True
def get_axes_locator(self):
"""
Return the axes_locator.
"""
return self._axes_locator
def _set_artist_props(self, a):
"""set the boilerplate props for artists added to axes"""
a.set_figure(self.figure)
if not a.is_transform_set():
a.set_transform(self.transData)
a.axes = self
if a.mouseover:
self.mouseover_set.add(a)
def _gen_axes_patch(self):
"""
Returns the patch used to draw the background of the axes. It
is also used as the clipping path for any data elements on the
axes.
In the standard axes, this is a rectangle, but in other
projections it may not be.
.. note::
Intended to be overridden by new projection types.
"""
return mpatches.Rectangle((0.0, 0.0), 1.0, 1.0)
def _gen_axes_spines(self, locations=None, offset=0.0, units='inches'):
"""
Returns a dict whose keys are spine names and values are
Line2D or Patch instances. Each element is used to draw a
spine of the axes.
In the standard axes, this is a single line segment, but in
other projections it may not be.
.. note::
Intended to be overridden by new projection types.
"""
return OrderedDict([
('left', mspines.Spine.linear_spine(self, 'left')),
('right', mspines.Spine.linear_spine(self, 'right')),
('bottom', mspines.Spine.linear_spine(self, 'bottom')),
('top', mspines.Spine.linear_spine(self, 'top'))])
def cla(self):
"""Clear the current axes."""
# Note: this is called by Axes.__init__()
# stash the current visibility state
if hasattr(self, 'patch'):
patch_visible = self.patch.get_visible()
else:
patch_visible = True
xaxis_visible = self.xaxis.get_visible()
yaxis_visible = self.yaxis.get_visible()
self.xaxis.cla()
self.yaxis.cla()
for name, spine in six.iteritems(self.spines):
spine.cla()
self.ignore_existing_data_limits = True
self.callbacks = cbook.CallbackRegistry()
if self._sharex is not None:
# major and minor are axis.Ticker class instances with
# locator and formatter attributes
self.xaxis.major = self._sharex.xaxis.major
self.xaxis.minor = self._sharex.xaxis.minor
x0, x1 = self._sharex.get_xlim()
self.set_xlim(x0, x1, emit=False, auto=None)
self.xaxis._scale = mscale.scale_factory(
self._sharex.xaxis.get_scale(), self.xaxis)
else:
self.xaxis._set_scale('linear')
try:
self.set_xlim(0, 1)
except TypeError:
pass
if self._sharey is not None:
self.yaxis.major = self._sharey.yaxis.major
self.yaxis.minor = self._sharey.yaxis.minor
y0, y1 = self._sharey.get_ylim()
self.set_ylim(y0, y1, emit=False, auto=None)
self.yaxis._scale = mscale.scale_factory(
self._sharey.yaxis.get_scale(), self.yaxis)
else:
self.yaxis._set_scale('linear')
try:
self.set_ylim(0, 1)
except TypeError:
pass
# update the minor locator for x and y axis based on rcParams
if (rcParams['xtick.minor.visible']):
self.xaxis.set_minor_locator(mticker.AutoMinorLocator())
if (rcParams['ytick.minor.visible']):
self.yaxis.set_minor_locator(mticker.AutoMinorLocator())
self._autoscaleXon = True
self._autoscaleYon = True
self._xmargin = rcParams['axes.xmargin']
self._ymargin = rcParams['axes.ymargin']
self._tight = None
self._use_sticky_edges = True
self._update_transScale() # needed?
self._get_lines = _process_plot_var_args(self)
self._get_patches_for_fill = _process_plot_var_args(self, 'fill')
self._gridOn = rcParams['axes.grid']
self.lines = []
self.patches = []
self.texts = []
self.tables = []
self.artists = []
self.images = []
self.mouseover_set = set()
self._current_image = None # strictly for pyplot via _sci, _gci
self.legend_ = None
self.collections = [] # collection.Collection instances
self.containers = []
self.grid(False) # Disable grid on init to use rcParameter
self.grid(self._gridOn, which=rcParams['axes.grid.which'],
axis=rcParams['axes.grid.axis'])
props = font_manager.FontProperties(
size=rcParams['axes.titlesize'],
weight=rcParams['axes.titleweight'])
self.title = mtext.Text(
x=0.5, y=1.0, text='',
fontproperties=props,
verticalalignment='baseline',
horizontalalignment='center',
)
self._left_title = mtext.Text(
x=0.0, y=1.0, text='',
fontproperties=props.copy(),
verticalalignment='baseline',
horizontalalignment='left', )
self._right_title = mtext.Text(
x=1.0, y=1.0, text='',
fontproperties=props.copy(),
verticalalignment='baseline',
horizontalalignment='right',
)
title_offset_points = rcParams['axes.titlepad']
# refactor this out so it can be called in ax.set_title if
# pad argument used...
self._set_title_offset_trans(title_offset_points)
for _title in (self.title, self._left_title, self._right_title):
self._set_artist_props(_title)
# The patch draws the background of the axes. We want this to be below
# the other artists. We use the frame to draw the edges so we are
# setting the edgecolor to None.
self.patch = self._gen_axes_patch()
self.patch.set_figure(self.figure)
self.patch.set_facecolor(self._facecolor)
self.patch.set_edgecolor('None')
self.patch.set_linewidth(0)
self.patch.set_transform(self.transAxes)
self.set_axis_on()
self.xaxis.set_clip_path(self.patch)
self.yaxis.set_clip_path(self.patch)
self._shared_x_axes.clean()
self._shared_y_axes.clean()
if self._sharex:
self.xaxis.set_visible(xaxis_visible)
self.patch.set_visible(patch_visible)
if self._sharey:
self.yaxis.set_visible(yaxis_visible)
self.patch.set_visible(patch_visible)
self.stale = True
@property
@cbook.deprecated("2.1", alternative="Axes.patch")
def axesPatch(self):
return self.patch
def clear(self):
"""Clear the axes."""
self.cla()
def get_facecolor(self):
"""Get the Axes facecolor."""
return self.patch.get_facecolor()
get_fc = get_facecolor
def set_facecolor(self, color):
"""Set the Axes facecolor.
.. ACCEPTS: color
Parameters
----------
color : color
"""
self._facecolor = color
return self.patch.set_facecolor(color)
set_fc = set_facecolor
def _set_title_offset_trans(self, title_offset_points):
"""
Set the offset for the title either from rcParams['axes.titlepad']
or from set_title kwarg ``pad``.
"""
self.titleOffsetTrans = mtransforms.ScaledTranslation(
0.0, title_offset_points / 72.0,
self.figure.dpi_scale_trans)
for _title in (self.title, self._left_title, self._right_title):
_title.set_transform(self.transAxes + self.titleOffsetTrans)
_title.set_clip_box(None)
def set_prop_cycle(self, *args, **kwargs):
"""
Set the property cycle for any future plot commands on this Axes.
set_prop_cycle(arg)
set_prop_cycle(label, itr)
set_prop_cycle(label1=itr1[, label2=itr2[, ...]])
Form 1 simply sets given `Cycler` object.
Form 2 creates and sets a `Cycler` from a label and an iterable.
Form 3 composes and sets a `Cycler` as an inner product of the
pairs of keyword arguments. In other words, all of the
iterables are cycled simultaneously, as if through zip().
Parameters
----------
arg : Cycler
Set the given Cycler.
Can also be `None` to reset to the cycle defined by the
current style.
label : str
The property key. Must be a valid `Artist` property.
For example, 'color' or 'linestyle'. Aliases are allowed,
such as 'c' for 'color' and 'lw' for 'linewidth'.
itr : iterable
Finite-length iterable of the property values. These values
are validated and will raise a ValueError if invalid.
See Also
--------
:func:`cycler` Convenience function for creating your
own cyclers.
"""
if args and kwargs:
raise TypeError("Cannot supply both positional and keyword "
"arguments to this method.")
if len(args) == 1 and args[0] is None:
prop_cycle = None
else:
prop_cycle = cycler(*args, **kwargs)
self._get_lines.set_prop_cycle(prop_cycle)
self._get_patches_for_fill.set_prop_cycle(prop_cycle)
@cbook.deprecated('1.5', alternative='`.set_prop_cycle`')
def set_color_cycle(self, clist):
"""
Set the color cycle for any future plot commands on this Axes.
Parameters
----------
clist
A list of mpl color specifiers.
"""
if clist is None:
# Calling set_color_cycle() or set_prop_cycle() with None
# effectively resets the cycle, but you can't do
# set_prop_cycle('color', None). So we are special-casing this.
self.set_prop_cycle(None)
else:
self.set_prop_cycle('color', clist)
@cbook.deprecated("2.0")
def ishold(self):
"""return the HOLD status of the axes
The `hold` mechanism is deprecated and will be removed in
v3.0.
"""
return self._hold
@cbook.deprecated("2.0", message=_hold_msg)
def hold(self, b=None):
"""
Set the hold state.
The ``hold`` mechanism is deprecated and will be removed in
v3.0. The behavior will remain consistent with the
long-time default value of True.
If *hold* is *None* (default), toggle the *hold* state. Else
set the *hold* state to boolean value *b*.
Examples::
# toggle hold
hold()
# turn hold on
hold(True)
# turn hold off
hold(False)
When hold is *True*, subsequent plot commands will be added to
the current axes. When hold is *False*, the current axes and
figure will be cleared on the next plot command
"""
if b is None:
self._hold = not self._hold
else:
self._hold = b
def get_aspect(self):
return self._aspect
def set_aspect(self, aspect, adjustable=None, anchor=None, share=False):
"""
Set the aspect of the axis scaling, i.e. the ratio of y-unit to x-unit.
Parameters
----------
aspect : ['auto' | 'equal'] or num
Possible values:
======== ================================================
value description
======== ================================================
'auto' automatic; fill the position rectangle with data
'equal' same scaling from data to plot units for x and y
num a circle will be stretched such that the height
is num times the width. aspect=1 is the same as
aspect='equal'.
======== ================================================
adjustable : None or ['box' | 'datalim'], optional
If not ``None``, this defines which parameter will be adjusted to
meet the required aspect. See `.set_adjustable` for further
details.
anchor : None or str or 2-tuple of float, optional
If not ``None``, this defines where the Axes will be drawn if there
is extra space due to aspect constraints. The most common way to
to specify the anchor are abbreviations of cardinal directions:
===== =====================
value description
===== =====================
'C' centered
'SW' lower left corner
'S' middle of bottom edge
'SE' lower right corner
etc.
===== =====================
See `.set_anchor` for further details.
share : bool, optional
If ``True``, apply the settings to all shared Axes.
Default is ``False``.
See Also
--------
matplotlib.axes.Axes.set_adjustable
defining the parameter to adjust in order to meet the required
aspect.
matplotlib.axes.Axes.set_anchor
defining the position in case of extra space.
"""
if not (isinstance(aspect, six.string_types)
and aspect in ('equal', 'auto')):
aspect = float(aspect) # raise ValueError if necessary
if share:
axes = set(self._shared_x_axes.get_siblings(self)
+ self._shared_y_axes.get_siblings(self))
else:
axes = [self]
for ax in axes:
ax._aspect = aspect
if adjustable is None:
adjustable = self._adjustable
self.set_adjustable(adjustable, share=share) # Handle sharing.
if anchor is not None:
self.set_anchor(anchor, share=share)
self.stale = True
def get_adjustable(self):
return self._adjustable
def set_adjustable(self, adjustable, share=False):
"""
Define which parameter the Axes will change to achieve a given aspect.
Parameters
----------
adjustable : ['box' | 'datalim']
If 'box', change the physical dimensions of the Axes.
If 'datalim', change the ``x`` or ``y`` data limits.
share : bool, optional
If ``True``, apply the settings to all shared Axes.
Default is ``False``.
.. ACCEPTS: [ 'box' | 'datalim']
See Also
--------
matplotlib.axes.Axes.set_aspect
for a description of aspect handling.
Notes
-----
Shared Axes (of which twinned Axes are a special case)
impose restrictions on how aspect ratios can be imposed.
For twinned Axes, use 'datalim'. For Axes that share both
x and y, use 'box'. Otherwise, either 'datalim' or 'box'
may be used. These limitations are partly a requirement
to avoid over-specification, and partly a result of the
particular implementation we are currently using, in
which the adjustments for aspect ratios are done sequentially
and independently on each Axes as it is drawn.
"""
if adjustable == 'box-forced':
warnings.warn("The 'box-forced' keyword argument is deprecated"
" since 2.2.", cbook.mplDeprecation)
if adjustable not in ('box', 'datalim', 'box-forced'):
raise ValueError("argument must be 'box', or 'datalim'")
if share:
axes = set(self._shared_x_axes.get_siblings(self)
+ self._shared_y_axes.get_siblings(self))
else:
axes = [self]
for ax in axes:
ax._adjustable = adjustable
self.stale = True
def get_anchor(self):
"""
Get the anchor location.
See Also
--------
matplotlib.axes.Axes.set_anchor
for a description of the anchor.
matplotlib.axes.Axes.set_aspect
for a description of aspect handling.
"""
return self._anchor
def set_anchor(self, anchor, share=False):
"""
Define the anchor location.
The actual drawing area (active position) of the Axes may be smaller
than the Bbox (original position) when a fixed aspect is required. The
anchor defines where the drawing area will be located within the
available space.
.. ACCEPTS: [ 'C' | 'SW' | 'S' | 'SE' | 'E' | 'NE' | 'N' | 'NW' | 'W' ]
Parameters
----------
anchor : str or 2-tuple of floats
The anchor position may be either:
- a sequence (*cx*, *cy*). *cx* and *cy* may range from 0
to 1, where 0 is left or bottom and 1 is right or top.
- a string using cardinal directions as abbreviation:
- 'C' for centered
- 'S' (south) for bottom-center
- 'SW' (south west) for bottom-left
- etc.
Here is an overview of the possible positions:
+------+------+------+
| 'NW' | 'N' | 'NE' |
+------+------+------+
| 'W' | 'C' | 'E' |
+------+------+------+
| 'SW' | 'S' | 'SE' |
+------+------+------+
share : bool, optional
If ``True``, apply the settings to all shared Axes.
Default is ``False``.
See Also
--------
matplotlib.axes.Axes.set_aspect
for a description of aspect handling.
"""
if not (anchor in mtransforms.Bbox.coefs or len(anchor) == 2):
raise ValueError('argument must be among %s' %
', '.join(mtransforms.Bbox.coefs))
if share:
axes = set(self._shared_x_axes.get_siblings(self)
+ self._shared_y_axes.get_siblings(self))
else:
axes = [self]
for ax in axes:
ax._anchor = anchor
self.stale = True
def get_data_ratio(self):
"""
Returns the aspect ratio of the raw data.
This method is intended to be overridden by new projection
types.
"""
xmin, xmax = self.get_xbound()
ymin, ymax = self.get_ybound()
xsize = max(abs(xmax - xmin), 1e-30)
ysize = max(abs(ymax - ymin), 1e-30)
return ysize / xsize
def get_data_ratio_log(self):
"""
Returns the aspect ratio of the raw data in log scale.
Will be used when both axis scales are in log.
"""
xmin, xmax = self.get_xbound()
ymin, ymax = self.get_ybound()
xsize = max(abs(math.log10(xmax) - math.log10(xmin)), 1e-30)
ysize = max(abs(math.log10(ymax) - math.log10(ymin)), 1e-30)
return ysize / xsize
def apply_aspect(self, position=None):
"""
Adjust the Axes for a specified data aspect ratio.
Depending on `.get_adjustable` this will modify either the Axes box
(position) or the view limits. In the former case, `.get_anchor`
will affect the position.
Notes
-----
This is called automatically when each Axes is drawn. You may need
to call it yourself if you need to update the Axes position and/or
view limits before the Figure is drawn.
See Also
--------
matplotlib.axes.Axes.set_aspect
for a description of aspect ratio handling.
matplotlib.axes.Axes.set_adjustable
defining the parameter to adjust in order to meet the required
aspect.
matplotlib.axes.Axes.set_anchor
defining the position in case of extra space.
"""
if position is None:
position = self.get_position(original=True)
aspect = self.get_aspect()
if self.name != 'polar':
xscale, yscale = self.get_xscale(), self.get_yscale()
if xscale == "linear" and yscale == "linear":
aspect_scale_mode = "linear"
elif xscale == "log" and yscale == "log":
aspect_scale_mode = "log"
elif ((xscale == "linear" and yscale == "log") or
(xscale == "log" and yscale == "linear")):
if aspect != "auto":
warnings.warn(
'aspect is not supported for Axes with xscale=%s, '
'yscale=%s' % (xscale, yscale))
aspect = "auto"
else: # some custom projections have their own scales.
pass
else:
aspect_scale_mode = "linear"
if aspect == 'auto':
self._set_position(position, which='active')
return
if aspect == 'equal':
A = 1
else:
A = aspect
figW, figH = self.get_figure().get_size_inches()
fig_aspect = figH / figW
if self._adjustable in ['box', 'box-forced']:
if self in self._twinned_axes:
raise RuntimeError("Adjustable 'box' is not allowed in a"
" twinned Axes. Use 'datalim' instead.")
if aspect_scale_mode == "log":
box_aspect = A * self.get_data_ratio_log()
else:
box_aspect = A * self.get_data_ratio()
pb = position.frozen()
pb1 = pb.shrunk_to_aspect(box_aspect, pb, fig_aspect)
self._set_position(pb1.anchored(self.get_anchor(), pb), 'active')
return
# reset active to original in case it had been changed
# by prior use of 'box'
self._set_position(position, which='active')
xmin, xmax = self.get_xbound()
ymin, ymax = self.get_ybound()
if aspect_scale_mode == "log":
xmin, xmax = math.log10(xmin), math.log10(xmax)
ymin, ymax = math.log10(ymin), math.log10(ymax)
xsize = max(abs(xmax - xmin), 1e-30)
ysize = max(abs(ymax - ymin), 1e-30)
l, b, w, h = position.bounds
box_aspect = fig_aspect * (h / w)
data_ratio = box_aspect / A
y_expander = (data_ratio * xsize / ysize - 1.0)
# If y_expander > 0, the dy/dx viewLim ratio needs to increase
if abs(y_expander) < 0.005:
return
if aspect_scale_mode == "log":
dL = self.dataLim
dL_width = math.log10(dL.x1) - math.log10(dL.x0)
dL_height = math.log10(dL.y1) - math.log10(dL.y0)
xr = 1.05 * dL_width
yr = 1.05 * dL_height
else:
dL = self.dataLim
xr = 1.05 * dL.width
yr = 1.05 * dL.height
xmarg = xsize - xr
ymarg = ysize - yr
Ysize = data_ratio * xsize
Xsize = ysize / data_ratio
Xmarg = Xsize - xr
Ymarg = Ysize - yr
# Setting these targets to, e.g., 0.05*xr does not seem to
# help.
xm = 0
ym = 0
shared_x = self in self._shared_x_axes
shared_y = self in self._shared_y_axes
# Not sure whether we need this check:
if shared_x and shared_y:
raise RuntimeError("adjustable='datalim' is not allowed when both"
" axes are shared.")
# If y is shared, then we are only allowed to change x, etc.
if shared_y:
adjust_y = False
else:
if xmarg > xm and ymarg > ym:
adjy = ((Ymarg > 0 and y_expander < 0) or
(Xmarg < 0 and y_expander > 0))
else:
adjy = y_expander > 0
adjust_y = shared_x or adjy # (Ymarg > xmarg)
if adjust_y:
yc = 0.5 * (ymin + ymax)
y0 = yc - Ysize / 2.0
y1 = yc + Ysize / 2.0
if aspect_scale_mode == "log":
self.set_ybound((10. ** y0, 10. ** y1))
else:
self.set_ybound((y0, y1))
else:
xc = 0.5 * (xmin + xmax)
x0 = xc - Xsize / 2.0
x1 = xc + Xsize / 2.0
if aspect_scale_mode == "log":
self.set_xbound((10. ** x0, 10. ** x1))
else:
self.set_xbound((x0, x1))
def axis(self, *v, **kwargs):
"""Set axis properties.
Valid signatures::
xmin, xmax, ymin, ymax = axis()
xmin, xmax, ymin, ymax = axis(list_arg)
xmin, xmax, ymin, ymax = axis(string_arg)
xmin, xmax, ymin, ymax = axis(**kwargs)
Parameters
----------
v : list of float or {'on', 'off', 'equal', 'tight', 'scaled',\
'normal', 'auto', 'image', 'square'}
Optional positional argument
Axis data limits set from a list; or a command relating to axes:
========== ================================================
Value Description
========== ================================================
'on' Toggle axis lines and labels on
'off' Toggle axis lines and labels off
'equal' Equal scaling by changing limits
'scaled' Equal scaling by changing box dimensions
'tight' Limits set such that all data is shown
'auto' Automatic scaling, fill rectangle with data
'normal' Same as 'auto'; deprecated
'image' 'scaled' with axis limits equal to data limits
'square' Square plot; similar to 'scaled', but initially\
forcing xmax-xmin = ymax-ymin
========== ================================================
emit : bool, optional
Passed to set_{x,y}lim functions, if observers
are notified of axis limit change
xmin, ymin, xmax, ymax : float, optional
The axis limits to be set
Returns
-------
xmin, xmax, ymin, ymax : float
The axis limits
"""
if len(v) == 0 and len(kwargs) == 0:
xmin, xmax = self.get_xlim()
ymin, ymax = self.get_ylim()
return xmin, xmax, ymin, ymax
emit = kwargs.get('emit', True)
if len(v) == 1 and isinstance(v[0], six.string_types):
s = v[0].lower()
if s == 'on':
self.set_axis_on()
elif s == 'off':
self.set_axis_off()
elif s in ('equal', 'tight', 'scaled', 'normal',
'auto', 'image', 'square'):
self.set_autoscale_on(True)
self.set_aspect('auto')
self.autoscale_view(tight=False)
# self.apply_aspect()
if s == 'equal':
self.set_aspect('equal', adjustable='datalim')
elif s == 'scaled':
self.set_aspect('equal', adjustable='box', anchor='C')
self.set_autoscale_on(False) # Req. by Mark Bakker
elif s == 'tight':
self.autoscale_view(tight=True)
self.set_autoscale_on(False)
elif s == 'image':
self.autoscale_view(tight=True)
self.set_autoscale_on(False)
self.set_aspect('equal', adjustable='box', anchor='C')
elif s == 'square':
self.set_aspect('equal', adjustable='box', anchor='C')
self.set_autoscale_on(False)
xlim = self.get_xlim()
ylim = self.get_ylim()
edge_size = max(np.diff(xlim), np.diff(ylim))
self.set_xlim([xlim[0], xlim[0] + edge_size],
emit=emit, auto=False)
self.set_ylim([ylim[0], ylim[0] + edge_size],
emit=emit, auto=False)
else:
raise ValueError('Unrecognized string %s to axis; '
'try on or off' % s)
xmin, xmax = self.get_xlim()
ymin, ymax = self.get_ylim()
return xmin, xmax, ymin, ymax
try:
v[0]
except IndexError:
xmin = kwargs.get('xmin', None)
xmax = kwargs.get('xmax', None)
auto = False # turn off autoscaling, unless...
if xmin is None and xmax is None:
auto = None # leave autoscaling state alone
xmin, xmax = self.set_xlim(xmin, xmax, emit=emit, auto=auto)
ymin = kwargs.get('ymin', None)
ymax = kwargs.get('ymax', None)
auto = False # turn off autoscaling, unless...
if ymin is None and ymax is None:
auto = None # leave autoscaling state alone
ymin, ymax = self.set_ylim(ymin, ymax, emit=emit, auto=auto)
return xmin, xmax, ymin, ymax
v = v[0]
if len(v) != 4:
raise ValueError('v must contain [xmin xmax ymin ymax]')
self.set_xlim([v[0], v[1]], emit=emit, auto=False)
self.set_ylim([v[2], v[3]], emit=emit, auto=False)
return v
def get_legend(self):
"""Return the `Legend` instance, or None if no legend is defined."""
return self.legend_
def get_images(self):
"""return a list of Axes images contained by the Axes"""
return cbook.silent_list('AxesImage', self.images)
def get_lines(self):
"""Return a list of lines contained by the Axes"""
return cbook.silent_list('Line2D', self.lines)
def get_xaxis(self):
"""Return the XAxis instance."""
return self.xaxis
def get_xgridlines(self):
"""Get the x grid lines as a list of `Line2D` instances."""
return cbook.silent_list('Line2D xgridline',
self.xaxis.get_gridlines())
def get_xticklines(self):
"""Get the x tick lines as a list of `Line2D` instances."""
return cbook.silent_list('Line2D xtickline',
self.xaxis.get_ticklines())
def get_yaxis(self):
"""Return the YAxis instance."""
return self.yaxis
def get_ygridlines(self):
"""Get the y grid lines as a list of `Line2D` instances."""
return cbook.silent_list('Line2D ygridline',
self.yaxis.get_gridlines())
def get_yticklines(self):
"""Get the y tick lines as a list of `Line2D` instances."""
return cbook.silent_list('Line2D ytickline',
self.yaxis.get_ticklines())
# Adding and tracking artists
def _sci(self, im):
"""
helper for :func:`~matplotlib.pyplot.sci`;
do not use elsewhere.
"""
if isinstance(im, matplotlib.contour.ContourSet):
if im.collections[0] not in self.collections:
raise ValueError(
"ContourSet must be in current Axes")
elif im not in self.images and im not in self.collections:
raise ValueError(
"Argument must be an image, collection, or ContourSet in "
"this Axes")
self._current_image = im
def _gci(self):
"""
Helper for :func:`~matplotlib.pyplot.gci`;
do not use elsewhere.
"""
return self._current_image
def has_data(self):
"""
Return *True* if any artists have been added to axes.
This should not be used to determine whether the *dataLim*
need to be updated, and may not actually be useful for
anything.
"""
return (
len(self.collections) +
len(self.images) +
len(self.lines) +
len(self.patches)) > 0
def add_artist(self, a):
"""Add any :class:`~matplotlib.artist.Artist` to the axes.
Use `add_artist` only for artists for which there is no dedicated
"add" method; and if necessary, use a method such as `update_datalim`
to manually update the dataLim if the artist is to be included in
autoscaling.
Returns the artist.
"""
a.axes = self
self.artists.append(a)
self._set_artist_props(a)
a.set_clip_path(self.patch)
a._remove_method = lambda h: self.artists.remove(h)
self.stale = True
return a
def add_collection(self, collection, autolim=True):
"""
Add a :class:`~matplotlib.collections.Collection` instance
to the axes.
Returns the collection.
"""
label = collection.get_label()
if not label:
collection.set_label('_collection%d' % len(self.collections))
self.collections.append(collection)
self._set_artist_props(collection)
if collection.get_clip_path() is None:
collection.set_clip_path(self.patch)
if autolim:
self.update_datalim(collection.get_datalim(self.transData))
collection._remove_method = lambda h: self.collections.remove(h)
self.stale = True
return collection
def add_image(self, image):
"""
Add a :class:`~matplotlib.image.AxesImage` to the axes.
Returns the image.
"""
self._set_artist_props(image)
if not image.get_label():
image.set_label('_image%d' % len(self.images))
self.images.append(image)
image._remove_method = lambda h: self.images.remove(h)
self.stale = True
return image
def _update_image_limits(self, image):
xmin, xmax, ymin, ymax = image.get_extent()
self.axes.update_datalim(((xmin, ymin), (xmax, ymax)))
def add_line(self, line):
"""
Add a :class:`~matplotlib.lines.Line2D` to the list of plot
lines
Returns the line.
"""
self._set_artist_props(line)
if line.get_clip_path() is None:
line.set_clip_path(self.patch)
self._update_line_limits(line)
if not line.get_label():
line.set_label('_line%d' % len(self.lines))
self.lines.append(line)
line._remove_method = lambda h: self.lines.remove(h)
self.stale = True
return line
def _add_text(self, txt):
"""
"""
self._set_artist_props(txt)
self.texts.append(txt)
txt._remove_method = lambda h: self.texts.remove(h)
self.stale = True
return txt
def _update_line_limits(self, line):
"""
Figures out the data limit of the given line, updating self.dataLim.
"""
path = line.get_path()
if path.vertices.size == 0:
return
line_trans = line.get_transform()
if line_trans == self.transData:
data_path = path
elif any(line_trans.contains_branch_seperately(self.transData)):
# identify the transform to go from line's coordinates
# to data coordinates
trans_to_data = line_trans - self.transData
# if transData is affine we can use the cached non-affine component
# of line's path. (since the non-affine part of line_trans is
# entirely encapsulated in trans_to_data).
if self.transData.is_affine:
line_trans_path = line._get_transformed_path()
na_path, _ = line_trans_path.get_transformed_path_and_affine()
data_path = trans_to_data.transform_path_affine(na_path)
else:
data_path = trans_to_data.transform_path(path)
else:
# for backwards compatibility we update the dataLim with the
# coordinate range of the given path, even though the coordinate
# systems are completely different. This may occur in situations
# such as when ax.transAxes is passed through for absolute
# positioning.
data_path = path
if data_path.vertices.size > 0:
updatex, updatey = line_trans.contains_branch_seperately(
self.transData)
self.dataLim.update_from_path(data_path,
self.ignore_existing_data_limits,
updatex=updatex,
updatey=updatey)
self.ignore_existing_data_limits = False
def add_patch(self, p):
"""
Add a :class:`~matplotlib.patches.Patch` *p* to the list of
axes patches; the clipbox will be set to the Axes clipping
box. If the transform is not set, it will be set to
:attr:`transData`.
Returns the patch.
"""
self._set_artist_props(p)
if p.get_clip_path() is None:
p.set_clip_path(self.patch)
self._update_patch_limits(p)
self.patches.append(p)
p._remove_method = lambda h: self.patches.remove(h)
return p
def _update_patch_limits(self, patch):
"""update the data limits for patch *p*"""
# hist can add zero height Rectangles, which is useful to keep
# the bins, counts and patches lined up, but it throws off log
# scaling. We'll ignore rects with zero height or width in
# the auto-scaling
# cannot check for '==0' since unitized data may not compare to zero
# issue #2150 - we update the limits if patch has non zero width
# or height.
if (isinstance(patch, mpatches.Rectangle) and
((not patch.get_width()) and (not patch.get_height()))):
return
vertices = patch.get_path().vertices
if vertices.size > 0:
xys = patch.get_patch_transform().transform(vertices)
if patch.get_data_transform() != self.transData:
patch_to_data = (patch.get_data_transform() -
self.transData)
xys = patch_to_data.transform(xys)
updatex, updatey = patch.get_transform().\
contains_branch_seperately(self.transData)
self.update_datalim(xys, updatex=updatex,
updatey=updatey)
def add_table(self, tab):
"""
Add a :class:`~matplotlib.table.Table` instance to the
list of axes tables
Parameters
----------
tab: `matplotlib.table.Table`
Table instance
Returns
-------
`matplotlib.table.Table`: the table.
"""
self._set_artist_props(tab)
self.tables.append(tab)
tab.set_clip_path(self.patch)
tab._remove_method = lambda h: self.tables.remove(h)
return tab
def add_container(self, container):
"""
Add a :class:`~matplotlib.container.Container` instance
to the axes.
Returns the collection.
"""
label = container.get_label()
if not label:
container.set_label('_container%d' % len(self.containers))
self.containers.append(container)
container.set_remove_method(lambda h: self.containers.remove(h))
return container
def _on_units_changed(self, scalex=False, scaley=False):
"""
Callback for processing changes to axis units.
Currently forces updates of data limits and view limits.
"""
self.relim()
self.autoscale_view(scalex=scalex, scaley=scaley)
def relim(self, visible_only=False):
"""
Recompute the data limits based on current artists. If you want to
exclude invisible artists from the calculation, set
``visible_only=True``
At present, :class:`~matplotlib.collections.Collection`
instances are not supported.
"""
# Collections are deliberately not supported (yet); see
# the TODO note in artists.py.
self.dataLim.ignore(True)
self.dataLim.set_points(mtransforms.Bbox.null().get_points())
self.ignore_existing_data_limits = True
for line in self.lines:
if not visible_only or line.get_visible():
self._update_line_limits(line)
for p in self.patches:
if not visible_only or p.get_visible():
self._update_patch_limits(p)
for image in self.images:
if not visible_only or image.get_visible():
self._update_image_limits(image)
def update_datalim(self, xys, updatex=True, updatey=True):
"""
Update the data lim bbox with seq of xy tups or equiv. 2-D array
"""
# if no data is set currently, the bbox will ignore its
# limits and set the bound to be the bounds of the xydata.
# Otherwise, it will compute the bounds of it's current data
# and the data in xydata
xys = np.asarray(xys)
if not len(xys):
return
self.dataLim.update_from_data_xy(xys, self.ignore_existing_data_limits,
updatex=updatex, updatey=updatey)
self.ignore_existing_data_limits = False
def update_datalim_bounds(self, bounds):
"""
Update the datalim to include the given
:class:`~matplotlib.transforms.Bbox` *bounds*
"""
self.dataLim.set(mtransforms.Bbox.union([self.dataLim, bounds]))
def _process_unit_info(self, xdata=None, ydata=None, kwargs=None):
"""Look for unit *kwargs* and update the axis instances as necessary"""
if self.xaxis is None or self.yaxis is None:
return
if xdata is not None:
# we only need to update if there is nothing set yet.
if not self.xaxis.have_units():
self.xaxis.update_units(xdata)
if ydata is not None:
# we only need to update if there is nothing set yet.
if not self.yaxis.have_units():
self.yaxis.update_units(ydata)
# process kwargs 2nd since these will override default units
if kwargs is not None:
xunits = kwargs.pop('xunits', self.xaxis.units)
if self.name == 'polar':
xunits = kwargs.pop('thetaunits', xunits)
if xunits != self.xaxis.units:
self.xaxis.set_units(xunits)
# If the units being set imply a different converter,
# we need to update.
if xdata is not None:
self.xaxis.update_units(xdata)
yunits = kwargs.pop('yunits', self.yaxis.units)
if self.name == 'polar':
yunits = kwargs.pop('runits', yunits)
if yunits != self.yaxis.units:
self.yaxis.set_units(yunits)
# If the units being set imply a different converter,
# we need to update.
if ydata is not None:
self.yaxis.update_units(ydata)
return kwargs
def in_axes(self, mouseevent):
"""
Return *True* if the given *mouseevent* (in display coords)
is in the Axes
"""
return self.patch.contains(mouseevent)[0]
def get_autoscale_on(self):
"""
Get whether autoscaling is applied for both axes on plot commands
"""
return self._autoscaleXon and self._autoscaleYon
def get_autoscalex_on(self):
"""
Get whether autoscaling for the x-axis is applied on plot commands
"""
return self._autoscaleXon
def get_autoscaley_on(self):
"""
Get whether autoscaling for the y-axis is applied on plot commands
"""
return self._autoscaleYon
def set_autoscale_on(self, b):
"""
Set whether autoscaling is applied on plot commands
.. ACCEPTS: bool
Parameters
----------
b : bool
"""
self._autoscaleXon = b
self._autoscaleYon = b
def set_autoscalex_on(self, b):
"""
Set whether autoscaling for the x-axis is applied on plot commands
.. ACCEPTS: bool
Parameters
----------
b : bool
"""
self._autoscaleXon = b
def set_autoscaley_on(self, b):
"""
Set whether autoscaling for the y-axis is applied on plot commands
.. ACCEPTS: bool
Parameters
----------
b : bool
"""
self._autoscaleYon = b
@property
def use_sticky_edges(self):
"""
When autoscaling, whether to obey all `Artist.sticky_edges`.
Default is ``True``.
Setting this to ``False`` ensures that the specified margins
will be applied, even if the plot includes an image, for
example, which would otherwise force a view limit to coincide
with its data limit.
The changing this property does not change the plot until
`autoscale` or `autoscale_view` is called.
"""
return self._use_sticky_edges
@use_sticky_edges.setter
def use_sticky_edges(self, b):
self._use_sticky_edges = bool(b)
# No effect until next autoscaling, which will mark the axes as stale.
def set_xmargin(self, m):
"""
Set padding of X data limits prior to autoscaling.
*m* times the data interval will be added to each
end of that interval before it is used in autoscaling.
For example, if your data is in the range [0, 2], a factor of
``m = 0.1`` will result in a range [-0.2, 2.2].
Negative values -0.5 < m < 0 will result in clipping of the data range.
I.e. for a data range [0, 2], a factor of ``m = -0.1`` will result in
a range [0.2, 1.8].
.. ACCEPTS: float greater than -0.5
Parameters
----------
m : float greater than -0.5
"""
if m <= -0.5:
raise ValueError("margin must be greater than -0.5")
self._xmargin = m
self.stale = True
def set_ymargin(self, m):
"""
Set padding of Y data limits prior to autoscaling.
*m* times the data interval will be added to each
end of that interval before it is used in autoscaling.
For example, if your data is in the range [0, 2], a factor of
``m = 0.1`` will result in a range [-0.2, 2.2].
Negative values -0.5 < m < 0 will result in clipping of the data range.
I.e. for a data range [0, 2], a factor of ``m = -0.1`` will result in
a range [0.2, 1.8].
.. ACCEPTS: float greater than -0.5
Parameters
----------
m : float greater than -0.5
"""
if m <= -0.5:
raise ValueError("margin must be greater than -0.5")
self._ymargin = m
self.stale = True
def margins(self, *args, **kw):
"""
Set or retrieve autoscaling margins.
signatures::
margins()
returns xmargin, ymargin
::
margins(margin)
margins(xmargin, ymargin)
margins(x=xmargin, y=ymargin)
margins(..., tight=False)
All three forms above set the xmargin and ymargin parameters.
All keyword parameters are optional. A single argument
specifies both xmargin and ymargin. The padding added to the end of
each interval is *margin* times the data interval. The *margin* must
be a float in the range [0, 1].
The *tight* parameter is passed to :meth:`autoscale_view`
, which is executed after a margin is changed; the default here is
*True*, on the assumption that when margins are specified, no
additional padding to match tick marks is usually desired. Setting
*tight* to *None* will preserve the previous setting.
Specifying any margin changes only the autoscaling; for example,
if *xmargin* is not None, then *xmargin* times the X data
interval will be added to each end of that interval before
it is used in autoscaling.
"""
if not args and not kw:
return self._xmargin, self._ymargin
tight = kw.pop('tight', True)
mx = kw.pop('x', None)
my = kw.pop('y', None)
if len(args) == 1:
mx = my = args[0]
elif len(args) == 2:
mx, my = args
elif len(args) > 2:
raise ValueError("more than two arguments were supplied")
if mx is not None:
self.set_xmargin(mx)
if my is not None:
self.set_ymargin(my)
scalex = (mx is not None)
scaley = (my is not None)
self.autoscale_view(tight=tight, scalex=scalex, scaley=scaley)
def set_rasterization_zorder(self, z):
"""
Parameters
----------
z : float or None
zorder below which artists are rasterized. ``None`` means that
artists do not get rasterized based on zorder.
.. ACCEPTS: float or None
"""
self._rasterization_zorder = z
self.stale = True
def get_rasterization_zorder(self):
"""Return the zorder value below which artists will be rasterized."""
return self._rasterization_zorder
def autoscale(self, enable=True, axis='both', tight=None):
"""
Autoscale the axis view to the data (toggle).
Convenience method for simple axis view autoscaling.
It turns autoscaling on or off, and then,
if autoscaling for either axis is on, it performs
the autoscaling on the specified axis or axes.
Parameters
----------
enable : bool or None, optional
True (default) turns autoscaling on, False turns it off.
None leaves the autoscaling state unchanged.
axis : ['both' | 'x' | 'y'], optional
which axis to operate on; default is 'both'
tight: bool or None, optional
If True, set view limits to data limits;
if False, let the locator and margins expand the view limits;
if None, use tight scaling if the only artist is an image,
otherwise treat *tight* as False.
The *tight* setting is retained for future autoscaling
until it is explicitly changed.
"""
if enable is None:
scalex = True
scaley = True
else:
scalex = False
scaley = False
if axis in ['x', 'both']:
self._autoscaleXon = bool(enable)
scalex = self._autoscaleXon
if axis in ['y', 'both']:
self._autoscaleYon = bool(enable)
scaley = self._autoscaleYon
if tight and scalex:
self._xmargin = 0
if tight and scaley:
self._ymargin = 0
self.autoscale_view(tight=tight, scalex=scalex, scaley=scaley)
def autoscale_view(self, tight=None, scalex=True, scaley=True):
"""
Autoscale the view limits using the data limits.
You can selectively autoscale only a single axis, e.g., the xaxis by
setting *scaley* to *False*. The autoscaling preserves any
axis direction reversal that has already been done.
If *tight* is *False*, the axis major locator will be used
to expand the view limits if rcParams['axes.autolimit_mode']
is 'round_numbers'. Note that any margins that are in effect
will be applied first, regardless of whether *tight* is
*True* or *False*. Specifying *tight* as *True* or *False*
saves the setting as a private attribute of the Axes; specifying
it as *None* (the default) applies the previously saved value.
The data limits are not updated automatically when artist data are
changed after the artist has been added to an Axes instance. In that
case, use :meth:`matplotlib.axes.Axes.relim` prior to calling
autoscale_view.
"""
if tight is not None:
self._tight = bool(tight)
if self.use_sticky_edges and (self._xmargin or self._ymargin):
stickies = [artist.sticky_edges for artist in self.get_children()]
x_stickies = sum([sticky.x for sticky in stickies], [])
y_stickies = sum([sticky.y for sticky in stickies], [])
if self.get_xscale().lower() == 'log':
x_stickies = [xs for xs in x_stickies if xs > 0]
if self.get_yscale().lower() == 'log':
y_stickies = [ys for ys in y_stickies if ys > 0]
else: # Small optimization.
x_stickies, y_stickies = [], []
def handle_single_axis(scale, autoscaleon, shared_axes, interval,
minpos, axis, margin, stickies, set_bound):
if not (scale and autoscaleon):
return # nothing to do...
shared = shared_axes.get_siblings(self)
dl = [ax.dataLim for ax in shared]
# ignore non-finite data limits if good limits exist
finite_dl = [d for d in dl if np.isfinite(d).all()]
if len(finite_dl):
# if finite limits exist for atleast one axis (and the
# other is infinite), restore the finite limits
x_finite = [d for d in dl
if (np.isfinite(d.intervalx).all() and
(d not in finite_dl))]
y_finite = [d for d in dl
if (np.isfinite(d.intervaly).all() and
(d not in finite_dl))]
dl = finite_dl
dl.extend(x_finite)
dl.extend(y_finite)
bb = mtransforms.BboxBase.union(dl)
x0, x1 = getattr(bb, interval)
locator = axis.get_major_locator()
try:
# e.g., DateLocator has its own nonsingular()
x0, x1 = locator.nonsingular(x0, x1)
except AttributeError:
# Default nonsingular for, e.g., MaxNLocator
x0, x1 = mtransforms.nonsingular(
x0, x1, increasing=False, expander=0.05)
# Add the margin in figure space and then transform back, to handle
# non-linear scales.
minpos = getattr(bb, minpos)
transform = axis.get_transform()
inverse_trans = transform.inverted()
# We cannot use exact equality due to floating point issues e.g.
# with streamplot.
do_lower_margin = not np.any(np.isclose(x0, stickies))
do_upper_margin = not np.any(np.isclose(x1, stickies))
x0, x1 = axis._scale.limit_range_for_scale(x0, x1, minpos)
x0t, x1t = transform.transform([x0, x1])
delta = (x1t - x0t) * margin
if do_lower_margin:
x0t -= delta
if do_upper_margin:
x1t += delta
x0, x1 = inverse_trans.transform([x0t, x1t])
if not self._tight:
x0, x1 = locator.view_limits(x0, x1)
set_bound(x0, x1)
# End of definition of internal function 'handle_single_axis'.
handle_single_axis(
scalex, self._autoscaleXon, self._shared_x_axes, 'intervalx',
'minposx', self.xaxis, self._xmargin, x_stickies, self.set_xbound)
handle_single_axis(
scaley, self._autoscaleYon, self._shared_y_axes, 'intervaly',
'minposy', self.yaxis, self._ymargin, y_stickies, self.set_ybound)
def _get_axis_list(self):
return (self.xaxis, self.yaxis)
# Drawing
@allow_rasterization
def draw(self, renderer=None, inframe=False):
"""Draw everything (plot lines, axes, labels)"""
if renderer is None:
renderer = self._cachedRenderer
if renderer is None:
raise RuntimeError('No renderer defined')
if not self.get_visible():
return
renderer.open_group('axes')
# prevent triggering call backs during the draw process
self._stale = True
locator = self.get_axes_locator()
if locator:
pos = locator(self, renderer)
self.apply_aspect(pos)
else:
self.apply_aspect()
artists = self.get_children()
artists.remove(self.patch)
# the frame draws the edges around the axes patch -- we
# decouple these so the patch can be in the background and the
# frame in the foreground. Do this before drawing the axis
# objects so that the spine has the opportunity to update them.
if not (self.axison and self._frameon):
for spine in six.itervalues(self.spines):
artists.remove(spine)
if self.axison and not inframe:
if self._axisbelow is True:
self.xaxis.set_zorder(0.5)
self.yaxis.set_zorder(0.5)
elif self._axisbelow is False:
self.xaxis.set_zorder(2.5)
self.yaxis.set_zorder(2.5)
else:
# 'line': above patches, below lines
self.xaxis.set_zorder(1.5)
self.yaxis.set_zorder(1.5)
else:
for _axis in self._get_axis_list():
artists.remove(_axis)
if inframe:
artists.remove(self.title)
artists.remove(self._left_title)
artists.remove(self._right_title)
if not self.figure.canvas.is_saving():
artists = [a for a in artists
if not a.get_animated() or a in self.images]
artists = sorted(artists, key=attrgetter('zorder'))
# rasterize artists with negative zorder
# if the minimum zorder is negative, start rasterization
rasterization_zorder = self._rasterization_zorder
if (rasterization_zorder is not None and
artists and artists[0].zorder < rasterization_zorder):
renderer.start_rasterizing()
artists_rasterized = [a for a in artists
if a.zorder < rasterization_zorder]
artists = [a for a in artists
if a.zorder >= rasterization_zorder]
else:
artists_rasterized = []
# the patch draws the background rectangle -- the frame below
# will draw the edges
if self.axison and self._frameon:
self.patch.draw(renderer)
if artists_rasterized:
for a in artists_rasterized:
a.draw(renderer)
renderer.stop_rasterizing()
mimage._draw_list_compositing_images(renderer, self, artists)
renderer.close_group('axes')
self._cachedRenderer = renderer
self.stale = False
def draw_artist(self, a):
"""
This method can only be used after an initial draw which
caches the renderer. It is used to efficiently update Axes
data (axis ticks, labels, etc are not updated)
"""
if self._cachedRenderer is None:
raise AttributeError("draw_artist can only be used after an "
"initial draw which caches the renderer")
a.draw(self._cachedRenderer)
def redraw_in_frame(self):
"""
This method can only be used after an initial draw which
caches the renderer. It is used to efficiently update Axes
data (axis ticks, labels, etc are not updated)
"""
if self._cachedRenderer is None:
raise AttributeError("redraw_in_frame can only be used after an "
"initial draw which caches the renderer")
self.draw(self._cachedRenderer, inframe=True)
def get_renderer_cache(self):
return self._cachedRenderer
# Axes rectangle characteristics
def get_frame_on(self):
"""
Get whether the axes rectangle patch is drawn.
"""
return self._frameon
def set_frame_on(self, b):
"""
Set whether the axes rectangle patch is drawn.
.. ACCEPTS: bool
Parameters
----------
b : bool
"""
self._frameon = b
self.stale = True
def get_axisbelow(self):
"""
Get whether axis ticks and gridlines are above or below most artists.
"""
return self._axisbelow
def set_axisbelow(self, b):
"""
Set whether axis ticks and gridlines are above or below most artists.
.. ACCEPTS: [ bool | 'line' ]
Parameters
----------
b : bool or 'line'
"""
self._axisbelow = validate_axisbelow(b)
self.stale = True
@docstring.dedent_interpd
def grid(self, b=None, which='major', axis='both', **kwargs):
"""
Turn the axes grids on or off.
Set the axes grids on or off; *b* is a boolean.
If *b* is *None* and ``len(kwargs)==0``, toggle the grid state. If
*kwargs* are supplied, it is assumed that you want a grid and *b*
is thus set to *True*.
*which* can be 'major' (default), 'minor', or 'both' to control
whether major tick grids, minor tick grids, or both are affected.
*axis* can be 'both' (default), 'x', or 'y' to control which
set of gridlines are drawn.
*kwargs* are used to set the grid line properties, e.g.,::
ax.grid(color='r', linestyle='-', linewidth=2)
Valid :class:`~matplotlib.lines.Line2D` kwargs are
%(Line2D)s
"""
if len(kwargs):
b = True
elif b is not None:
b = _string_to_bool(b)
if axis == 'x' or axis == 'both':
self.xaxis.grid(b, which=which, **kwargs)
if axis == 'y' or axis == 'both':
self.yaxis.grid(b, which=which, **kwargs)
def ticklabel_format(self, **kwargs):
"""
Change the `~matplotlib.ticker.ScalarFormatter` used by
default for linear axes.
Optional keyword arguments:
============== =========================================
Keyword Description
============== =========================================
*style* [ 'sci' (or 'scientific') | 'plain' ]
plain turns off scientific notation
*scilimits* (m, n), pair of integers; if *style*
is 'sci', scientific notation will
be used for numbers outside the range
10`m`:sup: to 10`n`:sup:.
Use (0,0) to include all numbers.
*useOffset* [ bool | offset ]; if True,
the offset will be calculated as needed;
if False, no offset will be used; if a
numeric offset is specified, it will be
used.
*axis* [ 'x' | 'y' | 'both' ]
*useLocale* If True, format the number according to
the current locale. This affects things
such as the character used for the
decimal separator. If False, use
C-style (English) formatting. The
default setting is controlled by the
axes.formatter.use_locale rcparam.
*useMathText* If True, render the offset and scientific
notation in mathtext
============== =========================================
Only the major ticks are affected.
If the method is called when the
:class:`~matplotlib.ticker.ScalarFormatter` is not the
:class:`~matplotlib.ticker.Formatter` being used, an
:exc:`AttributeError` will be raised.
"""
style = kwargs.pop('style', '').lower()
scilimits = kwargs.pop('scilimits', None)
useOffset = kwargs.pop('useOffset', None)
useLocale = kwargs.pop('useLocale', None)
useMathText = kwargs.pop('useMathText', None)
axis = kwargs.pop('axis', 'both').lower()
if scilimits is not None:
try:
m, n = scilimits
m + n + 1 # check that both are numbers
except (ValueError, TypeError):
raise ValueError("scilimits must be a sequence of 2 integers")
if style[:3] == 'sci':
sb = True
elif style == 'plain':
sb = False
elif style == 'comma':
raise NotImplementedError("comma style remains to be added")
elif style == '':
sb = None
else:
raise ValueError("%s is not a valid style value")
try:
if sb is not None:
if axis == 'both' or axis == 'x':
self.xaxis.major.formatter.set_scientific(sb)
if axis == 'both' or axis == 'y':
self.yaxis.major.formatter.set_scientific(sb)
if scilimits is not None:
if axis == 'both' or axis == 'x':
self.xaxis.major.formatter.set_powerlimits(scilimits)
if axis == 'both' or axis == 'y':
self.yaxis.major.formatter.set_powerlimits(scilimits)
if useOffset is not None:
if axis == 'both' or axis == 'x':
self.xaxis.major.formatter.set_useOffset(useOffset)
if axis == 'both' or axis == 'y':
self.yaxis.major.formatter.set_useOffset(useOffset)
if useLocale is not None:
if axis == 'both' or axis == 'x':
self.xaxis.major.formatter.set_useLocale(useLocale)
if axis == 'both' or axis == 'y':
self.yaxis.major.formatter.set_useLocale(useLocale)
if useMathText is not None:
if axis == 'both' or axis == 'x':
self.xaxis.major.formatter.set_useMathText(useMathText)
if axis == 'both' or axis == 'y':
self.yaxis.major.formatter.set_useMathText(useMathText)
except AttributeError:
raise AttributeError(
"This method only works with the ScalarFormatter.")
def locator_params(self, axis='both', tight=None, **kwargs):
"""
Control behavior of tick locators.
Parameters
----------
axis : ['both' | 'x' | 'y'], optional
The axis on which to operate.
tight : bool or None, optional
Parameter passed to :meth:`autoscale_view`.
Default is None, for no change.
Other Parameters
----------------
**kw :
Remaining keyword arguments are passed to directly to the
:meth:`~matplotlib.ticker.MaxNLocator.set_params` method.
Typically one might want to reduce the maximum number
of ticks and use tight bounds when plotting small
subplots, for example::
ax.locator_params(tight=True, nbins=4)
Because the locator is involved in autoscaling,
:meth:`autoscale_view` is called automatically after
the parameters are changed.
This presently works only for the
:class:`~matplotlib.ticker.MaxNLocator` used
by default on linear axes, but it may be generalized.
"""
_x = axis in ['x', 'both']
_y = axis in ['y', 'both']
if _x:
self.xaxis.get_major_locator().set_params(**kwargs)
if _y:
self.yaxis.get_major_locator().set_params(**kwargs)
self.autoscale_view(tight=tight, scalex=_x, scaley=_y)
def tick_params(self, axis='both', **kwargs):
"""Change the appearance of ticks, tick labels, and gridlines.
Parameters
----------
axis : {'x', 'y', 'both'}, optional
Which axis to apply the parameters to.
Other Parameters
----------------
axis : {'x', 'y', 'both'}
Axis on which to operate; default is 'both'.
reset : bool
If *True*, set all parameters to defaults
before processing other keyword arguments. Default is
*False*.
which : {'major', 'minor', 'both'}
Default is 'major'; apply arguments to *which* ticks.
direction : {'in', 'out', 'inout'}
Puts ticks inside the axes, outside the axes, or both.
length : float
Tick length in points.
width : float
Tick width in points.
color : color
Tick color; accepts any mpl color spec.
pad : float
Distance in points between tick and label.
labelsize : float or str
Tick label font size in points or as a string (e.g., 'large').
labelcolor : color
Tick label color; mpl color spec.
colors : color
Changes the tick color and the label color to the same value:
mpl color spec.
zorder : float
Tick and label zorder.
bottom, top, left, right : bool
Whether to draw the respective ticks.
labelbottom, labeltop, labelleft, labelright : bool
Whether to draw the respective tick labels.
labelrotation : float
Tick label rotation
grid_color : color
Changes the gridline color to the given mpl color spec.
grid_alpha : float
Transparency of gridlines: 0 (transparent) to 1 (opaque).
grid_linewidth : float
Width of gridlines in points.
grid_linestyle : string
Any valid :class:`~matplotlib.lines.Line2D` line style spec.
Examples
--------
Usage ::
ax.tick_params(direction='out', length=6, width=2, colors='r',
grid_color='r', grid_alpha=0.5)
This will make all major ticks be red, pointing out of the box,
and with dimensions 6 points by 2 points. Tick labels will
also be red. Gridlines will be red and translucent.
"""
if axis in ['x', 'both']:
xkw = dict(kwargs)
xkw.pop('left', None)
xkw.pop('right', None)
xkw.pop('labelleft', None)
xkw.pop('labelright', None)
self.xaxis.set_tick_params(**xkw)
if axis in ['y', 'both']:
ykw = dict(kwargs)
ykw.pop('top', None)
ykw.pop('bottom', None)
ykw.pop('labeltop', None)
ykw.pop('labelbottom', None)
self.yaxis.set_tick_params(**ykw)
def set_axis_off(self):
"""Turn off the axis."""
self.axison = False
self.stale = True
def set_axis_on(self):
"""Turn on the axis."""
self.axison = True
self.stale = True
# data limits, ticks, tick labels, and formatting
def invert_xaxis(self):
"""Invert the x-axis."""
self.set_xlim(self.get_xlim()[::-1], auto=None)
def xaxis_inverted(self):
"""Return whether the x-axis is inverted."""
left, right = self.get_xlim()
return right < left
def get_xbound(self):
"""Return the lower and upper x-axis bounds, in increasing order."""
left, right = self.get_xlim()
if left < right:
return left, right
else:
return right, left
def set_xbound(self, lower=None, upper=None):
"""
Set the lower and upper numerical bounds of the x-axis.
This method will honor axes inversion regardless of parameter order.
It will not change the _autoscaleXon attribute.
.. ACCEPTS: (lower: float, upper: float)
"""
if upper is None and iterable(lower):
lower, upper = lower
old_lower, old_upper = self.get_xbound()
if lower is None:
lower = old_lower
if upper is None:
upper = old_upper
if self.xaxis_inverted():
if lower < upper:
self.set_xlim(upper, lower, auto=None)
else:
self.set_xlim(lower, upper, auto=None)
else:
if lower < upper:
self.set_xlim(lower, upper, auto=None)
else:
self.set_xlim(upper, lower, auto=None)
def get_xlim(self):
"""
Get the x-axis range
Returns
-------
xlimits : tuple
Returns the current x-axis limits as the tuple
(`left`, `right`).
Notes
-----
The x-axis may be inverted, in which case the `left` value will
be greater than the `right` value.
"""
return tuple(self.viewLim.intervalx)
def _validate_converted_limits(self, limit, convert):
"""
Raise ValueError if converted limits are non-finite.
Note that this function also accepts None as a limit argument.
Returns
-------
The limit value after call to convert(), or None if limit is None.
"""
if limit is not None:
converted_limit = convert(limit)
if (isinstance(converted_limit, float) and
(not np.isreal(converted_limit) or
not np.isfinite(converted_limit))):
raise ValueError("Axis limits cannot be NaN or Inf")
return converted_limit
def set_xlim(self, left=None, right=None, emit=True, auto=False, **kw):
"""
Set the data limits for the x-axis
.. ACCEPTS: (left: float, right: float)
Parameters
----------
left : scalar, optional
The left xlim (default: None, which leaves the left limit
unchanged).
right : scalar, optional
The right xlim (default: None, which leaves the right limit
unchanged).
emit : bool, optional
Whether to notify observers of limit change (default: True).
auto : bool or None, optional
Whether to turn on autoscaling of the x-axis. True turns on,
False turns off (default action), None leaves unchanged.
xlimits : tuple, optional
The left and right xlims may be passed as the tuple
(`left`, `right`) as the first positional argument (or as
the `left` keyword argument).
Returns
-------
xlimits : tuple
Returns the new x-axis limits as (`left`, `right`).
Notes
-----
The `left` value may be greater than the `right` value, in which
case the x-axis values will decrease from left to right.
Examples
--------
>>> set_xlim(left, right)
>>> set_xlim((left, right))
>>> left, right = set_xlim(left, right)
One limit may be left unchanged.
>>> set_xlim(right=right_lim)
Limits may be passed in reverse order to flip the direction of
the x-axis. For example, suppose `x` represents the number of
years before present. The x-axis limits might be set like the
following so 5000 years ago is on the left of the plot and the
present is on the right.
>>> set_xlim(5000, 0)
"""
if 'xmin' in kw:
left = kw.pop('xmin')
if 'xmax' in kw:
right = kw.pop('xmax')
if kw:
raise ValueError("unrecognized kwargs: %s" % list(kw))
if right is None and iterable(left):
left, right = left
self._process_unit_info(xdata=(left, right))
left = self._validate_converted_limits(left, self.convert_xunits)
right = self._validate_converted_limits(right, self.convert_xunits)
old_left, old_right = self.get_xlim()
if left is None:
left = old_left
if right is None:
right = old_right
if left == right:
warnings.warn(
('Attempting to set identical left==right results\n'
'in singular transformations; automatically expanding.\n'
'left=%s, right=%s') % (left, right))
left, right = mtransforms.nonsingular(left, right, increasing=False)
if self.get_xscale() == 'log' and (left <= 0.0 or right <= 0.0):
warnings.warn(
'Attempted to set non-positive xlimits for log-scale axis; '
'invalid limits will be ignored.')
left, right = self.xaxis.limit_range_for_scale(left, right)
self.viewLim.intervalx = (left, right)
if auto is not None:
self._autoscaleXon = bool(auto)
if emit:
self.callbacks.process('xlim_changed', self)
# Call all of the other x-axes that are shared with this one
for other in self._shared_x_axes.get_siblings(self):
if other is not self:
other.set_xlim(self.viewLim.intervalx,
emit=False, auto=auto)
if (other.figure != self.figure and
other.figure.canvas is not None):
other.figure.canvas.draw_idle()
self.stale = True
return left, right
def get_xscale(self):
return self.xaxis.get_scale()
get_xscale.__doc__ = "Return the xaxis scale string: %s""" % (
", ".join(mscale.get_scale_names()))
def set_xscale(self, value, **kwargs):
"""
Set the x-axis scale.
.. ACCEPTS: [ 'linear' | 'log' | 'symlog' | 'logit' | ... ]
Parameters
----------
value : {"linear", "log", "symlog", "logit"}
scaling strategy to apply
Notes
-----
Different kwargs are accepted, depending on the scale. See
the `~matplotlib.scale` module for more information.
See also
--------
matplotlib.scale.LinearScale : linear transform
matplotlib.scale.LogTransform : log transform
matplotlib.scale.SymmetricalLogTransform : symlog transform
matplotlib.scale.LogisticTransform : logit transform
"""
g = self.get_shared_x_axes()
for ax in g.get_siblings(self):
ax.xaxis._set_scale(value, **kwargs)
ax._update_transScale()
ax.stale = True
self.autoscale_view(scaley=False)
def get_xticks(self, minor=False):
"""Return the x ticks as a list of locations"""
return self.xaxis.get_ticklocs(minor=minor)
def set_xticks(self, ticks, minor=False):
"""
Set the x ticks with list of *ticks*
.. ACCEPTS: list of tick locations.
Parameters
----------
ticks : list
List of x-axis tick locations.
minor : bool, optional
If ``False`` sets major ticks, if ``True`` sets minor ticks.
Default is ``False``.
"""
ret = self.xaxis.set_ticks(ticks, minor=minor)
self.stale = True
return ret
def get_xmajorticklabels(self):
"""
Get the major x tick labels.
Returns
-------
labels : list
List of :class:`~matplotlib.text.Text` instances
"""
return cbook.silent_list('Text xticklabel',
self.xaxis.get_majorticklabels())
def get_xminorticklabels(self):
"""
Get the minor x tick labels.
Returns
-------
labels : list
List of :class:`~matplotlib.text.Text` instances
"""
return cbook.silent_list('Text xticklabel',
self.xaxis.get_minorticklabels())
def get_xticklabels(self, minor=False, which=None):
"""
Get the x tick labels as a list of :class:`~matplotlib.text.Text`
instances.
Parameters
----------
minor : bool, optional
If True return the minor ticklabels,
else return the major ticklabels.
which : None, ('minor', 'major', 'both')
Overrides `minor`.
Selects which ticklabels to return
Returns
-------
ret : list
List of :class:`~matplotlib.text.Text` instances.
"""
return cbook.silent_list('Text xticklabel',
self.xaxis.get_ticklabels(minor=minor,
which=which))
def set_xticklabels(self, labels, fontdict=None, minor=False, **kwargs):
"""
Set the x-tick labels with list of string labels.
.. ACCEPTS: list of string labels
Parameters
----------
labels : list of str
List of string labels.
fontdict : dict, optional
A dictionary controlling the appearance of the ticklabels.
The default `fontdict` is::
{'fontsize': rcParams['axes.titlesize'],
'fontweight': rcParams['axes.titleweight'],
'verticalalignment': 'baseline',
'horizontalalignment': loc}
minor : bool, optional
Whether to set the minor ticklabels rather than the major ones.
Returns
-------
A list of `~.text.Text` instances.
Other Parameters
-----------------
**kwargs : `~.text.Text` properties.
"""
if fontdict is not None:
kwargs.update(fontdict)
ret = self.xaxis.set_ticklabels(labels,
minor=minor, **kwargs)
self.stale = True
return ret
def invert_yaxis(self):
"""Invert the y-axis."""
self.set_ylim(self.get_ylim()[::-1], auto=None)
def yaxis_inverted(self):
"""Return whether the y-axis is inverted."""
bottom, top = self.get_ylim()
return top < bottom
def get_ybound(self):
"""Return the lower and upper y-axis bounds, in increasing order."""
bottom, top = self.get_ylim()
if bottom < top:
return bottom, top
else:
return top, bottom
def set_ybound(self, lower=None, upper=None):
"""
Set the lower and upper numerical bounds of the y-axis.
This method will honor axes inversion regardless of parameter order.
It will not change the _autoscaleYon attribute.
.. ACCEPTS: (lower: float, upper: float)
"""
if upper is None and iterable(lower):
lower, upper = lower
old_lower, old_upper = self.get_ybound()
if lower is None:
lower = old_lower
if upper is None:
upper = old_upper
if self.yaxis_inverted():
if lower < upper:
self.set_ylim(upper, lower, auto=None)
else:
self.set_ylim(lower, upper, auto=None)
else:
if lower < upper:
self.set_ylim(lower, upper, auto=None)
else:
self.set_ylim(upper, lower, auto=None)
def get_ylim(self):
"""
Get the y-axis range
Returns
-------
ylimits : tuple
Returns the current y-axis limits as the tuple
(`bottom`, `top`).
Notes
-----
The y-axis may be inverted, in which case the `bottom` value
will be greater than the `top` value.
"""
return tuple(self.viewLim.intervaly)
def set_ylim(self, bottom=None, top=None, emit=True, auto=False, **kw):
"""
Set the data limits for the y-axis
.. ACCEPTS: (bottom: float, top: float)
Parameters
----------
bottom : scalar, optional
The bottom ylim (default: None, which leaves the bottom
limit unchanged).
top : scalar, optional
The top ylim (default: None, which leaves the top limit
unchanged).
emit : bool, optional
Whether to notify observers of limit change (default: True).
auto : bool or None, optional
Whether to turn on autoscaling of the y-axis. True turns on,
False turns off (default action), None leaves unchanged.
ylimits : tuple, optional
The bottom and top yxlims may be passed as the tuple
(`bottom`, `top`) as the first positional argument (or as
the `bottom` keyword argument).
Returns
-------
ylimits : tuple
Returns the new y-axis limits as (`bottom`, `top`).
Notes
-----
The `bottom` value may be greater than the `top` value, in which
case the y-axis values will decrease from bottom to top.
Examples
--------
>>> set_ylim(bottom, top)
>>> set_ylim((bottom, top))
>>> bottom, top = set_ylim(bottom, top)
One limit may be left unchanged.
>>> set_ylim(top=top_lim)
Limits may be passed in reverse order to flip the direction of
the y-axis. For example, suppose `y` represents depth of the
ocean in m. The y-axis limits might be set like the following
so 5000 m depth is at the bottom of the plot and the surface,
0 m, is at the top.
>>> set_ylim(5000, 0)
"""
if 'ymin' in kw:
bottom = kw.pop('ymin')
if 'ymax' in kw:
top = kw.pop('ymax')
if kw:
raise ValueError("unrecognized kwargs: %s" % list(kw))
if top is None and iterable(bottom):
bottom, top = bottom
bottom = self._validate_converted_limits(bottom, self.convert_yunits)
top = self._validate_converted_limits(top, self.convert_yunits)
old_bottom, old_top = self.get_ylim()
if bottom is None:
bottom = old_bottom
if top is None:
top = old_top
if bottom == top:
warnings.warn(
('Attempting to set identical bottom==top results\n'
'in singular transformations; automatically expanding.\n'
'bottom=%s, top=%s') % (bottom, top))
bottom, top = mtransforms.nonsingular(bottom, top, increasing=False)
if self.get_yscale() == 'log' and (bottom <= 0.0 or top <= 0.0):
warnings.warn(
'Attempted to set non-positive ylimits for log-scale axis; '
'invalid limits will be ignored.')
bottom, top = self.yaxis.limit_range_for_scale(bottom, top)
self.viewLim.intervaly = (bottom, top)
if auto is not None:
self._autoscaleYon = bool(auto)
if emit:
self.callbacks.process('ylim_changed', self)
# Call all of the other y-axes that are shared with this one
for other in self._shared_y_axes.get_siblings(self):
if other is not self:
other.set_ylim(self.viewLim.intervaly,
emit=False, auto=auto)
if (other.figure != self.figure and
other.figure.canvas is not None):
other.figure.canvas.draw_idle()
self.stale = True
return bottom, top
def get_yscale(self):
return self.yaxis.get_scale()
get_yscale.__doc__ = "Return the yaxis scale string: %s""" % (
", ".join(mscale.get_scale_names()))
def set_yscale(self, value, **kwargs):
"""
Set the y-axis scale.
.. ACCEPTS: [ 'linear' | 'log' | 'symlog' | 'logit' | ... ]
Parameters
----------
value : {"linear", "log", "symlog", "logit"}
scaling strategy to apply
Notes
-----
Different kwargs are accepted, depending on the scale. See
the `~matplotlib.scale` module for more information.
See also
--------
matplotlib.scale.LinearScale : linear transform
matplotlib.scale.LogTransform : log transform
matplotlib.scale.SymmetricalLogTransform : symlog transform
matplotlib.scale.LogisticTransform : logit transform
"""
g = self.get_shared_y_axes()
for ax in g.get_siblings(self):
ax.yaxis._set_scale(value, **kwargs)
ax._update_transScale()
ax.stale = True
self.autoscale_view(scalex=False)
def get_yticks(self, minor=False):
"""Return the y ticks as a list of locations"""
return self.yaxis.get_ticklocs(minor=minor)
def set_yticks(self, ticks, minor=False):
"""
Set the y ticks with list of *ticks*
.. ACCEPTS: list of tick locations.
Parameters
----------
ticks : sequence
List of y-axis tick locations
minor : bool, optional
If ``False`` sets major ticks, if ``True`` sets minor ticks.
Default is ``False``.
"""
ret = self.yaxis.set_ticks(ticks, minor=minor)
return ret
def get_ymajorticklabels(self):
"""
Get the major y tick labels.
Returns
-------
labels : list
List of :class:`~matplotlib.text.Text` instances
"""
return cbook.silent_list('Text yticklabel',
self.yaxis.get_majorticklabels())
def get_yminorticklabels(self):
"""
Get the minor y tick labels.
Returns
-------
labels : list
List of :class:`~matplotlib.text.Text` instances
"""
return cbook.silent_list('Text yticklabel',
self.yaxis.get_minorticklabels())
def get_yticklabels(self, minor=False, which=None):
"""
Get the x tick labels as a list of :class:`~matplotlib.text.Text`
instances.
Parameters
----------
minor : bool
If True return the minor ticklabels,
else return the major ticklabels
which : None, ('minor', 'major', 'both')
Overrides `minor`.
Selects which ticklabels to return
Returns
-------
ret : list
List of :class:`~matplotlib.text.Text` instances.
"""
return cbook.silent_list('Text yticklabel',
self.yaxis.get_ticklabels(minor=minor,
which=which))
def set_yticklabels(self, labels, fontdict=None, minor=False, **kwargs):
"""
Set the y-tick labels with list of strings labels.
.. ACCEPTS: list of string labels
Parameters
----------
labels : list of str
list of string labels
fontdict : dict, optional
A dictionary controlling the appearance of the ticklabels.
The default `fontdict` is::
{'fontsize': rcParams['axes.titlesize'],
'fontweight': rcParams['axes.titleweight'],
'verticalalignment': 'baseline',
'horizontalalignment': loc}
minor : bool, optional
Whether to set the minor ticklabels rather than the major ones.
Returns
-------
A list of `~.text.Text` instances.
Other Parameters
----------------
**kwargs : `~.text.Text` properties.
"""
if fontdict is not None:
kwargs.update(fontdict)
return self.yaxis.set_ticklabels(labels,
minor=minor, **kwargs)
def xaxis_date(self, tz=None):
"""
Sets up x-axis ticks and labels that treat the x data as dates.
Parameters
----------
tz : string or :class:`tzinfo` instance, optional
Timezone string or timezone. Defaults to rc value.
"""
# should be enough to inform the unit conversion interface
# dates are coming in
self.xaxis.axis_date(tz)
def yaxis_date(self, tz=None):
"""
Sets up y-axis ticks and labels that treat the y data as dates.
Parameters
----------
tz : string or :class:`tzinfo` instance, optional
Timezone string or timezone. Defaults to rc value.
"""
self.yaxis.axis_date(tz)
def format_xdata(self, x):
"""
Return *x* string formatted. This function will use the attribute
self.fmt_xdata if it is callable, else will fall back on the xaxis
major formatter
"""
try:
return self.fmt_xdata(x)
except TypeError:
func = self.xaxis.get_major_formatter().format_data_short
val = func(x)
return val
def format_ydata(self, y):
"""
Return y string formatted. This function will use the
:attr:`fmt_ydata` attribute if it is callable, else will fall
back on the yaxis major formatter
"""
try:
return self.fmt_ydata(y)
except TypeError:
func = self.yaxis.get_major_formatter().format_data_short
val = func(y)
return val
def format_coord(self, x, y):
"""Return a format string formatting the *x*, *y* coord"""
if x is None:
xs = '???'
else:
xs = self.format_xdata(x)
if y is None:
ys = '???'
else:
ys = self.format_ydata(y)
return 'x=%s y=%s' % (xs, ys)
def minorticks_on(self):
'Add autoscaling minor ticks to the axes.'
for ax in (self.xaxis, self.yaxis):
scale = ax.get_scale()
if scale == 'log':
s = ax._scale
ax.set_minor_locator(mticker.LogLocator(s.base, s.subs))
elif scale == 'symlog':
s = ax._scale
ax.set_minor_locator(
mticker.SymmetricalLogLocator(s._transform, s.subs))
else:
ax.set_minor_locator(mticker.AutoMinorLocator())
def minorticks_off(self):
"""Remove minor ticks from the axes."""
self.xaxis.set_minor_locator(mticker.NullLocator())
self.yaxis.set_minor_locator(mticker.NullLocator())
# Interactive manipulation
def can_zoom(self):
"""
Return *True* if this axes supports the zoom box button functionality.
"""
return True
def can_pan(self):
"""
Return *True* if this axes supports any pan/zoom button functionality.
"""
return True
def get_navigate(self):
"""
Get whether the axes responds to navigation commands
"""
return self._navigate
def set_navigate(self, b):
"""
Set whether the axes responds to navigation toolbar commands
.. ACCEPTS: bool
Parameters
----------
b : bool
"""
self._navigate = b
def get_navigate_mode(self):
"""
Get the navigation toolbar button status: 'PAN', 'ZOOM', or None
"""
return self._navigate_mode
def set_navigate_mode(self, b):
"""
Set the navigation toolbar button status;
.. warning::
this is not a user-API function.
"""
self._navigate_mode = b
def _get_view(self):
"""
Save information required to reproduce the current view.
Called before a view is changed, such as during a pan or zoom
initiated by the user. You may return any information you deem
necessary to describe the view.
.. note::
Intended to be overridden by new projection types, but if not, the
default implementation saves the view limits. You *must* implement
:meth:`_set_view` if you implement this method.
"""
xmin, xmax = self.get_xlim()
ymin, ymax = self.get_ylim()
return (xmin, xmax, ymin, ymax)
def _set_view(self, view):
"""
Apply a previously saved view.
Called when restoring a view, such as with the navigation buttons.
.. note::
Intended to be overridden by new projection types, but if not, the
default implementation restores the view limits. You *must*
implement :meth:`_get_view` if you implement this method.
"""
xmin, xmax, ymin, ymax = view
self.set_xlim((xmin, xmax))
self.set_ylim((ymin, ymax))
def _set_view_from_bbox(self, bbox, direction='in',
mode=None, twinx=False, twiny=False):
"""
Update view from a selection bbox.
.. note::
Intended to be overridden by new projection types, but if not, the
default implementation sets the view limits to the bbox directly.
Parameters
----------
bbox : 4-tuple or 3 tuple
* If bbox is a 4 tuple, it is the selected bounding box limits,
in *display* coordinates.
* If bbox is a 3 tuple, it is an (xp, yp, scl) triple, where
(xp,yp) is the center of zooming and scl the scale factor to
zoom by.
direction : str
The direction to apply the bounding box.
* `'in'` - The bounding box describes the view directly, i.e.,
it zooms in.
* `'out'` - The bounding box describes the size to make the
existing view, i.e., it zooms out.
mode : str or None
The selection mode, whether to apply the bounding box in only the
`'x'` direction, `'y'` direction or both (`None`).
twinx : bool
Whether this axis is twinned in the *x*-direction.
twiny : bool
Whether this axis is twinned in the *y*-direction.
"""
Xmin, Xmax = self.get_xlim()
Ymin, Ymax = self.get_ylim()
if len(bbox) == 3:
# Zooming code
xp, yp, scl = bbox
# Should not happen
if scl == 0:
scl = 1.
# direction = 'in'
if scl > 1:
direction = 'in'
else:
direction = 'out'
scl = 1/scl
# get the limits of the axes
tranD2C = self.transData.transform
xmin, ymin = tranD2C((Xmin, Ymin))
xmax, ymax = tranD2C((Xmax, Ymax))
# set the range
xwidth = xmax - xmin
ywidth = ymax - ymin
xcen = (xmax + xmin)*.5
ycen = (ymax + ymin)*.5
xzc = (xp*(scl - 1) + xcen)/scl
yzc = (yp*(scl - 1) + ycen)/scl
bbox = [xzc - xwidth/2./scl, yzc - ywidth/2./scl,
xzc + xwidth/2./scl, yzc + ywidth/2./scl]
elif len(bbox) != 4:
# should be len 3 or 4 but nothing else
warnings.warn(
"Warning in _set_view_from_bbox: bounding box is not a tuple "
"of length 3 or 4. Ignoring the view change.")
return
# Just grab bounding box
lastx, lasty, x, y = bbox
# zoom to rect
inverse = self.transData.inverted()
lastx, lasty = inverse.transform_point((lastx, lasty))
x, y = inverse.transform_point((x, y))
if twinx:
x0, x1 = Xmin, Xmax
else:
if Xmin < Xmax:
if x < lastx:
x0, x1 = x, lastx
else:
x0, x1 = lastx, x
if x0 < Xmin:
x0 = Xmin
if x1 > Xmax:
x1 = Xmax
else:
if x > lastx:
x0, x1 = x, lastx
else:
x0, x1 = lastx, x
if x0 > Xmin:
x0 = Xmin
if x1 < Xmax:
x1 = Xmax
if twiny:
y0, y1 = Ymin, Ymax
else:
if Ymin < Ymax:
if y < lasty:
y0, y1 = y, lasty
else:
y0, y1 = lasty, y
if y0 < Ymin:
y0 = Ymin
if y1 > Ymax:
y1 = Ymax
else:
if y > lasty:
y0, y1 = y, lasty
else:
y0, y1 = lasty, y
if y0 > Ymin:
y0 = Ymin
if y1 < Ymax:
y1 = Ymax
if direction == 'in':
if mode == 'x':
self.set_xlim((x0, x1))
elif mode == 'y':
self.set_ylim((y0, y1))
else:
self.set_xlim((x0, x1))
self.set_ylim((y0, y1))
elif direction == 'out':
if self.get_xscale() == 'log':
alpha = np.log(Xmax / Xmin) / np.log(x1 / x0)
rx1 = pow(Xmin / x0, alpha) * Xmin
rx2 = pow(Xmax / x0, alpha) * Xmin
else:
alpha = (Xmax - Xmin) / (x1 - x0)
rx1 = alpha * (Xmin - x0) + Xmin
rx2 = alpha * (Xmax - x0) + Xmin
if self.get_yscale() == 'log':
alpha = np.log(Ymax / Ymin) / np.log(y1 / y0)
ry1 = pow(Ymin / y0, alpha) * Ymin
ry2 = pow(Ymax / y0, alpha) * Ymin
else:
alpha = (Ymax - Ymin) / (y1 - y0)
ry1 = alpha * (Ymin - y0) + Ymin
ry2 = alpha * (Ymax - y0) + Ymin
if mode == 'x':
self.set_xlim((rx1, rx2))
elif mode == 'y':
self.set_ylim((ry1, ry2))
else:
self.set_xlim((rx1, rx2))
self.set_ylim((ry1, ry2))
def start_pan(self, x, y, button):
"""
Called when a pan operation has started.
*x*, *y* are the mouse coordinates in display coords.
button is the mouse button number:
* 1: LEFT
* 2: MIDDLE
* 3: RIGHT
.. note::
Intended to be overridden by new projection types.
"""
self._pan_start = cbook.Bunch(
lim=self.viewLim.frozen(),
trans=self.transData.frozen(),
trans_inverse=self.transData.inverted().frozen(),
bbox=self.bbox.frozen(),
x=x,
y=y)
def end_pan(self):
"""
Called when a pan operation completes (when the mouse button
is up.)
.. note::
Intended to be overridden by new projection types.
"""
del self._pan_start
def drag_pan(self, button, key, x, y):
"""
Called when the mouse moves during a pan operation.
*button* is the mouse button number:
* 1: LEFT
* 2: MIDDLE
* 3: RIGHT
*key* is a "shift" key
*x*, *y* are the mouse coordinates in display coords.
.. note::
Intended to be overridden by new projection types.
"""
def format_deltas(key, dx, dy):
if key == 'control':
if abs(dx) > abs(dy):
dy = dx
else:
dx = dy
elif key == 'x':
dy = 0
elif key == 'y':
dx = 0
elif key == 'shift':
if 2 * abs(dx) < abs(dy):
dx = 0
elif 2 * abs(dy) < abs(dx):
dy = 0
elif abs(dx) > abs(dy):
dy = dy / abs(dy) * abs(dx)
else:
dx = dx / abs(dx) * abs(dy)
return dx, dy
p = self._pan_start
dx = x - p.x
dy = y - p.y
if dx == 0 and dy == 0:
return
if button == 1:
dx, dy = format_deltas(key, dx, dy)
result = p.bbox.translated(-dx, -dy).transformed(p.trans_inverse)
elif button == 3:
try:
dx = -dx / self.bbox.width
dy = -dy / self.bbox.height
dx, dy = format_deltas(key, dx, dy)
if self.get_aspect() != 'auto':
dx = dy = 0.5 * (dx + dy)
alpha = np.power(10.0, (dx, dy))
start = np.array([p.x, p.y])
oldpoints = p.lim.transformed(p.trans)
newpoints = start + alpha * (oldpoints - start)
result = (mtransforms.Bbox(newpoints)
.transformed(p.trans_inverse))
except OverflowError:
warnings.warn('Overflow while panning')
return
valid = np.isfinite(result.transformed(p.trans))
points = result.get_points().astype(object)
# Just ignore invalid limits (typically, underflow in log-scale).
points[~valid] = None
self.set_xlim(points[:, 0])
self.set_ylim(points[:, 1])
@cbook.deprecated("2.1")
def get_cursor_props(self):
"""
Return the cursor propertiess as a (*linewidth*, *color*)
tuple, where *linewidth* is a float and *color* is an RGBA
tuple
"""
return self._cursorProps
@cbook.deprecated("2.1")
def set_cursor_props(self, *args):
"""Set the cursor property as
Call signature ::
ax.set_cursor_props(linewidth, color)
or::
ax.set_cursor_props((linewidth, color))
ACCEPTS: a (*float*, *color*) tuple
"""
if len(args) == 1:
lw, c = args[0]
elif len(args) == 2:
lw, c = args
else:
raise ValueError('args must be a (linewidth, color) tuple')
c = mcolors.to_rgba(c)
self._cursorProps = lw, c
def get_children(self):
"""return a list of child artists"""
children = []
children.extend(self.collections)
children.extend(self.patches)
children.extend(self.lines)
children.extend(self.texts)
children.extend(self.artists)
children.extend(six.itervalues(self.spines))
children.append(self.xaxis)
children.append(self.yaxis)
children.append(self.title)
children.append(self._left_title)
children.append(self._right_title)
children.extend(self.tables)
children.extend(self.images)
if self.legend_ is not None:
children.append(self.legend_)
children.append(self.patch)
return children
def contains(self, mouseevent):
"""
Test whether the mouse event occurred in the axes.
Returns *True* / *False*, {}
"""
if callable(self._contains):
return self._contains(self, mouseevent)
return self.patch.contains(mouseevent)
def contains_point(self, point):
"""
Returns *True* if the point (tuple of x,y) is inside the axes
(the area defined by the its patch). A pixel coordinate is
required.
"""
return self.patch.contains_point(point, radius=1.0)
def pick(self, *args):
"""Trigger pick event
Call signature::
pick(mouseevent)
each child artist will fire a pick event if mouseevent is over
the artist and the artist has picker set
"""
martist.Artist.pick(self, args[0])
def get_default_bbox_extra_artists(self):
return [artist for artist in self.get_children()
if artist.get_visible()]
def get_tightbbox(self, renderer, call_axes_locator=True):
"""
Return the tight bounding box of the axes.
The dimension of the Bbox in canvas coordinate.
If *call_axes_locator* is *False*, it does not call the
_axes_locator attribute, which is necessary to get the correct
bounding box. ``call_axes_locator==False`` can be used if the
caller is only intereted in the relative size of the tightbbox
compared to the axes bbox.
"""
bb = []
if not self.get_visible():
return None
locator = self.get_axes_locator()
if locator and call_axes_locator:
pos = locator(self, renderer)
self.apply_aspect(pos)
else:
self.apply_aspect()
bb.append(self.get_window_extent(renderer))
if self.title.get_visible():
bb.append(self.title.get_window_extent(renderer))
if self._left_title.get_visible():
bb.append(self._left_title.get_window_extent(renderer))
if self._right_title.get_visible():
bb.append(self._right_title.get_window_extent(renderer))
bb_xaxis = self.xaxis.get_tightbbox(renderer)
if bb_xaxis:
bb.append(bb_xaxis)
bb_yaxis = self.yaxis.get_tightbbox(renderer)
if bb_yaxis:
bb.append(bb_yaxis)
for child in self.get_children():
if isinstance(child, OffsetBox) and child.get_visible():
bb.append(child.get_window_extent(renderer))
elif isinstance(child, Legend) and child.get_visible():
bb.append(child._legend_box.get_window_extent(renderer))
_bbox = mtransforms.Bbox.union(
[b for b in bb if b.width != 0 or b.height != 0])
return _bbox
def _make_twin_axes(self, *kl, **kwargs):
"""
Make a twinx axes of self. This is used for twinx and twiny.
"""
# Typically, SubplotBase._make_twin_axes is called instead of this.
# There is also an override in axes_grid1/axes_divider.py.
if 'sharex' in kwargs and 'sharey' in kwargs:
raise ValueError("Twinned Axes may share only one axis.")
ax2 = self.figure.add_axes(self.get_position(True), *kl, **kwargs)
self.set_adjustable('datalim')
ax2.set_adjustable('datalim')
self._twinned_axes.join(self, ax2)
return ax2
def twinx(self):
"""
Create a twin Axes sharing the xaxis
Create a new Axes instance with an invisible x-axis and an independent
y-axis positioned opposite to the original one (i.e. at right). The
x-axis autoscale setting will be inherited from the original Axes.
To ensure that the tick marks of both y-axes align, see
`~matplotlib.ticker.LinearLocator`
Returns
-------
ax_twin : Axes
The newly created Axes instance
Notes
-----
For those who are 'picking' artists while using twinx, pick
events are only called for the artists in the top-most axes.
"""
ax2 = self._make_twin_axes(sharex=self)
ax2.yaxis.tick_right()
ax2.yaxis.set_label_position('right')
ax2.yaxis.set_offset_position('right')
ax2.set_autoscalex_on(self.get_autoscalex_on())
self.yaxis.tick_left()
ax2.xaxis.set_visible(False)
ax2.patch.set_visible(False)
return ax2
def twiny(self):
"""
Create a twin Axes sharing the yaxis
Create a new Axes instance with an invisible y-axis and an independent
x-axis positioned opposite to the original one (i.e. at top). The
y-axis autoscale setting will be inherited from the original Axes.
To ensure that the tick marks of both x-axes align, see
`~matplotlib.ticker.LinearLocator`
Returns
-------
ax_twin : Axes
The newly created Axes instance
Notes
-----
For those who are 'picking' artists while using twiny, pick
events are only called for the artists in the top-most axes.
"""
ax2 = self._make_twin_axes(sharey=self)
ax2.xaxis.tick_top()
ax2.xaxis.set_label_position('top')
ax2.set_autoscaley_on(self.get_autoscaley_on())
self.xaxis.tick_bottom()
ax2.yaxis.set_visible(False)
ax2.patch.set_visible(False)
return ax2
def get_shared_x_axes(self):
"""Return a reference to the shared axes Grouper object for x axes."""
return self._shared_x_axes
def get_shared_y_axes(self):
"""Return a reference to the shared axes Grouper object for y axes."""
return self._shared_y_axes
| 148,796 | 33.847073 | 79 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/axes/__init__.py | from __future__ import (absolute_import, division, print_function,
unicode_literals)
from ._subplots import *
from ._axes import *
| 156 | 25.166667 | 66 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/sphinxext/plot_directive.py | """
A directive for including a matplotlib plot in a Sphinx document.
By default, in HTML output, `plot` will include a .png file with a
link to a high-res .png and .pdf. In LaTeX output, it will include a
.pdf.
The source code for the plot may be included in one of three ways:
1. **A path to a source file** as the argument to the directive::
.. plot:: path/to/plot.py
When a path to a source file is given, the content of the
directive may optionally contain a caption for the plot::
.. plot:: path/to/plot.py
This is the caption for the plot
Additionally, one may specify the name of a function to call (with
no arguments) immediately after importing the module::
.. plot:: path/to/plot.py plot_function1
2. Included as **inline content** to the directive::
.. plot::
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
img = mpimg.imread('_static/stinkbug.png')
imgplot = plt.imshow(img)
3. Using **doctest** syntax::
.. plot::
A plotting example:
>>> import matplotlib.pyplot as plt
>>> plt.plot([1,2,3], [4,5,6])
Options
-------
The ``plot`` directive supports the following options:
format : {'python', 'doctest'}
Specify the format of the input
include-source : bool
Whether to display the source code. The default can be changed
using the `plot_include_source` variable in conf.py
encoding : str
If this source file is in a non-UTF8 or non-ASCII encoding,
the encoding must be specified using the `:encoding:` option.
The encoding will not be inferred using the ``-*- coding -*-``
metacomment.
context : bool or str
If provided, the code will be run in the context of all
previous plot directives for which the `:context:` option was
specified. This only applies to inline code plot directives,
not those run from files. If the ``:context: reset`` option is
specified, the context is reset for this and future plots, and
previous figures are closed prior to running the code.
``:context:close-figs`` keeps the context but closes previous figures
before running the code.
nofigs : bool
If specified, the code block will be run, but no figures will
be inserted. This is usually useful with the ``:context:``
option.
Additionally, this directive supports all of the options of the
`image` directive, except for `target` (since plot will add its own
target). These include `alt`, `height`, `width`, `scale`, `align` and
`class`.
Configuration options
---------------------
The plot directive has the following configuration options:
plot_include_source
Default value for the include-source option
plot_html_show_source_link
Whether to show a link to the source in HTML.
plot_pre_code
Code that should be executed before each plot. If not specified or None
it will default to a string containing::
import numpy as np
from matplotlib import pyplot as plt
plot_basedir
Base directory, to which ``plot::`` file names are relative
to. (If None or empty, file names are relative to the
directory where the file containing the directive is.)
plot_formats
File formats to generate. List of tuples or strings::
[(suffix, dpi), suffix, ...]
that determine the file format and the DPI. For entries whose
DPI was omitted, sensible defaults are chosen. When passing from
the command line through sphinx_build the list should be passed as
suffix:dpi,suffix:dpi, ....
plot_html_show_formats
Whether to show links to the files in HTML.
plot_rcparams
A dictionary containing any non-standard rcParams that should
be applied before each plot.
plot_apply_rcparams
By default, rcParams are applied when `context` option is not used in
a plot directive. This configuration option overrides this behavior
and applies rcParams before each plot.
plot_working_directory
By default, the working directory will be changed to the directory of
the example, so the code can get at its data files, if any. Also its
path will be added to `sys.path` so it can import any helper modules
sitting beside it. This configuration option can be used to specify
a central directory (also added to `sys.path`) where data files and
helper modules for all code are located.
plot_template
Provide a customized template for preparing restructured text.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
from six.moves import xrange
import sys, os, shutil, io, re, textwrap
from os.path import relpath
import traceback
import warnings
if not six.PY3:
import cStringIO
from docutils.parsers.rst import directives
from docutils.parsers.rst.directives.images import Image
align = Image.align
import sphinx
sphinx_version = sphinx.__version__.split(".")
# The split is necessary for sphinx beta versions where the string is
# '6b1'
sphinx_version = tuple([int(re.split('[^0-9]', x)[0])
for x in sphinx_version[:2]])
import jinja2 # Sphinx dependency.
import matplotlib
import matplotlib.cbook as cbook
try:
with warnings.catch_warnings(record=True):
warnings.simplefilter("error", UserWarning)
matplotlib.use('Agg')
except UserWarning:
import matplotlib.pyplot as plt
plt.switch_backend("Agg")
else:
import matplotlib.pyplot as plt
from matplotlib import _pylab_helpers
__version__ = 2
#------------------------------------------------------------------------------
# Registration hook
#------------------------------------------------------------------------------
def plot_directive(name, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
"""Implementation of the ``.. plot::`` directive.
See the module docstring for details.
"""
return run(arguments, content, options, state_machine, state, lineno)
def _option_boolean(arg):
if not arg or not arg.strip():
# no argument given, assume used as a flag
return True
elif arg.strip().lower() in ('no', '0', 'false'):
return False
elif arg.strip().lower() in ('yes', '1', 'true'):
return True
else:
raise ValueError('"%s" unknown boolean' % arg)
def _option_context(arg):
if arg in [None, 'reset', 'close-figs']:
return arg
raise ValueError("argument should be None or 'reset' or 'close-figs'")
def _option_format(arg):
return directives.choice(arg, ('python', 'doctest'))
def _option_align(arg):
return directives.choice(arg, ("top", "middle", "bottom", "left", "center",
"right"))
def mark_plot_labels(app, document):
"""
To make plots referenceable, we need to move the reference from
the "htmlonly" (or "latexonly") node to the actual figure node
itself.
"""
for name, explicit in six.iteritems(document.nametypes):
if not explicit:
continue
labelid = document.nameids[name]
if labelid is None:
continue
node = document.ids[labelid]
if node.tagname in ('html_only', 'latex_only'):
for n in node:
if n.tagname == 'figure':
sectname = name
for c in n:
if c.tagname == 'caption':
sectname = c.astext()
break
node['ids'].remove(labelid)
node['names'].remove(name)
n['ids'].append(labelid)
n['names'].append(name)
document.settings.env.labels[name] = \
document.settings.env.docname, labelid, sectname
break
def setup(app):
setup.app = app
setup.config = app.config
setup.confdir = app.confdir
options = {'alt': directives.unchanged,
'height': directives.length_or_unitless,
'width': directives.length_or_percentage_or_unitless,
'scale': directives.nonnegative_int,
'align': _option_align,
'class': directives.class_option,
'include-source': _option_boolean,
'format': _option_format,
'context': _option_context,
'nofigs': directives.flag,
'encoding': directives.encoding
}
app.add_directive('plot', plot_directive, True, (0, 2, False), **options)
app.add_config_value('plot_pre_code', None, True)
app.add_config_value('plot_include_source', False, True)
app.add_config_value('plot_html_show_source_link', True, True)
app.add_config_value('plot_formats', ['png', 'hires.png', 'pdf'], True)
app.add_config_value('plot_basedir', None, True)
app.add_config_value('plot_html_show_formats', True, True)
app.add_config_value('plot_rcparams', {}, True)
app.add_config_value('plot_apply_rcparams', False, True)
app.add_config_value('plot_working_directory', None, True)
app.add_config_value('plot_template', None, True)
app.connect(str('doctree-read'), mark_plot_labels)
metadata = {'parallel_read_safe': True, 'parallel_write_safe': True}
return metadata
#------------------------------------------------------------------------------
# Doctest handling
#------------------------------------------------------------------------------
def contains_doctest(text):
try:
# check if it's valid Python as-is
compile(text, '<string>', 'exec')
return False
except SyntaxError:
pass
r = re.compile(r'^\s*>>>', re.M)
m = r.search(text)
return bool(m)
def unescape_doctest(text):
"""
Extract code from a piece of text, which contains either Python code
or doctests.
"""
if not contains_doctest(text):
return text
code = ""
for line in text.split("\n"):
m = re.match(r'^\s*(>>>|\.\.\.) (.*)$', line)
if m:
code += m.group(2) + "\n"
elif line.strip():
code += "# " + line.strip() + "\n"
else:
code += "\n"
return code
def split_code_at_show(text):
"""
Split code at plt.show()
"""
parts = []
is_doctest = contains_doctest(text)
part = []
for line in text.split("\n"):
if (not is_doctest and line.strip() == 'plt.show()') or \
(is_doctest and line.strip() == '>>> plt.show()'):
part.append(line)
parts.append("\n".join(part))
part = []
else:
part.append(line)
if "\n".join(part).strip():
parts.append("\n".join(part))
return parts
def remove_coding(text):
r"""
Remove the coding comment, which six.exec\_ doesn't like.
"""
sub_re = re.compile("^#\s*-\*-\s*coding:\s*.*-\*-$", flags=re.MULTILINE)
return sub_re.sub("", text)
#------------------------------------------------------------------------------
# Template
#------------------------------------------------------------------------------
TEMPLATE = """
{{ source_code }}
{{ only_html }}
{% if source_link or (html_show_formats and not multi_image) %}
(
{%- if source_link -%}
`Source code <{{ source_link }}>`__
{%- endif -%}
{%- if html_show_formats and not multi_image -%}
{%- for img in images -%}
{%- for fmt in img.formats -%}
{%- if source_link or not loop.first -%}, {% endif -%}
`{{ fmt }} <{{ dest_dir }}/{{ img.basename }}.{{ fmt }}>`__
{%- endfor -%}
{%- endfor -%}
{%- endif -%}
)
{% endif %}
{% for img in images %}
.. figure:: {{ build_dir }}/{{ img.basename }}.{{ default_fmt }}
{% for option in options -%}
{{ option }}
{% endfor %}
{% if html_show_formats and multi_image -%}
(
{%- for fmt in img.formats -%}
{%- if not loop.first -%}, {% endif -%}
`{{ fmt }} <{{ dest_dir }}/{{ img.basename }}.{{ fmt }}>`__
{%- endfor -%}
)
{%- endif -%}
{{ caption }}
{% endfor %}
{{ only_latex }}
{% for img in images %}
{% if 'pdf' in img.formats -%}
.. figure:: {{ build_dir }}/{{ img.basename }}.pdf
{% for option in options -%}
{{ option }}
{% endfor %}
{{ caption }}
{% endif -%}
{% endfor %}
{{ only_texinfo }}
{% for img in images %}
.. image:: {{ build_dir }}/{{ img.basename }}.png
{% for option in options -%}
{{ option }}
{% endfor %}
{% endfor %}
"""
exception_template = """
.. htmlonly::
[`source code <%(linkdir)s/%(basename)s.py>`__]
Exception occurred rendering plot.
"""
# the context of the plot for all directives specified with the
# :context: option
plot_context = dict()
class ImageFile(object):
def __init__(self, basename, dirname):
self.basename = basename
self.dirname = dirname
self.formats = []
def filename(self, format):
return os.path.join(self.dirname, "%s.%s" % (self.basename, format))
def filenames(self):
return [self.filename(fmt) for fmt in self.formats]
def out_of_date(original, derived):
"""
Returns True if derivative is out-of-date wrt original,
both of which are full file paths.
"""
return (not os.path.exists(derived) or
(os.path.exists(original) and
os.stat(derived).st_mtime < os.stat(original).st_mtime))
class PlotError(RuntimeError):
pass
def run_code(code, code_path, ns=None, function_name=None):
"""
Import a Python module from a path, and run the function given by
name, if function_name is not None.
"""
# Change the working directory to the directory of the example, so
# it can get at its data files, if any. Add its path to sys.path
# so it can import any helper modules sitting beside it.
if six.PY2:
pwd = os.getcwdu()
else:
pwd = os.getcwd()
old_sys_path = list(sys.path)
if setup.config.plot_working_directory is not None:
try:
os.chdir(setup.config.plot_working_directory)
except OSError as err:
raise OSError(str(err) + '\n`plot_working_directory` option in'
'Sphinx configuration file must be a valid '
'directory path')
except TypeError as err:
raise TypeError(str(err) + '\n`plot_working_directory` option in '
'Sphinx configuration file must be a string or '
'None')
sys.path.insert(0, setup.config.plot_working_directory)
elif code_path is not None:
dirname = os.path.abspath(os.path.dirname(code_path))
os.chdir(dirname)
sys.path.insert(0, dirname)
# Reset sys.argv
old_sys_argv = sys.argv
sys.argv = [code_path]
# Redirect stdout
stdout = sys.stdout
if six.PY3:
sys.stdout = io.StringIO()
else:
sys.stdout = cStringIO.StringIO()
# Assign a do-nothing print function to the namespace. There
# doesn't seem to be any other way to provide a way to (not) print
# that works correctly across Python 2 and 3.
def _dummy_print(*arg, **kwarg):
pass
try:
try:
code = unescape_doctest(code)
if ns is None:
ns = {}
if not ns:
if setup.config.plot_pre_code is None:
six.exec_(six.text_type("import numpy as np\n" +
"from matplotlib import pyplot as plt\n"), ns)
else:
six.exec_(six.text_type(setup.config.plot_pre_code), ns)
ns['print'] = _dummy_print
if "__main__" in code:
six.exec_("__name__ = '__main__'", ns)
code = remove_coding(code)
six.exec_(code, ns)
if function_name is not None:
six.exec_(function_name + "()", ns)
except (Exception, SystemExit) as err:
raise PlotError(traceback.format_exc())
finally:
os.chdir(pwd)
sys.argv = old_sys_argv
sys.path[:] = old_sys_path
sys.stdout = stdout
return ns
def clear_state(plot_rcparams, close=True):
if close:
plt.close('all')
matplotlib.rc_file_defaults()
matplotlib.rcParams.update(plot_rcparams)
def get_plot_formats(config):
default_dpi = {'png': 80, 'hires.png': 200, 'pdf': 200}
formats = []
plot_formats = config.plot_formats
if isinstance(plot_formats, six.string_types):
# String Sphinx < 1.3, Split on , to mimic
# Sphinx 1.3 and later. Sphinx 1.3 always
# returns a list.
plot_formats = plot_formats.split(',')
for fmt in plot_formats:
if isinstance(fmt, six.string_types):
if ':' in fmt:
suffix, dpi = fmt.split(':')
formats.append((str(suffix), int(dpi)))
else:
formats.append((fmt, default_dpi.get(fmt, 80)))
elif type(fmt) in (tuple, list) and len(fmt) == 2:
formats.append((str(fmt[0]), int(fmt[1])))
else:
raise PlotError('invalid image format "%r" in plot_formats' % fmt)
return formats
def render_figures(code, code_path, output_dir, output_base, context,
function_name, config, context_reset=False,
close_figs=False):
"""
Run a pyplot script and save the images in *output_dir*.
Save the images under *output_dir* with file names derived from
*output_base*
"""
formats = get_plot_formats(config)
# -- Try to determine if all images already exist
code_pieces = split_code_at_show(code)
# Look for single-figure output files first
all_exists = True
img = ImageFile(output_base, output_dir)
for format, dpi in formats:
if out_of_date(code_path, img.filename(format)):
all_exists = False
break
img.formats.append(format)
if all_exists:
return [(code, [img])]
# Then look for multi-figure output files
results = []
all_exists = True
for i, code_piece in enumerate(code_pieces):
images = []
for j in xrange(1000):
if len(code_pieces) > 1:
img = ImageFile('%s_%02d_%02d' % (output_base, i, j),
output_dir)
else:
img = ImageFile('%s_%02d' % (output_base, j), output_dir)
for format, dpi in formats:
if out_of_date(code_path, img.filename(format)):
all_exists = False
break
img.formats.append(format)
# assume that if we have one, we have them all
if not all_exists:
all_exists = (j > 0)
break
images.append(img)
if not all_exists:
break
results.append((code_piece, images))
if all_exists:
return results
# We didn't find the files, so build them
results = []
if context:
ns = plot_context
else:
ns = {}
if context_reset:
clear_state(config.plot_rcparams)
plot_context.clear()
close_figs = not context or close_figs
for i, code_piece in enumerate(code_pieces):
if not context or config.plot_apply_rcparams:
clear_state(config.plot_rcparams, close_figs)
elif close_figs:
plt.close('all')
run_code(code_piece, code_path, ns, function_name)
images = []
fig_managers = _pylab_helpers.Gcf.get_all_fig_managers()
for j, figman in enumerate(fig_managers):
if len(fig_managers) == 1 and len(code_pieces) == 1:
img = ImageFile(output_base, output_dir)
elif len(code_pieces) == 1:
img = ImageFile("%s_%02d" % (output_base, j), output_dir)
else:
img = ImageFile("%s_%02d_%02d" % (output_base, i, j),
output_dir)
images.append(img)
for format, dpi in formats:
try:
figman.canvas.figure.savefig(img.filename(format), dpi=dpi)
except Exception as err:
raise PlotError(traceback.format_exc())
img.formats.append(format)
results.append((code_piece, images))
if not context or config.plot_apply_rcparams:
clear_state(config.plot_rcparams, close=not context)
return results
def run(arguments, content, options, state_machine, state, lineno):
document = state_machine.document
config = document.settings.env.config
nofigs = 'nofigs' in options
formats = get_plot_formats(config)
default_fmt = formats[0][0]
options.setdefault('include-source', config.plot_include_source)
keep_context = 'context' in options
context_opt = None if not keep_context else options['context']
rst_file = document.attributes['source']
rst_dir = os.path.dirname(rst_file)
if len(arguments):
if not config.plot_basedir:
source_file_name = os.path.join(setup.app.builder.srcdir,
directives.uri(arguments[0]))
else:
source_file_name = os.path.join(setup.confdir, config.plot_basedir,
directives.uri(arguments[0]))
# If there is content, it will be passed as a caption.
caption = '\n'.join(content)
# If the optional function name is provided, use it
if len(arguments) == 2:
function_name = arguments[1]
else:
function_name = None
with io.open(source_file_name, 'r', encoding='utf-8') as fd:
code = fd.read()
output_base = os.path.basename(source_file_name)
else:
source_file_name = rst_file
code = textwrap.dedent("\n".join(map(six.text_type, content)))
counter = document.attributes.get('_plot_counter', 0) + 1
document.attributes['_plot_counter'] = counter
base, ext = os.path.splitext(os.path.basename(source_file_name))
output_base = '%s-%d.py' % (base, counter)
function_name = None
caption = ''
base, source_ext = os.path.splitext(output_base)
if source_ext in ('.py', '.rst', '.txt'):
output_base = base
else:
source_ext = ''
# ensure that LaTeX includegraphics doesn't choke in foo.bar.pdf filenames
output_base = output_base.replace('.', '-')
# is it in doctest format?
is_doctest = contains_doctest(code)
if 'format' in options:
if options['format'] == 'python':
is_doctest = False
else:
is_doctest = True
# determine output directory name fragment
source_rel_name = relpath(source_file_name, setup.confdir)
source_rel_dir = os.path.dirname(source_rel_name)
while source_rel_dir.startswith(os.path.sep):
source_rel_dir = source_rel_dir[1:]
# build_dir: where to place output files (temporarily)
build_dir = os.path.join(os.path.dirname(setup.app.doctreedir),
'plot_directive',
source_rel_dir)
# get rid of .. in paths, also changes pathsep
# see note in Python docs for warning about symbolic links on Windows.
# need to compare source and dest paths at end
build_dir = os.path.normpath(build_dir)
if not os.path.exists(build_dir):
os.makedirs(build_dir)
# output_dir: final location in the builder's directory
dest_dir = os.path.abspath(os.path.join(setup.app.builder.outdir,
source_rel_dir))
if not os.path.exists(dest_dir):
os.makedirs(dest_dir) # no problem here for me, but just use built-ins
# how to link to files from the RST file
dest_dir_link = os.path.join(relpath(setup.confdir, rst_dir),
source_rel_dir).replace(os.path.sep, '/')
try:
build_dir_link = relpath(build_dir, rst_dir).replace(os.path.sep, '/')
except ValueError:
# on Windows, relpath raises ValueError when path and start are on
# different mounts/drives
build_dir_link = build_dir
source_link = dest_dir_link + '/' + output_base + source_ext
# make figures
try:
results = render_figures(code,
source_file_name,
build_dir,
output_base,
keep_context,
function_name,
config,
context_reset=context_opt == 'reset',
close_figs=context_opt == 'close-figs')
errors = []
except PlotError as err:
reporter = state.memo.reporter
sm = reporter.system_message(
2, "Exception occurred in plotting {}\n from {}:\n{}".format(
output_base, source_file_name, err),
line=lineno)
results = [(code, [])]
errors = [sm]
# Properly indent the caption
caption = '\n'.join(' ' + line.strip()
for line in caption.split('\n'))
# generate output restructuredtext
total_lines = []
for j, (code_piece, images) in enumerate(results):
if options['include-source']:
if is_doctest:
lines = ['']
lines += [row.rstrip() for row in code_piece.split('\n')]
else:
lines = ['.. code-block:: python', '']
lines += [' %s' % row.rstrip()
for row in code_piece.split('\n')]
source_code = "\n".join(lines)
else:
source_code = ""
if nofigs:
images = []
opts = [
':%s: %s' % (key, val) for key, val in six.iteritems(options)
if key in ('alt', 'height', 'width', 'scale', 'align', 'class')]
only_html = ".. only:: html"
only_latex = ".. only:: latex"
only_texinfo = ".. only:: texinfo"
# Not-None src_link signals the need for a source link in the generated
# html
if j == 0 and config.plot_html_show_source_link:
src_link = source_link
else:
src_link = None
result = jinja2.Template(config.plot_template or TEMPLATE).render(
default_fmt=default_fmt,
dest_dir=dest_dir_link,
build_dir=build_dir_link,
source_link=src_link,
multi_image=len(images) > 1,
only_html=only_html,
only_latex=only_latex,
only_texinfo=only_texinfo,
options=opts,
images=images,
source_code=source_code,
html_show_formats=config.plot_html_show_formats and len(images),
caption=caption)
total_lines.extend(result.split("\n"))
total_lines.extend("\n")
if total_lines:
state_machine.insert_input(total_lines, source=source_file_name)
# copy image files to builder's output directory, if necessary
if not os.path.exists(dest_dir):
cbook.mkdirs(dest_dir)
for code_piece, images in results:
for img in images:
for fn in img.filenames():
destimg = os.path.join(dest_dir, os.path.basename(fn))
if fn != destimg:
shutil.copyfile(fn, destimg)
# copy script (if necessary)
target_name = os.path.join(dest_dir, output_base + source_ext)
with io.open(target_name, 'w', encoding="utf-8") as f:
if source_file_name == rst_file:
code_escaped = unescape_doctest(code)
else:
code_escaped = code
f.write(code_escaped)
return errors
| 28,428 | 31.714614 | 79 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/sphinxext/mathmpl.py | from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
import os
import sys
from hashlib import md5
from docutils import nodes
from docutils.parsers.rst import directives
import warnings
from matplotlib import rcParams
from matplotlib.mathtext import MathTextParser
rcParams['mathtext.fontset'] = 'cm'
mathtext_parser = MathTextParser("Bitmap")
# Define LaTeX math node:
class latex_math(nodes.General, nodes.Element):
pass
def fontset_choice(arg):
return directives.choice(arg, ['cm', 'stix', 'stixsans'])
options_spec = {'fontset': fontset_choice}
def math_role(role, rawtext, text, lineno, inliner,
options={}, content=[]):
i = rawtext.find('`')
latex = rawtext[i+1:-1]
node = latex_math(rawtext)
node['latex'] = latex
node['fontset'] = options.get('fontset', 'cm')
return [node], []
math_role.options = options_spec
def math_directive(name, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
latex = ''.join(content)
node = latex_math(block_text)
node['latex'] = latex
node['fontset'] = options.get('fontset', 'cm')
return [node]
# This uses mathtext to render the expression
def latex2png(latex, filename, fontset='cm'):
latex = "$%s$" % latex
orig_fontset = rcParams['mathtext.fontset']
rcParams['mathtext.fontset'] = fontset
if os.path.exists(filename):
depth = mathtext_parser.get_depth(latex, dpi=100)
else:
try:
depth = mathtext_parser.to_png(filename, latex, dpi=100)
except:
warnings.warn("Could not render math expression %s" % latex,
Warning)
depth = 0
rcParams['mathtext.fontset'] = orig_fontset
sys.stdout.write("#")
sys.stdout.flush()
return depth
# LaTeX to HTML translation stuff:
def latex2html(node, source):
inline = isinstance(node.parent, nodes.TextElement)
latex = node['latex']
name = 'math-%s' % md5(latex.encode()).hexdigest()[-10:]
destdir = os.path.join(setup.app.builder.outdir, '_images', 'mathmpl')
if not os.path.exists(destdir):
os.makedirs(destdir)
dest = os.path.join(destdir, '%s.png' % name)
path = '/'.join((setup.app.builder.imgpath, 'mathmpl'))
depth = latex2png(latex, dest, node['fontset'])
if inline:
cls = ''
else:
cls = 'class="center" '
if inline and depth != 0:
style = 'style="position: relative; bottom: -%dpx"' % (depth + 1)
else:
style = ''
return '<img src="%s/%s.png" %s%s/>' % (path, name, cls, style)
def setup(app):
setup.app = app
# Add visit/depart methods to HTML-Translator:
def visit_latex_math_html(self, node):
source = self.document.attributes['source']
self.body.append(latex2html(node, source))
def depart_latex_math_html(self, node):
pass
# Add visit/depart methods to LaTeX-Translator:
def visit_latex_math_latex(self, node):
inline = isinstance(node.parent, nodes.TextElement)
if inline:
self.body.append('$%s$' % node['latex'])
else:
self.body.extend(['\\begin{equation}',
node['latex'],
'\\end{equation}'])
def depart_latex_math_latex(self, node):
pass
app.add_node(latex_math,
html=(visit_latex_math_html, depart_latex_math_html),
latex=(visit_latex_math_latex, depart_latex_math_latex))
app.add_role('math', math_role)
app.add_directive('math', math_directive,
True, (0, 0, 0), **options_spec)
metadata = {'parallel_read_safe': True, 'parallel_write_safe': True}
return metadata
| 3,822 | 29.830645 | 74 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/sphinxext/only_directives.py | #
# A pair of directives for inserting content that will only appear in
# either html or latex.
#
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import six
from docutils.nodes import Body, Element
class only_base(Body, Element):
def dont_traverse(self, *args, **kwargs):
return []
class html_only(only_base):
pass
class latex_only(only_base):
pass
def run(content, node_class, state, content_offset):
text = '\n'.join(content)
node = node_class(text)
state.nested_parse(content, content_offset, node)
return [node]
def html_only_directive(name, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
return run(content, html_only, state, content_offset)
def latex_only_directive(name, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
return run(content, latex_only, state, content_offset)
def builder_inited(app):
if app.builder.name == 'html':
latex_only.traverse = only_base.dont_traverse
else:
html_only.traverse = only_base.dont_traverse
def setup(app):
app.add_directive('htmlonly', html_only_directive, True, (0, 0, 0))
app.add_directive('latexonly', latex_only_directive, True, (0, 0, 0))
# This will *really* never see the light of day As it turns out,
# this results in "broken" image nodes since they never get
# processed, so best not to do this.
# app.connect('builder-inited', builder_inited)
# Add visit/depart methods to HTML-Translator:
def visit_perform(self, node):
pass
def depart_perform(self, node):
pass
def visit_ignore(self, node):
node.children = []
def depart_ignore(self, node):
node.children = []
app.add_node(html_only,
html=(visit_perform, depart_perform),
latex=(visit_ignore, depart_ignore))
app.add_node(latex_only,
latex=(visit_perform, depart_perform),
html=(visit_ignore, depart_ignore))
metadata = {'parallel_read_safe': True, 'parallel_write_safe': True}
return metadata
| 2,240 | 28.486842 | 75 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/sphinxext/__init__.py | from __future__ import (absolute_import, division, print_function,
unicode_literals)
| 109 | 35.666667 | 66 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/sphinxext/tests/conftest.py | from __future__ import (absolute_import, division, print_function,
unicode_literals)
from matplotlib.testing.conftest import (mpl_test_settings,
mpl_image_comparison_parameters,
pytest_configure, pytest_unconfigure)
| 323 | 45.285714 | 78 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/sphinxext/tests/test_tinypages.py | """ Tests for tinypages build using sphinx extensions """
import filecmp
from os.path import join as pjoin, dirname, isdir
from subprocess import call, Popen, PIPE
import sys
import pytest
from matplotlib import cbook
needs_sphinx = pytest.mark.skipif(
call([sys.executable, '-msphinx', '--help'], stdout=PIPE, stderr=PIPE),
reason="'{} -msphinx' does not return 0".format(sys.executable))
@cbook.deprecated("2.1", alternative="filecmp.cmp")
def file_same(file1, file2):
with open(file1, 'rb') as fobj:
contents1 = fobj.read()
with open(file2, 'rb') as fobj:
contents2 = fobj.read()
return contents1 == contents2
def test_tinypages(tmpdir):
html_dir = pjoin(str(tmpdir), 'html')
doctree_dir = pjoin(str(tmpdir), 'doctrees')
# Build the pages with warnings turned into errors
cmd = [sys.executable, '-msphinx', '-W', '-b', 'html', '-d', doctree_dir,
pjoin(dirname(__file__), 'tinypages'), html_dir]
proc = Popen(cmd, stdout=PIPE, stderr=PIPE)
out, err = proc.communicate()
assert proc.returncode == 0, \
"'{} -msphinx' failed with stdout:\n{}\nstderr:\n{}\n".format(
sys.executable, out, err)
assert isdir(html_dir)
def plot_file(num):
return pjoin(html_dir, 'some_plots-{0}.png'.format(num))
range_10, range_6, range_4 = [plot_file(i) for i in range(1, 4)]
# Plot 5 is range(6) plot
assert filecmp.cmp(range_6, plot_file(5))
# Plot 7 is range(4) plot
assert filecmp.cmp(range_4, plot_file(7))
# Plot 11 is range(10) plot
assert filecmp.cmp(range_10, plot_file(11))
# Plot 12 uses the old range(10) figure and the new range(6) figure
assert filecmp.cmp(range_10, plot_file('12_00'))
assert filecmp.cmp(range_6, plot_file('12_01'))
# Plot 13 shows close-figs in action
assert filecmp.cmp(range_4, plot_file(13))
# Plot 14 has included source
with open(pjoin(html_dir, 'some_plots.html'), 'rb') as fobj:
html_contents = fobj.read()
assert b'# Only a comment' in html_contents
# check plot defined in external file.
assert filecmp.cmp(range_4, pjoin(html_dir, 'range4.png'))
assert filecmp.cmp(range_6, pjoin(html_dir, 'range6.png'))
# check if figure caption made it into html file
assert b'This is the caption for plot 15.' in html_contents
| 2,350 | 35.169231 | 77 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/sphinxext/tests/__init__.py | # Make tests a package
| 23 | 11 | 22 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/sphinxext/tests/tinypages/range4.py | from matplotlib import pyplot as plt
plt.figure()
plt.plot(range(4))
plt.show()
| 81 | 12.666667 | 36 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/sphinxext/tests/tinypages/range6.py | from matplotlib import pyplot as plt
def range4():
'''This is never be called if plot_directive works as expected.'''
raise NotImplementedError
def range6():
'''This is the function that should be executed.'''
plt.figure()
plt.plot(range(6))
plt.show()
| 281 | 19.142857 | 70 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/sphinxext/tests/tinypages/conf.py | # -*- coding: utf-8 -*-
#
# tinypages documentation build configuration file, created by
# sphinx-quickstart on Tue Mar 18 11:58:34 2014.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
from os.path import join as pjoin, abspath
import sphinx
from distutils.version import LooseVersion
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
sys.path.insert(0, abspath(pjoin('..', '..')))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = ['matplotlib.sphinxext.plot_directive']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'tinypages'
copyright = u'2014, Matplotlib developers'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.1'
# The full version, including alpha/beta/rc tags.
release = '0.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
if LooseVersion(sphinx.__version__) >= LooseVersion('1.3'):
html_theme = 'classic'
else:
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'tinypagesdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
('index', 'tinypages.tex', u'tinypages Documentation',
u'Matplotlib developers', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'tinypages', u'tinypages Documentation',
[u'Matplotlib developers'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'tinypages', u'tinypages Documentation',
u'Matplotlib developers', 'tinypages', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
| 8,466 | 30.950943 | 79 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/style/core.py | from __future__ import absolute_import, division, print_function
import six
"""
Core functions and attributes for the matplotlib style library:
``use``
Select style sheet to override the current matplotlib settings.
``context``
Context manager to use a style sheet temporarily.
``available``
List available style sheets.
``library``
A dictionary of style names and matplotlib settings.
"""
import os
import re
import contextlib
import warnings
import matplotlib as mpl
from matplotlib import rc_params_from_file, rcParamsDefault
__all__ = ['use', 'context', 'available', 'library', 'reload_library']
BASE_LIBRARY_PATH = os.path.join(mpl.get_data_path(), 'stylelib')
# Users may want multiple library paths, so store a list of paths.
USER_LIBRARY_PATHS = [os.path.join(mpl._get_configdir(), 'stylelib')]
STYLE_EXTENSION = 'mplstyle'
STYLE_FILE_PATTERN = re.compile(r'([\S]+).%s$' % STYLE_EXTENSION)
# A list of rcParams that should not be applied from styles
STYLE_BLACKLIST = {
'interactive', 'backend', 'backend.qt4', 'webagg.port', 'webagg.address',
'webagg.port_retries', 'webagg.open_in_browser', 'backend_fallback',
'toolbar', 'timezone', 'datapath', 'figure.max_open_warning',
'savefig.directory', 'tk.window_focus', 'docstring.hardcopy'}
def _remove_blacklisted_style_params(d, warn=True):
o = {}
for key, val in d.items():
if key in STYLE_BLACKLIST:
if warn:
warnings.warn(
"Style includes a parameter, '{0}', that is not related "
"to style. Ignoring".format(key))
else:
o[key] = val
return o
def is_style_file(filename):
"""Return True if the filename looks like a style file."""
return STYLE_FILE_PATTERN.match(filename) is not None
def _apply_style(d, warn=True):
mpl.rcParams.update(_remove_blacklisted_style_params(d, warn=warn))
def use(style):
"""Use matplotlib style settings from a style specification.
The style name of 'default' is reserved for reverting back to
the default style settings.
Parameters
----------
style : str, dict, or list
A style specification. Valid options are:
+------+-------------------------------------------------------------+
| str | The name of a style or a path/URL to a style file. For a |
| | list of available style names, see `style.available`. |
+------+-------------------------------------------------------------+
| dict | Dictionary with valid key/value pairs for |
| | `matplotlib.rcParams`. |
+------+-------------------------------------------------------------+
| list | A list of style specifiers (str or dict) applied from first |
| | to last in the list. |
+------+-------------------------------------------------------------+
"""
style_alias = {'mpl20': 'default',
'mpl15': 'classic'}
if isinstance(style, six.string_types) or hasattr(style, 'keys'):
# If name is a single str or dict, make it a single element list.
styles = [style]
else:
styles = style
styles = (style_alias.get(s, s)
if isinstance(s, six.string_types)
else s
for s in styles)
for style in styles:
if not isinstance(style, six.string_types):
_apply_style(style)
elif style == 'default':
_apply_style(rcParamsDefault, warn=False)
elif style in library:
_apply_style(library[style])
else:
try:
rc = rc_params_from_file(style, use_default_template=False)
_apply_style(rc)
except IOError:
raise IOError(
"{!r} not found in the style library and input is not a "
"valid URL or path; see `style.available` for list of "
"available styles".format(style))
@contextlib.contextmanager
def context(style, after_reset=False):
"""Context manager for using style settings temporarily.
Parameters
----------
style : str, dict, or list
A style specification. Valid options are:
+------+-------------------------------------------------------------+
| str | The name of a style or a path/URL to a style file. For a |
| | list of available style names, see `style.available`. |
+------+-------------------------------------------------------------+
| dict | Dictionary with valid key/value pairs for |
| | `matplotlib.rcParams`. |
+------+-------------------------------------------------------------+
| list | A list of style specifiers (str or dict) applied from first |
| | to last in the list. |
+------+-------------------------------------------------------------+
after_reset : bool
If True, apply style after resetting settings to their defaults;
otherwise, apply style on top of the current settings.
"""
initial_settings = mpl.rcParams.copy()
if after_reset:
mpl.rcdefaults()
try:
use(style)
except:
# Restore original settings before raising errors during the update.
mpl.rcParams.update(initial_settings)
raise
else:
yield
finally:
mpl.rcParams.update(initial_settings)
def load_base_library():
"""Load style library defined in this package."""
library = dict()
library.update(read_style_directory(BASE_LIBRARY_PATH))
return library
def iter_user_libraries():
for stylelib_path in USER_LIBRARY_PATHS:
stylelib_path = os.path.expanduser(stylelib_path)
if os.path.exists(stylelib_path) and os.path.isdir(stylelib_path):
yield stylelib_path
def update_user_library(library):
"""Update style library with user-defined rc files"""
for stylelib_path in iter_user_libraries():
styles = read_style_directory(stylelib_path)
update_nested_dict(library, styles)
return library
def iter_style_files(style_dir):
"""Yield file path and name of styles in the given directory."""
for path in os.listdir(style_dir):
filename = os.path.basename(path)
if is_style_file(filename):
match = STYLE_FILE_PATTERN.match(filename)
path = os.path.abspath(os.path.join(style_dir, path))
yield path, match.groups()[0]
def read_style_directory(style_dir):
"""Return dictionary of styles defined in `style_dir`."""
styles = dict()
for path, name in iter_style_files(style_dir):
with warnings.catch_warnings(record=True) as warns:
styles[name] = rc_params_from_file(path,
use_default_template=False)
for w in warns:
message = 'In %s: %s' % (path, w.message)
warnings.warn(message)
return styles
def update_nested_dict(main_dict, new_dict):
"""Update nested dict (only level of nesting) with new values.
Unlike dict.update, this assumes that the values of the parent dict are
dicts (or dict-like), so you shouldn't replace the nested dict if it
already exists. Instead you should update the sub-dict.
"""
# update named styles specified by user
for name, rc_dict in six.iteritems(new_dict):
if name in main_dict:
main_dict[name].update(rc_dict)
else:
main_dict[name] = rc_dict
return main_dict
# Load style library
# ==================
_base_library = load_base_library()
library = None
available = []
def reload_library():
"""Reload style library."""
global library
available[:] = library = update_user_library(_base_library)
reload_library()
| 8,044 | 33.234043 | 78 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/matplotlib/style/__init__.py | from __future__ import absolute_import
from .core import use, context, available, library, reload_library
| 107 | 26 | 66 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/requests/auth.py | # -*- coding: utf-8 -*-
"""
requests.auth
~~~~~~~~~~~~~
This module contains the authentication handlers for Requests.
"""
import os
import re
import time
import hashlib
import threading
import warnings
from base64 import b64encode
from .compat import urlparse, str, basestring
from .cookies import extract_cookies_to_jar
from ._internal_utils import to_native_string
from .utils import parse_dict_header
CONTENT_TYPE_FORM_URLENCODED = 'application/x-www-form-urlencoded'
CONTENT_TYPE_MULTI_PART = 'multipart/form-data'
def _basic_auth_str(username, password):
"""Returns a Basic Auth string."""
# "I want us to put a big-ol' comment on top of it that
# says that this behaviour is dumb but we need to preserve
# it because people are relying on it."
# - Lukasa
#
# These are here solely to maintain backwards compatibility
# for things like ints. This will be removed in 3.0.0.
if not isinstance(username, basestring):
warnings.warn(
"Non-string usernames will no longer be supported in Requests "
"3.0.0. Please convert the object you've passed in ({0!r}) to "
"a string or bytes object in the near future to avoid "
"problems.".format(username),
category=DeprecationWarning,
)
username = str(username)
if not isinstance(password, basestring):
warnings.warn(
"Non-string passwords will no longer be supported in Requests "
"3.0.0. Please convert the object you've passed in ({0!r}) to "
"a string or bytes object in the near future to avoid "
"problems.".format(password),
category=DeprecationWarning,
)
password = str(password)
# -- End Removal --
if isinstance(username, str):
username = username.encode('latin1')
if isinstance(password, str):
password = password.encode('latin1')
authstr = 'Basic ' + to_native_string(
b64encode(b':'.join((username, password))).strip()
)
return authstr
class AuthBase(object):
"""Base class that all auth implementations derive from"""
def __call__(self, r):
raise NotImplementedError('Auth hooks must be callable.')
class HTTPBasicAuth(AuthBase):
"""Attaches HTTP Basic Authentication to the given Request object."""
def __init__(self, username, password):
self.username = username
self.password = password
def __eq__(self, other):
return all([
self.username == getattr(other, 'username', None),
self.password == getattr(other, 'password', None)
])
def __ne__(self, other):
return not self == other
def __call__(self, r):
r.headers['Authorization'] = _basic_auth_str(self.username, self.password)
return r
class HTTPProxyAuth(HTTPBasicAuth):
"""Attaches HTTP Proxy Authentication to a given Request object."""
def __call__(self, r):
r.headers['Proxy-Authorization'] = _basic_auth_str(self.username, self.password)
return r
class HTTPDigestAuth(AuthBase):
"""Attaches HTTP Digest Authentication to the given Request object."""
def __init__(self, username, password):
self.username = username
self.password = password
# Keep state in per-thread local storage
self._thread_local = threading.local()
def init_per_thread_state(self):
# Ensure state is initialized just once per-thread
if not hasattr(self._thread_local, 'init'):
self._thread_local.init = True
self._thread_local.last_nonce = ''
self._thread_local.nonce_count = 0
self._thread_local.chal = {}
self._thread_local.pos = None
self._thread_local.num_401_calls = None
def build_digest_header(self, method, url):
"""
:rtype: str
"""
realm = self._thread_local.chal['realm']
nonce = self._thread_local.chal['nonce']
qop = self._thread_local.chal.get('qop')
algorithm = self._thread_local.chal.get('algorithm')
opaque = self._thread_local.chal.get('opaque')
hash_utf8 = None
if algorithm is None:
_algorithm = 'MD5'
else:
_algorithm = algorithm.upper()
# lambdas assume digest modules are imported at the top level
if _algorithm == 'MD5' or _algorithm == 'MD5-SESS':
def md5_utf8(x):
if isinstance(x, str):
x = x.encode('utf-8')
return hashlib.md5(x).hexdigest()
hash_utf8 = md5_utf8
elif _algorithm == 'SHA':
def sha_utf8(x):
if isinstance(x, str):
x = x.encode('utf-8')
return hashlib.sha1(x).hexdigest()
hash_utf8 = sha_utf8
elif _algorithm == 'SHA-256':
def sha256_utf8(x):
if isinstance(x, str):
x = x.encode('utf-8')
return hashlib.sha256(x).hexdigest()
hash_utf8 = sha256_utf8
elif _algorithm == 'SHA-512':
def sha512_utf8(x):
if isinstance(x, str):
x = x.encode('utf-8')
return hashlib.sha512(x).hexdigest()
hash_utf8 = sha512_utf8
KD = lambda s, d: hash_utf8("%s:%s" % (s, d))
if hash_utf8 is None:
return None
# XXX not implemented yet
entdig = None
p_parsed = urlparse(url)
#: path is request-uri defined in RFC 2616 which should not be empty
path = p_parsed.path or "/"
if p_parsed.query:
path += '?' + p_parsed.query
A1 = '%s:%s:%s' % (self.username, realm, self.password)
A2 = '%s:%s' % (method, path)
HA1 = hash_utf8(A1)
HA2 = hash_utf8(A2)
if nonce == self._thread_local.last_nonce:
self._thread_local.nonce_count += 1
else:
self._thread_local.nonce_count = 1
ncvalue = '%08x' % self._thread_local.nonce_count
s = str(self._thread_local.nonce_count).encode('utf-8')
s += nonce.encode('utf-8')
s += time.ctime().encode('utf-8')
s += os.urandom(8)
cnonce = (hashlib.sha1(s).hexdigest()[:16])
if _algorithm == 'MD5-SESS':
HA1 = hash_utf8('%s:%s:%s' % (HA1, nonce, cnonce))
if not qop:
respdig = KD(HA1, "%s:%s" % (nonce, HA2))
elif qop == 'auth' or 'auth' in qop.split(','):
noncebit = "%s:%s:%s:%s:%s" % (
nonce, ncvalue, cnonce, 'auth', HA2
)
respdig = KD(HA1, noncebit)
else:
# XXX handle auth-int.
return None
self._thread_local.last_nonce = nonce
# XXX should the partial digests be encoded too?
base = 'username="%s", realm="%s", nonce="%s", uri="%s", ' \
'response="%s"' % (self.username, realm, nonce, path, respdig)
if opaque:
base += ', opaque="%s"' % opaque
if algorithm:
base += ', algorithm="%s"' % algorithm
if entdig:
base += ', digest="%s"' % entdig
if qop:
base += ', qop="auth", nc=%s, cnonce="%s"' % (ncvalue, cnonce)
return 'Digest %s' % (base)
def handle_redirect(self, r, **kwargs):
"""Reset num_401_calls counter on redirects."""
if r.is_redirect:
self._thread_local.num_401_calls = 1
def handle_401(self, r, **kwargs):
"""
Takes the given response and tries digest-auth, if needed.
:rtype: requests.Response
"""
# If response is not 4xx, do not auth
# See https://github.com/requests/requests/issues/3772
if not 400 <= r.status_code < 500:
self._thread_local.num_401_calls = 1
return r
if self._thread_local.pos is not None:
# Rewind the file position indicator of the body to where
# it was to resend the request.
r.request.body.seek(self._thread_local.pos)
s_auth = r.headers.get('www-authenticate', '')
if 'digest' in s_auth.lower() and self._thread_local.num_401_calls < 2:
self._thread_local.num_401_calls += 1
pat = re.compile(r'digest ', flags=re.IGNORECASE)
self._thread_local.chal = parse_dict_header(pat.sub('', s_auth, count=1))
# Consume content and release the original connection
# to allow our new request to reuse the same one.
r.content
r.close()
prep = r.request.copy()
extract_cookies_to_jar(prep._cookies, r.request, r.raw)
prep.prepare_cookies(prep._cookies)
prep.headers['Authorization'] = self.build_digest_header(
prep.method, prep.url)
_r = r.connection.send(prep, **kwargs)
_r.history.append(r)
_r.request = prep
return _r
self._thread_local.num_401_calls = 1
return r
def __call__(self, r):
# Initialize per-thread state, if needed
self.init_per_thread_state()
# If we have a saved nonce, skip the 401
if self._thread_local.last_nonce:
r.headers['Authorization'] = self.build_digest_header(r.method, r.url)
try:
self._thread_local.pos = r.body.tell()
except AttributeError:
# In the case of HTTPDigestAuth being reused and the body of
# the previous request was a file-like object, pos has the
# file position of the previous body. Ensure it's set to
# None.
self._thread_local.pos = None
r.register_hook('response', self.handle_401)
r.register_hook('response', self.handle_redirect)
self._thread_local.num_401_calls = 1
return r
def __eq__(self, other):
return all([
self.username == getattr(other, 'username', None),
self.password == getattr(other, 'password', None)
])
def __ne__(self, other):
return not self == other
| 10,208 | 32.362745 | 88 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/requests/hooks.py | # -*- coding: utf-8 -*-
"""
requests.hooks
~~~~~~~~~~~~~~
This module provides the capabilities for the Requests hooks system.
Available hooks:
``response``:
The response generated from a Request.
"""
HOOKS = ['response']
def default_hooks():
return dict((event, []) for event in HOOKS)
# TODO: response is the only one
def dispatch_hook(key, hooks, hook_data, **kwargs):
"""Dispatches a hook dictionary on a given piece of data."""
hooks = hooks or dict()
hooks = hooks.get(key)
if hooks:
if hasattr(hooks, '__call__'):
hooks = [hooks]
for hook in hooks:
_hook_data = hook(hook_data, **kwargs)
if _hook_data is not None:
hook_data = _hook_data
return hook_data
| 767 | 20.942857 | 68 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/requests/structures.py | # -*- coding: utf-8 -*-
"""
requests.structures
~~~~~~~~~~~~~~~~~~~
Data structures that power Requests.
"""
from .compat import OrderedDict, Mapping, MutableMapping
class CaseInsensitiveDict(MutableMapping):
"""A case-insensitive ``dict``-like object.
Implements all methods and operations of
``MutableMapping`` as well as dict's ``copy``. Also
provides ``lower_items``.
All keys are expected to be strings. The structure remembers the
case of the last key to be set, and ``iter(instance)``,
``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``
will contain case-sensitive keys. However, querying and contains
testing is case insensitive::
cid = CaseInsensitiveDict()
cid['Accept'] = 'application/json'
cid['aCCEPT'] == 'application/json' # True
list(cid) == ['Accept'] # True
For example, ``headers['content-encoding']`` will return the
value of a ``'Content-Encoding'`` response header, regardless
of how the header name was originally stored.
If the constructor, ``.update``, or equality comparison
operations are given keys that have equal ``.lower()``s, the
behavior is undefined.
"""
def __init__(self, data=None, **kwargs):
self._store = OrderedDict()
if data is None:
data = {}
self.update(data, **kwargs)
def __setitem__(self, key, value):
# Use the lowercased key for lookups, but store the actual
# key alongside the value.
self._store[key.lower()] = (key, value)
def __getitem__(self, key):
return self._store[key.lower()][1]
def __delitem__(self, key):
del self._store[key.lower()]
def __iter__(self):
return (casedkey for casedkey, mappedvalue in self._store.values())
def __len__(self):
return len(self._store)
def lower_items(self):
"""Like iteritems(), but with all lowercase keys."""
return (
(lowerkey, keyval[1])
for (lowerkey, keyval)
in self._store.items()
)
def __eq__(self, other):
if isinstance(other, Mapping):
other = CaseInsensitiveDict(other)
else:
return NotImplemented
# Compare insensitively
return dict(self.lower_items()) == dict(other.lower_items())
# Copy is required
def copy(self):
return CaseInsensitiveDict(self._store.values())
def __repr__(self):
return str(dict(self.items()))
class LookupDict(dict):
"""Dictionary lookup object."""
def __init__(self, name=None):
self.name = name
super(LookupDict, self).__init__()
def __repr__(self):
return '<lookup \'%s\'>' % (self.name)
def __getitem__(self, key):
# We allow fall-through here, so values default to None
return self.__dict__.get(key, None)
def get(self, key, default=None):
return self.__dict__.get(key, default)
| 2,981 | 27.673077 | 75 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/requests/exceptions.py | # -*- coding: utf-8 -*-
"""
requests.exceptions
~~~~~~~~~~~~~~~~~~~
This module contains the set of Requests' exceptions.
"""
from urllib3.exceptions import HTTPError as BaseHTTPError
class RequestException(IOError):
"""There was an ambiguous exception that occurred while handling your
request.
"""
def __init__(self, *args, **kwargs):
"""Initialize RequestException with `request` and `response` objects."""
response = kwargs.pop('response', None)
self.response = response
self.request = kwargs.pop('request', None)
if (response is not None and not self.request and
hasattr(response, 'request')):
self.request = self.response.request
super(RequestException, self).__init__(*args, **kwargs)
class HTTPError(RequestException):
"""An HTTP error occurred."""
class ConnectionError(RequestException):
"""A Connection error occurred."""
class ProxyError(ConnectionError):
"""A proxy error occurred."""
class SSLError(ConnectionError):
"""An SSL error occurred."""
class Timeout(RequestException):
"""The request timed out.
Catching this error will catch both
:exc:`~requests.exceptions.ConnectTimeout` and
:exc:`~requests.exceptions.ReadTimeout` errors.
"""
class ConnectTimeout(ConnectionError, Timeout):
"""The request timed out while trying to connect to the remote server.
Requests that produced this error are safe to retry.
"""
class ReadTimeout(Timeout):
"""The server did not send any data in the allotted amount of time."""
class URLRequired(RequestException):
"""A valid URL is required to make a request."""
class TooManyRedirects(RequestException):
"""Too many redirects."""
class MissingSchema(RequestException, ValueError):
"""The URL schema (e.g. http or https) is missing."""
class InvalidSchema(RequestException, ValueError):
"""See defaults.py for valid schemas."""
class InvalidURL(RequestException, ValueError):
"""The URL provided was somehow invalid."""
class InvalidHeader(RequestException, ValueError):
"""The header value provided was somehow invalid."""
class InvalidProxyURL(InvalidURL):
"""The proxy URL provided is invalid."""
class ChunkedEncodingError(RequestException):
"""The server declared chunked encoding but sent an invalid chunk."""
class ContentDecodingError(RequestException, BaseHTTPError):
"""Failed to decode response content"""
class StreamConsumedError(RequestException, TypeError):
"""The content for this response was already consumed"""
class RetryError(RequestException):
"""Custom retries logic failed"""
class UnrewindableBodyError(RequestException):
"""Requests encountered an error when trying to rewind a body"""
# Warnings
class RequestsWarning(Warning):
"""Base warning for Requests."""
pass
class FileModeWarning(RequestsWarning, DeprecationWarning):
"""A file was opened in text mode, but Requests determined its binary length."""
pass
class RequestsDependencyWarning(RequestsWarning):
"""An imported dependency doesn't match the expected version range."""
pass
| 3,185 | 24.086614 | 84 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/requests/cookies.py | # -*- coding: utf-8 -*-
"""
requests.cookies
~~~~~~~~~~~~~~~~
Compatibility code to be able to use `cookielib.CookieJar` with requests.
requests.utils imports from here, so be careful with imports.
"""
import copy
import time
import calendar
from ._internal_utils import to_native_string
from .compat import cookielib, urlparse, urlunparse, Morsel, MutableMapping
try:
import threading
except ImportError:
import dummy_threading as threading
class MockRequest(object):
"""Wraps a `requests.Request` to mimic a `urllib2.Request`.
The code in `cookielib.CookieJar` expects this interface in order to correctly
manage cookie policies, i.e., determine whether a cookie can be set, given the
domains of the request and the cookie.
The original request object is read-only. The client is responsible for collecting
the new headers via `get_new_headers()` and interpreting them appropriately. You
probably want `get_cookie_header`, defined below.
"""
def __init__(self, request):
self._r = request
self._new_headers = {}
self.type = urlparse(self._r.url).scheme
def get_type(self):
return self.type
def get_host(self):
return urlparse(self._r.url).netloc
def get_origin_req_host(self):
return self.get_host()
def get_full_url(self):
# Only return the response's URL if the user hadn't set the Host
# header
if not self._r.headers.get('Host'):
return self._r.url
# If they did set it, retrieve it and reconstruct the expected domain
host = to_native_string(self._r.headers['Host'], encoding='utf-8')
parsed = urlparse(self._r.url)
# Reconstruct the URL as we expect it
return urlunparse([
parsed.scheme, host, parsed.path, parsed.params, parsed.query,
parsed.fragment
])
def is_unverifiable(self):
return True
def has_header(self, name):
return name in self._r.headers or name in self._new_headers
def get_header(self, name, default=None):
return self._r.headers.get(name, self._new_headers.get(name, default))
def add_header(self, key, val):
"""cookielib has no legitimate use for this method; add it back if you find one."""
raise NotImplementedError("Cookie headers should be added with add_unredirected_header()")
def add_unredirected_header(self, name, value):
self._new_headers[name] = value
def get_new_headers(self):
return self._new_headers
@property
def unverifiable(self):
return self.is_unverifiable()
@property
def origin_req_host(self):
return self.get_origin_req_host()
@property
def host(self):
return self.get_host()
class MockResponse(object):
"""Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`.
...what? Basically, expose the parsed HTTP headers from the server response
the way `cookielib` expects to see them.
"""
def __init__(self, headers):
"""Make a MockResponse for `cookielib` to read.
:param headers: a httplib.HTTPMessage or analogous carrying the headers
"""
self._headers = headers
def info(self):
return self._headers
def getheaders(self, name):
self._headers.getheaders(name)
def extract_cookies_to_jar(jar, request, response):
"""Extract the cookies from the response into a CookieJar.
:param jar: cookielib.CookieJar (not necessarily a RequestsCookieJar)
:param request: our own requests.Request object
:param response: urllib3.HTTPResponse object
"""
if not (hasattr(response, '_original_response') and
response._original_response):
return
# the _original_response field is the wrapped httplib.HTTPResponse object,
req = MockRequest(request)
# pull out the HTTPMessage with the headers and put it in the mock:
res = MockResponse(response._original_response.msg)
jar.extract_cookies(res, req)
def get_cookie_header(jar, request):
"""
Produce an appropriate Cookie header string to be sent with `request`, or None.
:rtype: str
"""
r = MockRequest(request)
jar.add_cookie_header(r)
return r.get_new_headers().get('Cookie')
def remove_cookie_by_name(cookiejar, name, domain=None, path=None):
"""Unsets a cookie by name, by default over all domains and paths.
Wraps CookieJar.clear(), is O(n).
"""
clearables = []
for cookie in cookiejar:
if cookie.name != name:
continue
if domain is not None and domain != cookie.domain:
continue
if path is not None and path != cookie.path:
continue
clearables.append((cookie.domain, cookie.path, cookie.name))
for domain, path, name in clearables:
cookiejar.clear(domain, path, name)
class CookieConflictError(RuntimeError):
"""There are two cookies that meet the criteria specified in the cookie jar.
Use .get and .set and include domain and path args in order to be more specific.
"""
class RequestsCookieJar(cookielib.CookieJar, MutableMapping):
"""Compatibility class; is a cookielib.CookieJar, but exposes a dict
interface.
This is the CookieJar we create by default for requests and sessions that
don't specify one, since some clients may expect response.cookies and
session.cookies to support dict operations.
Requests does not use the dict interface internally; it's just for
compatibility with external client code. All requests code should work
out of the box with externally provided instances of ``CookieJar``, e.g.
``LWPCookieJar`` and ``FileCookieJar``.
Unlike a regular CookieJar, this class is pickleable.
.. warning:: dictionary operations that are normally O(1) may be O(n).
"""
def get(self, name, default=None, domain=None, path=None):
"""Dict-like get() that also supports optional domain and path args in
order to resolve naming collisions from using one cookie jar over
multiple domains.
.. warning:: operation is O(n), not O(1).
"""
try:
return self._find_no_duplicates(name, domain, path)
except KeyError:
return default
def set(self, name, value, **kwargs):
"""Dict-like set() that also supports optional domain and path args in
order to resolve naming collisions from using one cookie jar over
multiple domains.
"""
# support client code that unsets cookies by assignment of a None value:
if value is None:
remove_cookie_by_name(self, name, domain=kwargs.get('domain'), path=kwargs.get('path'))
return
if isinstance(value, Morsel):
c = morsel_to_cookie(value)
else:
c = create_cookie(name, value, **kwargs)
self.set_cookie(c)
return c
def iterkeys(self):
"""Dict-like iterkeys() that returns an iterator of names of cookies
from the jar.
.. seealso:: itervalues() and iteritems().
"""
for cookie in iter(self):
yield cookie.name
def keys(self):
"""Dict-like keys() that returns a list of names of cookies from the
jar.
.. seealso:: values() and items().
"""
return list(self.iterkeys())
def itervalues(self):
"""Dict-like itervalues() that returns an iterator of values of cookies
from the jar.
.. seealso:: iterkeys() and iteritems().
"""
for cookie in iter(self):
yield cookie.value
def values(self):
"""Dict-like values() that returns a list of values of cookies from the
jar.
.. seealso:: keys() and items().
"""
return list(self.itervalues())
def iteritems(self):
"""Dict-like iteritems() that returns an iterator of name-value tuples
from the jar.
.. seealso:: iterkeys() and itervalues().
"""
for cookie in iter(self):
yield cookie.name, cookie.value
def items(self):
"""Dict-like items() that returns a list of name-value tuples from the
jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a
vanilla python dict of key value pairs.
.. seealso:: keys() and values().
"""
return list(self.iteritems())
def list_domains(self):
"""Utility method to list all the domains in the jar."""
domains = []
for cookie in iter(self):
if cookie.domain not in domains:
domains.append(cookie.domain)
return domains
def list_paths(self):
"""Utility method to list all the paths in the jar."""
paths = []
for cookie in iter(self):
if cookie.path not in paths:
paths.append(cookie.path)
return paths
def multiple_domains(self):
"""Returns True if there are multiple domains in the jar.
Returns False otherwise.
:rtype: bool
"""
domains = []
for cookie in iter(self):
if cookie.domain is not None and cookie.domain in domains:
return True
domains.append(cookie.domain)
return False # there is only one domain in jar
def get_dict(self, domain=None, path=None):
"""Takes as an argument an optional domain and path and returns a plain
old Python dict of name-value pairs of cookies that meet the
requirements.
:rtype: dict
"""
dictionary = {}
for cookie in iter(self):
if (
(domain is None or cookie.domain == domain) and
(path is None or cookie.path == path)
):
dictionary[cookie.name] = cookie.value
return dictionary
def __contains__(self, name):
try:
return super(RequestsCookieJar, self).__contains__(name)
except CookieConflictError:
return True
def __getitem__(self, name):
"""Dict-like __getitem__() for compatibility with client code. Throws
exception if there are more than one cookie with name. In that case,
use the more explicit get() method instead.
.. warning:: operation is O(n), not O(1).
"""
return self._find_no_duplicates(name)
def __setitem__(self, name, value):
"""Dict-like __setitem__ for compatibility with client code. Throws
exception if there is already a cookie of that name in the jar. In that
case, use the more explicit set() method instead.
"""
self.set(name, value)
def __delitem__(self, name):
"""Deletes a cookie given a name. Wraps ``cookielib.CookieJar``'s
``remove_cookie_by_name()``.
"""
remove_cookie_by_name(self, name)
def set_cookie(self, cookie, *args, **kwargs):
if hasattr(cookie.value, 'startswith') and cookie.value.startswith('"') and cookie.value.endswith('"'):
cookie.value = cookie.value.replace('\\"', '')
return super(RequestsCookieJar, self).set_cookie(cookie, *args, **kwargs)
def update(self, other):
"""Updates this jar with cookies from another CookieJar or dict-like"""
if isinstance(other, cookielib.CookieJar):
for cookie in other:
self.set_cookie(copy.copy(cookie))
else:
super(RequestsCookieJar, self).update(other)
def _find(self, name, domain=None, path=None):
"""Requests uses this method internally to get cookie values.
If there are conflicting cookies, _find arbitrarily chooses one.
See _find_no_duplicates if you want an exception thrown if there are
conflicting cookies.
:param name: a string containing name of cookie
:param domain: (optional) string containing domain of cookie
:param path: (optional) string containing path of cookie
:return: cookie.value
"""
for cookie in iter(self):
if cookie.name == name:
if domain is None or cookie.domain == domain:
if path is None or cookie.path == path:
return cookie.value
raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
def _find_no_duplicates(self, name, domain=None, path=None):
"""Both ``__get_item__`` and ``get`` call this function: it's never
used elsewhere in Requests.
:param name: a string containing name of cookie
:param domain: (optional) string containing domain of cookie
:param path: (optional) string containing path of cookie
:raises KeyError: if cookie is not found
:raises CookieConflictError: if there are multiple cookies
that match name and optionally domain and path
:return: cookie.value
"""
toReturn = None
for cookie in iter(self):
if cookie.name == name:
if domain is None or cookie.domain == domain:
if path is None or cookie.path == path:
if toReturn is not None: # if there are multiple cookies that meet passed in criteria
raise CookieConflictError('There are multiple cookies with name, %r' % (name))
toReturn = cookie.value # we will eventually return this as long as no cookie conflict
if toReturn:
return toReturn
raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
def __getstate__(self):
"""Unlike a normal CookieJar, this class is pickleable."""
state = self.__dict__.copy()
# remove the unpickleable RLock object
state.pop('_cookies_lock')
return state
def __setstate__(self, state):
"""Unlike a normal CookieJar, this class is pickleable."""
self.__dict__.update(state)
if '_cookies_lock' not in self.__dict__:
self._cookies_lock = threading.RLock()
def copy(self):
"""Return a copy of this RequestsCookieJar."""
new_cj = RequestsCookieJar()
new_cj.set_policy(self.get_policy())
new_cj.update(self)
return new_cj
def get_policy(self):
"""Return the CookiePolicy instance used."""
return self._policy
def _copy_cookie_jar(jar):
if jar is None:
return None
if hasattr(jar, 'copy'):
# We're dealing with an instance of RequestsCookieJar
return jar.copy()
# We're dealing with a generic CookieJar instance
new_jar = copy.copy(jar)
new_jar.clear()
for cookie in jar:
new_jar.set_cookie(copy.copy(cookie))
return new_jar
def create_cookie(name, value, **kwargs):
"""Make a cookie from underspecified parameters.
By default, the pair of `name` and `value` will be set for the domain ''
and sent on every request (this is sometimes called a "supercookie").
"""
result = dict(
version=0,
name=name,
value=value,
port=None,
domain='',
path='/',
secure=False,
expires=None,
discard=True,
comment=None,
comment_url=None,
rest={'HttpOnly': None},
rfc2109=False,)
badargs = set(kwargs) - set(result)
if badargs:
err = 'create_cookie() got unexpected keyword arguments: %s'
raise TypeError(err % list(badargs))
result.update(kwargs)
result['port_specified'] = bool(result['port'])
result['domain_specified'] = bool(result['domain'])
result['domain_initial_dot'] = result['domain'].startswith('.')
result['path_specified'] = bool(result['path'])
return cookielib.Cookie(**result)
def morsel_to_cookie(morsel):
"""Convert a Morsel object into a Cookie containing the one k/v pair."""
expires = None
if morsel['max-age']:
try:
expires = int(time.time() + int(morsel['max-age']))
except ValueError:
raise TypeError('max-age: %s must be integer' % morsel['max-age'])
elif morsel['expires']:
time_template = '%a, %d-%b-%Y %H:%M:%S GMT'
expires = calendar.timegm(
time.strptime(morsel['expires'], time_template)
)
return create_cookie(
comment=morsel['comment'],
comment_url=bool(morsel['comment']),
discard=False,
domain=morsel['domain'],
expires=expires,
name=morsel.key,
path=morsel['path'],
port=None,
rest={'HttpOnly': morsel['httponly']},
rfc2109=False,
secure=bool(morsel['secure']),
value=morsel.value,
version=morsel['version'] or 0,
)
def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True):
"""Returns a CookieJar from a key/value dictionary.
:param cookie_dict: Dict of key/values to insert into CookieJar.
:param cookiejar: (optional) A cookiejar to add the cookies to.
:param overwrite: (optional) If False, will not replace cookies
already in the jar with new ones.
"""
if cookiejar is None:
cookiejar = RequestsCookieJar()
if cookie_dict is not None:
names_from_jar = [cookie.name for cookie in cookiejar]
for name in cookie_dict:
if overwrite or (name not in names_from_jar):
cookiejar.set_cookie(create_cookie(name, cookie_dict[name]))
return cookiejar
def merge_cookies(cookiejar, cookies):
"""Add cookies to cookiejar and returns a merged CookieJar.
:param cookiejar: CookieJar object to add the cookies to.
:param cookies: Dictionary or CookieJar object to be added.
"""
if not isinstance(cookiejar, cookielib.CookieJar):
raise ValueError('You can only merge into CookieJar')
if isinstance(cookies, dict):
cookiejar = cookiejar_from_dict(
cookies, cookiejar=cookiejar, overwrite=False)
elif isinstance(cookies, cookielib.CookieJar):
try:
cookiejar.update(cookies)
except AttributeError:
for cookie_in_jar in cookies:
cookiejar.set_cookie(cookie_in_jar)
return cookiejar
| 18,346 | 32.541133 | 111 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/requests/__version__.py | # .-. .-. .-. . . .-. .-. .-. .-.
# |( |- |.| | | |- `-. | `-.
# ' ' `-' `-`.`-' `-' `-' ' `-'
__title__ = 'requests'
__description__ = 'Python HTTP for Humans.'
__url__ = 'http://python-requests.org'
__version__ = '2.19.1'
__build__ = 0x021901
__author__ = 'Kenneth Reitz'
__author_email__ = '[email protected]'
__license__ = 'Apache 2.0'
__copyright__ = 'Copyright 2018 Kenneth Reitz'
__cake__ = u'\u2728 \U0001f370 \u2728'
| 436 | 28.133333 | 46 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/requests/utils.py | # -*- coding: utf-8 -*-
"""
requests.utils
~~~~~~~~~~~~~~
This module provides utility functions that are used within Requests
that are also useful for external consumption.
"""
import codecs
import contextlib
import io
import os
import re
import socket
import struct
import sys
import tempfile
import warnings
import zipfile
from .__version__ import __version__
from . import certs
# to_native_string is unused here, but imported here for backwards compatibility
from ._internal_utils import to_native_string
from .compat import parse_http_list as _parse_list_header
from .compat import (
quote, urlparse, bytes, str, OrderedDict, unquote, getproxies,
proxy_bypass, urlunparse, basestring, integer_types, is_py3,
proxy_bypass_environment, getproxies_environment, Mapping)
from .cookies import cookiejar_from_dict
from .structures import CaseInsensitiveDict
from .exceptions import (
InvalidURL, InvalidHeader, FileModeWarning, UnrewindableBodyError)
NETRC_FILES = ('.netrc', '_netrc')
DEFAULT_CA_BUNDLE_PATH = certs.where()
if sys.platform == 'win32':
# provide a proxy_bypass version on Windows without DNS lookups
def proxy_bypass_registry(host):
try:
if is_py3:
import winreg
else:
import _winreg as winreg
except ImportError:
return False
try:
internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
r'Software\Microsoft\Windows\CurrentVersion\Internet Settings')
# ProxyEnable could be REG_SZ or REG_DWORD, normalizing it
proxyEnable = int(winreg.QueryValueEx(internetSettings,
'ProxyEnable')[0])
# ProxyOverride is almost always a string
proxyOverride = winreg.QueryValueEx(internetSettings,
'ProxyOverride')[0]
except OSError:
return False
if not proxyEnable or not proxyOverride:
return False
# make a check value list from the registry entry: replace the
# '<local>' string by the localhost entry and the corresponding
# canonical entry.
proxyOverride = proxyOverride.split(';')
# now check if we match one of the registry values.
for test in proxyOverride:
if test == '<local>':
if '.' not in host:
return True
test = test.replace(".", r"\.") # mask dots
test = test.replace("*", r".*") # change glob sequence
test = test.replace("?", r".") # change glob char
if re.match(test, host, re.I):
return True
return False
def proxy_bypass(host): # noqa
"""Return True, if the host should be bypassed.
Checks proxy settings gathered from the environment, if specified,
or the registry.
"""
if getproxies_environment():
return proxy_bypass_environment(host)
else:
return proxy_bypass_registry(host)
def dict_to_sequence(d):
"""Returns an internal sequence dictionary update."""
if hasattr(d, 'items'):
d = d.items()
return d
def super_len(o):
total_length = None
current_position = 0
if hasattr(o, '__len__'):
total_length = len(o)
elif hasattr(o, 'len'):
total_length = o.len
elif hasattr(o, 'fileno'):
try:
fileno = o.fileno()
except io.UnsupportedOperation:
pass
else:
total_length = os.fstat(fileno).st_size
# Having used fstat to determine the file length, we need to
# confirm that this file was opened up in binary mode.
if 'b' not in o.mode:
warnings.warn((
"Requests has determined the content-length for this "
"request using the binary size of the file: however, the "
"file has been opened in text mode (i.e. without the 'b' "
"flag in the mode). This may lead to an incorrect "
"content-length. In Requests 3.0, support will be removed "
"for files in text mode."),
FileModeWarning
)
if hasattr(o, 'tell'):
try:
current_position = o.tell()
except (OSError, IOError):
# This can happen in some weird situations, such as when the file
# is actually a special file descriptor like stdin. In this
# instance, we don't know what the length is, so set it to zero and
# let requests chunk it instead.
if total_length is not None:
current_position = total_length
else:
if hasattr(o, 'seek') and total_length is None:
# StringIO and BytesIO have seek but no useable fileno
try:
# seek to end of file
o.seek(0, 2)
total_length = o.tell()
# seek back to current position to support
# partially read file-like objects
o.seek(current_position or 0)
except (OSError, IOError):
total_length = 0
if total_length is None:
total_length = 0
return max(0, total_length - current_position)
def get_netrc_auth(url, raise_errors=False):
"""Returns the Requests tuple auth for a given url from netrc."""
try:
from netrc import netrc, NetrcParseError
netrc_path = None
for f in NETRC_FILES:
try:
loc = os.path.expanduser('~/{0}'.format(f))
except KeyError:
# os.path.expanduser can fail when $HOME is undefined and
# getpwuid fails. See http://bugs.python.org/issue20164 &
# https://github.com/requests/requests/issues/1846
return
if os.path.exists(loc):
netrc_path = loc
break
# Abort early if there isn't one.
if netrc_path is None:
return
ri = urlparse(url)
# Strip port numbers from netloc. This weird `if...encode`` dance is
# used for Python 3.2, which doesn't support unicode literals.
splitstr = b':'
if isinstance(url, str):
splitstr = splitstr.decode('ascii')
host = ri.netloc.split(splitstr)[0]
try:
_netrc = netrc(netrc_path).authenticators(host)
if _netrc:
# Return with login / password
login_i = (0 if _netrc[0] else 1)
return (_netrc[login_i], _netrc[2])
except (NetrcParseError, IOError):
# If there was a parsing error or a permissions issue reading the file,
# we'll just skip netrc auth unless explicitly asked to raise errors.
if raise_errors:
raise
# AppEngine hackiness.
except (ImportError, AttributeError):
pass
def guess_filename(obj):
"""Tries to guess the filename of the given object."""
name = getattr(obj, 'name', None)
if (name and isinstance(name, basestring) and name[0] != '<' and
name[-1] != '>'):
return os.path.basename(name)
def extract_zipped_paths(path):
"""Replace nonexistent paths that look like they refer to a member of a zip
archive with the location of an extracted copy of the target, or else
just return the provided path unchanged.
"""
if os.path.exists(path):
# this is already a valid path, no need to do anything further
return path
# find the first valid part of the provided path and treat that as a zip archive
# assume the rest of the path is the name of a member in the archive
archive, member = os.path.split(path)
while archive and not os.path.exists(archive):
archive, prefix = os.path.split(archive)
member = '/'.join([prefix, member])
if not zipfile.is_zipfile(archive):
return path
zip_file = zipfile.ZipFile(archive)
if member not in zip_file.namelist():
return path
# we have a valid zip archive and a valid member of that archive
tmp = tempfile.gettempdir()
extracted_path = os.path.join(tmp, *member.split('/'))
if not os.path.exists(extracted_path):
extracted_path = zip_file.extract(member, path=tmp)
return extracted_path
def from_key_val_list(value):
"""Take an object and test to see if it can be represented as a
dictionary. Unless it can not be represented as such, return an
OrderedDict, e.g.,
::
>>> from_key_val_list([('key', 'val')])
OrderedDict([('key', 'val')])
>>> from_key_val_list('string')
ValueError: need more than 1 value to unpack
>>> from_key_val_list({'key': 'val'})
OrderedDict([('key', 'val')])
:rtype: OrderedDict
"""
if value is None:
return None
if isinstance(value, (str, bytes, bool, int)):
raise ValueError('cannot encode objects that are not 2-tuples')
return OrderedDict(value)
def to_key_val_list(value):
"""Take an object and test to see if it can be represented as a
dictionary. If it can be, return a list of tuples, e.g.,
::
>>> to_key_val_list([('key', 'val')])
[('key', 'val')]
>>> to_key_val_list({'key': 'val'})
[('key', 'val')]
>>> to_key_val_list('string')
ValueError: cannot encode objects that are not 2-tuples.
:rtype: list
"""
if value is None:
return None
if isinstance(value, (str, bytes, bool, int)):
raise ValueError('cannot encode objects that are not 2-tuples')
if isinstance(value, Mapping):
value = value.items()
return list(value)
# From mitsuhiko/werkzeug (used with permission).
def parse_list_header(value):
"""Parse lists as described by RFC 2068 Section 2.
In particular, parse comma-separated lists where the elements of
the list may include quoted-strings. A quoted-string could
contain a comma. A non-quoted string could have quotes in the
middle. Quotes are removed automatically after parsing.
It basically works like :func:`parse_set_header` just that items
may appear multiple times and case sensitivity is preserved.
The return value is a standard :class:`list`:
>>> parse_list_header('token, "quoted value"')
['token', 'quoted value']
To create a header from the :class:`list` again, use the
:func:`dump_header` function.
:param value: a string with a list header.
:return: :class:`list`
:rtype: list
"""
result = []
for item in _parse_list_header(value):
if item[:1] == item[-1:] == '"':
item = unquote_header_value(item[1:-1])
result.append(item)
return result
# From mitsuhiko/werkzeug (used with permission).
def parse_dict_header(value):
"""Parse lists of key, value pairs as described by RFC 2068 Section 2 and
convert them into a python dict:
>>> d = parse_dict_header('foo="is a fish", bar="as well"')
>>> type(d) is dict
True
>>> sorted(d.items())
[('bar', 'as well'), ('foo', 'is a fish')]
If there is no value for a key it will be `None`:
>>> parse_dict_header('key_without_value')
{'key_without_value': None}
To create a header from the :class:`dict` again, use the
:func:`dump_header` function.
:param value: a string with a dict header.
:return: :class:`dict`
:rtype: dict
"""
result = {}
for item in _parse_list_header(value):
if '=' not in item:
result[item] = None
continue
name, value = item.split('=', 1)
if value[:1] == value[-1:] == '"':
value = unquote_header_value(value[1:-1])
result[name] = value
return result
# From mitsuhiko/werkzeug (used with permission).
def unquote_header_value(value, is_filename=False):
r"""Unquotes a header value. (Reversal of :func:`quote_header_value`).
This does not use the real unquoting but what browsers are actually
using for quoting.
:param value: the header value to unquote.
:rtype: str
"""
if value and value[0] == value[-1] == '"':
# this is not the real unquoting, but fixing this so that the
# RFC is met will result in bugs with internet explorer and
# probably some other browsers as well. IE for example is
# uploading files with "C:\foo\bar.txt" as filename
value = value[1:-1]
# if this is a filename and the starting characters look like
# a UNC path, then just return the value without quotes. Using the
# replace sequence below on a UNC path has the effect of turning
# the leading double slash into a single slash and then
# _fix_ie_filename() doesn't work correctly. See #458.
if not is_filename or value[:2] != '\\\\':
return value.replace('\\\\', '\\').replace('\\"', '"')
return value
def dict_from_cookiejar(cj):
"""Returns a key/value dictionary from a CookieJar.
:param cj: CookieJar object to extract cookies from.
:rtype: dict
"""
cookie_dict = {}
for cookie in cj:
cookie_dict[cookie.name] = cookie.value
return cookie_dict
def add_dict_to_cookiejar(cj, cookie_dict):
"""Returns a CookieJar from a key/value dictionary.
:param cj: CookieJar to insert cookies into.
:param cookie_dict: Dict of key/values to insert into CookieJar.
:rtype: CookieJar
"""
return cookiejar_from_dict(cookie_dict, cj)
def get_encodings_from_content(content):
"""Returns encodings from given content string.
:param content: bytestring to extract encodings from.
"""
warnings.warn((
'In requests 3.0, get_encodings_from_content will be removed. For '
'more information, please see the discussion on issue #2266. (This'
' warning should only appear once.)'),
DeprecationWarning)
charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]', flags=re.I)
pragma_re = re.compile(r'<meta.*?content=["\']*;?charset=(.+?)["\'>]', flags=re.I)
xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]')
return (charset_re.findall(content) +
pragma_re.findall(content) +
xml_re.findall(content))
def _parse_content_type_header(header):
"""Returns content type and parameters from given header
:param header: string
:return: tuple containing content type and dictionary of
parameters
"""
tokens = header.split(';')
content_type, params = tokens[0].strip(), tokens[1:]
params_dict = {}
items_to_strip = "\"' "
for param in params:
param = param.strip()
if param:
key, value = param, True
index_of_equals = param.find("=")
if index_of_equals != -1:
key = param[:index_of_equals].strip(items_to_strip)
value = param[index_of_equals + 1:].strip(items_to_strip)
params_dict[key] = value
return content_type, params_dict
def get_encoding_from_headers(headers):
"""Returns encodings from given HTTP Header Dict.
:param headers: dictionary to extract encoding from.
:rtype: str
"""
content_type = headers.get('content-type')
if not content_type:
return None
content_type, params = _parse_content_type_header(content_type)
if 'charset' in params:
return params['charset'].strip("'\"")
if 'text' in content_type:
return 'ISO-8859-1'
def stream_decode_response_unicode(iterator, r):
"""Stream decodes a iterator."""
if r.encoding is None:
for item in iterator:
yield item
return
decoder = codecs.getincrementaldecoder(r.encoding)(errors='replace')
for chunk in iterator:
rv = decoder.decode(chunk)
if rv:
yield rv
rv = decoder.decode(b'', final=True)
if rv:
yield rv
def iter_slices(string, slice_length):
"""Iterate over slices of a string."""
pos = 0
if slice_length is None or slice_length <= 0:
slice_length = len(string)
while pos < len(string):
yield string[pos:pos + slice_length]
pos += slice_length
def get_unicode_from_response(r):
"""Returns the requested content back in unicode.
:param r: Response object to get unicode content from.
Tried:
1. charset from content-type
2. fall back and replace all unicode characters
:rtype: str
"""
warnings.warn((
'In requests 3.0, get_unicode_from_response will be removed. For '
'more information, please see the discussion on issue #2266. (This'
' warning should only appear once.)'),
DeprecationWarning)
tried_encodings = []
# Try charset from content-type
encoding = get_encoding_from_headers(r.headers)
if encoding:
try:
return str(r.content, encoding)
except UnicodeError:
tried_encodings.append(encoding)
# Fall back:
try:
return str(r.content, encoding, errors='replace')
except TypeError:
return r.content
# The unreserved URI characters (RFC 3986)
UNRESERVED_SET = frozenset(
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789-._~")
def unquote_unreserved(uri):
"""Un-escape any percent-escape sequences in a URI that are unreserved
characters. This leaves all reserved, illegal and non-ASCII bytes encoded.
:rtype: str
"""
parts = uri.split('%')
for i in range(1, len(parts)):
h = parts[i][0:2]
if len(h) == 2 and h.isalnum():
try:
c = chr(int(h, 16))
except ValueError:
raise InvalidURL("Invalid percent-escape sequence: '%s'" % h)
if c in UNRESERVED_SET:
parts[i] = c + parts[i][2:]
else:
parts[i] = '%' + parts[i]
else:
parts[i] = '%' + parts[i]
return ''.join(parts)
def requote_uri(uri):
"""Re-quote the given URI.
This function passes the given URI through an unquote/quote cycle to
ensure that it is fully and consistently quoted.
:rtype: str
"""
safe_with_percent = "!#$%&'()*+,/:;=?@[]~"
safe_without_percent = "!#$&'()*+,/:;=?@[]~"
try:
# Unquote only the unreserved characters
# Then quote only illegal characters (do not quote reserved,
# unreserved, or '%')
return quote(unquote_unreserved(uri), safe=safe_with_percent)
except InvalidURL:
# We couldn't unquote the given URI, so let's try quoting it, but
# there may be unquoted '%'s in the URI. We need to make sure they're
# properly quoted so they do not cause issues elsewhere.
return quote(uri, safe=safe_without_percent)
def address_in_network(ip, net):
"""This function allows you to check if an IP belongs to a network subnet
Example: returns True if ip = 192.168.1.1 and net = 192.168.1.0/24
returns False if ip = 192.168.1.1 and net = 192.168.100.0/24
:rtype: bool
"""
ipaddr = struct.unpack('=L', socket.inet_aton(ip))[0]
netaddr, bits = net.split('/')
netmask = struct.unpack('=L', socket.inet_aton(dotted_netmask(int(bits))))[0]
network = struct.unpack('=L', socket.inet_aton(netaddr))[0] & netmask
return (ipaddr & netmask) == (network & netmask)
def dotted_netmask(mask):
"""Converts mask from /xx format to xxx.xxx.xxx.xxx
Example: if mask is 24 function returns 255.255.255.0
:rtype: str
"""
bits = 0xffffffff ^ (1 << 32 - mask) - 1
return socket.inet_ntoa(struct.pack('>I', bits))
def is_ipv4_address(string_ip):
"""
:rtype: bool
"""
try:
socket.inet_aton(string_ip)
except socket.error:
return False
return True
def is_valid_cidr(string_network):
"""
Very simple check of the cidr format in no_proxy variable.
:rtype: bool
"""
if string_network.count('/') == 1:
try:
mask = int(string_network.split('/')[1])
except ValueError:
return False
if mask < 1 or mask > 32:
return False
try:
socket.inet_aton(string_network.split('/')[0])
except socket.error:
return False
else:
return False
return True
@contextlib.contextmanager
def set_environ(env_name, value):
"""Set the environment variable 'env_name' to 'value'
Save previous value, yield, and then restore the previous value stored in
the environment variable 'env_name'.
If 'value' is None, do nothing"""
value_changed = value is not None
if value_changed:
old_value = os.environ.get(env_name)
os.environ[env_name] = value
try:
yield
finally:
if value_changed:
if old_value is None:
del os.environ[env_name]
else:
os.environ[env_name] = old_value
def should_bypass_proxies(url, no_proxy):
"""
Returns whether we should bypass proxies or not.
:rtype: bool
"""
# Prioritize lowercase environment variables over uppercase
# to keep a consistent behaviour with other http projects (curl, wget).
get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper())
# First check whether no_proxy is defined. If it is, check that the URL
# we're getting isn't in the no_proxy list.
no_proxy_arg = no_proxy
if no_proxy is None:
no_proxy = get_proxy('no_proxy')
parsed = urlparse(url)
if no_proxy:
# We need to check whether we match here. We need to see if we match
# the end of the hostname, both with and without the port.
no_proxy = (
host for host in no_proxy.replace(' ', '').split(',') if host
)
if is_ipv4_address(parsed.hostname):
for proxy_ip in no_proxy:
if is_valid_cidr(proxy_ip):
if address_in_network(parsed.hostname, proxy_ip):
return True
elif parsed.hostname == proxy_ip:
# If no_proxy ip was defined in plain IP notation instead of cidr notation &
# matches the IP of the index
return True
else:
host_with_port = parsed.hostname
if parsed.port:
host_with_port += ':{0}'.format(parsed.port)
for host in no_proxy:
if parsed.hostname.endswith(host) or host_with_port.endswith(host):
# The URL does match something in no_proxy, so we don't want
# to apply the proxies on this URL.
return True
# If the system proxy settings indicate that this URL should be bypassed,
# don't proxy.
# The proxy_bypass function is incredibly buggy on OS X in early versions
# of Python 2.6, so allow this call to fail. Only catch the specific
# exceptions we've seen, though: this call failing in other ways can reveal
# legitimate problems.
with set_environ('no_proxy', no_proxy_arg):
try:
bypass = proxy_bypass(parsed.hostname)
except (TypeError, socket.gaierror):
bypass = False
if bypass:
return True
return False
def get_environ_proxies(url, no_proxy=None):
"""
Return a dict of environment proxies.
:rtype: dict
"""
if should_bypass_proxies(url, no_proxy=no_proxy):
return {}
else:
return getproxies()
def select_proxy(url, proxies):
"""Select a proxy for the url, if applicable.
:param url: The url being for the request
:param proxies: A dictionary of schemes or schemes and hosts to proxy URLs
"""
proxies = proxies or {}
urlparts = urlparse(url)
if urlparts.hostname is None:
return proxies.get(urlparts.scheme, proxies.get('all'))
proxy_keys = [
urlparts.scheme + '://' + urlparts.hostname,
urlparts.scheme,
'all://' + urlparts.hostname,
'all',
]
proxy = None
for proxy_key in proxy_keys:
if proxy_key in proxies:
proxy = proxies[proxy_key]
break
return proxy
def default_user_agent(name="python-requests"):
"""
Return a string representing the default user agent.
:rtype: str
"""
return '%s/%s' % (name, __version__)
def default_headers():
"""
:rtype: requests.structures.CaseInsensitiveDict
"""
return CaseInsensitiveDict({
'User-Agent': default_user_agent(),
'Accept-Encoding': ', '.join(('gzip', 'deflate')),
'Accept': '*/*',
'Connection': 'keep-alive',
})
def parse_header_links(value):
"""Return a list of parsed link headers proxies.
i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",<http://.../back.jpeg>; rel=back;type="image/jpeg"
:rtype: list
"""
links = []
replace_chars = ' \'"'
value = value.strip(replace_chars)
if not value:
return links
for val in re.split(', *<', value):
try:
url, params = val.split(';', 1)
except ValueError:
url, params = val, ''
link = {'url': url.strip('<> \'"')}
for param in params.split(';'):
try:
key, value = param.split('=')
except ValueError:
break
link[key.strip(replace_chars)] = value.strip(replace_chars)
links.append(link)
return links
# Null bytes; no need to recreate these on each call to guess_json_utf
_null = '\x00'.encode('ascii') # encoding to ASCII for Python 3
_null2 = _null * 2
_null3 = _null * 3
def guess_json_utf(data):
"""
:rtype: str
"""
# JSON always starts with two ASCII characters, so detection is as
# easy as counting the nulls and from their location and count
# determine the encoding. Also detect a BOM, if present.
sample = data[:4]
if sample in (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE):
return 'utf-32' # BOM included
if sample[:3] == codecs.BOM_UTF8:
return 'utf-8-sig' # BOM included, MS style (discouraged)
if sample[:2] in (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE):
return 'utf-16' # BOM included
nullcount = sample.count(_null)
if nullcount == 0:
return 'utf-8'
if nullcount == 2:
if sample[::2] == _null2: # 1st and 3rd are null
return 'utf-16-be'
if sample[1::2] == _null2: # 2nd and 4th are null
return 'utf-16-le'
# Did not detect 2 valid UTF-16 ascii-range characters
if nullcount == 3:
if sample[:3] == _null3:
return 'utf-32-be'
if sample[1:] == _null3:
return 'utf-32-le'
# Did not detect a valid UTF-32 ascii-range character
return None
def prepend_scheme_if_needed(url, new_scheme):
"""Given a URL that may or may not have a scheme, prepend the given scheme.
Does not replace a present scheme with the one provided as an argument.
:rtype: str
"""
scheme, netloc, path, params, query, fragment = urlparse(url, new_scheme)
# urlparse is a finicky beast, and sometimes decides that there isn't a
# netloc present. Assume that it's being over-cautious, and switch netloc
# and path if urlparse decided there was no netloc.
if not netloc:
netloc, path = path, netloc
return urlunparse((scheme, netloc, path, params, query, fragment))
def get_auth_from_url(url):
"""Given a url with authentication components, extract them into a tuple of
username,password.
:rtype: (str,str)
"""
parsed = urlparse(url)
try:
auth = (unquote(parsed.username), unquote(parsed.password))
except (AttributeError, TypeError):
auth = ('', '')
return auth
# Moved outside of function to avoid recompile every call
_CLEAN_HEADER_REGEX_BYTE = re.compile(b'^\\S[^\\r\\n]*$|^$')
_CLEAN_HEADER_REGEX_STR = re.compile(r'^\S[^\r\n]*$|^$')
def check_header_validity(header):
"""Verifies that header value is a string which doesn't contain
leading whitespace or return characters. This prevents unintended
header injection.
:param header: tuple, in the format (name, value).
"""
name, value = header
if isinstance(value, bytes):
pat = _CLEAN_HEADER_REGEX_BYTE
else:
pat = _CLEAN_HEADER_REGEX_STR
try:
if not pat.match(value):
raise InvalidHeader("Invalid return character or leading space in header: %s" % name)
except TypeError:
raise InvalidHeader("Value for header {%s: %s} must be of type str or "
"bytes, not %s" % (name, value, type(value)))
def urldefragauth(url):
"""
Given a url remove the fragment and the authentication part.
:rtype: str
"""
scheme, netloc, path, params, query, fragment = urlparse(url)
# see func:`prepend_scheme_if_needed`
if not netloc:
netloc, path = path, netloc
netloc = netloc.rsplit('@', 1)[-1]
return urlunparse((scheme, netloc, path, params, query, ''))
def rewind_body(prepared_request):
"""Move file pointer back to its recorded starting position
so it can be read again on redirect.
"""
body_seek = getattr(prepared_request.body, 'seek', None)
if body_seek is not None and isinstance(prepared_request._body_position, integer_types):
try:
body_seek(prepared_request._body_position)
except (IOError, OSError):
raise UnrewindableBodyError("An error occurred when rewinding request "
"body for redirect.")
else:
raise UnrewindableBodyError("Unable to rewind request body for redirect.")
| 30,156 | 29.86694 | 118 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/requests/packages.py | import sys
# This code exists for backwards compatibility reasons.
# I don't like it either. Just look the other way. :)
for package in ('urllib3', 'idna', 'chardet'):
locals()[package] = __import__(package)
# This traversal is apparently necessary such that the identities are
# preserved (requests.packages.urllib3.* is urllib3.*)
for mod in list(sys.modules):
if mod == package or mod.startswith(package + '.'):
sys.modules['requests.packages.' + mod] = sys.modules[mod]
# Kinda cool, though, right?
| 542 | 35.2 | 73 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/requests/status_codes.py | # -*- coding: utf-8 -*-
"""
The ``codes`` object defines a mapping from common names for HTTP statuses
to their numerical codes, accessible either as attributes or as dictionary
items.
>>> requests.codes['temporary_redirect']
307
>>> requests.codes.teapot
418
>>> requests.codes['\o/']
200
Some codes have multiple names, and both upper- and lower-case versions of
the names are allowed. For example, ``codes.ok``, ``codes.OK``, and
``codes.okay`` all correspond to the HTTP status code 200.
"""
from .structures import LookupDict
_codes = {
# Informational.
100: ('continue',),
101: ('switching_protocols',),
102: ('processing',),
103: ('checkpoint',),
122: ('uri_too_long', 'request_uri_too_long'),
200: ('ok', 'okay', 'all_ok', 'all_okay', 'all_good', '\\o/', '✓'),
201: ('created',),
202: ('accepted',),
203: ('non_authoritative_info', 'non_authoritative_information'),
204: ('no_content',),
205: ('reset_content', 'reset'),
206: ('partial_content', 'partial'),
207: ('multi_status', 'multiple_status', 'multi_stati', 'multiple_stati'),
208: ('already_reported',),
226: ('im_used',),
# Redirection.
300: ('multiple_choices',),
301: ('moved_permanently', 'moved', '\\o-'),
302: ('found',),
303: ('see_other', 'other'),
304: ('not_modified',),
305: ('use_proxy',),
306: ('switch_proxy',),
307: ('temporary_redirect', 'temporary_moved', 'temporary'),
308: ('permanent_redirect',
'resume_incomplete', 'resume',), # These 2 to be removed in 3.0
# Client Error.
400: ('bad_request', 'bad'),
401: ('unauthorized',),
402: ('payment_required', 'payment'),
403: ('forbidden',),
404: ('not_found', '-o-'),
405: ('method_not_allowed', 'not_allowed'),
406: ('not_acceptable',),
407: ('proxy_authentication_required', 'proxy_auth', 'proxy_authentication'),
408: ('request_timeout', 'timeout'),
409: ('conflict',),
410: ('gone',),
411: ('length_required',),
412: ('precondition_failed', 'precondition'),
413: ('request_entity_too_large',),
414: ('request_uri_too_large',),
415: ('unsupported_media_type', 'unsupported_media', 'media_type'),
416: ('requested_range_not_satisfiable', 'requested_range', 'range_not_satisfiable'),
417: ('expectation_failed',),
418: ('im_a_teapot', 'teapot', 'i_am_a_teapot'),
421: ('misdirected_request',),
422: ('unprocessable_entity', 'unprocessable'),
423: ('locked',),
424: ('failed_dependency', 'dependency'),
425: ('unordered_collection', 'unordered'),
426: ('upgrade_required', 'upgrade'),
428: ('precondition_required', 'precondition'),
429: ('too_many_requests', 'too_many'),
431: ('header_fields_too_large', 'fields_too_large'),
444: ('no_response', 'none'),
449: ('retry_with', 'retry'),
450: ('blocked_by_windows_parental_controls', 'parental_controls'),
451: ('unavailable_for_legal_reasons', 'legal_reasons'),
499: ('client_closed_request',),
# Server Error.
500: ('internal_server_error', 'server_error', '/o\\', '✗'),
501: ('not_implemented',),
502: ('bad_gateway',),
503: ('service_unavailable', 'unavailable'),
504: ('gateway_timeout',),
505: ('http_version_not_supported', 'http_version'),
506: ('variant_also_negotiates',),
507: ('insufficient_storage',),
509: ('bandwidth_limit_exceeded', 'bandwidth'),
510: ('not_extended',),
511: ('network_authentication_required', 'network_auth', 'network_authentication'),
}
codes = LookupDict(name='status_codes')
def _init():
for code, titles in _codes.items():
for title in titles:
setattr(codes, title, code)
if not title.startswith(('\\', '/')):
setattr(codes, title.upper(), code)
def doc(code):
names = ', '.join('``%s``' % n for n in _codes[code])
return '* %d: %s' % (code, names)
global __doc__
__doc__ = (__doc__ + '\n' +
'\n'.join(doc(code) for code in sorted(_codes))
if __doc__ is not None else None)
_init()
| 4,124 | 33.090909 | 89 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/requests/_internal_utils.py | # -*- coding: utf-8 -*-
"""
requests._internal_utils
~~~~~~~~~~~~~~
Provides utility functions that are consumed internally by Requests
which depend on extremely few external helpers (such as compat)
"""
from .compat import is_py2, builtin_str, str
def to_native_string(string, encoding='ascii'):
"""Given a string object, regardless of type, returns a representation of
that string in the native string type, encoding and decoding where
necessary. This assumes ASCII unless told otherwise.
"""
if isinstance(string, builtin_str):
out = string
else:
if is_py2:
out = string.encode(encoding)
else:
out = string.decode(encoding)
return out
def unicode_is_ascii(u_string):
"""Determine if unicode string only contains ASCII characters.
:param str u_string: unicode string to check. Must be unicode
and not Python 2 `str`.
:rtype: bool
"""
assert isinstance(u_string, str)
try:
u_string.encode('ascii')
return True
except UnicodeEncodeError:
return False
| 1,096 | 24.511628 | 77 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/requests/api.py | # -*- coding: utf-8 -*-
"""
requests.api
~~~~~~~~~~~~
This module implements the Requests API.
:copyright: (c) 2012 by Kenneth Reitz.
:license: Apache2, see LICENSE for more details.
"""
from . import sessions
def request(method, url, **kwargs):
"""Constructs and sends a :class:`Request <Request>`.
:param method: method for the new :class:`Request` object.
:param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
:param data: (optional) Dictionary or list of tuples ``[(key, value)]`` (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`.
:param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.
:param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
:param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.
:param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload.
``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')``
or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content-type'`` is a string
defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers
to add for the file.
:param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
:param timeout: (optional) How many seconds to wait for the server to send data
before giving up, as a float, or a :ref:`(connect timeout, read
timeout) <timeouts>` tuple.
:type timeout: float or tuple
:param allow_redirects: (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to ``True``.
:type allow_redirects: bool
:param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
:param verify: (optional) Either a boolean, in which case it controls whether we verify
the server's TLS certificate, or a string, in which case it must be a path
to a CA bundle to use. Defaults to ``True``.
:param stream: (optional) if ``False``, the response content will be immediately downloaded.
:param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.
:return: :class:`Response <Response>` object
:rtype: requests.Response
Usage::
>>> import requests
>>> req = requests.request('GET', 'http://httpbin.org/get')
<Response [200]>
"""
# By using the 'with' statement we are sure the session is closed, thus we
# avoid leaving sockets open which can trigger a ResourceWarning in some
# cases, and look like a memory leak in others.
with sessions.Session() as session:
return session.request(method=method, url=url, **kwargs)
def get(url, params=None, **kwargs):
r"""Sends a GET request.
:param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
kwargs.setdefault('allow_redirects', True)
return request('get', url, params=params, **kwargs)
def options(url, **kwargs):
r"""Sends an OPTIONS request.
:param url: URL for the new :class:`Request` object.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
kwargs.setdefault('allow_redirects', True)
return request('options', url, **kwargs)
def head(url, **kwargs):
r"""Sends a HEAD request.
:param url: URL for the new :class:`Request` object.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
kwargs.setdefault('allow_redirects', False)
return request('head', url, **kwargs)
def post(url, data=None, json=None, **kwargs):
r"""Sends a POST request.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`.
:param json: (optional) json data to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
return request('post', url, data=data, json=json, **kwargs)
def put(url, data=None, **kwargs):
r"""Sends a PUT request.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`.
:param json: (optional) json data to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
return request('put', url, data=data, **kwargs)
def patch(url, data=None, **kwargs):
r"""Sends a PATCH request.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`.
:param json: (optional) json data to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
return request('patch', url, data=data, **kwargs)
def delete(url, **kwargs):
r"""Sends a DELETE request.
:param url: URL for the new :class:`Request` object.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
"""
return request('delete', url, **kwargs)
| 6,261 | 39.928105 | 171 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/requests/help.py | """Module containing bug report helper(s)."""
from __future__ import print_function
import json
import platform
import sys
import ssl
import idna
import urllib3
import chardet
from . import __version__ as requests_version
try:
from urllib3.contrib import pyopenssl
except ImportError:
pyopenssl = None
OpenSSL = None
cryptography = None
else:
import OpenSSL
import cryptography
def _implementation():
"""Return a dict with the Python implementation and version.
Provide both the name and the version of the Python implementation
currently running. For example, on CPython 2.7.5 it will return
{'name': 'CPython', 'version': '2.7.5'}.
This function works best on CPython and PyPy: in particular, it probably
doesn't work for Jython or IronPython. Future investigation should be done
to work out the correct shape of the code for those platforms.
"""
implementation = platform.python_implementation()
if implementation == 'CPython':
implementation_version = platform.python_version()
elif implementation == 'PyPy':
implementation_version = '%s.%s.%s' % (sys.pypy_version_info.major,
sys.pypy_version_info.minor,
sys.pypy_version_info.micro)
if sys.pypy_version_info.releaselevel != 'final':
implementation_version = ''.join([
implementation_version, sys.pypy_version_info.releaselevel
])
elif implementation == 'Jython':
implementation_version = platform.python_version() # Complete Guess
elif implementation == 'IronPython':
implementation_version = platform.python_version() # Complete Guess
else:
implementation_version = 'Unknown'
return {'name': implementation, 'version': implementation_version}
def info():
"""Generate information for a bug report."""
try:
platform_info = {
'system': platform.system(),
'release': platform.release(),
}
except IOError:
platform_info = {
'system': 'Unknown',
'release': 'Unknown',
}
implementation_info = _implementation()
urllib3_info = {'version': urllib3.__version__}
chardet_info = {'version': chardet.__version__}
pyopenssl_info = {
'version': None,
'openssl_version': '',
}
if OpenSSL:
pyopenssl_info = {
'version': OpenSSL.__version__,
'openssl_version': '%x' % OpenSSL.SSL.OPENSSL_VERSION_NUMBER,
}
cryptography_info = {
'version': getattr(cryptography, '__version__', ''),
}
idna_info = {
'version': getattr(idna, '__version__', ''),
}
# OPENSSL_VERSION_NUMBER doesn't exist in the Python 2.6 ssl module.
system_ssl = getattr(ssl, 'OPENSSL_VERSION_NUMBER', None)
system_ssl_info = {
'version': '%x' % system_ssl if system_ssl is not None else ''
}
return {
'platform': platform_info,
'implementation': implementation_info,
'system_ssl': system_ssl_info,
'using_pyopenssl': pyopenssl is not None,
'pyOpenSSL': pyopenssl_info,
'urllib3': urllib3_info,
'chardet': chardet_info,
'cryptography': cryptography_info,
'idna': idna_info,
'requests': {
'version': requests_version,
},
}
def main():
"""Pretty-print the bug information as JSON."""
print(json.dumps(info(), sort_keys=True, indent=2))
if __name__ == '__main__':
main()
| 3,606 | 28.809917 | 78 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/requests/sessions.py | # -*- coding: utf-8 -*-
"""
requests.session
~~~~~~~~~~~~~~~~
This module provides a Session object to manage and persist settings across
requests (cookies, auth, proxies).
"""
import os
import sys
import time
from datetime import timedelta
from .auth import _basic_auth_str
from .compat import cookielib, is_py3, OrderedDict, urljoin, urlparse, Mapping
from .cookies import (
cookiejar_from_dict, extract_cookies_to_jar, RequestsCookieJar, merge_cookies)
from .models import Request, PreparedRequest, DEFAULT_REDIRECT_LIMIT
from .hooks import default_hooks, dispatch_hook
from ._internal_utils import to_native_string
from .utils import to_key_val_list, default_headers
from .exceptions import (
TooManyRedirects, InvalidSchema, ChunkedEncodingError, ContentDecodingError)
from .structures import CaseInsensitiveDict
from .adapters import HTTPAdapter
from .utils import (
requote_uri, get_environ_proxies, get_netrc_auth, should_bypass_proxies,
get_auth_from_url, rewind_body
)
from .status_codes import codes
# formerly defined here, reexposed here for backward compatibility
from .models import REDIRECT_STATI
# Preferred clock, based on which one is more accurate on a given system.
if sys.platform == 'win32':
try: # Python 3.4+
preferred_clock = time.perf_counter
except AttributeError: # Earlier than Python 3.
preferred_clock = time.clock
else:
preferred_clock = time.time
def merge_setting(request_setting, session_setting, dict_class=OrderedDict):
"""Determines appropriate setting for a given request, taking into account
the explicit setting on that request, and the setting in the session. If a
setting is a dictionary, they will be merged together using `dict_class`
"""
if session_setting is None:
return request_setting
if request_setting is None:
return session_setting
# Bypass if not a dictionary (e.g. verify)
if not (
isinstance(session_setting, Mapping) and
isinstance(request_setting, Mapping)
):
return request_setting
merged_setting = dict_class(to_key_val_list(session_setting))
merged_setting.update(to_key_val_list(request_setting))
# Remove keys that are set to None. Extract keys first to avoid altering
# the dictionary during iteration.
none_keys = [k for (k, v) in merged_setting.items() if v is None]
for key in none_keys:
del merged_setting[key]
return merged_setting
def merge_hooks(request_hooks, session_hooks, dict_class=OrderedDict):
"""Properly merges both requests and session hooks.
This is necessary because when request_hooks == {'response': []}, the
merge breaks Session hooks entirely.
"""
if session_hooks is None or session_hooks.get('response') == []:
return request_hooks
if request_hooks is None or request_hooks.get('response') == []:
return session_hooks
return merge_setting(request_hooks, session_hooks, dict_class)
class SessionRedirectMixin(object):
def get_redirect_target(self, resp):
"""Receives a Response. Returns a redirect URI or ``None``"""
# Due to the nature of how requests processes redirects this method will
# be called at least once upon the original response and at least twice
# on each subsequent redirect response (if any).
# If a custom mixin is used to handle this logic, it may be advantageous
# to cache the redirect location onto the response object as a private
# attribute.
if resp.is_redirect:
location = resp.headers['location']
# Currently the underlying http module on py3 decode headers
# in latin1, but empirical evidence suggests that latin1 is very
# rarely used with non-ASCII characters in HTTP headers.
# It is more likely to get UTF8 header rather than latin1.
# This causes incorrect handling of UTF8 encoded location headers.
# To solve this, we re-encode the location in latin1.
if is_py3:
location = location.encode('latin1')
return to_native_string(location, 'utf8')
return None
def resolve_redirects(self, resp, req, stream=False, timeout=None,
verify=True, cert=None, proxies=None, yield_requests=False, **adapter_kwargs):
"""Receives a Response. Returns a generator of Responses or Requests."""
hist = [] # keep track of history
url = self.get_redirect_target(resp)
previous_fragment = urlparse(req.url).fragment
while url:
prepared_request = req.copy()
# Update history and keep track of redirects.
# resp.history must ignore the original request in this loop
hist.append(resp)
resp.history = hist[1:]
try:
resp.content # Consume socket so it can be released
except (ChunkedEncodingError, ContentDecodingError, RuntimeError):
resp.raw.read(decode_content=False)
if len(resp.history) >= self.max_redirects:
raise TooManyRedirects('Exceeded %s redirects.' % self.max_redirects, response=resp)
# Release the connection back into the pool.
resp.close()
# Handle redirection without scheme (see: RFC 1808 Section 4)
if url.startswith('//'):
parsed_rurl = urlparse(resp.url)
url = '%s:%s' % (to_native_string(parsed_rurl.scheme), url)
# Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2)
parsed = urlparse(url)
if parsed.fragment == '' and previous_fragment:
parsed = parsed._replace(fragment=previous_fragment)
elif parsed.fragment:
previous_fragment = parsed.fragment
url = parsed.geturl()
# Facilitate relative 'location' headers, as allowed by RFC 7231.
# (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')
# Compliant with RFC3986, we percent encode the url.
if not parsed.netloc:
url = urljoin(resp.url, requote_uri(url))
else:
url = requote_uri(url)
prepared_request.url = to_native_string(url)
self.rebuild_method(prepared_request, resp)
# https://github.com/requests/requests/issues/1084
if resp.status_code not in (codes.temporary_redirect, codes.permanent_redirect):
# https://github.com/requests/requests/issues/3490
purged_headers = ('Content-Length', 'Content-Type', 'Transfer-Encoding')
for header in purged_headers:
prepared_request.headers.pop(header, None)
prepared_request.body = None
headers = prepared_request.headers
try:
del headers['Cookie']
except KeyError:
pass
# Extract any cookies sent on the response to the cookiejar
# in the new request. Because we've mutated our copied prepared
# request, use the old one that we haven't yet touched.
extract_cookies_to_jar(prepared_request._cookies, req, resp.raw)
merge_cookies(prepared_request._cookies, self.cookies)
prepared_request.prepare_cookies(prepared_request._cookies)
# Rebuild auth and proxy information.
proxies = self.rebuild_proxies(prepared_request, proxies)
self.rebuild_auth(prepared_request, resp)
# A failed tell() sets `_body_position` to `object()`. This non-None
# value ensures `rewindable` will be True, allowing us to raise an
# UnrewindableBodyError, instead of hanging the connection.
rewindable = (
prepared_request._body_position is not None and
('Content-Length' in headers or 'Transfer-Encoding' in headers)
)
# Attempt to rewind consumed file-like object.
if rewindable:
rewind_body(prepared_request)
# Override the original request.
req = prepared_request
if yield_requests:
yield req
else:
resp = self.send(
req,
stream=stream,
timeout=timeout,
verify=verify,
cert=cert,
proxies=proxies,
allow_redirects=False,
**adapter_kwargs
)
extract_cookies_to_jar(self.cookies, prepared_request, resp.raw)
# extract redirect url, if any, for the next loop
url = self.get_redirect_target(resp)
yield resp
def rebuild_auth(self, prepared_request, response):
"""When being redirected we may want to strip authentication from the
request to avoid leaking credentials. This method intelligently removes
and reapplies authentication where possible to avoid credential loss.
"""
headers = prepared_request.headers
url = prepared_request.url
if 'Authorization' in headers:
# If we get redirected to a new host, we should strip out any
# authentication headers.
original_parsed = urlparse(response.request.url)
redirect_parsed = urlparse(url)
if (original_parsed.hostname != redirect_parsed.hostname):
del headers['Authorization']
# .netrc might have more auth for us on our new host.
new_auth = get_netrc_auth(url) if self.trust_env else None
if new_auth is not None:
prepared_request.prepare_auth(new_auth)
return
def rebuild_proxies(self, prepared_request, proxies):
"""This method re-evaluates the proxy configuration by considering the
environment variables. If we are redirected to a URL covered by
NO_PROXY, we strip the proxy configuration. Otherwise, we set missing
proxy keys for this URL (in case they were stripped by a previous
redirect).
This method also replaces the Proxy-Authorization header where
necessary.
:rtype: dict
"""
proxies = proxies if proxies is not None else {}
headers = prepared_request.headers
url = prepared_request.url
scheme = urlparse(url).scheme
new_proxies = proxies.copy()
no_proxy = proxies.get('no_proxy')
bypass_proxy = should_bypass_proxies(url, no_proxy=no_proxy)
if self.trust_env and not bypass_proxy:
environ_proxies = get_environ_proxies(url, no_proxy=no_proxy)
proxy = environ_proxies.get(scheme, environ_proxies.get('all'))
if proxy:
new_proxies.setdefault(scheme, proxy)
if 'Proxy-Authorization' in headers:
del headers['Proxy-Authorization']
try:
username, password = get_auth_from_url(new_proxies[scheme])
except KeyError:
username, password = None, None
if username and password:
headers['Proxy-Authorization'] = _basic_auth_str(username, password)
return new_proxies
def rebuild_method(self, prepared_request, response):
"""When being redirected we may want to change the method of the request
based on certain specs or browser behavior.
"""
method = prepared_request.method
# http://tools.ietf.org/html/rfc7231#section-6.4.4
if response.status_code == codes.see_other and method != 'HEAD':
method = 'GET'
# Do what the browsers do, despite standards...
# First, turn 302s into GETs.
if response.status_code == codes.found and method != 'HEAD':
method = 'GET'
# Second, if a POST is responded to with a 301, turn it into a GET.
# This bizarre behaviour is explained in Issue 1704.
if response.status_code == codes.moved and method == 'POST':
method = 'GET'
prepared_request.method = method
class Session(SessionRedirectMixin):
"""A Requests session.
Provides cookie persistence, connection-pooling, and configuration.
Basic Usage::
>>> import requests
>>> s = requests.Session()
>>> s.get('http://httpbin.org/get')
<Response [200]>
Or as a context manager::
>>> with requests.Session() as s:
>>> s.get('http://httpbin.org/get')
<Response [200]>
"""
__attrs__ = [
'headers', 'cookies', 'auth', 'proxies', 'hooks', 'params', 'verify',
'cert', 'prefetch', 'adapters', 'stream', 'trust_env',
'max_redirects',
]
def __init__(self):
#: A case-insensitive dictionary of headers to be sent on each
#: :class:`Request <Request>` sent from this
#: :class:`Session <Session>`.
self.headers = default_headers()
#: Default Authentication tuple or object to attach to
#: :class:`Request <Request>`.
self.auth = None
#: Dictionary mapping protocol or protocol and host to the URL of the proxy
#: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to
#: be used on each :class:`Request <Request>`.
self.proxies = {}
#: Event-handling hooks.
self.hooks = default_hooks()
#: Dictionary of querystring data to attach to each
#: :class:`Request <Request>`. The dictionary values may be lists for
#: representing multivalued query parameters.
self.params = {}
#: Stream response content default.
self.stream = False
#: SSL Verification default.
self.verify = True
#: SSL client certificate default, if String, path to ssl client
#: cert file (.pem). If Tuple, ('cert', 'key') pair.
self.cert = None
#: Maximum number of redirects allowed. If the request exceeds this
#: limit, a :class:`TooManyRedirects` exception is raised.
#: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is
#: 30.
self.max_redirects = DEFAULT_REDIRECT_LIMIT
#: Trust environment settings for proxy configuration, default
#: authentication and similar.
self.trust_env = True
#: A CookieJar containing all currently outstanding cookies set on this
#: session. By default it is a
#: :class:`RequestsCookieJar <requests.cookies.RequestsCookieJar>`, but
#: may be any other ``cookielib.CookieJar`` compatible object.
self.cookies = cookiejar_from_dict({})
# Default connection adapters.
self.adapters = OrderedDict()
self.mount('https://', HTTPAdapter())
self.mount('http://', HTTPAdapter())
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
def prepare_request(self, request):
"""Constructs a :class:`PreparedRequest <PreparedRequest>` for
transmission and returns it. The :class:`PreparedRequest` has settings
merged from the :class:`Request <Request>` instance and those of the
:class:`Session`.
:param request: :class:`Request` instance to prepare with this
session's settings.
:rtype: requests.PreparedRequest
"""
cookies = request.cookies or {}
# Bootstrap CookieJar.
if not isinstance(cookies, cookielib.CookieJar):
cookies = cookiejar_from_dict(cookies)
# Merge with session cookies
merged_cookies = merge_cookies(
merge_cookies(RequestsCookieJar(), self.cookies), cookies)
# Set environment's basic authentication if not explicitly set.
auth = request.auth
if self.trust_env and not auth and not self.auth:
auth = get_netrc_auth(request.url)
p = PreparedRequest()
p.prepare(
method=request.method.upper(),
url=request.url,
files=request.files,
data=request.data,
json=request.json,
headers=merge_setting(request.headers, self.headers, dict_class=CaseInsensitiveDict),
params=merge_setting(request.params, self.params),
auth=merge_setting(auth, self.auth),
cookies=merged_cookies,
hooks=merge_hooks(request.hooks, self.hooks),
)
return p
def request(self, method, url,
params=None, data=None, headers=None, cookies=None, files=None,
auth=None, timeout=None, allow_redirects=True, proxies=None,
hooks=None, stream=None, verify=None, cert=None, json=None):
"""Constructs a :class:`Request <Request>`, prepares it and sends it.
Returns :class:`Response <Response>` object.
:param method: method for the new :class:`Request` object.
:param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary or bytes to be sent in the query
string for the :class:`Request`.
:param data: (optional) Dictionary, bytes, or file-like object to send
in the body of the :class:`Request`.
:param json: (optional) json to send in the body of the
:class:`Request`.
:param headers: (optional) Dictionary of HTTP Headers to send with the
:class:`Request`.
:param cookies: (optional) Dict or CookieJar object to send with the
:class:`Request`.
:param files: (optional) Dictionary of ``'filename': file-like-objects``
for multipart encoding upload.
:param auth: (optional) Auth tuple or callable to enable
Basic/Digest/Custom HTTP Auth.
:param timeout: (optional) How long to wait for the server to send
data before giving up, as a float, or a :ref:`(connect timeout,
read timeout) <timeouts>` tuple.
:type timeout: float or tuple
:param allow_redirects: (optional) Set to True by default.
:type allow_redirects: bool
:param proxies: (optional) Dictionary mapping protocol or protocol and
hostname to the URL of the proxy.
:param stream: (optional) whether to immediately download the response
content. Defaults to ``False``.
:param verify: (optional) Either a boolean, in which case it controls whether we verify
the server's TLS certificate, or a string, in which case it must be a path
to a CA bundle to use. Defaults to ``True``.
:param cert: (optional) if String, path to ssl client cert file (.pem).
If Tuple, ('cert', 'key') pair.
:rtype: requests.Response
"""
# Create the Request.
req = Request(
method=method.upper(),
url=url,
headers=headers,
files=files,
data=data or {},
json=json,
params=params or {},
auth=auth,
cookies=cookies,
hooks=hooks,
)
prep = self.prepare_request(req)
proxies = proxies or {}
settings = self.merge_environment_settings(
prep.url, proxies, stream, verify, cert
)
# Send the request.
send_kwargs = {
'timeout': timeout,
'allow_redirects': allow_redirects,
}
send_kwargs.update(settings)
resp = self.send(prep, **send_kwargs)
return resp
def get(self, url, **kwargs):
r"""Sends a GET request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:rtype: requests.Response
"""
kwargs.setdefault('allow_redirects', True)
return self.request('GET', url, **kwargs)
def options(self, url, **kwargs):
r"""Sends a OPTIONS request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:rtype: requests.Response
"""
kwargs.setdefault('allow_redirects', True)
return self.request('OPTIONS', url, **kwargs)
def head(self, url, **kwargs):
r"""Sends a HEAD request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:rtype: requests.Response
"""
kwargs.setdefault('allow_redirects', False)
return self.request('HEAD', url, **kwargs)
def post(self, url, data=None, json=None, **kwargs):
r"""Sends a POST request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
:param json: (optional) json to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:rtype: requests.Response
"""
return self.request('POST', url, data=data, json=json, **kwargs)
def put(self, url, data=None, **kwargs):
r"""Sends a PUT request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:rtype: requests.Response
"""
return self.request('PUT', url, data=data, **kwargs)
def patch(self, url, data=None, **kwargs):
r"""Sends a PATCH request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:rtype: requests.Response
"""
return self.request('PATCH', url, data=data, **kwargs)
def delete(self, url, **kwargs):
r"""Sends a DELETE request. Returns :class:`Response` object.
:param url: URL for the new :class:`Request` object.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:rtype: requests.Response
"""
return self.request('DELETE', url, **kwargs)
def send(self, request, **kwargs):
"""Send a given PreparedRequest.
:rtype: requests.Response
"""
# Set defaults that the hooks can utilize to ensure they always have
# the correct parameters to reproduce the previous request.
kwargs.setdefault('stream', self.stream)
kwargs.setdefault('verify', self.verify)
kwargs.setdefault('cert', self.cert)
kwargs.setdefault('proxies', self.proxies)
# It's possible that users might accidentally send a Request object.
# Guard against that specific failure case.
if isinstance(request, Request):
raise ValueError('You can only send PreparedRequests.')
# Set up variables needed for resolve_redirects and dispatching of hooks
allow_redirects = kwargs.pop('allow_redirects', True)
stream = kwargs.get('stream')
hooks = request.hooks
# Get the appropriate adapter to use
adapter = self.get_adapter(url=request.url)
# Start time (approximately) of the request
start = preferred_clock()
# Send the request
r = adapter.send(request, **kwargs)
# Total elapsed time of the request (approximately)
elapsed = preferred_clock() - start
r.elapsed = timedelta(seconds=elapsed)
# Response manipulation hooks
r = dispatch_hook('response', hooks, r, **kwargs)
# Persist cookies
if r.history:
# If the hooks create history then we want those cookies too
for resp in r.history:
extract_cookies_to_jar(self.cookies, resp.request, resp.raw)
extract_cookies_to_jar(self.cookies, request, r.raw)
# Redirect resolving generator.
gen = self.resolve_redirects(r, request, **kwargs)
# Resolve redirects if allowed.
history = [resp for resp in gen] if allow_redirects else []
# Shuffle things around if there's history.
if history:
# Insert the first (original) request at the start
history.insert(0, r)
# Get the last request made
r = history.pop()
r.history = history
# If redirects aren't being followed, store the response on the Request for Response.next().
if not allow_redirects:
try:
r._next = next(self.resolve_redirects(r, request, yield_requests=True, **kwargs))
except StopIteration:
pass
if not stream:
r.content
return r
def merge_environment_settings(self, url, proxies, stream, verify, cert):
"""
Check the environment and merge it with some settings.
:rtype: dict
"""
# Gather clues from the surrounding environment.
if self.trust_env:
# Set environment's proxies.
no_proxy = proxies.get('no_proxy') if proxies is not None else None
env_proxies = get_environ_proxies(url, no_proxy=no_proxy)
for (k, v) in env_proxies.items():
proxies.setdefault(k, v)
# Look for requests environment configuration and be compatible
# with cURL.
if verify is True or verify is None:
verify = (os.environ.get('REQUESTS_CA_BUNDLE') or
os.environ.get('CURL_CA_BUNDLE'))
# Merge all the kwargs.
proxies = merge_setting(proxies, self.proxies)
stream = merge_setting(stream, self.stream)
verify = merge_setting(verify, self.verify)
cert = merge_setting(cert, self.cert)
return {'verify': verify, 'proxies': proxies, 'stream': stream,
'cert': cert}
def get_adapter(self, url):
"""
Returns the appropriate connection adapter for the given URL.
:rtype: requests.adapters.BaseAdapter
"""
for (prefix, adapter) in self.adapters.items():
if url.lower().startswith(prefix.lower()):
return adapter
# Nothing matches :-/
raise InvalidSchema("No connection adapters were found for '%s'" % url)
def close(self):
"""Closes all adapters and as such the session"""
for v in self.adapters.values():
v.close()
def mount(self, prefix, adapter):
"""Registers a connection adapter to a prefix.
Adapters are sorted in descending order by prefix length.
"""
self.adapters[prefix] = adapter
keys_to_move = [k for k in self.adapters if len(k) < len(prefix)]
for key in keys_to_move:
self.adapters[key] = self.adapters.pop(key)
def __getstate__(self):
state = dict((attr, getattr(self, attr, None)) for attr in self.__attrs__)
return state
def __setstate__(self, state):
for attr, value in state.items():
setattr(self, attr, value)
def session():
"""
Returns a :class:`Session` for context-management.
:rtype: Session
"""
return Session()
| 27,829 | 36.506739 | 115 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/requests/models.py | # -*- coding: utf-8 -*-
"""
requests.models
~~~~~~~~~~~~~~~
This module contains the primary objects that power Requests.
"""
import datetime
import sys
# Import encoding now, to avoid implicit import later.
# Implicit import within threads may cause LookupError when standard library is in a ZIP,
# such as in Embedded Python. See https://github.com/requests/requests/issues/3578.
import encodings.idna
from urllib3.fields import RequestField
from urllib3.filepost import encode_multipart_formdata
from urllib3.util import parse_url
from urllib3.exceptions import (
DecodeError, ReadTimeoutError, ProtocolError, LocationParseError)
from io import UnsupportedOperation
from .hooks import default_hooks
from .structures import CaseInsensitiveDict
from .auth import HTTPBasicAuth
from .cookies import cookiejar_from_dict, get_cookie_header, _copy_cookie_jar
from .exceptions import (
HTTPError, MissingSchema, InvalidURL, ChunkedEncodingError,
ContentDecodingError, ConnectionError, StreamConsumedError)
from ._internal_utils import to_native_string, unicode_is_ascii
from .utils import (
guess_filename, get_auth_from_url, requote_uri,
stream_decode_response_unicode, to_key_val_list, parse_header_links,
iter_slices, guess_json_utf, super_len, check_header_validity)
from .compat import (
Callable, Mapping,
cookielib, urlunparse, urlsplit, urlencode, str, bytes,
is_py2, chardet, builtin_str, basestring)
from .compat import json as complexjson
from .status_codes import codes
#: The set of HTTP status codes that indicate an automatically
#: processable redirect.
REDIRECT_STATI = (
codes.moved, # 301
codes.found, # 302
codes.other, # 303
codes.temporary_redirect, # 307
codes.permanent_redirect, # 308
)
DEFAULT_REDIRECT_LIMIT = 30
CONTENT_CHUNK_SIZE = 10 * 1024
ITER_CHUNK_SIZE = 512
class RequestEncodingMixin(object):
@property
def path_url(self):
"""Build the path URL to use."""
url = []
p = urlsplit(self.url)
path = p.path
if not path:
path = '/'
url.append(path)
query = p.query
if query:
url.append('?')
url.append(query)
return ''.join(url)
@staticmethod
def _encode_params(data):
"""Encode parameters in a piece of data.
Will successfully encode parameters when passed as a dict or a list of
2-tuples. Order is retained if data is a list of 2-tuples but arbitrary
if parameters are supplied as a dict.
"""
if isinstance(data, (str, bytes)):
return data
elif hasattr(data, 'read'):
return data
elif hasattr(data, '__iter__'):
result = []
for k, vs in to_key_val_list(data):
if isinstance(vs, basestring) or not hasattr(vs, '__iter__'):
vs = [vs]
for v in vs:
if v is not None:
result.append(
(k.encode('utf-8') if isinstance(k, str) else k,
v.encode('utf-8') if isinstance(v, str) else v))
return urlencode(result, doseq=True)
else:
return data
@staticmethod
def _encode_files(files, data):
"""Build the body for a multipart/form-data request.
Will successfully encode files when passed as a dict or a list of
tuples. Order is retained if data is a list of tuples but arbitrary
if parameters are supplied as a dict.
The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype)
or 4-tuples (filename, fileobj, contentype, custom_headers).
"""
if (not files):
raise ValueError("Files must be provided.")
elif isinstance(data, basestring):
raise ValueError("Data must not be a string.")
new_fields = []
fields = to_key_val_list(data or {})
files = to_key_val_list(files or {})
for field, val in fields:
if isinstance(val, basestring) or not hasattr(val, '__iter__'):
val = [val]
for v in val:
if v is not None:
# Don't call str() on bytestrings: in Py3 it all goes wrong.
if not isinstance(v, bytes):
v = str(v)
new_fields.append(
(field.decode('utf-8') if isinstance(field, bytes) else field,
v.encode('utf-8') if isinstance(v, str) else v))
for (k, v) in files:
# support for explicit filename
ft = None
fh = None
if isinstance(v, (tuple, list)):
if len(v) == 2:
fn, fp = v
elif len(v) == 3:
fn, fp, ft = v
else:
fn, fp, ft, fh = v
else:
fn = guess_filename(v) or k
fp = v
if isinstance(fp, (str, bytes, bytearray)):
fdata = fp
elif hasattr(fp, 'read'):
fdata = fp.read()
elif fp is None:
continue
else:
fdata = fp
rf = RequestField(name=k, data=fdata, filename=fn, headers=fh)
rf.make_multipart(content_type=ft)
new_fields.append(rf)
body, content_type = encode_multipart_formdata(new_fields)
return body, content_type
class RequestHooksMixin(object):
def register_hook(self, event, hook):
"""Properly register a hook."""
if event not in self.hooks:
raise ValueError('Unsupported event specified, with event name "%s"' % (event))
if isinstance(hook, Callable):
self.hooks[event].append(hook)
elif hasattr(hook, '__iter__'):
self.hooks[event].extend(h for h in hook if isinstance(h, Callable))
def deregister_hook(self, event, hook):
"""Deregister a previously registered hook.
Returns True if the hook existed, False if not.
"""
try:
self.hooks[event].remove(hook)
return True
except ValueError:
return False
class Request(RequestHooksMixin):
"""A user-created :class:`Request <Request>` object.
Used to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server.
:param method: HTTP method to use.
:param url: URL to send.
:param headers: dictionary of headers to send.
:param files: dictionary of {filename: fileobject} files to multipart upload.
:param data: the body to attach to the request. If a dictionary is provided, form-encoding will take place.
:param json: json for the body to attach to the request (if files or data is not specified).
:param params: dictionary of URL parameters to append to the URL.
:param auth: Auth handler or (user, pass) tuple.
:param cookies: dictionary or CookieJar of cookies to attach to this request.
:param hooks: dictionary of callback hooks, for internal usage.
Usage::
>>> import requests
>>> req = requests.Request('GET', 'http://httpbin.org/get')
>>> req.prepare()
<PreparedRequest [GET]>
"""
def __init__(self,
method=None, url=None, headers=None, files=None, data=None,
params=None, auth=None, cookies=None, hooks=None, json=None):
# Default empty dicts for dict params.
data = [] if data is None else data
files = [] if files is None else files
headers = {} if headers is None else headers
params = {} if params is None else params
hooks = {} if hooks is None else hooks
self.hooks = default_hooks()
for (k, v) in list(hooks.items()):
self.register_hook(event=k, hook=v)
self.method = method
self.url = url
self.headers = headers
self.files = files
self.data = data
self.json = json
self.params = params
self.auth = auth
self.cookies = cookies
def __repr__(self):
return '<Request [%s]>' % (self.method)
def prepare(self):
"""Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it."""
p = PreparedRequest()
p.prepare(
method=self.method,
url=self.url,
headers=self.headers,
files=self.files,
data=self.data,
json=self.json,
params=self.params,
auth=self.auth,
cookies=self.cookies,
hooks=self.hooks,
)
return p
class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):
"""The fully mutable :class:`PreparedRequest <PreparedRequest>` object,
containing the exact bytes that will be sent to the server.
Generated from either a :class:`Request <Request>` object or manually.
Usage::
>>> import requests
>>> req = requests.Request('GET', 'http://httpbin.org/get')
>>> r = req.prepare()
<PreparedRequest [GET]>
>>> s = requests.Session()
>>> s.send(r)
<Response [200]>
"""
def __init__(self):
#: HTTP verb to send to the server.
self.method = None
#: HTTP URL to send the request to.
self.url = None
#: dictionary of HTTP headers.
self.headers = None
# The `CookieJar` used to create the Cookie header will be stored here
# after prepare_cookies is called
self._cookies = None
#: request body to send to the server.
self.body = None
#: dictionary of callback hooks, for internal usage.
self.hooks = default_hooks()
#: integer denoting starting position of a readable file-like body.
self._body_position = None
def prepare(self,
method=None, url=None, headers=None, files=None, data=None,
params=None, auth=None, cookies=None, hooks=None, json=None):
"""Prepares the entire request with the given parameters."""
self.prepare_method(method)
self.prepare_url(url, params)
self.prepare_headers(headers)
self.prepare_cookies(cookies)
self.prepare_body(data, files, json)
self.prepare_auth(auth, url)
# Note that prepare_auth must be last to enable authentication schemes
# such as OAuth to work on a fully prepared request.
# This MUST go after prepare_auth. Authenticators could add a hook
self.prepare_hooks(hooks)
def __repr__(self):
return '<PreparedRequest [%s]>' % (self.method)
def copy(self):
p = PreparedRequest()
p.method = self.method
p.url = self.url
p.headers = self.headers.copy() if self.headers is not None else None
p._cookies = _copy_cookie_jar(self._cookies)
p.body = self.body
p.hooks = self.hooks
p._body_position = self._body_position
return p
def prepare_method(self, method):
"""Prepares the given HTTP method."""
self.method = method
if self.method is not None:
self.method = to_native_string(self.method.upper())
@staticmethod
def _get_idna_encoded_host(host):
import idna
try:
host = idna.encode(host, uts46=True).decode('utf-8')
except idna.IDNAError:
raise UnicodeError
return host
def prepare_url(self, url, params):
"""Prepares the given HTTP URL."""
#: Accept objects that have string representations.
#: We're unable to blindly call unicode/str functions
#: as this will include the bytestring indicator (b'')
#: on python 3.x.
#: https://github.com/requests/requests/pull/2238
if isinstance(url, bytes):
url = url.decode('utf8')
else:
url = unicode(url) if is_py2 else str(url)
# Remove leading whitespaces from url
url = url.lstrip()
# Don't do any URL preparation for non-HTTP schemes like `mailto`,
# `data` etc to work around exceptions from `url_parse`, which
# handles RFC 3986 only.
if ':' in url and not url.lower().startswith('http'):
self.url = url
return
# Support for unicode domain names and paths.
try:
scheme, auth, host, port, path, query, fragment = parse_url(url)
except LocationParseError as e:
raise InvalidURL(*e.args)
if not scheme:
error = ("Invalid URL {0!r}: No schema supplied. Perhaps you meant http://{0}?")
error = error.format(to_native_string(url, 'utf8'))
raise MissingSchema(error)
if not host:
raise InvalidURL("Invalid URL %r: No host supplied" % url)
# In general, we want to try IDNA encoding the hostname if the string contains
# non-ASCII characters. This allows users to automatically get the correct IDNA
# behaviour. For strings containing only ASCII characters, we need to also verify
# it doesn't start with a wildcard (*), before allowing the unencoded hostname.
if not unicode_is_ascii(host):
try:
host = self._get_idna_encoded_host(host)
except UnicodeError:
raise InvalidURL('URL has an invalid label.')
elif host.startswith(u'*'):
raise InvalidURL('URL has an invalid label.')
# Carefully reconstruct the network location
netloc = auth or ''
if netloc:
netloc += '@'
netloc += host
if port:
netloc += ':' + str(port)
# Bare domains aren't valid URLs.
if not path:
path = '/'
if is_py2:
if isinstance(scheme, str):
scheme = scheme.encode('utf-8')
if isinstance(netloc, str):
netloc = netloc.encode('utf-8')
if isinstance(path, str):
path = path.encode('utf-8')
if isinstance(query, str):
query = query.encode('utf-8')
if isinstance(fragment, str):
fragment = fragment.encode('utf-8')
if isinstance(params, (str, bytes)):
params = to_native_string(params)
enc_params = self._encode_params(params)
if enc_params:
if query:
query = '%s&%s' % (query, enc_params)
else:
query = enc_params
url = requote_uri(urlunparse([scheme, netloc, path, None, query, fragment]))
self.url = url
def prepare_headers(self, headers):
"""Prepares the given HTTP headers."""
self.headers = CaseInsensitiveDict()
if headers:
for header in headers.items():
# Raise exception on invalid header value.
check_header_validity(header)
name, value = header
self.headers[to_native_string(name)] = value
def prepare_body(self, data, files, json=None):
"""Prepares the given HTTP body data."""
# Check if file, fo, generator, iterator.
# If not, run through normal process.
# Nottin' on you.
body = None
content_type = None
if not data and json is not None:
# urllib3 requires a bytes-like body. Python 2's json.dumps
# provides this natively, but Python 3 gives a Unicode string.
content_type = 'application/json'
body = complexjson.dumps(json)
if not isinstance(body, bytes):
body = body.encode('utf-8')
is_stream = all([
hasattr(data, '__iter__'),
not isinstance(data, (basestring, list, tuple, Mapping))
])
try:
length = super_len(data)
except (TypeError, AttributeError, UnsupportedOperation):
length = None
if is_stream:
body = data
if getattr(body, 'tell', None) is not None:
# Record the current file position before reading.
# This will allow us to rewind a file in the event
# of a redirect.
try:
self._body_position = body.tell()
except (IOError, OSError):
# This differentiates from None, allowing us to catch
# a failed `tell()` later when trying to rewind the body
self._body_position = object()
if files:
raise NotImplementedError('Streamed bodies and files are mutually exclusive.')
if length:
self.headers['Content-Length'] = builtin_str(length)
else:
self.headers['Transfer-Encoding'] = 'chunked'
else:
# Multi-part file uploads.
if files:
(body, content_type) = self._encode_files(files, data)
else:
if data:
body = self._encode_params(data)
if isinstance(data, basestring) or hasattr(data, 'read'):
content_type = None
else:
content_type = 'application/x-www-form-urlencoded'
self.prepare_content_length(body)
# Add content-type if it wasn't explicitly provided.
if content_type and ('content-type' not in self.headers):
self.headers['Content-Type'] = content_type
self.body = body
def prepare_content_length(self, body):
"""Prepare Content-Length header based on request method and body"""
if body is not None:
length = super_len(body)
if length:
# If length exists, set it. Otherwise, we fallback
# to Transfer-Encoding: chunked.
self.headers['Content-Length'] = builtin_str(length)
elif self.method not in ('GET', 'HEAD') and self.headers.get('Content-Length') is None:
# Set Content-Length to 0 for methods that can have a body
# but don't provide one. (i.e. not GET or HEAD)
self.headers['Content-Length'] = '0'
def prepare_auth(self, auth, url=''):
"""Prepares the given HTTP auth data."""
# If no Auth is explicitly provided, extract it from the URL first.
if auth is None:
url_auth = get_auth_from_url(self.url)
auth = url_auth if any(url_auth) else None
if auth:
if isinstance(auth, tuple) and len(auth) == 2:
# special-case basic HTTP auth
auth = HTTPBasicAuth(*auth)
# Allow auth to make its changes.
r = auth(self)
# Update self to reflect the auth changes.
self.__dict__.update(r.__dict__)
# Recompute Content-Length
self.prepare_content_length(self.body)
def prepare_cookies(self, cookies):
"""Prepares the given HTTP cookie data.
This function eventually generates a ``Cookie`` header from the
given cookies using cookielib. Due to cookielib's design, the header
will not be regenerated if it already exists, meaning this function
can only be called once for the life of the
:class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls
to ``prepare_cookies`` will have no actual effect, unless the "Cookie"
header is removed beforehand.
"""
if isinstance(cookies, cookielib.CookieJar):
self._cookies = cookies
else:
self._cookies = cookiejar_from_dict(cookies)
cookie_header = get_cookie_header(self._cookies, self)
if cookie_header is not None:
self.headers['Cookie'] = cookie_header
def prepare_hooks(self, hooks):
"""Prepares the given hooks."""
# hooks can be passed as None to the prepare method and to this
# method. To prevent iterating over None, simply use an empty list
# if hooks is False-y
hooks = hooks or []
for event in hooks:
self.register_hook(event, hooks[event])
class Response(object):
"""The :class:`Response <Response>` object, which contains a
server's response to an HTTP request.
"""
__attrs__ = [
'_content', 'status_code', 'headers', 'url', 'history',
'encoding', 'reason', 'cookies', 'elapsed', 'request'
]
def __init__(self):
self._content = False
self._content_consumed = False
self._next = None
#: Integer Code of responded HTTP Status, e.g. 404 or 200.
self.status_code = None
#: Case-insensitive Dictionary of Response Headers.
#: For example, ``headers['content-encoding']`` will return the
#: value of a ``'Content-Encoding'`` response header.
self.headers = CaseInsensitiveDict()
#: File-like object representation of response (for advanced usage).
#: Use of ``raw`` requires that ``stream=True`` be set on the request.
# This requirement does not apply for use internally to Requests.
self.raw = None
#: Final URL location of Response.
self.url = None
#: Encoding to decode with when accessing r.text.
self.encoding = None
#: A list of :class:`Response <Response>` objects from
#: the history of the Request. Any redirect responses will end
#: up here. The list is sorted from the oldest to the most recent request.
self.history = []
#: Textual reason of responded HTTP Status, e.g. "Not Found" or "OK".
self.reason = None
#: A CookieJar of Cookies the server sent back.
self.cookies = cookiejar_from_dict({})
#: The amount of time elapsed between sending the request
#: and the arrival of the response (as a timedelta).
#: This property specifically measures the time taken between sending
#: the first byte of the request and finishing parsing the headers. It
#: is therefore unaffected by consuming the response content or the
#: value of the ``stream`` keyword argument.
self.elapsed = datetime.timedelta(0)
#: The :class:`PreparedRequest <PreparedRequest>` object to which this
#: is a response.
self.request = None
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
def __getstate__(self):
# Consume everything; accessing the content attribute makes
# sure the content has been fully read.
if not self._content_consumed:
self.content
return dict(
(attr, getattr(self, attr, None))
for attr in self.__attrs__
)
def __setstate__(self, state):
for name, value in state.items():
setattr(self, name, value)
# pickled objects do not have .raw
setattr(self, '_content_consumed', True)
setattr(self, 'raw', None)
def __repr__(self):
return '<Response [%s]>' % (self.status_code)
def __bool__(self):
"""Returns True if :attr:`status_code` is less than 400.
This attribute checks if the status code of the response is between
400 and 600 to see if there was a client error or a server error. If
the status code, is between 200 and 400, this will return True. This
is **not** a check to see if the response code is ``200 OK``.
"""
return self.ok
def __nonzero__(self):
"""Returns True if :attr:`status_code` is less than 400.
This attribute checks if the status code of the response is between
400 and 600 to see if there was a client error or a server error. If
the status code, is between 200 and 400, this will return True. This
is **not** a check to see if the response code is ``200 OK``.
"""
return self.ok
def __iter__(self):
"""Allows you to use a response as an iterator."""
return self.iter_content(128)
@property
def ok(self):
"""Returns True if :attr:`status_code` is less than 400, False if not.
This attribute checks if the status code of the response is between
400 and 600 to see if there was a client error or a server error. If
the status code is between 200 and 400, this will return True. This
is **not** a check to see if the response code is ``200 OK``.
"""
try:
self.raise_for_status()
except HTTPError:
return False
return True
@property
def is_redirect(self):
"""True if this Response is a well-formed HTTP redirect that could have
been processed automatically (by :meth:`Session.resolve_redirects`).
"""
return ('location' in self.headers and self.status_code in REDIRECT_STATI)
@property
def is_permanent_redirect(self):
"""True if this Response one of the permanent versions of redirect."""
return ('location' in self.headers and self.status_code in (codes.moved_permanently, codes.permanent_redirect))
@property
def next(self):
"""Returns a PreparedRequest for the next request in a redirect chain, if there is one."""
return self._next
@property
def apparent_encoding(self):
"""The apparent encoding, provided by the chardet library."""
return chardet.detect(self.content)['encoding']
def iter_content(self, chunk_size=1, decode_unicode=False):
"""Iterates over the response data. When stream=True is set on the
request, this avoids reading the content at once into memory for
large responses. The chunk size is the number of bytes it should
read into memory. This is not necessarily the length of each item
returned as decoding can take place.
chunk_size must be of type int or None. A value of None will
function differently depending on the value of `stream`.
stream=True will read data as it arrives in whatever size the
chunks are received. If stream=False, data is returned as
a single chunk.
If decode_unicode is True, content will be decoded using the best
available encoding based on the response.
"""
def generate():
# Special case for urllib3.
if hasattr(self.raw, 'stream'):
try:
for chunk in self.raw.stream(chunk_size, decode_content=True):
yield chunk
except ProtocolError as e:
raise ChunkedEncodingError(e)
except DecodeError as e:
raise ContentDecodingError(e)
except ReadTimeoutError as e:
raise ConnectionError(e)
else:
# Standard file-like object.
while True:
chunk = self.raw.read(chunk_size)
if not chunk:
break
yield chunk
self._content_consumed = True
if self._content_consumed and isinstance(self._content, bool):
raise StreamConsumedError()
elif chunk_size is not None and not isinstance(chunk_size, int):
raise TypeError("chunk_size must be an int, it is instead a %s." % type(chunk_size))
# simulate reading small chunks of the content
reused_chunks = iter_slices(self._content, chunk_size)
stream_chunks = generate()
chunks = reused_chunks if self._content_consumed else stream_chunks
if decode_unicode:
chunks = stream_decode_response_unicode(chunks, self)
return chunks
def iter_lines(self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=None, delimiter=None):
"""Iterates over the response data, one line at a time. When
stream=True is set on the request, this avoids reading the
content at once into memory for large responses.
.. note:: This method is not reentrant safe.
"""
pending = None
for chunk in self.iter_content(chunk_size=chunk_size, decode_unicode=decode_unicode):
if pending is not None:
chunk = pending + chunk
if delimiter:
lines = chunk.split(delimiter)
else:
lines = chunk.splitlines()
if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]:
pending = lines.pop()
else:
pending = None
for line in lines:
yield line
if pending is not None:
yield pending
@property
def content(self):
"""Content of the response, in bytes."""
if self._content is False:
# Read the contents.
if self._content_consumed:
raise RuntimeError(
'The content for this response was already consumed')
if self.status_code == 0 or self.raw is None:
self._content = None
else:
self._content = b''.join(self.iter_content(CONTENT_CHUNK_SIZE)) or b''
self._content_consumed = True
# don't need to release the connection; that's been handled by urllib3
# since we exhausted the data.
return self._content
@property
def text(self):
"""Content of the response, in unicode.
If Response.encoding is None, encoding will be guessed using
``chardet``.
The encoding of the response content is determined based solely on HTTP
headers, following RFC 2616 to the letter. If you can take advantage of
non-HTTP knowledge to make a better guess at the encoding, you should
set ``r.encoding`` appropriately before accessing this property.
"""
# Try charset from content-type
content = None
encoding = self.encoding
if not self.content:
return str('')
# Fallback to auto-detected encoding.
if self.encoding is None:
encoding = self.apparent_encoding
# Decode unicode from given encoding.
try:
content = str(self.content, encoding, errors='replace')
except (LookupError, TypeError):
# A LookupError is raised if the encoding was not found which could
# indicate a misspelling or similar mistake.
#
# A TypeError can be raised if encoding is None
#
# So we try blindly encoding.
content = str(self.content, errors='replace')
return content
def json(self, **kwargs):
r"""Returns the json-encoded content of a response, if any.
:param \*\*kwargs: Optional arguments that ``json.loads`` takes.
:raises ValueError: If the response body does not contain valid json.
"""
if not self.encoding and self.content and len(self.content) > 3:
# No encoding set. JSON RFC 4627 section 3 states we should expect
# UTF-8, -16 or -32. Detect which one to use; If the detection or
# decoding fails, fall back to `self.text` (using chardet to make
# a best guess).
encoding = guess_json_utf(self.content)
if encoding is not None:
try:
return complexjson.loads(
self.content.decode(encoding), **kwargs
)
except UnicodeDecodeError:
# Wrong UTF codec detected; usually because it's not UTF-8
# but some other 8-bit codec. This is an RFC violation,
# and the server didn't bother to tell us what codec *was*
# used.
pass
return complexjson.loads(self.text, **kwargs)
@property
def links(self):
"""Returns the parsed header links of the response, if any."""
header = self.headers.get('link')
# l = MultiDict()
l = {}
if header:
links = parse_header_links(header)
for link in links:
key = link.get('rel') or link.get('url')
l[key] = link
return l
def raise_for_status(self):
"""Raises stored :class:`HTTPError`, if one occurred."""
http_error_msg = ''
if isinstance(self.reason, bytes):
# We attempt to decode utf-8 first because some servers
# choose to localize their reason strings. If the string
# isn't utf-8, we fall back to iso-8859-1 for all other
# encodings. (See PR #3538)
try:
reason = self.reason.decode('utf-8')
except UnicodeDecodeError:
reason = self.reason.decode('iso-8859-1')
else:
reason = self.reason
if 400 <= self.status_code < 500:
http_error_msg = u'%s Client Error: %s for url: %s' % (self.status_code, reason, self.url)
elif 500 <= self.status_code < 600:
http_error_msg = u'%s Server Error: %s for url: %s' % (self.status_code, reason, self.url)
if http_error_msg:
raise HTTPError(http_error_msg, response=self)
def close(self):
"""Releases the connection back to the pool. Once this method has been
called the underlying ``raw`` object must not be accessed again.
*Note: Should not normally need to be called explicitly.*
"""
if not self._content_consumed:
self.raw.close()
release_conn = getattr(self.raw, 'release_conn', None)
if release_conn is not None:
release_conn()
| 34,095 | 34.777545 | 119 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/requests/__init__.py | # -*- coding: utf-8 -*-
# __
# /__) _ _ _ _ _/ _
# / ( (- (/ (/ (- _) / _)
# /
"""
Requests HTTP Library
~~~~~~~~~~~~~~~~~~~~~
Requests is an HTTP library, written in Python, for human beings. Basic GET
usage:
>>> import requests
>>> r = requests.get('https://www.python.org')
>>> r.status_code
200
>>> 'Python is a programming language' in r.content
True
... or POST:
>>> payload = dict(key1='value1', key2='value2')
>>> r = requests.post('http://httpbin.org/post', data=payload)
>>> print(r.text)
{
...
"form": {
"key2": "value2",
"key1": "value1"
},
...
}
The other HTTP methods are supported - see `requests.api`. Full documentation
is at <http://python-requests.org>.
:copyright: (c) 2017 by Kenneth Reitz.
:license: Apache 2.0, see LICENSE for more details.
"""
import urllib3
import chardet
import warnings
from .exceptions import RequestsDependencyWarning
def check_compatibility(urllib3_version, chardet_version):
urllib3_version = urllib3_version.split('.')
assert urllib3_version != ['dev'] # Verify urllib3 isn't installed from git.
# Sometimes, urllib3 only reports its version as 16.1.
if len(urllib3_version) == 2:
urllib3_version.append('0')
# Check urllib3 for compatibility.
major, minor, patch = urllib3_version # noqa: F811
major, minor, patch = int(major), int(minor), int(patch)
# urllib3 >= 1.21.1, <= 1.23
assert major == 1
assert minor >= 21
assert minor <= 23
# Check chardet for compatibility.
major, minor, patch = chardet_version.split('.')[:3]
major, minor, patch = int(major), int(minor), int(patch)
# chardet >= 3.0.2, < 3.1.0
assert major == 3
assert minor < 1
assert patch >= 2
def _check_cryptography(cryptography_version):
# cryptography < 1.3.4
try:
cryptography_version = list(map(int, cryptography_version.split('.')))
except ValueError:
return
if cryptography_version < [1, 3, 4]:
warning = 'Old version of cryptography ({0}) may cause slowdown.'.format(cryptography_version)
warnings.warn(warning, RequestsDependencyWarning)
# Check imported dependencies for compatibility.
try:
check_compatibility(urllib3.__version__, chardet.__version__)
except (AssertionError, ValueError):
warnings.warn("urllib3 ({0}) or chardet ({1}) doesn't match a supported "
"version!".format(urllib3.__version__, chardet.__version__),
RequestsDependencyWarning)
# Attempt to enable urllib3's SNI support, if possible
try:
from urllib3.contrib import pyopenssl
pyopenssl.inject_into_urllib3()
# Check cryptography version
from cryptography import __version__ as cryptography_version
_check_cryptography(cryptography_version)
except ImportError:
pass
# urllib3's DependencyWarnings should be silenced.
from urllib3.exceptions import DependencyWarning
warnings.simplefilter('ignore', DependencyWarning)
from .__version__ import __title__, __description__, __url__, __version__
from .__version__ import __build__, __author__, __author_email__, __license__
from .__version__ import __copyright__, __cake__
from . import utils
from . import packages
from .models import Request, Response, PreparedRequest
from .api import request, get, head, post, patch, put, delete, options
from .sessions import session, Session
from .status_codes import codes
from .exceptions import (
RequestException, Timeout, URLRequired,
TooManyRedirects, HTTPError, ConnectionError,
FileModeWarning, ConnectTimeout, ReadTimeout
)
# Set default logging handler to avoid "No handler found" warnings.
import logging
try: # Python 2.7+
from logging import NullHandler
except ImportError:
class NullHandler(logging.Handler):
def emit(self, record):
pass
logging.getLogger(__name__).addHandler(NullHandler())
# FileModeWarnings go off per the default.
warnings.simplefilter('default', FileModeWarning, append=True)
| 4,056 | 28.613139 | 102 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/requests/compat.py | # -*- coding: utf-8 -*-
"""
requests.compat
~~~~~~~~~~~~~~~
This module handles import compatibility issues between Python 2 and
Python 3.
"""
import chardet
import sys
# -------
# Pythons
# -------
# Syntax sugar.
_ver = sys.version_info
#: Python 2.x?
is_py2 = (_ver[0] == 2)
#: Python 3.x?
is_py3 = (_ver[0] == 3)
try:
import simplejson as json
except ImportError:
import json
# ---------
# Specifics
# ---------
if is_py2:
from urllib import (
quote, unquote, quote_plus, unquote_plus, urlencode, getproxies,
proxy_bypass, proxy_bypass_environment, getproxies_environment)
from urlparse import urlparse, urlunparse, urljoin, urlsplit, urldefrag
from urllib2 import parse_http_list
import cookielib
from Cookie import Morsel
from StringIO import StringIO
from collections import Callable, Mapping, MutableMapping
from urllib3.packages.ordered_dict import OrderedDict
builtin_str = str
bytes = str
str = unicode
basestring = basestring
numeric_types = (int, long, float)
integer_types = (int, long)
elif is_py3:
from urllib.parse import urlparse, urlunparse, urljoin, urlsplit, urlencode, quote, unquote, quote_plus, unquote_plus, urldefrag
from urllib.request import parse_http_list, getproxies, proxy_bypass, proxy_bypass_environment, getproxies_environment
from http import cookiejar as cookielib
from http.cookies import Morsel
from io import StringIO
from collections import OrderedDict
from collections.abc import Callable, Mapping, MutableMapping
builtin_str = str
str = str
bytes = bytes
basestring = (str, bytes)
numeric_types = (int, float)
integer_types = (int,)
| 1,723 | 22.944444 | 132 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/requests/adapters.py | # -*- coding: utf-8 -*-
"""
requests.adapters
~~~~~~~~~~~~~~~~~
This module contains the transport adapters that Requests uses to define
and maintain connections.
"""
import os.path
import socket
from urllib3.poolmanager import PoolManager, proxy_from_url
from urllib3.response import HTTPResponse
from urllib3.util import parse_url
from urllib3.util import Timeout as TimeoutSauce
from urllib3.util.retry import Retry
from urllib3.exceptions import ClosedPoolError
from urllib3.exceptions import ConnectTimeoutError
from urllib3.exceptions import HTTPError as _HTTPError
from urllib3.exceptions import MaxRetryError
from urllib3.exceptions import NewConnectionError
from urllib3.exceptions import ProxyError as _ProxyError
from urllib3.exceptions import ProtocolError
from urllib3.exceptions import ReadTimeoutError
from urllib3.exceptions import SSLError as _SSLError
from urllib3.exceptions import ResponseError
from .models import Response
from .compat import urlparse, basestring
from .utils import (DEFAULT_CA_BUNDLE_PATH, extract_zipped_paths,
get_encoding_from_headers, prepend_scheme_if_needed,
get_auth_from_url, urldefragauth, select_proxy)
from .structures import CaseInsensitiveDict
from .cookies import extract_cookies_to_jar
from .exceptions import (ConnectionError, ConnectTimeout, ReadTimeout, SSLError,
ProxyError, RetryError, InvalidSchema, InvalidProxyURL)
from .auth import _basic_auth_str
try:
from urllib3.contrib.socks import SOCKSProxyManager
except ImportError:
def SOCKSProxyManager(*args, **kwargs):
raise InvalidSchema("Missing dependencies for SOCKS support.")
DEFAULT_POOLBLOCK = False
DEFAULT_POOLSIZE = 10
DEFAULT_RETRIES = 0
DEFAULT_POOL_TIMEOUT = None
class BaseAdapter(object):
"""The Base Transport Adapter"""
def __init__(self):
super(BaseAdapter, self).__init__()
def send(self, request, stream=False, timeout=None, verify=True,
cert=None, proxies=None):
"""Sends PreparedRequest object. Returns Response object.
:param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
:param stream: (optional) Whether to stream the request content.
:param timeout: (optional) How long to wait for the server to send
data before giving up, as a float, or a :ref:`(connect timeout,
read timeout) <timeouts>` tuple.
:type timeout: float or tuple
:param verify: (optional) Either a boolean, in which case it controls whether we verify
the server's TLS certificate, or a string, in which case it must be a path
to a CA bundle to use
:param cert: (optional) Any user-provided SSL certificate to be trusted.
:param proxies: (optional) The proxies dictionary to apply to the request.
"""
raise NotImplementedError
def close(self):
"""Cleans up adapter specific items."""
raise NotImplementedError
class HTTPAdapter(BaseAdapter):
"""The built-in HTTP Adapter for urllib3.
Provides a general-case interface for Requests sessions to contact HTTP and
HTTPS urls by implementing the Transport Adapter interface. This class will
usually be created by the :class:`Session <Session>` class under the
covers.
:param pool_connections: The number of urllib3 connection pools to cache.
:param pool_maxsize: The maximum number of connections to save in the pool.
:param max_retries: The maximum number of retries each connection
should attempt. Note, this applies only to failed DNS lookups, socket
connections and connection timeouts, never to requests where data has
made it to the server. By default, Requests does not retry failed
connections. If you need granular control over the conditions under
which we retry a request, import urllib3's ``Retry`` class and pass
that instead.
:param pool_block: Whether the connection pool should block for connections.
Usage::
>>> import requests
>>> s = requests.Session()
>>> a = requests.adapters.HTTPAdapter(max_retries=3)
>>> s.mount('http://', a)
"""
__attrs__ = ['max_retries', 'config', '_pool_connections', '_pool_maxsize',
'_pool_block']
def __init__(self, pool_connections=DEFAULT_POOLSIZE,
pool_maxsize=DEFAULT_POOLSIZE, max_retries=DEFAULT_RETRIES,
pool_block=DEFAULT_POOLBLOCK):
if max_retries == DEFAULT_RETRIES:
self.max_retries = Retry(0, read=False)
else:
self.max_retries = Retry.from_int(max_retries)
self.config = {}
self.proxy_manager = {}
super(HTTPAdapter, self).__init__()
self._pool_connections = pool_connections
self._pool_maxsize = pool_maxsize
self._pool_block = pool_block
self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block)
def __getstate__(self):
return dict((attr, getattr(self, attr, None)) for attr in
self.__attrs__)
def __setstate__(self, state):
# Can't handle by adding 'proxy_manager' to self.__attrs__ because
# self.poolmanager uses a lambda function, which isn't pickleable.
self.proxy_manager = {}
self.config = {}
for attr, value in state.items():
setattr(self, attr, value)
self.init_poolmanager(self._pool_connections, self._pool_maxsize,
block=self._pool_block)
def init_poolmanager(self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs):
"""Initializes a urllib3 PoolManager.
This method should not be called from user code, and is only
exposed for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param connections: The number of urllib3 connection pools to cache.
:param maxsize: The maximum number of connections to save in the pool.
:param block: Block when no free connections are available.
:param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager.
"""
# save these values for pickling
self._pool_connections = connections
self._pool_maxsize = maxsize
self._pool_block = block
self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize,
block=block, strict=True, **pool_kwargs)
def proxy_manager_for(self, proxy, **proxy_kwargs):
"""Return urllib3 ProxyManager for the given proxy.
This method should not be called from user code, and is only
exposed for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param proxy: The proxy to return a urllib3 ProxyManager for.
:param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager.
:returns: ProxyManager
:rtype: urllib3.ProxyManager
"""
if proxy in self.proxy_manager:
manager = self.proxy_manager[proxy]
elif proxy.lower().startswith('socks'):
username, password = get_auth_from_url(proxy)
manager = self.proxy_manager[proxy] = SOCKSProxyManager(
proxy,
username=username,
password=password,
num_pools=self._pool_connections,
maxsize=self._pool_maxsize,
block=self._pool_block,
**proxy_kwargs
)
else:
proxy_headers = self.proxy_headers(proxy)
manager = self.proxy_manager[proxy] = proxy_from_url(
proxy,
proxy_headers=proxy_headers,
num_pools=self._pool_connections,
maxsize=self._pool_maxsize,
block=self._pool_block,
**proxy_kwargs)
return manager
def cert_verify(self, conn, url, verify, cert):
"""Verify a SSL certificate. This method should not be called from user
code, and is only exposed for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param conn: The urllib3 connection object associated with the cert.
:param url: The requested URL.
:param verify: Either a boolean, in which case it controls whether we verify
the server's TLS certificate, or a string, in which case it must be a path
to a CA bundle to use
:param cert: The SSL certificate to verify.
"""
if url.lower().startswith('https') and verify:
cert_loc = None
# Allow self-specified cert location.
if verify is not True:
cert_loc = verify
if not cert_loc:
cert_loc = extract_zipped_paths(DEFAULT_CA_BUNDLE_PATH)
if not cert_loc or not os.path.exists(cert_loc):
raise IOError("Could not find a suitable TLS CA certificate bundle, "
"invalid path: {0}".format(cert_loc))
conn.cert_reqs = 'CERT_REQUIRED'
if not os.path.isdir(cert_loc):
conn.ca_certs = cert_loc
else:
conn.ca_cert_dir = cert_loc
else:
conn.cert_reqs = 'CERT_NONE'
conn.ca_certs = None
conn.ca_cert_dir = None
if cert:
if not isinstance(cert, basestring):
conn.cert_file = cert[0]
conn.key_file = cert[1]
else:
conn.cert_file = cert
conn.key_file = None
if conn.cert_file and not os.path.exists(conn.cert_file):
raise IOError("Could not find the TLS certificate file, "
"invalid path: {0}".format(conn.cert_file))
if conn.key_file and not os.path.exists(conn.key_file):
raise IOError("Could not find the TLS key file, "
"invalid path: {0}".format(conn.key_file))
def build_response(self, req, resp):
"""Builds a :class:`Response <requests.Response>` object from a urllib3
response. This should not be called from user code, and is only exposed
for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`
:param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.
:param resp: The urllib3 response object.
:rtype: requests.Response
"""
response = Response()
# Fallback to None if there's no status_code, for whatever reason.
response.status_code = getattr(resp, 'status', None)
# Make headers case-insensitive.
response.headers = CaseInsensitiveDict(getattr(resp, 'headers', {}))
# Set encoding.
response.encoding = get_encoding_from_headers(response.headers)
response.raw = resp
response.reason = response.raw.reason
if isinstance(req.url, bytes):
response.url = req.url.decode('utf-8')
else:
response.url = req.url
# Add new cookies from the server.
extract_cookies_to_jar(response.cookies, req, resp)
# Give the Response some context.
response.request = req
response.connection = self
return response
def get_connection(self, url, proxies=None):
"""Returns a urllib3 connection for the given URL. This should not be
called from user code, and is only exposed for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param url: The URL to connect to.
:param proxies: (optional) A Requests-style dictionary of proxies used on this request.
:rtype: urllib3.ConnectionPool
"""
proxy = select_proxy(url, proxies)
if proxy:
proxy = prepend_scheme_if_needed(proxy, 'http')
proxy_url = parse_url(proxy)
if not proxy_url.host:
raise InvalidProxyURL("Please check proxy URL. It is malformed"
" and could be missing the host.")
proxy_manager = self.proxy_manager_for(proxy)
conn = proxy_manager.connection_from_url(url)
else:
# Only scheme should be lower case
parsed = urlparse(url)
url = parsed.geturl()
conn = self.poolmanager.connection_from_url(url)
return conn
def close(self):
"""Disposes of any internal state.
Currently, this closes the PoolManager and any active ProxyManager,
which closes any pooled connections.
"""
self.poolmanager.clear()
for proxy in self.proxy_manager.values():
proxy.clear()
def request_url(self, request, proxies):
"""Obtain the url to use when making the final request.
If the message is being sent through a HTTP proxy, the full URL has to
be used. Otherwise, we should only use the path portion of the URL.
This should not be called from user code, and is only exposed for use
when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
:param proxies: A dictionary of schemes or schemes and hosts to proxy URLs.
:rtype: str
"""
proxy = select_proxy(request.url, proxies)
scheme = urlparse(request.url).scheme
is_proxied_http_request = (proxy and scheme != 'https')
using_socks_proxy = False
if proxy:
proxy_scheme = urlparse(proxy).scheme.lower()
using_socks_proxy = proxy_scheme.startswith('socks')
url = request.path_url
if is_proxied_http_request and not using_socks_proxy:
url = urldefragauth(request.url)
return url
def add_headers(self, request, **kwargs):
"""Add any headers needed by the connection. As of v2.0 this does
nothing by default, but is left for overriding by users that subclass
the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
This should not be called from user code, and is only exposed for use
when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to.
:param kwargs: The keyword arguments from the call to send().
"""
pass
def proxy_headers(self, proxy):
"""Returns a dictionary of the headers to add to any request sent
through a proxy. This works with urllib3 magic to ensure that they are
correctly sent to the proxy, rather than in a tunnelled request if
CONNECT is being used.
This should not be called from user code, and is only exposed for use
when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param proxies: The url of the proxy being used for this request.
:rtype: dict
"""
headers = {}
username, password = get_auth_from_url(proxy)
if username:
headers['Proxy-Authorization'] = _basic_auth_str(username,
password)
return headers
def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None):
"""Sends PreparedRequest object. Returns Response object.
:param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
:param stream: (optional) Whether to stream the request content.
:param timeout: (optional) How long to wait for the server to send
data before giving up, as a float, or a :ref:`(connect timeout,
read timeout) <timeouts>` tuple.
:type timeout: float or tuple or urllib3 Timeout object
:param verify: (optional) Either a boolean, in which case it controls whether
we verify the server's TLS certificate, or a string, in which case it
must be a path to a CA bundle to use
:param cert: (optional) Any user-provided SSL certificate to be trusted.
:param proxies: (optional) The proxies dictionary to apply to the request.
:rtype: requests.Response
"""
conn = self.get_connection(request.url, proxies)
self.cert_verify(conn, request.url, verify, cert)
url = self.request_url(request, proxies)
self.add_headers(request, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies)
chunked = not (request.body is None or 'Content-Length' in request.headers)
if isinstance(timeout, tuple):
try:
connect, read = timeout
timeout = TimeoutSauce(connect=connect, read=read)
except ValueError as e:
# this may raise a string formatting error.
err = ("Invalid timeout {0}. Pass a (connect, read) "
"timeout tuple, or a single float to set "
"both timeouts to the same value".format(timeout))
raise ValueError(err)
elif isinstance(timeout, TimeoutSauce):
pass
else:
timeout = TimeoutSauce(connect=timeout, read=timeout)
try:
if not chunked:
resp = conn.urlopen(
method=request.method,
url=url,
body=request.body,
headers=request.headers,
redirect=False,
assert_same_host=False,
preload_content=False,
decode_content=False,
retries=self.max_retries,
timeout=timeout
)
# Send the request.
else:
if hasattr(conn, 'proxy_pool'):
conn = conn.proxy_pool
low_conn = conn._get_conn(timeout=DEFAULT_POOL_TIMEOUT)
try:
low_conn.putrequest(request.method,
url,
skip_accept_encoding=True)
for header, value in request.headers.items():
low_conn.putheader(header, value)
low_conn.endheaders()
for i in request.body:
low_conn.send(hex(len(i))[2:].encode('utf-8'))
low_conn.send(b'\r\n')
low_conn.send(i)
low_conn.send(b'\r\n')
low_conn.send(b'0\r\n\r\n')
# Receive the response from the server
try:
# For Python 2.7+ versions, use buffering of HTTP
# responses
r = low_conn.getresponse(buffering=True)
except TypeError:
# For compatibility with Python 2.6 versions and back
r = low_conn.getresponse()
resp = HTTPResponse.from_httplib(
r,
pool=conn,
connection=low_conn,
preload_content=False,
decode_content=False
)
except:
# If we hit any problems here, clean up the connection.
# Then, reraise so that we can handle the actual exception.
low_conn.close()
raise
except (ProtocolError, socket.error) as err:
raise ConnectionError(err, request=request)
except MaxRetryError as e:
if isinstance(e.reason, ConnectTimeoutError):
# TODO: Remove this in 3.0.0: see #2811
if not isinstance(e.reason, NewConnectionError):
raise ConnectTimeout(e, request=request)
if isinstance(e.reason, ResponseError):
raise RetryError(e, request=request)
if isinstance(e.reason, _ProxyError):
raise ProxyError(e, request=request)
if isinstance(e.reason, _SSLError):
# This branch is for urllib3 v1.22 and later.
raise SSLError(e, request=request)
raise ConnectionError(e, request=request)
except ClosedPoolError as e:
raise ConnectionError(e, request=request)
except _ProxyError as e:
raise ProxyError(e)
except (_SSLError, _HTTPError) as e:
if isinstance(e, _SSLError):
# This branch is for urllib3 versions earlier than v1.22
raise SSLError(e, request=request)
elif isinstance(e, ReadTimeoutError):
raise ReadTimeout(e, request=request)
else:
raise
return self.build_response(request, resp)
| 21,236 | 38.99435 | 108 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/requests/certs.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
requests.certs
~~~~~~~~~~~~~~
This module returns the preferred default CA certificate bundle. There is
only one — the one from the certifi package.
If you are packaging Requests, e.g., for a Linux distribution or a managed
environment, you can change the definition of where() to return a separately
packaged CA bundle.
"""
from certifi import where
if __name__ == '__main__':
print(where())
| 451 | 22.789474 | 76 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/certifi/__main__.py | from certifi import where
print(where())
| 41 | 13 | 25 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/certifi/core.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
certifi.py
~~~~~~~~~~
This module returns the installation location of cacert.pem.
"""
import os
import warnings
class DeprecatedBundleWarning(DeprecationWarning):
"""
The weak security bundle is being deprecated. Please bother your service
provider to get them to stop using cross-signed roots.
"""
def where():
f = os.path.dirname(__file__)
return os.path.join(f, 'cacert.pem')
def old_where():
warnings.warn(
"The weak security bundle has been removed. certifi.old_where() is now an alias "
"of certifi.where(). Please update your code to use certifi.where() instead. "
"certifi.old_where() will be removed in 2018.",
DeprecatedBundleWarning
)
return where()
if __name__ == '__main__':
print(where())
| 836 | 21.026316 | 89 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/certifi/__init__.py | from .core import where, old_where
__version__ = "2018.04.16"
| 63 | 15 | 34 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/__init__.py | """
future: Easy, safe support for Python 2/3 compatibility
=======================================================
``future`` is the missing compatibility layer between Python 2 and Python
3. It allows you to use a single, clean Python 3.x-compatible codebase to
support both Python 2 and Python 3 with minimal overhead.
It is designed to be used as follows::
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import (
bytes, dict, int, list, object, range, str,
ascii, chr, hex, input, next, oct, open,
pow, round, super,
filter, map, zip)
followed by predominantly standard, idiomatic Python 3 code that then runs
similarly on Python 2.6/2.7 and Python 3.3+.
The imports have no effect on Python 3. On Python 2, they shadow the
corresponding builtins, which normally have different semantics on Python 3
versus 2, to provide their Python 3 semantics.
Standard library reorganization
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
``future`` supports the standard library reorganization (PEP 3108) through the
following Py3 interfaces:
>>> # Top-level packages with Py3 names provided on Py2:
>>> import html.parser
>>> import queue
>>> import tkinter.dialog
>>> import xmlrpc.client
>>> # etc.
>>> # Aliases provided for extensions to existing Py2 module names:
>>> from future.standard_library import install_aliases
>>> install_aliases()
>>> from collections import Counter, OrderedDict # backported to Py2.6
>>> from collections import UserDict, UserList, UserString
>>> import urllib.request
>>> from itertools import filterfalse, zip_longest
>>> from subprocess import getoutput, getstatusoutput
Automatic conversion
--------------------
An included script called `futurize
<http://python-future.org/automatic_conversion.html>`_ aids in converting
code (from either Python 2 or Python 3) to code compatible with both
platforms. It is similar to ``python-modernize`` but goes further in
providing Python 3 compatibility through the use of the backported types
and builtin functions in ``future``.
Documentation
-------------
See: http://python-future.org
Credits
-------
:Author: Ed Schofield
:Sponsor: Python Charmers Pty Ltd, Australia, and Python Charmers Pte
Ltd, Singapore. http://pythoncharmers.com
:Others: See docs/credits.rst or http://python-future.org/credits.html
Licensing
---------
Copyright 2013-2016 Python Charmers Pty Ltd, Australia.
The software is distributed under an MIT licence. See LICENSE.txt.
"""
__title__ = 'future'
__author__ = 'Ed Schofield'
__license__ = 'MIT'
__copyright__ = 'Copyright 2013-2016 Python Charmers Pty Ltd'
__ver_major__ = 0
__ver_minor__ = 16
__ver_patch__ = 0
__ver_sub__ = ''
__version__ = "%d.%d.%d%s" % (__ver_major__, __ver_minor__,
__ver_patch__, __ver_sub__)
| 2,967 | 30.574468 | 78 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/builtins/newsuper.py | '''
This module provides a newsuper() function in Python 2 that mimics the
behaviour of super() in Python 3. It is designed to be used as follows:
from __future__ import division, absolute_import, print_function
from future.builtins import super
And then, for example:
class VerboseList(list):
def append(self, item):
print('Adding an item')
super().append(item) # new simpler super() function
Importing this module on Python 3 has no effect.
This is based on (i.e. almost identical to) Ryan Kelly's magicsuper
module here:
https://github.com/rfk/magicsuper.git
Excerpts from Ryan's docstring:
"Of course, you can still explicitly pass in the arguments if you want
to do something strange. Sometimes you really do want that, e.g. to
skip over some classes in the method resolution order.
"How does it work? By inspecting the calling frame to determine the
function object being executed and the object on which it's being
called, and then walking the object's __mro__ chain to find out where
that function was defined. Yuck, but it seems to work..."
'''
from __future__ import absolute_import
import sys
from types import FunctionType
from future.utils import PY3, PY26
_builtin_super = super
_SENTINEL = object()
def newsuper(typ=_SENTINEL, type_or_obj=_SENTINEL, framedepth=1):
'''Like builtin super(), but capable of magic.
This acts just like the builtin super() function, but if called
without any arguments it attempts to infer them at runtime.
'''
# Infer the correct call if used without arguments.
if typ is _SENTINEL:
# We'll need to do some frame hacking.
f = sys._getframe(framedepth)
try:
# Get the function's first positional argument.
type_or_obj = f.f_locals[f.f_code.co_varnames[0]]
except (IndexError, KeyError,):
raise RuntimeError('super() used in a function with no args')
try:
# Get the MRO so we can crawl it.
mro = type_or_obj.__mro__
except (AttributeError, RuntimeError): # see issue #160
try:
mro = type_or_obj.__class__.__mro__
except AttributeError:
raise RuntimeError('super() used with a non-newstyle class')
# A ``for...else`` block? Yes! It's odd, but useful.
# If unfamiliar with for...else, see:
#
# http://psung.blogspot.com/2007/12/for-else-in-python.html
for typ in mro:
# Find the class that owns the currently-executing method.
for meth in typ.__dict__.values():
# Drill down through any wrappers to the underlying func.
# This handles e.g. classmethod() and staticmethod().
try:
while not isinstance(meth,FunctionType):
if isinstance(meth, property):
# Calling __get__ on the property will invoke
# user code which might throw exceptions or have
# side effects
meth = meth.fget
else:
try:
meth = meth.__func__
except AttributeError:
meth = meth.__get__(type_or_obj)
except (AttributeError, TypeError):
continue
if meth.func_code is f.f_code:
break # Aha! Found you.
else:
continue # Not found! Move onto the next class in MRO.
break # Found! Break out of the search loop.
else:
raise RuntimeError('super() called outside a method')
# Dispatch to builtin super().
if type_or_obj is not _SENTINEL:
return _builtin_super(typ, type_or_obj)
return _builtin_super(typ)
def superm(*args, **kwds):
f = sys._getframe(1)
nm = f.f_code.co_name
return getattr(newsuper(framedepth=2),nm)(*args, **kwds)
__all__ = ['newsuper']
| 4,169 | 34.948276 | 76 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/builtins/misc.py | """
A module that brings in equivalents of various modified Python 3 builtins
into Py2. Has no effect on Py3.
The builtin functions are:
- ``ascii`` (from Py2's future_builtins module)
- ``hex`` (from Py2's future_builtins module)
- ``oct`` (from Py2's future_builtins module)
- ``chr`` (equivalent to ``unichr`` on Py2)
- ``input`` (equivalent to ``raw_input`` on Py2)
- ``next`` (calls ``__next__`` if it exists, else ``next`` method)
- ``open`` (equivalent to io.open on Py2)
- ``super`` (backport of Py3's magic zero-argument super() function
- ``round`` (new "Banker's Rounding" behaviour from Py3)
``isinstance`` is also currently exported for backwards compatibility
with v0.8.2, although this has been deprecated since v0.9.
input()
-------
Like the new ``input()`` function from Python 3 (without eval()), except
that it returns bytes. Equivalent to Python 2's ``raw_input()``.
Warning: By default, importing this module *removes* the old Python 2
input() function entirely from ``__builtin__`` for safety. This is
because forgetting to import the new ``input`` from ``future`` might
otherwise lead to a security vulnerability (shell injection) on Python 2.
To restore it, you can retrieve it yourself from
``__builtin__._old_input``.
Fortunately, ``input()`` seems to be seldom used in the wild in Python
2...
"""
from future import utils
if utils.PY2:
from io import open
from future_builtins import ascii, oct, hex
from __builtin__ import unichr as chr, pow as _builtin_pow
import __builtin__
# Only for backward compatibility with future v0.8.2:
isinstance = __builtin__.isinstance
# Warning: Python 2's input() is unsafe and MUST not be able to be used
# accidentally by someone who expects Python 3 semantics but forgets
# to import it on Python 2. Versions of ``future`` prior to 0.11
# deleted it from __builtin__. Now we keep in __builtin__ but shadow
# the name like all others. Just be sure to import ``input``.
input = raw_input
from future.builtins.newnext import newnext as next
from future.builtins.newround import newround as round
from future.builtins.newsuper import newsuper as super
from future.types.newint import newint
_SENTINEL = object()
def pow(x, y, z=_SENTINEL):
"""
pow(x, y[, z]) -> number
With two arguments, equivalent to x**y. With three arguments,
equivalent to (x**y) % z, but may be more efficient (e.g. for ints).
"""
# Handle newints
if isinstance(x, newint):
x = long(x)
if isinstance(y, newint):
y = long(y)
if isinstance(z, newint):
z = long(z)
try:
if z == _SENTINEL:
return _builtin_pow(x, y)
else:
return _builtin_pow(x, y, z)
except ValueError:
if z == _SENTINEL:
return _builtin_pow(x+0j, y)
else:
return _builtin_pow(x+0j, y, z)
# ``future`` doesn't support Py3.0/3.1. If we ever did, we'd add this:
# callable = __builtin__.callable
__all__ = ['ascii', 'chr', 'hex', 'input', 'isinstance', 'next', 'oct',
'open', 'pow', 'round', 'super']
else:
import builtins
ascii = builtins.ascii
chr = builtins.chr
hex = builtins.hex
input = builtins.input
next = builtins.next
# Only for backward compatibility with future v0.8.2:
isinstance = builtins.isinstance
oct = builtins.oct
open = builtins.open
pow = builtins.pow
round = builtins.round
super = builtins.super
__all__ = []
# The callable() function was removed from Py3.0 and 3.1 and
# reintroduced into Py3.2+. ``future`` doesn't support Py3.0/3.1. If we ever
# did, we'd add this:
# try:
# callable = builtins.callable
# except AttributeError:
# # Definition from Pandas
# def callable(obj):
# return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)
# __all__.append('callable')
| 4,087 | 31.704 | 85 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/builtins/iterators.py | """
This module is designed to be used as follows::
from future.builtins.iterators import *
And then, for example::
for i in range(10**15):
pass
for (a, b) in zip(range(10**15), range(-10**15, 0)):
pass
Note that this is standard Python 3 code, plus some imports that do
nothing on Python 3.
The iterators this brings in are::
- ``range``
- ``filter``
- ``map``
- ``zip``
On Python 2, ``range`` is a pure-Python backport of Python 3's ``range``
iterator with slicing support. The other iterators (``filter``, ``map``,
``zip``) are from the ``itertools`` module on Python 2. On Python 3 these
are available in the module namespace but not exported for * imports via
__all__ (zero no namespace pollution).
Note that these are also available in the standard library
``future_builtins`` module on Python 2 -- but not Python 3, so using
the standard library version is not portable, nor anywhere near complete.
"""
from __future__ import division, absolute_import, print_function
import itertools
from future import utils
if not utils.PY3:
filter = itertools.ifilter
map = itertools.imap
from future.types import newrange as range
zip = itertools.izip
__all__ = ['filter', 'map', 'range', 'zip']
else:
import builtins
filter = builtins.filter
map = builtins.map
range = builtins.range
zip = builtins.zip
__all__ = []
| 1,401 | 24.962963 | 73 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/builtins/__init__.py | """
A module that brings in equivalents of the new and modified Python 3
builtins into Py2. Has no effect on Py3.
See the docs `here <http://python-future.org/what-else.html>`_
(``docs/what-else.rst``) for more information.
"""
from future.builtins.iterators import (filter, map, zip)
# The isinstance import is no longer needed. We provide it only for
# backward-compatibility with future v0.8.2. It will be removed in future v1.0.
from future.builtins.misc import (ascii, chr, hex, input, isinstance, next,
oct, open, pow, round, super)
from future.utils import PY3
if PY3:
import builtins
bytes = builtins.bytes
dict = builtins.dict
int = builtins.int
list = builtins.list
object = builtins.object
range = builtins.range
str = builtins.str
__all__ = []
else:
from future.types import (newbytes as bytes,
newdict as dict,
newint as int,
newlist as list,
newobject as object,
newrange as range,
newstr as str)
from future import utils
if not utils.PY3:
# We only import names that shadow the builtins on Py2. No other namespace
# pollution on Py2.
# Only shadow builtins on Py2; no new names
__all__ = ['filter', 'map', 'zip',
'ascii', 'chr', 'hex', 'input', 'next', 'oct', 'open', 'pow',
'round', 'super',
'bytes', 'dict', 'int', 'list', 'object', 'range', 'str',
]
else:
# No namespace pollution on Py3
__all__ = []
| 1,669 | 31.115385 | 79 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/builtins/newnext.py | '''
This module provides a newnext() function in Python 2 that mimics the
behaviour of ``next()`` in Python 3, falling back to Python 2's behaviour for
compatibility if this fails.
``newnext(iterator)`` calls the iterator's ``__next__()`` method if it exists. If this
doesn't exist, it falls back to calling a ``next()`` method.
For example:
>>> class Odds(object):
... def __init__(self, start=1):
... self.value = start - 2
... def __next__(self): # note the Py3 interface
... self.value += 2
... return self.value
... def __iter__(self):
... return self
...
>>> iterator = Odds()
>>> next(iterator)
1
>>> next(iterator)
3
If you are defining your own custom iterator class as above, it is preferable
to explicitly decorate the class with the @implements_iterator decorator from
``future.utils`` as follows:
>>> @implements_iterator
... class Odds(object):
... # etc
... pass
This next() function is primarily for consuming iterators defined in Python 3
code elsewhere that we would like to run on Python 2 or 3.
'''
_builtin_next = next
_SENTINEL = object()
def newnext(iterator, default=_SENTINEL):
"""
next(iterator[, default])
Return the next item from the iterator. If default is given and the iterator
is exhausted, it is returned instead of raising StopIteration.
"""
# args = []
# if default is not _SENTINEL:
# args.append(default)
try:
try:
return iterator.__next__()
except AttributeError:
try:
return iterator.next()
except AttributeError:
raise TypeError("'{0}' object is not an iterator".format(
iterator.__class__.__name__))
except StopIteration as e:
if default is _SENTINEL:
raise e
else:
return default
__all__ = ['newnext']
| 2,014 | 26.986111 | 86 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/builtins/disabled.py | """
This disables builtin functions (and one exception class) which are
removed from Python 3.3.
This module is designed to be used like this::
from future.builtins.disabled import *
This disables the following obsolete Py2 builtin functions::
apply, cmp, coerce, execfile, file, input, long,
raw_input, reduce, reload, unicode, xrange
We don't hack __builtin__, which is very fragile because it contaminates
imported modules too. Instead, we just create new functions with
the same names as the obsolete builtins from Python 2 which raise
NameError exceptions when called.
Note that both ``input()`` and ``raw_input()`` are among the disabled
functions (in this module). Although ``input()`` exists as a builtin in
Python 3, the Python 2 ``input()`` builtin is unsafe to use because it
can lead to shell injection. Therefore we shadow it by default upon ``from
future.builtins.disabled import *``, in case someone forgets to import our
replacement ``input()`` somehow and expects Python 3 semantics.
See the ``future.builtins.misc`` module for a working version of
``input`` with Python 3 semantics.
(Note that callable() is not among the functions disabled; this was
reintroduced into Python 3.2.)
This exception class is also disabled:
StandardError
"""
from __future__ import division, absolute_import, print_function
from future import utils
OBSOLETE_BUILTINS = ['apply', 'chr', 'cmp', 'coerce', 'execfile', 'file',
'input', 'long', 'raw_input', 'reduce', 'reload',
'unicode', 'xrange', 'StandardError']
def disabled_function(name):
'''
Returns a function that cannot be called
'''
def disabled(*args, **kwargs):
'''
A function disabled by the ``future`` module. This function is
no longer a builtin in Python 3.
'''
raise NameError('obsolete Python 2 builtin {0} is disabled'.format(name))
return disabled
if not utils.PY3:
for fname in OBSOLETE_BUILTINS:
locals()[fname] = disabled_function(fname)
__all__ = OBSOLETE_BUILTINS
else:
__all__ = []
| 2,109 | 30.492537 | 81 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/builtins/newround.py | """
``python-future``: pure Python implementation of Python 3 round().
"""
from future.utils import PYPY, PY26, bind_method
# Use the decimal module for simplicity of implementation (and
# hopefully correctness).
from decimal import Decimal, ROUND_HALF_EVEN
def newround(number, ndigits=None):
"""
See Python 3 documentation: uses Banker's Rounding.
Delegates to the __round__ method if for some reason this exists.
If not, rounds a number to a given precision in decimal digits (default
0 digits). This returns an int when called with one argument,
otherwise the same type as the number. ndigits may be negative.
See the test_round method in future/tests/test_builtins.py for
examples.
"""
return_int = False
if ndigits is None:
return_int = True
ndigits = 0
if hasattr(number, '__round__'):
return number.__round__(ndigits)
if ndigits < 0:
raise NotImplementedError('negative ndigits not supported yet')
exponent = Decimal('10') ** (-ndigits)
if PYPY:
# Work around issue #24: round() breaks on PyPy with NumPy's types
if 'numpy' in repr(type(number)):
number = float(number)
if not PY26:
d = Decimal.from_float(number).quantize(exponent,
rounding=ROUND_HALF_EVEN)
else:
d = from_float_26(number).quantize(exponent, rounding=ROUND_HALF_EVEN)
if return_int:
return int(d)
else:
return float(d)
### From Python 2.7's decimal.py. Only needed to support Py2.6:
def from_float_26(f):
"""Converts a float to a decimal number, exactly.
Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
Since 0.1 is not exactly representable in binary floating point, the
value is stored as the nearest representable value which is
0x1.999999999999ap-4. The exact equivalent of the value in decimal
is 0.1000000000000000055511151231257827021181583404541015625.
>>> Decimal.from_float(0.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')
>>> Decimal.from_float(float('nan'))
Decimal('NaN')
>>> Decimal.from_float(float('inf'))
Decimal('Infinity')
>>> Decimal.from_float(-float('inf'))
Decimal('-Infinity')
>>> Decimal.from_float(-0.0)
Decimal('-0')
"""
import math as _math
from decimal import _dec_from_triple # only available on Py2.6 and Py2.7 (not 3.3)
if isinstance(f, (int, long)): # handle integer inputs
return Decimal(f)
if _math.isinf(f) or _math.isnan(f): # raises TypeError if not a float
return Decimal(repr(f))
if _math.copysign(1.0, f) == 1.0:
sign = 0
else:
sign = 1
n, d = abs(f).as_integer_ratio()
# int.bit_length() method doesn't exist on Py2.6:
def bit_length(d):
if d != 0:
return len(bin(abs(d))) - 2
else:
return 0
k = bit_length(d) - 1
result = _dec_from_triple(sign, str(n*5**k), -k)
return result
__all__ = ['newround']
| 3,105 | 30.06 | 89 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/tests/base.py | from __future__ import print_function, absolute_import
import os
import tempfile
import unittest
import sys
import re
import warnings
import io
from textwrap import dedent
from future.utils import bind_method, PY26, PY3, PY2, PY27
from future.moves.subprocess import check_output, STDOUT, CalledProcessError
if PY26:
import unittest2 as unittest
def reformat_code(code):
"""
Removes any leading \n and dedents.
"""
if code.startswith('\n'):
code = code[1:]
return dedent(code)
def order_future_lines(code):
"""
Returns the code block with any ``__future__`` import lines sorted, and
then any ``future`` import lines sorted, then any ``builtins`` import lines
sorted.
This only sorts the lines within the expected blocks.
See test_order_future_lines() for an example.
"""
# We need .splitlines(keepends=True), which doesn't exist on Py2,
# so we use this instead:
lines = code.split('\n')
uufuture_line_numbers = [i for i, line in enumerate(lines)
if line.startswith('from __future__ import ')]
future_line_numbers = [i for i, line in enumerate(lines)
if line.startswith('from future')
or line.startswith('from past')]
builtins_line_numbers = [i for i, line in enumerate(lines)
if line.startswith('from builtins')]
assert code.lstrip() == code, ('internal usage error: '
'dedent the code before calling order_future_lines()')
def mymax(numbers):
return max(numbers) if len(numbers) > 0 else 0
def mymin(numbers):
return min(numbers) if len(numbers) > 0 else float('inf')
assert mymax(uufuture_line_numbers) <= mymin(future_line_numbers), \
'the __future__ and future imports are out of order'
# assert mymax(future_line_numbers) <= mymin(builtins_line_numbers), \
# 'the future and builtins imports are out of order'
uul = sorted([lines[i] for i in uufuture_line_numbers])
sorted_uufuture_lines = dict(zip(uufuture_line_numbers, uul))
fl = sorted([lines[i] for i in future_line_numbers])
sorted_future_lines = dict(zip(future_line_numbers, fl))
bl = sorted([lines[i] for i in builtins_line_numbers])
sorted_builtins_lines = dict(zip(builtins_line_numbers, bl))
# Replace the old unsorted "from __future__ import ..." lines with the
# new sorted ones:
new_lines = []
for i in range(len(lines)):
if i in uufuture_line_numbers:
new_lines.append(sorted_uufuture_lines[i])
elif i in future_line_numbers:
new_lines.append(sorted_future_lines[i])
elif i in builtins_line_numbers:
new_lines.append(sorted_builtins_lines[i])
else:
new_lines.append(lines[i])
return '\n'.join(new_lines)
class VerboseCalledProcessError(CalledProcessError):
"""
Like CalledProcessError, but it displays more information (message and
script output) for diagnosing test failures etc.
"""
def __init__(self, msg, returncode, cmd, output=None):
self.msg = msg
self.returncode = returncode
self.cmd = cmd
self.output = output
def __str__(self):
return ("Command '%s' failed with exit status %d\nMessage: %s\nOutput: %s"
% (self.cmd, self.returncode, self.msg, self.output))
class FuturizeError(VerboseCalledProcessError):
pass
class PasteurizeError(VerboseCalledProcessError):
pass
class CodeHandler(unittest.TestCase):
"""
Handy mixin for test classes for writing / reading / futurizing /
running .py files in the test suite.
"""
def setUp(self):
"""
The outputs from the various futurize stages should have the
following headers:
"""
# After stage1:
# TODO: use this form after implementing a fixer to consolidate
# __future__ imports into a single line:
# self.headers1 = """
# from __future__ import absolute_import, division, print_function
# """
self.headers1 = reformat_code("""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
""")
# After stage2 --all-imports:
# TODO: use this form after implementing a fixer to consolidate
# __future__ imports into a single line:
# self.headers2 = """
# from __future__ import (absolute_import, division,
# print_function, unicode_literals)
# from future import standard_library
# from future.builtins import *
# """
self.headers2 = reformat_code("""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from future import standard_library
standard_library.install_aliases()
from builtins import *
""")
self.interpreters = [sys.executable]
self.tempdir = tempfile.mkdtemp() + os.path.sep
pypath = os.getenv('PYTHONPATH')
if pypath:
self.env = {'PYTHONPATH': os.getcwd() + os.pathsep + pypath}
else:
self.env = {'PYTHONPATH': os.getcwd()}
def convert(self, code, stages=(1, 2), all_imports=False, from3=False,
reformat=True, run=True, conservative=False):
"""
Converts the code block using ``futurize`` and returns the
resulting code.
Passing stages=[1] or stages=[2] passes the flag ``--stage1`` or
``stage2`` to ``futurize``. Passing both stages runs ``futurize``
with both stages by default.
If from3 is False, runs ``futurize``, converting from Python 2 to
both 2 and 3. If from3 is True, runs ``pasteurize`` to convert
from Python 3 to both 2 and 3.
Optionally reformats the code block first using the reformat() function.
If run is True, runs the resulting code under all Python
interpreters in self.interpreters.
"""
if reformat:
code = reformat_code(code)
self._write_test_script(code)
self._futurize_test_script(stages=stages, all_imports=all_imports,
from3=from3, conservative=conservative)
output = self._read_test_script()
if run:
for interpreter in self.interpreters:
_ = self._run_test_script(interpreter=interpreter)
return output
def compare(self, output, expected, ignore_imports=True):
"""
Compares whether the code blocks are equal. If not, raises an
exception so the test fails. Ignores any trailing whitespace like
blank lines.
If ignore_imports is True, passes the code blocks into the
strip_future_imports method.
If one code block is a unicode string and the other a
byte-string, it assumes the byte-string is encoded as utf-8.
"""
if ignore_imports:
output = self.strip_future_imports(output)
expected = self.strip_future_imports(expected)
if isinstance(output, bytes) and not isinstance(expected, bytes):
output = output.decode('utf-8')
if isinstance(expected, bytes) and not isinstance(output, bytes):
expected = expected.decode('utf-8')
self.assertEqual(order_future_lines(output.rstrip()),
expected.rstrip())
def strip_future_imports(self, code):
"""
Strips any of these import lines:
from __future__ import <anything>
from future <anything>
from future.<anything>
from builtins <anything>
or any line containing:
install_hooks()
or:
install_aliases()
Limitation: doesn't handle imports split across multiple lines like
this:
from __future__ import (absolute_import, division, print_function,
unicode_literals)
"""
output = []
# We need .splitlines(keepends=True), which doesn't exist on Py2,
# so we use this instead:
for line in code.split('\n'):
if not (line.startswith('from __future__ import ')
or line.startswith('from future ')
or line.startswith('from builtins ')
or 'install_hooks()' in line
or 'install_aliases()' in line
# but don't match "from future_builtins" :)
or line.startswith('from future.')):
output.append(line)
return '\n'.join(output)
def convert_check(self, before, expected, stages=(1, 2), all_imports=False,
ignore_imports=True, from3=False, run=True,
conservative=False):
"""
Convenience method that calls convert() and compare().
Reformats the code blocks automatically using the reformat_code()
function.
If all_imports is passed, we add the appropriate import headers
for the stage(s) selected to the ``expected`` code-block, so they
needn't appear repeatedly in the test code.
If ignore_imports is True, ignores the presence of any lines
beginning:
from __future__ import ...
from future import ...
for the purpose of the comparison.
"""
output = self.convert(before, stages=stages, all_imports=all_imports,
from3=from3, run=run, conservative=conservative)
if all_imports:
headers = self.headers2 if 2 in stages else self.headers1
else:
headers = ''
self.compare(output, headers + reformat_code(expected),
ignore_imports=ignore_imports)
def unchanged(self, code, **kwargs):
"""
Convenience method to ensure the code is unchanged by the
futurize process.
"""
self.convert_check(code, code, **kwargs)
def _write_test_script(self, code, filename='mytestscript.py'):
"""
Dedents the given code (a multiline string) and writes it out to
a file in a temporary folder like /tmp/tmpUDCn7x/mytestscript.py.
"""
if isinstance(code, bytes):
code = code.decode('utf-8')
# Be explicit about encoding the temp file as UTF-8 (issue #63):
with io.open(self.tempdir + filename, 'wt', encoding='utf-8') as f:
f.write(dedent(code))
def _read_test_script(self, filename='mytestscript.py'):
with io.open(self.tempdir + filename, 'rt', encoding='utf-8') as f:
newsource = f.read()
return newsource
def _futurize_test_script(self, filename='mytestscript.py', stages=(1, 2),
all_imports=False, from3=False,
conservative=False):
params = []
stages = list(stages)
if all_imports:
params.append('--all-imports')
if from3:
script = 'pasteurize.py'
else:
script = 'futurize.py'
if stages == [1]:
params.append('--stage1')
elif stages == [2]:
params.append('--stage2')
else:
assert stages == [1, 2]
if conservative:
params.append('--conservative')
# No extra params needed
# Absolute file path:
fn = self.tempdir + filename
call_args = [sys.executable, script] + params + ['-w', fn]
try:
output = check_output(call_args, stderr=STDOUT, env=self.env)
except CalledProcessError as e:
with open(fn) as f:
msg = (
'Error running the command %s\n'
'%s\n'
'Contents of file %s:\n'
'\n'
'%s') % (
' '.join(call_args),
'env=%s' % self.env,
fn,
'----\n%s\n----' % f.read(),
)
ErrorClass = (FuturizeError if 'futurize' in script else PasteurizeError)
raise ErrorClass(msg, e.returncode, e.cmd, output=e.output)
return output
def _run_test_script(self, filename='mytestscript.py',
interpreter=sys.executable):
# Absolute file path:
fn = self.tempdir + filename
try:
output = check_output([interpreter, fn],
env=self.env, stderr=STDOUT)
except CalledProcessError as e:
with open(fn) as f:
msg = (
'Error running the command %s\n'
'%s\n'
'Contents of file %s:\n'
'\n'
'%s') % (
' '.join([interpreter, fn]),
'env=%s' % self.env,
fn,
'----\n%s\n----' % f.read(),
)
if not hasattr(e, 'output'):
# The attribute CalledProcessError.output doesn't exist on Py2.6
e.output = None
raise VerboseCalledProcessError(msg, e.returncode, e.cmd, output=e.output)
return output
# Decorator to skip some tests on Python 2.6 ...
skip26 = unittest.skipIf(PY26, "this test is known to fail on Py2.6")
def expectedFailurePY3(func):
if not PY3:
return func
return unittest.expectedFailure(func)
def expectedFailurePY26(func):
if not PY26:
return func
return unittest.expectedFailure(func)
def expectedFailurePY27(func):
if not PY27:
return func
return unittest.expectedFailure(func)
def expectedFailurePY2(func):
if not PY2:
return func
return unittest.expectedFailure(func)
# Renamed in Py3.3:
if not hasattr(unittest.TestCase, 'assertRaisesRegex'):
unittest.TestCase.assertRaisesRegex = unittest.TestCase.assertRaisesRegexp
# From Py3.3:
def assertRegex(self, text, expected_regex, msg=None):
"""Fail the test unless the text matches the regular expression."""
if isinstance(expected_regex, (str, unicode)):
assert expected_regex, "expected_regex must not be empty."
expected_regex = re.compile(expected_regex)
if not expected_regex.search(text):
msg = msg or "Regex didn't match"
msg = '%s: %r not found in %r' % (msg, expected_regex.pattern, text)
raise self.failureException(msg)
if not hasattr(unittest.TestCase, 'assertRegex'):
bind_method(unittest.TestCase, 'assertRegex', assertRegex)
class _AssertRaisesBaseContext(object):
def __init__(self, expected, test_case, callable_obj=None,
expected_regex=None):
self.expected = expected
self.test_case = test_case
if callable_obj is not None:
try:
self.obj_name = callable_obj.__name__
except AttributeError:
self.obj_name = str(callable_obj)
else:
self.obj_name = None
if isinstance(expected_regex, (bytes, str)):
expected_regex = re.compile(expected_regex)
self.expected_regex = expected_regex
self.msg = None
def _raiseFailure(self, standardMsg):
msg = self.test_case._formatMessage(self.msg, standardMsg)
raise self.test_case.failureException(msg)
def handle(self, name, callable_obj, args, kwargs):
"""
If callable_obj is None, assertRaises/Warns is being used as a
context manager, so check for a 'msg' kwarg and return self.
If callable_obj is not None, call it passing args and kwargs.
"""
if callable_obj is None:
self.msg = kwargs.pop('msg', None)
return self
with self:
callable_obj(*args, **kwargs)
class _AssertWarnsContext(_AssertRaisesBaseContext):
"""A context manager used to implement TestCase.assertWarns* methods."""
def __enter__(self):
# The __warningregistry__'s need to be in a pristine state for tests
# to work properly.
for v in sys.modules.values():
if getattr(v, '__warningregistry__', None):
v.__warningregistry__ = {}
self.warnings_manager = warnings.catch_warnings(record=True)
self.warnings = self.warnings_manager.__enter__()
warnings.simplefilter("always", self.expected)
return self
def __exit__(self, exc_type, exc_value, tb):
self.warnings_manager.__exit__(exc_type, exc_value, tb)
if exc_type is not None:
# let unexpected exceptions pass through
return
try:
exc_name = self.expected.__name__
except AttributeError:
exc_name = str(self.expected)
first_matching = None
for m in self.warnings:
w = m.message
if not isinstance(w, self.expected):
continue
if first_matching is None:
first_matching = w
if (self.expected_regex is not None and
not self.expected_regex.search(str(w))):
continue
# store warning for later retrieval
self.warning = w
self.filename = m.filename
self.lineno = m.lineno
return
# Now we simply try to choose a helpful failure message
if first_matching is not None:
self._raiseFailure('"{}" does not match "{}"'.format(
self.expected_regex.pattern, str(first_matching)))
if self.obj_name:
self._raiseFailure("{} not triggered by {}".format(exc_name,
self.obj_name))
else:
self._raiseFailure("{} not triggered".format(exc_name))
def assertWarns(self, expected_warning, callable_obj=None, *args, **kwargs):
"""Fail unless a warning of class warnClass is triggered
by callable_obj when invoked with arguments args and keyword
arguments kwargs. If a different type of warning is
triggered, it will not be handled: depending on the other
warning filtering rules in effect, it might be silenced, printed
out, or raised as an exception.
If called with callable_obj omitted or None, will return a
context object used like this::
with self.assertWarns(SomeWarning):
do_something()
An optional keyword argument 'msg' can be provided when assertWarns
is used as a context object.
The context manager keeps a reference to the first matching
warning as the 'warning' attribute; similarly, the 'filename'
and 'lineno' attributes give you information about the line
of Python code from which the warning was triggered.
This allows you to inspect the warning after the assertion::
with self.assertWarns(SomeWarning) as cm:
do_something()
the_warning = cm.warning
self.assertEqual(the_warning.some_attribute, 147)
"""
context = _AssertWarnsContext(expected_warning, self, callable_obj)
return context.handle('assertWarns', callable_obj, args, kwargs)
if not hasattr(unittest.TestCase, 'assertWarns'):
bind_method(unittest.TestCase, 'assertWarns', assertWarns)
| 19,734 | 36.095865 | 86 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/tests/__init__.py | 0 | 0 | 0 | py |
|
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/moves/_dummy_thread.py | from __future__ import absolute_import
from future.utils import PY3
if PY3:
from _dummy_thread import *
else:
__future_module__ = True
from dummy_thread import *
| 175 | 18.555556 | 38 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/moves/winreg.py | from __future__ import absolute_import
from future.utils import PY3
if PY3:
from winreg import *
else:
__future_module__ = True
from _winreg import *
| 163 | 17.222222 | 38 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/moves/configparser.py | from __future__ import absolute_import
from future.utils import PY2
if PY2:
from ConfigParser import *
else:
from configparser import *
| 146 | 15.333333 | 38 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/moves/_markupbase.py | from __future__ import absolute_import
from future.utils import PY3
if PY3:
from _markupbase import *
else:
__future_module__ = True
from markupbase import *
| 171 | 18.111111 | 38 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/moves/pickle.py | from __future__ import absolute_import
from future.utils import PY3
if PY3:
from pickle import *
else:
__future_module__ = True
try:
from cPickle import *
except ImportError:
from pickle import *
| 229 | 18.166667 | 38 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/moves/builtins.py | from __future__ import absolute_import
from future.utils import PY3
if PY3:
from builtins import *
else:
__future_module__ = True
from __builtin__ import *
# Overwrite any old definitions with the equivalent future.builtins ones:
from future.builtins import *
| 281 | 24.636364 | 77 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/moves/queue.py | from __future__ import absolute_import
from future.utils import PY3
if PY3:
from queue import *
else:
__future_module__ = True
from Queue import *
| 160 | 16.888889 | 38 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/moves/subprocess.py | from __future__ import absolute_import
from future.utils import PY2, PY26
from subprocess import *
if PY2:
__future_module__ = True
from commands import getoutput, getstatusoutput
if PY26:
from future.backports.misc import check_output
| 251 | 20 | 51 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/moves/copyreg.py | from __future__ import absolute_import
from future.utils import PY3
if PY3:
from copyreg import *
else:
__future_module__ = True
from copy_reg import *
| 165 | 17.444444 | 38 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/moves/itertools.py | from __future__ import absolute_import
from itertools import *
try:
zip_longest = izip_longest
filterfalse = ifilterfalse
except NameError:
pass
| 158 | 16.666667 | 38 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/moves/socketserver.py | from __future__ import absolute_import
from future.utils import PY3
if PY3:
from socketserver import *
else:
__future_module__ = True
from SocketServer import *
| 174 | 18.444444 | 38 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/moves/_thread.py | from __future__ import absolute_import
from future.utils import PY3
if PY3:
from _thread import *
else:
__future_module__ = True
from thread import *
| 163 | 17.222222 | 38 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/moves/__init__.py | # future.moves package
from __future__ import absolute_import
import sys
__future_module__ = True
from future.standard_library import import_top_level_modules
if sys.version_info[0] == 3:
import_top_level_modules()
| 220 | 23.555556 | 60 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/moves/collections.py | from __future__ import absolute_import
import sys
from future.utils import PY2, PY26
__future_module__ = True
from collections import *
if PY2:
from UserDict import UserDict
from UserList import UserList
from UserString import UserString
if PY26:
from future.backports.misc import OrderedDict, Counter
if sys.version_info < (3, 3):
from future.backports.misc import ChainMap, _count_elements
| 417 | 21 | 63 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/moves/sys.py | from __future__ import absolute_import
from future.utils import PY2
from sys import *
if PY2:
from __builtin__ import intern
| 132 | 13.777778 | 38 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/moves/reprlib.py | from __future__ import absolute_import
from future.utils import PY3
if PY3:
from reprlib import *
else:
__future_module__ = True
from repr import *
| 161 | 17 | 38 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/moves/urllib/error.py | from __future__ import absolute_import
from future.standard_library import suspend_hooks
from future.utils import PY3
if PY3:
from urllib.error import *
else:
__future_module__ = True
# We use this method to get at the original Py2 urllib before any renaming magic
# ContentTooShortError = sys.py2_modules['urllib'].ContentTooShortError
with suspend_hooks():
from urllib import ContentTooShortError
from urllib2 import URLError, HTTPError
| 487 | 27.705882 | 84 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/moves/urllib/response.py | from future import standard_library
from future.utils import PY3
if PY3:
from urllib.response import *
else:
__future_module__ = True
with standard_library.suspend_hooks():
from urllib import (addbase,
addclosehook,
addinfo,
addinfourl)
| 343 | 23.571429 | 42 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/moves/urllib/__init__.py | from __future__ import absolute_import
from future.utils import PY3
if not PY3:
__future_module__ = True
| 111 | 15 | 38 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/moves/urllib/parse.py | from __future__ import absolute_import
from future.standard_library import suspend_hooks
from future.utils import PY3
if PY3:
from urllib.parse import *
else:
__future_module__ = True
from urlparse import (ParseResult, SplitResult, parse_qs, parse_qsl,
urldefrag, urljoin, urlparse, urlsplit,
urlunparse, urlunsplit)
# we use this method to get at the original py2 urllib before any renaming
# quote = sys.py2_modules['urllib'].quote
# quote_plus = sys.py2_modules['urllib'].quote_plus
# unquote = sys.py2_modules['urllib'].unquote
# unquote_plus = sys.py2_modules['urllib'].unquote_plus
# urlencode = sys.py2_modules['urllib'].urlencode
# splitquery = sys.py2_modules['urllib'].splitquery
with suspend_hooks():
from urllib import (quote,
quote_plus,
unquote,
unquote_plus,
urlencode,
splitquery)
| 1,053 | 35.344828 | 78 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/moves/urllib/request.py | from __future__ import absolute_import
from future.standard_library import suspend_hooks
from future.utils import PY3
if PY3:
from urllib.request import *
# This aren't in __all__:
from urllib.request import (getproxies,
pathname2url,
proxy_bypass,
quote,
request_host,
splitattr,
splithost,
splitpasswd,
splitport,
splitquery,
splittag,
splittype,
splituser,
splitvalue,
thishost,
to_bytes,
unquote,
unwrap,
url2pathname,
urlcleanup,
urljoin,
urlopen,
urlparse,
urlretrieve,
urlsplit,
urlunparse)
else:
__future_module__ = True
with suspend_hooks():
from urllib import *
from urllib2 import *
from urlparse import *
# Rename:
from urllib import toBytes # missing from __all__ on Py2.6
to_bytes = toBytes
# from urllib import (pathname2url,
# url2pathname,
# getproxies,
# urlretrieve,
# urlcleanup,
# URLopener,
# FancyURLopener,
# proxy_bypass)
# from urllib2 import (
# AbstractBasicAuthHandler,
# AbstractDigestAuthHandler,
# BaseHandler,
# CacheFTPHandler,
# FileHandler,
# FTPHandler,
# HTTPBasicAuthHandler,
# HTTPCookieProcessor,
# HTTPDefaultErrorHandler,
# HTTPDigestAuthHandler,
# HTTPErrorProcessor,
# HTTPHandler,
# HTTPPasswordMgr,
# HTTPPasswordMgrWithDefaultRealm,
# HTTPRedirectHandler,
# HTTPSHandler,
# URLError,
# build_opener,
# install_opener,
# OpenerDirector,
# ProxyBasicAuthHandler,
# ProxyDigestAuthHandler,
# ProxyHandler,
# Request,
# UnknownHandler,
# urlopen,
# )
# from urlparse import (
# urldefrag
# urljoin,
# urlparse,
# urlunparse,
# urlsplit,
# urlunsplit,
# parse_qs,
# parse_q"
# )
| 3,525 | 36.510638 | 69 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/moves/urllib/robotparser.py | from __future__ import absolute_import
from future.utils import PY3
if PY3:
from urllib.robotparser import *
else:
__future_module__ = True
from robotparser import *
| 179 | 19 | 38 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/moves/dbm/gnu.py | from __future__ import absolute_import
from future.utils import PY3
if PY3:
from dbm.gnu import *
else:
__future_module__ = True
from gdbm import *
| 162 | 15.3 | 38 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/moves/dbm/dumb.py | from __future__ import absolute_import
from future.utils import PY3
if PY3:
from dbm.dumb import *
else:
__future_module__ = True
from dumbdbm import *
| 166 | 15.7 | 38 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/moves/dbm/__init__.py | from __future__ import absolute_import
from future.utils import PY3
if PY3:
from dbm import *
else:
__future_module__ = True
from whichdb import *
from anydbm import *
# Py3.3's dbm/__init__.py imports ndbm but doesn't expose it via __all__.
# In case some (badly written) code depends on dbm.ndbm after import dbm,
# we simulate this:
if PY3:
from dbm import ndbm
else:
try:
from future.moves.dbm import ndbm
except ImportError:
ndbm = None
| 488 | 22.285714 | 73 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/moves/dbm/ndbm.py | from __future__ import absolute_import
from future.utils import PY3
if PY3:
from dbm.ndbm import *
else:
__future_module__ = True
from dbm import *
| 162 | 15.3 | 38 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/moves/test/support.py | from __future__ import absolute_import
from future.standard_library import suspend_hooks
from future.utils import PY3
if PY3:
from test.support import *
else:
__future_module__ = True
with suspend_hooks():
from test.test_support import *
| 260 | 20.75 | 49 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/moves/test/__init__.py | from __future__ import absolute_import
from future.utils import PY3
if not PY3:
__future_module__ = True
| 110 | 17.5 | 38 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/moves/xmlrpc/server.py | from __future__ import absolute_import
from future.utils import PY3
if PY3:
from xmlrpc.server import *
else:
from xmlrpclib import *
| 143 | 17 | 38 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/moves/xmlrpc/client.py | from __future__ import absolute_import
from future.utils import PY3
if PY3:
from xmlrpc.client import *
else:
from xmlrpclib import *
| 143 | 17 | 38 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/moves/xmlrpc/__init__.py | 0 | 0 | 0 | py |
|
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/moves/tkinter/dnd.py | from __future__ import absolute_import
from future.utils import PY3
if PY3:
from tkinter.dnd import *
else:
try:
from Tkdnd import *
except ImportError:
raise ImportError('The Tkdnd module is missing. Does your Py2 '
'installation include tkinter?')
| 307 | 21 | 71 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/moves/tkinter/constants.py | from __future__ import absolute_import
from future.utils import PY3
if PY3:
from tkinter.constants import *
else:
try:
from Tkconstants import *
except ImportError:
raise ImportError('The Tkconstants module is missing. Does your Py2 '
'installation include tkinter?')
| 325 | 22.285714 | 77 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/moves/tkinter/tix.py | from __future__ import absolute_import
from future.utils import PY3
if PY3:
from tkinter.tix import *
else:
try:
from Tix import *
except ImportError:
raise ImportError('The Tix module is missing. Does your Py2 '
'installation include tkinter?')
| 303 | 20.714286 | 69 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/moves/tkinter/scrolledtext.py | from __future__ import absolute_import
from future.utils import PY3
if PY3:
from tkinter.scrolledtext import *
else:
try:
from ScrolledText import *
except ImportError:
raise ImportError('The ScrolledText module is missing. Does your Py2 '
'installation include tkinter?')
| 330 | 22.642857 | 78 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/moves/tkinter/dialog.py | from __future__ import absolute_import
from future.utils import PY3
if PY3:
from tkinter.dialog import *
else:
try:
from Dialog import *
except ImportError:
raise ImportError('The Dialog module is missing. Does your Py2 '
'installation include tkinter?')
| 312 | 21.357143 | 72 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/moves/tkinter/simpledialog.py | from __future__ import absolute_import
from future.utils import PY3
if PY3:
from tkinter.simpledialog import *
else:
try:
from SimpleDialog import *
except ImportError:
raise ImportError('The SimpleDialog module is missing. Does your Py2 '
'installation include tkinter?')
| 330 | 22.642857 | 78 | py |
cba-pipeline-public | cba-pipeline-public-master/containernet/ndn-containers/ndn_headless-player/bandits/venv/lib/python3.6/site-packages/future/moves/tkinter/colorchooser.py | from __future__ import absolute_import
from future.utils import PY3
if PY3:
from tkinter.colorchooser import *
else:
try:
from tkColorChooser import *
except ImportError:
raise ImportError('The tkColorChooser module is missing. Does your Py2 '
'installation include tkinter?')
| 334 | 22.928571 | 80 | py |
Subsets and Splits