source: src/python/bin/gnuboat-log-analyser@ 74c3571

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