source: src/common/gnuboat_common/spatial/tilegenerator.py@ 5e16955

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

First version of a working log processing task

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