source: src/common/bin/gnuboat-log-analyser@ bd0cb38

debian/bullseye
Last change on this file since bd0cb38 was 9af0638, checked in by Joachim Langenbach <joachim.langenbach@…>, 7 years ago

Created new python gnuboat_common package, with functions used by gnuboat and mapservice

  • Property mode set to 100644
File size: 13.2 KB
RevLine 
[ca02e8f]1#!/usr/bin/python
2# -*- coding: utf-8 -*-
3'''
[9af0638]4 Copyright (C) 2018 - 2020 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
[9af0638]33from gnuboat_common.datahandler import loghandler, logdataset
[ca02e8f]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)
[9af0638]164 result = log_handler.gnuboat_read_file(log_file_path, csv_callback.callback)
165 if result.messages():
166 print('\n'.join(result.errors()))
167 if not result.success():
[ca02e8f]168 sys.exit(5)
169
170 print(" {} correct and joined with stage {}".format(log_file_path, stage))
171 output_file.close()
172
[fbc3d47]173 print("Creating output files")
[ca02e8f]174 # create ogr file info
[fbc3d47]175 source_xml_file = os.path.join(output_directory, "tmp_ogr_input_file.vrt")
[ca02e8f]176 try:
[7b6d348]177 output_file = open(source_xml_file, 'wb')
[ca02e8f]178 except IOError as error:
179 print('ERROR: Could not open the output file for the ogr data source description: {}'.format(error))
180 sys.exit(4)
181 xml_data_source = ET.Element("OGRVRTDataSource")
[cb89b0e]182 xml_layer = ET.SubElement(xml_data_source, "OGRVRTLayer", {"name": source_data_layer})
[ca02e8f]183 xml_source = ET.SubElement(xml_layer, "SrcDataSource")
184 xml_source.text = corrected_joined_point_cloud_file_path
185 xml_geometry_type = ET.SubElement(xml_layer, "GeometryType")
186 xml_geometry_type.text = "wkbPoint"
187 xml_layer_system = ET.SubElement(xml_layer, "LayerSRS")
[2eed0da]188 xml_layer_system.text = input_epsg
[b76295a]189 xml_geometry_field = ET.SubElement(xml_layer, "GeometryField", {"encoding": "PointFromColumns", "x": "lon", "y": "lat", "z": "water_depth"})
[ca02e8f]190 xml_tree = ET.ElementTree(xml_data_source)
191 xml_tree.write(output_file, encoding="UTF-8", xml_declaration=False)
192 output_file.close()
193
194 # processing data with gdal
195 ogr.UseExceptions()
[cb89b0e]196 source_data = ogr.Open(source_xml_file)
197 source_layer = source_data.GetLayer(source_data_layer)
198 source_x_min, source_x_max, source_y_min, source_y_max = source_layer.GetExtent()
199
[fbc3d47]200 # create the grid data
201 gdal_file = "/vsimem/water_depth.tif"
[cb89b0e]202 tile_resolution = tile_width(target_zoomlevel)
[b76295a]203 target_x_res = int(tile_resolution["tile_size"] / tile_resolution["longitude"] * (source_x_max - source_x_min))
204 target_y_res = int(tile_resolution["tile_size"] / tile_resolution["latitude"] * (source_y_max - source_y_min))
[1c0ee46]205
206 lon_metre_max = 60 * 1852 * math.cos(math.radians(min(source_y_min, source_y_max))) # metre / degree
207 lat_metre_max = 111694 # metre / degree
208
[c5b13e1]209 circle_radius = math.sqrt(density_base) / math.pi
[1c0ee46]210 radius_x = circle_radius / lon_metre_max
211 radius_y = circle_radius / lat_metre_max
[dbaa7ce]212 gridding_algorithm = "average:radius1={}:radius2={}:angle=0.0:min_points={}:nodata={}".format(radius_x, radius_y, density_min, target_nodata_value)
213
214 if statistics:
215 print("Source statistics:")
[1c0ee46]216 print(" source EPSG: {}".format(input_epsg))
[dbaa7ce]217 print(" extents (x_min, y_min, x_max, y_max): {}, {}, {}, {}".format(source_x_min, source_y_min, source_x_max, source_y_max))
[1c0ee46]218 degree_per_pixel_lon = tile_resolution["longitude"] / tile_resolution["tile_size"]
219 degree_per_pixel_lat = tile_resolution["latitude"] / tile_resolution["tile_size"]
220 print(" degree / pixel x and y: {}, {}".format(degree_per_pixel_lon, degree_per_pixel_lat))
221 print(" metre / pixel x and y: {}, {}".format(degree_per_pixel_lon * lon_metre_max, degree_per_pixel_lat * lat_metre_max))
[c5b13e1]222 print(" Min density per squaredegree: {}".format(density_min * density_base / lon_metre_max / lat_metre_max))
223 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]224 print(" gridding algorithm {}".format(gridding_algorithm))
225
226 grid_options = gdal.GridOptions(
227 outputType = gdal.GDT_Float32,
228 format = "GTiff",
229 width = target_x_res,
230 height = target_y_res,
231 outputSRS = "WGS84",
232 noData = target_nodata_value,
233 layers = source_data_layer,
234 #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)
235 algorithm = gridding_algorithm
236 )
[7b6d348]237 gdal.Grid(gdal_file, source_xml_file, options = grid_options)
[c5b13e1]238 print(" Created raster Grid in memory")
[b76295a]239
[6794274]240 # hillshade
[c5b13e1]241 gdal_file_hillshade = '/vsimem/water_depth_hillshade.tif'
[fbc3d47]242 gdal.DEMProcessing(gdal_file_hillshade, gdal_file, "hillshade", options = gdal.DEMProcessingOptions(format = "GTiff", zFactor = -1))
[c5b13e1]243 print(" Created hillshade in memory")
[ca02e8f]244
[fbc3d47]245 # color relief
[c5b13e1]246 gdal_file_color_relief = '/vsimem/water_depth_color_relief.tif'
[fbc3d47]247 gdal_file_color_relief_config = os.path.join(output_directory, "tmp_water_depth_color_relief_config.txt")
248 with open(gdal_file_color_relief_config, 'w') as color_config:
249 for depth in colors:
250 color_config.write("{} {}\n".format(depth, colors[depth]))
[403e4ed]251 gdal.DEMProcessing(gdal_file_color_relief, gdal_file, "color-relief", options = gdal.DEMProcessingOptions(format = "GTiff", colorFilename = gdal_file_color_relief_config), addAlpha = True)
[c5b13e1]252 print(" Created color relief in memory")
[b76295a]253
[26d66d8]254 # slopeshade
[c5b13e1]255 gdal_file_slopeshade = os.path.join(output_directory, "water_depth_slopeshade.tif")
[403e4ed]256 gdal_file_slopeshade_tmp = "/vsimem/tmp_water_depth_slopeshade.tif"
257 gdal_file_slopeshade_config = os.path.join(output_directory, "tmp_water_depth_slopeshade_config.txt")
258 with open(gdal_file_slopeshade_config, 'w') as shade_config:
[fbc3d47]259 shade_config.write("0 255 255 255\n")
260 shade_config.write("90 0 0 0\n")
[c5b13e1]261 shade_config.write("270 0 0 0\n")
262 shade_config.write("360 255 255 255\n")
[403e4ed]263 gdal.DEMProcessing(gdal_file_slopeshade_tmp, gdal_file, "slope", options = gdal.DEMProcessingOptions(format = "GTiff"), slopeFormat = 'degree', zeroForFlat = True, addAlpha = True)
264 gdal.DEMProcessing(gdal_file_slopeshade, gdal_file_slopeshade_tmp, "color-relief", options = gdal.DEMProcessingOptions(format = "GTiff", colorFilename = gdal_file_slopeshade_config), addAlpha = True)
265 print(" Created slope shade in {}".format(gdal_file_slopeshade))
[2eed0da]266
267
268 # generate contour lines
[403e4ed]269 # @todo Cut Tifs / warp
[2eed0da]270 contour_input = gdal.Open(gdal_file, gdalconst.GA_ReadOnly)
271 contour_input_band = contour_input.GetRasterBand(1)
272 #Generate layer to save Contourlines in
273 contour_output = ogr.GetDriverByName("ESRI Shapefile").CreateDataSource(gdal_file_contours)
274 proj = osr.SpatialReference()
275 proj.SetWellKnownGeogCS(input_epsg)
276 for depth in colors:
[c5b13e1]277 contour_layer = contour_output.CreateLayer('contour_{}_{}_{}'.format(density_min, density_base, depth), srs = proj)
[2eed0da]278 field_definition = ogr.FieldDefn("ID", ogr.OFTInteger)
279 contour_layer.CreateField(field_definition)
280 field_definition = ogr.FieldDefn("elev", ogr.OFTReal)
281 contour_layer.CreateField(field_definition)
282 #Generate Contourlines
283 gdal.ContourGenerate(contour_input_band, depth, 0, [], 0, 0, contour_layer, 0, 1)
284 contour_output = None
285 del contour_output
[403e4ed]286
[c5b13e1]287 # combining hillshade and color relief
288
289
290 # cropping the tifs
291 #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))
292
293 # dstNodata is a workaround for not working addAlpha in color-relief
294 gdal_final_result = '/tmp/gnuboat/water_depth_{}_{}.tif'.format(density_min, density_base)
295 gdal_color_relief_alpha_tmp = '/vsimem/tmp_color_relief.tif'
296 gdal.Warp(gdal_final_result, [gdal_file_color_relief, gdal_file_hillshade], options = gdal.WarpOptions(format = 'GTiff', dstAlpha = False, dstNodata = "255 255 255"))
[ca02e8f]297
[26d66d8]298 # generate tiles
299 tile_zoom_option = "0-19"
300 tile_commands = [
[c5b13e1]301 #combined
302 {"file": gdal_final_result, "title": 'GNUBoat {} datasets per {} squaremetre'.format(density_min, density_base), "output": 'gnuboat_{}_{}'.format(density_min, density_base)},
[26d66d8]303 ]
304 print("Expanding {} tifs to tiles".format(len(tile_commands)))
305 for tile_command in tile_commands:
306 title = tile_command["title"]
307 output = os.path.join(output_directory, tile_command["output"])
308 os.system('gdal2tiles.py -q -w none -z {} -t "GNUBoat {}" {} {}'.format(tile_zoom_option, title, tile_command["file"], output))
309 print(" Created tiles for {} in {}".format(title, output))
310
[ca02e8f]311 sys.exit(0)
312
313if __name__ == "__main__":
314 main(sys.argv[1:])
Note: See TracBrowser for help on using the repository browser.