Skip to content

Commit

Permalink
Add working version for renaming
Browse files Browse the repository at this point in the history
  • Loading branch information
fso42 committed Jul 4, 2022
1 parent ebfa5b3 commit 14919f2
Showing 1 changed file with 26 additions and 202 deletions.
228 changes: 26 additions & 202 deletions avaframeLayerRename_algorithm.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,28 +40,11 @@
from qgis.PyQt.QtCore import QCoreApplication
from qgis.core import (
QgsProcessing,
# QgsFeatureSink,
# QgsFeatureRequest,
# QgsVectorLayer,
QgsProject,
# QgsRasterLayer,
QgsProcessingException,
QgsProcessingAlgorithm,
# QgsProcessingContext,
# QgsProcessingParameterFeatureSource,
QgsProcessingParameterString,
# QgsProcessingParameterBoolean,
# QgsProcessingParameterRasterLayer,
# QgsProcessingParameterVectorLayer,
QgsProcessingParameterMultipleLayers,
# QgsProcessingParameterVectorDestination,
# QgsProcessingParameterFolderDestination,
# QgsProcessingParameterRasterDestination,
# QgsProcessingLayerPostProcessorInterface,
# QgsProcessingOutputVectorLayer,
# QgsProcessingOutputRasterLayer,
# QgsProcessingOutputMultipleLayers,
# QgsProcessingParameterFeatureSink
)
from qgis import processing
import avaframe
Expand All @@ -74,7 +57,7 @@ class AvaFrameLayerRenameAlgorithm(QgsProcessingAlgorithm):
Rename avaframe layers by adding choosen parameters and their values
"""

# LAYERS = 'LAYERS'
LAYERS = 'LAYERS'
VARS = 'VARS'


Expand All @@ -84,21 +67,18 @@ def initAlgorithm(self, config):
with some other properties.
"""

# self.addParameter(QgsProcessingParameterMultipleLayers(
# self.LAYERS,
# self.tr('Layer(s) to rename'),
# layerType=QgsProcessing.TypeMapLayer
# ))
self.addParameter(QgsProcessingParameterMultipleLayers(
self.LAYERS,
self.tr('Layer(s) to rename'),
layerType=QgsProcessing.TypeMapLayer
))

self.addParameter(QgsProcessingParameterString(
self.VARS,
self.tr('Comma separated list (no spaces) of parameters to add to name'),
''
))

# self.addOutput(
# QgsProcessingOutputMultipleLayers(
# self.OUTPPR,
# ))

