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

debian/bullseye
Last change on this file since ca02e8f was ca02e8f, checked in by Joachim Langenbach <joachim.langenbach@…>, 8 years ago
  • Added gnuboat-log-analyser to the python module
  • Fixed some smaller issues
  • First version of gnuboat-log_analyser, to process log files
  • Property mode set to 100644
File size: 6.4 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 json
24import csv
25#import utm
26#import pdal
27import xml.etree.ElementTree as ET
28from osgeo import ogr
29
30from gnuboat.datahandler import loghandler, logdataset
31
32class CsvCallback:
33 def __init__(self, output_file):
34 self._output_file = output_file
35 self._stage = None
36
37 def stage_set(self, stage):
38 self._stage = stage
39
40 def callback(self, dataset):
41 if self._stage is None:
42 print("No stage set! Skipping dataset...")
43 return
44 # only add points with a water depth set
45 if dataset.water_depth() is None:
46 return
47 #[x, y, zone_number, zone_letter] = utm.from_latlon(dataset.latitude(), dataset.longitude())
48 water_depth = dataset.water_depth() - self._stage
49 self._output_file.writerow({"X": dataset.latitude(), "Y": dataset.longitude(), "Z": water_depth})
50
51def main(argv):
52 input_file_path = None
53 output_directory = None
54
55 parser = argparse.ArgumentParser(description='Generates the digital terrain model from gnuboat logfiles')
56 parser.add_argument('input_file', metavar='input_file_path', type=str,
57 help='JSON file with logfiles and correction data to be processed')
58 parser.add_argument('output_directory', metavar='output_directory', type=str,
59 help='Write the Digital Terrain Model into this directory (output)')
60 arguments = parser.parse_args(argv)
61
62 if arguments.input_file is None:
63 print('ERROR: No input file specified')
64 sys.exit(2)
65 #elif not os.path.exists(arguments.input_file):
66 print('ERROR: Specified input file does not exists: {}'.format(arguments.input_file))
67 sys.exit(3)
68 else:
69 input_file_path = arguments.input_file
70
71 if arguments.output_directory is None:
72 print('ERROR: No output file specified')
73 sys.exit(2)
74 elif not os.path.exists(os.path.dirname(arguments.output_directory)):
75 print('ERROR: Specified directory for output does not exists: {}'.format(arguments.output_directory))
76 sys.exit(3)
77 else:
78 output_directory = arguments.output_directory
79
80 with open(input_file_path, 'r') as input_file:
81 logfiles = json.load(input_file)
82
83 corrected_joined_point_cloud_file_path = "{}/{}".format(output_directory, "corrected_joined_points.csv")
84 try:
85 output_file = open(corrected_joined_point_cloud_file_path, 'w')
86 except IOError as error:
87 print('ERROR: Could not open the output file for the corrected, joined point cloud: {}'.format(error))
88 sys.exit(4)
89 output_file_csv = None
90 fields = ['X', 'Y', 'Z']
91 output_file_csv = csv.DictWriter(output_file, delimiter=' ', quotechar='"',
92 fieldnames=fields)
93 output_file_csv.writeheader()
94 csv_callback = CsvCallback(output_file_csv)
95 log_handler = loghandler.LogHandler()
96
97 print("Correcting and combining {} log files".format(len(logfiles)))
98 for logfile in logfiles:
99 stage = logfile["stage"]
100 log_file_path = logfile["file"]
101
102 # building the log file path
103 if not os.path.isabs(log_file_path):
104 log_file_path = "{}/{}".format(os.path.dirname(input_file_path), log_file_path)
105 # check stage
106 try:
107 stage = float(stage)
108 except ValueError:
109 print("Stage is not convertible into float for file {}. Skipping the file".format(log_file_path))
110 continue
111 # parse, correct and append log file
112 csv_callback.stage_set(stage)
113 if not log_handler.gnuboat_read(log_file_path, csv_callback.callback):
114 sys.exit(5)
115
116 print(" {} correct and joined with stage {}".format(log_file_path, stage))
117 output_file.close()
118
119 # create ogr file info
120 ogr_data_layer = "points"
121 ogr_xml_file = "{}/{}".format(output_directory, "ogr_input_file.xml")
122 try:
123 output_file = open(ogr_xml_file, 'w')
124 except IOError as error:
125 print('ERROR: Could not open the output file for the ogr data source description: {}'.format(error))
126 sys.exit(4)
127 xml_data_source = ET.Element("OGRVRTDataSource")
128 xml_layer = ET.SubElement(xml_data_source, "OGRVRTLayer", {"name": ogr_data_layer})
129 xml_source = ET.SubElement(xml_layer, "SrcDataSource")
130 xml_source.text = corrected_joined_point_cloud_file_path
131 xml_source_layer = ET.SubElement(xml_layer, "SrcLayer")
132 xml_source_layer.text = ogr_data_layer
133 xml_geometry_type = ET.SubElement(xml_layer, "GeometryType")
134 xml_geometry_type.text = "wkbPoint"
135 xml_layer_system = ET.SubElement(xml_layer, "LayerSRS")
136 xml_layer_system.text = "WGS84"
137 xml_geometry_field = ET.SubElement(xml_layer, "GeometryField", {"encoding": "PointFromColumns", "x": "X", "y": "Y", "z": "Z"})
138 xml_tree = ET.ElementTree(xml_data_source)
139 xml_tree.write(output_file, encoding="UTF-8", xml_declaration=False)
140 output_file.close()
141
142 # processing data with gdal
143 ogr.UseExceptions()
144 ogr_data_source = ogr.Open(ogr_xml_file)
145 ogr_layer = ogr_data_source.GetLayer(ogr_data_layer)
146
147 # creating pipeline
148 #output_file_path = "{}/{}".format(output_directory, "water_depth.tif")
149 #print("Creating Digital Terrain Model in {}".format(output_file_path))
150 #pipeline = {"pipeline":[
151 #{
152 #"type": "readers.text",
153 #"filename": corrected_joined_point_cloud_file_path
154 #},
155 #{
156 #"type": "filters.pmf"
157 #},
158 #{
159 #"type": "filters.range",
160 #"limits": "Classification[2:2]"
161 #},
162 #{
163 #"type": "writers.text",
164 #"order":"X,Y,Z",
165 #"keep_unspecified":"false",
166 #"filename":"outputfile.txt"
167 #}
168 ##{
169 ##"type": "writers.gdal",
170 ##"filename": output_file_path,
171 ##"output_type": "min",
172 ##"gdaldriver": "GTiff",
173 ##"resolution": 0.01
174 ###"grid_dist_x": 1.0,
175 ###"grid_dist_y": 1.0
176 ##}
177 #]}
178 #pdal_pipeline = pdal.Pipeline(json.dumps(pipeline))
179 #pdal_pipeline.validate()
180 #pdal_pipeline.set_loglevel(8)
181 #count = pdal_pipeline.execute()
182 #metadata = pdal_pipeline.get_metadata()
183 #log = pdal_pipeline.get_(log)
184
185 #print(metadata)
186 #print(log)
187
188 sys.exit(0)
189
190if __name__ == "__main__":
191 main(sys.argv[1:])
Note: See TracBrowser for help on using the repository browser.