source: src/python/bin/gnuboat-log-analyser@ 2eed0da

debian/bullseye
Last change on this file since 2eed0da was 2eed0da, checked in by Joachim Langenbach <joachim.langenbach@…>, 8 years ago
  • Cleaning and or creating output directory at the beginning
  • Creating contours
  • Property mode set to 100644
File size: 9.8 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'
[fbc3d47]43
[ca02e8f]44class CsvCallback:
45 def __init__(self, output_file):
46 self._output_file = output_file
47 self._stage = None
48
49 def stage_set(self, stage):
50 self._stage = stage
51
52 def callback(self, dataset):
53 if self._stage is None:
54 print("No stage set! Skipping dataset...")
55 return
56 # only add points with a water depth set
57 if dataset.water_depth() is None:
58 return
59 water_depth = dataset.water_depth() - self._stage
[b76295a]60 self._output_file.writerow({"lon": dataset.longitude(), "lat": dataset.latitude(), "water_depth": water_depth})
[ca02e8f]61
[cb89b0e]62def tile_width(zoomlevel):
63 tile_size = 256
64 tiles = math.sqrt(tile_number(zoomlevel))
[b76295a]65 return {"tile_size": tile_size, "longitude": 360.0/tiles, "latitude": 180.0/tiles}
[cb89b0e]66
67def tile_number(zoomlevel):
68 return 2**(zoomlevel*2)
69
[ca02e8f]70def main(argv):
[fbc3d47]71 global color
72
[ca02e8f]73 input_file_path = None
74 output_directory = None
[cb89b0e]75 statistics = False
[b76295a]76 target_nodata_value = 0.0
[cb89b0e]77 target_zoomlevel = 18
[ca02e8f]78
79 parser = argparse.ArgumentParser(description='Generates the digital terrain model from gnuboat logfiles')
80 parser.add_argument('input_file', metavar='input_file_path', type=str,
81 help='JSON file with logfiles and correction data to be processed')
82 parser.add_argument('output_directory', metavar='output_directory', type=str,
83 help='Write the Digital Terrain Model into this directory (output)')
[cb89b0e]84 parser.add_argument('-s', '--statistics', dest='statistics', action='store_true',
85 help='Print some statistics of the input and result datasets')
[ca02e8f]86 arguments = parser.parse_args(argv)
87
88 if arguments.input_file is None:
89 print('ERROR: No input file specified')
90 sys.exit(2)
91 #elif not os.path.exists(arguments.input_file):
92 print('ERROR: Specified input file does not exists: {}'.format(arguments.input_file))
93 sys.exit(3)
94 else:
95 input_file_path = arguments.input_file
96
97 if arguments.output_directory is None:
98 print('ERROR: No output file specified')
99 sys.exit(2)
100 else:
101 output_directory = arguments.output_directory
[cb89b0e]102
103 if arguments.statistics is not None:
104 statistics = arguments.statistics
[2eed0da]105
106 gdal_file_contours = os.path.join(output_directory, "contours")
107 print("Cleaning up / Preparing output directory")
108 if os.path.exists(output_directory):
109 for root, dirs, files in os.walk(output_directory):
110 for f in files:
111 os.unlink(os.path.join(root, f))
112 for d in dirs:
113 shutil.rmtree(os.path.join(root, d))
114 else:
115 os.makedirs(output_directory)
116 if os.path.exists(gdal_file_contours):
117 shutil.rmtree(gdal_file_contours)
118
[ca02e8f]119
120 with open(input_file_path, 'r') as input_file:
121 logfiles = json.load(input_file)
122
[fbc3d47]123 source_data_layer = "tmp_corrected_joined_points"
124 corrected_joined_point_cloud_file_path = os.path.join(output_directory, "{}.csv".format(source_data_layer))
[ca02e8f]125 try:
126 output_file = open(corrected_joined_point_cloud_file_path, 'w')
127 except IOError as error:
128 print('ERROR: Could not open the output file for the corrected, joined point cloud: {}'.format(error))
129 sys.exit(4)
130 output_file_csv = None
[b76295a]131 fields = ['lon', 'lat', 'water_depth']
[cb89b0e]132 output_file_csv = csv.DictWriter(output_file, delimiter=',', quotechar='"',
[ca02e8f]133 fieldnames=fields)
134 output_file_csv.writeheader()
135 csv_callback = CsvCallback(output_file_csv)
136 log_handler = loghandler.LogHandler()
137
138 print("Correcting and combining {} log files".format(len(logfiles)))
139 for logfile in logfiles:
140 stage = logfile["stage"]
141 log_file_path = logfile["file"]
142
143 # building the log file path
144 if not os.path.isabs(log_file_path):
145 log_file_path = "{}/{}".format(os.path.dirname(input_file_path), log_file_path)
146 # check stage
147 try:
148 stage = float(stage)
149 except ValueError:
150 print("Stage is not convertible into float for file {}. Skipping the file".format(log_file_path))
151 continue
152 # parse, correct and append log file
153 csv_callback.stage_set(stage)
154 if not log_handler.gnuboat_read(log_file_path, csv_callback.callback):
155 sys.exit(5)
156
157 print(" {} correct and joined with stage {}".format(log_file_path, stage))
158 output_file.close()
159
[fbc3d47]160 print("Creating output files")
[ca02e8f]161 # create ogr file info
[fbc3d47]162 source_xml_file = os.path.join(output_directory, "tmp_ogr_input_file.vrt")
[ca02e8f]163 try:
[7b6d348]164 output_file = open(source_xml_file, 'wb')
[ca02e8f]165 except IOError as error:
166 print('ERROR: Could not open the output file for the ogr data source description: {}'.format(error))
167 sys.exit(4)
168 xml_data_source = ET.Element("OGRVRTDataSource")
[cb89b0e]169 xml_layer = ET.SubElement(xml_data_source, "OGRVRTLayer", {"name": source_data_layer})
[ca02e8f]170 xml_source = ET.SubElement(xml_layer, "SrcDataSource")
171 xml_source.text = corrected_joined_point_cloud_file_path
172 xml_geometry_type = ET.SubElement(xml_layer, "GeometryType")
173 xml_geometry_type.text = "wkbPoint"
174 xml_layer_system = ET.SubElement(xml_layer, "LayerSRS")
[2eed0da]175 xml_layer_system.text = input_epsg
[b76295a]176 xml_geometry_field = ET.SubElement(xml_layer, "GeometryField", {"encoding": "PointFromColumns", "x": "lon", "y": "lat", "z": "water_depth"})
[ca02e8f]177 xml_tree = ET.ElementTree(xml_data_source)
178 xml_tree.write(output_file, encoding="UTF-8", xml_declaration=False)
179 output_file.close()
180
181 # processing data with gdal
182 ogr.UseExceptions()
[cb89b0e]183 source_data = ogr.Open(source_xml_file)
184 source_layer = source_data.GetLayer(source_data_layer)
185 source_x_min, source_x_max, source_y_min, source_y_max = source_layer.GetExtent()
186 if statistics:
187 print("Source statistics:")
188 #print(" projection: {}".format(source_layer.GetProjection())
189 #print(" reference system: {}".format(source_data.GetAttrValue("geocs")))
190 print(" extents (x_min, y_min, x_max, y_max): {}, {}, {}, {}".format(source_x_min, source_y_min, source_x_max, source_y_max))
191
[fbc3d47]192 # create the grid data
193 gdal_file = "/vsimem/water_depth.tif"
[cb89b0e]194 tile_resolution = tile_width(target_zoomlevel)
[b76295a]195 target_x_res = int(tile_resolution["tile_size"] / tile_resolution["longitude"] * (source_x_max - source_x_min))
196 target_y_res = int(tile_resolution["tile_size"] / tile_resolution["latitude"] * (source_y_max - source_y_min))
197 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)
[7b6d348]198 gdal.Grid(gdal_file, source_xml_file, options = grid_options)
[fbc3d47]199 print(" Created raster DEM in {}".format(gdal_file))
[b76295a]200
[6794274]201 # hillshade
202 gdal_file_hillshade = os.path.join(output_directory, "water_depth_hillshade.tif")
[fbc3d47]203 gdal.DEMProcessing(gdal_file_hillshade, gdal_file, "hillshade", options = gdal.DEMProcessingOptions(format = "GTiff", zFactor = -1))
204 print(" Created hillshade in {}".format(gdal_file_hillshade))
[ca02e8f]205
[fbc3d47]206 # color relief
207 gdal_file_color_relief = os.path.join(output_directory, "water_depth_color_relief.tif")
208 gdal_file_color_relief_config = os.path.join(output_directory, "tmp_water_depth_color_relief_config.txt")
209 with open(gdal_file_color_relief_config, 'w') as color_config:
210 for depth in colors:
211 color_config.write("{} {}\n".format(depth, colors[depth]))
212 gdal.DEMProcessing(gdal_file_color_relief, gdal_file, "color-relief", options = gdal.DEMProcessingOptions(format = "GTiff", colorFilename = gdal_file_color_relief_config))
213 print(" Created color relief in {}".format(gdal_file_color_relief))
[b76295a]214
[fbc3d47]215 # slope shade
216 gdal_file_slope_shade_tmp = "/vsimem/tmp_water_depth_slope_shade.tif"
217 gdal_file_slope_shade = os.path.join(output_directory, "water_depth_slope_shade.tif")
218 gdal_file_slope_shade_config = os.path.join(output_directory, "tmp_water_depth_slope_shade_config.txt")
219 with open(gdal_file_slope_shade_config, 'w') as shade_config:
220 shade_config.write("0 255 255 255\n")
221 shade_config.write("90 0 0 0\n")
222 gdal.DEMProcessing(gdal_file_slope_shade_tmp, gdal_file, "slope", options = gdal.DEMProcessingOptions(format = "GTiff"))
223 gdal.DEMProcessing(gdal_file_slope_shade, gdal_file_slope_shade_tmp, "color-relief", options = gdal.DEMProcessingOptions(format = "GTiff", colorFilename = gdal_file_slope_shade_config))
224 print(" Created slope shade in {}".format(gdal_file_slope_shade))
[2eed0da]225
226
227 # generate contour lines
228 contour_input = gdal.Open(gdal_file, gdalconst.GA_ReadOnly)
229 contour_input_band = contour_input.GetRasterBand(1)
230 #Generate layer to save Contourlines in
231 contour_output = ogr.GetDriverByName("ESRI Shapefile").CreateDataSource(gdal_file_contours)
232 proj = osr.SpatialReference()
233 proj.SetWellKnownGeogCS(input_epsg)
234 for depth in colors:
235 contour_layer = contour_output.CreateLayer('contour-{}'.format(depth), srs = proj)
236 field_definition = ogr.FieldDefn("ID", ogr.OFTInteger)
237 contour_layer.CreateField(field_definition)
238 field_definition = ogr.FieldDefn("elev", ogr.OFTReal)
239 contour_layer.CreateField(field_definition)
240 #Generate Contourlines
241 gdal.ContourGenerate(contour_input_band, depth, 0, [], 0, 0, contour_layer, 0, 1)
242 contour_output = None
243 del contour_output
[ca02e8f]244
245 sys.exit(0)
246
247if __name__ == "__main__":
248 main(sys.argv[1:])
Note: See TracBrowser for help on using the repository browser.