Debian Codegraph @

texmf-dist/tex/latex/mercatormap/mercatorpy.def

raw
1 \begin{filecontents}[force,noheader,nowarn]{maptiles.texpy}
2 """
3 The LaTeX package mercatormap - version 1.3.0 (2026/02/19)
4 maptiles.texpy: Python script for map tile download
5
6 -------------------------------------------------------------------------------------------
7 Copyright (c) 2020-2026 by Prof. Dr. Dr. Thomas F. Sturm <thomas dot sturm at unibw dot de>
8 -------------------------------------------------------------------------------------------
9
10 This work may be distributed and/or modified under the
11 conditions of the LaTeX Project Public License, either version 1.3
12 of this license or (at your option) any later version.
13 The latest version of this license is in
14 https://www.latex-project.org/lppl.txt
15 and version 1.3c or later is part of all distributions of LaTeX
16 version 2008-05-04 or later.
17
18 This work has the LPPL maintenance status `author-maintained'.
19
20 This work consists of all files listed in README
21 """
22
23 import argparse
24 import math
25 import os
26 import requests
27 from pathlib import Path
28 from PIL import Image
29
30
31 packageversion = '1.3.0 (2026/02/19)'
32
33
34 def gd(x):
35 return math.atan(math.sinh(x))
36
37
38 def arggd(x):
39 return math.asinh(math.tan(x))
40
41
42 def rad2planar(lon_rad, lat_rad):
43 x = 0.5*lon_rad/math.pi + 0.5
44 y = 0.5*arggd(lat_rad)/math.pi + 0.5
45 return x, y
46
47
48 def deg2planar(lon_deg, lat_deg):
49 return rad2planar(math.radians(lon_deg), math.radians(lat_deg))
50
51
52 def planar2rad(x, y):
53 lon_rad = math.pi*(2*x-1)
54 lat_rad = gd(math.pi*(2*y-1))
55 return lon_rad, lat_rad
56
57
58 def planar2deg(x, y):
59 (lon_rad, lat_rad) = planar2rad(x, y)
60 return math.degrees(lon_rad), math.degrees(lat_rad)
61
62
63 def download(session, url, filename, overwrite=False):
64 local_file = Path(filename)
65 if local_file.is_file() and not overwrite:
66 return
67 print(url+' -> '+filename)
68 r = session.get(url)
69 r.raise_for_status()
70 with open(filename, 'wb') as handler:
71 handler.write(r.content)
72 return
73
74
75 def makeparentdirs(afile):
76 directory = Path(os.path.abspath(afile)).parent
77 if not directory.is_dir():
78 os.makedirs(directory)
79
80
81 class MapDefinition(object):
82 def __init__(self, pargs, west, east, north, south, zoom, x_1, y_1, x_2, y_2,
83 width, height, west_offset, north_offset, south_offset):
84 self.west = west
85 self.east = east
86 self.north = north
87 self.south = south
88 self.zoom = zoom
89 self.x_1 = x_1
90 self.y_1 = y_1
91 self.x_2 = x_2
92 self.y_2 = y_2
93 self.width = width
94 self.height= height
95 self.west_offset = west_offset
96 self.north_offset = north_offset
97 self.south_offset = south_offset
98 self.n = 2 ** self.zoom
99 self.local_file_prefix = 'tiles/tile_'
100 self.attribution = pargs.attribution
101 self.attributionprint = pargs.attributionprint
102 self.pixel = pargs.pixel
103 self.pixel_width = round(self.width*self.pixel)
104 self.pixel_height = round(self.height*self.pixel)
105 self.tilesize = pargs.tilesize
106
107
108 @classmethod
109 def construct_from_boundaries_rad(cls, pargs, zoom, west_rad, east_rad, north_rad, south_rad):
110 if zoom<0:
111 zoom = 0
112 if west_rad>=east_rad:
113 east_rad += 2*math.pi*math.ceil(0.5*(west_rad-east_rad)/math.pi+1e-10)
114 max_lat = gd(math.pi)-1e-10
115 if north_rad<south_rad:
116 (north_rad, south_rad) = (south_rad, north_rad)
117 if north_rad > max_lat:
118 north_rad = max_lat
119 if south_rad < -max_lat:
120 south_rad = -max_lat
121 P = 2**(zoom-1)/math.pi
122 a1 = (west_rad+math.pi)*P
123 b1 = (math.pi-arggd(north_rad))*P
124 a2 = (east_rad+math.pi)*P
125 b2 = (math.pi-arggd(south_rad))*P
126 x1 = math.floor(a1)
127 y1 = math.floor(b1)
128 x2 = math.ceil(a2)-1
129 y2 = math.ceil(b2)-1
130 width = a2-a1
131 height = b2-b1
132 west_offset = a1-x1
133 north_offset = b1-y1
134 south_offset = y2-b2+1
135 return cls(pargs, west_rad, east_rad, north_rad, south_rad, zoom, x1, y1, x2, y2,
136 width, height, west_offset, north_offset, south_offset)
137
138
139 @classmethod
140 def construct_from_boundaries_deg(cls, pargs, zoom, west_deg, east_deg, north_deg, south_deg):
141 return cls.construct_from_boundaries_rad(pargs,
142 zoom, math.radians(west_deg), math.radians(east_deg),
143 math.radians(north_deg), math.radians(south_deg))
144
145
146 @classmethod
147 def construct_from_boundaries_args(cls, pargs):
148 return cls.construct_from_boundaries_rad(pargs,
149 pargs.zoom, math.radians(pargs.west), math.radians(pargs.east), math.radians(pargs.north), math.radians(pargs.south))
150
151
152 @classmethod
153 def construct_from_reference_rad(cls, pargs, zoom, width, height,
154 ref_lon_rad, ref_lat_rad, xalign, yalign):
155 if zoom<0:
156 zoom = 0
157 P = 2**(zoom-1)/math.pi
158 ac = (ref_lon_rad+math.pi)*P
159 bc = (math.pi-arggd(ref_lat_rad))*P
160 a1 = ac - (1+xalign)/2*width
161 a2 = a1 + width
162 b1 = bc - (1+yalign)/2*height
163 b2 = b1 + height
164 west_rad = a1/P - math.pi
165 north_rad = gd(math.pi-b1/P)
166 east_rad = a2/P - math.pi
167 south_rad = gd(math.pi-b2/P)
168 x1 = math.floor(a1)
169 y1 = math.floor(b1)
170 x2 = math.ceil(a2)-1
171 y2 = math.ceil(b2)-1
172 west_offset = a1-x1
173 north_offset = b1-y1
174 south_offset = y2-b2+1
175 return cls(pargs, west_rad, east_rad, north_rad, south_rad, zoom, x1, y1, x2, y2,
176 width, height, west_offset, north_offset, south_offset)
177
178
179 @classmethod
180 def construct_from_reference_deg(cls, pargs, zoom, width, height,
181 ref_lon_deg, ref_lat_deg, xalign, yalign):
182 return cls.construct_from_reference_rad(pargs, zoom, width, height,
183 math.radians(ref_lon_deg), math.radians(ref_lat_deg), xalign, yalign)
184
185
186 @classmethod
187 def construct_from_reference_args(cls, pargs):
188 return cls.construct_from_reference_rad(pargs, pargs.zoom, pargs.width, pargs.height,
189 math.radians(pargs.longitude), math.radians(pargs.latitude), pargs.xalign, pargs.yalign)
190
191
192 @classmethod
193 def construct_to_fit_region_rad(cls, pargs, width, height, reg_west_rad, reg_east_rad,
194 reg_north_rad, reg_south_rad, xalign, yalign):
195 if reg_west_rad>=reg_east_rad:
196 reg_east_rad += 2*math.pi*math.ceil(0.5*(reg_west_rad-reg_east_rad)/math.pi+1e-10)
197 max_lat = gd(math.pi)-1e-10
198 if reg_north_rad<reg_south_rad:
199 (reg_north_rad, reg_south_rad) = (reg_south_rad, reg_north_rad)
200 if reg_north_rad > max_lat:
201 reg_north_rad = max_lat
202 if reg_south_rad < -max_lat:
203 reg_south_rad = -max_lat
204 zoom = max( 0, 1 + math.floor( math.log2( math.pi *
205 min( width/(reg_east_rad-reg_west_rad), height/(arggd(reg_north_rad)-arggd(reg_south_rad)))
206 )))
207 P = 2**(zoom-1)/math.pi
208
209 if xalign<0:
210 a1 = (reg_west_rad+math.pi)*P
211 a2 = a1 + width
212 elif xalign>0:
213 a2 = (reg_east_rad+math.pi)*P
214 a1 = a2 - width
215 else:
216 a1 = ((reg_west_rad+reg_east_rad)/2+math.pi)*P - width/2
217 a2 = a1 + width
218
219 if yalign<0:
220 b1 = (math.pi-arggd(reg_north_rad))*P
221 b2 = b1 + height
222 elif yalign>0:
223 b2 = (math.pi-arggd(reg_south_rad))*P
224 b1 = b2 - height
225 else:
226 b1 = (math.pi-(arggd(reg_north_rad)+arggd(reg_south_rad))/2)*P - height/2
227 b2 = b1 + height
228 west_rad = a1/P - math.pi
229 north_rad = gd(math.pi-b1/P)
230 east_rad = a2/P - math.pi
231 south_rad = gd(math.pi-b2/P)
232 x1 = math.floor(a1)
233 y1 = math.floor(b1)
234 x2 = math.ceil(a2)-1
235 y2 = math.ceil(b2)-1
236 west_offset = a1-x1
237 north_offset = b1-y1
238 south_offset = y2-b2+1
239 return cls(pargs, west_rad, east_rad, north_rad, south_rad, zoom, x1, y1, x2, y2,
240 width, height, west_offset, north_offset, south_offset)
241
242
243 @classmethod
244 def construct_to_fit_region_deg(cls, pargs, width, height,
245 reg_west_deg, reg_east_deg, reg_north_deg, reg_south_deg,
246 xalign, yalign):
247 return cls.construct_to_fit_region_rad(pargs, width, height,
248 math.radians(reg_west_deg), math.radians(reg_east_deg),
249 math.radians(reg_north_deg), math.radians(reg_south_deg),
250 xalign, yalign)
251
252
253 @classmethod
254 def construct_to_fit_region_args(cls, pargs):
255 return cls.construct_to_fit_region_rad(pargs, pargs.width, pargs.height,
256 math.radians(pargs.west), math.radians(pargs.east),
257 math.radians(pargs.north), math.radians(pargs.south),
258 pargs.xalign, pargs.yalign)
259
260
261 def get_tile_quantity(self):
262 return (self.x_2-self.x_1+1)*(self.y_2-self.y_1+1)
263
264
265 def get_pixel_quantity(self):
266 return self.pixel_width*self.pixel_height
267
268
269 def download_tiles(self, url_format, local_file_prefix):
270 self.local_file_prefix = local_file_prefix
271 makeparentdirs(local_file_prefix)
272 with requests.Session() as s:
273 s.headers.update(dict(referer = 'mercatormap/'+packageversion))
274 try:
275 for xx in range(self.x_1, self.x_2+1):
276 x = xx % self.n
277 for y in range(self.y_1, self.y_2+1):
278 if (y>=0) and (y<self.n):
279 url = url_format.format(x=x, y=y, z=self.zoom)
280 filename = local_file_prefix + '_{z}_{x}_{y}.png'.format(x=x, y=y, z=self.zoom)
281 download(s,url,filename)
282 except requests.exceptions.RequestException as err:
283 print('Download error:', err)
284 return False
285 return True
286
287
288 def merge_map(self, map_definition, local_file_prefix):
289 makeparentdirs(map_definition)
290 new_im = Image.new('RGB', (self.pixel_width, self.pixel_height), 'white')
291 xoff = -round(self.west_offset*self.pixel)
292 for xx in range(self.x_1, self.x_2+1):
293 x = xx % self.n
294 yoff = -round(self.north_offset*self.pixel)
295 for y in range(self.y_1, self.y_2+1):
296 if (y>=0) and (y<self.n):
297 filename = local_file_prefix + '_{z}_{x}_{y}.png'.format(x=x, y=y, z=self.zoom)
298 new_im.paste(Image.open(filename), (xoff,yoff))
299 yoff+=self.pixel
300 xoff+=self.pixel
301 new_im.save(map_definition+'.png', optimize=True)
302 return True
303
304
305 def download_wms_map(self, url_format, map_definition):
306 makeparentdirs(map_definition)
307 # bbox in tiles for given zoom
308 xmin = self.x_1+self.west_offset
309 xmax = xmin+self.width
310 ymin = self.y_1+self.north_offset
311 ymax = ymin+self.height
312
313 # global scale bbox
314 f = math.pi*6378137
315 xmin = (2*xmin/self.n-1)*f
316 xmax = (2*xmax/self.n-1)*f
317 (ymin, ymax) = (ymax, ymin) # switch ymin/ymax
318 ymin = (1-2*ymin/self.n)*f
319 ymax = (1-2*ymax/self.n)*f
320
321 url = url_format.format(xmin=xmin, ymin=ymin, xmax=xmax, ymax=ymax,
322 width=self.pixel_width, height=self.pixel_height)
323 filename = map_definition+'.png'
324 with requests.Session() as s:
325 s.headers.update(dict(referer = 'mercatormap/'+packageversion))
326 try:
327 download(s,url,filename,True)
328 except requests.exceptions.RequestException as err:
329 print('Download error:', err)
330 return False
331 return True
332
333
334 def save_map(self, map_definition, tiles=False, merge=False, wms=False):
335 makeparentdirs(map_definition)
336 with open(map_definition+'.def', "w", encoding="utf-8") as desc:
337 desc.write(f'% generated by mercatormap maptiles {packageversion}\n')
338 desc.write('\\mrcdefinemap{\n')
339 desc.write(f' west={math.degrees(self.west)},\n')
340 desc.write(f' east={math.degrees(self.east)},\n')
341 desc.write(f' north={math.degrees(self.north)},\n')
342 desc.write(f' south={math.degrees(self.south)},\n')
343 desc.write(f' zoom={self.zoom},\n')
344 desc.write(f' xmin={self.x_1},\n')
345 desc.write(f' ymin={self.y_1},\n')
346 desc.write(f' xmax={self.x_2},\n')
347 desc.write(f' ymax={self.y_2},\n')
348 desc.write(f' pixelwidth={self.pixel_width},\n')
349 desc.write(f' pixelheight={self.pixel_height},\n')
350 desc.write(f' westoffset={self.west_offset},\n')
351 desc.write(f' northoffset={self.north_offset},\n')
352 desc.write(f' southoffset={self.south_offset},\n')
353 desc.write(f' basename={self.local_file_prefix},\n')
354 if self.attribution is not None:
355 desc.write(' attribution={'+self.attribution+'},\n')
356 if self.attributionprint is not None:
357 desc.write(' attribution print={'+self.attributionprint+'},\n')
358 if self.tilesize is not None:
359 desc.write(f' tile size={self.tilesize},\n')
360 if wms:
361 desc.write(f' resource=wmsmap,\n')
362 elif merge:
363 desc.write(f' resource=mergedmap,\n')
364 elif tiles:
365 desc.write(f' resource=tiles,\n')
366 else:
367 desc.write(f' resource=none,\n')
368 desc.write('}\n')
369 return
370
371
372 def print_description(self):
373 print('------ map description (class) ------')
374 print(f'west = {math.degrees(self.west)}')
375 print(f'east = {math.degrees(self.east)}')
376 print(f'north = {math.degrees(self.north)}')
377 print(f'south = {math.degrees(self.south)}')
378 print(f'zoom = {self.zoom}')
379 print(f'X_1 = {self.x_1}')
380 print(f'Y_1 = {self.y_1}')
381 print(f'X_2 = {self.x_2}')
382 print(f'Y_2 = {self.y_2}')
383 print(f'width = {self.width}')
384 print(f'height = {self.height}')
385 print(f'd_west = {self.west_offset}')
386 print(f'd_north = {self.north_offset}')
387 print(f'd_south = {self.south_offset}')
388 return
389
390
391 def map_tile_info(Z, X, Y):
392 N = 2.0 ** Z
393 lon_min = math.pi*(2*X-N)/N
394 lon_max = math.pi*(2*X+2-N)/N
395 lat_min = gd(math.pi*(N-2*Y-2)/N)
396 lat_max = gd(math.pi*(N-2*Y)/N)
397 r = 6371000
398 height = r*(lat_max-lat_min)
399 rdel_lon = r*(lon_max-lon_min)
400 width_n = rdel_lon*math.cos(lat_max)
401 width_s = rdel_lon*math.cos(lat_min)
402 area = r*rdel_lon*(math.sin(lat_max)-math.sin(lat_min))
403 print(f'(Z,X,Y) = ({Z},{X},{Y})')
404 print(f'west = {math.degrees(lon_min)}')
405 print(f'east = {math.degrees(lon_max)}')
406 print(f'south = {math.degrees(lat_min)}')
407 print(f'north = {math.degrees(lat_max)}')
408 print(f'height = {height/1000}')
409 print(f'width(N)= {width_n/1000}')
410 print(f'width(S)= {width_s/1000}')
411 print(f'area = {area/1000000}')
412 return
413
414
415 if __name__ == '__main__':
416 parser = argparse.ArgumentParser(description='Compute a full map description and download map tiles')
417
418 parser.add_argument('type', type=str, help='type of map computation',
419 choices=['boundaries', 'reference', 'areafit'])
420
421 parser.add_argument('-z', '--zoom', type=int, default=9,
422 help='zoom level (boundaries/reference)')
423 parser.add_argument('-w', '--west', type=float, default=11,
424 help='longitude west (boundaries/areafit)')
425 parser.add_argument('-e', '--east', type=float, default=13,
426 help='longitude east (boundaries/areafit)')
427 parser.add_argument('-n', '--north', type=float, default=48,
428 help='latitude north (boundaries/areafit)')
429 parser.add_argument('-s', '--south', type=float, default=50,
430 help='latitude south (boundaries/areafit)')
431 parser.add_argument('-lon', '--longitude', type=float, default=12,
432 help='longitude (reference)')
433 parser.add_argument('-lat', '--latitude', type=float, default=49,
434 help='latitude (reference)')
435 parser.add_argument('-mw', '--width', type=float, default=4,
436 help='map width as multiplicity of map tiles (reference/areafit)')
437 parser.add_argument('-mh', '--height', type=float, default=4,
438 help='map height as multiplicity of map tiles (reference/areafit)')
439 parser.add_argument('-a', '--align', type=str, default='center',
440 help='alignment of reference or area (reference/areafit)',
441 choices=['northwest', 'north', 'northeast',
442 'west', 'center', 'east',
443 'southwest', 'south', 'southeast'] )
444 parser.add_argument('-d', '--definition', type=str, default='mapdefinition',
445 help='name of the produced map definition for LaTeX')
446 parser.add_argument('-t', '--target', type=str, default='tiles',
447 help='target to create tiles or a merged map',
448 choices=['none', 'tiles', 'mergedmap', 'wmsmap'] )
449 parser.add_argument('-u', '--url', type=str, default=None,
450 help='url format with placeholder {z}{x}{y} for downloading tiles')
451 parser.add_argument('-at', '--attribution', type=str, default=None,
452 help='attribution text of the tile producer')
453 parser.add_argument('-atp', '--attributionprint', type=str, default=None,
454 help='attribution text of the tile producer')
455 parser.add_argument('-f', '--fileprefix', type=str, default='tiles/unknown',
456 help='prefix for local tile files, e.g. "tiles/map" for "tiles/map_10_10_10.png"')
457 parser.add_argument('-c', '--confirm', action="store_true",
458 help='confirm bulk download for map tiles')
459 parser.add_argument('-p', '--pixel', type=int, default=256,
460 help='pixel width/height of a tile')
461 parser.add_argument('-ts', '--tilesize', type=str, default=None,
462 help='TeX tile size')
463
464 args = parser.parse_args()
465
466 print('')
467 print('** This is maptiles.py version', packageversion,
468 'for generating', args.definition)
469
470 switcher = {
471 'northwest': (-1,-1),
472 'north': ( 0,-1),
473 'northeast': ( 1,-1),
474 'west': (-1, 0),
475 'center': ( 0, 0),
476 'east': ( 1, 0),
477 'southwest': (-1, 1),
478 'south': ( 0, 1),
479 'southeast': ( 1, 1)
480 }
481 (args.xalign, args.yalign) = switcher.get(args.align)
482
483 switcher = {
484 'boundaries': MapDefinition.construct_from_boundaries_args,
485 'reference': MapDefinition.construct_from_reference_args,
486 'areafit': MapDefinition.construct_to_fit_region_args
487 }
488 mapdef = switcher.get(args.type)(args)
489
490 switcher = {
491 'none': 0,
492 'tiles': 1,
493 'mergedmap': 2,
494 'wmsmap': 3
495 }
496 target = switcher.get(args.target)
497
498 tiles_success = False
499 merge_success = False
500 wms_success = False
501
502 if target>0:
503 if args.url is not None:
504 if target<3:
505 if mapdef.get_tile_quantity()>400:
506 if args.confirm:
507 tiles_success = mapdef.download_tiles(args.url, args.fileprefix)
508 else:
509 print(f'Too many tiles ({mapdef.get_tile_quantity()}). Add confirm option to proceed anyway.')
510 else:
511 tiles_success = mapdef.download_tiles(args.url, args.fileprefix)
512 if tiles_success:
513 print('** Download of tiles successful for', args.definition)
514 if target>1:
515 merge_success = mapdef.merge_map(args.definition, args.fileprefix)
516 if merge_success:
517 print('** Merging tiles successful for', args.definition)
518 else:
519 print('** WARNING: Merging tiles failed for', args.definition)
520 else:
521 print('** WARNING: Map tiles download failed for', args.definition)
522 else:
523 if mapdef.get_pixel_quantity()>100000000:
524 if args.confirm:
525 wms_success = mapdef.download_wms_map(args.url, args.definition)
526 else:
527 print(f'Too many pixels ({mapdef.get_pixel_quantity()}). Add confirm option to proceed anyway.')
528 else:
529 wms_success = mapdef.download_wms_map(args.url, args.definition)
530 else:
531 print('No url for download given')
532
533 mapdef.save_map(args.definition, tiles_success, merge_success, wms_success)
534 \end{filecontents}