-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathWorkflow.py
314 lines (264 loc) · 12.1 KB
/
Workflow.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
"""
***************************************************************************
Workflow.py
-------------------------------------
Copyright (C) 2014 TIGER-NET (www.tiger-net.org)
***************************************************************************
* This plugin is part of the Water Observation Information System (WOIS) *
* developed under the TIGER-NET project funded by the European Space *
* Agency as part of the long-term TIGER initiative aiming at promoting *
* the use of Earth Observation (EO) for improved Integrated Water *
* Resources Management (IWRM) in Africa. *
* *
* WOIS is a free software i.e. you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published *
* by the Free Software Foundation, either version 3 of the License, *
* or (at your option) any later version. *
* *
* WOIS is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License *
* for more details. *
* *
* You should have received a copy of the GNU General Public License along *
* with this program. If not, see <http://www.gnu.org/licenses/>. *
***************************************************************************
"""
from builtins import str
from io import open
import os
import json
from qgis.PyQt.QtCore import QCoreApplication
from qgis.core import (QgsApplication,
QgsProcessingAlgorithm,
QgsProcessingParameterString,
QgsProcessingParameterBoolean,
QgsProcessingParameterEnum,
QgsProcessingParameterNumber,
QgsProcessingParameterExtent)
from processing.algs.grass7.Grass7Algorithm import Grass7Algorithm
from processing.algs.grass7.Grass7Utils import Grass7Utils
from processing_workflow.StepDialog import StepDialog, NORMAL_MODE, BATCH_MODE
from processing_workflow.WrongWorkflowException import WrongWorkflowException
from processing_workflow.WorkflowUtils import WorkflowUtils
DIRNAME = os.path.dirname(__file__)
# Class containing the list of steps (algorithms) in the workflow together with the mode
# and instructions for each step
class Workflow(QgsProcessingAlgorithm):
def __init__(self):
QgsProcessingAlgorithm.__init__(self)
# holds the algorithm object, the mode (normal or batch) and instructions
self._steps = list()
self._name = ''
self._group = ''
self.descriptionFile = ''
self.style = None
self.parameters = [QgsProcessingParameterString("Info",
"Workflow can not be run as a batch " +
"process. Please close this dialog and " +
"execute as a normal process.",
"",
False)]
self.showInModeler = False
def addStep(self, algorithm, mode, instructions, algParameters={}):
step = {'algorithm': algorithm, 'mode': mode, 'instructions': instructions,
'parameters': algParameters}
self._steps.append(step)
def changeStep(self, index, algorithm, mode, instructions, algParameters={}):
algParameters = {}
for param in algorithm.parameterDefinitions():
if isinstance(param, QgsProcessingParameterBoolean) or\
isinstance(param, QgsProcessingParameterNumber) or\
isinstance(param, QgsProcessingParameterString) or\
isinstance(param, QgsProcessingParameterEnum) or\
isinstance(param, QgsProcessingParameterExtent):
algParameters[param.name()] = param.defaultValue()
self._steps[index] = {'algorithm': algorithm, 'mode': mode, 'instructions': instructions,
'parameters': algParameters}
def changeMode(self, index, mode):
self._steps[index]['mode'] = mode
def changeInstructions(self, index, instructions):
self._steps[index]['instructions'] = instructions
def getLength(self):
return len(self._steps)
def getAlgorithm(self, index):
return self._steps[index]['algorithm']
def getParameters(self, index):
return self._steps[index]['parameters']
def getMode(self, index):
return self._steps[index]['mode']
def getInstructions(self, index):
return self._steps[index]['instructions']
def icon(self):
try:
return self.provider().icon()
except AttributeError:
return WorkflowUtils.workflowIcon()
def getStyle(self):
styleFile = os.path.join(self.provider().baseDir, self.provider().css)
if not os.path.isfile(styleFile):
styleFile = os.path.join(DIRNAME, "style.css")
with open(styleFile, 'r') as fi:
self.style = fi.read()
def createInstance(self):
newone = Workflow()
newone.setProvider(self.provider())
newone.openWorkflow(self.descriptionFile)
newone.getStyle()
return newone
def removeStep(self, index):
self._steps.pop(index)
def processAlgorithm(self, parameters, context, progress):
# execute the first step
step = self._steps[0]
stepDialog = self.executeStep(step)
# execute the rest
while True:
# check if workflow should go forward, backward or finish
if stepDialog.goForward:
step = self.nextStep(step)
elif stepDialog.goBackward:
step = self.previousStep(step)
else:
step = None
# finish the workflow or execute the next step
if step is None:
Grass7Utils.endGrassSession()
return {}
else:
stepDialog = self.executeStep(step)
def executeStep(self, step):
if isinstance(step['algorithm'], Grass7Algorithm):
Grass7Utils.startGrassSession()
else:
Grass7Utils.endGrassSession()
stepDialog = StepDialog(step['algorithm'], step['parameters'], None,
os.path.dirname(self.descriptionFile), False, style=self.style)
stepDialog.setMode(step['mode'])
stepDialog.setInstructions(step['instructions'])
stepDialog.setWindowTitle(
u"Workflow {workflowname}, Step {stepno} of {nsteps}: {algname}"
.format(
workflowname=self.name(),
stepno=(self._steps.index(step) + 1),
nsteps=len(self._steps),
algname=step['algorithm'].displayName()))
stepDialog.setWindowIcon(self.icon())
# set as window modal to allow access to QGIS functions
stepDialog.setWindowModality(1)
stepDialog.exec_()
return stepDialog
def nextStep(self, step):
index = self._steps.index(step)
if index < len(self._steps)-1:
return (self._steps[index+1])
else:
return None
def previousStep(self, step):
index = self._steps.index(step)
if index > 0:
return (self._steps[index-1])
else:
return (self._steps[0])
def serialize(self):
s = ".NAME:" + str(self.name()) + "\n"
s += ".GROUP:" + str(self.group()) + "\n"
for step in self._steps:
s += ".ALGORITHM:%s:%s\n" % (step['algorithm'].provider().id(), step['algorithm'].name())
s += ".PARAMETERS:%s\n" % json.dumps(step['parameters'])
s += ".MODE:%s\n" % step['mode']
s += ".INSTRUCTIONS:%s\n" % step['instructions']
if not str(s).endswith("\n"):
s += "\n"
s += "!INSTRUCTIONS" + "\n"
return s
# Read workflow from text file
def openWorkflow(self, filename):
self._steps = list()
self.descriptionFile = filename
instructions = False
lineNumber = 0
with open(filename, 'r', encoding="utf-8-sig") as fileinput:
for line in fileinput:
lineNumber += 1
line = line.rstrip()
try:
# comment line
if line.startswith("#"):
pass
if line.startswith(".NAME:"):
self._name = self.tr(line[len(".NAME:"):])
elif line.startswith(".GROUP:"):
self._group = self.tr(line[len(".GROUP:"):])
self._groupId = line[len(".GROUP:"):].lower().replace(" ", "_")
elif line.startswith(".ALGORITHM:"):
alg = QgsApplication.processingRegistry().algorithmById(
line[len(".ALGORITHM:"):])
if alg:
self.addStep(alg, NORMAL_MODE, '')
else:
raise WrongWorkflowException
elif line.startswith(".MODE:"):
if line[len(".MODE:"):] == NORMAL_MODE:
self._steps[-1]['mode'] = NORMAL_MODE
elif line[len(".MODE:"):] == BATCH_MODE:
self._steps[-1]['mode'] = BATCH_MODE
else:
raise WrongWorkflowException
elif line.startswith(".PARAMETERS:"):
try:
params = json.loads(line[len(".PARAMETERS:"):])
except json.JSONDecodeError:
params = None
if type(params) == dict:
self._steps[-1]['parameters'] = params
else:
raise WrongWorkflowException
elif line.startswith(".INSTRUCTIONS"):
instructions = line[len(".INSTRUCTIONS:"):]+"\n"
self._steps[-1]['instructions'] = instructions
instructions = True
elif instructions:
if line == "!INSTRUCTIONS":
instructions = False
elif line == "":
self._steps[-1]['instructions'] += "\n"
else:
self._steps[-1]['instructions'] += line+"\n"
except WrongWorkflowException:
msg = "Error on line number "+str(lineNumber)+": "+line+"\n"
raise WrongWorkflowException(msg)
except Exception as e:
raise e
def name(self):
return self._name
def setName(self, name):
self._name = name
def displayName(self):
return self._name
def shortDescription(self):
return self._name
def group(self):
return self._group
def setGroup(self, group):
self._group = group
def groupId(self):
return self._groupId
def flags(self):
return super().flags() | (QgsProcessingAlgorithm.FlagNoThreading |
QgsProcessingAlgorithm.FlagHideFromModeler &
~QgsProcessingAlgorithm.FlagSupportsBatch)
def helpUrl(self):
return ""
def helpId(self):
return ""
def svgIconPath(self):
return ""
def tr(self, string, context=''):
if context == '':
context = self.__class__.__name__
return QCoreApplication.translate(context, string)
def initAlgorithm(self, config=None):
pass
def validateInputCRS(self):
return True