| 1 | #!/usr/bin/python
|
|---|
| 2 | # -*- coding: utf-8 -*-
|
|---|
| 3 | '''
|
|---|
| 4 | Copyright (C) 2018 - 2020 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.
|
|---|
| 5 |
|
|---|
| 6 | This program is free software: you can redistribute it and/or modify
|
|---|
| 7 | it under the terms of the GNU General Public License as published by
|
|---|
| 8 | the Free Software Foundation, either version 3 of the License, or
|
|---|
| 9 | (at your option) any later version.
|
|---|
| 10 |
|
|---|
| 11 | This program is distributed in the hope that it will be useful,
|
|---|
| 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|---|
| 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|---|
| 14 | GNU General Public License for more details.
|
|---|
| 15 |
|
|---|
| 16 | You should have received a copy of the GNU General Public License
|
|---|
| 17 | along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|---|
| 18 | '''
|
|---|
| 19 |
|
|---|
| 20 | import os
|
|---|
| 21 | import pathlib
|
|---|
| 22 | import argparse
|
|---|
| 23 | import sys
|
|---|
| 24 | import math
|
|---|
| 25 | import json
|
|---|
| 26 | import csv
|
|---|
| 27 | import xml.etree.ElementTree as ET
|
|---|
| 28 | import tempfile
|
|---|
| 29 | from osgeo import ogr
|
|---|
| 30 | from osgeo import osr
|
|---|
| 31 | from osgeo import gdal
|
|---|
| 32 | from osgeo import gdalconst
|
|---|
| 33 | import shutil
|
|---|
| 34 | import progressbar
|
|---|
| 35 | from time import process_time
|
|---|
| 36 |
|
|---|
| 37 | from gnuboat_common.datahandler import loghandler, logdataset
|
|---|
| 38 | from gnuboat_common.spatial import tilegenerator
|
|---|
| 39 |
|
|---|
| 40 | # -999 is a workaround, as long gdal python api does not handle addAlpha
|
|---|
| 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"
|
|---|
| 47 | }
|
|---|
| 48 | input_epsg = 'EPSG:4326'
|
|---|
| 49 | target_nodata_value = -999.0
|
|---|
| 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
|
|---|
| 53 |
|
|---|
| 54 |
|
|---|
| 55 | class CsvCallback:
|
|---|
| 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 |
|
|---|
| 82 |
|
|---|
| 83 | def tile_width(zoomlevel):
|
|---|
| 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 |
|
|---|
| 92 |
|
|---|
| 93 | def tile_number(zoomlevel):
|
|---|
| 94 | return 2**(zoomlevel * 2)
|
|---|
| 95 |
|
|---|
| 96 |
|
|---|
| 97 | def main(argv):
|
|---|
| 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 |
|
|---|
| 412 |
|
|---|
| 413 | if __name__ == "__main__":
|
|---|
| 414 | main(sys.argv[1:])
|
|---|