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

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

Fixed inverted lon,lat --> x,y resolution

  • Property mode set to 100644
File size: 8.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
26#import utm
27#import pdal
28import xml.etree.ElementTree as ET
29from osgeo import ogr
[cb89b0e]30from osgeo import gdal
[ca02e8f]31
32from gnuboat.datahandler import loghandler, logdataset
33
34class CsvCallback:
35 def __init__(self, output_file):
36 self._output_file = output_file
37 self._stage = None
38
39 def stage_set(self, stage):
40 self._stage = stage
41
42 def callback(self, dataset):
43 if self._stage is None:
44 print("No stage set! Skipping dataset...")
45 return
46 # only add points with a water depth set
47 if dataset.water_depth() is None:
48 return
49 water_depth = dataset.water_depth() - self._stage
[b76295a]50 self._output_file.writerow({"lon": dataset.longitude(), "lat": dataset.latitude(), "water_depth": water_depth})
[ca02e8f]51
[cb89b0e]52def tile_width(zoomlevel):
53 tile_size = 256
54 tiles = math.sqrt(tile_number(zoomlevel))
[b76295a]55 return {"tile_size": tile_size, "longitude": 360.0/tiles, "latitude": 180.0/tiles}
[cb89b0e]56
57def tile_number(zoomlevel):
58 return 2**(zoomlevel*2)
59
[ca02e8f]60def main(argv):
61 input_file_path = None
62 output_directory = None
[cb89b0e]63 statistics = False
[b76295a]64 target_nodata_value = 0.0
[cb89b0e]65 target_zoomlevel = 18
[ca02e8f]66
67 parser = argparse.ArgumentParser(description='Generates the digital terrain model from gnuboat logfiles')
68 parser.add_argument('input_file', metavar='input_file_path', type=str,
69 help='JSON file with logfiles and correction data to be processed')
70 parser.add_argument('output_directory', metavar='output_directory', type=str,
71 help='Write the Digital Terrain Model into this directory (output)')
[cb89b0e]72 parser.add_argument('-s', '--statistics', dest='statistics', action='store_true',
73 help='Print some statistics of the input and result datasets')
[ca02e8f]74 arguments = parser.parse_args(argv)
75
76 if arguments.input_file is None:
77 print('ERROR: No input file specified')
78 sys.exit(2)
79 #elif not os.path.exists(arguments.input_file):
80 print('ERROR: Specified input file does not exists: {}'.format(arguments.input_file))
81 sys.exit(3)
82 else:
83 input_file_path = arguments.input_file
84
85 if arguments.output_directory is None:
86 print('ERROR: No output file specified')
87 sys.exit(2)
88 elif not os.path.exists(os.path.dirname(arguments.output_directory)):
89 print('ERROR: Specified directory for output does not exists: {}'.format(arguments.output_directory))
90 sys.exit(3)
91 else:
92 output_directory = arguments.output_directory
[cb89b0e]93
94 if arguments.statistics is not None:
95 statistics = arguments.statistics
[ca02e8f]96
97 with open(input_file_path, 'r') as input_file:
98 logfiles = json.load(input_file)
99
[cb89b0e]100 source_data_layer = "corrected_joined_points"
101 corrected_joined_point_cloud_file_path = "{}/{}.csv".format(output_directory, source_data_layer)
[ca02e8f]102 try:
103 output_file = open(corrected_joined_point_cloud_file_path, 'w')
104 except IOError as error:
105 print('ERROR: Could not open the output file for the corrected, joined point cloud: {}'.format(error))
106 sys.exit(4)
107 output_file_csv = None
[b76295a]108 fields = ['lon', 'lat', 'water_depth']
[cb89b0e]109 output_file_csv = csv.DictWriter(output_file, delimiter=',', quotechar='"',
[ca02e8f]110 fieldnames=fields)
111 output_file_csv.writeheader()
112 csv_callback = CsvCallback(output_file_csv)
113 log_handler = loghandler.LogHandler()
114
115 print("Correcting and combining {} log files".format(len(logfiles)))
116 for logfile in logfiles:
117 stage = logfile["stage"]
118 log_file_path = logfile["file"]
119
120 # building the log file path
121 if not os.path.isabs(log_file_path):
122 log_file_path = "{}/{}".format(os.path.dirname(input_file_path), log_file_path)
123 # check stage
124 try:
125 stage = float(stage)
126 except ValueError:
127 print("Stage is not convertible into float for file {}. Skipping the file".format(log_file_path))
128 continue
129 # parse, correct and append log file
130 csv_callback.stage_set(stage)
131 if not log_handler.gnuboat_read(log_file_path, csv_callback.callback):
132 sys.exit(5)
133
134 print(" {} correct and joined with stage {}".format(log_file_path, stage))
135 output_file.close()
136
137 # create ogr file info
[7b6d348]138 source_xml_file = os.path.join(output_directory, "ogr_input_file.vrt")
[ca02e8f]139 try:
[7b6d348]140 output_file = open(source_xml_file, 'wb')
[ca02e8f]141 except IOError as error:
142 print('ERROR: Could not open the output file for the ogr data source description: {}'.format(error))
143 sys.exit(4)
144 xml_data_source = ET.Element("OGRVRTDataSource")
[cb89b0e]145 xml_layer = ET.SubElement(xml_data_source, "OGRVRTLayer", {"name": source_data_layer})
[ca02e8f]146 xml_source = ET.SubElement(xml_layer, "SrcDataSource")
147 xml_source.text = corrected_joined_point_cloud_file_path
148 xml_geometry_type = ET.SubElement(xml_layer, "GeometryType")
149 xml_geometry_type.text = "wkbPoint"
150 xml_layer_system = ET.SubElement(xml_layer, "LayerSRS")
[b76295a]151 xml_layer_system.text = "EPSG:4326"
152 xml_geometry_field = ET.SubElement(xml_layer, "GeometryField", {"encoding": "PointFromColumns", "x": "lon", "y": "lat", "z": "water_depth"})
[ca02e8f]153 xml_tree = ET.ElementTree(xml_data_source)
154 xml_tree.write(output_file, encoding="UTF-8", xml_declaration=False)
155 output_file.close()
156
157 # processing data with gdal
158 ogr.UseExceptions()
[cb89b0e]159 source_data = ogr.Open(source_xml_file)
160 source_layer = source_data.GetLayer(source_data_layer)
161 source_x_min, source_x_max, source_y_min, source_y_max = source_layer.GetExtent()
162 if statistics:
163 print("Source statistics:")
164 #print(" projection: {}".format(source_layer.GetProjection())
165 #print(" reference system: {}".format(source_data.GetAttrValue("geocs")))
166 print(" extents (x_min, y_min, x_max, y_max): {}, {}, {}, {}".format(source_x_min, source_y_min, source_x_max, source_y_max))
167
168 # Create the destination data source
169 tile_resolution = tile_width(target_zoomlevel)
[b76295a]170 target_x_res = int(tile_resolution["tile_size"] / tile_resolution["longitude"] * (source_x_max - source_x_min))
171 target_y_res = int(tile_resolution["tile_size"] / tile_resolution["latitude"] * (source_y_max - source_y_min))
172 #print("target resolution x,y: {},{}".format(target_x_res, target_y_res))
173 #print("pixel size x,y: {},{}".format((source_x_max - source_x_min)/target_x_res, (source_y_max - source_y_min)/target_y_res))
[cb89b0e]174 #target_data = gdal.GetDriverByName('MEM').Create('', target_x_res, target_y_res, gdal.GDT_Byte)
175 #target_data.SetGeoTransform((source_x_min, pixel_size, 0, source_y_max, 0, -pixel_size))
176 #band = target_ds.GetRasterBand(1)
177 #band.SetNoDataValue(NoData_value)
178
179 # create the grid data
[7b6d348]180 gdal_file = os.path.join(output_directory, "water_depth.tif")
[b76295a]181 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]182 gdal.Grid(gdal_file, source_xml_file, options = grid_options)
[b76295a]183
184 # translate the data
185 #gdal_file_translated = '/vsimem/translated.vrt'
186 #gdal_file_translated = os.path.join(output_directory, "water_depth_translated.tif")
187 #gdal.Translate(gdal_file_translated, gdal_file,
188 #options = gdal.TranslateOptions(width = target_x_res, height = target_y_res, outputSRS = 'EPSG:3857', noData = target_nodata_value)
189 #)
[ca02e8f]190
191 # creating pipeline
192 #output_file_path = "{}/{}".format(output_directory, "water_depth.tif")
193 #print("Creating Digital Terrain Model in {}".format(output_file_path))
194 #pipeline = {"pipeline":[
195 #{
196 #"type": "readers.text",
197 #"filename": corrected_joined_point_cloud_file_path
198 #},
199 #{
200 #"type": "filters.pmf"
201 #},
202 #{
203 #"type": "filters.range",
204 #"limits": "Classification[2:2]"
205 #},
206 #{
207 #"type": "writers.text",
208 #"order":"X,Y,Z",
209 #"keep_unspecified":"false",
210 #"filename":"outputfile.txt"
211 #}
212 ##{
213 ##"type": "writers.gdal",
214 ##"filename": output_file_path,
215 ##"output_type": "min",
216 ##"gdaldriver": "GTiff",
217 ##"resolution": 0.01
218 ###"grid_dist_x": 1.0,
219 ###"grid_dist_y": 1.0
220 ##}
221 #]}
222 #pdal_pipeline = pdal.Pipeline(json.dumps(pipeline))
223 #pdal_pipeline.validate()
224 #pdal_pipeline.set_loglevel(8)
225 #count = pdal_pipeline.execute()
226 #metadata = pdal_pipeline.get_metadata()
227 #log = pdal_pipeline.get_(log)
228
229 #print(metadata)
230 #print(log)
[b76295a]231
232 #ds_in = gdal.Open(gdal_file)
233 #band_in = ds_in.GetRasterBand(band)
[ca02e8f]234
235 sys.exit(0)
236
237if __name__ == "__main__":
238 main(sys.argv[1:])
Note: See TracBrowser for help on using the repository browser.