Skip to content

Commit 60c0f23

Browse files
committed
com6RockAvalanche: Update variableVoellmyShapeToRaster
Update variableVoellmyShapeToRaster so that inputs are fetched automatically and no file paths are needed
1 parent d5624ec commit 60c0f23

File tree

6 files changed

+75
-112
lines changed

6 files changed

+75
-112
lines changed

avaframe/avaframeCfg.ini

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
[MAIN]
66
# Path to avalanche directory
7-
avalancheDir = data/avaParabola
7+
avalancheDir =
88

99
# number of CPU cores to use for the computation of com1DFA
1010
# possible values are:
Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,23 @@
11
The VariableVoellmyShapeToRaster.py script allows the user to define spatially different values for the voellmy Parameters mu and xsi, with the use of polygon shapefiles. For the extent of a DEM raster, all the areas that are not covered by a polygon get assigned a default mu or xsi value. The script then converts this Information into a raster mu and a raster xsi file, which can then be used in Avaframe Simulation runs, using the "spatialVoellmy" friction model.
22

33
First, set up the Config File and provide inputs:
4+
•Config File:
5+
oIn the first step, the Config File needs to be configured and all input files have to be provided
6+
Main Config (avaframeCfg.ini):
7+
•Set the path to the avalanche directory
48
oInputs:
5-
dem: Path to the DEM Raster that is later on used for the avaframe simulation. This is needed, because the mu and xsi output rasters need to be the exact same size. Usually this file lies in \AvaFrame\avaframe\data\ *yourAvalancheDir*\Inputs
6-
mu_shapefile: Path to the mu shapefile, that is then converted to a raster file. Be aware, that the attribute has to be named “xsi”.
7-
xsi_shapefile: Path to the xsi shapefile, that is then converted to a raster file. Be aware, that the attribute has to be named “mu”.
9+
All the Input Files are automatically fetched through the set avalanche directory. It is not necessary to provide a file path.
10+
dem: DEM Raster that is later on used for the avaframe simulation. This is needed, because the mu and xsi output rasters need to be the exact same size. Has to lie in avadir/Inputs.
11+
mu_shapefile: Mu shapefile, that is then converted to a raster file. Be aware, that the attribute has to be named “mu” and the file name has to end with “_mu”. Has to lie in avadir/Inputs/POLYGONS.
12+
xsi_shapefile: Xsi shapefile, that is then converted to a raster file. Be aware, that the attribute has to be named “xsi” and the file name has to end with “_xsi”. Has to lie in avadir/Inputs/POLYGONS.
813
oDefaults:
914
default_mu: this is the default mu value, that gets assigned to all areas in the raster, that are not covered by shapefile-polygons
1015
default_xsi: this is the default xsi value, that gets assigned to all areas in the raster, that are not covered by shapefile-polygons
11-
12-
RunScript:
16+
oOutputs:
17+
For the variable Voellmy calculations in the com1DFA algorithm to work, it is mandatory, that the files are stored in: avaframe\data\*yourAvalancheDir*\Inputs\RASTERS\
18+
mu_raster: Output for the generated mu raster file stored as *_mu.asc
19+
xsi_raster: Output for the generated xsi raster file stored as *_xi.asc
20+
21+
•RunScript:
1322
oOnce everything is set up, run the script “runVariableVoellmyShapeToRaster.py”
1423
oIf libraries are missing use: pip install *name of missing library

avaframe/com6RockAvalanche/variableVoellmyShapeToRaster.ini

Lines changed: 0 additions & 33 deletions
This file was deleted.
Lines changed: 30 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,48 @@
1-
# -*- coding: utf-8 -*-
2-
"""
3-
Created on Tue Jan 21 11:43:18 2025
4-
5-
@author: Domi
6-
"""
7-
1+
82
import rasterio
93
import numpy as np
10-
import configparser
4+
import pathlib
115
from rasterio.features import rasterize
126
from shapely.geometry import shape, mapping
137
from in2Trans.shpConversion import SHP2Array
8+
from in1Data.getInput import getAndCheckInputFiles
149
import logging
1510

1611
# Configure logging
1712
logging.basicConfig(level=logging.DEBUG)
1813
log = logging.getLogger(__name__)
1914

