Changeset 5e16955 for src/common/gnuboat_common/spatial
- Timestamp:
- Mar 30, 2020, 8:31:10 PM (7 years ago)
- Branches:
- debian/bullseye, master
- Children:
- b72d9c4
- Parents:
- 9f5877d
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
src/common/gnuboat_common/spatial/tilegenerator.py
r9f5877d r5e16955 26 26 import subprocess 27 27 import math 28 import copy 29 30 try: 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 53 except 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 72 class 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 85 class 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 110 class 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']) 28 140 29 141 class TileGenerator: … … 35 147 - nodata_value = Value used for pixels without valid data 36 148 """ 37 def __init__(self, tile_sizes = [256, 512], zoom_range = [14, 19],densities = [10, 100], density_base = 100, nodata_value = -999.0, debug=False):149 def __init__(self, tile_sizes = [256, 512], densities = [10, 100], density_base = 100, nodata_value = -999.0, debug=False): 38 150 self._tile_sizes = tile_sizes 39 self._zoom_range = zoom_range40 151 self._densities = densities 41 152 self._density_base = density_base … … 54 165 ogr.UseExceptions() 55 166 56 def run(self, input_file, output_directory, tile_sizes = None, zoom_range = None, densities = None, density_base = None, nodata_value = None): 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): 57 239 """ 58 240 Runs all nescessary steps to create the tiles. 59 241 All default parameters equal to none are replaced by the one of the object 60 242 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 243 Returns an array of paths with the created tiles if successfull 244 """ 66 245 if densities is None: 67 246 densities = self._densities … … 72 251 73 252 # 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') 253 datasource = self._datasource_open(input_file) 79 254 source_layer = datasource.GetLayerByIndex(0) 80 255 source_x_min, source_x_max, source_y_min, source_y_max = source_layer.GetExtent() … … 88 263 radius_y = circle_radius / lat_metre_max 89 264 265 tile_result_paths = [] 90 266 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) 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)) 93 275 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'): 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'): 128 297 """ 129 298 Rastering the data from source file into a tif. … … 137 306 outputType = gdal.GDT_Float32, 138 307 format = "GTiff", 139 width = width,140 height = height,308 width = tile_slice.grid_width(), 309 height = tile_slice.grid_height(), 141 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()], 142 312 noData = nodata_value, 143 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()), 144 315 algorithm = gridding_algorithm 145 316 ) … … 187 358 return output_file 188 359 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)) 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()) 194 362 # using the patched (tilesize) gdal2tiles.py script here, until the upstream version mades it in the distros 195 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) 196 364 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) 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 205 394 206 395 #def contours_create():
Note:
See TracChangeset
for help on using the changeset viewer.
