source: src/python/bin/gnuboat-log-analyser@ 7b6d348

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

Using os.path.join to generate paths to files

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