| [ca02e8f] | 1 | #!/usr/bin/python
|
|---|
| 2 | # -*- coding: utf-8 -*-
|
|---|
| 3 | '''
|
|---|
| [9af0638] | 4 | Copyright (C) 2018 - 2020 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.
|
|---|
| [ca02e8f] | 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
|
|---|
| [cb89b0e] | 23 | import math
|
|---|
| [ca02e8f] | 24 | import json
|
|---|
| 25 | import csv
|
|---|
| 26 | import xml.etree.ElementTree as ET
|
|---|
| 27 | from osgeo import ogr
|
|---|
| [2eed0da] | 28 | from osgeo import osr
|
|---|
| [cb89b0e] | 29 | from osgeo import gdal
|
|---|
| [2eed0da] | 30 | from osgeo import gdalconst
|
|---|
| 31 | import shutil
|
|---|
| [ca02e8f] | 32 |
|
|---|
| [9af0638] | 33 | from gnuboat_common.datahandler import loghandler, logdataset
|
|---|
| [9f5877d] | 34 | from gnuboat_common.spatial import tilegenerator
|
|---|
| [ca02e8f] | 35 |
|
|---|
| [c5b13e1] | 36 | # -999 is a workaround, as long gdal python api does not handle addAlpha
|
|---|
| [fbc3d47] | 37 | colors = {
|
|---|
| [c5b13e1] | 38 | -999: "255 255 255",
|
|---|
| [fbc3d47] | 39 | 0: "0 0 139",
|
|---|
| 40 | 2: "30 144 255",
|
|---|
| 41 | 6: "173 216 230",
|
|---|
| 42 | 10: "240 248 255"
|
|---|
| 43 | }
|
|---|
| [2eed0da] | 44 | input_epsg = 'EPSG:4326'
|
|---|
| [c5b13e1] | 45 | target_nodata_value = -999.0
|
|---|
| [dbaa7ce] | 46 | target_zoomlevel = 19
|
|---|
| [c5b13e1] | 47 | density_min = 10 # number of points per density_base squaremetres needed to set a value different from nodata
|
|---|
| 48 | density_base = 100 # squaremetre used as base for density_min
|
|---|
| [fbc3d47] | 49 |
|
|---|
| [ca02e8f] | 50 | class CsvCallback:
|
|---|
| 51 | def __init__(self, output_file):
|
|---|
| 52 | self._output_file = output_file
|
|---|
| 53 | self._stage = None
|
|---|
| 54 |
|
|---|
| 55 | def stage_set(self, stage):
|
|---|
| 56 | self._stage = stage
|
|---|
| 57 |
|
|---|
| 58 | def callback(self, dataset):
|
|---|
| 59 | if self._stage is None:
|
|---|
| 60 | print("No stage set! Skipping dataset...")
|
|---|
| 61 | return
|
|---|
| 62 | # only add points with a water depth set
|
|---|
| 63 | if dataset.water_depth() is None:
|
|---|
| 64 | return
|
|---|
| 65 | water_depth = dataset.water_depth() - self._stage
|
|---|
| [b76295a] | 66 | self._output_file.writerow({"lon": dataset.longitude(), "lat": dataset.latitude(), "water_depth": water_depth})
|
|---|
| [ca02e8f] | 67 |
|
|---|
| [cb89b0e] | 68 | def tile_width(zoomlevel):
|
|---|
| 69 | tile_size = 256
|
|---|
| 70 | tiles = math.sqrt(tile_number(zoomlevel))
|
|---|
| [b76295a] | 71 | return {"tile_size": tile_size, "longitude": 360.0/tiles, "latitude": 180.0/tiles}
|
|---|
| [cb89b0e] | 72 |
|
|---|
| 73 | def tile_number(zoomlevel):
|
|---|
| 74 | return 2**(zoomlevel*2)
|
|---|
| 75 |
|
|---|
| [ca02e8f] | 76 | def main(argv):
|
|---|
| [c5b13e1] | 77 | global color, input_epsg, target_nodata_value, target_zoomlevel, density_min, density_base
|
|---|
| [fbc3d47] | 78 |
|
|---|
| [ca02e8f] | 79 | input_file_path = None
|
|---|
| 80 | output_directory = None
|
|---|
| [cb89b0e] | 81 | statistics = False
|
|---|
| [c5b13e1] | 82 |
|
|---|
| 83 | gdal.UseExceptions()
|
|---|
| [ca02e8f] | 84 |
|
|---|
| 85 | parser = argparse.ArgumentParser(description='Generates the digital terrain model from gnuboat logfiles')
|
|---|
| 86 | parser.add_argument('input_file', metavar='input_file_path', type=str,
|
|---|
| 87 | help='JSON file with logfiles and correction data to be processed')
|
|---|
| 88 | parser.add_argument('output_directory', metavar='output_directory', type=str,
|
|---|
| 89 | help='Write the Digital Terrain Model into this directory (output)')
|
|---|
| [cb89b0e] | 90 | parser.add_argument('-s', '--statistics', dest='statistics', action='store_true',
|
|---|
| 91 | help='Print some statistics of the input and result datasets')
|
|---|
| [1c0ee46] | 92 | parser.add_argument('-p', '--points-min', dest='points_min', type=int,
|
|---|
| [c5b13e1] | 93 | help='Print min points per {} squaremetre'.format(density_base), default=density_min)
|
|---|
| [ca02e8f] | 94 | arguments = parser.parse_args(argv)
|
|---|
| 95 |
|
|---|
| 96 | if arguments.input_file is None:
|
|---|
| 97 | print('ERROR: No input file specified')
|
|---|
| 98 | sys.exit(2)
|
|---|
| 99 | #elif not os.path.exists(arguments.input_file):
|
|---|
| 100 | print('ERROR: Specified input file does not exists: {}'.format(arguments.input_file))
|
|---|
| 101 | sys.exit(3)
|
|---|
| 102 | else:
|
|---|
| 103 | input_file_path = arguments.input_file
|
|---|
| 104 |
|
|---|
| 105 | if arguments.output_directory is None:
|
|---|
| 106 | print('ERROR: No output file specified')
|
|---|
| 107 | sys.exit(2)
|
|---|
| 108 | else:
|
|---|
| 109 | output_directory = arguments.output_directory
|
|---|
| [cb89b0e] | 110 |
|
|---|
| 111 | if arguments.statistics is not None:
|
|---|
| 112 | statistics = arguments.statistics
|
|---|
| [2eed0da] | 113 |
|
|---|
| [1c0ee46] | 114 | if arguments.points_min is not None:
|
|---|
| 115 | density_min = arguments.points_min
|
|---|
| 116 |
|
|---|
| [c5b13e1] | 117 | gdal_file_contours = os.path.join(output_directory, 'contours_{}_{}'.format(density_min, density_base))
|
|---|
| [2eed0da] | 118 | print("Cleaning up / Preparing output directory")
|
|---|
| 119 | if os.path.exists(output_directory):
|
|---|
| 120 | for root, dirs, files in os.walk(output_directory):
|
|---|
| 121 | for f in files:
|
|---|
| 122 | os.unlink(os.path.join(root, f))
|
|---|
| 123 | for d in dirs:
|
|---|
| 124 | shutil.rmtree(os.path.join(root, d))
|
|---|
| 125 | else:
|
|---|
| 126 | os.makedirs(output_directory)
|
|---|
| 127 | if os.path.exists(gdal_file_contours):
|
|---|
| 128 | shutil.rmtree(gdal_file_contours)
|
|---|
| 129 |
|
|---|
| [ca02e8f] | 130 |
|
|---|
| 131 | with open(input_file_path, 'r') as input_file:
|
|---|
| 132 | logfiles = json.load(input_file)
|
|---|
| 133 |
|
|---|
| [fbc3d47] | 134 | source_data_layer = "tmp_corrected_joined_points"
|
|---|
| 135 | corrected_joined_point_cloud_file_path = os.path.join(output_directory, "{}.csv".format(source_data_layer))
|
|---|
| [ca02e8f] | 136 | try:
|
|---|
| 137 | output_file = open(corrected_joined_point_cloud_file_path, 'w')
|
|---|
| 138 | except IOError as error:
|
|---|
| 139 | print('ERROR: Could not open the output file for the corrected, joined point cloud: {}'.format(error))
|
|---|
| 140 | sys.exit(4)
|
|---|
| 141 | output_file_csv = None
|
|---|
| [b76295a] | 142 | fields = ['lon', 'lat', 'water_depth']
|
|---|
| [cb89b0e] | 143 | output_file_csv = csv.DictWriter(output_file, delimiter=',', quotechar='"',
|
|---|
| [ca02e8f] | 144 | fieldnames=fields)
|
|---|
| 145 | output_file_csv.writeheader()
|
|---|
| 146 | csv_callback = CsvCallback(output_file_csv)
|
|---|
| 147 | log_handler = loghandler.LogHandler()
|
|---|
| 148 |
|
|---|
| 149 | print("Correcting and combining {} log files".format(len(logfiles)))
|
|---|
| 150 | for logfile in logfiles:
|
|---|
| 151 | stage = logfile["stage"]
|
|---|
| 152 | log_file_path = logfile["file"]
|
|---|
| 153 |
|
|---|
| 154 | # building the log file path
|
|---|
| 155 | if not os.path.isabs(log_file_path):
|
|---|
| 156 | log_file_path = "{}/{}".format(os.path.dirname(input_file_path), log_file_path)
|
|---|
| 157 | # check stage
|
|---|
| 158 | try:
|
|---|
| 159 | stage = float(stage)
|
|---|
| 160 | except ValueError:
|
|---|
| 161 | print("Stage is not convertible into float for file {}. Skipping the file".format(log_file_path))
|
|---|
| 162 | continue
|
|---|
| 163 | # parse, correct and append log file
|
|---|
| 164 | csv_callback.stage_set(stage)
|
|---|
| [9af0638] | 165 | result = log_handler.gnuboat_read_file(log_file_path, csv_callback.callback)
|
|---|
| 166 | if result.messages():
|
|---|
| 167 | print('\n'.join(result.errors()))
|
|---|
| 168 | if not result.success():
|
|---|
| [ca02e8f] | 169 | sys.exit(5)
|
|---|
| 170 |
|
|---|
| 171 | print(" {} correct and joined with stage {}".format(log_file_path, stage))
|
|---|
| 172 | output_file.close()
|
|---|
| 173 |
|
|---|
| [fbc3d47] | 174 | print("Creating output files")
|
|---|
| [ca02e8f] | 175 | # create ogr file info
|
|---|
| [fbc3d47] | 176 | source_xml_file = os.path.join(output_directory, "tmp_ogr_input_file.vrt")
|
|---|
| [ca02e8f] | 177 | try:
|
|---|
| [7b6d348] | 178 | output_file = open(source_xml_file, 'wb')
|
|---|
| [ca02e8f] | 179 | except IOError as error:
|
|---|
| 180 | print('ERROR: Could not open the output file for the ogr data source description: {}'.format(error))
|
|---|
| 181 | sys.exit(4)
|
|---|
| 182 | xml_data_source = ET.Element("OGRVRTDataSource")
|
|---|
| [cb89b0e] | 183 | xml_layer = ET.SubElement(xml_data_source, "OGRVRTLayer", {"name": source_data_layer})
|
|---|
| [ca02e8f] | 184 | xml_source = ET.SubElement(xml_layer, "SrcDataSource")
|
|---|
| 185 | xml_source.text = corrected_joined_point_cloud_file_path
|
|---|
| 186 | xml_geometry_type = ET.SubElement(xml_layer, "GeometryType")
|
|---|
| 187 | xml_geometry_type.text = "wkbPoint"
|
|---|
| 188 | xml_layer_system = ET.SubElement(xml_layer, "LayerSRS")
|
|---|
| [2eed0da] | 189 | xml_layer_system.text = input_epsg
|
|---|
| [b76295a] | 190 | xml_geometry_field = ET.SubElement(xml_layer, "GeometryField", {"encoding": "PointFromColumns", "x": "lon", "y": "lat", "z": "water_depth"})
|
|---|
| [ca02e8f] | 191 | xml_tree = ET.ElementTree(xml_data_source)
|
|---|
| 192 | xml_tree.write(output_file, encoding="UTF-8", xml_declaration=False)
|
|---|
| 193 | output_file.close()
|
|---|
| 194 |
|
|---|
| [9f5877d] | 195 | tilegen = tilegenerator.TileGenerator(zoom_range=5-19, debug=statistics)
|
|---|
| 196 | tilegen.run(source_xml_file, output_directory)
|
|---|
| [26d66d8] | 197 |
|
|---|
| [ca02e8f] | 198 | sys.exit(0)
|
|---|
| 199 |
|
|---|
| 200 | if __name__ == "__main__":
|
|---|
| 201 | main(sys.argv[1:])
|
|---|