20-
def generateMuXsiRasters(configPath):
15+
def generateMuXsiRasters(avadir, variableVoellmyCfg):
2116
"""
22-
Generate raster files for μ and ξ based on input DEM and shapefiles.
17+
Generate raster files for \u03bc and \u03be based on input DEM and shapefiles.
2318
2419
Parameters
2520
----------
26-
configPath : str
27-
Path to the configuration file.
21+
avadir : str
22+
Path to the avalanche directory.
23+
variableVoellmyCfg : Config Parser Object
24+
variableVoellmyCfg Configuration File
2825
2926
Returns
3027
-------
3128
None
3229
"""
33-
# Load configuration
34-
config = configparser.ConfigParser()
35-
config.read(configPath)
30+
avadir = pathlib.Path(avadir)
31+
32+
config = variableVoellmyCfg # Directly use the ConfigParser object
33+
34+
inputDir = avadir / "Inputs"
35+
outputDir = avadir / "Inputs" # Output directory is Inputs, because Outputs of this Script will be used as Inputs for AvaFrame
36+
37+
demPath, _ = getAndCheckInputFiles(inputDir, '', 'DEM', fileExt='asc')
38+
muShapefile, _ = getAndCheckInputFiles(inputDir, 'POLYGONS', '\u03bc Shapefile', fileExt='shp', fileSuffix='_mu')
39+
xsiShapefile, _ = getAndCheckInputFiles(inputDir, 'POLYGONS', '\u03be Shapefile', fileExt='shp', fileSuffix='_xsi')
40+
41+
muOutputPath = outputDir / "RASTERS" / "raster_mu.asc"
42+
xsiOutputPath = outputDir / "RASTERS" /"raster_xi.asc"
3643

37-
demPath = config['INPUT']['dem']
38-
muShapefile = config['INPUT']['mu_shapefile']
39-
xsiShapefile = config['INPUT']['xsi_shapefile']
4044
defaultMu = float(config['DEFAULTS']['default_mu'])
4145
defaultXsi = float(config['DEFAULTS']['default_xsi'])
42-
muOutputPath = config['OUTPUT']['mu_raster']
43-
xsiOutputPath = config['OUTPUT']['xsi_raster']
4446

4547
# Read DEM
4648
with rasterio.open(demPath) as demSrc:
@@ -49,7 +51,6 @@ def generateMuXsiRasters(configPath):
4951
demCrs = demSrc.crs
5052
demShape = demData.shape
5153

52-
# Helper function to rasterize shapefiles
5354
def rasterizeShapefile(shapefilePath, defaultValue, attributeName):
5455
if not shapefilePath:
5556
return np.full(demShape, defaultValue, dtype=np.float32)
@@ -61,45 +62,25 @@ def rasterizeShapefile(shapefilePath, defaultValue, attributeName):
6162
length = int(shpData['Length'][i])
6263
coords = [(shpData['x'][j], shpData['y'][j]) for j in range(start, start + length)]
6364
poly = shape({'type': 'Polygon', 'coordinates': [coords]})
64-
value = shpData['attributes'][i][attributeName] # Extract the attribute value
65+
value = shpData['attributes'][i][attributeName]
6566
shapes.append((mapping(poly), value))
6667

67-
rasterData = rasterize(
68-
shapes,
69-
out_shape=demShape,
70-
transform=demTransform,
71-
fill=defaultValue,
72-
all_touched=True,
73-
dtype=np.float32
74-
)
75-
return rasterData
76-
77-
# Generate μ and ξ rasters
78-
log.info("Rasterizing μ shapefile.")
68+
return rasterize(shapes, out_shape=demShape, transform=demTransform, fill=defaultValue, all_touched=True, dtype=np.float32)
69+
70+
log.info("Rasterizing \u03bc shapefile.")
7971
muRaster = rasterizeShapefile(muShapefile, defaultMu, "mu")
8072

81-
log.info("Rasterizing ξ shapefile.")
73+
log.info("Rasterizing \u03be shapefile.")
8274
xsiRaster = rasterizeShapefile(xsiShapefile, defaultXsi, "xsi")
8375

84-
# Save output rasters
8576
def saveRaster(outputPath, data):
86-
with rasterio.open(
87-
outputPath,
88-
'w',
89-
driver='GTiff',
90-
height=data.shape[0],
91-
width=data.shape[1],
92-
count=1,
93-
dtype=data.dtype,
94-
crs=demCrs,
95-
transform=demTransform,
96-
) as dst:
77+
with rasterio.open(outputPath, 'w', driver='GTiff', height=data.shape[0], width=data.shape[1], count=1, dtype=data.dtype, crs=demCrs, transform=demTransform) as dst:
9778
dst.write(data, 1)
9879

