source: src/common/gnuboat_common/spatial/tilegenerator.py@ cdd6542

debian/bullseye
Last change on this file since cdd6542 was 37f674d, checked in by Joachim Langenbach <joachim.langenbach@…>, 7 years ago

Changed SliceJob, TileGenerator.RasterSlice, LangLatBBox so that values could be None when calling from_dict

  • Property mode set to 100644
File size: 18.7 KB
Line 
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
28import copy
29from pathlib import Path
30from PIL import Image
31
32try:
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 """
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 """
52 path: str
53 prefixes: dict
54
55except ImportError:
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 """
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 """
70 def __init__(self, path, prefixes):
71 self.path = path
72 self.prefixes = prefixes
73
74class ZoomRange(dict):
75 def __init__(self, minimum, maximum):
76 super(ZoomRange, self).__init__({'minimum': minimum, 'maximum': maximum})
77
78 def minimum(self):
79 return self['minimum']
80
81 def maximum(self):
82 return self['maximum']
83
84 def from_dict(dictionary):
85 return ZoomRange(dictionary['minimum'], dictionary['maximum'])
86
87class LngLatBbox(dict):
88 def __init__(self, west, south, east, north):
89 super(LngLatBbox, self).__init__({'west': west, 'south': south, 'east': east, 'north': north})
90
91 def west(self):
92 return self['west']
93
94 def south(self):
95 return self['south']
96
97 def east(self):
98 return self['east']
99
100 def north(self):
101 return self['north']
102
103 def to_mercantile_bbox(self):
104 return mercantile.LngLatBbox(self.west(), self.south(), self.east(), self.north())
105
106 def from_mercantile_bbox(mercantile_bbox):
107 return LngLatBbox(mercantile_bbox.west, mercantile_bbox.south, mercantile_bbox.east, mercantile_bbox.north)
108
109 def from_dict(dictionary):
110 if dictionary is None:
111 return None
112 return LngLatBbox(dictionary['west'], dictionary['south'], dictionary['east'], dictionary['north'])
113
114class RasterSlice(dict):
115 """
116 lng_lat_box: LngLatBbox
117 zoom_range: ZoomRange
118 tile_size: The tile size in Pixel,
119 grid_width: The width of the resulting rastr
120 grid_height: The height of the resulting rastr
121
122 It's derived from dict to be json serialisable
123 """
124 def __init__(self, lng_lat_box, zoom_range, tile_size, grid_width, grid_height):
125 super(RasterSlice, self).__init__({'lng_lat_box': lng_lat_box, 'zoom_range': zoom_range, 'tile_size': tile_size, 'grid_width': grid_width, 'grid_height': grid_height})
126
127 def lng_lat_bbox(self):
128 return self['lng_lat_box']
129
130 def zoom_range(self):
131 return self['zoom_range']
132
133 def tile_size(self):
134 return self['tile_size']
135
136 def grid_width(self):
137 return self['grid_width']
138
139 def grid_height(self):
140 return self['grid_height']
141
142 def from_dict(dictionary):
143 if dictionary is None:
144 return None
145 return RasterSlice(LngLatBbox.from_dict(dictionary['lng_lat_box']), ZoomRange.from_dict(dictionary['zoom_range']), dictionary['tile_size'], dictionary['grid_width'], dictionary['grid_height'])
146
147class TileGenerator:
148 """
149 - tile_sizes = Array of tile sizes in pixel, which should be rendered
150 - zoom_range = Range of zooms, tiles are created for
151 - densities = Array with counts of data points per density_base, where tiles are created for
152 - density_base = Radios of circle as a datum plane for the densities values
153 - nodata_value = Value used for pixels without valid data
154 """
155 def __init__(self, tile_sizes = [256, 512], densities = [10, 100], density_base = 100, nodata_value = -999.0, debug=False):
156 self._tile_sizes = tile_sizes
157 self._densities = densities
158 self._density_base = density_base
159 self._nodata_value = nodata_value
160 self._debug = debug
161
162 # -999 is a workaround, as long gdal python api does not handle addAlpha
163 self._colors = {
164 -999: '255 255 255',
165 0: '0 0 139',
166 2: '30 144 255',
167 6: '173 216 230',
168 10: '240 248 255'
169 }
170
171 ogr.UseExceptions()
172
173 def fit_extent_to_tiles(self, lng_lat_box, zoom_range):
174 """
175 Enlarges the extent (given by lng_lat_box) to the borders of the tiles
176 lng_lat_box is of Type LngLatBbox
177 """
178 tile_bounding = mercantile.bounding_tile(lng_lat_box.west(), lng_lat_box.south(), lng_lat_box.east(), lng_lat_box.north())
179 if tile_bounding.z > zoom_range.minimum():
180 return LngLatBbox.from_mercantile_bbox(mercantile.bounds(mercantile.parent(tile_bounding, zoom=zoom_range.minimum())))
181 else:
182 return LngLatBbox.from_mercantile_bbox(mercantile.bounds(tile_bounding))
183
184 def slices(self, input_file, zoom_range, tile_sizes = None, raster_file_size_max = 1024 * 1024 * 1024 * 8):
185 """
186 Slice the complete area of input_file into smaller pieces,
187 so that each created raster file is smaller than raster_file_size_max
188 and cut into pieces at the borders of tiles and not thorugh tiles.
189 It returns an array of latitude longitude boxes representaing the borders, per slice.
190 """
191 if tile_sizes is None:
192 tile_sizes = self._tile_sizes
193
194 datasource = self._datasource_open(input_file)
195 source_layer = datasource.GetLayerByIndex(0)
196 west, east, south, north = source_layer.GetExtent()
197
198 raster_slices = []
199 for tile_size in tile_sizes:
200 # fitting to tile borders
201 lng_lat_box = self.fit_extent_to_tiles(LngLatBbox(west, south, east, north), zoom_range)
202 # The lng_lat_box is exactly on the border between tiles. Since there are rounding errors,
203 # we move the corner edges a very little bit (about a few mm) into the tile. This makes sure,
204 # that we only get those tiles returned, which are really in the lng_lat_box.
205 tiles_zoom_min = mercantile.tiles(lng_lat_box.west() + 1*10**-7, lng_lat_box.south() + 1*10**-7, lng_lat_box.east() - 1*10**-7, lng_lat_box.north() - 1*10**-7, zoom_range.minimum())
206
207 # calculating size of raster file for GDT_Float32 = 32bits
208 delta_zoom = math.floor(math.log(raster_file_size_max / (tile_size**2 * 32)) / math.log(4))
209 steps = math.floor((zoom_range.maximum() - zoom_range.minimum()) / delta_zoom)
210 zoom_steps = []
211 step = zoom_range.minimum()
212 while step < zoom_range.maximum():
213 zoom_steps.append(step)
214 step += delta_zoom + 1
215 for tile in tiles_zoom_min:
216 raster_slices += self._slice_tile(tile, zoom_steps, zoom_range.maximum(), tile_size, source_layer)
217 return raster_slices
218
219 def _slice_tile(self, parent_tile, zoom_steps, zoom_total_max, tile_size, source_layer, tiles_with_geometry = True):
220 if len(zoom_steps) < 1:
221 raise ValueError('No zoomsteps given to slice tile generation')
222 zoom_min = zoom_steps[0]
223 if len(zoom_steps) < 2:
224 zoom_max = zoom_total_max
225 else:
226 zoom_max = zoom_steps[1] - 1
227
228 raster_slices = []
229 lng_lat_box = mercantile.bounds(parent_tile)
230 width = math.sqrt(4**(zoom_max - zoom_min)) * tile_size
231 if width != round(width):
232 raise ValueError('Found a slice, with incomplete tiles')
233 raster_slice = RasterSlice(LngLatBbox.from_mercantile_bbox(lng_lat_box), ZoomRange(zoom_min, zoom_max), tile_size, width, width)
234 raster_slices.append(raster_slice)
235 if len(zoom_steps) > 1:
236 zoom_steps_new = copy.deepcopy(zoom_steps)
237 zoom_steps_new.pop(0)
238 zoom_min_new = zoom_steps_new[0]
239 for child in mercantile.children(parent_tile, zoom=zoom_min_new):
240 # test, if tile has geometry
241 lng_lat_box = mercantile.bounds(child)
242 source_layer.SetSpatialFilterRect(lng_lat_box.west, lng_lat_box.south, lng_lat_box.east, lng_lat_box.north)
243 if source_layer.GetNextFeature() or not tiles_with_geometry:
244 raster_slices += self._slice_tile(child, zoom_steps_new, zoom_total_max, tile_size, source_layer, tiles_with_geometry = tiles_with_geometry)
245 source_layer.SetSpatialFilter(None)
246 return raster_slices
247
248
249 def run(self, input_file, output_directory, tile_slice, densities = None, density_base = None, nodata_value = None):
250 """
251 Runs all nescessary steps to create the tiles.
252 All default parameters equal to none are replaced by the one of the object
253 input_file = vrt source file used as a base for all steps to creating the tiles
254 Returns an array of paths with the created tiles if successfull
255 """
256 if densities is None:
257 densities = self._densities
258 if density_base is None:
259 density_base = self._density_base
260 if nodata_value is None:
261 nodata_value = self._nodata_value
262
263 # get source boundaries (Envelope / Extent)
264 datasource = self._datasource_open(input_file)
265 source_layer = datasource.GetLayerByIndex(0)
266 source_x_min, source_x_max, source_y_min, source_y_max = source_layer.GetExtent()
267 source_layer_name = source_layer.GetName()
268
269 # define density information for gridding algorithm
270 lon_metre_max = 60 * 1852 * math.cos(math.radians(min(source_y_min, source_y_max))) # metre / degree
271 lat_metre_max = 111694 # metre / degree
272 circle_radius = math.sqrt(density_base) / math.pi
273 radius_x = circle_radius / lon_metre_max
274 radius_y = circle_radius / lat_metre_max
275
276 tile_result_paths = []
277 for density_min in densities:
278 gridding_algorithm = 'average:radius1={}:radius2={}:angle=0.0:min_points={}:nodata={}'.format(radius_x, radius_y, density_min, nodata_value)
279 if self._debug:
280 print("Run for density {} and {} tile size:".format(density_min, tile_slice.tile_size()))
281 print(" Statistics:")
282 print(" Found {} Points".format(source_layer.GetFeatureCount()))
283 print(" Min density per squaredegree: {}".format(density_min * density_base / lon_metre_max / lat_metre_max))
284 print(" Min density per pixel: {}".format(density_min * density_base / (degree_per_pixel_lon * lon_metre_max) / (degree_per_pixel_lat * lat_metre_max)))
285 print(" gridding algorithm {}".format(gridding_algorithm))
286
287 # create the grid data
288 raster_file = self.raster_create(input_file, source_layer_name, tile_slice, gridding_algorithm)
289 # hillshade
290 hillshade_file = self.hillshade_create(raster_file)
291 # color relief
292 color_relief_file = self.color_relief_create(raster_file)
293 # slopeshade
294 slopeshade_file = os.path.join(output_directory, 'water_depth_slopeshade.tif')
295 slopeshade_file = self.slopeshade_create(raster_file, slopeshade_file)
296 # merge color relief and hillshade
297 merged_file = os.path.join(output_directory, 'water_depth_{}_{}.tif'.format(density_min, density_base))
298 self.merge_color_relief_hillshade(color_relief_file, hillshade_file, merged_file)
299 # create the tiles
300 title = 'GNUBoat {} datasets per {} squaremetre, Tilesize: {}'.format(density_min, density_base, tile_slice.tile_size())
301 prefix_density = '{}_{}'.format(density_min, density_base)
302 tiles_output = os.path.join(output_directory, '{}/{}'.format(prefix_density, tile_slice.tile_size()))
303 self.tiles_create(merged_file, title, tile_slice.tile_size(), tiles_output, zoom_range = tile_slice.zoom_range())
304 tile_result_paths.append(ResultPath(tiles_output, {'tile_size': str(tile_slice.tile_size()), 'density': prefix_density}))
305 return tile_result_paths
306
307 def raster_create(self, input_file, layers, tile_slice, gridding_algorithm, nodata_value=None, output_file='/vsimem/water_depth.tif'):
308 """
309 Rastering the data from source file into a tif.
310 The input should be a vrt source file.
311 The function returns the path to the generated tif file.
312 """
313 if nodata_value is None:
314 nodata_value = self._nodata_value
315
316 grid_options = gdal.GridOptions(
317 outputType = gdal.GDT_Float32,
318 format = "GTiff",
319 width = tile_slice.grid_width(),
320 height = tile_slice.grid_height(),
321 outputSRS = "WGS84",
322 outputBounds = [tile_slice.lng_lat_bbox().west(), tile_slice.lng_lat_bbox().north(), tile_slice.lng_lat_bbox().east(), tile_slice.lng_lat_bbox().south()],
323 noData = nodata_value,
324 layers = layers,
325 spatFilter = (tile_slice.lng_lat_bbox().west(), tile_slice.lng_lat_bbox().south(), tile_slice.lng_lat_bbox().east(), tile_slice.lng_lat_bbox().north()),
326 algorithm = gridding_algorithm
327 )
328 gdal.Grid(output_file, input_file, options = grid_options)
329 return output_file
330
331 def hillshade_create(self, input_file, output_file='/vsimem/water_depth_hillshade.tif'):
332 """
333 Creates the hillshade from a raster tif file and returns the path to the resulting tif file
334 """
335 gdal.DEMProcessing(output_file, input_file, "hillshade", options = gdal.DEMProcessingOptions(format = "GTiff", zFactor = -1))
336 return output_file
337
338 def color_relief_create(self, input_file, output_file='/vsimem/water_depth_color_relief.tif', colors = None):
339 """
340 Creates the color relief from a raster tif and returns the path to the resulting tif file
341 """
342 if colors is None:
343 colors = self._colors
344
345 gdal_file_color_relief_config = tempfile.NamedTemporaryFile(mode='w', suffix='txt')
346 for depth in colors:
347 gdal_file_color_relief_config.write("{} {}\n".format(depth, colors[depth]))
348 gdal_file_color_relief_config.flush()
349 gdal.DEMProcessing(output_file, input_file, "color-relief", options = gdal.DEMProcessingOptions(format = "GTiff", colorFilename = gdal_file_color_relief_config.name), addAlpha = True)
350 gdal_file_color_relief_config.close()
351 return output_file
352
353 def slopeshade_create(self, input_file, output_file):
354 gdal_file_slopeshade_tmp = "/vsimem/tmp_water_depth_slopeshade.tif"
355 gdal_file_slopeshade_config = tempfile.NamedTemporaryFile(mode='w', suffix='txt')
356 gdal_file_slopeshade_config.write("0 255 255 255\n")
357 gdal_file_slopeshade_config.write("90 0 0 0\n")
358 gdal_file_slopeshade_config.write("270 0 0 0\n")
359 gdal_file_slopeshade_config.write("360 255 255 255\n")
360 gdal_file_slopeshade_config.flush()
361 gdal.DEMProcessing(gdal_file_slopeshade_tmp, input_file, "slope", options = gdal.DEMProcessingOptions(format = "GTiff"), slopeFormat = 'degree', zeroForFlat = True, addAlpha = True)
362 gdal.DEMProcessing(output_file, gdal_file_slopeshade_tmp, "color-relief", options = gdal.DEMProcessingOptions(format = "GTiff", colorFilename = gdal_file_slopeshade_config.name), addAlpha = True)
363 gdal_file_slopeshade_config.close()
364 return output_file
365
366 def merge_color_relief_hillshade(self, input_color_relief_file, input_hillshade_file, output_file):
367 # dstNodata is a workaround for not working addAlpha in color-relief
368 gdal.Warp(output_file, [input_color_relief_file, input_hillshade_file], options = gdal.WarpOptions(format = 'GTiff', dstAlpha = False, dstNodata = "255 255 255"))
369 return output_file
370
371 def tiles_create(self, input_file, title, tile_size, output_directory, zoom_range):
372 tile_zoom_option = '{}-{}'.format(zoom_range.minimum(), zoom_range.maximum())
373 # using the patched (tilesize) gdal2tiles.py script here, until the upstream version mades it in the distros
374 subprocess.run(['gdal2tiles-gnuboat.py', '-q', '-w', 'none', '--tilesize={}'.format(tile_size), '-z', tile_zoom_option, '-t', title, input_file, output_directory], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
375
376 def move_tiles_in_place(self, source_path, target_path, skip_empty = True):
377 """
378 Moves the generated tiles from the source_path into the target_path.
379 It moves file per file, so that the tiles are going to be integrated into an existing folder.
380 If skip_emtpy = True only one empty tile is copied to the top level directory. All other empty
381 tiles are not moved into target_path.
382 """
383 copied_empty_tile = False
384
385 src_path = Path(source_path)
386 trg_path = Path(target_path)
387 empty_tile = trg_path.joinpath('empty_tile.png')
388 for path in Path(source_path).rglob('*.png'):
389 # Substract source_path from path and make it relative to
390 # target_path
391 relative = path.relative_to(src_path)
392 relative_path = trg_path.joinpath(relative)
393 if self._tile_is_empty(path) and skip_empty:
394 if not copied_empty_tile:
395 if not empty_tile.parent.exists():
396 os.makedirs(empty_tile.parent)
397 shutil.copy(path, empty_tile)
398 copied_empty_tile = True
399 else:
400 if not relative_path.parent.exists():
401 os.makedirs(relative_path.parent)
402 shutil.copy(path, relative_path)
403
404 def _datasource_open(self, source_file):
405 datasource = ogr.Open(source_file)
406 if datasource is None:
407 raise FileNotFoundError('Could not open input file {}'.format(source_file))
408 if datasource.GetLayerCount() < 1:
409 raise ReferenceError('No layers in input file')
410 return datasource
411
412 def _tile_is_empty(self, tile_file_path):
413 is_empty = True
414 colors_tmp = set()
415 colors_tmp_transparent = set()
416
417 img = Image.open(tile_file_path)
418 # calculate histogram for blue channel
419 colors_img = img.getcolors(256)
420 if not colors_img:
421 return False
422 else:
423 for color in colors_img:
424 color_hex = ''.join('{:02X}'.format(value) for value in color[1])
425 if color[1][3] != 0:
426 return False
427 return True
428
429 #def contours_create():
430 # @todo Cut Tifs / warp
431 #contour_input = gdal.Open(gdal_file, gdalconst.GA_ReadOnly)
432 #contour_input_band = contour_input.GetRasterBand(1)
433 ##Generate layer to save Contourlines in
434 #contour_output = ogr.GetDriverByName("ESRI Shapefile").CreateDataSource(gdal_file_contours)
435 #proj = osr.SpatialReference()
436 #proj.SetWellKnownGeogCS(input_epsg)
437 #for depth in colors:
438 #contour_layer = contour_output.CreateLayer('contour_{}_{}_{}'.format(density_min, density_base, depth), srs = proj)
439 #field_definition = ogr.FieldDefn("ID", ogr.OFTInteger)
440 #contour_layer.CreateField(field_definition)
441 #field_definition = ogr.FieldDefn("elev", ogr.OFTReal)
442 #contour_layer.CreateField(field_definition)
443 ##Generate Contourlines
444 #gdal.ContourGenerate(contour_input_band, depth, 0, [], 0, 0, contour_layer, 0, 1)
445 #contour_output = None
446 #del contour_output
447 #print(" Created contour lines {}".format(gdal_file_contours))
448
449 #def crop():
450 # cropping the tifs
451 #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.