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

debian/bullseye
Last change on this file since fbc3d47 was fbc3d47, checked in by Joachim Langenbach <joachim.langenbach@…>, 8 years ago
  • Moved DEM to virtual memory file
  • Prefexid all temporary files with tmp_
  • Generating color-relief, hillshade and slope shade
  • Property mode set to 100644
File size: 8.7 KB
Line 
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
23import math
24import json
25import csv
26#import utm
27#import pdal
28import xml.etree.ElementTree as ET
29from osgeo import ogr
30from osgeo import gdal
31
32from gnuboat.datahandler import loghandler, logdataset
33
34
35colors = {
36 0: "0 0 139",
37 2: "30 144 255",
38 6: "173 216 230",
39 10: "240 248 255"
40}
41
42class CsvCallback:
43 def __init__(self, output_file):
44 self._output_file = output_file
45 self._stage = None
46
47 def stage_set(self, stage):
48 self._stage = stage
49
50 def callback(self, dataset):
51 if self._stage is None:
52 print("No stage set! Skipping dataset...")
53 return
54 # only add points with a water depth set
55 if dataset.water_depth() is None:
56 return
57 water_depth = dataset.water_depth() - self._stage
58 self._output_file.writerow({"lon": dataset.longitude(), "lat": dataset.latitude(), "water_depth": water_depth})
59
60def tile_width(zoomlevel):
61 tile_size = 256
62 tiles = math.sqrt(tile_number(zoomlevel))
63 return {"tile_size": tile_size, "longitude": 360.0/tiles, "latitude": 180.0/tiles}
64
65def tile_number(zoomlevel):
66 return 2**(zoomlevel*2)
67
68def main(argv):
69 global color
70
71 input_file_path = None
72 output_directory = None
73 statistics = False
74 target_nodata_value = 0.0
75 target_zoomlevel = 18
76
77 parser = argparse.ArgumentParser(description='Generates the digital terrain model from gnuboat logfiles')
78 parser.add_argument('input_file', metavar='input_file_path', type=str,
79 help='JSON file with logfiles and correction data to be processed')
80 parser.add_argument('output_directory', metavar='output_directory', type=str,
81 help='Write the Digital Terrain Model into this directory (output)')
82 parser.add_argument('-s', '--statistics', dest='statistics', action='store_true',
83 help='Print some statistics of the input and result datasets')
84 arguments = parser.parse_args(argv)
85
86 if arguments.input_file is None:
87 print('ERROR: No input file specified')
88 sys.exit(2)
89 #elif not os.path.exists(arguments.input_file):
90 print('ERROR: Specified input file does not exists: {}'.format(arguments.input_file))
91 sys.exit(3)
92 else:
93 input_file_path = arguments.input_file
94
95 if arguments.output_directory is None:
96 print('ERROR: No output file specified')
97 sys.exit(2)
98 elif not os.path.exists(os.path.dirname(arguments.output_directory)):
99 print('ERROR: Specified directory for output does not exists: {}'.format(arguments.output_directory))
100 sys.exit(3)
101 else:
102 output_directory = arguments.output_directory
103
104 if arguments.statistics is not None:
105 statistics = arguments.statistics
106
107 with open(input_file_path, 'r') as input_file:
108 logfiles = json.load(input_file)
109
110 source_data_layer = "tmp_corrected_joined_points"
111 corrected_joined_point_cloud_file_path = os.path.join(output_directory, "{}.csv".format(source_data_layer))
112 try:
113 output_file = open(corrected_joined_point_cloud_file_path, 'w')
114 except IOError as error:
115 print('ERROR: Could not open the output file for the corrected, joined point cloud: {}'.format(error))
116 sys.exit(4)
117 output_file_csv = None
118 fields = ['lon', 'lat', 'water_depth']
119 output_file_csv = csv.DictWriter(output_file, delimiter=',', quotechar='"',
120 fieldnames=fields)
121 output_file_csv.writeheader()
122 csv_callback = CsvCallback(output_file_csv)
123 log_handler = loghandler.LogHandler()
124
125 print("Correcting and combining {} log files".format(len(logfiles)))
126 for logfile in logfiles:
127 stage = logfile["stage"]
128 log_file_path = logfile["file"]
129
130 # building the log file path
131 if not os.path.isabs(log_file_path):
132 log_file_path = "{}/{}".format(os.path.dirname(input_file_path), log_file_path)
133 # check stage
134 try:
135 stage = float(stage)
136 except ValueError:
137 print("Stage is not convertible into float for file {}. Skipping the file".format(log_file_path))
138 continue
139 # parse, correct and append log file
140 csv_callback.stage_set(stage)
141 if not log_handler.gnuboat_read(log_file_path, csv_callback.callback):
142 sys.exit(5)
143
144 print(" {} correct and joined with stage {}".format(log_file_path, stage))
145 output_file.close()
146
147
148 print("Creating output files")
149 # create ogr file info
150 source_xml_file = os.path.join(output_directory, "tmp_ogr_input_file.vrt")
151 try:
152 output_file = open(source_xml_file, 'wb')
153 except IOError as error:
154 print('ERROR: Could not open the output file for the ogr data source description: {}'.format(error))
155 sys.exit(4)
156 xml_data_source = ET.Element("OGRVRTDataSource")
157 xml_layer = ET.SubElement(xml_data_source, "OGRVRTLayer", {"name": source_data_layer})
158 xml_source = ET.SubElement(xml_layer, "SrcDataSource")
159 xml_source.text = corrected_joined_point_cloud_file_path
160 xml_geometry_type = ET.SubElement(xml_layer, "GeometryType")
161 xml_geometry_type.text = "wkbPoint"
162 xml_layer_system = ET.SubElement(xml_layer, "LayerSRS")
163 xml_layer_system.text = "EPSG:4326"
164 xml_geometry_field = ET.SubElement(xml_layer, "GeometryField", {"encoding": "PointFromColumns", "x": "lon", "y": "lat", "z": "water_depth"})
165 xml_tree = ET.ElementTree(xml_data_source)
166 xml_tree.write(output_file, encoding="UTF-8", xml_declaration=False)
167 output_file.close()
168
169 # processing data with gdal
170 ogr.UseExceptions()
171 source_data = ogr.Open(source_xml_file)
172 source_layer = source_data.GetLayer(source_data_layer)
173 source_x_min, source_x_max, source_y_min, source_y_max = source_layer.GetExtent()
174 if statistics:
175 print("Source statistics:")
176 #print(" projection: {}".format(source_layer.GetProjection())
177 #print(" reference system: {}".format(source_data.GetAttrValue("geocs")))
178 print(" extents (x_min, y_min, x_max, y_max): {}, {}, {}, {}".format(source_x_min, source_y_min, source_x_max, source_y_max))
179
180 # create the grid data
181 gdal_file = "/vsimem/water_depth.tif"
182 tile_resolution = tile_width(target_zoomlevel)
183 target_x_res = int(tile_resolution["tile_size"] / tile_resolution["longitude"] * (source_x_max - source_x_min))
184 target_y_res = int(tile_resolution["tile_size"] / tile_resolution["latitude"] * (source_y_max - source_y_min))
185 grid_options = gdal.GridOptions(outputType = gdal.GDT_Float32, format = "GTiff", width = target_x_res, height = target_y_res, outputSRS = "WGS84", noData = target_nodata_value, layers = source_data_layer)
186 gdal.Grid(gdal_file, source_xml_file, options = grid_options)
187 print(" Created raster DEM in {}".format(gdal_file))
188
189 # hillshade
190 gdal_file_hillshade = os.path.join(output_directory, "water_depth_hillshade.tif")
191 gdal.DEMProcessing(gdal_file_hillshade, gdal_file, "hillshade", options = gdal.DEMProcessingOptions(format = "GTiff", zFactor = -1))
192 print(" Created hillshade in {}".format(gdal_file_hillshade))
193
194 # color relief
195 gdal_file_color_relief = os.path.join(output_directory, "water_depth_color_relief.tif")
196 gdal_file_color_relief_config = os.path.join(output_directory, "tmp_water_depth_color_relief_config.txt")
197 with open(gdal_file_color_relief_config, 'w') as color_config:
198 for depth in colors:
199 color_config.write("{} {}\n".format(depth, colors[depth]))
200 gdal.DEMProcessing(gdal_file_color_relief, gdal_file, "color-relief", options = gdal.DEMProcessingOptions(format = "GTiff", colorFilename = gdal_file_color_relief_config))
201 print(" Created color relief in {}".format(gdal_file_color_relief))
202
203 # slope shade
204 gdal_file_slope_shade_tmp = "/vsimem/tmp_water_depth_slope_shade.tif"
205 gdal_file_slope_shade = os.path.join(output_directory, "water_depth_slope_shade.tif")
206 gdal_file_slope_shade_config = os.path.join(output_directory, "tmp_water_depth_slope_shade_config.txt")
207 with open(gdal_file_slope_shade_config, 'w') as shade_config:
208 shade_config.write("0 255 255 255\n")
209 shade_config.write("90 0 0 0\n")
210 gdal.DEMProcessing(gdal_file_slope_shade_tmp, gdal_file, "slope", options = gdal.DEMProcessingOptions(format = "GTiff"))
211 gdal.DEMProcessing(gdal_file_slope_shade, gdal_file_slope_shade_tmp, "color-relief", options = gdal.DEMProcessingOptions(format = "GTiff", colorFilename = gdal_file_slope_shade_config))
212 print(" Created slope shade in {}".format(gdal_file_slope_shade))
213
214 sys.exit(0)
215
216if __name__ == "__main__":
217 main(sys.argv[1:])
Note: See TracBrowser for help on using the repository browser.