source: src/common/gnuboat_common/spatial/tilegenerator.py@ 3db3d13

debian/bullseye
Last change on this file since 3db3d13 was 7be94aa, checked in by Joachim Langenbach <joachim.langenbach@…>, 7 years ago
  • Added yapf style config (src/python-style.yapf)
    • Updated all files to the yapf formatted version
  • Property mode set to 100644
File size: 23.6 KB
RevLine 
[9f5877d]1# -*- coding: utf-8 -*-
2'''
3 Copyright (C) 2020 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.
4
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17'''
18
19import mercantile
20from osgeo import ogr
21from osgeo import gdal
22from osgeo import gdalconst
23import tempfile
24import os
25import shutil
26import subprocess
27import math
[5e16955]28import copy
[d0a651d]29from pathlib import Path
30from PIL import Image
[5e16955]31
32try:
[7be94aa]33 from dataclasses import dataclass
34
35 #@dataclass
36 #class TileWidth:
37 #"""
38 #tile_size: The tile size in Pixel,
39 #longitude: The width of the Tile in decimal degrees
40 #latitude: The height of the Tile in decimal degrees
41 #"""
42 #tile_size: int
43 #longitude: float
44 #latitude: float
45
46 @dataclass
47 class ResultPath:
48 """
[5e16955]49 path: Absolute path of the created results
50 prefixes: Dict with meaningful prefixes in the path. e.g. {'tile_size': '512', 'density': '10_100'}
51 """
[7be94aa]52 path: str
53 prefixes: dict
54
[5e16955]55except ImportError:
[7be94aa]56 #class TileWidth:
57 #"""
58 #Workaround for @dataclass, until python 3.7 is available in main distros
59 #"""
60 #def __init__(self, tile_size, longitude, latitude):
61 #self.tile_size = tile_size
62 #self.longitude = longitude
63 #self.latitude = latitude
64
65 class ResultPath:
66 """
[5e16955]67 path: Absolute path of the created results
68 prefixes: Dict with meaningful prefixes in the path. e.g. {'tile_size': '512', 'density': '10_100'}
69 """
[7be94aa]70 def __init__(self, path, prefixes):
71 self.path = path
72 self.prefixes = prefixes
73
[5e16955]74
75class ZoomRange(dict):
[7be94aa]76 def __init__(self, minimum, maximum):
77 super(ZoomRange, self).__init__({
78 'minimum': minimum,
79 'maximum': maximum
80 })
81
82 def minimum(self):
83 return self['minimum']
84
85 def maximum(self):
86 return self['maximum']
87
88 def from_dict(dictionary):
89 return ZoomRange(dictionary['minimum'], dictionary['maximum'])
90
[5e16955]91
92class LngLatBbox(dict):
[7be94aa]93 def __init__(self, west, south, east, north):
94 super(LngLatBbox, self).__init__({
95 'west': west,
96 'south': south,
97 'east': east,
98 'north': north
99 })
100
101 def west(self):
102 return self['west']
103
104 def south(self):
105 return self['south']
106
107 def east(self):
108 return self['east']
109
110 def north(self):
111 return self['north']
112
113 def to_mercantile_bbox(self):
114 return mercantile.LngLatBbox(
115 self.west(), self.south(), self.east(), self.north()
116 )
117
118 def from_mercantile_bbox(mercantile_bbox):
119 return LngLatBbox(
120 mercantile_bbox.west, mercantile_bbox.south, mercantile_bbox.east,
121 mercantile_bbox.north
122 )
123
124 def from_dict(dictionary):
125 if dictionary is None:
126 return None
127 return LngLatBbox(
128 dictionary['west'], dictionary['south'], dictionary['east'],
129 dictionary['north']
130 )
131
[5e16955]132
133class RasterSlice(dict):
[7be94aa]134 """
[5e16955]135 lng_lat_box: LngLatBbox
136 zoom_range: ZoomRange
137 tile_size: The tile size in Pixel,
138 grid_width: The width of the resulting rastr
139 grid_height: The height of the resulting rastr
140
141 It's derived from dict to be json serialisable
142 """
[7be94aa]143 def __init__(
144 self, lng_lat_box, zoom_range, tile_size, grid_width, grid_height
145 ):
146 super(RasterSlice, self).__init__({
147 'lng_lat_box': lng_lat_box,
148 'zoom_range': zoom_range,
149 'tile_size': tile_size,
150 'grid_width': grid_width,
151 'grid_height': grid_height
152 })
153
154 def lng_lat_bbox(self):
155 return self['lng_lat_box']
156
157 def zoom_range(self):
158 return self['zoom_range']
159
160 def tile_size(self):
161 return self['tile_size']
162
163 def grid_width(self):
164 return self['grid_width']
165
166 def grid_height(self):
167 return self['grid_height']
168
169 def from_dict(dictionary):
170 if dictionary is None:
171 return None
172 return RasterSlice(
173 LngLatBbox.from_dict(dictionary['lng_lat_box']),
174 ZoomRange.from_dict(dictionary['zoom_range']),
175 dictionary['tile_size'], dictionary['grid_width'],
176 dictionary['grid_height']
177 )
178
[9f5877d]179
180class TileGenerator:
[7be94aa]181 """
[9f5877d]182 - tile_sizes = Array of tile sizes in pixel, which should be rendered
183 - zoom_range = Range of zooms, tiles are created for
184 - densities = Array with counts of data points per density_base, where tiles are created for
185 - density_base = Radios of circle as a datum plane for the densities values
186 - nodata_value = Value used for pixels without valid data
187 """
[7be94aa]188 def __init__(
189 self,
190 tile_sizes=[256, 512],
191 densities=[10, 100],
192 density_base=100,
193 nodata_value=-999.0,
194 debug=False
195 ):
196 self._tile_sizes = tile_sizes
197 self._densities = densities
198 self._density_base = density_base
199 self._nodata_value = nodata_value
200 self._debug = debug
[9f5877d]201
[7be94aa]202 # -999 is a workaround, as long gdal python api does not handle addAlpha
203 self._colors = {
204 -999: '255 255 255',
205 0: '0 0 139',
206 2: '30 144 255',
207 6: '173 216 230',
208 10: '240 248 255'
209 }
210
211 ogr.UseExceptions()
212
213 def fit_extent_to_tiles(self, lng_lat_box, zoom_range):
214 """
[5e16955]215 Enlarges the extent (given by lng_lat_box) to the borders of the tiles
216 lng_lat_box is of Type LngLatBbox
217 """
[7be94aa]218 tile_bounding = mercantile.bounding_tile(
219 lng_lat_box.west(), lng_lat_box.south(), lng_lat_box.east(),
220 lng_lat_box.north()
221 )
222 if tile_bounding.z > zoom_range.minimum():
223 return LngLatBbox.from_mercantile_bbox(
224 mercantile.bounds(
225 mercantile.parent(
226 tile_bounding, zoom=zoom_range.minimum()
227 )
228 )
229 )
230 else:
231 return LngLatBbox.from_mercantile_bbox(
232 mercantile.bounds(tile_bounding)
233 )
[5e16955]234
[7be94aa]235 def slices(
236 self,
237 input_file,
238 zoom_range,
239 tile_sizes=None,
240 raster_file_size_max=1024 * 1024 * 1024 * 8
241 ):
242 """
[5e16955]243 Slice the complete area of input_file into smaller pieces,
244 so that each created raster file is smaller than raster_file_size_max
245 and cut into pieces at the borders of tiles and not thorugh tiles.
246 It returns an array of latitude longitude boxes representaing the borders, per slice.
247 """
[7be94aa]248 if tile_sizes is None:
249 tile_sizes = self._tile_sizes
250
251 datasource = self._datasource_open(input_file)
252 source_layer = datasource.GetLayerByIndex(0)
253 west, east, south, north = source_layer.GetExtent()
254
255 raster_slices = []
256 for tile_size in tile_sizes:
257 # fitting to tile borders
258 lng_lat_box = self.fit_extent_to_tiles(
259 LngLatBbox(west, south, east, north), zoom_range
260 )
261 # The lng_lat_box is exactly on the border between tiles. Since there are rounding errors,
262 # we move the corner edges a very little bit (about a few mm) into the tile. This makes sure,
263 # that we only get those tiles returned, which are really in the lng_lat_box.
264 tiles_zoom_min = mercantile.tiles(
265 lng_lat_box.west() + 1 * 10**-7,
266 lng_lat_box.south() + 1 * 10**-7,
267 lng_lat_box.east() - 1 * 10**-7,
268 lng_lat_box.north() - 1 * 10**-7, zoom_range.minimum()
269 )
270
271 # calculating size of raster file for GDT_Float32 = 32bits
272 delta_zoom = math.floor(
273 math.log(raster_file_size_max / (tile_size**2 * 32)) /
274 math.log(4)
275 )
276 steps = math.floor(
277 (zoom_range.maximum() - zoom_range.minimum()) / delta_zoom
278 )
279 zoom_steps = []
280 step = zoom_range.minimum()
281 while step < zoom_range.maximum():
282 zoom_steps.append(step)
283 step += delta_zoom + 1
284 for tile in tiles_zoom_min:
285 raster_slices += self._slice_tile(
286 tile, zoom_steps, zoom_range.maximum(), tile_size,
287 source_layer
288 )
289 return raster_slices
290
291 def _slice_tile(
292 self,
293 parent_tile,
294 zoom_steps,
295 zoom_total_max,
296 tile_size,
297 source_layer,
298 tiles_with_geometry=True
299 ):
300 if len(zoom_steps) < 1:
301 raise ValueError('No zoomsteps given to slice tile generation')
302 zoom_min = zoom_steps[0]
303 if len(zoom_steps) < 2:
304 zoom_max = zoom_total_max
305 else:
306 zoom_max = zoom_steps[1] - 1
307
308 raster_slices = []
309 lng_lat_box = mercantile.bounds(parent_tile)
310 width = math.sqrt(4**(zoom_max - zoom_min)) * tile_size
311 if width != round(width):
312 raise ValueError('Found a slice, with incomplete tiles')
313 raster_slice = RasterSlice(
314 LngLatBbox.from_mercantile_bbox(lng_lat_box),
315 ZoomRange(zoom_min, zoom_max), tile_size, width, width
316 )
317 raster_slices.append(raster_slice)
318 if len(zoom_steps) > 1:
319 zoom_steps_new = copy.deepcopy(zoom_steps)
320 zoom_steps_new.pop(0)
321 zoom_min_new = zoom_steps_new[0]
322 for child in mercantile.children(parent_tile, zoom=zoom_min_new):
323 # test, if tile has geometry
324 lng_lat_box = mercantile.bounds(child)
325 source_layer.SetSpatialFilterRect(
326 lng_lat_box.west, lng_lat_box.south, lng_lat_box.east,
327 lng_lat_box.north
328 )
329 if source_layer.GetNextFeature() or not tiles_with_geometry:
330 raster_slices += self._slice_tile(
331 child,
332 zoom_steps_new,
333 zoom_total_max,
334 tile_size,
335 source_layer,
336 tiles_with_geometry=tiles_with_geometry
337 )
338 source_layer.SetSpatialFilter(None)
339 return raster_slices
340
341 def run(
342 self,
343 input_file,
344 output_directory,
345 tile_slice,
346 densities=None,
347 density_base=None,
348 nodata_value=None
349 ):
350 """
[9f5877d]351 Runs all nescessary steps to create the tiles.
352 All default parameters equal to none are replaced by the one of the object
353 input_file = vrt source file used as a base for all steps to creating the tiles
[5e16955]354 Returns an array of paths with the created tiles if successfull
[9f5877d]355 """
[7be94aa]356 if densities is None:
357 densities = self._densities
358 if density_base is None:
359 density_base = self._density_base
360 if nodata_value is None:
361 nodata_value = self._nodata_value
362
363 # get source boundaries (Envelope / Extent)
364 datasource = self._datasource_open(input_file)
365 source_layer = datasource.GetLayerByIndex(0)
366 source_x_min, source_x_max, source_y_min, source_y_max = source_layer.GetExtent(
367 )
368 source_layer_name = source_layer.GetName()
369
370 # define density information for gridding algorithm
371 lon_metre_max = 60 * 1852 * math.cos(
372 math.radians(min(source_y_min, source_y_max))
373 ) # metre / degree
374 lat_metre_max = 111694 # metre / degree
375 circle_radius = math.sqrt(density_base) / math.pi
376 radius_x = circle_radius / lon_metre_max
377 radius_y = circle_radius / lat_metre_max
378
379 tile_result_paths = []
380 for density_min in densities:
381 gridding_algorithm = 'average:radius1={}:radius2={}:angle=0.0:min_points={}:nodata={}'.format(
382 radius_x, radius_y, density_min, nodata_value
383 )
384 if self._debug:
385 print(
386 "Run for density {} and {} tile size:".format(
387 density_min, tile_slice.tile_size()
388 )
389 )
390 print(" Statistics:")
391 print(
392 " Found {} Points".format(
393 source_layer.GetFeatureCount()
394 )
395 )
396 print(
397 " Min density per squaredegree: {}".format(
398 density_min * density_base / lon_metre_max /
399 lat_metre_max
400 )
401 )
402 print(
403 " Min density per pixel: {}".format(
404 density_min * density_base /
405 (degree_per_pixel_lon * lon_metre_max) /
406 (degree_per_pixel_lat * lat_metre_max)
407 )
408 )
409 print(" gridding algorithm {}".format(gridding_algorithm))
410
411 # create the grid data
412 raster_file = self.raster_create(
413 input_file, source_layer_name, tile_slice, gridding_algorithm
414 )
415 # hillshade
416 hillshade_file = self.hillshade_create(raster_file)
417 # color relief
418 color_relief_file = self.color_relief_create(raster_file)
419 # slopeshade
420 slopeshade_file = os.path.join(
421 output_directory, 'water_depth_slopeshade.tif'
422 )
423 slopeshade_file = self.slopeshade_create(
424 raster_file, slopeshade_file
425 )
426 # merge color relief and hillshade
427 merged_file = os.path.join(
428 output_directory,
429 'water_depth_{}_{}.tif'.format(density_min, density_base)
430 )
431 self.merge_color_relief_hillshade(
432 color_relief_file, hillshade_file, merged_file
433 )
434 # create the tiles
435 title = 'GNUBoat {} datasets per {} squaremetre, Tilesize: {}'.format(
436 density_min, density_base, tile_slice.tile_size()
437 )
438 prefix_density = '{}_{}'.format(density_min, density_base)
439 tiles_output = os.path.join(
440 output_directory,
441 '{}/{}'.format(prefix_density, tile_slice.tile_size())
442 )
443 self.tiles_create(
444 merged_file,
445 title,
446 tile_slice.tile_size(),
447 tiles_output,
448 zoom_range=tile_slice.zoom_range()
449 )
450 tile_result_paths.append(
451 ResultPath(
452 tiles_output, {
453 'tile_size': str(tile_slice.tile_size()),
454 'density': prefix_density
455 }
456 )
457 )
458 return tile_result_paths
459
460 def raster_create(
461 self,
462 input_file,
463 layers,
464 tile_slice,
465 gridding_algorithm,
466 nodata_value=None,
467 output_file='/vsimem/water_depth.tif'
468 ):
469 """
[9f5877d]470 Rastering the data from source file into a tif.
471 The input should be a vrt source file.
472 The function returns the path to the generated tif file.
473 """
[7be94aa]474 if nodata_value is None:
475 nodata_value = self._nodata_value
476
477 grid_options = gdal.GridOptions(
478 outputType=gdal.GDT_Float32,
479 format="GTiff",
480 width=tile_slice.grid_width(),
481 height=tile_slice.grid_height(),
482 outputSRS="WGS84",
483 outputBounds=[
484 tile_slice.lng_lat_bbox().west(),
485 tile_slice.lng_lat_bbox().north(),
486 tile_slice.lng_lat_bbox().east(),
487 tile_slice.lng_lat_bbox().south()
488 ],
489 noData=nodata_value,
490 layers=layers,
491 spatFilter=(
492 tile_slice.lng_lat_bbox().west(),
493 tile_slice.lng_lat_bbox().south(),
494 tile_slice.lng_lat_bbox().east(),
495 tile_slice.lng_lat_bbox().north()
496 ),
497 algorithm=gridding_algorithm
498 )
499 gdal.Grid(output_file, input_file, options=grid_options)
500 return output_file
501
502 def hillshade_create(
503 self, input_file, output_file='/vsimem/water_depth_hillshade.tif'
504 ):
505 """
[9f5877d]506 Creates the hillshade from a raster tif file and returns the path to the resulting tif file
507 """
[7be94aa]508 gdal.DEMProcessing(
509 output_file,
510 input_file,
511 "hillshade",
512 options=gdal.DEMProcessingOptions(format="GTiff", zFactor=-1)
513 )
514 return output_file
[9f5877d]515
[7be94aa]516 def color_relief_create(
517 self,
518 input_file,
519 output_file='/vsimem/water_depth_color_relief.tif',
520 colors=None
521 ):
522 """
[9f5877d]523 Creates the color relief from a raster tif and returns the path to the resulting tif file
524 """
[7be94aa]525 if colors is None:
526 colors = self._colors
527
528 gdal_file_color_relief_config = tempfile.NamedTemporaryFile(
529 mode='w', suffix='txt'
530 )
531 for depth in colors:
532 gdal_file_color_relief_config.write(
533 "{} {}\n".format(depth, colors[depth])
534 )
535 gdal_file_color_relief_config.flush()
536 gdal.DEMProcessing(
537 output_file,
538 input_file,
539 "color-relief",
540 options=gdal.DEMProcessingOptions(
541 format="GTiff",
542 colorFilename=gdal_file_color_relief_config.name
543 ),
544 addAlpha=True
545 )
546 gdal_file_color_relief_config.close()
547 return output_file
548
549 def slopeshade_create(self, input_file, output_file):
550 gdal_file_slopeshade_tmp = "/vsimem/tmp_water_depth_slopeshade.tif"
551 gdal_file_slopeshade_config = tempfile.NamedTemporaryFile(
552 mode='w', suffix='txt'
553 )
554 gdal_file_slopeshade_config.write("0 255 255 255\n")
555 gdal_file_slopeshade_config.write("90 0 0 0\n")
556 gdal_file_slopeshade_config.write("270 0 0 0\n")
557 gdal_file_slopeshade_config.write("360 255 255 255\n")
558 gdal_file_slopeshade_config.flush()
559 gdal.DEMProcessing(
560 gdal_file_slopeshade_tmp,
561 input_file,
562 "slope",
563 options=gdal.DEMProcessingOptions(format="GTiff"),
564 slopeFormat='degree',
565 zeroForFlat=True,
566 addAlpha=True
567 )
568 gdal.DEMProcessing(
569 output_file,
570 gdal_file_slopeshade_tmp,
571 "color-relief",
572 options=gdal.DEMProcessingOptions(
573 format="GTiff", colorFilename=gdal_file_slopeshade_config.name
574 ),
575 addAlpha=True
576 )
577 gdal_file_slopeshade_config.close()
578 return output_file
579
580 def merge_color_relief_hillshade(
581 self, input_color_relief_file, input_hillshade_file, output_file
582 ):
583 # dstNodata is a workaround for not working addAlpha in color-relief
584 gdal.Warp(
585 output_file, [input_color_relief_file, input_hillshade_file],
586 options=gdal.WarpOptions(
587 format='GTiff', dstAlpha=False, dstNodata="255 255 255"
588 )
589 )
590 return output_file
591
592 def tiles_create(
593 self, input_file, title, tile_size, output_directory, zoom_range
594 ):
595 tile_zoom_option = '{}-{}'.format(
596 zoom_range.minimum(), zoom_range.maximum()
597 )
598 # using the patched (tilesize) gdal2tiles.py script here, until the upstream version mades it in the distros
599 subprocess.run([
600 'gdal2tiles-gnuboat.py', '-q', '-w', 'none',
601 '--tilesize={}'.format(tile_size), '-z', tile_zoom_option, '-t',
602 title, input_file, output_directory
603 ],
604 check=True,
605 stdout=subprocess.PIPE,
606 stderr=subprocess.PIPE)
607
608 def move_tiles_in_place(self, source_path, target_path, skip_empty=True):
609 """
[d0a651d]610 Moves the generated tiles from the source_path into the target_path.
611 It moves file per file, so that the tiles are going to be integrated into an existing folder.
612 If skip_emtpy = True only one empty tile is copied to the top level directory. All other empty
613 tiles are not moved into target_path.
614 """
[7be94aa]615 copied_empty_tile = False
616
617 src_path = Path(source_path)
618 trg_path = Path(target_path)
619 empty_tile = trg_path.joinpath('empty_tile.png')
620 for path in Path(source_path).rglob('*.png'):
621 # Substract source_path from path and make it relative to
622 # target_path
623 relative = path.relative_to(src_path)
624 relative_path = trg_path.joinpath(relative)
625 if self._tile_is_empty(path) and skip_empty:
626 if not copied_empty_tile:
627 if not empty_tile.parent.exists():
628 os.makedirs(empty_tile.parent)
629 shutil.copy(path, empty_tile)
630 copied_empty_tile = True
631 else:
632 if not relative_path.parent.exists():
633 os.makedirs(relative_path.parent)
634 shutil.copy(path, relative_path)
635
636 def _datasource_open(self, source_file):
637 datasource = ogr.Open(source_file)
638 if datasource is None:
639 raise FileNotFoundError(
640 'Could not open input file {}'.format(source_file)
641 )
642 if datasource.GetLayerCount() < 1:
643 raise ReferenceError('No layers in input file')
644 return datasource
645
646 def _tile_is_empty(self, tile_file_path):
647 is_empty = True
648 colors_tmp = set()
649 colors_tmp_transparent = set()
650
651 img = Image.open(tile_file_path)
652 # calculate histogram for blue channel
653 colors_img = img.getcolors(256)
654 if not colors_img:
655 return False
656 else:
657 for color in colors_img:
658 color_hex = ''.join(
659 '{:02X}'.format(value) for value in color[1]
660 )
661 if color[1][3] != 0:
662 return False
663 return True
664
665 #def contours_create():
666 # @todo Cut Tifs / warp
667 #contour_input = gdal.Open(gdal_file, gdalconst.GA_ReadOnly)
668 #contour_input_band = contour_input.GetRasterBand(1)
669 ##Generate layer to save Contourlines in
670 #contour_output = ogr.GetDriverByName("ESRI Shapefile").CreateDataSource(gdal_file_contours)
671 #proj = osr.SpatialReference()
672 #proj.SetWellKnownGeogCS(input_epsg)
673 #for depth in colors:
674 #contour_layer = contour_output.CreateLayer('contour_{}_{}_{}'.format(density_min, density_base, depth), srs = proj)
675 #field_definition = ogr.FieldDefn("ID", ogr.OFTInteger)
676 #contour_layer.CreateField(field_definition)
677 #field_definition = ogr.FieldDefn("elev", ogr.OFTReal)
678 #contour_layer.CreateField(field_definition)
679 ##Generate Contourlines
680 #gdal.ContourGenerate(contour_input_band, depth, 0, [], 0, 0, contour_layer, 0, 1)
681 #contour_output = None
682 #del contour_output
683 #print(" Created contour lines {}".format(gdal_file_contours))
684
685 #def crop():
686 # cropping the tifs
687 #gdal.Warp('/tmp/gnuboat/test.tif', gdal_file_color_relief, options = gdal.WarpOptions(format = 'GTiff', dstAlpha = True, srcNodata = "255 255 255", dstNodata = target_nodata_value, cutlineDSName = '/tmp/gnuboat/contours/contour-0.shp', cutlineLayer="contour-0", cropToCutline=True))
Note: See TracBrowser for help on using the repository browser.