source: src/common/bin/gnuboat-log-analyser@ 5e16955

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

First version of a working log processing task

  • Property mode set to 100644
File size: 9.8 KB
RevLine 
[ca02e8f]1#!/usr/bin/python
2# -*- coding: utf-8 -*-
3'''
[9af0638]4 Copyright (C) 2018 - 2020 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.
[ca02e8f]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
[5e16955]21import pathlib
[ca02e8f]22import argparse
23import sys
[cb89b0e]24import math
[ca02e8f]25import json
26import csv
27import xml.etree.ElementTree as ET
[5e16955]28import tempfile
[ca02e8f]29from osgeo import ogr
[2eed0da]30from osgeo import osr
[cb89b0e]31from osgeo import gdal
[2eed0da]32from osgeo import gdalconst
33import shutil
[5e16955]34import progressbar
35from time import process_time
[ca02e8f]36
[9af0638]37from gnuboat_common.datahandler import loghandler, logdataset
[9f5877d]38from gnuboat_common.spatial import tilegenerator
[ca02e8f]39
[c5b13e1]40# -999 is a workaround, as long gdal python api does not handle addAlpha
[fbc3d47]41colors = {
[c5b13e1]42 -999: "255 255 255",
[fbc3d47]43 0: "0 0 139",
44 2: "30 144 255",
45 6: "173 216 230",
46 10: "240 248 255"
47}
[2eed0da]48input_epsg = 'EPSG:4326'
[c5b13e1]49target_nodata_value = -999.0
[dbaa7ce]50target_zoomlevel = 19
[c5b13e1]51density_min = 10 # number of points per density_base squaremetres needed to set a value different from nodata
52density_base = 100 # squaremetre used as base for density_min
[fbc3d47]53
[ca02e8f]54class CsvCallback:
55 def __init__(self, output_file):
56 self._output_file = output_file
57 self._stage = None
[5e16955]58 self._resultsets = 0
59
60 def count(self):
61 return self._resultsets
[ca02e8f]62
63 def stage_set(self, stage):
64 self._stage = stage
65
66 def callback(self, dataset):
67 if self._stage is None:
68 print("No stage set! Skipping dataset...")
69 return
70 # only add points with a water depth set
71 if dataset.water_depth() is None:
72 return
73 water_depth = dataset.water_depth() - self._stage
[b76295a]74 self._output_file.writerow({"lon": dataset.longitude(), "lat": dataset.latitude(), "water_depth": water_depth})
[5e16955]75 self._resultsets += 1
[ca02e8f]76
[cb89b0e]77def tile_width(zoomlevel):
78 tile_size = 256
79 tiles = math.sqrt(tile_number(zoomlevel))
[b76295a]80 return {"tile_size": tile_size, "longitude": 360.0/tiles, "latitude": 180.0/tiles}
[cb89b0e]81
82def tile_number(zoomlevel):
83 return 2**(zoomlevel*2)
84
[ca02e8f]85def main(argv):
[c5b13e1]86 global color, input_epsg, target_nodata_value, target_zoomlevel, density_min, density_base
[fbc3d47]87
[ca02e8f]88 input_file_path = None
89 output_directory = None
[cb89b0e]90 statistics = False
[5e16955]91 tile_sizes = [256]
[c5b13e1]92
93 gdal.UseExceptions()
[ca02e8f]94
95 parser = argparse.ArgumentParser(description='Generates the digital terrain model from gnuboat logfiles')
96 parser.add_argument('input_file', metavar='input_file_path', type=str,
97 help='JSON file with logfiles and correction data to be processed')
98 parser.add_argument('output_directory', metavar='output_directory', type=str,
99 help='Write the Digital Terrain Model into this directory (output)')
[5e16955]100 parser.add_argument('-v', '--statistics', dest='statistics', action='store_true',
101 help='Print some statistics of the input and result datasets')
102 parser.add_argument('-p', '--points-min', dest='points_min', type=int, default=density_min,
103 help='Minimum points per {} squaremetre is needed to create a valid depth information'.format(density_base))
104 parser.add_argument('-z', '--zoomlevels', dest='zoom_range', nargs=2, default=[10, 19], type=int,
105 help='Creates tiles for the specified range of zoomlevels')
106 parser.add_argument('--high-res', dest='high_res', action='store_true',
107 help='Creates tiles with 512 pixel per tile additionally to the 256 pixel per tile tiles')
108 parser.add_argument('-m', '--raster_file_max', dest='raster_file_size_max', default=1024, type=int,
109 help='Maximum size of temporary raster Tifs for tile generation in MB')
[ca02e8f]110 arguments = parser.parse_args(argv)
111
112 if arguments.input_file is None:
113 print('ERROR: No input file specified')
114 sys.exit(2)
[5e16955]115 elif not os.path.exists(arguments.input_file):
[ca02e8f]116 print('ERROR: Specified input file does not exists: {}'.format(arguments.input_file))
117 sys.exit(3)
118 else:
119 input_file_path = arguments.input_file
120
121 if arguments.output_directory is None:
122 print('ERROR: No output file specified')
123 sys.exit(2)
124 else:
125 output_directory = arguments.output_directory
[cb89b0e]126
127 if arguments.statistics is not None:
128 statistics = arguments.statistics
[2eed0da]129
[1c0ee46]130 if arguments.points_min is not None:
131 density_min = arguments.points_min
[2eed0da]132
[5e16955]133 if arguments.zoom_range is not None:
134 zoom_range = arguments.zoom_range
135
136 if arguments.high_res is not None:
137 tile_sizes.append(512)
138
139 if arguments.raster_file_size_max is not None:
140 raster_file_size_max = arguments.raster_file_size_max
141
142 # create temporary directory
143 temp_directory = tempfile.mkdtemp(prefix='gnuboat-log-analyser')
[ca02e8f]144
145 with open(input_file_path, 'r') as input_file:
146 logfiles = json.load(input_file)
147
[fbc3d47]148 source_data_layer = "tmp_corrected_joined_points"
[5e16955]149 corrected_joined_point_cloud_file_path = os.path.join(temp_directory, "{}.csv".format(source_data_layer))
[ca02e8f]150 try:
151 output_file = open(corrected_joined_point_cloud_file_path, 'w')
152 except IOError as error:
153 print('ERROR: Could not open the output file for the corrected, joined point cloud: {}'.format(error))
154 sys.exit(4)
155 output_file_csv = None
[b76295a]156 fields = ['lon', 'lat', 'water_depth']
[cb89b0e]157 output_file_csv = csv.DictWriter(output_file, delimiter=',', quotechar='"',
[ca02e8f]158 fieldnames=fields)
159 output_file_csv.writeheader()
160 csv_callback = CsvCallback(output_file_csv)
161 log_handler = loghandler.LogHandler()
162
163 print("Correcting and combining {} log files".format(len(logfiles)))
164 for logfile in logfiles:
[5e16955]165 gaugeHeight = logfile["gaugeHeight"]
166 referenceWaterLevelGaugeHeight = logfile["referenceWaterLevelGaugeHeight"]
[ca02e8f]167 log_file_path = logfile["file"]
168
169 # building the log file path
170 if not os.path.isabs(log_file_path):
171 log_file_path = "{}/{}".format(os.path.dirname(input_file_path), log_file_path)
172 # check stage
173 try:
[5e16955]174 gaugeHeight = float(gaugeHeight)
[ca02e8f]175 except ValueError:
[5e16955]176 print("gaugeHeight is not convertible into float for file {}. Skipping the file".format(log_file_path))
177 continue
178 try:
179 referenceWaterLevelGaugeHeight = float(referenceWaterLevelGaugeHeight)
180 except ValueError:
181 print("referenceWaterLevelGaugeHeight is not convertible into float for file {}. Skipping the file".format(log_file_path))
[ca02e8f]182 continue
183 # parse, correct and append log file
[5e16955]184 difference = referenceWaterLevelGaugeHeight - gaugeHeight
185 csv_callback.stage_set(difference)
[9af0638]186 result = log_handler.gnuboat_read_file(log_file_path, csv_callback.callback)
187 if result.messages():
188 print('\n'.join(result.errors()))
189 if not result.success():
[ca02e8f]190 sys.exit(5)
191
[5e16955]192 print(" {} correct and joined with difference {:.3f}m".format(log_file_path, difference))
[ca02e8f]193 output_file.close()
[5e16955]194 print (' Processed {} points'.format(csv_callback.count()))
[ca02e8f]195
[5e16955]196 print("Generating tiles")
[ca02e8f]197 # create ogr file info
[5e16955]198 source_xml_file = os.path.join(temp_directory, "tmp_ogr_input_file.vrt")
[ca02e8f]199 try:
[7b6d348]200 output_file = open(source_xml_file, 'wb')
[ca02e8f]201 except IOError as error:
202 print('ERROR: Could not open the output file for the ogr data source description: {}'.format(error))
203 sys.exit(4)
204 xml_data_source = ET.Element("OGRVRTDataSource")
[cb89b0e]205 xml_layer = ET.SubElement(xml_data_source, "OGRVRTLayer", {"name": source_data_layer})
[ca02e8f]206 xml_source = ET.SubElement(xml_layer, "SrcDataSource")
207 xml_source.text = corrected_joined_point_cloud_file_path
208 xml_geometry_type = ET.SubElement(xml_layer, "GeometryType")
209 xml_geometry_type.text = "wkbPoint"
210 xml_layer_system = ET.SubElement(xml_layer, "LayerSRS")
[2eed0da]211 xml_layer_system.text = input_epsg
[b76295a]212 xml_geometry_field = ET.SubElement(xml_layer, "GeometryField", {"encoding": "PointFromColumns", "x": "lon", "y": "lat", "z": "water_depth"})
[ca02e8f]213 xml_tree = ET.ElementTree(xml_data_source)
214 xml_tree.write(output_file, encoding="UTF-8", xml_declaration=False)
215 output_file.close()
[5e16955]216
217 # preparing output_directory
218 if os.path.exists(output_directory):
219 for root, dirs, files in os.walk(output_directory):
220 for f in files:
221 os.unlink(os.path.join(root, f))
222 for d in dirs:
223 shutil.rmtree(os.path.join(root, d))
224 else:
225 os.makedirs(output_directory)
226
227 # get source boundaries (Envelope / Extent)
228 datasource = ogr.Open(source_xml_file)
229 if datasource is None:
230 raise FileNotFoundError('Could not open input file {}'.format(source_xml_file))
231 if datasource.GetLayerCount() < 1:
232 raise ReferenceError('No layers in input file')
233 source_layer = datasource.GetLayerByIndex(0)
234 source_x_min, source_x_max, source_y_min, source_y_max = source_layer.GetExtent()
[ca02e8f]235
[5e16955]236 tilegen = tilegenerator.TileGenerator(tile_sizes = tile_sizes, densities = [density_min], density_base = density_base, debug=statistics)
237 slices = tilegen.slices(source_xml_file, tilegenerator.ZoomRange(zoom_range[0], zoom_range[1]), raster_file_size_max = raster_file_size_max * 1024 * 1024 * 8)
238 slices_count = len(slices)
239 print('Generated {} slices for rastering'.format(slices_count))
240
241 t1_start = process_time()
242 print('Rastering slices and generating tiles')
243 with progressbar.ProgressBar(max_value=slices_count, redirect_stdout=True) as bar:
244 i = 1
245 for tile_slice in slices:
246 if statistics:
247 print(' Generating tiles for slice {} in {}'.format(i, temp_directory))
248 result_paths = tilegen.run(source_xml_file, temp_directory, tile_slice)
249 for path in result_paths:
250 tilegen.move_tiles_in_place(path.path, os.path.join(output_directory, path.prefixes['density'], path.prefixes['tile_size']))
251 bar.update(i)
252 i += 1
253 t1_stop = process_time()
254 print(' Tooks {:.2f} hours'.format((t1_stop - t1_start) / 60 / 60))
255
256 # delete temporary directory
257 shutil.rmtree(temp_directory)
258
259 print('Generated tiles in {}'.format(output_directory))
[26d66d8]260
[ca02e8f]261 sys.exit(0)
262
263if __name__ == "__main__":
264 main(sys.argv[1:])
Note: See TracBrowser for help on using the repository browser.