| [ca02e8f] | 1 | #!/usr/bin/python
|
|---|
| 2 | # -*- coding: utf-8 -*-
|
|---|
| 3 | '''
|
|---|
| 4 | Copyright (C) 2018 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 argparse
|
|---|
| 22 | import sys
|
|---|
| [cb89b0e] | 23 | import math
|
|---|
| [ca02e8f] | 24 | import json
|
|---|
| 25 | import csv
|
|---|
| 26 | import xml.etree.ElementTree as ET
|
|---|
| 27 | from osgeo import ogr
|
|---|
| [2eed0da] | 28 | from osgeo import osr
|
|---|
| [cb89b0e] | 29 | from osgeo import gdal
|
|---|
| [2eed0da] | 30 | from osgeo import gdalconst
|
|---|
| 31 | import shutil
|
|---|
| [ca02e8f] | 32 |
|
|---|
| 33 | from gnuboat.datahandler import loghandler, logdataset
|
|---|
| 34 |
|
|---|
| [fbc3d47] | 35 |
|
|---|
| 36 | colors = {
|
|---|
| 37 | 0: "0 0 139",
|
|---|
| 38 | 2: "30 144 255",
|
|---|
| 39 | 6: "173 216 230",
|
|---|
| 40 | 10: "240 248 255"
|
|---|
| 41 | }
|
|---|
| [2eed0da] | 42 | input_epsg = 'EPSG:4326'
|
|---|
| [dbaa7ce] | 43 | target_nodata_value = 0.0
|
|---|
| 44 | target_zoomlevel = 19
|
|---|
| [1c0ee46] | 45 | density_min = 20 # number of points per densitiy_base squaremetres needed to set a value different from nodata
|
|---|
| [dbaa7ce] | 46 | densitiy_base = 100 # squaremetre used as base for density_min
|
|---|
| [fbc3d47] | 47 |
|
|---|
| [ca02e8f] | 48 | class CsvCallback:
|
|---|
| 49 | def __init__(self, output_file):
|
|---|
| 50 | self._output_file = output_file
|
|---|
| 51 | self._stage = None
|
|---|
| 52 |
|
|---|
| 53 | def stage_set(self, stage):
|
|---|
| 54 | self._stage = stage
|
|---|
| 55 |
|
|---|
| 56 | def callback(self, dataset):
|
|---|
| 57 | if self._stage is None:
|
|---|
| 58 | print("No stage set! Skipping dataset...")
|
|---|
| 59 | return
|
|---|
| 60 | # only add points with a water depth set
|
|---|
| 61 | if dataset.water_depth() is None:
|
|---|
| 62 | return
|
|---|
| 63 | water_depth = dataset.water_depth() - self._stage
|
|---|
| [b76295a] | 64 | self._output_file.writerow({"lon": dataset.longitude(), "lat": dataset.latitude(), "water_depth": water_depth})
|
|---|
| [ca02e8f] | 65 |
|
|---|
| [cb89b0e] | 66 | def tile_width(zoomlevel):
|
|---|
| 67 | tile_size = 256
|
|---|
| 68 | tiles = math.sqrt(tile_number(zoomlevel))
|
|---|
| [b76295a] | 69 | return {"tile_size": tile_size, "longitude": 360.0/tiles, "latitude": 180.0/tiles}
|
|---|
| [cb89b0e] | 70 |
|
|---|
| 71 | def tile_number(zoomlevel):
|
|---|
| 72 | return 2**(zoomlevel*2)
|
|---|
| 73 |
|
|---|
| [ca02e8f] | 74 | def main(argv):
|
|---|
| [dbaa7ce] | 75 | global color, input_epsg, target_nodata_value, target_zoomlevel
|
|---|
| [fbc3d47] | 76 |
|
|---|
| [ca02e8f] | 77 | input_file_path = None
|
|---|
| 78 | output_directory = None
|
|---|
| [cb89b0e] | 79 | statistics = False
|
|---|
| [ca02e8f] | 80 |
|
|---|
| 81 | parser = argparse.ArgumentParser(description='Generates the digital terrain model from gnuboat logfiles')
|
|---|
| 82 | parser.add_argument('input_file', metavar='input_file_path', type=str,
|
|---|
| 83 | help='JSON file with logfiles and correction data to be processed')
|
|---|
| 84 | parser.add_argument('output_directory', metavar='output_directory', type=str,
|
|---|
| 85 | help='Write the Digital Terrain Model into this directory (output)')
|
|---|
| [cb89b0e] | 86 | parser.add_argument('-s', '--statistics', dest='statistics', action='store_true',
|
|---|
| 87 | help='Print some statistics of the input and result datasets')
|
|---|
| [1c0ee46] | 88 | parser.add_argument('-p', '--points-min', dest='points_min', type=int,
|
|---|
| 89 | help='Print min points per 100 squaremetre', default=10)
|
|---|
| [ca02e8f] | 90 | arguments = parser.parse_args(argv)
|
|---|
| 91 |
|
|---|
| 92 | if arguments.input_file is None:
|
|---|
| 93 | print('ERROR: No input file specified')
|
|---|
| 94 | sys.exit(2)
|
|---|
| 95 | #elif not os.path.exists(arguments.input_file):
|
|---|
| 96 | print('ERROR: Specified input file does not exists: {}'.format(arguments.input_file))
|
|---|
| 97 | sys.exit(3)
|
|---|
| 98 | else:
|
|---|
| 99 | input_file_path = arguments.input_file
|
|---|
| 100 |
|
|---|
| 101 | if arguments.output_directory is None:
|
|---|
| 102 | print('ERROR: No output file specified')
|
|---|
| 103 | sys.exit(2)
|
|---|
| 104 | else:
|
|---|
| 105 | output_directory = arguments.output_directory
|
|---|
| [cb89b0e] | 106 |
|
|---|
| 107 | if arguments.statistics is not None:
|
|---|
| 108 | statistics = arguments.statistics
|
|---|
| [2eed0da] | 109 |
|
|---|
| [1c0ee46] | 110 | if arguments.points_min is not None:
|
|---|
| 111 | density_min = arguments.points_min
|
|---|
| 112 |
|
|---|
| [2eed0da] | 113 | gdal_file_contours = os.path.join(output_directory, "contours")
|
|---|
| 114 | print("Cleaning up / Preparing output directory")
|
|---|
| 115 | if os.path.exists(output_directory):
|
|---|
| 116 | for root, dirs, files in os.walk(output_directory):
|
|---|
| 117 | for f in files:
|
|---|
| 118 | os.unlink(os.path.join(root, f))
|
|---|
| 119 | for d in dirs:
|
|---|
| 120 | shutil.rmtree(os.path.join(root, d))
|
|---|
| 121 | else:
|
|---|
| 122 | os.makedirs(output_directory)
|
|---|
| 123 | if os.path.exists(gdal_file_contours):
|
|---|
| 124 | shutil.rmtree(gdal_file_contours)
|
|---|
| 125 |
|
|---|
| [ca02e8f] | 126 |
|
|---|
| 127 | with open(input_file_path, 'r') as input_file:
|
|---|
| 128 | logfiles = json.load(input_file)
|
|---|
| 129 |
|
|---|
| [fbc3d47] | 130 | source_data_layer = "tmp_corrected_joined_points"
|
|---|
| 131 | corrected_joined_point_cloud_file_path = os.path.join(output_directory, "{}.csv".format(source_data_layer))
|
|---|
| [ca02e8f] | 132 | try:
|
|---|
| 133 | output_file = open(corrected_joined_point_cloud_file_path, 'w')
|
|---|
| 134 | except IOError as error:
|
|---|
| 135 | print('ERROR: Could not open the output file for the corrected, joined point cloud: {}'.format(error))
|
|---|
| 136 | sys.exit(4)
|
|---|
| 137 | output_file_csv = None
|
|---|
| [b76295a] | 138 | fields = ['lon', 'lat', 'water_depth']
|
|---|
| [cb89b0e] | 139 | output_file_csv = csv.DictWriter(output_file, delimiter=',', quotechar='"',
|
|---|
| [ca02e8f] | 140 | fieldnames=fields)
|
|---|
| 141 | output_file_csv.writeheader()
|
|---|
| 142 | csv_callback = CsvCallback(output_file_csv)
|
|---|
| 143 | log_handler = loghandler.LogHandler()
|
|---|
| 144 |
|
|---|
| 145 | print("Correcting and combining {} log files".format(len(logfiles)))
|
|---|
| 146 | for logfile in logfiles:
|
|---|
| 147 | stage = logfile["stage"]
|
|---|
| 148 | log_file_path = logfile["file"]
|
|---|
| 149 |
|
|---|
| 150 | # building the log file path
|
|---|
| 151 | if not os.path.isabs(log_file_path):
|
|---|
| 152 | log_file_path = "{}/{}".format(os.path.dirname(input_file_path), log_file_path)
|
|---|
| 153 | # check stage
|
|---|
| 154 | try:
|
|---|
| 155 | stage = float(stage)
|
|---|
| 156 | except ValueError:
|
|---|
| 157 | print("Stage is not convertible into float for file {}. Skipping the file".format(log_file_path))
|
|---|
| 158 | continue
|
|---|
| 159 | # parse, correct and append log file
|
|---|
| 160 | csv_callback.stage_set(stage)
|
|---|
| 161 | if not log_handler.gnuboat_read(log_file_path, csv_callback.callback):
|
|---|
| 162 | sys.exit(5)
|
|---|
| 163 |
|
|---|
| 164 | print(" {} correct and joined with stage {}".format(log_file_path, stage))
|
|---|
| 165 | output_file.close()
|
|---|
| 166 |
|
|---|
| [fbc3d47] | 167 | print("Creating output files")
|
|---|
| [ca02e8f] | 168 | # create ogr file info
|
|---|
| [fbc3d47] | 169 | source_xml_file = os.path.join(output_directory, "tmp_ogr_input_file.vrt")
|
|---|
| [ca02e8f] | 170 | try:
|
|---|
| [7b6d348] | 171 | output_file = open(source_xml_file, 'wb')
|
|---|
| [ca02e8f] | 172 | except IOError as error:
|
|---|
| 173 | print('ERROR: Could not open the output file for the ogr data source description: {}'.format(error))
|
|---|
| 174 | sys.exit(4)
|
|---|
| 175 | xml_data_source = ET.Element("OGRVRTDataSource")
|
|---|
| [cb89b0e] | 176 | xml_layer = ET.SubElement(xml_data_source, "OGRVRTLayer", {"name": source_data_layer})
|
|---|
| [ca02e8f] | 177 | xml_source = ET.SubElement(xml_layer, "SrcDataSource")
|
|---|
| 178 | xml_source.text = corrected_joined_point_cloud_file_path
|
|---|
| 179 | xml_geometry_type = ET.SubElement(xml_layer, "GeometryType")
|
|---|
| 180 | xml_geometry_type.text = "wkbPoint"
|
|---|
| 181 | xml_layer_system = ET.SubElement(xml_layer, "LayerSRS")
|
|---|
| [2eed0da] | 182 | xml_layer_system.text = input_epsg
|
|---|
| [b76295a] | 183 | xml_geometry_field = ET.SubElement(xml_layer, "GeometryField", {"encoding": "PointFromColumns", "x": "lon", "y": "lat", "z": "water_depth"})
|
|---|
| [ca02e8f] | 184 | xml_tree = ET.ElementTree(xml_data_source)
|
|---|
| 185 | xml_tree.write(output_file, encoding="UTF-8", xml_declaration=False)
|
|---|
| 186 | output_file.close()
|
|---|
| 187 |
|
|---|
| 188 | # processing data with gdal
|
|---|
| 189 | ogr.UseExceptions()
|
|---|
| [cb89b0e] | 190 | source_data = ogr.Open(source_xml_file)
|
|---|
| 191 | source_layer = source_data.GetLayer(source_data_layer)
|
|---|
| 192 | source_x_min, source_x_max, source_y_min, source_y_max = source_layer.GetExtent()
|
|---|
| 193 |
|
|---|
| [fbc3d47] | 194 | # create the grid data
|
|---|
| 195 | gdal_file = "/vsimem/water_depth.tif"
|
|---|
| [cb89b0e] | 196 | tile_resolution = tile_width(target_zoomlevel)
|
|---|
| [b76295a] | 197 | target_x_res = int(tile_resolution["tile_size"] / tile_resolution["longitude"] * (source_x_max - source_x_min))
|
|---|
| 198 | target_y_res = int(tile_resolution["tile_size"] / tile_resolution["latitude"] * (source_y_max - source_y_min))
|
|---|
| [1c0ee46] | 199 |
|
|---|
| 200 | lon_metre_max = 60 * 1852 * math.cos(math.radians(min(source_y_min, source_y_max))) # metre / degree
|
|---|
| 201 | lat_metre_max = 111694 # metre / degree
|
|---|
| 202 |
|
|---|
| 203 | circle_radius = math.sqrt(densitiy_base) / math.pi
|
|---|
| 204 | radius_x = circle_radius / lon_metre_max
|
|---|
| 205 | radius_y = circle_radius / lat_metre_max
|
|---|
| [dbaa7ce] | 206 | gridding_algorithm = "average:radius1={}:radius2={}:angle=0.0:min_points={}:nodata={}".format(radius_x, radius_y, density_min, target_nodata_value)
|
|---|
| 207 |
|
|---|
| 208 | if statistics:
|
|---|
| 209 | print("Source statistics:")
|
|---|
| [1c0ee46] | 210 | print(" source EPSG: {}".format(input_epsg))
|
|---|
| [dbaa7ce] | 211 | print(" extents (x_min, y_min, x_max, y_max): {}, {}, {}, {}".format(source_x_min, source_y_min, source_x_max, source_y_max))
|
|---|
| [1c0ee46] | 212 | degree_per_pixel_lon = tile_resolution["longitude"] / tile_resolution["tile_size"]
|
|---|
| 213 | degree_per_pixel_lat = tile_resolution["latitude"] / tile_resolution["tile_size"]
|
|---|
| 214 | print(" degree / pixel x and y: {}, {}".format(degree_per_pixel_lon, degree_per_pixel_lat))
|
|---|
| 215 | print(" metre / pixel x and y: {}, {}".format(degree_per_pixel_lon * lon_metre_max, degree_per_pixel_lat * lat_metre_max))
|
|---|
| 216 | print(" Min density per squaredegree: {}".format(density_min * densitiy_base / lon_metre_max / lat_metre_max))
|
|---|
| 217 | print(" Min density per pixel: {}".format(density_min * densitiy_base / (degree_per_pixel_lon * lon_metre_max) / (degree_per_pixel_lat * lat_metre_max)))
|
|---|
| [dbaa7ce] | 218 | print(" gridding algorithm {}".format(gridding_algorithm))
|
|---|
| 219 |
|
|---|
| 220 | grid_options = gdal.GridOptions(
|
|---|
| 221 | outputType = gdal.GDT_Float32,
|
|---|
| 222 | format = "GTiff",
|
|---|
| 223 | width = target_x_res,
|
|---|
| 224 | height = target_y_res,
|
|---|
| 225 | outputSRS = "WGS84",
|
|---|
| 226 | noData = target_nodata_value,
|
|---|
| 227 | layers = source_data_layer,
|
|---|
| 228 | #algorithm = "invdist:power=2.0:smoothing=0.0:radius1=0.0:radius2=0.0:angle=0.0:max_points=0:min_points=0:nodata={}".format(target_nodata_value)
|
|---|
| 229 | algorithm = gridding_algorithm
|
|---|
| 230 | )
|
|---|
| [7b6d348] | 231 | gdal.Grid(gdal_file, source_xml_file, options = grid_options)
|
|---|
| [dbaa7ce] | 232 | print(" Created raster DEM in memory")
|
|---|
| [b76295a] | 233 |
|
|---|
| [6794274] | 234 | # hillshade
|
|---|
| 235 | gdal_file_hillshade = os.path.join(output_directory, "water_depth_hillshade.tif")
|
|---|
| [fbc3d47] | 236 | gdal.DEMProcessing(gdal_file_hillshade, gdal_file, "hillshade", options = gdal.DEMProcessingOptions(format = "GTiff", zFactor = -1))
|
|---|
| 237 | print(" Created hillshade in {}".format(gdal_file_hillshade))
|
|---|
| [ca02e8f] | 238 |
|
|---|
| [fbc3d47] | 239 | # color relief
|
|---|
| 240 | gdal_file_color_relief = os.path.join(output_directory, "water_depth_color_relief.tif")
|
|---|
| 241 | gdal_file_color_relief_config = os.path.join(output_directory, "tmp_water_depth_color_relief_config.txt")
|
|---|
| 242 | with open(gdal_file_color_relief_config, 'w') as color_config:
|
|---|
| 243 | for depth in colors:
|
|---|
| 244 | color_config.write("{} {}\n".format(depth, colors[depth]))
|
|---|
| 245 | gdal.DEMProcessing(gdal_file_color_relief, gdal_file, "color-relief", options = gdal.DEMProcessingOptions(format = "GTiff", colorFilename = gdal_file_color_relief_config))
|
|---|
| 246 | print(" Created color relief in {}".format(gdal_file_color_relief))
|
|---|
| [b76295a] | 247 |
|
|---|
| [fbc3d47] | 248 | # slope shade
|
|---|
| 249 | gdal_file_slope_shade_tmp = "/vsimem/tmp_water_depth_slope_shade.tif"
|
|---|
| 250 | gdal_file_slope_shade = os.path.join(output_directory, "water_depth_slope_shade.tif")
|
|---|
| 251 | gdal_file_slope_shade_config = os.path.join(output_directory, "tmp_water_depth_slope_shade_config.txt")
|
|---|
| 252 | with open(gdal_file_slope_shade_config, 'w') as shade_config:
|
|---|
| 253 | shade_config.write("0 255 255 255\n")
|
|---|
| 254 | shade_config.write("90 0 0 0\n")
|
|---|
| 255 | gdal.DEMProcessing(gdal_file_slope_shade_tmp, gdal_file, "slope", options = gdal.DEMProcessingOptions(format = "GTiff"))
|
|---|
| 256 | gdal.DEMProcessing(gdal_file_slope_shade, gdal_file_slope_shade_tmp, "color-relief", options = gdal.DEMProcessingOptions(format = "GTiff", colorFilename = gdal_file_slope_shade_config))
|
|---|
| 257 | print(" Created slope shade in {}".format(gdal_file_slope_shade))
|
|---|
| [2eed0da] | 258 |
|
|---|
| 259 |
|
|---|
| 260 | # generate contour lines
|
|---|
| 261 | contour_input = gdal.Open(gdal_file, gdalconst.GA_ReadOnly)
|
|---|
| 262 | contour_input_band = contour_input.GetRasterBand(1)
|
|---|
| 263 | #Generate layer to save Contourlines in
|
|---|
| 264 | contour_output = ogr.GetDriverByName("ESRI Shapefile").CreateDataSource(gdal_file_contours)
|
|---|
| 265 | proj = osr.SpatialReference()
|
|---|
| 266 | proj.SetWellKnownGeogCS(input_epsg)
|
|---|
| 267 | for depth in colors:
|
|---|
| 268 | contour_layer = contour_output.CreateLayer('contour-{}'.format(depth), srs = proj)
|
|---|
| 269 | field_definition = ogr.FieldDefn("ID", ogr.OFTInteger)
|
|---|
| 270 | contour_layer.CreateField(field_definition)
|
|---|
| 271 | field_definition = ogr.FieldDefn("elev", ogr.OFTReal)
|
|---|
| 272 | contour_layer.CreateField(field_definition)
|
|---|
| 273 | #Generate Contourlines
|
|---|
| 274 | gdal.ContourGenerate(contour_input_band, depth, 0, [], 0, 0, contour_layer, 0, 1)
|
|---|
| 275 | contour_output = None
|
|---|
| 276 | del contour_output
|
|---|
| [ca02e8f] | 277 |
|
|---|
| 278 | sys.exit(0)
|
|---|
| 279 |
|
|---|
| 280 | if __name__ == "__main__":
|
|---|
| 281 | main(sys.argv[1:])
|
|---|