/usr/lib/python2.7/dist-packages/cartopy/tests/mpl/__init__.py is in python-cartopy 0.14.2+dfsg1-2build3.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 | # (C) British Crown Copyright 2011 - 2016, Met Office
#
# This file is part of cartopy.
#
# cartopy is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# cartopy is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with cartopy. If not, see <https://www.gnu.org/licenses/>.
from __future__ import (absolute_import, division, print_function)
import base64
import os
import glob
import shutil
import warnings
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import matplotlib.testing.compare as mcompare
import matplotlib.tests as mtests
import matplotlib._pylab_helpers as pyplot_helpers
class ImageTesting(object):
"""
Provides a convenient class for running visual matplotlib tests.
In general, this class should be used as a decorator to a test function
which generates one (or more) figures.
::
@ImageTesting(['simple_test'])
def test_simple():
import matplotlib.pyplot as plt
plt.plot(range(10))
To find out where the result and expected images reside one can create
a empty ImageTesting class instance and get the paths from the
:meth:`expected_path` and :meth:`result_path` methods::
>>> import os
>>> import cartopy.tests.mpl
>>> img_testing = cartopy.tests.mpl.ImageTesting([])
>>> exp_fname = img_testing.expected_path('<TESTNAME>', '<IMGNAME>')
>>> result_fname = img_testing.result_path('<TESTNAME>', '<IMGNAME>')
>>> img_test_mod_dir = os.path.dirname(cartopy.__file__)
>>> print 'Result:', os.path.relpath(result_fname, img_test_mod_dir)
Result: tests/mpl/output/<TESTNAME>/result-<IMGNAME>.png
>>> print 'Expected:', os.path.relpath(exp_fname, img_test_mod_dir)
Expected: tests/mpl/baseline_images/mpl/<TESTNAME>/<IMGNAME>.png
.. note::
Subclasses of the ImageTesting class may decide to change the
location of the expected and result images. However, the same
technique for finding the locations of the images should hold true.
"""
#: The path where the standard ``baseline_images`` exist.
root_image_results = os.path.dirname(__file__)
#: The path where the images generated by the tests should go.
image_output_directory = os.path.join(root_image_results, 'output')
if not os.access(image_output_directory, os.W_OK):
if not os.access(os.getcwd(), os.W_OK):
raise IOError('Write access to a local disk is required to run '
'image tests. Run the tests from a current working '
'directory you have write access to to avoid this '
'issue.')
else:
image_output_directory = os.path.join(os.getcwd(),
'cartopy_test_output')
def __init__(self, img_names, tolerance=(0.1
if mpl.__version__ < '1.4' else
0.5)):
# With matplotlib v1.3 the tolerance keyword is an RMS of the pixel
# differences, as computed by matplotlib.testing.compare.calculate_rms
self.img_names = img_names
self.tolerance = tolerance
def expected_path(self, test_name, img_name, ext='.png'):
"""
Return the full path (minus extension) of where the expected image
should be found, given the name of the image being tested and the
name of the test being run.
"""
expected_fname = os.path.join(self.root_image_results,
'baseline_images', 'mpl', test_name,
img_name)
return expected_fname + ext
def result_path(self, test_name, img_name, ext='.png'):
"""
Return the full path (minus extension) of where the result image
should be given the name of the image being tested and the
name of the test being run.
"""
result_fname = os.path.join(self.image_output_directory,
test_name, 'result-' + img_name)
return result_fname + ext
def run_figure_comparisons(self, figures, test_name):
"""
Run the figure comparisons against the ``image_names``.
The number of figures passed must be equal to the number of
image names in ``self.image_names``.
.. note::
The figures are not closed by this method. If using the decorator
version of ImageTesting, they will be closed for you.
"""
n_figures_msg = ('Expected %s figures (based on the number of '
'image result filenames), but there are %s figures '
'available. The most likely reason for this is that '
'this test is producing too many figures, '
'(alternatively if not using ImageCompare as a '
'decorator, it is possible that a test run prior to '
'this one has not closed its figures).'
'' % (len(self.img_names), len(figures))
)
assert len(figures) == len(self.img_names), n_figures_msg
for img_name, figure in zip(self.img_names, figures):
expected_path = self.expected_path(test_name, img_name, '.png')
result_path = self.result_path(test_name, img_name, '.png')
if not os.path.isdir(os.path.dirname(expected_path)):
os.makedirs(os.path.dirname(expected_path))
if not os.path.isdir(os.path.dirname(result_path)):
os.makedirs(os.path.dirname(result_path))
self.save_figure(figure, result_path)
self.do_compare(result_path, expected_path, self.tolerance)
def save_figure(self, figure, result_fname):
"""
The actual call which saves the figure.
Returns nothing.
May be overridden to do figure based pre-processing (such
as removing text objects etc.)
"""
figure.savefig(result_fname)
def do_compare(self, result_fname, expected_fname, tol):
"""
Runs the comparison of the result file with the expected file.
If an RMS difference greater than ``tol`` is found an assertion
error is raised with an appropriate message with the paths to
the files concerned.
"""
if not os.path.exists(expected_fname):
warnings.warn('Created image in %s' % expected_fname)
shutil.copy2(result_fname, expected_fname)
err = mcompare.compare_images(expected_fname, result_fname,
tol=tol, in_decorator=True)
if err:
msg = ('Images were different (RMS: %s).\n%s %s %s\nConsider '
'running idiff to inspect these differences.'
'' % (err['rms'], err['actual'],
err['expected'], err['diff']))
assert False, msg
def __call__(self, test_func):
"""Called when the decorator is applied to a function."""
test_name = test_func.__name__
mod_name = test_func.__module__
if mod_name == '__main__':
import sys
fname = sys.modules[mod_name].__file__
mod_name = os.path.basename(os.path.splitext(fname)[0])
mod_name = mod_name.rsplit('.', 1)[-1]
def wrapped(*args, **kwargs):
orig_backend = plt.get_backend()
plt.switch_backend('agg')
mtests.setup()
if pyplot_helpers.Gcf.figs:
warnings.warn('Figures existed before running the %s %s test.'
' All figures should be closed after they run. '
'They will be closed automatically now.' %
(mod_name, test_name))
pyplot_helpers.Gcf.destroy_all()
r = test_func(*args, **kwargs)
fig_managers = pyplot_helpers.Gcf._activeQue
figures = [manager.canvas.figure for manager in fig_managers]
try:
self.run_figure_comparisons(figures, test_name=mod_name)
finally:
for figure in figures:
pyplot_helpers.Gcf.destroy_fig(figure)
plt.switch_backend(orig_backend)
return r
# nose needs the function's name to be in the form "test_*" to
# pick it up
wrapped.__name__ = test_name
return wrapped
def failed_images_iter():
"""
Return a generator of [expected, actual, diff] filenames for all failed
image tests since the test output directory was created.
"""
baseline_img_dir = os.path.join(ImageTesting.root_image_results,
'baseline_images', 'mpl')
diff_dir = os.path.join(ImageTesting.image_output_directory)
baselines = sorted(glob.glob(os.path.join(baseline_img_dir,
'*', '*.png')))
for expected_fname in baselines:
# Get the relative path of the expected image 2 folders up.
expected_rel = os.path.relpath(
expected_fname, os.path.dirname(os.path.dirname(expected_fname)))
result_fname = os.path.join(
diff_dir, os.path.dirname(expected_rel),
'result-' + os.path.basename(expected_rel))
diff_fname = result_fname[:-4] + '-failed-diff.png'
if os.path.exists(diff_fname):
yield expected_fname, result_fname, diff_fname
def failed_images_html():
"""
Generates HTML which shows the image failures side-by-side
when viewed in a web browser.
"""
data_uri_template = '<img alt="{alt}" src="data:image/png;base64,{img}">'
def image_as_base64(fname):
with open(fname, "rb") as fh:
return base64.b64encode(fh.read()).decode("ascii")
html = ['<!DOCTYPE html>', '<html>', '<body>']
for expected, actual, diff in failed_images_iter():
expected_html = data_uri_template.format(
alt='expected', img=image_as_base64(expected))
actual_html = data_uri_template.format(
alt='actual', img=image_as_base64(actual))
diff_html = data_uri_template.format(
alt='diff', img=image_as_base64(diff))
html.extend([expected, '<br>',
expected_html, actual_html, diff_html,
'<br><hr>'])
html.extend(['</body>', '</html>'])
return '\n'.join(html)
def show(projection, geometry):
orig_backend = matplotlib.get_backend()
plt.switch_backend('tkagg')
if geometry.type == 'MultiPolygon' and 1:
multi_polygon = geometry
for polygon in multi_polygon:
import cartopy.mpl.patch as patch
paths = patch.geos_to_path(polygon)
for pth in paths:
patch = mpatches.PathPatch(pth, edgecolor='none',
lw=0, alpha=0.2)
plt.gca().add_patch(patch)
line_string = polygon.exterior
plt.plot(*zip(*line_string.coords),
marker='+', linestyle='-')
elif geometry.type == 'MultiPolygon':
multi_polygon = geometry
for polygon in multi_polygon:
line_string = polygon.exterior
plt.plot(*zip(*line_string.coords),
marker='+', linestyle='-')
elif geometry.type == 'MultiLineString':
multi_line_string = geometry
for line_string in multi_line_string:
plt.plot(*zip(*line_string.coords),
marker='+', linestyle='-')
elif geometry.type == 'LinearRing':
plt.plot(*zip(*geometry.coords), marker='+', linestyle='-')
if 1:
# Whole map domain
plt.autoscale()
elif 0:
# The left-hand triangle
plt.xlim(-1.65e7, -1.2e7)
plt.ylim(0.3e7, 0.65e7)
elif 0:
# The tip of the left-hand triangle
plt.xlim(-1.65e7, -1.55e7)
plt.ylim(0.3e7, 0.4e7)
elif 1:
# The very tip of the left-hand triangle
plt.xlim(-1.632e7, -1.622e7)
plt.ylim(0.327e7, 0.337e7)
elif 1:
# The tip of the right-hand triangle
plt.xlim(1.55e7, 1.65e7)
plt.ylim(0.3e7, 0.4e7)
plt.plot(*zip(*projection.boundary.coords), marker='o',
scalex=False, scaley=False, zorder=-1)
plt.show()
plt.switch_backend(orig_backend)
|