source: src/python/bin/gnuboat-log-analyser@ 26d66d8

debian/bullseye
Last change on this file since 26d66d8 was 26d66d8, checked in by Joachim Langenbach <joachim.langenbach@…>, 8 years ago

Extended log-analyser to create tiles

  • Property mode set to 100644
File size: 12.2 KB
Line 
1#!/usr/bin/python
2# -*- coding: utf-8 -*-
3'''
4 Copyright (C) 2018 - 2019 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.datahandler import loghandler, logdataset
34
35
36colors = {
37 0: "0 0 139",
38 2: "30 144 255",
39 6: "173 216 230",
40 10: "240 248 255"
41}
42input_epsg = 'EPSG:4326'
43target_nodata_value = 0.0
44target_zoomlevel = 19
45density_min = 20 # number of points per densitiy_base squaremetres needed to set a value different from nodata
46densitiy_base = 100 # squaremetre used as base for density_min
47
48class 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
64 self._output_file.writerow({"lon": dataset.longitude(), "lat": dataset.latitude(), "water_depth": water_depth})
65
66def tile_width(zoomlevel):
67 tile_size = 256
68 tiles = math.sqrt(tile_number(zoomlevel))
69 return {"tile_size": tile_size, "longitude": 360.0/tiles, "latitude": 180.0/tiles}
70
71def tile_number(zoomlevel):
72 return 2**(zoomlevel*2)
73
74def main(argv):
75 global color, input_epsg, target_nodata_value, target_zoomlevel
76
77 input_file_path = None
78 output_directory = None
79 statistics = False
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)')
86 parser.add_argument('-s', '--statistics', dest='statistics', action='store_true',
87 help='Print some statistics of the input and result datasets')
88 parser.add_argument('-p', '--points-min', dest='points_min', type=int,
89 help='Print min points per 100 squaremetre', default=10)
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
106
107 if arguments.statistics is not None:
108 statistics = arguments.statistics
109
110 if arguments.points_min is not None:
111 density_min = arguments.points_min
112
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
126
127 with open(input_file_path, 'r') as input_file:
128 logfiles = json.load(input_file)
129
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))
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
138 fields = ['lon', 'lat', 'water_depth']
139 output_file_csv = csv.DictWriter(output_file, delimiter=',', quotechar='"',
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
167 print("Creating output files")
168 # create ogr file info
169 source_xml_file = os.path.join(output_directory, "tmp_ogr_input_file.vrt")
170 try:
171 output_file = open(source_xml_file, 'wb')
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")
176 xml_layer = ET.SubElement(xml_data_source, "OGRVRTLayer", {"name": source_data_layer})
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")
182 xml_layer_system.text = input_epsg
183 xml_geometry_field = ET.SubElement(xml_layer, "GeometryField", {"encoding": "PointFromColumns", "x": "lon", "y": "lat", "z": "water_depth"})
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()
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
194 # create the grid data
195 gdal_file = "/vsimem/water_depth.tif"
196 tile_resolution = tile_width(target_zoomlevel)
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))
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
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:")
210 print(" source EPSG: {}".format(input_epsg))
211 print(" extents (x_min, y_min, x_max, y_max): {}, {}, {}, {}".format(source_x_min, source_y_min, source_x_max, source_y_max))
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)))
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 )
231 gdal.Grid(gdal_file, source_xml_file, options = grid_options)
232 print(" Created raster DEM in memory")
233
234 # hillshade
235 gdal_file_hillshade = os.path.join(output_directory, "water_depth_hillshade.tif")
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))
238
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))
247
248 # slopeshade
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))
258
259
260 # generate contour lines
261 # @todo not useful in this configuration!
262 contour_input = gdal.Open(gdal_file, gdalconst.GA_ReadOnly)
263 contour_input_band = contour_input.GetRasterBand(1)
264 #Generate layer to save Contourlines in
265 contour_output = ogr.GetDriverByName("ESRI Shapefile").CreateDataSource(gdal_file_contours)
266 proj = osr.SpatialReference()
267 proj.SetWellKnownGeogCS(input_epsg)
268 for depth in colors:
269 contour_layer = contour_output.CreateLayer('contour-{}'.format(depth), srs = proj)
270 field_definition = ogr.FieldDefn("ID", ogr.OFTInteger)
271 contour_layer.CreateField(field_definition)
272 field_definition = ogr.FieldDefn("elev", ogr.OFTReal)
273 contour_layer.CreateField(field_definition)
274 #Generate Contourlines
275 gdal.ContourGenerate(contour_input_band, depth, 0, [], 0, 0, contour_layer, 0, 1)
276 contour_output = None
277 del contour_output
278
279 # generate tiles
280 tile_zoom_option = "0-19"
281 tile_commands = [
282 #hillshade
283 {"file": gdal_file_hillshade, "title": 'Hillshade', "output": 'hillshade'},
284 #color relief
285 {"file": gdal_file_color_relief, "title": 'Color relief', "output": 'color_relief'},
286 #slopeshade
287 {"file": gdal_file_slope_shade, "title": 'Slopeshade', "output": 'slopeshade'}
288 ]
289 print("Expanding {} tifs to tiles".format(len(tile_commands)))
290 for tile_command in tile_commands:
291 title = tile_command["title"]
292 output = os.path.join(output_directory, tile_command["output"])
293 os.system('gdal2tiles.py -q -w none -z {} -t "GNUBoat {}" {} {}'.format(tile_zoom_option, title, tile_command["file"], output))
294 print(" Created tiles for {} in {}".format(title, output))
295
296 sys.exit(0)
297
298if __name__ == "__main__":
299 main(sys.argv[1:])
Note: See TracBrowser for help on using the repository browser.