source: src/python/bin/gnuboat-log-analyser@ dbaa7ce

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

Started to play with gridding algorithms and implemented rules mentioned in wiki to determine water depth

  • Property mode set to 100644
File size: 10.5 KB
RevLine 
[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
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
[fbc3d47]35
36colors = {
37 0: "0 0 139",
38 2: "30 144 255",
39 6: "173 216 230",
40 10: "240 248 255"
41}
[2eed0da]42input_epsg = 'EPSG:4326'
[dbaa7ce]43target_nodata_value = 0.0
44target_zoomlevel = 19
45density_min = 100 # 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
[fbc3d47]47
[ca02e8f]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
[b76295a]64 self._output_file.writerow({"lon": dataset.longitude(), "lat": dataset.latitude(), "water_depth": water_depth})
[ca02e8f]65
[cb89b0e]66def 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
71def tile_number(zoomlevel):
72 return 2**(zoomlevel*2)
73
[ca02e8f]74def 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')
[ca02e8f]88 arguments = parser.parse_args(argv)
89
90 if arguments.input_file is None:
91 print('ERROR: No input file specified')
92 sys.exit(2)
93 #elif not os.path.exists(arguments.input_file):
94 print('ERROR: Specified input file does not exists: {}'.format(arguments.input_file))
95 sys.exit(3)
96 else:
97 input_file_path = arguments.input_file
98
99 if arguments.output_directory is None:
100 print('ERROR: No output file specified')
101 sys.exit(2)
102 else:
103 output_directory = arguments.output_directory
[cb89b0e]104
105 if arguments.statistics is not None:
106 statistics = arguments.statistics
[2eed0da]107
108 gdal_file_contours = os.path.join(output_directory, "contours")
109 print("Cleaning up / Preparing output directory")
110 if os.path.exists(output_directory):
111 for root, dirs, files in os.walk(output_directory):
112 for f in files:
113 os.unlink(os.path.join(root, f))
114 for d in dirs:
115 shutil.rmtree(os.path.join(root, d))
116 else:
117 os.makedirs(output_directory)
118 if os.path.exists(gdal_file_contours):
119 shutil.rmtree(gdal_file_contours)
120
[ca02e8f]121
122 with open(input_file_path, 'r') as input_file:
123 logfiles = json.load(input_file)
124
[fbc3d47]125 source_data_layer = "tmp_corrected_joined_points"
126 corrected_joined_point_cloud_file_path = os.path.join(output_directory, "{}.csv".format(source_data_layer))
[ca02e8f]127 try:
128 output_file = open(corrected_joined_point_cloud_file_path, 'w')
129 except IOError as error:
130 print('ERROR: Could not open the output file for the corrected, joined point cloud: {}'.format(error))
131 sys.exit(4)
132 output_file_csv = None
[b76295a]133 fields = ['lon', 'lat', 'water_depth']
[cb89b0e]134 output_file_csv = csv.DictWriter(output_file, delimiter=',', quotechar='"',
[ca02e8f]135 fieldnames=fields)
136 output_file_csv.writeheader()
137 csv_callback = CsvCallback(output_file_csv)
138 log_handler = loghandler.LogHandler()
139
140 print("Correcting and combining {} log files".format(len(logfiles)))
141 for logfile in logfiles:
142 stage = logfile["stage"]
143 log_file_path = logfile["file"]
144
145 # building the log file path
146 if not os.path.isabs(log_file_path):
147 log_file_path = "{}/{}".format(os.path.dirname(input_file_path), log_file_path)
148 # check stage
149 try:
150 stage = float(stage)
151 except ValueError:
152 print("Stage is not convertible into float for file {}. Skipping the file".format(log_file_path))
153 continue
154 # parse, correct and append log file
155 csv_callback.stage_set(stage)
156 if not log_handler.gnuboat_read(log_file_path, csv_callback.callback):
157 sys.exit(5)
158
159 print(" {} correct and joined with stage {}".format(log_file_path, stage))
160 output_file.close()
161
[fbc3d47]162 print("Creating output files")
[ca02e8f]163 # create ogr file info
[fbc3d47]164 source_xml_file = os.path.join(output_directory, "tmp_ogr_input_file.vrt")
[ca02e8f]165 try:
[7b6d348]166 output_file = open(source_xml_file, 'wb')
[ca02e8f]167 except IOError as error:
168 print('ERROR: Could not open the output file for the ogr data source description: {}'.format(error))
169 sys.exit(4)
170 xml_data_source = ET.Element("OGRVRTDataSource")
[cb89b0e]171 xml_layer = ET.SubElement(xml_data_source, "OGRVRTLayer", {"name": source_data_layer})
[ca02e8f]172 xml_source = ET.SubElement(xml_layer, "SrcDataSource")
173 xml_source.text = corrected_joined_point_cloud_file_path
174 xml_geometry_type = ET.SubElement(xml_layer, "GeometryType")
175 xml_geometry_type.text = "wkbPoint"
176 xml_layer_system = ET.SubElement(xml_layer, "LayerSRS")
[2eed0da]177 xml_layer_system.text = input_epsg
[b76295a]178 xml_geometry_field = ET.SubElement(xml_layer, "GeometryField", {"encoding": "PointFromColumns", "x": "lon", "y": "lat", "z": "water_depth"})
[ca02e8f]179 xml_tree = ET.ElementTree(xml_data_source)
180 xml_tree.write(output_file, encoding="UTF-8", xml_declaration=False)
181 output_file.close()
182
183 # processing data with gdal
184 ogr.UseExceptions()
[cb89b0e]185 source_data = ogr.Open(source_xml_file)
186 source_layer = source_data.GetLayer(source_data_layer)
187 source_x_min, source_x_max, source_y_min, source_y_max = source_layer.GetExtent()
188
[fbc3d47]189 # create the grid data
190 gdal_file = "/vsimem/water_depth.tif"
[cb89b0e]191 tile_resolution = tile_width(target_zoomlevel)
[b76295a]192 target_x_res = int(tile_resolution["tile_size"] / tile_resolution["longitude"] * (source_x_max - source_x_min))
193 target_y_res = int(tile_resolution["tile_size"] / tile_resolution["latitude"] * (source_y_max - source_y_min))
[dbaa7ce]194 degree_per_metre = 60 * 1852
195 radius_x = math.sqrt(densitiy_base / math.pi) / degree_per_metre
196 radius_y = radius_x
197 gridding_algorithm = "average:radius1={}:radius2={}:angle=0.0:min_points={}:nodata={}".format(radius_x, radius_y, density_min, target_nodata_value)
198
199 if statistics:
200 print("Source statistics:")
201 #print(" projection: {}".format(source_layer.GetProjection())
202 #print(" reference system: {}".format(source_data.GetAttrValue("geocs")))
203 print(" extents (x_min, y_min, x_max, y_max): {}, {}, {}, {}".format(source_x_min, source_y_min, source_x_max, source_y_max))
204 print(" gridding algorithm {}".format(gridding_algorithm))
205
206 grid_options = gdal.GridOptions(
207 outputType = gdal.GDT_Float32,
208 format = "GTiff",
209 width = target_x_res,
210 height = target_y_res,
211 outputSRS = "WGS84",
212 noData = target_nodata_value,
213 layers = source_data_layer,
214 #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)
215 algorithm = gridding_algorithm
216 )
[7b6d348]217 gdal.Grid(gdal_file, source_xml_file, options = grid_options)
[dbaa7ce]218 print(" Created raster DEM in memory")
[b76295a]219
[6794274]220 # hillshade
221 gdal_file_hillshade = os.path.join(output_directory, "water_depth_hillshade.tif")
[fbc3d47]222 gdal.DEMProcessing(gdal_file_hillshade, gdal_file, "hillshade", options = gdal.DEMProcessingOptions(format = "GTiff", zFactor = -1))
223 print(" Created hillshade in {}".format(gdal_file_hillshade))
[ca02e8f]224
[fbc3d47]225 # color relief
226 gdal_file_color_relief = os.path.join(output_directory, "water_depth_color_relief.tif")
227 gdal_file_color_relief_config = os.path.join(output_directory, "tmp_water_depth_color_relief_config.txt")
228 with open(gdal_file_color_relief_config, 'w') as color_config:
229 for depth in colors:
230 color_config.write("{} {}\n".format(depth, colors[depth]))
231 gdal.DEMProcessing(gdal_file_color_relief, gdal_file, "color-relief", options = gdal.DEMProcessingOptions(format = "GTiff", colorFilename = gdal_file_color_relief_config))
232 print(" Created color relief in {}".format(gdal_file_color_relief))
[b76295a]233
[fbc3d47]234 # slope shade
235 gdal_file_slope_shade_tmp = "/vsimem/tmp_water_depth_slope_shade.tif"
236 gdal_file_slope_shade = os.path.join(output_directory, "water_depth_slope_shade.tif")
237 gdal_file_slope_shade_config = os.path.join(output_directory, "tmp_water_depth_slope_shade_config.txt")
238 with open(gdal_file_slope_shade_config, 'w') as shade_config:
239 shade_config.write("0 255 255 255\n")
240 shade_config.write("90 0 0 0\n")
241 gdal.DEMProcessing(gdal_file_slope_shade_tmp, gdal_file, "slope", options = gdal.DEMProcessingOptions(format = "GTiff"))
242 gdal.DEMProcessing(gdal_file_slope_shade, gdal_file_slope_shade_tmp, "color-relief", options = gdal.DEMProcessingOptions(format = "GTiff", colorFilename = gdal_file_slope_shade_config))
243 print(" Created slope shade in {}".format(gdal_file_slope_shade))
[2eed0da]244
245
246 # generate contour lines
247 contour_input = gdal.Open(gdal_file, gdalconst.GA_ReadOnly)
248 contour_input_band = contour_input.GetRasterBand(1)
249 #Generate layer to save Contourlines in
250 contour_output = ogr.GetDriverByName("ESRI Shapefile").CreateDataSource(gdal_file_contours)
251 proj = osr.SpatialReference()
252 proj.SetWellKnownGeogCS(input_epsg)
253 for depth in colors:
254 contour_layer = contour_output.CreateLayer('contour-{}'.format(depth), srs = proj)
255 field_definition = ogr.FieldDefn("ID", ogr.OFTInteger)
256 contour_layer.CreateField(field_definition)
257 field_definition = ogr.FieldDefn("elev", ogr.OFTReal)
258 contour_layer.CreateField(field_definition)
259 #Generate Contourlines
260 gdal.ContourGenerate(contour_input_band, depth, 0, [], 0, 0, contour_layer, 0, 1)
261 contour_output = None
262 del contour_output
[ca02e8f]263
264 sys.exit(0)
265
266if __name__ == "__main__":
267 main(sys.argv[1:])
Note: See TracBrowser for help on using the repository browser.