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
|
#!/usr/bin/env python3
# Use the proper idiom in the main module ...
# NOTE: See https://docs.python.org/3.12/library/multiprocessing.html#the-spawn-and-forkserver-start-methods
if __name__ == "__main__":
# Import standard modules ...
import gzip
import json
import math
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 numpy
except:
raise Exception("\"numpy\" is not installed; run \"pip install --user numpy\"") from None
try:
import PIL
import PIL.Image
PIL.Image.MAX_IMAGE_PIXELS = 1024 * 1024 * 1024 # [px]
import PIL.ImageDraw
except:
raise Exception("\"PIL\" is not installed; run \"pip install --user Pillow\"") from None
try:
import shapely
import shapely.geometry
import shapely.wkb
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; run \"pip install --user PyGuymer3\"") from None
# **************************************************************************
# Define resolution ...
res = "i"
nLon = 3600 # [px]
nLat = 1800 # [px]
dLon = 360.0 / float(nLon) # [°/px]
dLat = 180.0 / float(nLat) # [°/px]
# Define speed ...
speed = 20.0 # [NM/hr]
# Define starting location ...
startingLon = -1.0 # [°]
startingLat = 50.5 # [°]
# Define combinations ...
combs = [
# Study convergence (changing just "nAng" and "prec") ...
(2, 9, 5000,),
(2, 17, 2500,),
(2, 33, 1250,),
]
# **************************************************************************
# Load colour tables ...
with open(f"{pyguymer3.__path__[0]}/data/json/colourTables.json", "rt", encoding = "utf-8") as fObj:
cts = json.load(fObj)
# Find the Shapefiles ...
sfiles = [
cartopy.io.shapereader.gshhs(
level = 1,
scale = res,
),
cartopy.io.shapereader.gshhs(
level = 5,
scale = res,
),
cartopy.io.shapereader.gshhs(
level = 6,
scale = res,
),
]
print("Making axes ...")
# Create axes ...
lons = numpy.linspace(
-180.0 + 0.5 * dLon,
+180.0 - 0.5 * dLon,
nLon,
dtype = numpy.float64,
) # [°]
lats = numpy.linspace(
+90.0 - 0.5 * dLat,
-90.0 + 0.5 * dLat,
nLat,
dtype = numpy.float64,
) # [°]
# Check if the direct distance array exists ...
if os.path.exists("directDist.bin"):
# Load direct distance array ...
directDist = numpy.fromfile(
"directDist.bin",
dtype = numpy.float64,
).reshape(nLat, nLon) # [m]
else:
# Create (and save) direct distance array ...
directDist = numpy.zeros((nLat, nLon), dtype = numpy.float64) # [m]
for iLon in range(nLon):
for iLat in range(nLat):
try:
directDist[iLat, iLon], _, _ = pyguymer3.geo.calc_dist_between_two_locs(
startingLon,
startingLat,
lons[iLon],
lats[iLat],
) # [m]
except:
print(f"WARNING: Failed to find distance to ({lons[iLon]:+.9f}°,{lats[iLat]:+.9f}°), skipping.")
directDist[iLat, iLon] = -1.0 # [m]
directDist.tofile("directDist.bin")
# **************************************************************************
# Loop over combinations ...
for cons, nAng, prec in combs:
print(f"Processing \"cons={cons:.2e}, nAng={nAng:d}, prec={prec:.2e}\" ...")
# **********************************************************************
# Initialize images ...
absDiff = numpy.full((nLat, nLon), 1.0e9, dtype = numpy.float64) # [m]
relDiff = numpy.full((nLat, nLon), 1.0e9, dtype = numpy.float64) # [%]
# **********************************************************************
# Create short-hands ...
# NOTE: Say that 40,000 metres takes 1 hour at 20 knots.
freqLand = 24 * 40000 // prec # [#]
freqSimp = 40000 // prec # [#]
# Deduce directory name ...
dname = f"res={res}_cons={cons:.2e}_tol=1.00e-10/nAng={nAng:d}_prec={prec:.2e}/freqLand={freqLand:d}_freqSimp={freqSimp:d}_lon={startingLon:+011.6f}_lat={startingLat:+010.6f}/limit"
# Loop over sailing distances ...
for sailingDist in range(5, 30005, 5):
# Skip if this distance cannot exist (because the precision is too
# coarse) and determine the step count ...
if (1000 * sailingDist) % prec != 0:
continue
istep = ((1000 * sailingDist) // prec) - 1 # [#]
# Deduce file name and skip if it is missing ...
fname = f"{dname}/istep={istep + 1:06d}.wkb.gz"
if not os.path.exists(fname):
continue
# Load [Multi]LineString ...
with gzip.open(fname, mode = "rb") as gzObj:
limit = shapely.wkb.loads(gzObj.read())
# Loop over lines ...
for line in pyguymer3.geo.extract_lines(limit, onlyValid = False):
# Loop over coordinates ...
for lon, lat in line.coords:
# Deduce indices and skip if there isn't a direct distance ...
iLon = max(0, min(nLon - 1, math.floor((lon + 180.0) / dLon))) # [px]
iLat = max(0, min(nLat - 1, math.floor(( 90.0 - lat) / dLat))) # [px]
if directDist[iLat, iLon] < 0.0:
continue
# Update differences ...
delta = float(sailingDist * 1000) - directDist[iLat, iLon] # [m]
absDiff[iLat, iLon] = min(
absDiff[iLat, iLon],
delta,
) # [m]
relDiff[iLat, iLon] = min(
relDiff[iLat, iLon],
delta / directDist[iLat, iLon],
) # [%]
# **********************************************************************
print(" > Cleaning arrays ...")
# Remove pixels which are numerical noise (e.g., ones where it is
# quicker to sail than go directly) ...
numpy.place(absDiff, absDiff < 0.0, 0.0) # [m]
numpy.place(relDiff, relDiff < 0.0, 0.0) # [%]
print(f" > Maximum absolute value = {absDiff[absDiff < 1.0e9].max():.6e} m.")
print(f" > Maximum relative value = {relDiff[relDiff < 1.0e9].max():.6e} %.")
# **********************************************************************
print(" > Scaling array ...")
# Convert to useful units ...
# NOTE: 1.0e9 / 1852.0 / speed = 26997.84017278618 ≥ 1.0e4
absDiff /= 1852.0 # [NM]
absDiff /= speed # [hr]
print(f" > Maximum absolute value = {absDiff[absDiff < 1.0e4].max():.6e} hr.")
# **********************************************************************
# NOTE: Maximum absolute value = 1.435046e+07 m.
# NOTE: Maximum relative value = 1.276112e+01 %.
# NOTE: Maximum absolute value = 3.874313e+02 hr.
# NOTE: Maximum absolute value = 7.169781e+06 m.
# NOTE: Maximum relative value = 3.577232e+00 %.
# NOTE: Maximum absolute value = 1.935686e+02 hr.
# **********************************************************************
print(" > Making PNGs ...")
# Create image ...
absDiffImg = numpy.zeros((nLat, nLon, 3), dtype = numpy.uint8)
for iLat in range(nLat):
for iLon in range(nLon):
if absDiff[iLat, iLon] < 1.0e4:
color = round(
min(
255.0,
255.0 * absDiff[iLat, iLon].astype(numpy.float64) / 200.0,
)
)
absDiffImg[iLat, iLon, :] = cts["rainbow"][color][:]
else:
absDiffImg[iLat, iLon, :] = 255
absDiffImg = PIL.Image.fromarray(absDiffImg)
# Create image ...
relDiffImg = numpy.zeros((nLat, nLon, 3), dtype = numpy.uint8)
for iLat in range(nLat):
for iLon in range(nLon):
if relDiff[iLat, iLon] < 1.0e9:
color = round(
min(
255.0,
255.0 * relDiff[iLat, iLon].astype(numpy.float64) / 4.0,
)
)
relDiffImg[iLat, iLon, :] = cts["rainbow"][color][:]
else:
relDiffImg[iLat, iLon, :] = 255
relDiffImg = PIL.Image.fromarray(relDiffImg)
# Create drawing objects ...
absDiffDraw = PIL.ImageDraw.Draw(absDiffImg)
relDiffDraw = PIL.ImageDraw.Draw(relDiffImg)
# Loop over Shapefiles ...
for sfile in sfiles:
# Loop over records ...
for record in cartopy.io.shapereader.Reader(sfile).records():
# Loop over Polygons ...
for poly in pyguymer3.geo.extract_polys(record.geometry, onlyValid = False, repair = False):
# Initialize list ...
coords = [] # [px], [px]
# Loop over coordinates in exterior ring ...
for coord in poly.exterior.coords:
# Deduce location and append to list ...
x = max(0.0, min(float(nLon), (coord[0] + 180.0) / dLon)) # [px]
y = max(0.0, min(float(nLat), ( 90.0 - coord[1]) / dLat)) # [px]
coords.append((x, y)) # [px], [px]
# Draw exterior ring ...
absDiffDraw.line(coords, fill = (255, 255, 255), width = 1)
relDiffDraw.line(coords, fill = (255, 255, 255), width = 1)
# Save PNG ...
absDiffImg.save(f"../res={res}_cons={cons:.2e}_nAng={nAng:d}_prec={prec:.2e}_lon={startingLon:+011.6f}_lat={startingLat:+010.6f}_abs.png")
pyguymer3.image.optimize_image(f"../res={res}_cons={cons:.2e}_nAng={nAng:d}_prec={prec:.2e}_lon={startingLon:+011.6f}_lat={startingLat:+010.6f}_abs.png", strip = True)
# Save PNG ...
relDiffImg.save(f"../res={res}_cons={cons:.2e}_nAng={nAng:d}_prec={prec:.2e}_lon={startingLon:+011.6f}_lat={startingLat:+010.6f}_rel.png")
pyguymer3.image.optimize_image(f"../res={res}_cons={cons:.2e}_nAng={nAng:d}_prec={prec:.2e}_lon={startingLon:+011.6f}_lat={startingLat:+010.6f}_rel.png", strip = True)
|