source: src/common/gnuboat_common/spatial/tilegenerator.py@ 9f5877d

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

Moved all functions needed to generate raster data and tiles into new class TileGenerator in gnuboat_common

  • Property mode set to 100644
File size: 10.9 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
28
29class TileGenerator:
30 """
31 - tile_sizes = Array of tile sizes in pixel, which should be rendered
32 - zoom_range = Range of zooms, tiles are created for
33 - densities = Array with counts of data points per density_base, where tiles are created for
34 - density_base = Radios of circle as a datum plane for the densities values
35 - nodata_value = Value used for pixels without valid data
36 """
37 def __init__(self, tile_sizes = [256, 512], zoom_range = [14, 19], densities = [10, 100], density_base = 100, nodata_value = -999.0, debug=False):
38 self._tile_sizes = tile_sizes
39 self._zoom_range = zoom_range
40 self._densities = densities
41 self._density_base = density_base
42 self._nodata_value = nodata_value
43 self._debug = debug
44
45 # -999 is a workaround, as long gdal python api does not handle addAlpha
46 self._colors = {
47 -999: '255 255 255',
48 0: '0 0 139',
49 2: '30 144 255',
50 6: '173 216 230',
51 10: '240 248 255'
52 }
53
54 ogr.UseExceptions()
55
56 def run(self, input_file, output_directory, tile_sizes = None, zoom_range = None, densities = None, density_base = None, nodata_value = None):
57 """
58 Runs all nescessary steps to create the tiles.
59 All default parameters equal to none are replaced by the one of the object
60 input_file = vrt source file used as a base for all steps to creating the tiles
61 """
62 if tile_sizes is None:
63 tile_sizes = self._tile_sizes
64 if zoom_range is None:
65 zoom_range = self._zoom_range
66 if densities is None:
67 densities = self._densities
68 if density_base is None:
69 density_base = self._density_base
70 if nodata_value is None:
71 nodata_value = self._nodata_value
72
73 # get source boundaries (Envelope / Extent)
74 datasource = ogr.Open(input_file)
75 if datasource is None:
76 raise FileNotFoundError('Could not open input file {}'.format(input_file))
77 if datasource.GetLayerCount() < 1:
78 raise ReferenceError('No layers in input file')
79 source_layer = datasource.GetLayerByIndex(0)
80 source_x_min, source_x_max, source_y_min, source_y_max = source_layer.GetExtent()
81 source_layer_name = source_layer.GetName()
82
83 # define density information for gridding algorithm
84 lon_metre_max = 60 * 1852 * math.cos(math.radians(min(source_y_min, source_y_max))) # metre / degree
85 lat_metre_max = 111694 # metre / degree
86 circle_radius = math.sqrt(density_base) / math.pi
87 radius_x = circle_radius / lon_metre_max
88 radius_y = circle_radius / lat_metre_max
89
90 for density_min in densities:
91 for tile_size in tile_sizes:
92 gridding_algorithm = 'average:radius1={}:radius2={}:angle=0.0:min_points={}:nodata={}'.format(radius_x, radius_y, density_min, nodata_value)
93
94 tile_resolution = self._tile_width(tile_size, zoom_range[1])
95 target_x_res = int(tile_resolution['tile_size'] / tile_resolution['longitude'] * (source_x_max - source_x_min))
96 target_y_res = int(tile_resolution['tile_size'] / tile_resolution['latitude'] * (source_y_max - source_y_min))
97
98 if self._debug:
99 print("Run for density {} and {} tile size:".format(density_min, tile_size))
100 print(" Statistics:")
101 print(" Found {} Points".format(source_layer.GetFeatureCount()))
102 degree_per_pixel_lon = tile_resolution['longitude'] / tile_resolution['tile_size']
103 degree_per_pixel_lat = tile_resolution['latitude'] / tile_resolution['tile_size']
104 print(" degree / pixel x and y: {}, {}".format(degree_per_pixel_lon, degree_per_pixel_lat))
105 print(" metre / pixel x and y: {}, {}".format(degree_per_pixel_lon * lon_metre_max, degree_per_pixel_lat * lat_metre_max))
106 print(" Min density per squaredegree: {}".format(density_min * density_base / lon_metre_max / lat_metre_max))
107 print(" Min density per pixel: {}".format(density_min * density_base / (degree_per_pixel_lon * lon_metre_max) / (degree_per_pixel_lat * lat_metre_max)))
108 print(" gridding algorithm {}".format(gridding_algorithm))
109
110 # create the grid data
111 raster_file = self.raster_create(input_file, source_layer_name, target_x_res, target_y_res, gridding_algorithm)
112 # hillshade
113 hillshade_file = self.hillshade_create(raster_file)
114 # color relief
115 color_relief_file = self.color_relief_create(raster_file)
116 # slopeshade
117 slopeshade_file = os.path.join(output_directory, 'water_depth_slopeshade.tif')
118 slopeshade_file = self.slopeshade_create(raster_file, slopeshade_file)
119 # merge color relief and hillshade
120 merged_file = os.path.join(output_directory, 'water_depth_{}_{}.tif'.format(density_min, density_base))
121 self.merge_color_relief_hillshade(color_relief_file, hillshade_file, merged_file)
122 # create the tiles
123 title = 'GNUBoat {} datasets per {} squaremetre, Tilesize: {}'.format(density_min, density_base, tile_size)
124 tiles_output = os.path.join(output_directory, '{}_{}/{}'.format(density_min, density_base, tile_size))
125 self.tiles_create(merged_file, title, tile_size, tiles_output)
126
127 def raster_create(self, input_file, layers, width, height, gridding_algorithm, nodata_value=None, output_file='/vsimem/water_depth.tif'):
128 """
129 Rastering the data from source file into a tif.
130 The input should be a vrt source file.
131 The function returns the path to the generated tif file.
132 """
133 if nodata_value is None:
134 nodata_value = self._nodata_value
135
136 grid_options = gdal.GridOptions(
137 outputType = gdal.GDT_Float32,
138 format = "GTiff",
139 width = width,
140 height = height,
141 outputSRS = "WGS84",
142 noData = nodata_value,
143 layers = layers,
144 algorithm = gridding_algorithm
145 )
146 gdal.Grid(output_file, input_file, options = grid_options)
147 return output_file
148
149 def hillshade_create(self, input_file, output_file='/vsimem/water_depth_hillshade.tif'):
150 """
151 Creates the hillshade from a raster tif file and returns the path to the resulting tif file
152 """
153 gdal.DEMProcessing(output_file, input_file, "hillshade", options = gdal.DEMProcessingOptions(format = "GTiff", zFactor = -1))
154 return output_file
155
156 def color_relief_create(self, input_file, output_file='/vsimem/water_depth_color_relief.tif', colors = None):
157 """
158 Creates the color relief from a raster tif and returns the path to the resulting tif file
159 """
160 if colors is None:
161 colors = self._colors
162
163 gdal_file_color_relief_config = tempfile.NamedTemporaryFile(mode='w', suffix='txt')
164 for depth in colors:
165 gdal_file_color_relief_config.write("{} {}\n".format(depth, colors[depth]))
166 gdal_file_color_relief_config.flush()
167 gdal.DEMProcessing(output_file, input_file, "color-relief", options = gdal.DEMProcessingOptions(format = "GTiff", colorFilename = gdal_file_color_relief_config.name), addAlpha = True)
168 gdal_file_color_relief_config.close()
169 return output_file
170
171 def slopeshade_create(self, input_file, output_file):
172 gdal_file_slopeshade_tmp = "/vsimem/tmp_water_depth_slopeshade.tif"
173 gdal_file_slopeshade_config = tempfile.NamedTemporaryFile(mode='w', suffix='txt')
174 gdal_file_slopeshade_config.write("0 255 255 255\n")
175 gdal_file_slopeshade_config.write("90 0 0 0\n")
176 gdal_file_slopeshade_config.write("270 0 0 0\n")
177 gdal_file_slopeshade_config.write("360 255 255 255\n")
178 gdal_file_slopeshade_config.flush()
179 gdal.DEMProcessing(gdal_file_slopeshade_tmp, input_file, "slope", options = gdal.DEMProcessingOptions(format = "GTiff"), slopeFormat = 'degree', zeroForFlat = True, addAlpha = True)
180 gdal.DEMProcessing(output_file, gdal_file_slopeshade_tmp, "color-relief", options = gdal.DEMProcessingOptions(format = "GTiff", colorFilename = gdal_file_slopeshade_config.name), addAlpha = True)
181 gdal_file_slopeshade_config.close()
182 return output_file
183
184 def merge_color_relief_hillshade(self, input_color_relief_file, input_hillshade_file, output_file):
185 # dstNodata is a workaround for not working addAlpha in color-relief
186 gdal.Warp(output_file, [input_color_relief_file, input_hillshade_file], options = gdal.WarpOptions(format = 'GTiff', dstAlpha = False, dstNodata = "255 255 255"))
187 return output_file
188
189 def tiles_create(self, input_file, title, tile_size, output_directory, zoom_range = None):
190 if zoom_range is None:
191 zoom_range = self._zoom_range
192
193 tile_zoom_option = "-".join(map(str, zoom_range))
194 # using the patched (tilesize) gdal2tiles.py script here, until the upstream version mades it in the distros
195 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)
196
197 def _tile_width(self, tile_size, zoomlevel):
198 lng_lat_box = mercantile.bounds(mercantile.Tile(1, 1, zoomlevel))
199 tiles = math.sqrt(self._tile_number(zoomlevel))
200 #print ({"tile_size": tile_size, "longitude": 360.0/tiles, "latitude": 180.0/tiles})
201 return {"tile_size": tile_size, "longitude": abs(lng_lat_box.west - lng_lat_box.east), "latitude": abs(lng_lat_box.north - lng_lat_box.south)}
202
203 def _tile_number(self, zoomlevel):
204 return 2**(zoomlevel*2)
205
206 #def contours_create():
207 # @todo Cut Tifs / warp
208 #contour_input = gdal.Open(gdal_file, gdalconst.GA_ReadOnly)
209 #contour_input_band = contour_input.GetRasterBand(1)
210 ##Generate layer to save Contourlines in
211 #contour_output = ogr.GetDriverByName("ESRI Shapefile").CreateDataSource(gdal_file_contours)
212 #proj = osr.SpatialReference()
213 #proj.SetWellKnownGeogCS(input_epsg)
214 #for depth in colors:
215 #contour_layer = contour_output.CreateLayer('contour_{}_{}_{}'.format(density_min, density_base, depth), srs = proj)
216 #field_definition = ogr.FieldDefn("ID", ogr.OFTInteger)
217 #contour_layer.CreateField(field_definition)
218 #field_definition = ogr.FieldDefn("elev", ogr.OFTReal)
219 #contour_layer.CreateField(field_definition)
220 ##Generate Contourlines
221 #gdal.ContourGenerate(contour_input_band, depth, 0, [], 0, 0, contour_layer, 0, 1)
222 #contour_output = None
223 #del contour_output
224 #print(" Created contour lines {}".format(gdal_file_contours))
225
226 #def crop():
227 # cropping the tifs
228 #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.