Changeset 7be94aa for src/common
- Timestamp:
- Apr 11, 2020, 4:46:15 PM (7 years ago)
- Branches:
- debian/bullseye, master
- Children:
- 3db3d13
- Parents:
- da2be70
- Location:
- src/common
- Files:
-
- 7 edited
-
bin/gnuboat-log-analyser (modified) (1 diff)
-
bin/gnuboat-log-converter (modified) (9 diffs)
-
bin/gnuboat-log-uploader (modified) (1 diff)
-
gnuboat_common/datahandler/logdataset.py (modified) (2 diffs)
-
gnuboat_common/datahandler/loghandler.py (modified) (2 diffs)
-
gnuboat_common/spatial/tilegenerator.py (modified) (6 diffs)
-
tests/test_tilegenerator.py (modified) (1 diff)
Legend:
- Unmodified
- Added
- Removed
-
src/common/bin/gnuboat-log-analyser
rda2be70 r7be94aa 40 40 # -999 is a workaround, as long gdal python api does not handle addAlpha 41 41 colors = { 42 -999: "255 255 255",43 0: "0 0 139",44 2: "30 144 255",45 6: "173 216 230",46 10: "240 248 255"42 -999: "255 255 255", 43 0: "0 0 139", 44 2: "30 144 255", 45 6: "173 216 230", 46 10: "240 248 255" 47 47 } 48 48 input_epsg = 'EPSG:4326' 49 49 target_nodata_value = -999.0 50 50 target_zoomlevel = 19 51 density_min = 10 # number of points per density_base squaremetres needed to set a value different from nodata 52 density_base = 100 # squaremetre used as base for density_min 51 density_min = 10 # number of points per density_base squaremetres needed to set a value different from nodata 52 density_base = 100 # squaremetre used as base for density_min 53 53 54 54 55 class CsvCallback: 55 def __init__(self, output_file): 56 self._output_file = output_file 57 self._stage = None 58 self._resultsets = 0 59 60 def count(self): 61 return self._resultsets 62 63 def stage_set(self, stage): 64 self._stage = stage 65 66 def callback(self, dataset): 67 if self._stage is None: 68 print("No stage set! Skipping dataset...") 69 return 70 # only add points with a water depth set 71 if dataset.water_depth() is None: 72 return 73 water_depth = dataset.water_depth() - self._stage 74 self._output_file.writerow({"lon": dataset.longitude(), "lat": dataset.latitude(), "water_depth": water_depth}) 75 self._resultsets += 1 56 def __init__(self, output_file): 57 self._output_file = output_file 58 self._stage = None 59 self._resultsets = 0 60 61 def count(self): 62 return self._resultsets 63 64 def stage_set(self, stage): 65 self._stage = stage 66 67 def callback(self, dataset): 68 if self._stage is None: 69 print("No stage set! Skipping dataset...") 70 return 71 # only add points with a water depth set 72 if dataset.water_depth() is None: 73 return 74 water_depth = dataset.water_depth() - self._stage 75 self._output_file.writerow({ 76 "lon": dataset.longitude(), 77 "lat": dataset.latitude(), 78 "water_depth": water_depth 79 }) 80 self._resultsets += 1 81 76 82 77 83 def tile_width(zoomlevel): 78 tile_size = 256 79 tiles = math.sqrt(tile_number(zoomlevel)) 80 return {"tile_size": tile_size, "longitude": 360.0/tiles, "latitude": 180.0/tiles} 84 tile_size = 256 85 tiles = math.sqrt(tile_number(zoomlevel)) 86 return { 87 "tile_size": tile_size, 88 "longitude": 360.0 / tiles, 89 "latitude": 180.0 / tiles 90 } 91 81 92 82 93 def tile_number(zoomlevel): 83 return 2**(zoomlevel*2) 94 return 2**(zoomlevel * 2) 95 84 96 85 97 def main(argv): 86 global color, input_epsg, target_nodata_value, target_zoomlevel, density_min, density_base 87 88 input_file_path = None 89 output_directory = None 90 statistics = False 91 tile_sizes = [256] 92 skip_empty = True 93 94 gdal.UseExceptions() 95 96 parser = argparse.ArgumentParser(description='Generates the digital terrain model from gnuboat logfiles') 97 parser.add_argument('input_file', metavar='input_file_path', type=str, 98 help='JSON file with logfiles and correction data to be processed') 99 parser.add_argument('output_directory', metavar='output_directory', type=str, 100 help='Write the Digital Terrain Model into this directory (output)') 101 parser.add_argument('-v', '--verbose', dest='statistics', action='store_true', 102 help='Print some statistics of the input and result datasets') 103 parser.add_argument('-p', '--points-min', dest='points_min', type=int, default=density_min, 104 help='Minimum points per {} squaremetre is needed to create a valid depth information'.format(density_base)) 105 parser.add_argument('-z', '--zoomlevels', dest='zoom_range', nargs=2, default=[10, 19], type=int, 106 help='Creates tiles for the specified range of zoomlevels') 107 parser.add_argument('--high-res', dest='high_res', action='store_true', 108 help='Creates tiles with 512 pixel per tile additionally to the 256 pixel per tile tiles') 109 parser.add_argument('-m', '--raster_file_max', dest='raster_file_size_max', default=1024, type=int, 110 help='Maximum size of temporary raster Tifs for tile generation in MB') 111 parser.add_argument('-k', '--keep-empty', dest='skip_empty', action='store_false', 112 help='Do not skip empty tiles (=move only one empty tile into place), when moving tiles into target directory') 113 arguments = parser.parse_args(argv) 114 115 if arguments.input_file is None: 116 print('ERROR: No input file specified') 117 sys.exit(2) 118 elif not os.path.exists(arguments.input_file): 119 print('ERROR: Specified input file does not exists: {}'.format(arguments.input_file)) 120 sys.exit(3) 121 else: 122 input_file_path = arguments.input_file 123 124 if arguments.output_directory is None: 125 print('ERROR: No output file specified') 126 sys.exit(2) 127 else: 128 output_directory = arguments.output_directory 129 130 if arguments.statistics is not None: 131 statistics = arguments.statistics 132 133 if arguments.points_min is not None: 134 density_min = arguments.points_min 135 136 if arguments.zoom_range is not None: 137 zoom_range = arguments.zoom_range 138 139 if arguments.high_res is not None and arguments.high_res: 140 tile_sizes.append(512) 141 142 if arguments.raster_file_size_max is not None: 143 raster_file_size_max = arguments.raster_file_size_max 144 145 if arguments.skip_empty is not None and not arguments.skip_empty: 146 skip_empty = arguments.skip_empty 147 148 # create temporary directory 149 temp_directory = tempfile.mkdtemp(prefix='gnuboat-log-analyser') 150 151 with open(input_file_path, 'r') as input_file: 152 logfiles = json.load(input_file) 153 154 source_data_layer = "tmp_corrected_joined_points" 155 corrected_joined_point_cloud_file_path = os.path.join(temp_directory, "{}.csv".format(source_data_layer)) 156 try: 157 output_file = open(corrected_joined_point_cloud_file_path, 'w') 158 except IOError as error: 159 print('ERROR: Could not open the output file for the corrected, joined point cloud: {}'.format(error)) 160 sys.exit(4) 161 output_file_csv = None 162 fields = ['lon', 'lat', 'water_depth'] 163 output_file_csv = csv.DictWriter(output_file, delimiter=',', quotechar='"', 164 fieldnames=fields) 165 output_file_csv.writeheader() 166 csv_callback = CsvCallback(output_file_csv) 167 log_handler = loghandler.LogHandler() 168 169 print("Correcting and combining {} log files".format(len(logfiles))) 170 for logfile in logfiles: 171 gaugeHeight = logfile["gaugeHeight"] 172 referenceWaterLevelGaugeHeight = logfile["referenceWaterLevelGaugeHeight"] 173 log_file_path = logfile["file"] 174 175 # building the log file path 176 if not os.path.isabs(log_file_path): 177 log_file_path = "{}/{}".format(os.path.dirname(input_file_path), log_file_path) 178 # check stage 179 try: 180 gaugeHeight = float(gaugeHeight) 181 except ValueError: 182 print("gaugeHeight is not convertible into float for file {}. Skipping the file".format(log_file_path)) 183 continue 184 try: 185 referenceWaterLevelGaugeHeight = float(referenceWaterLevelGaugeHeight) 186 except ValueError: 187 print("referenceWaterLevelGaugeHeight is not convertible into float for file {}. Skipping the file".format(log_file_path)) 188 continue 189 # parse, correct and append log file 190 difference = referenceWaterLevelGaugeHeight - gaugeHeight 191 csv_callback.stage_set(difference) 192 result = log_handler.gnuboat_read_file(log_file_path, csv_callback.callback) 193 if result.messages(): 194 print('\n'.join(result.errors())) 195 if not result.success(): 196 sys.exit(5) 197 198 print(" {} correct and joined with difference {:.3f}m".format(log_file_path, difference)) 199 output_file.close() 200 print (' Processed {} points'.format(csv_callback.count())) 201 202 # create ogr file info 203 source_xml_file = os.path.join(temp_directory, '{}.vrt'.format(source_data_layer)) 204 try: 205 output_file = open(source_xml_file, 'wb') 206 except IOError as error: 207 print('ERROR: Could not open the output file for the ogr data source description: {}'.format(error)) 208 sys.exit(4) 209 xml_data_source = ET.Element("OGRVRTDataSource") 210 xml_layer = ET.SubElement(xml_data_source, "OGRVRTLayer", {"name": source_data_layer}) 211 xml_source = ET.SubElement(xml_layer, "SrcDataSource", {'relativeToVRT': "1"}) 212 xml_source.text = corrected_joined_point_cloud_file_path 213 xml_geometry_type = ET.SubElement(xml_layer, "GeometryType") 214 xml_geometry_type.text = "wkbPoint" 215 xml_layer_system = ET.SubElement(xml_layer, "LayerSRS") 216 xml_layer_system.text = input_epsg 217 xml_geometry_field = ET.SubElement(xml_layer, "GeometryField", {"encoding": "PointFromColumns", "x": "lon", "y": "lat", "z": "water_depth"}) 218 xml_tree = ET.ElementTree(xml_data_source) 219 xml_tree.write(output_file, encoding="UTF-8", xml_declaration=False) 220 output_file.close() 221 222 # create csvt file 223 try: 224 output_file_csvt = open(os.path.join(temp_directory, '{}.csvt'.format(source_data_layer)), 'w') 225 except IOError as error: 226 print('ERROR: Could not open the output file for the ogr data source description: {}'.format(error)) 227 sys.exit(6) 228 output_file_csvt.write('"Real","Real","Real"') 229 output_file_csvt.close() 230 231 # preparing output_directory 232 if os.path.exists(output_directory): 233 for root, dirs, files in os.walk(output_directory): 234 for f in files: 235 os.unlink(os.path.join(root, f)) 236 for d in dirs: 237 shutil.rmtree(os.path.join(root, d)) 238 else: 239 os.makedirs(output_directory) 240 241 # get source boundaries (Envelope / Extent) 242 datasource = ogr.Open(source_xml_file) 243 if datasource is None: 244 raise FileNotFoundError('Could not open input file {}'.format(source_xml_file)) 245 if datasource.GetLayerCount() < 1: 246 raise ReferenceError('No layers in input file') 247 source_layer = datasource.GetLayerByIndex(0) 248 source_x_min, source_x_max, source_y_min, source_y_max = source_layer.GetExtent() 249 250 tilegen = tilegenerator.TileGenerator(tile_sizes = tile_sizes, densities = [density_min], density_base = density_base, debug=statistics) 251 slices = tilegen.slices(source_xml_file, tilegenerator.ZoomRange(zoom_range[0], zoom_range[1]), raster_file_size_max = raster_file_size_max * 1024 * 1024 * 8) 252 slices_count = len(slices) 253 print('Generated {} slices for rastering'.format(slices_count)) 254 255 t1_start = process_time() 256 print('Rastering slices and generating tiles') 257 with progressbar.ProgressBar(max_value=slices_count, redirect_stdout=True) as bar: 258 i = 1 259 for tile_slice in slices: 260 if statistics: 261 print(' Generating tiles for slice {} in {}'.format(i, temp_directory)) 262 result_paths = tilegen.run(source_xml_file, temp_directory, tile_slice) 263 for path in result_paths: 264 tilegen.move_tiles_in_place(path.path, os.path.join(output_directory, path.prefixes['density'], path.prefixes['tile_size']), skip_empty = skip_empty) 265 bar.update(i) 266 i += 1 267 t1_stop = process_time() 268 print(' Tooks {:.2f} hours'.format((t1_stop - t1_start) / 60 / 60)) 269 270 # delete temporary directory 271 shutil.rmtree(temp_directory) 272 273 print('Generated tiles in {}'.format(output_directory)) 274 275 sys.exit(0) 98 global color, input_epsg, target_nodata_value, target_zoomlevel, density_min, density_base 99 100 input_file_path = None 101 output_directory = None 102 statistics = False 103 tile_sizes = [256] 104 skip_empty = True 105 106 gdal.UseExceptions() 107 108 parser = argparse.ArgumentParser( 109 description='Generates the digital terrain model from gnuboat logfiles' 110 ) 111 parser.add_argument( 112 'input_file', 113 metavar='input_file_path', 114 type=str, 115 help='JSON file with logfiles and correction data to be processed' 116 ) 117 parser.add_argument( 118 'output_directory', 119 metavar='output_directory', 120 type=str, 121 help='Write the Digital Terrain Model into this directory (output)' 122 ) 123 parser.add_argument( 124 '-v', 125 '--verbose', 126 dest='statistics', 127 action='store_true', 128 help='Print some statistics of the input and result datasets' 129 ) 130 parser.add_argument( 131 '-p', 132 '--points-min', 133 dest='points_min', 134 type=int, 135 default=density_min, 136 help= 137 'Minimum points per {} squaremetre is needed to create a valid depth information' 138 .format(density_base) 139 ) 140 parser.add_argument( 141 '-z', 142 '--zoomlevels', 143 dest='zoom_range', 144 nargs=2, 145 default=[10, 19], 146 type=int, 147 help='Creates tiles for the specified range of zoomlevels' 148 ) 149 parser.add_argument( 150 '--high-res', 151 dest='high_res', 152 action='store_true', 153 help= 154 'Creates tiles with 512 pixel per tile additionally to the 256 pixel per tile tiles' 155 ) 156 parser.add_argument( 157 '-m', 158 '--raster_file_max', 159 dest='raster_file_size_max', 160 default=1024, 161 type=int, 162 help='Maximum size of temporary raster Tifs for tile generation in MB' 163 ) 164 parser.add_argument( 165 '-k', 166 '--keep-empty', 167 dest='skip_empty', 168 action='store_false', 169 help= 170 'Do not skip empty tiles (=move only one empty tile into place), when moving tiles into target directory' 171 ) 172 arguments = parser.parse_args(argv) 173 174 if arguments.input_file is None: 175 print('ERROR: No input file specified') 176 sys.exit(2) 177 elif not os.path.exists(arguments.input_file): 178 print( 179 'ERROR: Specified input file does not exists: {}'.format( 180 arguments.input_file 181 ) 182 ) 183 sys.exit(3) 184 else: 185 input_file_path = arguments.input_file 186 187 if arguments.output_directory is None: 188 print('ERROR: No output file specified') 189 sys.exit(2) 190 else: 191 output_directory = arguments.output_directory 192 193 if arguments.statistics is not None: 194 statistics = arguments.statistics 195 196 if arguments.points_min is not None: 197 density_min = arguments.points_min 198 199 if arguments.zoom_range is not None: 200 zoom_range = arguments.zoom_range 201 202 if arguments.high_res is not None and arguments.high_res: 203 tile_sizes.append(512) 204 205 if arguments.raster_file_size_max is not None: 206 raster_file_size_max = arguments.raster_file_size_max 207 208 if arguments.skip_empty is not None and not arguments.skip_empty: 209 skip_empty = arguments.skip_empty 210 211 # create temporary directory 212 temp_directory = tempfile.mkdtemp(prefix='gnuboat-log-analyser') 213 214 with open(input_file_path, 'r') as input_file: 215 logfiles = json.load(input_file) 216 217 source_data_layer = "tmp_corrected_joined_points" 218 corrected_joined_point_cloud_file_path = os.path.join( 219 temp_directory, "{}.csv".format(source_data_layer) 220 ) 221 try: 222 output_file = open(corrected_joined_point_cloud_file_path, 'w') 223 except IOError as error: 224 print( 225 'ERROR: Could not open the output file for the corrected, joined point cloud: {}' 226 .format(error) 227 ) 228 sys.exit(4) 229 output_file_csv = None 230 fields = ['lon', 'lat', 'water_depth'] 231 output_file_csv = csv.DictWriter( 232 output_file, delimiter=',', quotechar='"', fieldnames=fields 233 ) 234 output_file_csv.writeheader() 235 csv_callback = CsvCallback(output_file_csv) 236 log_handler = loghandler.LogHandler() 237 238 print("Correcting and combining {} log files".format(len(logfiles))) 239 for logfile in logfiles: 240 gaugeHeight = logfile["gaugeHeight"] 241 referenceWaterLevelGaugeHeight = logfile[ 242 "referenceWaterLevelGaugeHeight"] 243 log_file_path = logfile["file"] 244 245 # building the log file path 246 if not os.path.isabs(log_file_path): 247 log_file_path = "{}/{}".format( 248 os.path.dirname(input_file_path), log_file_path 249 ) 250 # check stage 251 try: 252 gaugeHeight = float(gaugeHeight) 253 except ValueError: 254 print( 255 "gaugeHeight is not convertible into float for file {}. Skipping the file" 256 .format(log_file_path) 257 ) 258 continue 259 try: 260 referenceWaterLevelGaugeHeight = float( 261 referenceWaterLevelGaugeHeight 262 ) 263 except ValueError: 264 print( 265 "referenceWaterLevelGaugeHeight is not convertible into float for file {}. Skipping the file" 266 .format(log_file_path) 267 ) 268 continue 269 # parse, correct and append log file 270 difference = referenceWaterLevelGaugeHeight - gaugeHeight 271 csv_callback.stage_set(difference) 272 result = log_handler.gnuboat_read_file( 273 log_file_path, csv_callback.callback 274 ) 275 if result.messages(): 276 print('\n'.join(result.errors())) 277 if not result.success(): 278 sys.exit(5) 279 280 print( 281 " {} correct and joined with difference {:.3f}m".format( 282 log_file_path, difference 283 ) 284 ) 285 output_file.close() 286 print(' Processed {} points'.format(csv_callback.count())) 287 288 # create ogr file info 289 source_xml_file = os.path.join( 290 temp_directory, '{}.vrt'.format(source_data_layer) 291 ) 292 try: 293 output_file = open(source_xml_file, 'wb') 294 except IOError as error: 295 print( 296 'ERROR: Could not open the output file for the ogr data source description: {}' 297 .format(error) 298 ) 299 sys.exit(4) 300 xml_data_source = ET.Element("OGRVRTDataSource") 301 xml_layer = ET.SubElement( 302 xml_data_source, "OGRVRTLayer", {"name": source_data_layer} 303 ) 304 xml_source = ET.SubElement( 305 xml_layer, "SrcDataSource", {'relativeToVRT': "1"} 306 ) 307 xml_source.text = corrected_joined_point_cloud_file_path 308 xml_geometry_type = ET.SubElement(xml_layer, "GeometryType") 309 xml_geometry_type.text = "wkbPoint" 310 xml_layer_system = ET.SubElement(xml_layer, "LayerSRS") 311 xml_layer_system.text = input_epsg 312 xml_geometry_field = ET.SubElement( 313 xml_layer, "GeometryField", { 314 "encoding": "PointFromColumns", 315 "x": "lon", 316 "y": "lat", 317 "z": "water_depth" 318 } 319 ) 320 xml_tree = ET.ElementTree(xml_data_source) 321 xml_tree.write(output_file, encoding="UTF-8", xml_declaration=False) 322 output_file.close() 323 324 # create csvt file 325 try: 326 output_file_csvt = open( 327 os.path.join(temp_directory, '{}.csvt'.format(source_data_layer)), 328 'w' 329 ) 330 except IOError as error: 331 print( 332 'ERROR: Could not open the output file for the ogr data source description: {}' 333 .format(error) 334 ) 335 sys.exit(6) 336 output_file_csvt.write('"Real","Real","Real"') 337 output_file_csvt.close() 338 339 # preparing output_directory 340 if os.path.exists(output_directory): 341 for root, dirs, files in os.walk(output_directory): 342 for f in files: 343 os.unlink(os.path.join(root, f)) 344 for d in dirs: 345 shutil.rmtree(os.path.join(root, d)) 346 else: 347 os.makedirs(output_directory) 348 349 # get source boundaries (Envelope / Extent) 350 datasource = ogr.Open(source_xml_file) 351 if datasource is None: 352 raise FileNotFoundError( 353 'Could not open input file {}'.format(source_xml_file) 354 ) 355 if datasource.GetLayerCount() < 1: 356 raise ReferenceError('No layers in input file') 357 source_layer = datasource.GetLayerByIndex(0) 358 source_x_min, source_x_max, source_y_min, source_y_max = source_layer.GetExtent( 359 ) 360 361 tilegen = tilegenerator.TileGenerator( 362 tile_sizes=tile_sizes, 363 densities=[density_min], 364 density_base=density_base, 365 debug=statistics 366 ) 367 slices = tilegen.slices( 368 source_xml_file, 369 tilegenerator.ZoomRange(zoom_range[0], zoom_range[1]), 370 raster_file_size_max=raster_file_size_max * 1024 * 1024 * 8 371 ) 372 slices_count = len(slices) 373 print('Generated {} slices for rastering'.format(slices_count)) 374 375 t1_start = process_time() 376 print('Rastering slices and generating tiles') 377 with progressbar.ProgressBar( 378 max_value=slices_count, redirect_stdout=True 379 ) as bar: 380 i = 1 381 for tile_slice in slices: 382 if statistics: 383 print( 384 ' Generating tiles for slice {} in {}'.format( 385 i, temp_directory 386 ) 387 ) 388 result_paths = tilegen.run( 389 source_xml_file, temp_directory, tile_slice 390 ) 391 for path in result_paths: 392 tilegen.move_tiles_in_place( 393 path.path, 394 os.path.join( 395 output_directory, path.prefixes['density'], 396 path.prefixes['tile_size'] 397 ), 398 skip_empty=skip_empty 399 ) 400 bar.update(i) 401 i += 1 402 t1_stop = process_time() 403 print(' Tooks {:.2f} hours'.format((t1_stop - t1_start) / 60 / 60)) 404 405 # delete temporary directory 406 shutil.rmtree(temp_directory) 407 408 print('Generated tiles in {}'.format(output_directory)) 409 410 sys.exit(0) 411 276 412 277 413 if __name__ == "__main__": 278 main(sys.argv[1:])414 main(sys.argv[1:]) -
src/common/bin/gnuboat-log-converter
rda2be70 r7be94aa 29 29 from gnuboat_common.datahandler import loghandler, logdataset 30 30 31 31 32 class Format(Enum): 32 33 CSV = 1 … … 34 35 GPX = 3 35 36 37 36 38 class CsvCallback: 37 39 def __init__(self, output_file): … … 41 43 self._output_file.writerow(dataset.to_dict()) 42 44 43 def convertToCsv(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time): 45 46 def convertToCsv( 47 input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time 48 ): 44 49 try: 45 50 output_file = open(output_file_path, 'w') … … 49 54 50 55 output_file_csv = None 51 fields = ['datetime', 'gps_status', 'latitude', 'latitude_direction', 'longitude', 52 'longitude_direction', 'speed_over_ground', 'course_over_ground' , 53 'water_depth', 'water_temperature'] 54 output_file_csv = csv.DictWriter(output_file, delimiter=' ', quotechar='"', 55 quoting=csv.QUOTE_NONNUMERIC, fieldnames=fields) 56 fields = [ 57 'datetime', 'gps_status', 'latitude', 'latitude_direction', 58 'longitude', 'longitude_direction', 'speed_over_ground', 59 'course_over_ground', 'water_depth', 'water_temperature' 60 ] 61 output_file_csv = csv.DictWriter( 62 output_file, 63 delimiter=' ', 64 quotechar='"', 65 quoting=csv.QUOTE_NONNUMERIC, 66 fieldnames=fields 67 ) 56 68 output_file_csv.writeheader() 57 69 58 70 csv_callback = CsvCallback(output_file_csv) 59 71 log_handler = loghandler.LogHandler() 60 result = log_handler.gnuboat_read_file(input_file_path, csv_callback.callback, checksums_fix, errors_ignore) 72 result = log_handler.gnuboat_read_file( 73 input_file_path, csv_callback.callback, checksums_fix, errors_ignore 74 ) 61 75 if result.messages(): 62 76 print('\n'.join(result.errors())) 63 77 output_file.close() 64 78 65 def convertToNmea0183(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time): 79 80 def convertToNmea0183( 81 input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time 82 ): 66 83 try: 67 84 output_file = open(output_file_path, 'w') … … 76 93 print('ERROR: Could not open the input file: {}'.format(error)) 77 94 sys.exit(3) 78 95 79 96 log_handler = loghandler.LogHandler() 80 97 current_row = 1 … … 83 100 nmea_sentence = log_handler.parse_nmea_sentence(line, checksums_fix) 84 101 if nmea_sentence is None: 85 print('INFO: Failed to parse nmea sentence ({}) at line {}'.format(line.strip(), current_row)) 102 print( 103 'INFO: Failed to parse nmea sentence ({}) at line {}'.format( 104 line.strip(), current_row 105 ) 106 ) 86 107 if not errors_ignore: 87 108 input_file.close() … … 91 112 output_string = str(nmea_sentence['nmea_sentence']) 92 113 if not strip_time and nmea_sentence['log_timestamp']: 93 output_string = '{}{}'.format(nmea_sentence['log_timestamp'], output_string) 114 output_string = '{}{}'.format( 115 nmea_sentence['log_timestamp'], output_string 116 ) 94 117 output_file.write('{}\r\n'.format(str(output_string))) 95 118 current_row += 1 96 119 output_file.close() 97 120 input_file.close() 98 99 def convertToGpx(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time): 121 122 123 def convertToGpx( 124 input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time 125 ): 100 126 # make sure, nmea input file, does not have timestamps in front of the nmea 101 127 # sentences 102 [nmea_without_timestamps_handle, nmea_without_timestamp_file_path] = tempfile.mkstemp(text=True) 103 convertToNmea0183(input_file_path, nmea_without_timestamp_file_path, errors_ignore, checksums_fix, True) 104 105 subprocess.call(['gpsbabel', '-i', 'nmea', '-f', nmea_without_timestamp_file_path, '-o', 'gpx', '-F', output_file_path]) 128 [nmea_without_timestamps_handle, 129 nmea_without_timestamp_file_path] = tempfile.mkstemp(text=True) 130 convertToNmea0183( 131 input_file_path, nmea_without_timestamp_file_path, errors_ignore, 132 checksums_fix, True 133 ) 134 135 subprocess.call([ 136 'gpsbabel', '-i', 'nmea', '-f', nmea_without_timestamp_file_path, '-o', 137 'gpx', '-F', output_file_path 138 ]) 106 139 os.remove(nmea_without_timestamp_file_path) 140 107 141 108 142 def main(argv): … … 116 150 formats = [] 117 151 for file_format in Format: 118 formats.append(file_format.name) 119 120 parser = argparse.ArgumentParser(description='Convert gnuboat logfiles into other formats') 121 parser.add_argument('-f', '--format', dest='output_format', type=str, 122 help='Format of the output file.', choices=formats, default='CSV') 123 parser.add_argument('-i', '--ignore-errors', dest='errors_ignore', action='store_false', 124 help='Ignore any errors reading the log file') 125 parser.add_argument('-c', '--checksums-fix', dest='checksums_fix', action='store_true', 126 help='Ignore all checksums (and replace them with a new correct one, if needed)') 127 parser.add_argument('input_file', metavar='input_file_path', type=str, 128 help='File to be converted (input)') 129 parser.add_argument('output_file', metavar='output_file_path', type=str, 130 help='Write the converted content to file (output)') 131 parser.add_argument('--strip-time', dest='strip_time', action='store_true', 132 help='Removes timestamp in front of the nmea sentence, if it is there') 152 formats.append(file_format.name) 153 154 parser = argparse.ArgumentParser( 155 description='Convert gnuboat logfiles into other formats' 156 ) 157 parser.add_argument( 158 '-f', 159 '--format', 160 dest='output_format', 161 type=str, 162 help='Format of the output file.', 163 choices=formats, 164 default='CSV' 165 ) 166 parser.add_argument( 167 '-i', 168 '--ignore-errors', 169 dest='errors_ignore', 170 action='store_false', 171 help='Ignore any errors reading the log file' 172 ) 173 parser.add_argument( 174 '-c', 175 '--checksums-fix', 176 dest='checksums_fix', 177 action='store_true', 178 help= 179 'Ignore all checksums (and replace them with a new correct one, if needed)' 180 ) 181 parser.add_argument( 182 'input_file', 183 metavar='input_file_path', 184 type=str, 185 help='File to be converted (input)' 186 ) 187 parser.add_argument( 188 'output_file', 189 metavar='output_file_path', 190 type=str, 191 help='Write the converted content to file (output)' 192 ) 193 parser.add_argument( 194 '--strip-time', 195 dest='strip_time', 196 action='store_true', 197 help='Removes timestamp in front of the nmea sentence, if it is there' 198 ) 133 199 arguments = parser.parse_args(argv) 134 200 135 201 if arguments.output_format is not None: 136 202 format_found = False 137 203 for file_format in Format: 138 204 if file_format.name == arguments.output_format: 139 output_format = file_format.value140 format_found = True205 output_format = file_format.value 206 format_found = True 141 207 if not format_found: 142 print('ERROR: Invalid input format specified: {}'.format(arguments.output_format)) 208 print( 209 'ERROR: Invalid input format specified: {}'.format( 210 arguments.output_format 211 ) 212 ) 143 213 sys.exit(1) 144 214 145 215 if arguments.errors_ignore is not None: 146 216 errors_ignore = arguments.errors_ignore 147 217 148 218 if arguments.checksums_fix is not None: 149 219 checksums_fix = arguments.checksums_fix 150 220 151 221 if arguments.strip_time is not None: 152 222 strip_time = arguments.strip_time 153 223 154 224 if arguments.input_file is None: 155 225 print('ERROR: No input file specified') 156 226 sys.exit(2) 157 #elif not os.path.exists(arguments.input_file): 158 print('ERROR: Specified input file does not exists: {}'.format(arguments.input_file)) 227 #elif not os.path.exists(arguments.input_file): 228 print( 229 'ERROR: Specified input file does not exists: {}'.format( 230 arguments.input_file 231 ) 232 ) 159 233 sys.exit(3) 160 234 else: 161 235 input_file_path = arguments.input_file 162 236 163 237 if arguments.output_file is None: 164 238 print('ERROR: No output file specified') 165 239 sys.exit(2) 166 240 elif not os.path.exists(os.path.dirname(arguments.output_file)): 167 print('ERROR: Specified directory of output file does not exists: {}'.format(arguments.output_file)) 241 print( 242 'ERROR: Specified directory of output file does not exists: {}'. 243 format(arguments.output_file) 244 ) 168 245 sys.exit(3) 169 246 else: 170 247 output_file_path = arguments.output_file 171 248 172 if output_format == Format.CSV.value: 173 convertToCsv(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time) 249 if output_format == Format.CSV.value: 250 convertToCsv( 251 input_file_path, output_file_path, errors_ignore, checksums_fix, 252 strip_time 253 ) 174 254 elif output_format == Format.NMEA0183.value: 175 convertToNmea0183(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time) 255 convertToNmea0183( 256 input_file_path, output_file_path, errors_ignore, checksums_fix, 257 strip_time 258 ) 176 259 elif output_format == Format.GPX.value: 177 convertToGpx(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time) 260 convertToGpx( 261 input_file_path, output_file_path, errors_ignore, checksums_fix, 262 strip_time 263 ) 178 264 else: 179 265 print('ERROR: Undefined output format!\n') … … 182 268 sys.exit(0) 183 269 270 184 271 if __name__ == "__main__": 185 272 main(sys.argv[1:]) -
src/common/bin/gnuboat-log-uploader
rda2be70 r7be94aa 24 24 import argparse 25 25 26 26 27 class Log: 27 """28 """ 28 29 Workaround for @dataclass, until python 3.7 is available in main distros 29 30 """ 30 def __init__(self, water_id, device_id, gauge_id, gauge_height, comment, logfile): 31 self.water_id = water_id 32 self.device_id = device_id 33 self.gauge_id = gauge_id 34 self.gauge_height = gauge_height 35 self.comment = comment 36 self.logfile = logfile 37 38 def log_creation(self): 39 return { 40 'water': self.water_id, 41 'device': self.device_id, 42 'gauge': self.gauge_id, 43 'gaugeHeight': self.gauge_height, 44 'comment': self.comment 45 } 31 def __init__( 32 self, water_id, device_id, gauge_id, gauge_height, comment, logfile 33 ): 34 self.water_id = water_id 35 self.device_id = device_id 36 self.gauge_id = gauge_id 37 self.gauge_height = gauge_height 38 self.comment = comment 39 self.logfile = logfile 40 41 def log_creation(self): 42 return { 43 'water': self.water_id, 44 'device': self.device_id, 45 'gauge': self.gauge_id, 46 'gaugeHeight': self.gauge_height, 47 'comment': self.comment 48 } 49 46 50 47 51 def to_int(value_string): 48 try: 49 return int(value_string) 50 except: 51 return None 52 try: 53 return int(value_string) 54 except: 55 return None 56 52 57 53 58 def to_float(value_string): 54 try: 55 return float(value_string) 56 except: 57 return None 59 try: 60 return float(value_string) 61 except: 62 return None 63 58 64 59 65 def header(api_key): 60 return { 61 'X-API-KEY': api_key 62 # 'Content-type': 'multipart/form-data' 63 } 66 return { 67 'X-API-KEY': api_key 68 # 'Content-type': 'multipart/form-data' 69 } 70 64 71 65 72 def create_log(log, url, api_key): 66 response = requests.post(url, 67 json = log.log_creation(), 68 headers = header(api_key) 69 ) 70 71 if response.status_code != 200: 72 print('ERROR: Could not create LogMetaData for logfile {}'.format(log.logfile)) 73 print(' Response status code: {}'.format(response.status_code)) 74 print(' Response: \n{}'.format(response.text)) 75 print(' Request headers: {}'.format(response.request.headers)) 76 print(' Request body: {}'.format(response.request.body)) 77 sys.exit(5) 78 79 data = response.json() 80 if not 'logId' in data: 81 print('ERROR: No log id returned') 82 sys.exit(6) 83 return data["logId"] 73 response = requests.post( 74 url, json=log.log_creation(), headers=header(api_key) 75 ) 76 77 if response.status_code != 200: 78 print( 79 'ERROR: Could not create LogMetaData for logfile {}'.format( 80 log.logfile 81 ) 82 ) 83 print(' Response status code: {}'.format(response.status_code)) 84 print(' Response: \n{}'.format(response.text)) 85 print(' Request headers: {}'.format(response.request.headers)) 86 print(' Request body: {}'.format(response.request.body)) 87 sys.exit(5) 88 89 data = response.json() 90 if not 'logId' in data: 91 print('ERROR: No log id returned') 92 sys.exit(6) 93 return data["logId"] 94 84 95 85 96 def upload_log(log_id, log, url, api_key): 86 fileContent = open(log.logfile, 'rb') 87 headers = header(api_key) 88 headers["Accept"] = "application/json" 89 response = requests.post( 90 "{}/{}".format(url, log_id), 91 data = fileContent, 92 headers = headers 93 ) 94 if response.status_code != 200: 95 print('ERROR: Could not upload log for logfile {}'.format(log.logfile)) 96 print("Response status code: {}".format(response.status_code)) 97 print("Response: \n{}".format(response.text)) 98 sys.exit(7) 97 fileContent = open(log.logfile, 'rb') 98 headers = header(api_key) 99 headers["Accept"] = "application/json" 100 response = requests.post( 101 "{}/{}".format(url, log_id), data=fileContent, headers=headers 102 ) 103 if response.status_code != 200: 104 print('ERROR: Could not upload log for logfile {}'.format(log.logfile)) 105 print("Response status code: {}".format(response.status_code)) 106 print("Response: \n{}".format(response.text)) 107 sys.exit(7) 108 99 109 100 110 def main(argv): 101 input_file_path = None 102 url = None 103 api_key = None 104 105 parser = argparse.ArgumentParser(description='Uploads logfiles to GNUBoat server') 106 parser.add_argument('input_file', metavar='input_file_path', type=str, 107 help='JSON file with water, gauge, device, logfiles and correction data to be processed') 108 parser.add_argument('-s', '--server', dest='server', type=str, 109 help='Server host and port to upload the logsfiles to') 110 parser.add_argument('-k', '--api-key', dest='api_key', type=str, 111 help='API Key for authorisation') 112 arguments = parser.parse_args(argv) 113 114 if arguments.input_file is None: 115 print('ERROR: No input file specified') 116 sys.exit(2) 117 elif not os.path.exists(arguments.input_file): 118 print('ERROR: Specified input file does not exists: {}'.format(arguments.input_file)) 119 sys.exit(3) 120 else: 121 input_file_path = arguments.input_file 122 123 if arguments.server is None: 124 print('ERROR: No server specified') 125 sys.exit(2) 126 else: 127 url = 'http://{}/mapservice/v1/logs'.format(arguments.server) 128 129 if arguments.api_key is None: 130 print('ERROR: No API key specified') 131 sys.exit(2) 132 else: 133 api_key = arguments.api_key 134 135 logs_checked = [] 136 print('Checking input from {}'.format(input_file_path)) 137 with open(input_file_path, 'r') as input_file: 138 logs = json.load(input_file) 139 for log in logs: 140 if not 'water' in log: 141 print('ERROR: No water in log {}'.format(json.dumps(log))) 142 sys.exit(4) 143 water_id = to_int(log['water']) 144 if not water_id: 145 print('ERROR: Could not convert water to int {}'.format(log['water'])) 146 sys.exit(4) 147 148 if not 'gauge' in log: 149 print('ERROR: No gauge in log {}'.format(json.dumps(log))) 150 sys.exit(4) 151 gauge_id = to_int(log['gauge']) 152 if not gauge_id: 153 print('ERROR: Could not convert gauge to int {}'.format(log['gauge'])) 154 sys.exit(4) 155 156 if not 'device' in log: 157 print('ERROR: No device in log {}'.format(json.dumps(log))) 158 sys.exit(4) 159 device_id = to_int(log['device']) 160 if not device_id: 161 print('ERROR: Could not convert device to int {}'.format(log['device'])) 162 sys.exit(4) 163 164 if not 'gaugeHeight' in log: 165 print('ERROR: No gaugeHeight in log {}'.format(json.dumps(log))) 166 sys.exit(4) 167 gauge_height = to_float(log['gaugeHeight']) 168 if not gauge_height: 169 print('ERROR: Could not convert gaugeHeight to float {}'.format(log['gaugeHeight'])) 170 sys.exit(4) 171 172 if not 'file' in log: 173 print('ERROR: No file in log {}'.format(json.dumps(log))) 174 sys.exit(4) 175 176 comment = '' 177 if 'comment' in log: 178 comment = log['comment'] 179 180 logfile = os.path.join(os.path.dirname(__file__), log['file']) 181 if not os.path.exists(logfile): 182 logfile_rel = os.path.join(os.path.dirname(input_file_path), log['file']) 183 if not os.path.exists(logfile_rel): 184 print('ERROR: Logfile not found at {} or {}'.format(logfile, logfile_rel)) 185 sys.exit(4) 186 else: 187 logfile = logfile_rel 188 logs_checked.append(Log(water_id, device_id, gauge_id, gauge_height, comment, logfile)) 189 190 print('Uploading {} logs'.format(len(logs_checked))) 191 for log in logs_checked: 192 log_id = create_log(log, url, api_key) 193 upload_log(log_id, log, url, api_key) 194 print(' Finished {}'.format(log.logfile)) 111 input_file_path = None 112 url = None 113 api_key = None 114 115 parser = argparse.ArgumentParser( 116 description='Uploads logfiles to GNUBoat server' 117 ) 118 parser.add_argument( 119 'input_file', 120 metavar='input_file_path', 121 type=str, 122 help= 123 'JSON file with water, gauge, device, logfiles and correction data to be processed' 124 ) 125 parser.add_argument( 126 '-s', 127 '--server', 128 dest='server', 129 type=str, 130 help='Server host and port to upload the logsfiles to' 131 ) 132 parser.add_argument( 133 '-k', 134 '--api-key', 135 dest='api_key', 136 type=str, 137 help='API Key for authorisation' 138 ) 139 arguments = parser.parse_args(argv) 140 141 if arguments.input_file is None: 142 print('ERROR: No input file specified') 143 sys.exit(2) 144 elif not os.path.exists(arguments.input_file): 145 print( 146 'ERROR: Specified input file does not exists: {}'.format( 147 arguments.input_file 148 ) 149 ) 150 sys.exit(3) 151 else: 152 input_file_path = arguments.input_file 153 154 if arguments.server is None: 155 print('ERROR: No server specified') 156 sys.exit(2) 157 else: 158 url = 'http://{}/mapservice/v1/logs'.format(arguments.server) 159 160 if arguments.api_key is None: 161 print('ERROR: No API key specified') 162 sys.exit(2) 163 else: 164 api_key = arguments.api_key 165 166 logs_checked = [] 167 print('Checking input from {}'.format(input_file_path)) 168 with open(input_file_path, 'r') as input_file: 169 logs = json.load(input_file) 170 for log in logs: 171 if not 'water' in log: 172 print('ERROR: No water in log {}'.format(json.dumps(log))) 173 sys.exit(4) 174 water_id = to_int(log['water']) 175 if not water_id: 176 print( 177 'ERROR: Could not convert water to int {}'.format( 178 log['water'] 179 ) 180 ) 181 sys.exit(4) 182 183 if not 'gauge' in log: 184 print('ERROR: No gauge in log {}'.format(json.dumps(log))) 185 sys.exit(4) 186 gauge_id = to_int(log['gauge']) 187 if not gauge_id: 188 print( 189 'ERROR: Could not convert gauge to int {}'.format( 190 log['gauge'] 191 ) 192 ) 193 sys.exit(4) 194 195 if not 'device' in log: 196 print('ERROR: No device in log {}'.format(json.dumps(log))) 197 sys.exit(4) 198 device_id = to_int(log['device']) 199 if not device_id: 200 print( 201 'ERROR: Could not convert device to int {}'.format( 202 log['device'] 203 ) 204 ) 205 sys.exit(4) 206 207 if not 'gaugeHeight' in log: 208 print( 209 'ERROR: No gaugeHeight in log {}'.format(json.dumps(log)) 210 ) 211 sys.exit(4) 212 gauge_height = to_float(log['gaugeHeight']) 213 if not gauge_height: 214 print( 215 'ERROR: Could not convert gaugeHeight to float {}'.format( 216 log['gaugeHeight'] 217 ) 218 ) 219 sys.exit(4) 220 221 if not 'file' in log: 222 print('ERROR: No file in log {}'.format(json.dumps(log))) 223 sys.exit(4) 224 225 comment = '' 226 if 'comment' in log: 227 comment = log['comment'] 228 229 logfile = os.path.join(os.path.dirname(__file__), log['file']) 230 if not os.path.exists(logfile): 231 logfile_rel = os.path.join( 232 os.path.dirname(input_file_path), log['file'] 233 ) 234 if not os.path.exists(logfile_rel): 235 print( 236 'ERROR: Logfile not found at {} or {}'.format( 237 logfile, logfile_rel 238 ) 239 ) 240 sys.exit(4) 241 else: 242 logfile = logfile_rel 243 logs_checked.append( 244 Log( 245 water_id, device_id, gauge_id, gauge_height, comment, 246 logfile 247 ) 248 ) 249 250 print('Uploading {} logs'.format(len(logs_checked))) 251 for log in logs_checked: 252 log_id = create_log(log, url, api_key) 253 upload_log(log_id, log, url, api_key) 254 print(' Finished {}'.format(log.logfile)) 255 195 256 196 257 if __name__ == "__main__": 197 main(sys.argv[1:])258 main(sys.argv[1:]) -
src/common/gnuboat_common/datahandler/logdataset.py
rda2be70 r7be94aa 1 # -*- coding: utf-8 -*-1 # -*- coding: utf-8 -*- 2 2 ''' 3 3 Copyright (C) 2016 - 2018 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved. … … 21 21 22 22 Location = namedtuple('Location', 'latitude longitude') 23 24 23 """@class Dataset of a log entry 25 24 """ 25 26 26 27 class LogDataset: 27 def __init__(self, datetime = None, gps_status = None, latitude = None, latitude_direction = None, 28 longitude = None, longitude_direction = None, speed_over_ground = None, 29 course_over_ground = None, water_depth = None, water_temperature = None): 30 self._datetime = datetime 31 self._gps_status = gps_status 32 self._latitude = latitude 33 self._latitude_direction = latitude_direction 34 self._longitude = longitude 35 self._longitude_direction = longitude_direction 36 self._speed_over_ground = speed_over_ground 37 self._course_over_ground = course_over_ground 38 self._water_depth = water_depth 39 self._water_temperature = water_temperature 40 41 def datetime(self): 42 return self._datetime 43 44 def datetime_object(self): 45 if self.datetime() is None: 46 return None 47 return datetime.strptime(self.datetime(), "%Y-%m-%d %H:%M:%S").replace(tzinfo=timezone.utc) 48 49 def datetime_set(self, datetime): 50 self._datetime = datetime 51 52 def gps_status(self): 53 return self._gps_status 54 55 def gps_status_set(self, status): 56 self._gps_status = status 57 58 def latitude(self): 59 return self._latitude 60 61 def latitude_set(self, latitude): 62 self._latitude = latitude 63 64 def latitude_direction(self): 65 return self._latitude_direction 66 67 def latitude_direction_set(self, direction): 68 self._latitude_direction = direction 69 70 def longitude(self): 71 return self._longitude 72 73 def longitude_set(self, longitude): 74 self._longitude = longitude 75 76 def longitude_direction(self): 77 return self._longitude_direction 78 79 def longitude_direction_set(self, direction): 80 self._longitude_direction = direction 81 82 def location(self): 83 if self.latitude_direction() is None: 84 return None 85 elif self.latitude_direction() == 'N': 86 latitude = self.latitude() 87 elif self.latitude_direction() == 'S': 88 latitude = -1.0 * self.latitude() 89 else: 90 return None 91 if self.longitude_direction() is None: 92 return None 93 elif self.longitude_direction() == 'E': 94 longitude = self.longitude() 95 elif self.longitude_direction() == 'W': 96 longitude = -1.0 * self.longitude() 97 else: 98 return None 99 return Location(latitude, longitude) 100 101 def speed_over_ground(self): 102 return self._speed_over_ground 103 104 def speed_over_ground_set(self, speed): 105 self._speed_over_ground = speed 106 107 def course_over_ground(self): 108 return self._course_over_ground 109 110 def course_over_ground_set(self, course): 111 self._course_over_ground = course 112 113 def water_depth(self): 114 return self._water_depth 115 116 def water_depth_set(self, depth): 117 self._water_depth = depth 118 119 def water_temperature(self): 120 return self._water_temperature 121 122 def water_temperature_set(self, temperature): 123 self._water_temperature = temperature 124 125 def to_dict(self): 126 return {'datetime': self.datetime(), 127 'gps_status': self.gps_status(), 128 'latitude': self.latitude(), 129 'latitude_direction': self.latitude_direction(), 130 'longitude': self.longitude(), 131 'longitude_direction': self.longitude_direction(), 132 'speed_over_ground': self.speed_over_ground(), 133 'course_over_ground': self.course_over_ground(), 134 'water_depth': self.water_depth(), 135 'water_temperature': self.water_temperature()} 28 def __init__( 29 self, 30 datetime=None, 31 gps_status=None, 32 latitude=None, 33 latitude_direction=None, 34 longitude=None, 35 longitude_direction=None, 36 speed_over_ground=None, 37 course_over_ground=None, 38 water_depth=None, 39 water_temperature=None 40 ): 41 self._datetime = datetime 42 self._gps_status = gps_status 43 self._latitude = latitude 44 self._latitude_direction = latitude_direction 45 self._longitude = longitude 46 self._longitude_direction = longitude_direction 47 self._speed_over_ground = speed_over_ground 48 self._course_over_ground = course_over_ground 49 self._water_depth = water_depth 50 self._water_temperature = water_temperature 51 52 def datetime(self): 53 return self._datetime 54 55 def datetime_object(self): 56 if self.datetime() is None: 57 return None 58 return datetime.strptime(self.datetime(), "%Y-%m-%d %H:%M:%S").replace( 59 tzinfo=timezone.utc 60 ) 61 62 def datetime_set(self, datetime): 63 self._datetime = datetime 64 65 def gps_status(self): 66 return self._gps_status 67 68 def gps_status_set(self, status): 69 self._gps_status = status 70 71 def latitude(self): 72 return self._latitude 73 74 def latitude_set(self, latitude): 75 self._latitude = latitude 76 77 def latitude_direction(self): 78 return self._latitude_direction 79 80 def latitude_direction_set(self, direction): 81 self._latitude_direction = direction 82 83 def longitude(self): 84 return self._longitude 85 86 def longitude_set(self, longitude): 87 self._longitude = longitude 88 89 def longitude_direction(self): 90 return self._longitude_direction 91 92 def longitude_direction_set(self, direction): 93 self._longitude_direction = direction 94 95 def location(self): 96 if self.latitude_direction() is None: 97 return None 98 elif self.latitude_direction() == 'N': 99 latitude = self.latitude() 100 elif self.latitude_direction() == 'S': 101 latitude = -1.0 * self.latitude() 102 else: 103 return None 104 if self.longitude_direction() is None: 105 return None 106 elif self.longitude_direction() == 'E': 107 longitude = self.longitude() 108 elif self.longitude_direction() == 'W': 109 longitude = -1.0 * self.longitude() 110 else: 111 return None 112 return Location(latitude, longitude) 113 114 def speed_over_ground(self): 115 return self._speed_over_ground 116 117 def speed_over_ground_set(self, speed): 118 self._speed_over_ground = speed 119 120 def course_over_ground(self): 121 return self._course_over_ground 122 123 def course_over_ground_set(self, course): 124 self._course_over_ground = course 125 126 def water_depth(self): 127 return self._water_depth 128 129 def water_depth_set(self, depth): 130 self._water_depth = depth 131 132 def water_temperature(self): 133 return self._water_temperature 134 135 def water_temperature_set(self, temperature): 136 self._water_temperature = temperature 137 138 def to_dict(self): 139 return { 140 'datetime': self.datetime(), 141 'gps_status': self.gps_status(), 142 'latitude': self.latitude(), 143 'latitude_direction': self.latitude_direction(), 144 'longitude': self.longitude(), 145 'longitude_direction': self.longitude_direction(), 146 'speed_over_ground': self.speed_over_ground(), 147 'course_over_ground': self.course_over_ground(), 148 'water_depth': self.water_depth(), 149 'water_temperature': self.water_temperature() 150 } -
src/common/gnuboat_common/datahandler/loghandler.py
rda2be70 r7be94aa 1 # -*- coding: utf-8 -*-1 # -*- coding: utf-8 -*- 2 2 ''' 3 3 Copyright (C) 2016 - 2020 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved. … … 27 27 from gnuboat_common.datahandler import logdataset 28 28 29 29 30 class LogParsingResult: 30 def __init__(self): 31 self._success = False 32 self._errors = [] 33 34 def error_add(self, error): 35 self._errors.append(error) 36 37 def errors(self): 38 return self._errors 39 40 def messages(self): 41 if len(self._errors) > 0: 42 return True 43 return False 44 45 def succeeded(self, status): 46 self._success = status 47 48 def success(self): 49 return self._success 31 def __init__(self): 32 self._success = False 33 self._errors = [] 34 35 def error_add(self, error): 36 self._errors.append(error) 37 38 def errors(self): 39 return self._errors 40 41 def messages(self): 42 if len(self._errors) > 0: 43 return True 44 return False 45 46 def succeeded(self, status): 47 self._success = status 48 49 def success(self): 50 return self._success 51 50 52 51 53 """@class LogHandler 52 54 """ 55 56 53 57 class LogHandler: 54 def __init__(self, log_directory = None): 55 self._regex_nmea_sentence = re.compile(r"^([^\$!]{0,})([\$!]{1}[\w]{2}[\w]{3}[^\*]+\*[\da-zA-Z]+)$") 56 self._regex_nmea_sentence_without_checksum = re.compile(r"^([^\$!]{0,})([\$!]{1}[\w]{2}[\w]{3}[^\*]+)\*[\da-zA-Z]+$") 57 self._regex_nmea_position_latitude = re.compile(r"^([0-9]{2})([0-9]{2}\.[0-9]+)$") 58 self._regex_nmea_position_longitude = re.compile(r"^([0-9]{3})([0-9]{2}\.[0-9]+)$") 59 self._log_directory = log_directory 60 self._nmea_file = None 61 self._nmea_file_date = None 62 63 def gnuboat_write(self, gps_fix, gps_time, dataset, transducer_valid, log_verbose, log_system_time): 64 # Only log, if we have a gps fix 65 if gps_fix < 2: 66 if not log_verbose: 67 return 68 gps_status = 'V' 69 mode = 'N' 70 if gps_time is None: 71 gps_time = datetime.datetime.utcnow() 72 73 nmea_file_date_should = datetime.datetime.utcnow().strftime("%Y-%m-%d") 74 mode = 'A' 75 if self._nmea_file == None or self._nmea_file_date is None or self._nmea_file_date != nmea_file_date_should: 76 if self._nmea_file: 77 self._nmea_file.close() 78 try: 79 self._nmea_file_date = nmea_file_date_should 80 nmea_log_file = 'nmea0183-{}.log'.format(self._nmea_file_date) 81 self._nmea_file = open(os.path.join(self._log_directory, nmea_log_file), 'a', 0) 82 except IOError as error: 83 print('Could not open the logfile: {}'.format(error)) 84 return False 85 else: 86 nmea_log_file = self._nmea_file.name 87 88 latitude = self._degreesDecimalToNmea(dataset.latitude()) 89 longitude = self._degreesDecimalToNmea(dataset.longitude()) 90 91 logsystemtime = "" 92 if log_system_time: 93 logsystemtime = '{}: '.format(datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")) 94 95 try: 96 self._nmea_file.write('{}{}\r\n'.format(logsystemtime, str(pynmea2.RMC('GN', 'RMC', 97 (gps_time.strftime("%H%M%S"), dataset.gps_status(), 98 '{:02d}{:07.4f}'.format(latitude['degrees'], latitude['minutes']), 99 dataset.latitude_direction(), 100 '{:03d}{:07.4f}'.format(longitude['degrees'], longitude['minutes']), 101 dataset.longitude_direction(), 102 '{:04.1f}'.format(dataset.speed_over_ground()), '{:04.1f}'.format(dataset.course_over_ground()), 103 gps_time.strftime("%d%m%y"), '', '', mode))))) 104 if transducer_valid: 105 self._nmea_file.write('{}{}\r\n'.format(logsystemtime, str(pynmea2.DPT('SD', 'DPT', ('{:05.2f}'.format(dataset.water_depth()), '00.00'))))) 106 self._nmea_file.write('{}{}\r\n'.format(logsystemtime, str(pynmea2.MTW('YX', 'MTW', ('{:04.1f}'.format(dataset.water_temperature()), 'C'))))) 107 return True 108 except: 109 print('Failed writing to logfile {}'.format(nmea_log_file)) 110 print(traceback.format_exc()) 111 return False 112 return False 113 114 def gnuboat_close(self): 115 if self._nmea_file: 116 self._nmea_file.close() 117 118 def parse_nmea_sentence(self, line, checksum_ingore = False): 119 line = line.strip() 120 if checksum_ingore: 121 matches = self._regex_nmea_sentence_without_checksum.match(line) 122 else: 123 matches = self._regex_nmea_sentence.match(line) 124 if matches is None: 125 return None 126 return {'log_timestamp': matches.group(1), 'nmea_sentence': pynmea2.parse(matches.group(2), not checksum_ingore)} 127 128 """ Reads the original gnuboat log files and calls a callable function on all complete LogDataset 58 def __init__(self, log_directory=None): 59 self._regex_nmea_sentence = re.compile( 60 r"^([^\$!]{0,})([\$!]{1}[\w]{2}[\w]{3}[^\*]+\*[\da-zA-Z]+)$" 61 ) 62 self._regex_nmea_sentence_without_checksum = re.compile( 63 r"^([^\$!]{0,})([\$!]{1}[\w]{2}[\w]{3}[^\*]+)\*[\da-zA-Z]+$" 64 ) 65 self._regex_nmea_position_latitude = re.compile( 66 r"^([0-9]{2})([0-9]{2}\.[0-9]+)$" 67 ) 68 self._regex_nmea_position_longitude = re.compile( 69 r"^([0-9]{3})([0-9]{2}\.[0-9]+)$" 70 ) 71 self._log_directory = log_directory 72 self._nmea_file = None 73 self._nmea_file_date = None 74 75 def gnuboat_write( 76 self, gps_fix, gps_time, dataset, transducer_valid, log_verbose, 77 log_system_time 78 ): 79 # Only log, if we have a gps fix 80 if gps_fix < 2: 81 if not log_verbose: 82 return 83 gps_status = 'V' 84 mode = 'N' 85 if gps_time is None: 86 gps_time = datetime.datetime.utcnow() 87 88 nmea_file_date_should = datetime.datetime.utcnow().strftime("%Y-%m-%d") 89 mode = 'A' 90 if self._nmea_file == None or self._nmea_file_date is None or self._nmea_file_date != nmea_file_date_should: 91 if self._nmea_file: 92 self._nmea_file.close() 93 try: 94 self._nmea_file_date = nmea_file_date_should 95 nmea_log_file = 'nmea0183-{}.log'.format(self._nmea_file_date) 96 self._nmea_file = open( 97 os.path.join(self._log_directory, nmea_log_file), 'a', 0 98 ) 99 except IOError as error: 100 print('Could not open the logfile: {}'.format(error)) 101 return False 102 else: 103 nmea_log_file = self._nmea_file.name 104 105 latitude = self._degreesDecimalToNmea(dataset.latitude()) 106 longitude = self._degreesDecimalToNmea(dataset.longitude()) 107 108 logsystemtime = "" 109 if log_system_time: 110 logsystemtime = '{}: '.format( 111 datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S") 112 ) 113 114 try: 115 self._nmea_file.write( 116 '{}{}\r\n'.format( 117 logsystemtime, 118 str( 119 pynmea2.RMC( 120 'GN', 'RMC', ( 121 gps_time.strftime("%H%M%S"), 122 dataset.gps_status(), '{:02d}{:07.4f}'.format( 123 latitude['degrees'], latitude['minutes'] 124 ), dataset.latitude_direction(), 125 '{:03d}{:07.4f}'.format( 126 longitude['degrees'], longitude['minutes'] 127 ), dataset.longitude_direction(), 128 '{:04.1f}'.format(dataset.speed_over_ground()), 129 '{:04.1f}'.format( 130 dataset.course_over_ground() 131 ), gps_time.strftime("%d%m%y"), '', '', mode 132 ) 133 ) 134 ) 135 ) 136 ) 137 if transducer_valid: 138 self._nmea_file.write( 139 '{}{}\r\n'.format( 140 logsystemtime, 141 str( 142 pynmea2.DPT( 143 'SD', 'DPT', ( 144 '{:05.2f}'.format(dataset.water_depth() 145 ), '00.00' 146 ) 147 ) 148 ) 149 ) 150 ) 151 self._nmea_file.write( 152 '{}{}\r\n'.format( 153 logsystemtime, 154 str( 155 pynmea2.MTW( 156 'YX', 'MTW', ( 157 '{:04.1f}'.format( 158 dataset.water_temperature() 159 ), 'C' 160 ) 161 ) 162 ) 163 ) 164 ) 165 return True 166 except: 167 print('Failed writing to logfile {}'.format(nmea_log_file)) 168 print(traceback.format_exc()) 169 return False 170 return False 171 172 def gnuboat_close(self): 173 if self._nmea_file: 174 self._nmea_file.close() 175 176 def parse_nmea_sentence(self, line, checksum_ingore=False): 177 line = line.strip() 178 if checksum_ingore: 179 matches = self._regex_nmea_sentence_without_checksum.match(line) 180 else: 181 matches = self._regex_nmea_sentence.match(line) 182 if matches is None: 183 return None 184 return { 185 'log_timestamp': 186 matches.group(1), 187 'nmea_sentence': 188 pynmea2.parse(matches.group(2), not checksum_ingore) 189 } 190 191 """ Reads the original gnuboat log files and calls a callable function on all complete LogDataset 129 192 callback must be of a function wich excepts the LogDataset as a parameter. 130 193 """ 131 def gnuboat_read_file(self, input_file_path, callback, checksums_fix = False, errors_ignore = False): 132 result = LogParsingResult() 133 134 # reading input file 135 try: 136 input_file = open(input_file_path, 'r') 137 except IOError as error: 138 result.error_add('ERROR: Could not open the input file: {}'.format(error)) 139 result.succeeded(False) 140 return result 141 result = self.gnuboat_read(input_file, callback, checksums_fix, errors_ignore = False) 142 input_file.close() 143 return result 144 145 """ Reads the original gnuboat log from input_list and calls a callable function on all complete LogDataset 194 195 def gnuboat_read_file( 196 self, 197 input_file_path, 198 callback, 199 checksums_fix=False, 200 errors_ignore=False 201 ): 202 result = LogParsingResult() 203 204 # reading input file 205 try: 206 input_file = open(input_file_path, 'r') 207 except IOError as error: 208 result.error_add( 209 'ERROR: Could not open the input file: {}'.format(error) 210 ) 211 result.succeeded(False) 212 return result 213 result = self.gnuboat_read( 214 input_file, callback, checksums_fix, errors_ignore=False 215 ) 216 input_file.close() 217 return result 218 219 """ Reads the original gnuboat log from input_list and calls a callable function on all complete LogDataset 146 220 callback must be of a function wich excepts the LogDataset as a parameter. 147 221 """ 148 def gnuboat_read(self, input_list, callback, checksums_fix = False, errors_ignore = False): 149 result = LogParsingResult() 150 151 current_row = 1 152 last_row = None 153 for line in input_list: 154 nmea_sentence = self.parse_nmea_sentence(line, checksums_fix) 155 if nmea_sentence is None: 156 result.error_add('INFO: Failed to parse nmea sentence ({}) at line {}'.format(line.strip(), current_row)) 157 if not errors_ignore: 158 result.succeeded(False) 159 return result 160 else: 161 nmea_sentence = nmea_sentence['nmea_sentence'] 162 if nmea_sentence.sentence_type == 'RMC': 163 if last_row is not None: 164 callback(last_row) 165 last_row = logdataset.LogDataset() 166 last_row.datetime_set('{} {}'.format(nmea_sentence.datestamp, nmea_sentence.timestamp)) 167 last_row.gps_status_set(nmea_sentence.status) 168 last_row.latitude_set(self._nmeaLatitudeToDecimalDegrees(nmea_sentence.lat, current_row)) 169 last_row.latitude_direction_set(nmea_sentence.lat_dir) 170 last_row.longitude_set(self._nmeaLongitudeToDecimalDegrees(nmea_sentence.lon, current_row)) 171 last_row.longitude_direction_set(nmea_sentence.lon_dir) 172 last_row.speed_over_ground_set(self._to_float(nmea_sentence.spd_over_grnd, current_row)) 173 last_row.course_over_ground_set(self._to_float(nmea_sentence.true_course, current_row)) 174 last_row.water_depth_set(None) 175 last_row.water_temperature_set(None) 176 elif nmea_sentence.sentence_type == 'DPT' and last_row is not None: 177 last_row.water_depth_set(self._to_float(nmea_sentence.depth, current_row)) 178 elif nmea_sentence.sentence_type == 'MTW' and last_row is not None: 179 last_row.water_temperature_set(self._to_float(nmea_sentence.temperature, current_row)) 180 current_row += 1 181 if last_row is not None: 182 callback(last_row) 183 result.succeeded(True) 184 return result 185 186 def _to_float(self, string, current_row): 187 try: 188 return float(string) 189 except ValueError as error: 190 try: 191 return int(string) 192 except ValueError as error: 193 print('INFO: Failed to convert value from line {} into numeric: {}\n Message: {}'.format(current_row, string, error)) 194 return 0 195 196 def _nmeaLatitudeToDecimalDegrees(self, nmea_value, current_row): 197 if self._to_float(nmea_value, current_row) == 0: 198 return 0 199 200 matches = self._regex_nmea_position_latitude.match(nmea_value) 201 if matches is None: 202 print('INFO: Failed to convert latitude position value from line {} into decimal degrees: {}'.format(current_row, nmea_value)) 203 return 204 decimalDegrees = self._to_float(matches.group(1), current_row) 205 decimalMinutes = self._to_float(matches.group(2), current_row) 206 return decimalDegrees + (decimalMinutes / 60.0) 207 208 def _nmeaLongitudeToDecimalDegrees(self, nmea_value, current_row): 209 if self._to_float(nmea_value, current_row) == 0: 210 return 0 211 212 matches = self._regex_nmea_position_longitude.match(nmea_value) 213 if matches is None: 214 print('INFO: Failed to convert longitude position value from line {} into decimal degrees: {}'.format(current_row, nmea_value)) 215 return 216 decimalDegrees = self._to_float(matches.group(1), current_row) 217 decimalMinutes = self._to_float(matches.group(2), current_row) 218 return decimalDegrees + (decimalMinutes / 60.0) 219 220 221 def _degreesDecimalToNmea(self, decimalDegrees): 222 degrees = int(math.floor(decimalDegrees)) 223 minutes = 60.0 * (decimalDegrees - degrees) 224 return { 'degrees': degrees, 'minutes': minutes} 222 223 def gnuboat_read( 224 self, input_list, callback, checksums_fix=False, errors_ignore=False 225 ): 226 result = LogParsingResult() 227 228 current_row = 1 229 last_row = None 230 for line in input_list: 231 nmea_sentence = self.parse_nmea_sentence(line, checksums_fix) 232 if nmea_sentence is None: 233 result.error_add( 234 'INFO: Failed to parse nmea sentence ({}) at line {}'. 235 format(line.strip(), current_row) 236 ) 237 if not errors_ignore: 238 result.succeeded(False) 239 return result 240 else: 241 nmea_sentence = nmea_sentence['nmea_sentence'] 242 if nmea_sentence.sentence_type == 'RMC': 243 if last_row is not None: 244 callback(last_row) 245 last_row = logdataset.LogDataset() 246 last_row.datetime_set( 247 '{} {}'.format( 248 nmea_sentence.datestamp, nmea_sentence.timestamp 249 ) 250 ) 251 last_row.gps_status_set(nmea_sentence.status) 252 last_row.latitude_set( 253 self._nmeaLatitudeToDecimalDegrees( 254 nmea_sentence.lat, current_row 255 ) 256 ) 257 last_row.latitude_direction_set(nmea_sentence.lat_dir) 258 last_row.longitude_set( 259 self._nmeaLongitudeToDecimalDegrees( 260 nmea_sentence.lon, current_row 261 ) 262 ) 263 last_row.longitude_direction_set(nmea_sentence.lon_dir) 264 last_row.speed_over_ground_set( 265 self._to_float( 266 nmea_sentence.spd_over_grnd, current_row 267 ) 268 ) 269 last_row.course_over_ground_set( 270 self._to_float(nmea_sentence.true_course, current_row) 271 ) 272 last_row.water_depth_set(None) 273 last_row.water_temperature_set(None) 274 elif nmea_sentence.sentence_type == 'DPT' and last_row is not None: 275 last_row.water_depth_set( 276 self._to_float(nmea_sentence.depth, current_row) 277 ) 278 elif nmea_sentence.sentence_type == 'MTW' and last_row is not None: 279 last_row.water_temperature_set( 280 self._to_float(nmea_sentence.temperature, current_row) 281 ) 282 current_row += 1 283 if last_row is not None: 284 callback(last_row) 285 result.succeeded(True) 286 return result 287 288 def _to_float(self, string, current_row): 289 try: 290 return float(string) 291 except ValueError as error: 292 try: 293 return int(string) 294 except ValueError as error: 295 print( 296 'INFO: Failed to convert value from line {} into numeric: {}\n Message: {}' 297 .format(current_row, string, error) 298 ) 299 return 0 300 301 def _nmeaLatitudeToDecimalDegrees(self, nmea_value, current_row): 302 if self._to_float(nmea_value, current_row) == 0: 303 return 0 304 305 matches = self._regex_nmea_position_latitude.match(nmea_value) 306 if matches is None: 307 print( 308 'INFO: Failed to convert latitude position value from line {} into decimal degrees: {}' 309 .format(current_row, nmea_value) 310 ) 311 return 312 decimalDegrees = self._to_float(matches.group(1), current_row) 313 decimalMinutes = self._to_float(matches.group(2), current_row) 314 return decimalDegrees + (decimalMinutes / 60.0) 315 316 def _nmeaLongitudeToDecimalDegrees(self, nmea_value, current_row): 317 if self._to_float(nmea_value, current_row) == 0: 318 return 0 319 320 matches = self._regex_nmea_position_longitude.match(nmea_value) 321 if matches is None: 322 print( 323 'INFO: Failed to convert longitude position value from line {} into decimal degrees: {}' 324 .format(current_row, nmea_value) 325 ) 326 return 327 decimalDegrees = self._to_float(matches.group(1), current_row) 328 decimalMinutes = self._to_float(matches.group(2), current_row) 329 return decimalDegrees + (decimalMinutes / 60.0) 330 331 def _degreesDecimalToNmea(self, decimalDegrees): 332 degrees = int(math.floor(decimalDegrees)) 333 minutes = 60.0 * (decimalDegrees - degrees) 334 return {'degrees': degrees, 'minutes': minutes} -
src/common/gnuboat_common/spatial/tilegenerator.py
rda2be70 r7be94aa 31 31 32 32 try: 33 from dataclasses import dataclass34 35 #@dataclass36 #class TileWidth:37 #"""38 #tile_size: The tile size in Pixel,39 #longitude: The width of the Tile in decimal degrees40 #latitude: The height of the Tile in decimal degrees41 #"""42 #tile_size: int43 #longitude: float44 #latitude: float45 46 @dataclass47 class ResultPath:48 """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 49 path: Absolute path of the created results 50 50 prefixes: Dict with meaningful prefixes in the path. e.g. {'tile_size': '512', 'density': '10_100'} 51 51 """ 52 path: str53 prefixes: dict54 52 path: str 53 prefixes: dict 54 55 55 except ImportError: 56 #class TileWidth:57 #"""58 #Workaround for @dataclass, until python 3.7 is available in main distros59 #"""60 #def __init__(self, tile_size, longitude, latitude):61 #self.tile_size = tile_size62 #self.longitude = longitude63 #self.latitude = latitude64 65 class ResultPath:66 """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 67 path: Absolute path of the created results 68 68 prefixes: Dict with meaningful prefixes in the path. e.g. {'tile_size': '512', 'density': '10_100'} 69 69 """ 70 def __init__(self, path, prefixes): 71 self.path = path 72 self.prefixes = prefixes 70 def __init__(self, path, prefixes): 71 self.path = path 72 self.prefixes = prefixes 73 73 74 74 75 class 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']) 76 def __init__(self, minimum, maximum): 77 super(ZoomRange, self).__init__({ 78 'minimum': minimum, 79 'maximum': maximum 80 }) 81 82 def minimum(self): 83 return self['minimum'] 84 85 def maximum(self): 86 return self['maximum'] 87 88 def from_dict(dictionary): 89 return ZoomRange(dictionary['minimum'], dictionary['maximum']) 90 86 91 87 92 class 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']) 93 def __init__(self, west, south, east, north): 94 super(LngLatBbox, self).__init__({ 95 'west': west, 96 'south': south, 97 'east': east, 98 'north': north 99 }) 100 101 def west(self): 102 return self['west'] 103 104 def south(self): 105 return self['south'] 106 107 def east(self): 108 return self['east'] 109 110 def north(self): 111 return self['north'] 112 113 def to_mercantile_bbox(self): 114 return mercantile.LngLatBbox( 115 self.west(), self.south(), self.east(), self.north() 116 ) 117 118 def from_mercantile_bbox(mercantile_bbox): 119 return LngLatBbox( 120 mercantile_bbox.west, mercantile_bbox.south, mercantile_bbox.east, 121 mercantile_bbox.north 122 ) 123 124 def from_dict(dictionary): 125 if dictionary is None: 126 return None 127 return LngLatBbox( 128 dictionary['west'], dictionary['south'], dictionary['east'], 129 dictionary['north'] 130 ) 131 113 132 114 133 class RasterSlice(dict): 115 """134 """ 116 135 lng_lat_box: LngLatBbox 117 136 zoom_range: ZoomRange … … 122 141 It's derived from dict to be json serialisable 123 142 """ 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']) 143 def __init__( 144 self, lng_lat_box, zoom_range, tile_size, grid_width, grid_height 145 ): 146 super(RasterSlice, self).__init__({ 147 'lng_lat_box': lng_lat_box, 148 'zoom_range': zoom_range, 149 'tile_size': tile_size, 150 'grid_width': grid_width, 151 'grid_height': grid_height 152 }) 153 154 def lng_lat_bbox(self): 155 return self['lng_lat_box'] 156 157 def zoom_range(self): 158 return self['zoom_range'] 159 160 def tile_size(self): 161 return self['tile_size'] 162 163 def grid_width(self): 164 return self['grid_width'] 165 166 def grid_height(self): 167 return self['grid_height'] 168 169 def from_dict(dictionary): 170 if dictionary is None: 171 return None 172 return RasterSlice( 173 LngLatBbox.from_dict(dictionary['lng_lat_box']), 174 ZoomRange.from_dict(dictionary['zoom_range']), 175 dictionary['tile_size'], dictionary['grid_width'], 176 dictionary['grid_height'] 177 ) 178 146 179 147 180 class TileGenerator: 148 """181 """ 149 182 - tile_sizes = Array of tile sizes in pixel, which should be rendered 150 183 - zoom_range = Range of zooms, tiles are created for … … 153 186 - nodata_value = Value used for pixels without valid data 154 187 """ 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 """ 188 def __init__( 189 self, 190 tile_sizes=[256, 512], 191 densities=[10, 100], 192 density_base=100, 193 nodata_value=-999.0, 194 debug=False 195 ): 196 self._tile_sizes = tile_sizes 197 self._densities = densities 198 self._density_base = density_base 199 self._nodata_value = nodata_value 200 self._debug = debug 201 202 # -999 is a workaround, as long gdal python api does not handle addAlpha 203 self._colors = { 204 -999: '255 255 255', 205 0: '0 0 139', 206 2: '30 144 255', 207 6: '173 216 230', 208 10: '240 248 255' 209 } 210 211 ogr.UseExceptions() 212 213 def fit_extent_to_tiles(self, lng_lat_box, zoom_range): 214 """ 175 215 Enlarges the extent (given by lng_lat_box) to the borders of the tiles 176 216 lng_lat_box is of Type LngLatBbox 177 217 """ 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 """ 218 tile_bounding = mercantile.bounding_tile( 219 lng_lat_box.west(), lng_lat_box.south(), lng_lat_box.east(), 220 lng_lat_box.north() 221 ) 222 if tile_bounding.z > zoom_range.minimum(): 223 return LngLatBbox.from_mercantile_bbox( 224 mercantile.bounds( 225 mercantile.parent( 226 tile_bounding, zoom=zoom_range.minimum() 227 ) 228 ) 229 ) 230 else: 231 return LngLatBbox.from_mercantile_bbox( 232 mercantile.bounds(tile_bounding) 233 ) 234 235 def slices( 236 self, 237 input_file, 238 zoom_range, 239 tile_sizes=None, 240 raster_file_size_max=1024 * 1024 * 1024 * 8 241 ): 242 """ 186 243 Slice the complete area of input_file into smaller pieces, 187 244 so that each created raster file is smaller than raster_file_size_max … … 189 246 It returns an array of latitude longitude boxes representaing the borders, per slice. 190 247 """ 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 """ 248 if tile_sizes is None: 249 tile_sizes = self._tile_sizes 250 251 datasource = self._datasource_open(input_file) 252 source_layer = datasource.GetLayerByIndex(0) 253 west, east, south, north = source_layer.GetExtent() 254 255 raster_slices = [] 256 for tile_size in tile_sizes: 257 # fitting to tile borders 258 lng_lat_box = self.fit_extent_to_tiles( 259 LngLatBbox(west, south, east, north), zoom_range 260 ) 261 # The lng_lat_box is exactly on the border between tiles. Since there are rounding errors, 262 # we move the corner edges a very little bit (about a few mm) into the tile. This makes sure, 263 # that we only get those tiles returned, which are really in the lng_lat_box. 264 tiles_zoom_min = mercantile.tiles( 265 lng_lat_box.west() + 1 * 10**-7, 266 lng_lat_box.south() + 1 * 10**-7, 267 lng_lat_box.east() - 1 * 10**-7, 268 lng_lat_box.north() - 1 * 10**-7, zoom_range.minimum() 269 ) 270 271 # calculating size of raster file for GDT_Float32 = 32bits 272 delta_zoom = math.floor( 273 math.log(raster_file_size_max / (tile_size**2 * 32)) / 274 math.log(4) 275 ) 276 steps = math.floor( 277 (zoom_range.maximum() - zoom_range.minimum()) / delta_zoom 278 ) 279 zoom_steps = [] 280 step = zoom_range.minimum() 281 while step < zoom_range.maximum(): 282 zoom_steps.append(step) 283 step += delta_zoom + 1 284 for tile in tiles_zoom_min: 285 raster_slices += self._slice_tile( 286 tile, zoom_steps, zoom_range.maximum(), tile_size, 287 source_layer 288 ) 289 return raster_slices 290 291 def _slice_tile( 292 self, 293 parent_tile, 294 zoom_steps, 295 zoom_total_max, 296 tile_size, 297 source_layer, 298 tiles_with_geometry=True 299 ): 300 if len(zoom_steps) < 1: 301 raise ValueError('No zoomsteps given to slice tile generation') 302 zoom_min = zoom_steps[0] 303 if len(zoom_steps) < 2: 304 zoom_max = zoom_total_max 305 else: 306 zoom_max = zoom_steps[1] - 1 307 308 raster_slices = [] 309 lng_lat_box = mercantile.bounds(parent_tile) 310 width = math.sqrt(4**(zoom_max - zoom_min)) * tile_size 311 if width != round(width): 312 raise ValueError('Found a slice, with incomplete tiles') 313 raster_slice = RasterSlice( 314 LngLatBbox.from_mercantile_bbox(lng_lat_box), 315 ZoomRange(zoom_min, zoom_max), tile_size, width, width 316 ) 317 raster_slices.append(raster_slice) 318 if len(zoom_steps) > 1: 319 zoom_steps_new = copy.deepcopy(zoom_steps) 320 zoom_steps_new.pop(0) 321 zoom_min_new = zoom_steps_new[0] 322 for child in mercantile.children(parent_tile, zoom=zoom_min_new): 323 # test, if tile has geometry 324 lng_lat_box = mercantile.bounds(child) 325 source_layer.SetSpatialFilterRect( 326 lng_lat_box.west, lng_lat_box.south, lng_lat_box.east, 327 lng_lat_box.north 328 ) 329 if source_layer.GetNextFeature() or not tiles_with_geometry: 330 raster_slices += self._slice_tile( 331 child, 332 zoom_steps_new, 333 zoom_total_max, 334 tile_size, 335 source_layer, 336 tiles_with_geometry=tiles_with_geometry 337 ) 338 source_layer.SetSpatialFilter(None) 339 return raster_slices 340 341 def run( 342 self, 343 input_file, 344 output_directory, 345 tile_slice, 346 densities=None, 347 density_base=None, 348 nodata_value=None 349 ): 350 """ 251 351 Runs all nescessary steps to create the tiles. 252 352 All default parameters equal to none are replaced by the one of the object … … 254 354 Returns an array of paths with the created tiles if successfull 255 355 """ 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 """ 356 if densities is None: 357 densities = self._densities 358 if density_base is None: 359 density_base = self._density_base 360 if nodata_value is None: 361 nodata_value = self._nodata_value 362 363 # get source boundaries (Envelope / Extent) 364 datasource = self._datasource_open(input_file) 365 source_layer = datasource.GetLayerByIndex(0) 366 source_x_min, source_x_max, source_y_min, source_y_max = source_layer.GetExtent( 367 ) 368 source_layer_name = source_layer.GetName() 369 370 # define density information for gridding algorithm 371 lon_metre_max = 60 * 1852 * math.cos( 372 math.radians(min(source_y_min, source_y_max)) 373 ) # metre / degree 374 lat_metre_max = 111694 # metre / degree 375 circle_radius = math.sqrt(density_base) / math.pi 376 radius_x = circle_radius / lon_metre_max 377 radius_y = circle_radius / lat_metre_max 378 379 tile_result_paths = [] 380 for density_min in densities: 381 gridding_algorithm = 'average:radius1={}:radius2={}:angle=0.0:min_points={}:nodata={}'.format( 382 radius_x, radius_y, density_min, nodata_value 383 ) 384 if self._debug: 385 print( 386 "Run for density {} and {} tile size:".format( 387 density_min, tile_slice.tile_size() 388 ) 389 ) 390 print(" Statistics:") 391 print( 392 " Found {} Points".format( 393 source_layer.GetFeatureCount() 394 ) 395 ) 396 print( 397 " Min density per squaredegree: {}".format( 398 density_min * density_base / lon_metre_max / 399 lat_metre_max 400 ) 401 ) 402 print( 403 " Min density per pixel: {}".format( 404 density_min * density_base / 405 (degree_per_pixel_lon * lon_metre_max) / 406 (degree_per_pixel_lat * lat_metre_max) 407 ) 408 ) 409 print(" gridding algorithm {}".format(gridding_algorithm)) 410 411 # create the grid data 412 raster_file = self.raster_create( 413 input_file, source_layer_name, tile_slice, gridding_algorithm 414 ) 415 # hillshade 416 hillshade_file = self.hillshade_create(raster_file) 417 # color relief 418 color_relief_file = self.color_relief_create(raster_file) 419 # slopeshade 420 slopeshade_file = os.path.join( 421 output_directory, 'water_depth_slopeshade.tif' 422 ) 423 slopeshade_file = self.slopeshade_create( 424 raster_file, slopeshade_file 425 ) 426 # merge color relief and hillshade 427 merged_file = os.path.join( 428 output_directory, 429 'water_depth_{}_{}.tif'.format(density_min, density_base) 430 ) 431 self.merge_color_relief_hillshade( 432 color_relief_file, hillshade_file, merged_file 433 ) 434 # create the tiles 435 title = 'GNUBoat {} datasets per {} squaremetre, Tilesize: {}'.format( 436 density_min, density_base, tile_slice.tile_size() 437 ) 438 prefix_density = '{}_{}'.format(density_min, density_base) 439 tiles_output = os.path.join( 440 output_directory, 441 '{}/{}'.format(prefix_density, tile_slice.tile_size()) 442 ) 443 self.tiles_create( 444 merged_file, 445 title, 446 tile_slice.tile_size(), 447 tiles_output, 448 zoom_range=tile_slice.zoom_range() 449 ) 450 tile_result_paths.append( 451 ResultPath( 452 tiles_output, { 453 'tile_size': str(tile_slice.tile_size()), 454 'density': prefix_density 455 } 456 ) 457 ) 458 return tile_result_paths 459 460 def raster_create( 461 self, 462 input_file, 463 layers, 464 tile_slice, 465 gridding_algorithm, 466 nodata_value=None, 467 output_file='/vsimem/water_depth.tif' 468 ): 469 """ 309 470 Rastering the data from source file into a tif. 310 471 The input should be a vrt source file. 311 472 The function returns the path to the generated tif file. 312 473 """ 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 """ 474 if nodata_value is None: 475 nodata_value = self._nodata_value 476 477 grid_options = gdal.GridOptions( 478 outputType=gdal.GDT_Float32, 479 format="GTiff", 480 width=tile_slice.grid_width(), 481 height=tile_slice.grid_height(), 482 outputSRS="WGS84", 483 outputBounds=[ 484 tile_slice.lng_lat_bbox().west(), 485 tile_slice.lng_lat_bbox().north(), 486 tile_slice.lng_lat_bbox().east(), 487 tile_slice.lng_lat_bbox().south() 488 ], 489 noData=nodata_value, 490 layers=layers, 491 spatFilter=( 492 tile_slice.lng_lat_bbox().west(), 493 tile_slice.lng_lat_bbox().south(), 494 tile_slice.lng_lat_bbox().east(), 495 tile_slice.lng_lat_bbox().north() 496 ), 497 algorithm=gridding_algorithm 498 ) 499 gdal.Grid(output_file, input_file, options=grid_options) 500 return output_file 501 502 def hillshade_create( 503 self, input_file, output_file='/vsimem/water_depth_hillshade.tif' 504 ): 505 """ 333 506 Creates the hillshade from a raster tif file and returns the path to the resulting tif file 334 507 """ 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 """ 508 gdal.DEMProcessing( 509 output_file, 510 input_file, 511 "hillshade", 512 options=gdal.DEMProcessingOptions(format="GTiff", zFactor=-1) 513 ) 514 return output_file 515 516 def color_relief_create( 517 self, 518 input_file, 519 output_file='/vsimem/water_depth_color_relief.tif', 520 colors=None 521 ): 522 """ 340 523 Creates the color relief from a raster tif and returns the path to the resulting tif file 341 524 """ 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 """ 525 if colors is None: 526 colors = self._colors 527 528 gdal_file_color_relief_config = tempfile.NamedTemporaryFile( 529 mode='w', suffix='txt' 530 ) 531 for depth in colors: 532 gdal_file_color_relief_config.write( 533 "{} {}\n".format(depth, colors[depth]) 534 ) 535 gdal_file_color_relief_config.flush() 536 gdal.DEMProcessing( 537 output_file, 538 input_file, 539 "color-relief", 540 options=gdal.DEMProcessingOptions( 541 format="GTiff", 542 colorFilename=gdal_file_color_relief_config.name 543 ), 544 addAlpha=True 545 ) 546 gdal_file_color_relief_config.close() 547 return output_file 548 549 def slopeshade_create(self, input_file, output_file): 550 gdal_file_slopeshade_tmp = "/vsimem/tmp_water_depth_slopeshade.tif" 551 gdal_file_slopeshade_config = tempfile.NamedTemporaryFile( 552 mode='w', suffix='txt' 553 ) 554 gdal_file_slopeshade_config.write("0 255 255 255\n") 555 gdal_file_slopeshade_config.write("90 0 0 0\n") 556 gdal_file_slopeshade_config.write("270 0 0 0\n") 557 gdal_file_slopeshade_config.write("360 255 255 255\n") 558 gdal_file_slopeshade_config.flush() 559 gdal.DEMProcessing( 560 gdal_file_slopeshade_tmp, 561 input_file, 562 "slope", 563 options=gdal.DEMProcessingOptions(format="GTiff"), 564 slopeFormat='degree', 565 zeroForFlat=True, 566 addAlpha=True 567 ) 568 gdal.DEMProcessing( 569 output_file, 570 gdal_file_slopeshade_tmp, 571 "color-relief", 572 options=gdal.DEMProcessingOptions( 573 format="GTiff", colorFilename=gdal_file_slopeshade_config.name 574 ), 575 addAlpha=True 576 ) 577 gdal_file_slopeshade_config.close() 578 return output_file 579 580 def merge_color_relief_hillshade( 581 self, input_color_relief_file, input_hillshade_file, output_file 582 ): 583 # dstNodata is a workaround for not working addAlpha in color-relief 584 gdal.Warp( 585 output_file, [input_color_relief_file, input_hillshade_file], 586 options=gdal.WarpOptions( 587 format='GTiff', dstAlpha=False, dstNodata="255 255 255" 588 ) 589 ) 590 return output_file 591 592 def tiles_create( 593 self, input_file, title, tile_size, output_directory, zoom_range 594 ): 595 tile_zoom_option = '{}-{}'.format( 596 zoom_range.minimum(), zoom_range.maximum() 597 ) 598 # using the patched (tilesize) gdal2tiles.py script here, until the upstream version mades it in the distros 599 subprocess.run([ 600 'gdal2tiles-gnuboat.py', '-q', '-w', 'none', 601 '--tilesize={}'.format(tile_size), '-z', tile_zoom_option, '-t', 602 title, input_file, output_directory 603 ], 604 check=True, 605 stdout=subprocess.PIPE, 606 stderr=subprocess.PIPE) 607 608 def move_tiles_in_place(self, source_path, target_path, skip_empty=True): 609 """ 378 610 Moves the generated tiles from the source_path into the target_path. 379 611 It moves file per file, so that the tiles are going to be integrated into an existing folder. … … 381 613 tiles are not moved into target_path. 382 614 """ 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)) 615 copied_empty_tile = False 616 617 src_path = Path(source_path) 618 trg_path = Path(target_path) 619 empty_tile = trg_path.joinpath('empty_tile.png') 620 for path in Path(source_path).rglob('*.png'): 621 # Substract source_path from path and make it relative to 622 # target_path 623 relative = path.relative_to(src_path) 624 relative_path = trg_path.joinpath(relative) 625 if self._tile_is_empty(path) and skip_empty: 626 if not copied_empty_tile: 627 if not empty_tile.parent.exists(): 628 os.makedirs(empty_tile.parent) 629 shutil.copy(path, empty_tile) 630 copied_empty_tile = True 631 else: 632 if not relative_path.parent.exists(): 633 os.makedirs(relative_path.parent) 634 shutil.copy(path, relative_path) 635 636 def _datasource_open(self, source_file): 637 datasource = ogr.Open(source_file) 638 if datasource is None: 639 raise FileNotFoundError( 640 'Could not open input file {}'.format(source_file) 641 ) 642 if datasource.GetLayerCount() < 1: 643 raise ReferenceError('No layers in input file') 644 return datasource 645 646 def _tile_is_empty(self, tile_file_path): 647 is_empty = True 648 colors_tmp = set() 649 colors_tmp_transparent = set() 650 651 img = Image.open(tile_file_path) 652 # calculate histogram for blue channel 653 colors_img = img.getcolors(256) 654 if not colors_img: 655 return False 656 else: 657 for color in colors_img: 658 color_hex = ''.join( 659 '{:02X}'.format(value) for value in color[1] 660 ) 661 if color[1][3] != 0: 662 return False 663 return True 664 665 #def contours_create(): 666 # @todo Cut Tifs / warp 667 #contour_input = gdal.Open(gdal_file, gdalconst.GA_ReadOnly) 668 #contour_input_band = contour_input.GetRasterBand(1) 669 ##Generate layer to save Contourlines in 670 #contour_output = ogr.GetDriverByName("ESRI Shapefile").CreateDataSource(gdal_file_contours) 671 #proj = osr.SpatialReference() 672 #proj.SetWellKnownGeogCS(input_epsg) 673 #for depth in colors: 674 #contour_layer = contour_output.CreateLayer('contour_{}_{}_{}'.format(density_min, density_base, depth), srs = proj) 675 #field_definition = ogr.FieldDefn("ID", ogr.OFTInteger) 676 #contour_layer.CreateField(field_definition) 677 #field_definition = ogr.FieldDefn("elev", ogr.OFTReal) 678 #contour_layer.CreateField(field_definition) 679 ##Generate Contourlines 680 #gdal.ContourGenerate(contour_input_band, depth, 0, [], 0, 0, contour_layer, 0, 1) 681 #contour_output = None 682 #del contour_output 683 #print(" Created contour lines {}".format(gdal_file_contours)) 684 685 #def crop(): 686 # cropping the tifs 687 #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)) -
src/common/tests/test_tilegenerator.py
rda2be70 r7be94aa 32 32 33 33 def compare_lng_lat_bbox(left, right): 34 assert np.isclose(left.east(), right.east(), 10**-7), '{:.7f} != {:.7f} vs. West {} != {}'.format(left.east(), right.east(), left.west(), right.west()) 35 assert np.isclose(left.south(), right.south(), 10**-7), '{:.7f} != {:.7f}'.format(left.south(), right.south()) 36 assert np.isclose(left.west(), right.west(), 10**-7), '{:.7f} != {:.7f}'.format(left.west(), right.west()) 37 assert np.isclose(left.north(), right.north(), 10**-7), '{:.7f} != {:.7f}'.format(left.north(), right.north()) 34 assert np.isclose(left.east(), right.east(), 35 10**-7), '{:.7f} != {:.7f} vs. West {} != {}'.format( 36 left.east(), right.east(), left.west(), right.west() 37 ) 38 assert np.isclose(left.south(), right.south(), 39 10**-7), '{:.7f} != {:.7f}'.format( 40 left.south(), right.south() 41 ) 42 assert np.isclose(left.west(), right.west(), 10**-7 43 ), '{:.7f} != {:.7f}'.format(left.west(), right.west()) 44 assert np.isclose(left.north(), right.north(), 45 10**-7), '{:.7f} != {:.7f}'.format( 46 left.north(), right.north() 47 ) 48 38 49 39 50 @pytest.mark.parametrize( 40 "data, result", 41 [ 42 ({ 'lng_lat_bbox': tilegenerator.LngLatBbox(10.041963, 48.427407, 10.043652, 48.428932), 'zoom_range': tilegenerator.ZoomRange(18, 19)}, 43 tilegenerator.LngLatBbox(10.041504, 48.427378, 10.044250, 48.429200)), 44 ({ 'lng_lat_bbox': tilegenerator.LngLatBbox(10.041963, 48.427407, 10.043652, 48.428932), 'zoom_range': tilegenerator.ZoomRange(14, 19)}, 45 tilegenerator.LngLatBbox(10.041504, 48.414619, 10.063477, 48.429200)), 46 ({ 'lng_lat_bbox': tilegenerator.LngLatBbox(10.041963, 48.427407, 10.043652, 48.428932), 'zoom_range': tilegenerator.ZoomRange(17, 19)}, 47 tilegenerator.LngLatBbox(10.041504, 48.427378, 10.044250, 48.429200)), 48 ({ 'lng_lat_bbox': tilegenerator.LngLatBbox(10.041963, 48.427407, 10.043652, 48.428932), 'zoom_range': tilegenerator.ZoomRange(10, 19)}, 49 tilegenerator.LngLatBbox(9.843750, 48.224673, 10.195312, 48.458352)), 50 ] 51 "data, result", [ 52 ({ 53 'lng_lat_bbox': 54 tilegenerator.LngLatBbox( 55 10.041963, 48.427407, 10.043652, 48.428932 56 ), 57 'zoom_range': 58 tilegenerator.ZoomRange(18, 19) 59 }, 60 tilegenerator.LngLatBbox(10.041504, 48.427378, 10.044250, 48.429200)), 61 ({ 62 'lng_lat_bbox': 63 tilegenerator.LngLatBbox( 64 10.041963, 48.427407, 10.043652, 48.428932 65 ), 66 'zoom_range': 67 tilegenerator.ZoomRange(14, 19) 68 }, 69 tilegenerator.LngLatBbox(10.041504, 48.414619, 10.063477, 48.429200)), 70 ({ 71 'lng_lat_bbox': 72 tilegenerator.LngLatBbox( 73 10.041963, 48.427407, 10.043652, 48.428932 74 ), 75 'zoom_range': 76 tilegenerator.ZoomRange(17, 19) 77 }, 78 tilegenerator.LngLatBbox(10.041504, 48.427378, 10.044250, 48.429200)), 79 ({ 80 'lng_lat_bbox': 81 tilegenerator.LngLatBbox( 82 10.041963, 48.427407, 10.043652, 48.428932 83 ), 84 'zoom_range': 85 tilegenerator.ZoomRange(10, 19) 86 }, tilegenerator.LngLatBbox(9.843750, 48.224673, 10.195312, 87 48.458352)), 88 ] 51 89 ) 52 90 def test_fit_extent_to_tiles(data, result): 53 tilegen = tilegenerator.TileGenerator() 54 tile = tilegen.fit_extent_to_tiles(data['lng_lat_bbox'], data['zoom_range']) 55 compare_lng_lat_bbox(tile, result) 91 tilegen = tilegenerator.TileGenerator() 92 tile = tilegen.fit_extent_to_tiles( 93 data['lng_lat_bbox'], data['zoom_range'] 94 ) 95 compare_lng_lat_bbox(tile, result) 96 56 97 57 98 @pytest.mark.parametrize( 58 "data, result_slices", 59 [ ( 60 { 'tile_sizes': [256], 'zoom_range': tilegenerator.ZoomRange(14, 19), 'file_size': 4 * 1024 * 1024 * 8, 61 'datasource': os.path.join(os.path.dirname(__file__), 'data/slice-log2.csv'), 'layer': 'slice-log2' }, 62 [ tilegenerator.RasterSlice(tilegenerator.LngLatBbox(10.041504, 48.414619, 10.063477, 48.429200), tilegenerator.ZoomRange(14, 16), 256, 1024, 1024), 63 tilegenerator.RasterSlice(tilegenerator.LngLatBbox(10.041504, 48.427378, 10.044250, 48.429200), tilegenerator.ZoomRange(17, 19), 256, 1024, 1024) 64 ] 65 ), 66 ( 67 { 'tile_sizes': [256], 'zoom_range': tilegenerator.ZoomRange(10, 19), 'file_size': 64 * 1024 * 1024 * 8, 68 'datasource': os.path.join(os.path.dirname(__file__), 'data/slice-log2.csv'), 'layer': 'slice-log2' }, 69 [ tilegenerator.RasterSlice(tilegenerator.LngLatBbox(9.843750, 48.224673, 10.195312, 48.458352), tilegenerator.ZoomRange(10, 14), 256, 4096, 4096), 70 tilegenerator.RasterSlice(tilegenerator.LngLatBbox(10.041504, 48.421910, 10.052490, 48.429200), tilegenerator.ZoomRange(15, 19), 256, 4096, 4096) 71 ] 72 ), 73 ( 74 { 'tile_sizes': [512], 'zoom_range': tilegenerator.ZoomRange(10, 19), 'file_size': 256 * 1024 * 1024 * 8, 75 'datasource': os.path.join(os.path.dirname(__file__), 'data/slice-log2.csv'), 'layer': 'slice-log2' }, 76 [ tilegenerator.RasterSlice(tilegenerator.LngLatBbox(9.843750, 48.224673, 10.195312, 48.458352), tilegenerator.ZoomRange(10, 15), 512, 8192, 8192), 77 tilegenerator.RasterSlice(tilegenerator.LngLatBbox(10.041504, 48.421910, 10.052490, 48.429200), tilegenerator.ZoomRange(16, 19), 512, 8192, 8192) 78 ] 79 ), 80 ( 81 { 'tile_sizes': [512], 'zoom_range': tilegenerator.ZoomRange(10, 19), 'file_size': 64 * 1024 * 1024 * 8, 82 'datasource': os.path.join(os.path.dirname(__file__), 'data/slice-log2.csv'), 'layer': 'slice-log2' }, 83 [ tilegenerator.RasterSlice(tilegenerator.LngLatBbox(9.843750, 48.224673, 10.195312, 48.458352), tilegenerator.ZoomRange(10, 13), 512, 4096, 4096), 84 tilegenerator.RasterSlice(tilegenerator.LngLatBbox(10.041504, 48.414619, 10.063477, 48.429200), tilegenerator.ZoomRange(14, 17), 512, 4096, 4096), 85 tilegenerator.RasterSlice(tilegenerator.LngLatBbox(10.041504, 48.428289, 10.042877, 48.429200), tilegenerator.ZoomRange(18, 19), 512, 1024, 1024), 86 tilegenerator.RasterSlice(tilegenerator.LngLatBbox(10.042877, 48.428289, 10.044250, 48.429200), tilegenerator.ZoomRange(18, 19), 512, 1024, 1024), 87 tilegenerator.RasterSlice(tilegenerator.LngLatBbox(10.042877, 48.427378, 10.044250, 48.428289), tilegenerator.ZoomRange(18, 19), 512, 1024, 1024), 88 tilegenerator.RasterSlice(tilegenerator.LngLatBbox(10.041504, 48.427378, 10.042877, 48.428289), tilegenerator.ZoomRange(18, 19), 512, 1024, 1024) 89 ] 90 ), 91 ] 99 "data, result_slices", [ 100 ({ 101 'tile_sizes': [256], 102 'zoom_range': 103 tilegenerator.ZoomRange(14, 19), 104 'file_size': 105 4 * 1024 * 1024 * 8, 106 'datasource': 107 os.path.join(os.path.dirname(__file__), 'data/slice-log2.csv'), 108 'layer': 109 'slice-log2' 110 }, [ 111 tilegenerator.RasterSlice( 112 tilegenerator.LngLatBbox( 113 10.041504, 48.414619, 10.063477, 48.429200 114 ), tilegenerator.ZoomRange(14, 16), 256, 1024, 1024 115 ), 116 tilegenerator.RasterSlice( 117 tilegenerator.LngLatBbox( 118 10.041504, 48.427378, 10.044250, 48.429200 119 ), tilegenerator.ZoomRange(17, 19), 256, 1024, 1024 120 ) 121 ]), 122 ({ 123 'tile_sizes': [256], 124 'zoom_range': 125 tilegenerator.ZoomRange(10, 19), 126 'file_size': 127 64 * 1024 * 1024 * 8, 128 'datasource': 129 os.path.join(os.path.dirname(__file__), 'data/slice-log2.csv'), 130 'layer': 131 'slice-log2' 132 }, [ 133 tilegenerator.RasterSlice( 134 tilegenerator.LngLatBbox( 135 9.843750, 48.224673, 10.195312, 48.458352 136 ), tilegenerator.ZoomRange(10, 14), 256, 4096, 4096 137 ), 138 tilegenerator.RasterSlice( 139 tilegenerator.LngLatBbox( 140 10.041504, 48.421910, 10.052490, 48.429200 141 ), tilegenerator.ZoomRange(15, 19), 256, 4096, 4096 142 ) 143 ]), 144 ({ 145 'tile_sizes': [512], 146 'zoom_range': 147 tilegenerator.ZoomRange(10, 19), 148 'file_size': 149 256 * 1024 * 1024 * 8, 150 'datasource': 151 os.path.join(os.path.dirname(__file__), 'data/slice-log2.csv'), 152 'layer': 153 'slice-log2' 154 }, [ 155 tilegenerator.RasterSlice( 156 tilegenerator.LngLatBbox( 157 9.843750, 48.224673, 10.195312, 48.458352 158 ), tilegenerator.ZoomRange(10, 15), 512, 8192, 8192 159 ), 160 tilegenerator.RasterSlice( 161 tilegenerator.LngLatBbox( 162 10.041504, 48.421910, 10.052490, 48.429200 163 ), tilegenerator.ZoomRange(16, 19), 512, 8192, 8192 164 ) 165 ]), 166 ({ 167 'tile_sizes': [512], 168 'zoom_range': 169 tilegenerator.ZoomRange(10, 19), 170 'file_size': 171 64 * 1024 * 1024 * 8, 172 'datasource': 173 os.path.join(os.path.dirname(__file__), 'data/slice-log2.csv'), 174 'layer': 175 'slice-log2' 176 }, [ 177 tilegenerator.RasterSlice( 178 tilegenerator.LngLatBbox( 179 9.843750, 48.224673, 10.195312, 48.458352 180 ), tilegenerator.ZoomRange(10, 13), 512, 4096, 4096 181 ), 182 tilegenerator.RasterSlice( 183 tilegenerator.LngLatBbox( 184 10.041504, 48.414619, 10.063477, 48.429200 185 ), tilegenerator.ZoomRange(14, 17), 512, 4096, 4096 186 ), 187 tilegenerator.RasterSlice( 188 tilegenerator.LngLatBbox( 189 10.041504, 48.428289, 10.042877, 48.429200 190 ), tilegenerator.ZoomRange(18, 19), 512, 1024, 1024 191 ), 192 tilegenerator.RasterSlice( 193 tilegenerator.LngLatBbox( 194 10.042877, 48.428289, 10.044250, 48.429200 195 ), tilegenerator.ZoomRange(18, 19), 512, 1024, 1024 196 ), 197 tilegenerator.RasterSlice( 198 tilegenerator.LngLatBbox( 199 10.042877, 48.427378, 10.044250, 48.428289 200 ), tilegenerator.ZoomRange(18, 19), 512, 1024, 1024 201 ), 202 tilegenerator.RasterSlice( 203 tilegenerator.LngLatBbox( 204 10.041504, 48.427378, 10.042877, 48.428289 205 ), tilegenerator.ZoomRange(18, 19), 512, 1024, 1024 206 ) 207 ]), 208 ] 92 209 ) 93 210 def test_slicing(data, result_slices): 94 datasource_vrt = os.path.join(os.path.dirname(__file__), 'data/slice-log2.vrt') 95 tilegen = tilegenerator.TileGenerator() 96 slices = tilegen.slices(datasource_vrt, data['zoom_range'], tile_sizes = data['tile_sizes'], raster_file_size_max = data['file_size']) 97 98 assert len(slices) == len(result_slices) 99 for i in range(len(slices)): 100 compare_lng_lat_bbox(slices[i].lng_lat_bbox(), result_slices[i].lng_lat_bbox()) 101 assert slices[i].zoom_range(), result_slices[i].zoom_range() 102 assert slices[i].tile_size(), result_slices[i].tile_size() 103 assert slices[i].grid_width(), result_slices[i].grid_width() 104 assert slices[i].grid_height(), result_slices[i].grid_height() 211 datasource_vrt = os.path.join( 212 os.path.dirname(__file__), 'data/slice-log2.vrt' 213 ) 214 tilegen = tilegenerator.TileGenerator() 215 slices = tilegen.slices( 216 datasource_vrt, 217 data['zoom_range'], 218 tile_sizes=data['tile_sizes'], 219 raster_file_size_max=data['file_size'] 220 ) 221 222 assert len(slices) == len(result_slices) 223 for i in range(len(slices)): 224 compare_lng_lat_bbox( 225 slices[i].lng_lat_bbox(), result_slices[i].lng_lat_bbox() 226 ) 227 assert slices[i].zoom_range(), result_slices[i].zoom_range() 228 assert slices[i].tile_size(), result_slices[i].tile_size() 229 assert slices[i].grid_width(), result_slices[i].grid_width() 230 assert slices[i].grid_height(), result_slices[i].grid_height() 231 105 232 106 233 @pytest.mark.parametrize( 107 "tile_slice", 108 [ 109 ( tilegenerator.RasterSlice(tilegenerator.LngLatBbox(10.041504, 48.428289, 10.042877, 48.429200), tilegenerator.ZoomRange(18, 19), 512, 1024, 1024) ), 110 ( tilegenerator.RasterSlice(tilegenerator.LngLatBbox(9.843750, 48.224673, 10.195312, 48.458352), tilegenerator.ZoomRange(10, 15), 512, 8192, 8192) ) 111 ] 234 "tile_slice", [( 235 tilegenerator.RasterSlice( 236 tilegenerator.LngLatBbox( 237 10.041504, 48.428289, 10.042877, 48.429200 238 ), tilegenerator.ZoomRange(18, 19), 512, 1024, 1024 239 ) 240 ), 241 ( 242 tilegenerator.RasterSlice( 243 tilegenerator.LngLatBbox( 244 9.843750, 48.224673, 10.195312, 48.458352 245 ), tilegenerator.ZoomRange(10, 15), 512, 8192, 8192 246 ) 247 )] 112 248 ) 113 249 def test_rastering(tile_slice): 114 output = tempfile.NamedTemporaryFile(mode='wb', prefix='gnuboat-test', suffix='.tif', delete=False) 115 output.close() 116 output = os.path.join(tempfile.gettempdir(), output.name) 117 118 datasource_vrt = os.path.join(os.path.dirname(__file__), 'data/slice-log2.vrt') 119 120 datasource = ogr.Open(datasource_vrt) 121 source_layer = datasource.GetLayerByIndex(0) 122 source_x_min, source_x_max, source_y_min, source_y_max = source_layer.GetExtent() 123 source_layer_name = source_layer.GetName() 124 lon_metre_max = 60 * 1852 * math.cos(math.radians(min(source_y_min, source_y_max))) # metre / degree 125 lat_metre_max = 111694 # metre / degree 126 circle_radius = math.sqrt(100) / math.pi 127 radius_x = circle_radius / lon_metre_max 128 radius_y = circle_radius / lat_metre_max 129 130 tilegen = tilegenerator.TileGenerator() 131 gridding_algorithm = 'average:radius1={}:radius2={}:angle=0.0:min_points={}:nodata={}'.format(radius_x, radius_y, 10, -999) 132 raster_file = tilegen.raster_create(datasource_vrt, 'slice-log2', tile_slice, gridding_algorithm, output_file=output) 133 134 assert os.path.exists(raster_file) 135 try: 136 datasource_gtiff = gdal.Open(raster_file) 137 assert datasource_gtiff.RasterXSize == tile_slice.grid_width() 138 assert datasource_gtiff.RasterYSize == tile_slice.grid_height() 139 assert datasource_gtiff.RasterCount == 1 140 141 # Top (north) left (west) corner of the image 142 corner = datasource_gtiff.GetGeoTransform() 143 assert np.isclose(corner[0], tile_slice.lng_lat_bbox().west(), 1*10**-7) 144 assert np.isclose(corner[3], tile_slice.lng_lat_bbox().north(), 1*10**-7) 145 146 # Reference system 147 assert 'AUTHORITY["EPSG","4326"]' in datasource_gtiff.GetProjection() 148 finally: 149 os.remove(raster_file) 250 output = tempfile.NamedTemporaryFile( 251 mode='wb', prefix='gnuboat-test', suffix='.tif', delete=False 252 ) 253 output.close() 254 output = os.path.join(tempfile.gettempdir(), output.name) 255 256 datasource_vrt = os.path.join( 257 os.path.dirname(__file__), 'data/slice-log2.vrt' 258 ) 259 260 datasource = ogr.Open(datasource_vrt) 261 source_layer = datasource.GetLayerByIndex(0) 262 source_x_min, source_x_max, source_y_min, source_y_max = source_layer.GetExtent( 263 ) 264 source_layer_name = source_layer.GetName() 265 lon_metre_max = 60 * 1852 * math.cos( 266 math.radians(min(source_y_min, source_y_max)) 267 ) # metre / degree 268 lat_metre_max = 111694 # metre / degree 269 circle_radius = math.sqrt(100) / math.pi 270 radius_x = circle_radius / lon_metre_max 271 radius_y = circle_radius / lat_metre_max 272 273 tilegen = tilegenerator.TileGenerator() 274 gridding_algorithm = 'average:radius1={}:radius2={}:angle=0.0:min_points={}:nodata={}'.format( 275 radius_x, radius_y, 10, -999 276 ) 277 raster_file = tilegen.raster_create( 278 datasource_vrt, 279 'slice-log2', 280 tile_slice, 281 gridding_algorithm, 282 output_file=output 283 ) 284 285 assert os.path.exists(raster_file) 286 try: 287 datasource_gtiff = gdal.Open(raster_file) 288 assert datasource_gtiff.RasterXSize == tile_slice.grid_width() 289 assert datasource_gtiff.RasterYSize == tile_slice.grid_height() 290 assert datasource_gtiff.RasterCount == 1 291 292 # Top (north) left (west) corner of the image 293 corner = datasource_gtiff.GetGeoTransform() 294 assert np.isclose( 295 corner[0], 296 tile_slice.lng_lat_bbox().west(), 1 * 10**-7 297 ) 298 assert np.isclose( 299 corner[3], 300 tile_slice.lng_lat_bbox().north(), 1 * 10**-7 301 ) 302 303 # Reference system 304 assert 'AUTHORITY["EPSG","4326"]' in datasource_gtiff.GetProjection() 305 finally: 306 os.remove(raster_file) 307 150 308 151 309 @pytest.mark.parametrize( 152 "data, result", 153 [ 154 ({ 'tile_slice': tilegenerator.RasterSlice(tilegenerator.LngLatBbox(10.041504, 48.421910, 10.052490, 48.429200), tilegenerator.ZoomRange(15, 19), 256, 4096, 4096), 155 'densities': [10], 156 'density_base': 100, 157 'nodata_value': -999, 158 'skip_empty': True }, 159 { 'result_paths': 1, 160 'files': [ 161 'empty_tile.png', 162 '19/276769/342974.png', 163 '19/276769/342973.png', 164 '19/276769/342972.png', 165 '19/276770/342974.png', 166 '19/276770/342973.png', 167 '19/276770/342972.png', 168 '19/276771/342973.png', 169 '18/138384/171487.png', 170 '18/138384/171486.png', 171 '18/138385/171487.png', 172 '18/138385/171486.png', 173 '17/69192/85743.png', 174 '16/34596/42871.png', 175 '15/17298/21435.png' 176 ]} 177 ), 178 ({ 'tile_slice': tilegenerator.RasterSlice(tilegenerator.LngLatBbox(10.041504, 48.421910, 10.052490, 48.429200), tilegenerator.ZoomRange(15, 19), 512, 16384, 16384), 179 'densities': [10], 180 'density_base': 100, 181 'nodata_value': -999, 182 'skip_empty': True }, 183 { 'result_paths': 1, 184 'files': [ 185 'empty_tile.png', 186 '19/276769/342974.png', 187 '19/276769/342973.png', 188 '19/276769/342972.png', 189 '19/276770/342974.png', 190 '19/276770/342973.png', 191 '19/276770/342972.png', 192 '19/276771/342973.png', 193 '18/138384/171487.png', 194 '18/138384/171486.png', 195 '18/138385/171487.png', 196 '18/138385/171486.png', 197 '17/69192/85743.png', 198 '16/34596/42871.png', 199 '15/17298/21435.png' 200 ]} 201 ) 202 ] 310 "data, result", [({ 311 'tile_slice': 312 tilegenerator.RasterSlice( 313 tilegenerator.LngLatBbox( 314 10.041504, 48.421910, 10.052490, 48.429200 315 ), tilegenerator.ZoomRange(15, 19), 256, 4096, 4096 316 ), 317 'densities': [10], 318 'density_base': 319 100, 320 'nodata_value': 321 -999, 322 'skip_empty': 323 True 324 }, { 325 'result_paths': 326 1, 327 'files': [ 328 'empty_tile.png', '19/276769/342974.png', '19/276769/342973.png', 329 '19/276769/342972.png', '19/276770/342974.png', 330 '19/276770/342973.png', '19/276770/342972.png', 331 '19/276771/342973.png', '18/138384/171487.png', 332 '18/138384/171486.png', '18/138385/171487.png', 333 '18/138385/171486.png', '17/69192/85743.png', '16/34596/42871.png', 334 '15/17298/21435.png' 335 ] 336 }), 337 ({ 338 'tile_slice': 339 tilegenerator.RasterSlice( 340 tilegenerator.LngLatBbox( 341 10.041504, 48.421910, 10.052490, 48.429200 342 ), tilegenerator.ZoomRange(15, 19), 512, 343 16384, 16384 344 ), 345 'densities': [10], 346 'density_base': 347 100, 348 'nodata_value': 349 -999, 350 'skip_empty': 351 True 352 }, { 353 'result_paths': 354 1, 355 'files': [ 356 'empty_tile.png', '19/276769/342974.png', 357 '19/276769/342973.png', '19/276769/342972.png', 358 '19/276770/342974.png', '19/276770/342973.png', 359 '19/276770/342972.png', '19/276771/342973.png', 360 '18/138384/171487.png', '18/138384/171486.png', 361 '18/138385/171487.png', '18/138385/171486.png', 362 '17/69192/85743.png', '16/34596/42871.png', 363 '15/17298/21435.png' 364 ] 365 })] 203 366 ) 204 367 def test_run(data, result): 205 temp_directory = tempfile.mkdtemp(prefix='gnuboat-test_run') 206 temp_directory_target = tempfile.mkdtemp(prefix='gnuboat-test_run') 207 208 datasource_vrt = os.path.join(os.path.dirname(__file__), 'data/slice-log2.vrt') 209 tilegen = tilegenerator.TileGenerator() 210 result_paths = tilegen.run(datasource_vrt, temp_directory, data['tile_slice'], densities = data['densities'], density_base = data['density_base'], nodata_value = data['nodata_value']) 211 try: 212 assert len(result_paths) == result['result_paths'] 213 214 for path in result_paths: 215 tilegen.move_tiles_in_place(path.path, temp_directory_target, data['skip_empty']) 216 for result_file in result['files']: 217 assert os.path.isfile(os.path.join(temp_directory_target, result_file)), 'Tile {} not found in {}'.format(result_file, temp_directory_target) 218 finally: 219 shutil.rmtree(temp_directory) 220 shutil.rmtree(temp_directory_target) 368 temp_directory = tempfile.mkdtemp(prefix='gnuboat-test_run') 369 temp_directory_target = tempfile.mkdtemp(prefix='gnuboat-test_run') 370 371 datasource_vrt = os.path.join( 372 os.path.dirname(__file__), 'data/slice-log2.vrt' 373 ) 374 tilegen = tilegenerator.TileGenerator() 375 result_paths = tilegen.run( 376 datasource_vrt, 377 temp_directory, 378 data['tile_slice'], 379 densities=data['densities'], 380 density_base=data['density_base'], 381 nodata_value=data['nodata_value'] 382 ) 383 try: 384 assert len(result_paths) == result['result_paths'] 385 386 for path in result_paths: 387 tilegen.move_tiles_in_place( 388 path.path, temp_directory_target, data['skip_empty'] 389 ) 390 for result_file in result['files']: 391 assert os.path.isfile( 392 os.path.join(temp_directory_target, result_file) 393 ), 'Tile {} not found in {}'.format( 394 result_file, temp_directory_target 395 ) 396 finally: 397 shutil.rmtree(temp_directory) 398 shutil.rmtree(temp_directory_target)
Note:
See TracChangeset
for help on using the changeset viewer.
