Skip to content

Commit 74f59cf

Browse files
committed
refactor(com1DFA): improve code readability and fix logging messages; comments AW
- Introduced a deep copy for `com1DFA` configuration to prevent unintended mutations - `getModuleConfig` priority documentation and logic handling - Added warning for ignored friction calibration in expert mode
1 parent ebc0d2a commit 74f59cf

3 files changed

Lines changed: 51 additions & 36 deletions

File tree

avaframe/com3Hybrid/com3Hybrid.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -78,15 +78,16 @@ def maincom3Hybrid(cfgMain, cfgHybrid):
7878
iterate = True
7979
resultsHybrid = {}
8080
while iteration < nIterMax and iterate:
81-
# update the com1DFA mu value directly in ConfigParser
82-
com1DFACfg['GENERAL']['mucoulomb'] = '%.4f' % muArray[-1]
81+
# create a copy to avoid com1DFAMain modifying the original config
82+
com1DFACfgCopy = copy.deepcopy(com1DFACfg)
83+
com1DFACfgCopy['GENERAL']['mucoulomb'] = '%.4f' % muArray[-1]
8384

8485
log.info('Mu is set to: %f' % muArray[-1])
8586
# ++++++++++ RUN COM1DFA +++++++++++
8687
# Run dense flow with coulomb friction
8788
# Clean input directory of old work and output files from module
8889
initProj.cleanModuleFiles(avalancheDir, com1DFA, deleteOutput=False)
89-
dem, _, _, simDF = com1DFA.com1DFAMain(cfgMain, cfgInfo=com1DFACfg)
90+
dem, _, _, simDF = com1DFA.com1DFAMain(cfgMain, cfgInfo=com1DFACfgCopy)
9091
simID = simDF.index[0]
9192
particlesList, timeStepInfo = particleTools.readPartFromPickle(avalancheDir, simName=simID, flagAvaDir=True,
9293
comModule='com1DFA')
@@ -135,7 +136,7 @@ def maincom3Hybrid(cfgMain, cfgHybrid):
135136
iteration = iteration + 1
136137

