/
buffer.py
268 lines (241 loc) · 9.58 KB
/
buffer.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
#!/usr/bin/env python3
# Use the proper idiom in the main module ...
# NOTE: See https://docs.python.org/3.11/library/multiprocessing.html#the-spawn-and-forkserver-start-methods
if __name__ == "__main__":
# This is a test suite for “geo.buffer()” with:
# A) a polygon that span the whole numerical range;
# B) a polygon that cross the equator;
# C) a polygon that cross the anti-meridian;
# D) a polygon that cross a pole;
# E) a polygon that cross both the equator and the anti-meridian; and
# F) a polygon that cross both a pole and the anti-meridian.
# Each polygon has a plot with both a top-down projection and a Robinson
# projection so that you can check it, along with an equirectangular plot.
# Import standard modules ...
import os
# Import special modules ...
try:
import cartopy
cartopy.config.update(
{
"cache_dir" : os.path.expanduser("~/.local/share/cartopy_cache"),
}
)
except:
raise Exception("\"cartopy\" is not installed; run \"pip install --user Cartopy\"") from None
try:
import geojson
geojson.geometry.Geometry.__init__.__defaults__ = (None, False, 12) # NOTE: See https://github.com/jazzband/geojson/issues/135#issuecomment-596509669
except:
raise Exception("\"geojson\" is not installed; run \"pip install --user geojson\"") from None
try:
import matplotlib
matplotlib.rcParams.update(
{
"backend" : "Agg", # NOTE: See https://matplotlib.org/stable/gallery/user_interfaces/canvasagg.html
"figure.dpi" : 300,
"figure.figsize" : (9.6, 7.2), # NOTE: See https://github.com/Guymer/misc/blob/main/README.md#matplotlib-figure-sizes
"font.size" : 8,
}
)
import matplotlib.pyplot
except:
raise Exception("\"matplotlib\" is not installed; run \"pip install --user matplotlib\"") from None
try:
import numpy
except:
raise Exception("\"numpy\" is not installed; run \"pip install --user numpy\"") from None
try:
import shapely
import shapely.geometry
except:
raise Exception("\"shapely\" is not installed; run \"pip install --user Shapely\"") from None
# Import my modules ...
try:
import pyguymer3
import pyguymer3.geo
import pyguymer3.image
except:
raise Exception("\"pyguymer3\" is not installed; you need to have the Python module from https://github.com/Guymer/PyGuymer3 located somewhere in your $PYTHONPATH") from None
print(f"Testing \"{pyguymer3.__path__[0]}\" ...")
# **************************************************************************
# Configure functions ...
debug = False
fill = 1.0 # [°]
fillSpace = "EuclideanSpace"
nang = 361 # [#]
simp = -1.0 # [°]
tol = 1.0e-10 # [°]
# Define polygons ...
polys = [
(-180.0, +90.0, 1000000.0, 900000.0), # Satisfies test A, C, D, F
( -90.0, +45.0, 1000000.0, 900000.0), # Satisfies test A
( 0.0, 0.0, 1000000.0, 900000.0), # Satisfies test A, B
( +90.0, -45.0, 1000000.0, 900000.0), # Satisfies test A
(+180.0, -90.0, 1000000.0, 900000.0), # Satisfies test A, C, D, F
(+170.0, +10.0, 1000000.0, 4000000.0), # Satisfies test B, C, E
(+170.0, +80.0, 1000000.0, 4000000.0), # Satisfies test C, D, F
( 0.0, +83.0, 1000000.0, 900000.0), # Satisfies test C, D, F
( -90.0, -83.0, 1000000.0, 900000.0), # Satisfies test C, D, F
( 0.0, 0.0, 10000000.0, 1500.0), # Satisfies test A, B
]
# Make output directory ...
if not os.path.exists("buffer"):
os.mkdir("buffer")
# **************************************************************************
# Loop over polygons ...
for i, (lon, lat, dist1, dist2) in enumerate(polys):
# Determine file names ...
fname = f"buffer/buffer{i:d}.png"
jname = f"buffer/buffer{i:d}.geojson"
print(f" > Making \"{jname}\" and \"{fname}\" ...")
# Create figure ...
fg = matplotlib.pyplot.figure()
# Create axis ...
ax1 = pyguymer3.geo.add_axis(
fg,
coastlines_resolution = "c",
index = 1,
ncols = 2,
nrows = 2,
)
# Configure axis ...
pyguymer3.geo.add_map_background(ax1)
# Create axis ...
ax2 = pyguymer3.geo.add_axis(
fg,
coastlines_resolution = "c",
index = 2,
lat = lat,
lon = lon,
ncols = 2,
nrows = 2,
)
# Configure axis ...
pyguymer3.geo.add_map_background(ax2)
# Create axis ...
ax3 = fg.add_subplot(2, 2, (3, 4))
# Configure axis ...
ax3.grid()
ax3.set_aspect("equal")
ax3.set_xlabel("Longitude [°]")
ax3.set_xlim(-180.0, +180.0)
ax3.set_xticks(range(-180, 225, 45))
ax3.set_ylabel("Latitude [°]")
ax3.set_ylim(-90.0, +90.0)
ax3.set_yticks(range(-90, 135, 45))
# Create point ...
point = shapely.geometry.point.Point(lon, lat)
# Buffer Point and plot it thrice ...
buff0 = pyguymer3.geo.buffer(
point,
dist1 + dist2,
debug = debug,
fill = fill,
fillSpace = fillSpace,
nang = nang,
simp = simp,
tol = tol,
)
ax1.add_geometries(
pyguymer3.geo.extract_polys(buff0),
cartopy.crs.PlateCarree(),
edgecolor = (1.0, 0.0, 0.0, 1.0),
facecolor = "none",
linewidth = 1.0,
)
ax2.add_geometries(
pyguymer3.geo.extract_polys(buff0),
cartopy.crs.PlateCarree(),
edgecolor = (1.0, 0.0, 0.0, 1.0),
facecolor = "none",
linewidth = 1.0,
)
for poly in pyguymer3.geo.extract_polys(buff0):
coords = numpy.array(poly.exterior.coords) # [°]
ax3.plot(
coords[:, 0],
coords[:, 1],
color = (1.0, 0.0, 0.0, 1.0),
)
# Buffer Point and plot it twice ...
buff1 = pyguymer3.geo.buffer(
point,
dist1,
debug = debug,
fill = fill,
fillSpace = fillSpace,
nang = nang,
simp = simp,
tol = tol,
)
ax1.add_geometries(
pyguymer3.geo.extract_polys(buff1),
cartopy.crs.PlateCarree(),
edgecolor = (0.0, 1.0, 0.0, 1.0),
facecolor = "none",
linewidth = 1.0,
)
ax2.add_geometries(
pyguymer3.geo.extract_polys(buff1),
cartopy.crs.PlateCarree(),
edgecolor = (0.0, 1.0, 0.0, 1.0),
facecolor = "none",
linewidth = 1.0,
)
for poly in pyguymer3.geo.extract_polys(buff1):
coords = numpy.array(poly.exterior.coords) # [°]
ax3.plot(
coords[:, 0],
coords[:, 1],
color = (0.0, 1.0, 0.0, 1.0),
)
# Buffer Polygon and plot it thrice ...
buff2 = pyguymer3.geo.buffer(
buff1,
dist2,
debug = debug,
fill = fill,
fillSpace = fillSpace,
nang = nang,
simp = simp,
tol = tol,
)
ax1.add_geometries(
pyguymer3.geo.extract_polys(buff2),
cartopy.crs.PlateCarree(),
edgecolor = (0.0, 0.0, 1.0, 1.0),
facecolor = (0.0, 0.0, 1.0, 0.5),
linewidth = 1.0,
)
ax2.add_geometries(
pyguymer3.geo.extract_polys(buff2),
cartopy.crs.PlateCarree(),
edgecolor = (0.0, 0.0, 1.0, 1.0),
facecolor = (0.0, 0.0, 1.0, 0.5),
linewidth = 1.0,
)
for poly in pyguymer3.geo.extract_polys(buff2):
coords = numpy.array(poly.exterior.coords) # [°]
ax3.plot(
coords[:, 0],
coords[:, 1],
color = (0.0, 0.0, 1.0, 1.0),
)
# Save GeoJSON ...
with open(jname, "wt", encoding = "utf-8") as fObj:
geojson.dump(
buff2,
fObj,
ensure_ascii = False,
indent = 4,
sort_keys = True,
)
# Configure figure ...
fg.suptitle(f"({lon:.1f},{lat:.1f}) buffered by {0.001 * dist1:,.1f}km & {0.001 * dist2:,.1f}km\nred = {0.001 * (dist1 + dist2):,.1f}km; green = {0.001 * dist1:,.1f}km; blue = {0.001 * dist1:,.1f}km & {0.001 * dist2:,.1f}km")
fg.tight_layout()
# Save figure ...
fg.savefig(fname)
matplotlib.pyplot.close(fg)
# Optimize PNG ..
pyguymer3.image.optimize_image(fname, strip = True)