Changeset 5e16955 for src/common


Ignore:
Timestamp:
Mar 30, 2020, 8:31:10 PM (7 years ago)
Author:
Joachim Langenbach <joachim.langenbach@…>
Branches:
debian/bullseye, master
Children:
b72d9c4
Parents:
9f5877d
Message:

First version of a working log processing task

Location:
src/common
Files:
1 added
3 edited

Legend:

Unmodified
Added
Removed
  • src/common/bin/gnuboat-log-analyser

    r9f5877d r5e16955  
    1919
    2020import os
     21import pathlib
    2122import argparse
    2223import sys
    … …  
    2526import csv
    2627import xml.etree.ElementTree as ET
     28import tempfile
    2729from osgeo import ogr
    2830from osgeo import osr
    … …  
    3032from osgeo import gdalconst
    3133import shutil
     34import progressbar
     35from time import process_time
    3236
    3337from gnuboat_common.datahandler import loghandler, logdataset
    … …  
    5256                self._output_file = output_file
    5357                self._stage = None
     58                self._resultsets = 0
     59               
     60        def count(self):
     61                return self._resultsets
    5462               
    5563        def stage_set(self, stage):
    … …  
    6573                water_depth = dataset.water_depth() - self._stage
    6674                self._output_file.writerow({"lon": dataset.longitude(), "lat": dataset.latitude(), "water_depth": water_depth})
     75                self._resultsets += 1
    6776
    6877def tile_width(zoomlevel):
    … …  
    8089        output_directory = None
    8190        statistics = False
     91        tile_sizes = [256]
    8292       
    8393        gdal.UseExceptions()
    … …  
    8898        parser.add_argument('output_directory', metavar='output_directory', type=str,
    8999                                                help='Write the Digital Terrain Model into this directory (output)')
    90         parser.add_argument('-s', '--statistics', dest='statistics', action='store_true',
    91                         help='Print some statistics of the input and result datasets')
    92         parser.add_argument('-p', '--points-min', dest='points_min', type=int,
    93                         help='Print min points per {} squaremetre'.format(density_base), default=density_min)
     100        parser.add_argument('-v', '--statistics', dest='statistics', action='store_true',
     101                                                help='Print some statistics of the input and result datasets')
     102        parser.add_argument('-p', '--points-min', dest='points_min', type=int, default=density_min,
     103                                                help='Minimum points per {} squaremetre is needed to create a valid depth information'.format(density_base))
     104        parser.add_argument('-z', '--zoomlevels', dest='zoom_range', nargs=2, default=[10, 19], type=int,
     105                                                help='Creates tiles for the specified range of zoomlevels')
     106        parser.add_argument('--high-res', dest='high_res', action='store_true',
     107                                                help='Creates tiles with 512 pixel per tile additionally to the 256 pixel per tile tiles')
     108        parser.add_argument('-m', '--raster_file_max', dest='raster_file_size_max', default=1024, type=int,
     109                                                help='Maximum size of temporary raster Tifs for tile generation in MB')
    94110        arguments = parser.parse_args(argv)
    95111
    … …  
    97113                print('ERROR: No input file specified')
    98114                sys.exit(2)
    99         #elif not os.path.exists(arguments.input_file):
     115        elif not os.path.exists(arguments.input_file):
    100116                print('ERROR: Specified input file does not exists: {}'.format(arguments.input_file))
    101117                sys.exit(3)
    … …  
    114130        if arguments.points_min is not None:
    115131                density_min = arguments.points_min
    116                
    117         gdal_file_contours = os.path.join(output_directory, 'contours_{}_{}'.format(density_min, density_base))
    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        
     132       
     133        if arguments.zoom_range is not None:
     134                zoom_range = arguments.zoom_range
     135       
     136        if arguments.high_res is not None:
     137                tile_sizes.append(512)
     138               
     139        if arguments.raster_file_size_max is not None:
     140                raster_file_size_max = arguments.raster_file_size_max
     141               
     142        # create temporary directory
     143        temp_directory = tempfile.mkdtemp(prefix='gnuboat-log-analyser')
    130144
    131145        with open(input_file_path, 'r') as input_file:
    … …  
    133147       
    134148        source_data_layer = "tmp_corrected_joined_points"
    135         corrected_joined_point_cloud_file_path = os.path.join(output_directory, "{}.csv".format(source_data_layer))
     149        corrected_joined_point_cloud_file_path = os.path.join(temp_directory, "{}.csv".format(source_data_layer))
    136150        try:
    137151                output_file = open(corrected_joined_point_cloud_file_path, 'w')
    … …  
    149163        print("Correcting and combining {} log files".format(len(logfiles)))
    150164        for logfile in logfiles:
    151                 stage = logfile["stage"]
     165                gaugeHeight = logfile["gaugeHeight"]
     166                referenceWaterLevelGaugeHeight = logfile["referenceWaterLevelGaugeHeight"]
    152167                log_file_path = logfile["file"]
    153168               
    … …  
    157172                # check stage
    158173                try:
    159                         stage = float(stage)
     174                        gaugeHeight = float(gaugeHeight)
    160175                except ValueError:
    161                         print("Stage is not convertible into float for file {}. Skipping the file".format(log_file_path))
     176                        print("gaugeHeight is not convertible into float for file {}. Skipping the file".format(log_file_path))
     177                        continue
     178                try:
     179                        referenceWaterLevelGaugeHeight = float(referenceWaterLevelGaugeHeight)
     180                except ValueError:
     181                        print("referenceWaterLevelGaugeHeight is not convertible into float for file {}. Skipping the file".format(log_file_path))
    162182                        continue
    163183                # parse, correct and append log file
    164                 csv_callback.stage_set(stage)
     184                difference = referenceWaterLevelGaugeHeight - gaugeHeight
     185                csv_callback.stage_set(difference)
    165186                result = log_handler.gnuboat_read_file(log_file_path, csv_callback.callback)
    166187                if result.messages():
    … …  
    169190                        sys.exit(5)
    170191               
    171                 print("  {} correct and joined with stage {}".format(log_file_path, stage))
     192                print("  {} correct and joined with difference {:.3f}m".format(log_file_path, difference))
    172193        output_file.close()
    173 
    174         print("Creating output files")
     194        print ('  Processed {} points'.format(csv_callback.count()))
     195
     196        print("Generating tiles")
    175197        # create ogr file info
    176         source_xml_file = os.path.join(output_directory, "tmp_ogr_input_file.vrt")
     198        source_xml_file = os.path.join(temp_directory, "tmp_ogr_input_file.vrt")
    177199        try:
    178200                output_file = open(source_xml_file, 'wb')
    … …  
    192214        xml_tree.write(output_file, encoding="UTF-8", xml_declaration=False)
    193215        output_file.close()
    194 
    195         tilegen = tilegenerator.TileGenerator(zoom_range=5-19, debug=statistics)
    196         tilegen.run(source_xml_file, output_directory)
     216       
     217        # preparing output_directory
     218        if os.path.exists(output_directory):
     219                for root, dirs, files in os.walk(output_directory):
     220                        for f in files:
     221                                os.unlink(os.path.join(root, f))
     222                        for d in dirs:
     223                                shutil.rmtree(os.path.join(root, d))
     224        else:
     225                os.makedirs(output_directory)
     226       
     227        # get source boundaries (Envelope / Extent)
     228        datasource = ogr.Open(source_xml_file)
     229        if datasource is None:
     230                raise FileNotFoundError('Could not open input file {}'.format(source_xml_file))
     231        if datasource.GetLayerCount() < 1:
     232                raise ReferenceError('No layers in input file')
     233        source_layer = datasource.GetLayerByIndex(0)
     234        source_x_min, source_x_max, source_y_min, source_y_max = source_layer.GetExtent()
     235
     236        tilegen = tilegenerator.TileGenerator(tile_sizes = tile_sizes, densities = [density_min], density_base = density_base, debug=statistics)
     237        slices = tilegen.slices(source_xml_file, tilegenerator.ZoomRange(zoom_range[0], zoom_range[1]), raster_file_size_max = raster_file_size_max * 1024 * 1024 * 8)
     238        slices_count = len(slices)
     239        print('Generated {} slices for rastering'.format(slices_count))
     240       
     241        t1_start = process_time()
     242        print('Rastering slices and generating tiles')
     243        with progressbar.ProgressBar(max_value=slices_count, redirect_stdout=True) as bar:
     244                i = 1
     245                for tile_slice in slices:
     246                        if statistics:
     247                                print(' Generating tiles for slice {} in {}'.format(i, temp_directory))
     248                        result_paths = tilegen.run(source_xml_file, temp_directory, tile_slice)
     249                        for path in result_paths:
     250                                tilegen.move_tiles_in_place(path.path, os.path.join(output_directory, path.prefixes['density'], path.prefixes['tile_size']))
     251                        bar.update(i)
     252                        i += 1
     253        t1_stop = process_time()
     254        print('  Tooks {:.2f} hours'.format((t1_stop - t1_start) / 60 / 60))
     255
     256        # delete temporary directory
     257        shutil.rmtree(temp_directory)
     258       
     259        print('Generated tiles in {}'.format(output_directory))
    197260
    198261        sys.exit(0)
  • src/common/gnuboat_common/spatial/tilegenerator.py

    r9f5877d r5e16955  
    2626import subprocess
    2727import math
     28import copy
     29
     30try:
     31        from dataclasses import dataclass
     32       
     33        #@dataclass
     34        #class TileWidth:
     35                #"""
     36                        #tile_size: The tile size in Pixel,
     37                        #longitude: The width of the Tile in decimal degrees
     38                        #latitude:  The height of the Tile in decimal degrees
     39                #"""
     40                #tile_size: int
     41                #longitude: float
     42                #latitude: float
     43       
     44        @dataclass
     45        class ResultPath:
     46                """
     47                        path: Absolute path of the created results
     48                        prefixes: Dict with meaningful prefixes in the path. e.g. {'tile_size': '512', 'density': '10_100'}
     49                """
     50                path: str
     51                prefixes: dict
     52               
     53except ImportError:
     54        #class TileWidth:
     55                #"""
     56                        #Workaround for @dataclass, until python 3.7 is available in main distros
     57                #"""
     58                #def __init__(self, tile_size, longitude, latitude):
     59                        #self.tile_size = tile_size
     60                        #self.longitude = longitude
     61                        #self.latitude = latitude
     62       
     63        class ResultPath:
     64                """
     65                        path: Absolute path of the created results
     66                        prefixes: Dict with meaningful prefixes in the path. e.g. {'tile_size': '512', 'density': '10_100'}
     67                """
     68                def __init__(self, path, prefixes):
     69                        self.path = path
     70                        self.prefixes = prefixes
     71
     72class ZoomRange(dict):
     73        def __init__(self, minimum, maximum):
     74                super(ZoomRange, self).__init__({'minimum': minimum, 'maximum': maximum})
     75               
     76        def minimum(self):
     77                return self['minimum']
     78       
     79        def maximum(self):
     80                return self['maximum']
     81       
     82        def from_dict(dictionary):
     83                return ZoomRange(dictionary['minimum'], dictionary['maximum'])
     84
     85class LngLatBbox(dict):
     86        def __init__(self, east, south, west, north):
     87                super(LngLatBbox, self).__init__({'east': east, 'south': south, 'west': west, 'north': north})
     88               
     89        def east(self):
     90                return self['east']
     91       
     92        def south(self):
     93                return self['south']
     94       
     95        def west(self):
     96                return self['west']
     97       
     98        def north(self):
     99                return self['north']
     100               
     101        def to_mercantile_bbox(self):
     102                return mercantile.LngLatBbox(self.west(), self.south(), self.east(), self.north())
     103       
     104        def from_mercantile_bbox(mercantile_bbox):
     105                return LngLatBbox(mercantile_bbox.east, mercantile_bbox.south, mercantile_bbox.west, mercantile_bbox.north)
     106       
     107        def from_dict(dictionary):
     108                return LngLatBbox(dictionary['east'], dictionary['south'], dictionary['west'], dictionary['north'])
     109
     110class RasterSlice(dict):
     111        """
     112                lng_lat_box: LngLatBbox
     113                zoom_range: ZoomRange
     114                tile_size: The tile size in Pixel,
     115                grid_width: The width of the resulting rastr
     116                grid_height:  The height of the resulting rastr
     117               
     118                It's derived from dict to be json serialisable
     119        """
     120        def __init__(self, lng_lat_box, zoom_range, tile_size, grid_width, grid_height):
     121                super(RasterSlice, self).__init__({'lng_lat_box': lng_lat_box, 'zoom_range': zoom_range, 'tile_size': tile_size, 'grid_width': grid_width, 'grid_height': grid_height})
     122               
     123        def lng_lat_box(self):
     124                return self['lng_lat_box']
     125       
     126        def zoom_range(self):
     127                return self['zoom_range']
     128       
     129        def tile_size(self):
     130                return self['tile_size']
     131       
     132        def grid_width(self):
     133                return self['grid_width']
     134       
     135        def grid_height(self):
     136                return self['grid_height']
     137       
     138        def from_dict(dictionary):
     139                return RasterSlice(LngLatBbox.from_dict(dictionary['lng_lat_box']), ZoomRange.from_dict(dictionary['zoom_range']), dictionary['tile_size'], dictionary['grid_width'], dictionary['grid_height'])
    28140
    29141class TileGenerator:
    … …  
    35147                - nodata_value = Value used for pixels without valid data
    36148        """
    37         def __init__(self, tile_sizes = [256, 512], zoom_range = [14, 19], densities = [10, 100], density_base = 100, nodata_value = -999.0, debug=False):
     149        def __init__(self, tile_sizes = [256, 512], densities = [10, 100], density_base = 100, nodata_value = -999.0, debug=False):
    38150                self._tile_sizes = tile_sizes
    39                 self._zoom_range = zoom_range
    40151                self._densities = densities
    41152                self._density_base = density_base
    … …  
    54165                ogr.UseExceptions()
    55166
    56         def run(self, input_file, output_directory, tile_sizes = None, zoom_range = None, densities = None, density_base = None, nodata_value = None):
     167        def fit_extent_to_tiles(self, lng_lat_box, zoom_range):
     168                """
     169                        Enlarges the extent (given by lng_lat_box) to the borders of the tiles
     170                        lng_lat_box is of Type LngLatBbox
     171                """
     172                tile_bounding = mercantile.bounding_tile(lng_lat_box.west, lng_lat_box.south, lng_lat_box.east, lng_lat_box.north)
     173                if tile_bounding.z > zoom_range.minimum():
     174                        return LngLatBbox.from_mercantile_bbox(mercantile.bounds(mercantile.parent(tile_bounding, zoom=zoom_range.minimum())))
     175                else:
     176                        return LngLatBbox.from_mercantile_bbox(mercantile.bounds(tile_bounding))
     177
     178        def slices(self, input_file, zoom_range, tile_sizes = None, raster_file_size_max = 1024 * 1024 * 1024 * 8):
     179                """
     180                        Slice the complete area of input_file into smaller pieces,
     181                        so that each created raster file is smaller than raster_file_size_max
     182                        and cut into pieces at the borders of tiles and not thorugh tiles.
     183                        It returns an array of latitude longitude boxes representaing the borders, per slice.
     184                """
     185                if tile_sizes is None:
     186                        tile_sizes = self._tile_sizes
     187               
     188                datasource = self._datasource_open(input_file)
     189                source_layer = datasource.GetLayerByIndex(0)
     190                west, east, south, north = source_layer.GetExtent()
     191               
     192                raster_slices = []
     193                for tile_size in tile_sizes:
     194                        # fitting to tile borders
     195                        lng_lat_box = self.fit_extent_to_tiles(mercantile.LngLatBbox(west, south, east, north), zoom_range)
     196                        tiles_zoom_min = mercantile.tiles(lng_lat_box.west(), lng_lat_box.south(), lng_lat_box.east(), lng_lat_box.north(), zoom_range.minimum())
     197                                       
     198                        # calculating size of raster file for GDT_Float32 = 24bits (at least the tif'S seen at my pc)
     199                        tile_count_max =  math.floor(raster_file_size_max / (tile_size**2 * 24))
     200                        delta_zoom = math.floor(math.log(tile_count_max) / math.log(4))
     201                        steps = math.floor((zoom_range.maximum() - zoom_range.minimum()) / delta_zoom)
     202                        zoom_steps = []
     203                        step = zoom_range.minimum()
     204                        while step < zoom_range.maximum():
     205                                zoom_steps.append(step)
     206                                if step + math.floor(1.5 * delta_zoom) > zoom_range.maximum():
     207                                        break
     208                                step += delta_zoom
     209                        for tile in tiles_zoom_min:
     210                                raster_slices += self._slice_tile(tile, zoom_steps, zoom_range.maximum(), tile_count_max, tile_size)
     211                return raster_slices
     212
     213        def _slice_tile(self, parent_tile, zoom_steps, zoom_total_max, tiles_per_slice, tile_size):
     214                if len(zoom_steps) < 1:
     215                        raise ValueError('No zoomsteps given to slice tile generation')
     216                zoom_min = zoom_steps[0]
     217                if len(zoom_steps) < 2:
     218                        zoom_max = zoom_total_max
     219                else:
     220                        zoom_max = zoom_steps[1] - 1
     221               
     222                raster_slices = []
     223                lng_lat_box = mercantile.bounds(parent_tile)
     224                width = math.sqrt(4**(zoom_max - zoom_min)) * tile_size
     225                if width != round(width):
     226                        raise ValueError('Found a slice, with incomplete tiles')
     227                raster_slice = RasterSlice(LngLatBbox.from_mercantile_bbox(lng_lat_box), ZoomRange(zoom_min, zoom_max), tile_size, width, width)
     228                raster_slices.append(raster_slice)
     229                if len(zoom_steps) > 1:
     230                        zoom_steps_new = copy.deepcopy(zoom_steps)
     231                        zoom_steps_new.pop(0)
     232                        zoom_min_new = zoom_steps_new[0]
     233                        for child in mercantile.children(parent_tile, zoom=zoom_min_new):
     234                                raster_slices += self._slice_tile(child, zoom_steps_new, zoom_total_max, tiles_per_slice, tile_size)
     235                return raster_slices
     236
     237
     238        def run(self, input_file, output_directory, tile_slice, densities = None, density_base = None, nodata_value = None):
    57239                """
    58240                        Runs all nescessary steps to create the tiles.
    59241                        All default parameters equal to none are replaced by the one of the object
    60242                        input_file = vrt source file used as a base for all steps to creating the tiles
    61                 """
    62                 if tile_sizes is None:
    63                         tile_sizes = self._tile_sizes
    64                 if zoom_range is None:
    65                         zoom_range = self._zoom_range
     243                        Returns an array of paths with the created tiles if successfull
     244                """
    66245                if densities is None:
    67246                        densities = self._densities
    … …  
    72251               
    73252                # get source boundaries (Envelope / Extent)
    74                 datasource = ogr.Open(input_file)
    75                 if datasource is None:
    76                         raise FileNotFoundError('Could not open input file {}'.format(input_file))
    77                 if datasource.GetLayerCount() < 1:
    78                         raise ReferenceError('No layers in input file')
     253                datasource = self._datasource_open(input_file)
    79254                source_layer = datasource.GetLayerByIndex(0)
    80255                source_x_min, source_x_max, source_y_min, source_y_max = source_layer.GetExtent()
    … …  
    88263                radius_y = circle_radius / lat_metre_max
    89264               
     265                tile_result_paths = []
    90266                for density_min in densities:
    91                         for tile_size in tile_sizes:
    92                                 gridding_algorithm = 'average:radius1={}:radius2={}:angle=0.0:min_points={}:nodata={}'.format(radius_x, radius_y, density_min, nodata_value)
     267                        gridding_algorithm = 'average:radius1={}:radius2={}:angle=0.0:min_points={}:nodata={}'.format(radius_x, radius_y, density_min, nodata_value)
     268                        if self._debug:
     269                                print("Run for density {} and {} tile size:".format(density_min, tile_slice.tile_size()))
     270                                print("  Statistics:")
     271                                print("    Found {} Points".format(source_layer.GetFeatureCount()))
     272                                print("    Min density per squaredegree: {}".format(density_min * density_base / lon_metre_max / lat_metre_max))
     273                                print("    Min density per pixel: {}".format(density_min * density_base / (degree_per_pixel_lon * lon_metre_max) / (degree_per_pixel_lat * lat_metre_max)))
     274                                print("    gridding algorithm {}".format(gridding_algorithm))
    93275                               
    94                                 tile_resolution = self._tile_width(tile_size, zoom_range[1])
    95                                 target_x_res = int(tile_resolution['tile_size'] / tile_resolution['longitude'] * (source_x_max - source_x_min))
    96                                 target_y_res = int(tile_resolution['tile_size'] / tile_resolution['latitude'] * (source_y_max - source_y_min))
    97                                
    98                                 if self._debug:
    99                                         print("Run for density {} and {} tile size:".format(density_min, tile_size))
    100                                         print("  Statistics:")
    101                                         print("    Found {} Points".format(source_layer.GetFeatureCount()))
    102                                         degree_per_pixel_lon = tile_resolution['longitude'] / tile_resolution['tile_size']
    103                                         degree_per_pixel_lat = tile_resolution['latitude'] / tile_resolution['tile_size']
    104                                         print("    degree / pixel x and y: {}, {}".format(degree_per_pixel_lon, degree_per_pixel_lat))
    105                                         print("    metre / pixel x and y: {}, {}".format(degree_per_pixel_lon * lon_metre_max, degree_per_pixel_lat * lat_metre_max))
    106                                         print("    Min density per squaredegree: {}".format(density_min * density_base / lon_metre_max / lat_metre_max))
    107                                         print("    Min density per pixel: {}".format(density_min * density_base / (degree_per_pixel_lon * lon_metre_max) / (degree_per_pixel_lat * lat_metre_max)))
    108                                         print("    gridding algorithm {}".format(gridding_algorithm))
    109                                        
    110                                 # create the grid data
    111                                 raster_file = self.raster_create(input_file, source_layer_name, target_x_res, target_y_res, gridding_algorithm)
    112                                 # hillshade
    113                                 hillshade_file = self.hillshade_create(raster_file)
    114                                 # color relief
    115                                 color_relief_file = self.color_relief_create(raster_file)
    116                                 # slopeshade
    117                                 slopeshade_file = os.path.join(output_directory, 'water_depth_slopeshade.tif')
    118                                 slopeshade_file = self.slopeshade_create(raster_file, slopeshade_file)
    119                                 # merge color relief and hillshade
    120                                 merged_file = os.path.join(output_directory, 'water_depth_{}_{}.tif'.format(density_min, density_base))
    121                                 self.merge_color_relief_hillshade(color_relief_file, hillshade_file, merged_file)
    122                                 # create the tiles
    123                                 title = 'GNUBoat {} datasets per {} squaremetre, Tilesize: {}'.format(density_min, density_base, tile_size)
    124                                 tiles_output = os.path.join(output_directory, '{}_{}/{}'.format(density_min, density_base, tile_size))
    125                                 self.tiles_create(merged_file, title, tile_size, tiles_output)
    126 
    127         def raster_create(self, input_file, layers, width, height, gridding_algorithm, nodata_value=None, output_file='/vsimem/water_depth.tif'):
     276                        # create the grid data
     277                        raster_file = self.raster_create(input_file, source_layer_name, tile_slice, gridding_algorithm)
     278                        # hillshade
     279                        hillshade_file = self.hillshade_create(raster_file)
     280                        # color relief
     281                        color_relief_file = self.color_relief_create(raster_file)
     282                        # slopeshade
     283                        slopeshade_file = os.path.join(output_directory, 'water_depth_slopeshade.tif')
     284                        slopeshade_file = self.slopeshade_create(raster_file, slopeshade_file)
     285                        # merge color relief and hillshade
     286                        merged_file = os.path.join(output_directory, 'water_depth_{}_{}.tif'.format(density_min, density_base))
     287                        self.merge_color_relief_hillshade(color_relief_file, hillshade_file, merged_file)
     288                        # create the tiles
     289                        title = 'GNUBoat {} datasets per {} squaremetre, Tilesize: {}'.format(density_min, density_base, tile_slice.tile_size())
     290                        prefix_density = '{}_{}'.format(density_min, density_base)
     291                        tiles_output = os.path.join(output_directory, '{}/{}'.format(prefix_density, tile_slice.tile_size()))
     292                        self.tiles_create(merged_file, title, tile_slice.tile_size(), tiles_output, zoom_range = tile_slice.zoom_range())
     293                        tile_result_paths.append(ResultPath(tiles_output, {'tile_size': str(tile_slice.tile_size()), 'density': prefix_density}))
     294                return tile_result_paths
     295
     296        def raster_create(self, input_file, layers, tile_slice, gridding_algorithm, nodata_value=None, output_file='/vsimem/water_depth.tif'):
    128297                """
    129298                        Rastering the data from source file into a tif.
    … …  
    137306                        outputType = gdal.GDT_Float32,
    138307                        format = "GTiff",
    139                         width = width,
    140                         height = height,
     308                        width = tile_slice.grid_width(),
     309                        height = tile_slice.grid_height(),
    141310                        outputSRS = "WGS84",
     311                        outputBounds = [tile_slice.lng_lat_box().east(), tile_slice.lng_lat_box().south(), tile_slice.lng_lat_box().west(), tile_slice.lng_lat_box().north()],
    142312                        noData = nodata_value,
    143313                        layers = layers,
     314                        #spatFilter = (tile_slice.lng_lat_box().east(), tile_slice.lng_lat_box().south(), tile_slice.lng_lat_box().west(), tile_slice.lng_lat_box().north()),
    144315                        algorithm = gridding_algorithm
    145316                )
    … …  
    187358                return output_file
    188359
    189         def tiles_create(self, input_file, title, tile_size, output_directory, zoom_range = None):
    190                 if zoom_range is None:
    191                         zoom_range = self._zoom_range
    192                
    193                 tile_zoom_option = "-".join(map(str, zoom_range))
     360        def tiles_create(self, input_file, title, tile_size, output_directory, zoom_range):
     361                tile_zoom_option = '{}-{}'.format(zoom_range.minimum(), zoom_range.maximum())
    194362                # using the patched (tilesize) gdal2tiles.py script here, until the upstream version mades it in the distros
    195363                subprocess.run(['gdal2tiles-gnuboat.py', '-q', '-w', 'none', '--tilesize={}'.format(tile_size), '-z', tile_zoom_option, '-t', title, input_file, output_directory], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    196364
    197         def _tile_width(self, tile_size, zoomlevel):
    198                 lng_lat_box = mercantile.bounds(mercantile.Tile(1, 1, zoomlevel))
    199                 tiles = math.sqrt(self._tile_number(zoomlevel))
    200                 #print ({"tile_size": tile_size, "longitude": 360.0/tiles, "latitude": 180.0/tiles})
    201                 return {"tile_size": tile_size, "longitude": abs(lng_lat_box.west - lng_lat_box.east), "latitude": abs(lng_lat_box.north - lng_lat_box.south)}
    202 
    203         def _tile_number(self, zoomlevel):
    204                 return 2**(zoomlevel*2)
     365        def move_tiles_in_place(self, source_path, target_path):
     366                if not os.path.exists(target_path):
     367                        target_parent = os.path.dirname(target_path)
     368                        if not os.path.exists(target_parent):
     369                                os.makedirs(target_parent)
     370                        shutil.copytree(source_path, target_path)
     371                        return
     372                for item in os.listdir(source_path):
     373                        src = os.path.join(source_path, item)
     374                        if os.path.isdir(src):
     375                                target_path_new = os.path.join(target_path, item)
     376                                if os.path.exists(target_path_new):
     377                                        self.move_tiles_in_place(src, target_path_new)
     378                                else:
     379                                        if not os.path.exists(target_path):
     380                                                os.makedirs(target_path)
     381                                        shutil.copytree(src, target_path_new)
     382                        else:
     383                                if not os.path.exists(target_path):
     384                                        os.makedirs(target_path)
     385                                shutil.copy(src, target_path)
     386
     387        def _datasource_open(self, source_file):
     388                datasource = ogr.Open(source_file)
     389                if datasource is None:
     390                        raise FileNotFoundError('Could not open input file {}'.format(source_file))
     391                if datasource.GetLayerCount() < 1:
     392                        raise ReferenceError('No layers in input file')
     393                return datasource
    205394
    206395        #def contours_create():
  • src/common/setup.py

    r9f5877d r5e16955  
    3535setup(
    3636  name="gnuboat_common",
    37   version="0.4.6",
     37  version="0.4.7",
    3838  maintainer="EngSaS - Langenbach",
    3939  maintainer_email="info@engsas.de",
    … …  
    4444  #package_dir={'': ''},
    4545  packages=find_packages(),
    46   scripts=["bin/gnuboat-log-converter", "bin/gnuboat-log-analyser", "bin/gdal2tiles-gnuboat.py"],
     46  scripts=["bin/gnuboat-log-converter", "bin/gnuboat-log-analyser", "bin/gnuboat-log-uploader", "bin/gdal2tiles-gnuboat.py"],
    4747  long_description=README_TEXT,
    4848  install_requires=reqs_install,
Note: See TracChangeset for help on using the changeset viewer.