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

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