source: src/common/bin/gnuboat-log-analyser@ 538a9fe

debian/bullseye
Last change on this file since 538a9fe 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
Line 
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
20import os
21import argparse
22import sys
23import math
24import json
25import csv
26import xml.etree.ElementTree as ET
27from osgeo import ogr
28from osgeo import osr
29from osgeo import gdal
30from osgeo import gdalconst
31import shutil
32
33from gnuboat_common.datahandler import loghandler, logdataset
34
35# -999 is a workaround, as long gdal python api does not handle addAlpha
36colors = {
37 -999: "255 255 255",
38 0: "0 0 139",
39 2: "30 144 255",
40 6: "173 216 230",
41 10: "240 248 255"
42}
43input_epsg = 'EPSG:4326'
44target_nodata_value = -999.0
45target_zoomlevel = 19
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
48
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
65 self._output_file.writerow({"lon": dataset.longitude(), "lat": dataset.latitude(), "water_depth": water_depth})
66
67def tile_width(zoomlevel):
68 tile_size = 256
69 tiles = math.sqrt(tile_number(zoomlevel))
70 return {"tile_size": tile_size, "longitude": 360.0/tiles, "latitude": 180.0/tiles}
71
72def tile_number(zoomlevel):
73 return 2**(zoomlevel*2)
74
75def main(argv):
76 global color, input_epsg, target_nodata_value, target_zoomlevel, density_min, density_base
77
78 input_file_path = None
79 output_directory = None
80 statistics = False
81
82 gdal.UseExceptions()
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)')
89 parser.add_argument('-s', '--statistics', dest='statistics', action='store_true',
90 help='Print some statistics of the input and result datasets')
91 parser.add_argument('-p', '--points-min', dest='points_min', type=int,
92 help='Print min points per {} squaremetre'.format(density_base), default=density_min)
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
109
110 if arguments.statistics is not None:
111 statistics = arguments.statistics
112
113 if arguments.points_min is not None:
114 density_min = arguments.points_min
115
116 gdal_file_contours = os.path.join(output_directory, 'contours_{}_{}'.format(density_min, density_base))
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
129
130 with open(input_file_path, 'r') as input_file:
131 logfiles = json.load(input_file)
132
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))
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
141 fields = ['lon', 'lat', 'water_depth']
142 output_file_csv = csv.DictWriter(output_file, delimiter=',', quotechar='"',
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 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():
168 sys.exit(5)
169
170 print(" {} correct and joined with stage {}".format(log_file_path, stage))
171 output_file.close()
172
173 print("Creating output files")
174 # create ogr file info
175 source_xml_file = os.path.join(output_directory, "tmp_ogr_input_file.vrt")
176 try:
177 output_file = open(source_xml_file, 'wb')
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")
182 xml_layer = ET.SubElement(xml_data_source, "OGRVRTLayer", {"name": source_data_layer})
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")
188 xml_layer_system.text = input_epsg
189 xml_geometry_field = ET.SubElement(xml_layer, "GeometryField", {"encoding": "PointFromColumns", "x": "lon", "y": "lat", "z": "water_depth"})
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()
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
200 # create the grid data
201 gdal_file = "/vsimem/water_depth.tif"
202 tile_resolution = tile_width(target_zoomlevel)
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))
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
209 circle_radius = math.sqrt(density_base) / math.pi
210 radius_x = circle_radius / lon_metre_max
211 radius_y = circle_radius / lat_metre_max
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:")
216 print(" source EPSG: {}".format(input_epsg))
217 print(" extents (x_min, y_min, x_max, y_max): {}, {}, {}, {}".format(source_x_min, source_y_min, source_x_max, source_y_max))
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))
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)))
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 )
237 gdal.Grid(gdal_file, source_xml_file, options = grid_options)
238 print(" Created raster Grid in memory")
239
240 # hillshade
241 gdal_file_hillshade = '/vsimem/water_depth_hillshade.tif'
242 gdal.DEMProcessing(gdal_file_hillshade, gdal_file, "hillshade", options = gdal.DEMProcessingOptions(format = "GTiff", zFactor = -1))
243 print(" Created hillshade in memory")
244
245 # color relief
246 gdal_file_color_relief = '/vsimem/water_depth_color_relief.tif'
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]))
251 gdal.DEMProcessing(gdal_file_color_relief, gdal_file, "color-relief", options = gdal.DEMProcessingOptions(format = "GTiff", colorFilename = gdal_file_color_relief_config), addAlpha = True)
252 print(" Created color relief in memory")
253
254 # slopeshade
255 gdal_file_slopeshade = os.path.join(output_directory, "water_depth_slopeshade.tif")
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:
259 shade_config.write("0 255 255 255\n")
260 shade_config.write("90 0 0 0\n")
261 shade_config.write("270 0 0 0\n")
262 shade_config.write("360 255 255 255\n")
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))
266
267
268 # generate contour lines
269 # @todo Cut Tifs / warp
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:
277 contour_layer = contour_output.CreateLayer('contour_{}_{}_{}'.format(density_min, density_base, depth), srs = proj)
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
286
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"))
297
298 # generate tiles
299 tile_zoom_option = "0-19"
300 tile_commands = [
301 #combined
302 {"file": gdal_final_result, "title": 'GNUBoat {} datasets per {} squaremetre'.format(density_min, density_base), "output": 'gnuboat_{}_{}'.format(density_min, density_base)},
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
311 sys.exit(0)
312
313if __name__ == "__main__":
314 main(sys.argv[1:])
Note: See TracBrowser for help on using the repository browser.