#!/usr/bin/python # -*- coding: utf-8 -*- ''' Copyright (C) 2018 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . ''' import os import argparse import sys import json import csv #import utm #import pdal import xml.etree.ElementTree as ET from osgeo import ogr from gnuboat.datahandler import loghandler, logdataset class CsvCallback: def __init__(self, output_file): self._output_file = output_file self._stage = None def stage_set(self, stage): self._stage = stage def callback(self, dataset): if self._stage is None: print("No stage set! Skipping dataset...") return # only add points with a water depth set if dataset.water_depth() is None: return #[x, y, zone_number, zone_letter] = utm.from_latlon(dataset.latitude(), dataset.longitude()) water_depth = dataset.water_depth() - self._stage self._output_file.writerow({"X": dataset.latitude(), "Y": dataset.longitude(), "Z": water_depth}) def main(argv): input_file_path = None output_directory = None parser = argparse.ArgumentParser(description='Generates the digital terrain model from gnuboat logfiles') parser.add_argument('input_file', metavar='input_file_path', type=str, help='JSON file with logfiles and correction data to be processed') parser.add_argument('output_directory', metavar='output_directory', type=str, help='Write the Digital Terrain Model into this directory (output)') arguments = parser.parse_args(argv) if arguments.input_file is None: print('ERROR: No input file specified') sys.exit(2) #elif not os.path.exists(arguments.input_file): print('ERROR: Specified input file does not exists: {}'.format(arguments.input_file)) sys.exit(3) else: input_file_path = arguments.input_file if arguments.output_directory is None: print('ERROR: No output file specified') sys.exit(2) elif not os.path.exists(os.path.dirname(arguments.output_directory)): print('ERROR: Specified directory for output does not exists: {}'.format(arguments.output_directory)) sys.exit(3) else: output_directory = arguments.output_directory with open(input_file_path, 'r') as input_file: logfiles = json.load(input_file) corrected_joined_point_cloud_file_path = "{}/{}".format(output_directory, "corrected_joined_points.csv") try: output_file = open(corrected_joined_point_cloud_file_path, 'w') except IOError as error: print('ERROR: Could not open the output file for the corrected, joined point cloud: {}'.format(error)) sys.exit(4) output_file_csv = None fields = ['X', 'Y', 'Z'] output_file_csv = csv.DictWriter(output_file, delimiter=' ', quotechar='"', fieldnames=fields) output_file_csv.writeheader() csv_callback = CsvCallback(output_file_csv) log_handler = loghandler.LogHandler() print("Correcting and combining {} log files".format(len(logfiles))) for logfile in logfiles: stage = logfile["stage"] log_file_path = logfile["file"] # building the log file path if not os.path.isabs(log_file_path): log_file_path = "{}/{}".format(os.path.dirname(input_file_path), log_file_path) # check stage try: stage = float(stage) except ValueError: print("Stage is not convertible into float for file {}. Skipping the file".format(log_file_path)) continue # parse, correct and append log file csv_callback.stage_set(stage) if not log_handler.gnuboat_read(log_file_path, csv_callback.callback): sys.exit(5) print(" {} correct and joined with stage {}".format(log_file_path, stage)) output_file.close() # create ogr file info ogr_data_layer = "points" ogr_xml_file = "{}/{}".format(output_directory, "ogr_input_file.xml") try: output_file = open(ogr_xml_file, 'w') except IOError as error: print('ERROR: Could not open the output file for the ogr data source description: {}'.format(error)) sys.exit(4) xml_data_source = ET.Element("OGRVRTDataSource") xml_layer = ET.SubElement(xml_data_source, "OGRVRTLayer", {"name": ogr_data_layer}) xml_source = ET.SubElement(xml_layer, "SrcDataSource") xml_source.text = corrected_joined_point_cloud_file_path xml_source_layer = ET.SubElement(xml_layer, "SrcLayer") xml_source_layer.text = ogr_data_layer xml_geometry_type = ET.SubElement(xml_layer, "GeometryType") xml_geometry_type.text = "wkbPoint" xml_layer_system = ET.SubElement(xml_layer, "LayerSRS") xml_layer_system.text = "WGS84" xml_geometry_field = ET.SubElement(xml_layer, "GeometryField", {"encoding": "PointFromColumns", "x": "X", "y": "Y", "z": "Z"}) xml_tree = ET.ElementTree(xml_data_source) xml_tree.write(output_file, encoding="UTF-8", xml_declaration=False) output_file.close() # processing data with gdal ogr.UseExceptions() ogr_data_source = ogr.Open(ogr_xml_file) ogr_layer = ogr_data_source.GetLayer(ogr_data_layer) # creating pipeline #output_file_path = "{}/{}".format(output_directory, "water_depth.tif") #print("Creating Digital Terrain Model in {}".format(output_file_path)) #pipeline = {"pipeline":[ #{ #"type": "readers.text", #"filename": corrected_joined_point_cloud_file_path #}, #{ #"type": "filters.pmf" #}, #{ #"type": "filters.range", #"limits": "Classification[2:2]" #}, #{ #"type": "writers.text", #"order":"X,Y,Z", #"keep_unspecified":"false", #"filename":"outputfile.txt" #} ##{ ##"type": "writers.gdal", ##"filename": output_file_path, ##"output_type": "min", ##"gdaldriver": "GTiff", ##"resolution": 0.01 ###"grid_dist_x": 1.0, ###"grid_dist_y": 1.0 ##} #]} #pdal_pipeline = pdal.Pipeline(json.dumps(pipeline)) #pdal_pipeline.validate() #pdal_pipeline.set_loglevel(8) #count = pdal_pipeline.execute() #metadata = pdal_pipeline.get_metadata() #log = pdal_pipeline.get_(log) #print(metadata) #print(log) sys.exit(0) if __name__ == "__main__": main(sys.argv[1:])