99-
log.info("Saving μ raster to %s", muOutputPath)
80+
log.info("Saving \u03bc raster to %s", muOutputPath)
10081
saveRaster(muOutputPath, muRaster)
10182

102-
log.info("Saving ξ raster to %s", xsiOutputPath)
83+
log.info("Saving \u03be raster to %s", xsiOutputPath)
10384
saveRaster(xsiOutputPath, xsiRaster)
10485

10586
log.info("Raster generation completed.")
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
[DEFAULTS]
2+
# Default \u03bc value for areas not covered by shapefiles
3+
default_mu = 0.1
4+
5+
# Default \u03be value for areas not covered by shapefiles
6+
default_xsi = 300.0
Lines changed: 24 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,60 +1,60 @@
1-
# -*- coding: utf-8 -*-
2-
"""
3-
Created on Tue Jan 21 11:49:44 2025
4-
5-
@author: Domi
6-
"""
71

82
import argparse
93
import pathlib
10-
from com6RockAvalanche.variableVoellmyShapeToRaster import generateMuXsiRasters
4+
import time
115
from avaframe.in3Utils import cfgUtils
126
from avaframe.in3Utils import logUtils
13-
from avaframe.in3Utils import initializeProject as initProj
7+
import avaframe.in3Utils.initializeProject as initProj
8+
from com6RockAvalanche import variableVoellmyShapeToRaster
9+
from com6RockAvalanche.variableVoellmyShapeToRaster import generateMuXsiRasters
1410

15-
def runMuXsiWorkflow(configPath=''):
11+
def runMuXsiWorkflow(avadir=''):
1612
"""
1713
Run the workflow to generate \u03bc and \u03be rasters.
1814
1915
Parameters
2016
----------
21-
configPath : str
22-
Path to the configuration file.
17+
avadir : str
18+
Path to the avalanche directory containing input and output folders.
2319
2420
Returns
2521
-------
2622
None
2723
"""
24+
startTime = time.time()
2825
logName = 'runMuXsi'
2926

3027
# Load general configuration file
3128
cfgMain = cfgUtils.getGeneralConfig()
32-
33-
# Load configuration file path from general config if not provided
34-
if configPath:
35-
cfgMain['MAIN']['configFile'] = configPath
29+
if avadir:
30+
cfgMain['MAIN']['avalancheDir'] = avadir
3631
else:
37-
configPath = cfgMain['MAIN']['configFile']
32+
avadir = cfgMain['MAIN']['avalancheDir']
3833

39-
configPath = pathlib.Path(configPath)
34+
avadir = pathlib.Path(avadir)
4035

4136
# Start logging
42-
log = logUtils.initiateLogger(configPath.parent, logName)
37+
log = logUtils.initiateLogger(avadir, logName)
4338
log.info('MAIN SCRIPT')
44-
log.info('Using configuration file: %s', configPath)
39+
log.info('Using avalanche directory: %s', avadir)
4540

4641
# Clean input directory(ies) of old work files
47-
initProj.cleanSingleAvaDir(configPath.parent, deleteOutput=False)
42+
initProj.cleanSingleAvaDir(avadir, deleteOutput=False)
43+
44+
# Load module-specific configuration for Variable Voellmy
45+
variableVoellmyCfg = cfgUtils.getModuleConfig(variableVoellmyShapeToRaster)
4846

4947
# Run the raster generation process
50-
generateMuXsiRasters(str(configPath))
48+
generateMuXsiRasters(avadir, variableVoellmyCfg)
5149

50+
endTime = time.time()
51+
log.info("Took %6.1f seconds to calculate.", (endTime - startTime))
5252
log.info('Workflow completed successfully.')
5353

5454
if __name__ == '__main__':
5555
parser = argparse.ArgumentParser(description='Run \u03bc and \u03be raster generation workflow')
56-
parser.add_argument('configPath', metavar='c', type=str, nargs='?', default='',
57-
help='Path to the configuration file')
56+
parser.add_argument('avadir', metavar='a', type=str, nargs='?', default='',
57+
help='Path to the avalanche directory')
5858

5959
args = parser.parse_args()
60-
runMuXsiWorkflow(str(args.configPath))
60+
runMuXsiWorkflow(str(args.avadir))

0 commit comments

Comments
 (0)