-
Notifications
You must be signed in to change notification settings - Fork 80
/
test_ctx.py
490 lines (414 loc) · 15.5 KB
/
test_ctx.py
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
import matplotlib
matplotlib.use("agg") # To prevent plots from using display
import contextily as ctx
import os
import numpy as np
import mercantile as mt
import rasterio as rio
from contextily.tile import _calculate_zoom
from numpy.testing import assert_array_almost_equal
import pytest
TOL = 7
SEARCH = "boulder"
ADJUST = -3 # To save download size / time
# Tile
def test_bounds2raster():
w, s, e, n = (
-106.6495132446289,
25.845197677612305,
-93.50721740722656,
36.49387741088867,
)
_ = ctx.bounds2raster(w, s, e, n, "test.tif", zoom=4, ll=True)
rtr = rio.open("test.tif")
img = np.array([band for band in rtr.read()]).transpose(1, 2, 0)
solu = (
-12528334.684053527,
2509580.5126589066,
-10023646.141204873,
5014269.05550756,
)
for i, j in zip(rtr.bounds, solu):
assert round(i - j, TOL) == 0
assert img[100, 100, :].tolist() == [230, 229, 188, 255]
assert img[100, 200, :].tolist() == [156, 180, 131, 255]
assert img[200, 100, :].tolist() == [230, 225, 189, 255]
assert img[:,:,:3].sum() == 36926856
assert img.sum() == 53638536
assert_array_almost_equal(img[:,:,:3].mean(), 187.8197021484375)
assert_array_almost_equal(img.mean(), 204.614777)
# multiple tiles for which result is not square
w, s, e, n = (
2.5135730322461427,
49.529483547557504,
6.15665815595878,
51.47502370869813,
)
img, ext = ctx.bounds2raster(w, s, e, n, "test2.tif", zoom=7, ll=True)
rtr = rio.open("test2.tif")
rimg = np.array([band for band in rtr.read()]).transpose(1, 2, 0)
assert rimg.shape == img.shape
assert rimg.sum() == img.sum()
assert_array_almost_equal(rimg.mean(), img.mean())
assert_array_almost_equal(
ext, (0.0, 939258.2035682457, 6261721.35712164, 6887893.492833804)
)
rtr_bounds = [
-611.49622628141,
6262332.853347922,
938646.7073419644,
6888504.989060086,
]
assert_array_almost_equal(list(rtr.bounds), rtr_bounds)
def test_bounds2img():
w, s, e, n = (
-106.6495132446289,
25.845197677612305,
-93.50721740722656,
36.49387741088867,
)
img, ext = ctx.bounds2img(w, s, e, n, zoom=4, ll=True)
solu = (
-12523442.714243276,
-10018754.171394622,
2504688.5428486555,
5009377.085697309,
)
for i, j in zip(ext, solu):
assert round(i - j, TOL) == 0
assert img[100, 100, :].tolist() == [230, 229, 188, 255]
assert img[100, 200, :].tolist() == [156, 180, 131, 255]
assert img[200, 100, :].tolist() == [230, 225, 189, 255]
def test_warp_tiles():
w, s, e, n = (
-106.6495132446289,
25.845197677612305,
-93.50721740722656,
36.49387741088867,
)
img, ext = ctx.bounds2img(w, s, e, n, zoom=4, ll=True)
wimg, wext = ctx.warp_tiles(img, ext)
assert_array_almost_equal(
np.array(wext),
np.array(
[
-112.54394531249996,
-90.07903186397023,
21.966726124122374,
41.013065787006276,
]
),
)
assert wimg[100, 100, :].tolist() == [228, 221, 184, 255]
assert wimg[100, 200, :].tolist() == [213, 219, 177, 255]
assert wimg[200, 100, :].tolist() == [133, 130, 109, 255]
def test_warp_img_transform():
w, s, e, n = ext = (
-106.6495132446289,
25.845197677612305,
-93.50721740722656,
36.49387741088867,
)
_ = ctx.bounds2raster(w, s, e, n, "test.tif", zoom=4, ll=True)
rtr = rio.open("test.tif")
img = np.array([band for band in rtr.read()])
wimg, wext = ctx.warp_img_transform(
img, rtr.transform, rtr.crs, {"init": "epsg:4326"}
)
assert wimg[:, 100, 100].tolist() == [228, 221, 184, 255]
assert wimg[:, 100, 200].tolist() == [213, 219, 177, 255]
assert wimg[:, 200, 100].tolist() == [133, 130, 109, 255]
def test_howmany():
w, s, e, n = (
-106.6495132446289,
25.845197677612305,
-93.50721740722656,
36.49387741088867,
)
zoom = 7
expected = 25
got = ctx.howmany(w, s, e, n, zoom=zoom, verbose=False, ll=True)
assert got == expected
def test_ll2wdw():
w, s, e, n = (
-106.6495132446289,
25.845197677612305,
-93.50721740722656,
36.49387741088867,
)
hou = (-10676650.69219051, 3441477.046670125, -10576977.7804825, 3523606.146650609)
_ = ctx.bounds2raster(w, s, e, n, "test.tif", zoom=4, ll=True)
rtr = rio.open("test.tif")
wdw = ctx.tile.bb2wdw(hou, rtr)
assert wdw == ((152, 161), (189, 199))
def test__sm2ll():
w, s, e, n = (
-106.6495132446289,
25.845197677612305,
-93.50721740722656,
36.49387741088867,
)
minX, minY = ctx.tile._sm2ll(w, s)
maxX, maxY = ctx.tile._sm2ll(e, n)
nw, ns = mt.xy(minX, minY)
ne, nn = mt.xy(maxX, maxY)
assert round(nw - w, TOL) == 0
assert round(ns - s, TOL) == 0
assert round(ne - e, TOL) == 0
assert round(nn - n, TOL) == 0
def test_autozoom():
w, s, e, n = (-105.3014509, 39.9643513, -105.1780988, 40.094409)
expected_zoom = 13
zoom = _calculate_zoom(w, s, e, n)
assert zoom == expected_zoom
def test_validate_zoom():
# tiny extent to trigger large calculated zoom
w, s, e, n = (0, 0, 0.001, 0.001)
# automatically inferred -> set to known max but warn
with pytest.warns(UserWarning, match="inferred zoom level"):
ctx.bounds2img(w, s, e, n)
# specify manually -> raise an error
with pytest.raises(ValueError):
ctx.bounds2img(w, s, e, n, zoom=23)
# with specific string url (not dict) -> error when specified
url = "https://a.tile.openstreetmap.org/{z}/{x}/{y}.png"
with pytest.raises(ValueError):
ctx.bounds2img(w, s, e, n, zoom=33, source=url)
# but also when inferred (no max zoom know to set to)
with pytest.raises(ValueError):
ctx.bounds2img(w, s, e, n, source=url)
# Place
def test_place():
expected_bbox = [-105.430545, 39.8549856, -105.110545, 40.1749856]
expected_bbox_map = [
-11740727.544603072,
-11662456.027639052,
4774562.53480525,
4931105.568733288,
]
expected_zoom = 9
loc = ctx.Place(SEARCH, zoom_adjust=ADJUST)
assert loc.im.shape == (512, 256, 4)
loc # Make sure repr works
# Check auto picks are correct
assert loc.search == SEARCH
assert_array_almost_equal([loc.w, loc.s, loc.e, loc.n], expected_bbox)
assert_array_almost_equal(loc.bbox_map, expected_bbox_map)
assert loc.zoom == expected_zoom
loc = ctx.Place(SEARCH, path="./test2.tif", zoom_adjust=ADJUST)
assert os.path.exists("./test2.tif")
# .plot() method
ax = loc.plot()
assert_array_almost_equal(loc.bbox_map, ax.images[0].get_extent())
f, ax = matplotlib.pyplot.subplots(1)
ax = loc.plot(ax=ax)
assert_array_almost_equal(loc.bbox_map, ax.images[0].get_extent())
def test_plot_map():
# Place as a search
loc = ctx.Place(SEARCH, zoom_adjust=ADJUST)
w, e, s, n = loc.bbox_map
ax = ctx.plot_map(loc)
assert ax.get_title() == loc.place
ax = ctx.plot_map(loc.im, loc.bbox)
assert_array_almost_equal(loc.bbox, ax.images[0].get_extent())
# Place as an image
img, ext = ctx.bounds2img(w, s, e, n, zoom=10)
ax = ctx.plot_map(img, ext)
assert_array_almost_equal(ext, ax.images[0].get_extent())
# Plotting
def test_add_basemap():
# Plot boulder bbox as in test_place
x1, x2, y1, y2 = [
-11740727.544603072,
-11701591.786121061,
4852834.0517692715,
4891969.810251278,
]
# Test web basemap
fig, ax = matplotlib.pyplot.subplots(1)
ax.set_xlim(x1, x2)
ax.set_ylim(y1, y2)
ctx.add_basemap(ax, zoom=10)
# ensure add_basemap did not change the axis limits of ax
ax_extent = (x1, x2, y1, y2)
assert ax.axis() == ax_extent
assert ax.images[0].get_array().sum() == 51551927
assert ax.images[0].get_array().shape == (256, 256, 4)
assert_array_almost_equal(ax.images[0].get_array()[:,:,:3].mean(), 177.20665995279947)
assert_array_almost_equal(ax.images[0].get_array().mean(), 196.654995)
# Test local source
## Windowed read
subset = (
-11730803.981631357,
-11711668.223149346,
4862910.488797557,
4882046.247279563,
)
f, ax = matplotlib.pyplot.subplots(1)
ax.set_xlim(subset[0], subset[1])
ax.set_ylim(subset[2], subset[3])
loc = ctx.Place(SEARCH, path="./test2.tif", zoom_adjust=ADJUST)
ctx.add_basemap(ax, source="./test2.tif", reset_extent=True)
assert_array_almost_equal(subset, ax.images[0].get_extent())
assert ax.images[0].get_array().sum() == 3187219
assert ax.images[0].get_array()[:,:,:3].sum() == 2175124
assert ax.images[0].get_array().shape == (64, 64, 4)
assert_array_almost_equal(ax.images[0].get_array()[:,:,:3].mean(), 177.01204427083334)
assert_array_almost_equal(ax.images[0].get_array().mean(), 194.53240966796875)
## Full read
f, ax = matplotlib.pyplot.subplots(1)
ax.set_xlim(x1, x2)
ax.set_ylim(y1, y2)
loc = ctx.Place(SEARCH, path="./test2.tif", zoom_adjust=ADJUST)
ctx.add_basemap(ax, source="./test2.tif", reset_extent=False)
raster_extent = (
-11740880.418659642,
-11662608.901695622,
4774715.408861821,
4931258.442789858,
)
assert_array_almost_equal(raster_extent, ax.images[0].get_extent())
assert ax.images[0].get_array()[:,:,:3].sum() == 76248416
assert ax.images[0].get_array().sum() == 109671776
assert ax.images[0].get_array().shape == (512, 256, 4)
assert_array_almost_equal(ax.images[0].get_array()[:,:,:3].mean(), 193.90974934895834)
assert_array_almost_equal(ax.images[0].get_array().mean(), 209.18231201171875)
# Test with auto-zoom
f, ax = matplotlib.pyplot.subplots(1)
ax.set_xlim(x1, x2)
ax.set_ylim(y1, y2)
ctx.add_basemap(ax, zoom="auto")
ax_extent = (
-11740727.544603072,
-11701591.786121061,
4852834.051769271,
4891969.810251278,
)
assert_array_almost_equal(ax_extent, ax.images[0].get_extent())
assert ax.images[0].get_array()[:,:,:3].sum() == 563185119
assert ax.images[0].get_array().sum() == 830571999
assert ax.images[0].get_array().shape == (1024, 1024, 4)
assert_array_almost_equal(ax.images[0].get_array()[:,:,:3].mean(), 179.03172779083252)
assert_array_almost_equal(ax.images[0].get_array().mean(), 198.023796)
# Test on-th-fly warping
x1, x2 = -105.5, -105.00
y1, y2 = 39.56, 40.13
f, ax = matplotlib.pyplot.subplots(1)
ax.set_xlim(x1, x2)
ax.set_ylim(y1, y2)
ctx.add_basemap(ax, crs={"init": "epsg:4326"}, attribution=None)
assert ax.get_xlim() == (x1, x2)
assert ax.get_ylim() == (y1, y2)
assert ax.images[0].get_array()[:,:,:3].sum() == 724238693
assert ax.images[0].get_array().shape == (1135, 1183, 4)
assert_array_almost_equal(ax.images[0].get_array()[:,:,:3].mean(), 179.79593258881636)
assert_array_almost_equal(ax.images[0].get_array().mean(), 198.596949)
# Test local source warping
_ = ctx.bounds2raster(x1, y1, x2, y2, "./test2.tif", ll=True)
f, ax = matplotlib.pyplot.subplots(1)
ax.set_xlim(x1, x2)
ax.set_ylim(y1, y2)
ctx.add_basemap(
ax, source="./test2.tif", crs={"init": "epsg:4326"}, attribution=None
)
assert ax.get_xlim() == (x1, x2)
assert ax.get_ylim() == (y1, y2)
assert ax.images[0].get_array()[:,:,:3].sum() == 464536503
assert ax.images[0].get_array().shape == (980, 862, 4)
assert_array_almost_equal(ax.images[0].get_array()[:,:,:3].mean(), 183.301175)
assert ax.images[0].get_array().sum() == 678981558
assert_array_almost_equal(ax.images[0].get_array().mean(), 200.939189)
x1, x2, y1, y2 = [
-11740727.544603072,
-11701591.786121061,
4852834.0517692715,
4891969.810251278,
]
def test_add_basemap_overlay():
x1, x2, y1, y2 = [
-11740727.544603072,
-11701591.786121061,
4852834.0517692715,
4891969.810251278,
]
fig, ax = matplotlib.pyplot.subplots(1)
ax.set_xlim(x1, x2)
ax.set_ylim(y1, y2)
# Draw two layers, the 2nd of which is an overlay.
ctx.add_basemap(ax, zoom=10)
ctx.add_basemap(ax, zoom=10, source=ctx.providers.Stamen.TonerLabels)
# ensure add_basemap did not change the axis limits of ax
ax_extent = (x1, x2, y1, y2)
assert ax.axis() == ax_extent
# check totals on lowest (opaque terrain) base layer
assert_array_almost_equal(ax_extent, ax.images[0].get_extent())
assert ax.images[0].get_array()[:, :, :3].sum() == 34840247
assert ax.images[0].get_array().sum() == 51551927
assert ax.images[0].get_array().shape == (256, 256, 4)
assert_array_almost_equal(ax.images[0].get_array()[:, :, :3].mean(), 177.20665995279947)
assert_array_almost_equal(ax.images[0].get_array().mean(), 196.654995)
# check totals on overaly (mostly transparent labels) layer
assert ax.images[1].get_array().sum() == 1653387
assert ax.images[1].get_array().shape == (256, 256, 4)
assert_array_almost_equal(ax.images[1].get_array().mean(), 6.3071708679)
# create a new map
fig, ax = matplotlib.pyplot.subplots(1)
ax.set_xlim(x1, x2)
ax.set_ylim(y1, y2)
# Draw two layers, the 1st of which is an overlay.
ctx.add_basemap(ax, zoom=10, source=ctx.providers.Stamen.TonerLabels)
ctx.add_basemap(ax, zoom=10)
# check that z-order of overlay is higher than that of base layer
assert ax.images[0].zorder > ax.images[1].zorder
assert ax.images[0].get_array().sum() == 1653387
assert ax.images[1].get_array().sum() == 51551927
def test_basemap_attribution():
extent = (-11945319, -10336026, 2910477, 4438236)
def get_attr(ax):
return [
c
for c in ax.get_children()
if isinstance(c, matplotlib.text.Text) and c.get_text()
]
# default provider and attribution
fig, ax = matplotlib.pyplot.subplots()
ax.axis(extent)
ctx.add_basemap(ax)
(txt,) = get_attr(ax)
assert txt.get_text() == ctx.providers.Stamen.Terrain["attribution"]
# override attribution
fig, ax = matplotlib.pyplot.subplots()
ax.axis(extent)
ctx.add_basemap(ax, attribution="custom text")
(txt,) = get_attr(ax)
assert txt.get_text() == "custom text"
# disable attribution
fig, ax = matplotlib.pyplot.subplots()
ax.axis(extent)
ctx.add_basemap(ax, attribution=False)
assert len(get_attr(ax)) == 0
# specified provider
fig, ax = matplotlib.pyplot.subplots()
ax.axis(extent)
ctx.add_basemap(ax, source=ctx.providers.OpenStreetMap.Mapnik)
(txt,) = get_attr(ax)
assert txt.get_text() == ctx.providers.OpenStreetMap.Mapnik["attribution"]
def test_attribution():
fig, ax = matplotlib.pyplot.subplots(1)
txt = ctx.add_attribution(ax, "Test")
assert isinstance(txt, matplotlib.text.Text)
assert txt.get_text() == "Test"
# test passthrough font size and kwargs
fig, ax = matplotlib.pyplot.subplots(1)
txt = ctx.add_attribution(ax, "Test", font_size=15, fontfamily="monospace")
assert txt.get_size() == 15
assert txt.get_fontfamily() == ["monospace"]
def test_set_cache_dir(tmpdir):
# set cache directory manually
path = str(tmpdir.mkdir("cache"))
ctx.set_cache_dir(path)
# then check that plotting still works
extent = (-11945319, -10336026, 2910477, 4438236)
fig, ax = matplotlib.pyplot.subplots()
ax.axis(extent)
ctx.add_basemap(ax)