137138
# write final com1DFA configuration to file for documentation
138-
cfgUtils.writeCfgFile(avalancheDir, com1DFA, com1DFACfg, fileName='com1DFA_settings',
139+
cfgUtils.writeCfgFile(avalancheDir, com1DFA, com1DFACfgCopy, fileName='com1DFA_settings',
139140
filePath=workPath)
140141

141142
# fetch fields for desired time step

avaframe/in3Utils/cfgUtils.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -95,10 +95,16 @@ def getGeneralConfig(nameFile=""):
9595
return cfg
9696

9797

98-
def getModuleConfig(module, avalancheDir="", fileOverride="", batchCfgDir="", modInfo=False, toPrint=True, onlyDefault=False):
98+
def getModuleConfig(
99+
module, avalancheDir="", fileOverride="", batchCfgDir="", modInfo=False, toPrint=True, onlyDefault=False
100+
):
99101
"""Returns the configuration for a given module
100102
returns a configParser object OR pathlib.Path (when batchCfgDir is used)
101103
104+
Priority order:
105+
batchCfgDir (returns Path) -> onlyDefault -> fileOverride -> expert config (CFGs/) ->
106+
local_MODULECfg.ini -> MODULECfg.ini
107+
102108
Parameters
103109
----------
104110
module : module object or pathlib.Path
@@ -132,8 +138,6 @@ def getModuleConfig(module, avalancheDir="", fileOverride="", batchCfgDir="", mo
132138
ConfigParser object with merged configuration, OR
133139
pathlib.Path when batchCfgDir is provided
134140
135-
Priority order:
136-
batchCfgDir (returns Path) -> fileOverride -> expert config (CFGs/) -> local_MODULECfg.ini -> MODULECfg.ini
137141
138142
"""
139143
if isinstance(onlyDefault, bool) == False:

avaframe/runCom1DFA.py

Lines changed: 39 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""
2-
Run script for running python com1DFA kernel
2+
Run script for running python com1DFA kernel
33
"""
4+
45
# Load modules
56
# importing general python modules
67
import time
@@ -16,8 +17,9 @@
1617
from avaframe.in3Utils import logUtils
1718
from avaframe.in3Utils import fileHandlerUtils as fU
1819

19-
def runCom1DFA(avalancheDir='', calibration=''):
20-
""" Run com1DFA in the default configuration with only an
20+
21+
def runCom1DFA(avalancheDir="", calibration=""):
22+
"""Run com1DFA in the default configuration with only an
2123
avalanche directory as input and the (optional) friction calibration
2224
size
2325
@@ -38,21 +40,21 @@ def runCom1DFA(avalancheDir='', calibration=''):
3840
startTime = time.time()
3941

4042
# log file name; leave empty to use default runLog.log
41-
logName = 'runCom1DFA'
43+
logName = "runCom1DFA"
4244

4345
# Load avalanche directory from general configuration file
4446
# More information about the configuration can be found here
4547
# on the Configuration page in the documentation
4648
cfgMain = cfgUtils.getGeneralConfig()
47-
if avalancheDir != '':
48-
cfgMain['MAIN']['avalancheDir'] = avalancheDir
49+
if avalancheDir != "":
50+
cfgMain["MAIN"]["avalancheDir"] = avalancheDir
4951
else:
50-
avalancheDir = cfgMain['MAIN']['avalancheDir']
52+
avalancheDir = cfgMain["MAIN"]["avalancheDir"]
5153

5254
# Start logging
5355
log = logUtils.initiateLogger(avalancheDir, logName)
54-
log.info('MAIN SCRIPT')
55-
log.info('Current avalanche: %s', avalancheDir)
56+
log.info("MAIN SCRIPT")
57+
log.info("Current avalanche: %s", avalancheDir)
5658

5759
# ----------------
5860
# Clean input directory(ies) of old work and output files
@@ -63,42 +65,50 @@ def runCom1DFA(avalancheDir='', calibration=''):
6365
# Set friction model according to cmd argument
6466
cfgCom1DFA = cfgUtils.getModuleConfig(com1DFA, avalancheDir, toPrint=False)
6567

66-
if calibration.lower() == 'small':
67-
cfgCom1DFA['GENERAL']['frictModel'] = 'samosATSmall'
68-
elif calibration.lower() == 'medium':
69-
cfgCom1DFA['GENERAL']['frictModel'] = 'samosATMedium'
70-
elif calibration.lower() == 'large':
71-
cfgCom1DFA['GENERAL']['frictModel'] = 'samosAT'
72-
elif calibration.lower() == 'auto':
73-
cfgCom1DFA['GENERAL']['frictModel'] = 'samosATAuto'
68+
if isinstance(cfgCom1DFA, pathlib.Path):
69+
log.warning("Expert mode detected - friction calibration override is ignored")
70+
elif calibration.lower() == "small":
71+
cfgCom1DFA["GENERAL"]["frictModel"] = "samosATSmall"
72+
elif calibration.lower() == "medium":
73+
cfgCom1DFA["GENERAL"]["frictModel"] = "samosATMedium"
74+
elif calibration.lower() == "large":
75+
cfgCom1DFA["GENERAL"]["frictModel"] = "samosAT"
76+
elif calibration.lower() == "auto":
77+
cfgCom1DFA["GENERAL"]["frictModel"] = "samosATAuto"
7478
else:
75-
log.info('no friction calibration override given - using ini')
79+
log.info("no friction calibration override given - using ini")
7680

7781
# ----------------
7882
# Run dense flow
7983
dem, plotDict, reportDictList, simDF = com1DFA.com1DFAMain(cfgMain, cfgInfo=cfgCom1DFA)
8084

8185
# Get peakfiles to return to QGIS
8286
avaDir = pathlib.Path(avalancheDir)
83-
inputDir = avaDir / 'Outputs' / 'com1DFA' / 'peakFiles'
87+
inputDir = avaDir / "Outputs" / "com1DFA" / "peakFiles"
8488
peakFilesDF = fU.makeSimDF(inputDir, avaDir=avaDir)
8589

8690
# Print time needed
8791
endTime = time.time()
88-
log.info('Took %6.1f seconds to calculate.' % (endTime - startTime))
92+
log.info("Took %6.1f seconds to calculate." % (endTime - startTime))
8993

9094
return peakFilesDF
9195

9296

93-
if __name__ == '__main__':
94-
95-
parser = argparse.ArgumentParser(description='Run com1DFA workflow')
96-
parser.add_argument('avadir', metavar='avalancheDir', type=str, nargs='?', default='',
97-
help='the avalanche directory')
98-
parser.add_argument('-fc', '--friction_calibration', choices=['auto', 'large', 'medium', 'small', 'ini'],
99-
type=str, default='ini',
100-
help='friction calibration override, possible values are large, medium , small, auto and ini.' +
101-
'Overrides default AND local configs')
97+
if __name__ == "__main__":
98+
99+
parser = argparse.ArgumentParser(description="Run com1DFA workflow")
100+
parser.add_argument(
101+
"avadir", metavar="avalancheDir", type=str, nargs="?", default="", help="the avalanche directory"
102+
)
103+
parser.add_argument(
104+
"-fc",
105+
"--friction_calibration",
106+
choices=["auto", "large", "medium", "small", "ini"],
107+
type=str,
108+
default="ini",
109+
help="friction calibration override, possible values are large, medium , small, auto and ini."
110+
+ "Overrides default AND local configs",
111+
)
102112

103113
args = parser.parse_args()
104114
runCom1DFA(str(args.avadir), str(args.friction_calibration))

0 commit comments

Comments
 (0)