maps4fs 1.6.91__py3-none-any.whl → 1.7.5__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of maps4fs might be problematic. Click here for more details.
- maps4fs/__init__.py +4 -2
- maps4fs/generator/component.py +6 -15
- maps4fs/generator/dtm/dtm.py +276 -48
- maps4fs/generator/dtm/nrw.py +127 -0
- maps4fs/generator/dtm/srtm.py +59 -161
- maps4fs/generator/dtm/usgs.py +6 -222
- maps4fs/generator/settings.py +1 -1
- maps4fs/generator/texture.py +51 -49
- maps4fs/toolbox/custom_osm.py +67 -0
- {maps4fs-1.6.91.dist-info → maps4fs-1.7.5.dist-info}/METADATA +64 -29
- {maps4fs-1.6.91.dist-info → maps4fs-1.7.5.dist-info}/RECORD +14 -12
- {maps4fs-1.6.91.dist-info → maps4fs-1.7.5.dist-info}/WHEEL +1 -1
- {maps4fs-1.6.91.dist-info → maps4fs-1.7.5.dist-info}/LICENSE.md +0 -0
- {maps4fs-1.6.91.dist-info → maps4fs-1.7.5.dist-info}/top_level.txt +0 -0
maps4fs/__init__.py
CHANGED
@@ -1,7 +1,8 @@
|
|
1
1
|
# pylint: disable=missing-module-docstring
|
2
2
|
from maps4fs.generator.dtm.dtm import DTMProvider
|
3
|
-
from maps4fs.generator.dtm.srtm import SRTM30Provider
|
4
|
-
from maps4fs.generator.dtm.usgs import USGSProvider
|
3
|
+
from maps4fs.generator.dtm.srtm import SRTM30Provider, SRTM30ProviderSettings
|
4
|
+
from maps4fs.generator.dtm.usgs import USGSProvider, USGSProviderSettings
|
5
|
+
from maps4fs.generator.dtm.nrw import NRWProvider, NRWProviderSettings
|
5
6
|
from maps4fs.generator.game import Game
|
6
7
|
from maps4fs.generator.map import Map
|
7
8
|
from maps4fs.generator.settings import (
|
@@ -9,6 +10,7 @@ from maps4fs.generator.settings import (
|
|
9
10
|
DEMSettings,
|
10
11
|
GRLESettings,
|
11
12
|
I3DSettings,
|
13
|
+
SatelliteSettings,
|
12
14
|
SettingsModel,
|
13
15
|
SplineSettings,
|
14
16
|
TextureSettings,
|
maps4fs/generator/component.py
CHANGED
@@ -188,8 +188,7 @@ class Component:
|
|
188
188
|
self,
|
189
189
|
coordinates: tuple[float, float] | None = None,
|
190
190
|
distance: int | None = None,
|
191
|
-
|
192
|
-
) -> tuple[int, int, int, int]:
|
191
|
+
) -> tuple[float, float, float, float]:
|
193
192
|
"""Calculates the bounding box of the map from the coordinates and the height and
|
194
193
|
width of the map.
|
195
194
|
If coordinates and distance are not provided, the instance variables are used.
|
@@ -199,24 +198,23 @@ class Component:
|
|
199
198
|
of the map. Defaults to None.
|
200
199
|
distance (int, optional): The distance from the center of the map to the edge of the
|
201
200
|
map in all directions. Defaults to None.
|
202
|
-
project_utm (bool, optional): Whether to project the bounding box to UTM.
|
203
201
|
|
204
202
|
Returns:
|
205
|
-
tuple[
|
203
|
+
tuple[float, float, float, float]: The bounding box of the map.
|
206
204
|
"""
|
207
205
|
coordinates = coordinates or self.coordinates
|
208
206
|
distance = distance or int(self.map_rotated_size / 2)
|
209
207
|
|
210
208
|
west, south, east, north = ox.utils_geo.bbox_from_point( # type: ignore
|
211
|
-
coordinates,
|
209
|
+
coordinates,
|
210
|
+
dist=distance,
|
212
211
|
)
|
213
212
|
|
214
213
|
bbox = north, south, east, west
|
215
214
|
self.logger.debug(
|
216
|
-
"Calculated bounding box for component: %s: %s,
|
215
|
+
"Calculated bounding box for component: %s: %s, distance: %s",
|
217
216
|
self.__class__.__name__,
|
218
217
|
bbox,
|
219
|
-
project_utm,
|
220
218
|
distance,
|
221
219
|
)
|
222
220
|
return bbox
|
@@ -225,7 +223,7 @@ class Component:
|
|
225
223
|
"""Saves the bounding box of the map to the component instance from the coordinates and the
|
226
224
|
height and width of the map.
|
227
225
|
"""
|
228
|
-
self.bbox = self.get_bbox(
|
226
|
+
self.bbox = self.get_bbox()
|
229
227
|
self.logger.debug("Saved bounding box: %s", self.bbox)
|
230
228
|
|
231
229
|
@property
|
@@ -544,17 +542,10 @@ class Component:
|
|
544
542
|
"""
|
545
543
|
|
546
544
|
scaling_factor = 1 / self.map.dem_settings.multiplier
|
547
|
-
self.logger.debug("Z scaling factor including DEM multiplier: %s", scaling_factor)
|
548
545
|
|
549
546
|
if self.map.shared_settings.height_scale_multiplier:
|
550
547
|
scaling_factor *= self.map.shared_settings.height_scale_multiplier
|
551
|
-
self.logger.debug(
|
552
|
-
"Z scaling factor including height scale multiplier: %s", scaling_factor
|
553
|
-
)
|
554
548
|
if self.map.shared_settings.mesh_z_scaling_factor:
|
555
549
|
scaling_factor *= 1 / self.map.shared_settings.mesh_z_scaling_factor
|
556
|
-
self.logger.debug(
|
557
|
-
"Z scaling factor including mesh z scaling factor: %s", scaling_factor
|
558
|
-
)
|
559
550
|
|
560
551
|
return scaling_factor
|
maps4fs/generator/dtm/dtm.py
CHANGED
@@ -11,7 +11,10 @@ from typing import TYPE_CHECKING, Type
|
|
11
11
|
import numpy as np
|
12
12
|
import osmnx as ox # type: ignore
|
13
13
|
import rasterio # type: ignore
|
14
|
-
import
|
14
|
+
from rasterio.warp import calculate_default_transform, reproject
|
15
|
+
from rasterio.enums import Resampling
|
16
|
+
from rasterio.merge import merge
|
17
|
+
|
15
18
|
from pydantic import BaseModel
|
16
19
|
|
17
20
|
from maps4fs.logger import Logger
|
@@ -23,8 +26,11 @@ if TYPE_CHECKING:
|
|
23
26
|
class DTMProviderSettings(BaseModel):
|
24
27
|
"""Base class for DTM provider settings models."""
|
25
28
|
|
29
|
+
easy_mode: bool = True
|
30
|
+
power_factor: int = 0
|
31
|
+
|
26
32
|
|
27
|
-
# pylint: disable=too-many-public-methods
|
33
|
+
# pylint: disable=too-many-public-methods, too-many-instance-attributes
|
28
34
|
class DTMProvider(ABC):
|
29
35
|
"""Base class for DTM providers."""
|
30
36
|
|
@@ -44,6 +50,21 @@ class DTMProvider(ABC):
|
|
44
50
|
|
45
51
|
_instructions: str | None = None
|
46
52
|
|
53
|
+
_base_instructions = (
|
54
|
+
"ℹ️ Using **Easy mode** is recommended, as it automatically adjusts the values in the "
|
55
|
+
"image, so the terrain elevation in Giants Editor will match real world "
|
56
|
+
"elevation in meters. \n"
|
57
|
+
"ℹ️ If the terrain height difference in the real world is bigger than 255 meters, "
|
58
|
+
"the [Height scale](https://github.com/iwatkot/maps4fs/blob/main/docs/dem.md#height-scale)"
|
59
|
+
" parameter in the **map.i3d** file will be automatically adjusted. \n"
|
60
|
+
"⚡ If the **Easy mode** option is disabled, you will probably get completely flat "
|
61
|
+
"terrain, unless you adjust the DEM Multiplier Setting or the Height scale parameter in "
|
62
|
+
"the Giants Editor. \n"
|
63
|
+
"💡 You can use the **Power factor** setting to make the difference between heights "
|
64
|
+
"bigger. Be extremely careful with this setting, and use only low values, otherwise your "
|
65
|
+
"terrain may be completely broken. \n"
|
66
|
+
)
|
67
|
+
|
47
68
|
# pylint: disable=R0913, R0917
|
48
69
|
def __init__(
|
49
70
|
self,
|
@@ -169,6 +190,15 @@ class DTMProvider(ABC):
|
|
169
190
|
"""
|
170
191
|
return cls._instructions
|
171
192
|
|
193
|
+
@classmethod
|
194
|
+
def base_instructions(cls) -> str | None:
|
195
|
+
"""Instructions for using any provider.
|
196
|
+
|
197
|
+
Returns:
|
198
|
+
str: Instructions for using any provider.
|
199
|
+
"""
|
200
|
+
return cls._base_instructions
|
201
|
+
|
172
202
|
@property
|
173
203
|
def user_settings(self) -> DTMProviderSettings | None:
|
174
204
|
"""User settings of the provider.
|
@@ -212,63 +242,116 @@ class DTMProvider(ABC):
|
|
212
242
|
"""
|
213
243
|
providers = {}
|
214
244
|
for provider in cls.__subclasses__():
|
215
|
-
|
216
|
-
providers[provider._code] = provider.description() # pylint: disable=W0212
|
245
|
+
providers[provider._code] = provider.description() # pylint: disable=W0212
|
217
246
|
return providers # type: ignore
|
218
247
|
|
219
|
-
|
220
|
-
|
221
|
-
|
222
|
-
Arguments:
|
223
|
-
output_path (str): Path to save the downloaded tile.
|
248
|
+
@abstractmethod
|
249
|
+
def download_tiles(self) -> list[str]:
|
250
|
+
"""Download tiles from the provider.
|
224
251
|
|
225
252
|
Returns:
|
226
|
-
|
253
|
+
list: List of paths to the downloaded tiles.
|
227
254
|
"""
|
228
|
-
|
229
|
-
response = requests.get(url, stream=True, timeout=10)
|
230
|
-
if response.status_code == 200:
|
231
|
-
with open(output_path, "wb") as file:
|
232
|
-
for chunk in response.iter_content(chunk_size=1024):
|
233
|
-
file.write(chunk)
|
234
|
-
return True
|
235
|
-
return False
|
236
|
-
|
237
|
-
def get_or_download_tile(self, output_path: str, **kwargs) -> str | None:
|
238
|
-
"""Get or download a tile from the provider.
|
255
|
+
raise NotImplementedError
|
239
256
|
|
240
|
-
|
241
|
-
|
257
|
+
def get_numpy(self) -> np.ndarray:
|
258
|
+
"""Get numpy array of the tile.
|
259
|
+
Resulting array must be 16 bit (signed or unsigned) integer and it should be already
|
260
|
+
windowed to the bounding box of ROI. It also must have only one channel.
|
242
261
|
|
243
262
|
Returns:
|
244
|
-
|
245
|
-
not downloaded.
|
263
|
+
np.ndarray: Numpy array of the tile.
|
246
264
|
"""
|
247
|
-
|
248
|
-
|
249
|
-
|
250
|
-
|
265
|
+
# download tiles using DTM provider implementation
|
266
|
+
tiles = self.download_tiles()
|
267
|
+
self.logger.debug(f"Downloaded {len(tiles)} DEM tiles")
|
268
|
+
|
269
|
+
# merge tiles if necessary
|
270
|
+
if len(tiles) > 1:
|
271
|
+
self.logger.debug("Multiple tiles downloaded. Merging tiles")
|
272
|
+
tile, _ = self.merge_geotiff(tiles)
|
273
|
+
else:
|
274
|
+
tile = tiles[0]
|
275
|
+
|
276
|
+
# determine CRS of the resulting tile and reproject if necessary
|
277
|
+
with rasterio.open(tile) as src:
|
278
|
+
crs = src.crs
|
279
|
+
if crs != "EPSG:4326":
|
280
|
+
self.logger.debug(f"Reprojecting GeoTIFF from {crs} to EPSG:4326...")
|
281
|
+
tile = self.reproject_geotiff(tile)
|
282
|
+
|
283
|
+
# extract region of interest from the tile
|
284
|
+
data = self.extract_roi(tile)
|
285
|
+
|
286
|
+
# process elevation data to be compatible with the game
|
287
|
+
data = self.process_elevation(data)
|
251
288
|
|
252
|
-
|
253
|
-
|
254
|
-
|
289
|
+
return data
|
290
|
+
|
291
|
+
def process_elevation(self, data: np.ndarray) -> np.ndarray:
|
292
|
+
"""Process elevation data.
|
293
|
+
|
294
|
+
Arguments:
|
295
|
+
data (np.ndarray): Elevation data.
|
255
296
|
|
256
297
|
Returns:
|
257
|
-
|
298
|
+
np.ndarray: Processed elevation data.
|
258
299
|
"""
|
259
|
-
|
300
|
+
self.data_info = {}
|
301
|
+
self.add_numpy_params(data, "original")
|
260
302
|
|
261
|
-
|
262
|
-
|
263
|
-
|
264
|
-
|
265
|
-
|
303
|
+
data = self.signed_to_unsigned(data)
|
304
|
+
self.add_numpy_params(data, "grounded")
|
305
|
+
|
306
|
+
original_deviation = int(self.data_info["original_deviation"])
|
307
|
+
in_game_maximum_height = 65535 // 255
|
308
|
+
if original_deviation > in_game_maximum_height:
|
309
|
+
suggested_height_scale_multiplier = (
|
310
|
+
original_deviation / in_game_maximum_height # type: ignore
|
311
|
+
)
|
312
|
+
suggested_height_scale_value = int(255 * suggested_height_scale_multiplier)
|
313
|
+
else:
|
314
|
+
suggested_height_scale_multiplier = 1
|
315
|
+
suggested_height_scale_value = 255
|
316
|
+
|
317
|
+
self.data_info["suggested_height_scale_multiplier"] = suggested_height_scale_multiplier
|
318
|
+
self.data_info["suggested_height_scale_value"] = suggested_height_scale_value
|
319
|
+
|
320
|
+
self.map.shared_settings.height_scale_multiplier = ( # type: ignore
|
321
|
+
suggested_height_scale_multiplier
|
322
|
+
)
|
323
|
+
self.map.shared_settings.height_scale_value = suggested_height_scale_value # type: ignore
|
324
|
+
|
325
|
+
if self.user_settings.easy_mode: # type: ignore
|
326
|
+
try:
|
327
|
+
data = self.normalize_dem(data)
|
328
|
+
self.add_numpy_params(data, "normalized")
|
329
|
+
|
330
|
+
normalized_deviation = self.data_info["normalized_deviation"]
|
331
|
+
z_scaling_factor = normalized_deviation / original_deviation # type: ignore
|
332
|
+
self.data_info["z_scaling_factor"] = z_scaling_factor
|
333
|
+
|
334
|
+
self.map.shared_settings.mesh_z_scaling_factor = z_scaling_factor # type: ignore
|
335
|
+
self.map.shared_settings.change_height_scale = True # type: ignore
|
336
|
+
|
337
|
+
except Exception as e: # pylint: disable=W0718
|
338
|
+
self.logger.error(
|
339
|
+
"Failed to normalize DEM data. Error: %s. Using original data.", e
|
340
|
+
)
|
341
|
+
|
342
|
+
return data
|
343
|
+
|
344
|
+
def info_sequence(self) -> dict[str, int | str | float] | None:
|
345
|
+
"""Returns the information sequence for the component. Must be implemented in the child
|
346
|
+
class. If the component does not have an information sequence, an empty dictionary must be
|
347
|
+
returned.
|
266
348
|
|
267
349
|
Returns:
|
268
|
-
|
350
|
+
dict[str, int | str | float] | None: Information sequence for the component.
|
269
351
|
"""
|
270
|
-
|
352
|
+
return self.data_info
|
271
353
|
|
354
|
+
# region helpers
|
272
355
|
def get_bbox(self) -> tuple[float, float, float, float]:
|
273
356
|
"""Get bounding box of the tile based on the center point and size.
|
274
357
|
|
@@ -281,6 +364,83 @@ class DTMProvider(ABC):
|
|
281
364
|
bbox = north, south, east, west
|
282
365
|
return bbox
|
283
366
|
|
367
|
+
def reproject_geotiff(self, input_tiff: str) -> str:
|
368
|
+
"""Reproject a GeoTIFF file to a new coordinate reference system (CRS).
|
369
|
+
|
370
|
+
Arguments:
|
371
|
+
input_tiff (str): Path to the input GeoTIFF file.
|
372
|
+
target_crs (str): Target CRS (e.g., EPSG:4326 for CRS:84).
|
373
|
+
|
374
|
+
Returns:
|
375
|
+
str: Path to the reprojected GeoTIFF file.
|
376
|
+
"""
|
377
|
+
output_tiff = os.path.join(self._tile_directory, "merged.tif")
|
378
|
+
|
379
|
+
# Open the source GeoTIFF
|
380
|
+
self.logger.debug("Reprojecting GeoTIFF to %s CRS...", "EPSG:4326")
|
381
|
+
with rasterio.open(input_tiff) as src:
|
382
|
+
# Get the transform, width, and height of the target CRS
|
383
|
+
transform, width, height = calculate_default_transform(
|
384
|
+
src.crs, "EPSG:4326", src.width, src.height, *src.bounds
|
385
|
+
)
|
386
|
+
|
387
|
+
# Update the metadata for the target GeoTIFF
|
388
|
+
kwargs = src.meta.copy()
|
389
|
+
kwargs.update(
|
390
|
+
{"crs": "EPSG:4326", "transform": transform, "width": width, "height": height}
|
391
|
+
)
|
392
|
+
|
393
|
+
# Open the destination GeoTIFF file and reproject
|
394
|
+
with rasterio.open(output_tiff, "w", **kwargs) as dst:
|
395
|
+
for i in range(1, src.count + 1): # Iterate over all raster bands
|
396
|
+
reproject(
|
397
|
+
source=rasterio.band(src, i),
|
398
|
+
destination=rasterio.band(dst, i),
|
399
|
+
src_transform=src.transform,
|
400
|
+
src_crs=src.crs,
|
401
|
+
dst_transform=transform,
|
402
|
+
dst_crs="EPSG:4326",
|
403
|
+
resampling=Resampling.nearest, # Choose resampling method
|
404
|
+
)
|
405
|
+
|
406
|
+
self.logger.debug("Reprojected GeoTIFF saved to %s", output_tiff)
|
407
|
+
return output_tiff
|
408
|
+
|
409
|
+
def merge_geotiff(self, input_files: list[str]) -> tuple[str, str]:
|
410
|
+
"""Merge multiple GeoTIFF files into a single GeoTIFF file.
|
411
|
+
|
412
|
+
Arguments:
|
413
|
+
input_files (list): List of input GeoTIFF files to merge.
|
414
|
+
output_file (str): Path to save the merged GeoTIFF file.
|
415
|
+
"""
|
416
|
+
output_file = os.path.join(self._tile_directory, "merged.tif")
|
417
|
+
# Open all input GeoTIFF files as datasets
|
418
|
+
self.logger.debug("Merging tiff files...")
|
419
|
+
datasets = [rasterio.open(file) for file in input_files]
|
420
|
+
|
421
|
+
# Merge datasets
|
422
|
+
crs = datasets[0].crs
|
423
|
+
mosaic, out_transform = merge(datasets, nodata=0)
|
424
|
+
|
425
|
+
# Get metadata from the first file and update it for the output
|
426
|
+
out_meta = datasets[0].meta.copy()
|
427
|
+
out_meta.update(
|
428
|
+
{
|
429
|
+
"driver": "GTiff",
|
430
|
+
"height": mosaic.shape[1],
|
431
|
+
"width": mosaic.shape[2],
|
432
|
+
"transform": out_transform,
|
433
|
+
"count": mosaic.shape[0], # Number of bands
|
434
|
+
}
|
435
|
+
)
|
436
|
+
|
437
|
+
# Write merged GeoTIFF to the output file
|
438
|
+
with rasterio.open(output_file, "w", **out_meta) as dest:
|
439
|
+
dest.write(mosaic)
|
440
|
+
|
441
|
+
self.logger.debug("GeoTIFF images merged successfully into %s", output_file)
|
442
|
+
return output_file, crs
|
443
|
+
|
284
444
|
def extract_roi(self, tile_path: str) -> np.ndarray:
|
285
445
|
"""Extract region of interest (ROI) from the GeoTIFF file.
|
286
446
|
|
@@ -304,18 +464,86 @@ class DTMProvider(ABC):
|
|
304
464
|
window.width,
|
305
465
|
window.height,
|
306
466
|
)
|
307
|
-
data = src.read(1, window=window)
|
467
|
+
data = src.read(1, window=window, masked=True)
|
308
468
|
if not data.size > 0:
|
309
469
|
raise ValueError("No data in the tile.")
|
310
470
|
|
311
471
|
return data
|
312
472
|
|
313
|
-
def
|
314
|
-
"""
|
315
|
-
|
316
|
-
|
473
|
+
def normalize_dem(self, data: np.ndarray) -> np.ndarray:
|
474
|
+
"""Normalize DEM data to 16-bit unsigned integer using max height from settings.
|
475
|
+
|
476
|
+
Arguments:
|
477
|
+
data (np.ndarray): DEM data from SRTM file after cropping.
|
317
478
|
|
318
479
|
Returns:
|
319
|
-
|
480
|
+
np.ndarray: Normalized DEM data.
|
320
481
|
"""
|
321
|
-
|
482
|
+
maximum_height = int(data.max())
|
483
|
+
minimum_height = int(data.min())
|
484
|
+
deviation = maximum_height - minimum_height
|
485
|
+
self.logger.debug(
|
486
|
+
"Maximum height: %s. Minimum height: %s. Deviation: %s.",
|
487
|
+
maximum_height,
|
488
|
+
minimum_height,
|
489
|
+
deviation,
|
490
|
+
)
|
491
|
+
self.logger.debug("Number of unique values in original DEM data: %s.", np.unique(data).size)
|
492
|
+
|
493
|
+
adjusted_maximum_height = maximum_height * 255
|
494
|
+
adjusted_maximum_height = min(adjusted_maximum_height, 65535)
|
495
|
+
scaling_factor = adjusted_maximum_height / maximum_height
|
496
|
+
self.logger.debug(
|
497
|
+
"Adjusted maximum height: %s. Scaling factor: %s.",
|
498
|
+
adjusted_maximum_height,
|
499
|
+
scaling_factor,
|
500
|
+
)
|
501
|
+
|
502
|
+
if self.user_settings.power_factor: # type: ignore
|
503
|
+
power_factor = 1 + self.user_settings.power_factor / 10 # type: ignore
|
504
|
+
self.logger.debug(
|
505
|
+
"Applying power factor: %s to the DEM data.",
|
506
|
+
power_factor,
|
507
|
+
)
|
508
|
+
data = np.power(data, power_factor).astype(np.uint16)
|
509
|
+
|
510
|
+
normalized_data = np.round(data * scaling_factor).astype(np.uint16)
|
511
|
+
self.logger.debug(
|
512
|
+
"Normalized data maximum height: %s. Minimum height: %s. Number of unique values: %s.",
|
513
|
+
normalized_data.max(),
|
514
|
+
normalized_data.min(),
|
515
|
+
np.unique(normalized_data).size,
|
516
|
+
)
|
517
|
+
return normalized_data
|
518
|
+
|
519
|
+
def signed_to_unsigned(self, data: np.ndarray, add_one: bool = True) -> np.ndarray:
|
520
|
+
"""Convert signed 16-bit integer to unsigned 16-bit integer.
|
521
|
+
|
522
|
+
Arguments:
|
523
|
+
data (np.ndarray): DEM data from SRTM file after cropping.
|
524
|
+
|
525
|
+
Returns:
|
526
|
+
np.ndarray: Unsigned DEM data.
|
527
|
+
"""
|
528
|
+
data = data - data.min()
|
529
|
+
if add_one:
|
530
|
+
data = data + 1
|
531
|
+
return data.astype(np.uint16)
|
532
|
+
|
533
|
+
def add_numpy_params(
|
534
|
+
self,
|
535
|
+
data: np.ndarray,
|
536
|
+
prefix: str,
|
537
|
+
) -> None:
|
538
|
+
"""Add numpy array parameters to the data_info dictionary.
|
539
|
+
|
540
|
+
Arguments:
|
541
|
+
data (np.ndarray): Numpy array of the tile.
|
542
|
+
prefix (str): Prefix for the parameters.
|
543
|
+
"""
|
544
|
+
self.data_info[f"{prefix}_minimum_height"] = int(data.min()) # type: ignore
|
545
|
+
self.data_info[f"{prefix}_maximum_height"] = int(data.max()) # type: ignore
|
546
|
+
self.data_info[f"{prefix}_deviation"] = int(data.max() - data.min()) # type: ignore
|
547
|
+
self.data_info[f"{prefix}_unique_values"] = int(np.unique(data).size) # type: ignore
|
548
|
+
|
549
|
+
# endregion
|
@@ -0,0 +1,127 @@
|
|
1
|
+
"""This module contains provider of USGS data."""
|
2
|
+
|
3
|
+
import os
|
4
|
+
|
5
|
+
import numpy as np
|
6
|
+
from owslib.wcs import WebCoverageService
|
7
|
+
from owslib.util import Authentication
|
8
|
+
from pyproj import Transformer
|
9
|
+
|
10
|
+
from maps4fs.generator.dtm.dtm import DTMProvider, DTMProviderSettings
|
11
|
+
|
12
|
+
|
13
|
+
class NRWProviderSettings(DTMProviderSettings):
|
14
|
+
"""Settings for the USGS provider."""
|
15
|
+
|
16
|
+
|
17
|
+
# pylint: disable=too-many-locals
|
18
|
+
class NRWProvider(DTMProvider):
|
19
|
+
"""Generic provider of WCS sources."""
|
20
|
+
|
21
|
+
_code = "NRW"
|
22
|
+
_name = "North Rhine-Westphalia DGM1"
|
23
|
+
_region = "DE"
|
24
|
+
_icon = "🇩🇪"
|
25
|
+
_resolution = 1
|
26
|
+
_data: np.ndarray | None = None
|
27
|
+
_settings = NRWProviderSettings
|
28
|
+
_author = "[kbrandwijk](https://github.com/kbrandwijk)"
|
29
|
+
_is_community = True
|
30
|
+
_instructions = None
|
31
|
+
|
32
|
+
def __init__(self, *args, **kwargs):
|
33
|
+
super().__init__(*args, **kwargs)
|
34
|
+
self.shared_tiff_path = os.path.join(self._tile_directory, "shared")
|
35
|
+
os.makedirs(self.shared_tiff_path, exist_ok=True)
|
36
|
+
|
37
|
+
def download_tiles(self) -> list[str]:
|
38
|
+
bbox = self.get_bbox()
|
39
|
+
bbox = self.transform_bbox(bbox, "EPSG:25832")
|
40
|
+
|
41
|
+
tiles = self.tile_bbox(bbox, 1000)
|
42
|
+
|
43
|
+
all_tif_files = self.download_all_tiles(tiles)
|
44
|
+
return all_tif_files
|
45
|
+
|
46
|
+
def tile_bbox(
|
47
|
+
self,
|
48
|
+
bbox: tuple[float, float, float, float],
|
49
|
+
tile_size: int) -> list[tuple[float, float, float, float]]:
|
50
|
+
"""Tile the bounding box into smaller bounding boxes of a specified size.
|
51
|
+
|
52
|
+
Arguments:
|
53
|
+
bbox (tuple): Bounding box to tile (north, south, east, west).
|
54
|
+
tile_size (int): Size of the tiles in meters.
|
55
|
+
|
56
|
+
Returns:
|
57
|
+
list: List of smaller bounding boxes (north, south, east, west).
|
58
|
+
"""
|
59
|
+
north, south, east, west = bbox
|
60
|
+
x_coords = np.arange(west, east, tile_size)
|
61
|
+
y_coords = np.arange(south, north, tile_size)
|
62
|
+
x_coords = np.append(x_coords, east).astype(x_coords.dtype)
|
63
|
+
y_coords = np.append(y_coords, north).astype(y_coords.dtype)
|
64
|
+
|
65
|
+
x_min, y_min = np.meshgrid(x_coords[:-1], y_coords[:-1], indexing="ij")
|
66
|
+
x_max, y_max = np.meshgrid(x_coords[1:], y_coords[1:], indexing="ij")
|
67
|
+
|
68
|
+
tiles = np.stack([x_min.ravel(), y_min.ravel(), x_max.ravel(), y_max.ravel()], axis=1)
|
69
|
+
|
70
|
+
return tiles
|
71
|
+
|
72
|
+
def download_all_tiles(self, tiles: list[tuple[float, float, float, float]]) -> list[str]:
|
73
|
+
"""Download tiles from the NRW provider.
|
74
|
+
|
75
|
+
Arguments:
|
76
|
+
tiles (list): List of tiles to download.
|
77
|
+
|
78
|
+
Returns:
|
79
|
+
list: List of paths to the downloaded GeoTIFF files.
|
80
|
+
"""
|
81
|
+
all_tif_files = []
|
82
|
+
wcs = WebCoverageService(
|
83
|
+
'https://www.wcs.nrw.de/geobasis/wcs_nw_dgm',
|
84
|
+
auth=Authentication(verify=False),
|
85
|
+
timeout=600)
|
86
|
+
for tile in tiles:
|
87
|
+
file_name = '_'.join(map(str, tile)) + '.tif'
|
88
|
+
file_path = os.path.join(self.shared_tiff_path, file_name)
|
89
|
+
|
90
|
+
if not os.path.exists(file_path):
|
91
|
+
output = wcs.getCoverage(
|
92
|
+
identifier=['nw_dgm'],
|
93
|
+
subsets=[('y', str(tile[0]), str(tile[2])), ('x', str(tile[1]), str(tile[3]))],
|
94
|
+
format='image/tiff'
|
95
|
+
)
|
96
|
+
with open(file_path, 'wb') as f:
|
97
|
+
f.write(output.read())
|
98
|
+
|
99
|
+
all_tif_files.append(file_path)
|
100
|
+
return all_tif_files
|
101
|
+
|
102
|
+
def transform_bbox(
|
103
|
+
self,
|
104
|
+
bbox: tuple[float, float, float, float],
|
105
|
+
to_crs: str) -> tuple[float, float, float, float]:
|
106
|
+
"""Transform the bounding box to a different coordinate reference system (CRS).
|
107
|
+
|
108
|
+
Arguments:
|
109
|
+
bbox (tuple): Bounding box to transform (north, south, east, west).
|
110
|
+
to_crs (str): Target CRS (e.g., EPSG:4326 for CRS:84).
|
111
|
+
|
112
|
+
Returns:
|
113
|
+
tuple: Transformed bounding box (north, south, east, west).
|
114
|
+
"""
|
115
|
+
transformer = Transformer.from_crs("epsg:4326", to_crs)
|
116
|
+
north, south, east, west = bbox
|
117
|
+
bottom_left_x, bottom_left_y = transformer.transform(xx=south, yy=west)
|
118
|
+
top_left_x, top_left_y = transformer.transform(xx=north, yy=west)
|
119
|
+
top_right_x, top_right_y = transformer.transform(xx=north, yy=east)
|
120
|
+
bottom_right_x, bottom_right_y = transformer.transform(xx=south, yy=east)
|
121
|
+
|
122
|
+
west = min(bottom_left_y, bottom_right_y)
|
123
|
+
east = max(top_left_y, top_right_y)
|
124
|
+
south = min(bottom_left_x, top_left_x)
|
125
|
+
north = max(bottom_right_x, top_right_x)
|
126
|
+
|
127
|
+
return north, south, east, west
|