| 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 | 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
|
|---|
| 76 |
|
|---|
| 77 | 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}
|
|---|
| 81 |
|
|---|
| 82 | def tile_number(zoomlevel):
|
|---|
| 83 | return 2**(zoomlevel*2)
|
|---|
| 84 |
|
|---|
| 85 | 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)
|
|---|
| 276 |
|
|---|
| 277 | if __name__ == "__main__":
|
|---|
| 278 | main(sys.argv[1:])
|
|---|