def processAlgorithm(self, parameters, context, feedback):
"""
Expand All @@ -109,15 +89,13 @@ def processAlgorithm(self, parameters, context, feedback):

#for Testing, together with:
# ➜ qgis_process run AVAFRAME:AvaFrameLayerRename --project_path=/home/felix/tmp/TestProj.qgz -- LAYERS= VARS='mu'


project = QgsProject().instance()
allLay = project.mapLayers().values()

# allLay = self.parameterAsLayerList(parameters, self.LAYERS, context)
# if allLay is None:
# raise QgsProcessingException(self.invalidSourceError(parameters, self.LAYERS))
# allLay = project.mapLayers().values()

allLay = self.parameterAsLayerList(parameters, self.LAYERS, context)
if allLay is None:
raise QgsProcessingException(self.invalidSourceError(parameters, self.LAYERS))
#
vars = self.parameterAsString(parameters, self.VARS, context)

feedback.pushInfo(vars)
Expand All @@ -139,183 +117,29 @@ def processAlgorithm(self, parameters, context, feedback):
# make the list unique
avaDirs = list(set(avaDirList))

print(avaDirs)
# get rename info
# TODO: merge DF across avaDirs
allRenameDF = pandas.DataFrame()
for avaDir in avaDirs:
avaDir = pathlib.Path(avaDir)
renameDF = cfgHandling.addInfoToSimName(avaDir,vars)

print(renameDF)
allRenameDF = pandas.concat([allRenameDF, renameDF])

# Loop through layers again, this time renaming
for layer in toRenameList:
layerPath = layer.dataProvider().dataSourceUri()
print(layer.dataProvider().dataSourceUri())
print(layer.name())
layer.setName('Hutzliputzli')
print(layer.name())
# # copy DEM
# sourceDEMPath = pathlib.Path(sourceDEM.source())
# targetDEMPath = targetDir / 'Inputs'
# try:
# shutil.copy(sourceDEMPath, targetDEMPath)
# except shutil.SameFileError:
# pass
#
# # copy all release shapefile parts
# for sourceREL in relDict:
# sourceRELPath = pathlib.Path(sourceREL)
# targetRELPath = targetDir / 'Inputs' / 'REL'
#
# shpParts = self.getSHPParts(sourceRELPath)
# for shpPart in shpParts:
# try:
# shutil.copy(shpPart, targetRELPath)
# except shutil.SameFileError:
# pass
#
# # copy all entrainment shapefile parts
# if sourceENT is not None:
# sourceENTPath = pathlib.Path(sourceENT.source())
# targetENTPath = targetDir / 'Inputs' / 'ENT'
#
# shpParts = self.getSHPParts(sourceENTPath)
# for shpPart in shpParts:
# try:
# shutil.copy(shpPart, targetENTPath)
# except shutil.SameFileError:
# pass
#
# # copy all resistance shapefile parts
# if sourceRES is not None:
# sourceRESPath = pathlib.Path(sourceRES.source())
# targetRESPath = targetDir / 'Inputs' / 'RES'
#
# shpParts = self.getSHPParts(sourceRESPath)
# for shpPart in shpParts:
# try:
# shutil.copy(shpPart, targetRESPath)
# except shutil.SameFileError:
# pass
#
# # copy all Profile shapefile parts
# if sourcePROFILE is not None:
# sourcePROFILEPath = pathlib.Path(sourcePROFILE.source())
# targetPROFILEPath = targetDir / 'Inputs' / 'LINES'
#
# shpParts = self.getSHPParts(sourcePROFILEPath)
#
# for shpPart in shpParts:
# try:
# # make sure this file contains AB (for com2AB)
# if 'AB' not in str(shpPart):
# newName = shpPart.stem + '_AB' + shpPart.suffix
# newName = targetPROFILEPath / newName
# shutil.copy(shpPart, newName)
# else:
# shutil.copy(shpPart, targetPROFILEPath)
# except shutil.SameFileError:
# pass
#
# # copy all Splitpoint shapefile parts
# if sourceSPLITPOINTS is not None:
# sourceSPLITPOINTSPath = pathlib.Path(sourceSPLITPOINTS.source())
# targetSPLITPOINTSPath = targetDir / 'Inputs' / 'POINTS'
#
# shpParts = self.getSHPParts(sourceSPLITPOINTSPath)
# for shpPart in shpParts:
# try:
# shutil.copy(shpPart, targetSPLITPOINTSPath)
# except shutil.SameFileError:
# pass
#
#
# feedback.pushInfo('Starting the simulations')
# feedback.pushInfo('This might take a while')
# feedback.pushInfo('Open Plugins -> Python Console to see the progress')
#
# abResultsSource, rasterResults = runOp.runOperational(str(targetDir))
#
# feedback.pushInfo('Done, start loading the results')
#
# if abResultsSource == 'None':
# source = None
# feedback.pushInfo('Alpha Beta was not run')
# else:
# feedback.pushInfo('Found ab source')
# shpLayer = str(abResultsSource) + '.shp'
#
# source = QgsVectorLayer(shpLayer, "AlphaBeta", "ogr")
#
#
# scriptDir = Path(__file__).parent
# qmls = dict()
# qmls['ppr'] = str(scriptDir / 'QGisStyles' / 'ppr.qml')
# qmls['pfd'] = str(scriptDir / 'QGisStyles' / 'pfd.qml')
# qmls['pfv'] = str(scriptDir / 'QGisStyles' / 'pfv.qml')
#
# allRasterLayers = list()
# for index, row in rasterResults.iterrows():
# print(row["files"], row["resType"])
# rstLayer = QgsRasterLayer(str(row['files']), row['names'])
# rstLayer.loadNamedStyle(qmls[row['resType']])
#
# allRasterLayers.append(rstLayer)
#
# # should work, but doesn't...
# # rstLayer.setName('ThisIsDaStuff')
#
#
# # # Add SamosAT Group
# # Root = QgsProject.instance().layerTreeRoot()
#
# # # See if SamosAT group exists
# # # if not, create
# # SatGroup = Root.findGroup("com1DFA")
# # if SatGroup:
# # feedback.pushDebugInfo('Found')
# # else:
# # feedback.pushDebugInfo('Not Found')
# # SatGroup = Root.insertGroup(0, "com1DFA")
#
# context.temporaryLayerStore().addMapLayers(allRasterLayers)
#
# for item in allRasterLayers:
# context.addLayerToLoadOnCompletion(
# item.id(),
# QgsProcessingContext.LayerDetails('raster layer',
# context.project(),
# self.OUTPPR))
#
# if source is not None:
# context.temporaryLayerStore().addMapLayer(source)
# context.addLayerToLoadOnCompletion(
# source.id(),
# QgsProcessingContext.LayerDetails('OGR layer',
# context.project(),
# self.OUTPUT))
#
# # context.temporaryLayerStore().addMapLayer(rstLayer)
# # context.addLayerToLoadOnCompletion(
# # rstLayer.id(),
# # QgsProcessingContext.LayerDetails('raster layer',
# # context.project(),
# # self.OUTPPR))
#
# # context.layerToLoadOnCompletionDetails(rstLayer.id()).setPostProcessor(renamer)
#
# # self.ImportDFA(sourceDIR, Sim, SatGroup)
#
# # iface.layerTreeView().collapseAllNodes()
# #
# feedback.pushInfo('\n---------------------------------')
# feedback.pushInfo('Done, find results and logs here:')
# feedback.pushInfo(str(targetDir.resolve()))
# feedback.pushInfo('---------------------------------\n')
#
name = layer.name()
# get variable type by splitting at last underscore
simName, delim, varType = name.rpartition('_')

# find corresponding simName
dfRow = allRenameDF.loc[allRenameDF['simName'] == simName]

# take newName and readd variable type
newLayerName = dfRow['newName'].values[0] + '_' + varType

# finally rename
layer.setName(newLayerName)

# return {self.OUTPUT: source, self.OUTPPR: allRasterLayers}
return {}

def name(self):
Expand Down

0 comments on commit 14919f2

Please sign in to comment.