| 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 |
|
|---|
| 20 | import os
|
|---|
| 21 | import argparse
|
|---|
| 22 | import sys
|
|---|
| 23 | import math
|
|---|
| 24 | import json
|
|---|
| 25 | import csv
|
|---|
| 26 | #import utm
|
|---|
| 27 | #import pdal
|
|---|
| 28 | import xml.etree.ElementTree as ET
|
|---|
| 29 | from osgeo import ogr
|
|---|
| 30 | from osgeo import gdal
|
|---|
| 31 |
|
|---|
| 32 | from gnuboat.datahandler import loghandler, logdataset
|
|---|
| 33 |
|
|---|
| 34 | class 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 |
|
|---|
| 53 | def 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 |
|
|---|
| 58 | def tile_number(zoomlevel):
|
|---|
| 59 | return 2**(zoomlevel*2)
|
|---|
| 60 |
|
|---|
| 61 | def main(argv):
|
|---|
| 62 | input_file_path = None
|
|---|
| 63 | output_directory = None
|
|---|
| 64 | statistics = False
|
|---|
| 65 | target_nodata_value = 0
|
|---|
| 66 | target_zoomlevel = 18
|
|---|
| 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)')
|
|---|
| 73 | parser.add_argument('-s', '--statistics', dest='statistics', action='store_true',
|
|---|
| 74 | help='Print some statistics of the input and result datasets')
|
|---|
| 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
|
|---|
| 94 |
|
|---|
| 95 | if arguments.statistics is not None:
|
|---|
| 96 | statistics = arguments.statistics
|
|---|
| 97 |
|
|---|
| 98 | with open(input_file_path, 'r') as input_file:
|
|---|
| 99 | logfiles = json.load(input_file)
|
|---|
| 100 |
|
|---|
| 101 | source_data_layer = "corrected_joined_points"
|
|---|
| 102 | corrected_joined_point_cloud_file_path = "{}/{}.csv".format(output_directory, source_data_layer)
|
|---|
| 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']
|
|---|
| 110 | output_file_csv = csv.DictWriter(output_file, delimiter=',', quotechar='"',
|
|---|
| 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
|
|---|
| 139 | source_xml_file = "{}/{}".format(output_directory, "ogr_input_file.vrt")
|
|---|
| 140 | try:
|
|---|
| 141 | output_file = open(source_xml_file, 'w')
|
|---|
| 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")
|
|---|
| 146 | xml_layer = ET.SubElement(xml_data_source, "OGRVRTLayer", {"name": source_data_layer})
|
|---|
| 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()
|
|---|
| 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
|
|---|
| 181 | grid_options = gdal.GridOptions(format = "GTiff", width = target_x_res, height = target_y_res, outputSRS = "WGS84", noData = target_nodata_value, layers = source_data_layer)
|
|---|
| 182 | #gdal.Grid("/tmp/test.tif", source_xml_file)
|
|---|
| 183 | gdal.Grid("/tmp/test.tif", source_xml_file, options = grid_options)
|
|---|
| 184 |
|
|---|
| 185 | # creating pipeline
|
|---|
| 186 | #output_file_path = "{}/{}".format(output_directory, "water_depth.tif")
|
|---|
| 187 | #print("Creating Digital Terrain Model in {}".format(output_file_path))
|
|---|
| 188 | #pipeline = {"pipeline":[
|
|---|
| 189 | #{
|
|---|
| 190 | #"type": "readers.text",
|
|---|
| 191 | #"filename": corrected_joined_point_cloud_file_path
|
|---|
| 192 | #},
|
|---|
| 193 | #{
|
|---|
| 194 | #"type": "filters.pmf"
|
|---|
| 195 | #},
|
|---|
| 196 | #{
|
|---|
| 197 | #"type": "filters.range",
|
|---|
| 198 | #"limits": "Classification[2:2]"
|
|---|
| 199 | #},
|
|---|
| 200 | #{
|
|---|
| 201 | #"type": "writers.text",
|
|---|
| 202 | #"order":"X,Y,Z",
|
|---|
| 203 | #"keep_unspecified":"false",
|
|---|
| 204 | #"filename":"outputfile.txt"
|
|---|
| 205 | #}
|
|---|
| 206 | ##{
|
|---|
| 207 | ##"type": "writers.gdal",
|
|---|
| 208 | ##"filename": output_file_path,
|
|---|
| 209 | ##"output_type": "min",
|
|---|
| 210 | ##"gdaldriver": "GTiff",
|
|---|
| 211 | ##"resolution": 0.01
|
|---|
| 212 | ###"grid_dist_x": 1.0,
|
|---|
| 213 | ###"grid_dist_y": 1.0
|
|---|
| 214 | ##}
|
|---|
| 215 | #]}
|
|---|
| 216 | #pdal_pipeline = pdal.Pipeline(json.dumps(pipeline))
|
|---|
| 217 | #pdal_pipeline.validate()
|
|---|
| 218 | #pdal_pipeline.set_loglevel(8)
|
|---|
| 219 | #count = pdal_pipeline.execute()
|
|---|
| 220 | #metadata = pdal_pipeline.get_metadata()
|
|---|
| 221 | #log = pdal_pipeline.get_(log)
|
|---|
| 222 |
|
|---|
| 223 | #print(metadata)
|
|---|
| 224 | #print(log)
|
|---|
| 225 |
|
|---|
| 226 | sys.exit(0)
|
|---|
| 227 |
|
|---|
| 228 | if __name__ == "__main__":
|
|---|
| 229 | main(sys.argv[1:])
|
|---|