/
model.py
2976 lines (2499 loc) · 95.3 KB
/
model.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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
@package gmodeler.model
@brief wxGUI Graphical Modeler (base classes & read/write)
Classes:
- model::Model
- model::ModelObject
- model::ModelAction
- model::ModelData
- model::ModelRelation
- model::ModelItem
- model::ModelLoop
- model::ModelCondition
- model::ModelComment
- model::ProcessModelFile
- model::WriteModelFile
- model::WritePythonFile
- model::ModelParamDialog
(C) 2010-2018 by the GRASS Development Team
This program is free software under the GNU General Public License
(>=v2). Read the file COPYING that comes with GRASS for details.
@author Martin Landa <landa.martin gmail.com>
@author Python parameterization Ondrej Pesek <pesej.ondrek gmail.com>
"""
import os
import getpass
import copy
import re
import mimetypes
import time
import six
try:
import xml.etree.ElementTree as etree
except ImportError:
import elementtree.ElementTree as etree # Python <= 2.4
import xml.sax.saxutils as saxutils
import wx
from wx.lib import ogl
from core import globalvar
from core import utils
from core.gcmd import GMessage, GException, GError, RunCommand, GWarning, GetDefaultEncoding
from core.settings import UserSettings
from gui_core.forms import GUI, CmdPanel
from gui_core.widgets import GNotebook
from gui_core.wrap import Button
from gmodeler.giface import GraphicalModelerGrassInterface
from grass.script import core as grass
from grass.script import task as gtask
class Model(object):
"""Class representing the model"""
def __init__(self, canvas=None):
self.items = list() # list of ordered items (action/loop/condition)
# model properties
self.properties = {
'name': _("model"),
'description': _("Script generated by wxGUI Graphical Modeler."),
'author': getpass.getuser()}
# model variables
self.variables = dict()
self.variablesParams = dict()
self.canvas = canvas
def GetCanvas(self):
"""Get canvas or None"""
return self.canvas
def GetItems(self, objType=None):
"""Get list of model items
:param objType: Object type to filter model objects
"""
if not objType:
return self.items
result = list()
for item in self.items:
if isinstance(item, objType):
result.append(item)
return result
def GetItem(self, aId, objType=None):
"""Get item of given id
:param aId: item id
:return: Model* instance
:return: None if no item found
"""
ilist = self.GetItems(objType)
for item in ilist:
if item.GetId() == aId:
return item
return None
def GetItemIndex(self, item):
"""Return list index of given item"""
return self.items.index(item)
def GetNumItems(self, actionOnly=False):
"""Get number of items"""
if actionOnly:
return len(self.GetItems(objType=ModelAction))
return len(self.GetItems())
def ReorderItems(self, idxList):
items = list()
for oldIdx, newIdx in six.iteritems(idxList):
item = self.items.pop(oldIdx)
items.append(item)
self.items.insert(newIdx, item)
# try:
# nextItem = self.items[newIdx+1]
# except IndexError:
# continue # newIdx is the last item in the list
# items.append(nextItem)
# x = item.GetX()
# y = item.GetY()
# item.SetX(nextItem.GetX())
# item.SetY(nextItem.GetY())
# nextItem.SetX(x)
# nextItem.SetY(y)
dc = wx.ClientDC(self.canvas)
for item in items:
item.MoveLinks(dc)
for mo in item.GetBlock():
if isinstance(mo, ModelLoop):
self.canvas.parent.DefineLoop(mo)
elif isinstance(mo, ModelCondition):
self.canvas.parent.DefineCondition(mo)
def Normalize(self):
# check for inconsistecies
for idx in range(1, len(self.items)):
if not self.items[idx].GetBlock() and \
isinstance(self.items[idx - 1], ModelLoop):
# swap action not-in-block with previously defined
# loop
itemPrev = self.items[idx - 1]
self.items[idx - 1] = self.items[idx]
self.items[idx] = itemPrev
# update ids
iId = 1
for item in self.items:
item.SetId(iId)
item.SetLabel()
iId += 1
def GetNextId(self):
"""Get next id (data ignored)
:return: next id to be used (default: 1)
"""
if len(self.items) < 1:
return 1
currId = self.items[-1].GetId()
if currId > 0:
return currId + 1
return 1
def GetProperties(self):
"""Get model properties"""
return self.properties
def GetVariables(self, params=False):
"""Get model variables"""
if params:
return self.variablesParams
return self.variables
def SetVariables(self, data):
"""Set model variables"""
self.variables = data
def Reset(self):
"""Reset model"""
self.items = list()
def RemoveItem(self, item, reference=None):
"""Remove item from model
:item: item to be removed
:reference: reference item valid for deletion
:return: list of related items to remove/update
"""
relList = list()
upList = list()
doRemove = True
if isinstance(item, ModelAction):
for rel in item.GetRelations():
relList.append(rel)
data = rel.GetData()
if len(data.GetRelations()) < 2:
relList.append(data)
else:
upList.append(data)
elif isinstance(item, ModelData):
for rel in item.GetRelations():
otherItem = rel.GetTo() if rel.GetFrom() == item else rel.GetFrom()
if reference and reference != otherItem:
doRemove = False
continue # avoid recursive deletion
relList.append(rel)
if reference and reference != otherItem:
relList.append(otherItem)
if not doRemove:
upList.append(item)
elif isinstance(item, ModelLoop):
for rel in item.GetRelations():
relList.append(rel)
for action in self.GetItems():
action.UnSetBlock(item)
if doRemove and item in self.items:
self.items.remove(item)
return relList, upList
def FindAction(self, aId):
"""Find action by id"""
alist = self.GetItems(objType=ModelAction)
for action in alist:
if action.GetId() == aId:
return action
return None
def GetMaps(self, prompt):
"""Get list of maps of selected type
:param prompt: to filter maps"""
maps = list()
for data in self.GetData():
if prompt == data.GetPrompt():
mapName = data.GetValue()
if not mapName or mapName[0] == '%':
continue # skip variables
maps.append(mapName)
return maps
def GetData(self):
"""Get list of data items"""
result = list()
dataItems = self.GetItems(objType=ModelData)
for action in self.GetItems(objType=ModelAction):
for rel in action.GetRelations():
dataItem = rel.GetData()
if dataItem not in result:
result.append(dataItem)
if dataItem in dataItems:
dataItems.remove(dataItem)
# standalone data
if dataItems:
result += dataItems
return result
def FindData(self, value, prompt):
"""Find data item in the model
:param value: value
:param prompt: prompt
:return: ModelData instance
:return: None if not found
"""
for data in self.GetData():
if data.GetValue() == value and \
data.GetPrompt() == prompt:
return data
return None
def LoadModel(self, filename):
"""Load model definition stored in GRASS Model XML file (gxm)
.. todo::
Validate against DTD
Raise exception on error.
"""
dtdFilename = os.path.join(globalvar.WXGUIDIR, "xml", "grass-gxm.dtd")
# parse workspace file
try:
gxmXml = ProcessModelFile(etree.parse(filename))
except Exception as e:
raise GException('{}'.format(e))
if self.canvas:
win = self.canvas.parent
if gxmXml.pos:
win.SetPosition(gxmXml.pos)
if gxmXml.size:
win.SetSize(gxmXml.size)
# load properties
self.properties = gxmXml.properties
self.variables = gxmXml.variables
# load actions
for action in gxmXml.actions:
actionItem = ModelAction(parent=self,
x=action['pos'][0],
y=action['pos'][1],
width=action['size'][0],
height=action['size'][1],
task=action['task'],
id=action['id'],
label=action['label'],
comment=action['comment'])
if action['disabled']:
actionItem.Enable(False)
self.AddItem(actionItem, pos=actionItem.GetId() - 1)
actionItem.SetValid(actionItem.GetTask().get_options())
actionItem.GetLog() # substitute variables (-> valid/invalid)
# load data & relations
for data in gxmXml.data:
dataItem = ModelData(parent=self,
x=data['pos'][0],
y=data['pos'][1],
width=data['size'][0],
height=data['size'][1],
prompt=data['prompt'],
value=data['value'])
dataItem.SetIntermediate(data['intermediate'])
dataItem.SetHasDisplay(data['display'])
for rel in data['rels']:
actionItem = self.FindAction(rel['id'])
if rel['dir'] == 'from':
relation = ModelRelation(
parent=self,
fromShape=dataItem,
toShape=actionItem,
param=rel['name'])
else:
relation = ModelRelation(
parent=self,
fromShape=actionItem,
toShape=dataItem,
param=rel['name'])
relation.SetControlPoints(rel['points'])
actionItem.AddRelation(relation)
dataItem.AddRelation(relation)
if self.canvas:
dataItem.Update()
# load loops
for loop in gxmXml.loops:
loopItem = ModelLoop(parent=self,
x=loop['pos'][0],
y=loop['pos'][1],
width=loop['size'][0],
height=loop['size'][1],
label=loop['text'],
id=loop['id'])
self.AddItem(loopItem, pos=loopItem.GetId() - 1)
# load conditions
for condition in gxmXml.conditions:
conditionItem = ModelCondition(parent=self,
x=condition['pos'][0],
y=condition['pos'][1],
width=condition['size'][0],
height=condition['size'][1],
label=condition['text'],
id=condition['id'])
self.AddItem(conditionItem, pos=conditionItem.GetId() - 1)
# define loops & if/else items
for loop in gxmXml.loops:
loopItem = self.GetItem(loop['id'], objType=ModelLoop)
loopItem.SetItems(loop['items'])
for idx in loop['items']:
action = self.GetItem(idx, objType=ModelAction)
action.SetBlock(loopItem)
for condition in gxmXml.conditions:
conditionItem = self.GetItem(condition['id'])
for b in condition['items'].keys():
alist = list()
for aId in condition['items'][b]:
action = self.GetItem(aId)
alist.append(action)
conditionItem.SetItems(alist, branch=b)
items = conditionItem.GetItems()
for b in items.keys():
for action in items[b]:
action.SetBlock(conditionItem)
# load comments
for comment in gxmXml.comments:
commentItem = ModelComment(parent=self,
x=comment['pos'][0],
y=comment['pos'][1],
width=comment['size'][0],
height=comment['size'][1],
id=comment['id'],
label=comment['text'])
self.AddItem(commentItem, pos=commentItem.GetId() - 1)
def AddItem(self, newItem, pos=-1):
"""Add item to the list"""
if pos != -1:
self.items.insert(pos, newItem)
else:
self.items.append(newItem)
# i = 1
# for item in self.items:
# item.SetId(i)
# i += 1
def IsValid(self):
"""Return True if model is valid"""
if self.Validate():
return False
return True
def Validate(self):
"""Validate model, return None if model is valid otherwise
error string"""
errList = list()
variables = self.GetVariables().keys()
pattern = re.compile(r'(.*)(%.+\s?)(.*)')
for action in self.GetItems(objType=ModelAction):
cmd = action.GetLog(string=False)
task = GUI(show=None).ParseCommand(cmd=cmd)
errList += map(lambda x: cmd[0] + ': ' + x, task.get_cmd_error())
# check also variables
for opt in cmd[1:]:
if '=' not in opt:
continue
key, value = opt.split('=', 1)
sval = pattern.search(value)
if sval:
var = sval.group(2).strip()[1:] # strip '%' from beginning
found = False
for v in variables:
if var.startswith(v):
found = True
break
if not found:
report = True
for item in filter(
lambda x: isinstance(x, ModelLoop),
action.GetBlock()):
if var in item.GetLabel():
report = False
break
if report:
errList.append(
cmd[0] +
": " +
_("undefined variable '%s'") %
var)
# TODO: check variables in file only optionally
### errList += self._substituteFile(action, checkOnly = True)
return errList
def _substituteFile(self, item, params=None, checkOnly=False):
"""Subsitute variables in command file inputs
:param bool checkOnly: tuble - True to check variable, don't touch files
:return: list of undefined variables
"""
errList = list()
self.fileInput = dict()
# collect ascii inputs
for p in item.GetParams()['params']:
if p.get('element', '') == 'file' and \
p.get('prompt', '') == 'input' and \
p.get('age', '') == 'old':
filename = p.get('value', p.get('default', ''))
if filename and \
mimetypes.guess_type(filename)[0] == 'text/plain':
self.fileInput[filename] = None
for finput in self.fileInput:
# read lines
fd = open(finput, "r")
try:
data = self.fileInput[finput] = fd.read()
finally:
fd.close()
# substitute variables
write = False
variables = self.GetVariables()
for variable in variables:
pattern = re.compile('%' + variable)
value = ''
if params and 'variables' in params:
for p in params['variables']['params']:
if variable == p.get('name', ''):
if p.get('type', 'string') == 'string':
value = p.get('value', '')
else:
value = str(p.get('value', ''))
break
if not value:
value = variables[variable].get('value', '')
data = pattern.sub(value, data)
if not checkOnly:
write = True
pattern = re.compile(r'(.*)(%.+\s?)(.*)')
sval = pattern.search(data)
if sval:
var = sval.group(2).strip()[1:] # ignore '%'
cmd = item.GetLog(string=False)[0]
errList.append(cmd + ": " + _("undefined variable '%s'") % var)
if not checkOnly:
if write:
fd = open(finput, "w")
try:
fd.write(data)
finally:
fd.close()
else:
self.fileInput[finput] = None
return errList
def OnPrepare(self, item, params):
self._substituteFile(item, params, checkOnly=False)
def RunAction(self, item, params, log, onDone=None,
onPrepare=None, statusbar=None):
"""Run given action
:param item: action item
:param params: parameters dict
:param log: logging window
:param onDone: on-done method
:param onPrepare: on-prepare method
:param statusbar: wx.StatusBar instance or None
"""
name = '({0}) {1}'.format(item.GetId(), item.GetLabel())
if name in params:
paramsOrig = item.GetParams(dcopy=True)
item.MergeParams(params[name])
if statusbar:
statusbar.SetStatusText(_('Running model...'), 0)
data = {'item': item,
'params': copy.deepcopy(params)}
log.RunCmd(command=item.GetLog(string=False, substitute=params),
onDone=onDone, onPrepare=self.OnPrepare, userData=data)
if name in params:
item.SetParams(paramsOrig)
def Run(self, log, onDone, parent=None):
"""Run model
:param log: logging window (see gconsole.GConsole)
:param onDone: on-done method
:param parent: window for messages or None
"""
if self.GetNumItems() < 1:
GMessage(parent=parent,
message=_('Model is empty. Nothing to run.'))
return
statusbar = None
if isinstance(parent, wx.Frame):
statusbar = parent.GetStatusBar()
# validation
if statusbar:
statusbar.SetStatusText(_('Validating model...'), 0)
errList = self.Validate()
if statusbar:
statusbar.SetStatusText('', 0)
if errList:
dlg = wx.MessageDialog(
parent=parent,
message=_(
'Model is not valid. Do you want to '
'run the model anyway?\n\n%s') %
'\n'.join(errList),
caption=_("Run model?"),
style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)
ret = dlg.ShowModal()
dlg.Destroy()
if ret != wx.ID_YES:
return
# parametrization
params = self.Parameterize()
delInterData = False
if params:
dlg = ModelParamDialog(parent=parent,
model=self,
params=params)
dlg.CenterOnParent()
ret = dlg.ShowModal()
if ret != wx.ID_OK:
dlg.Destroy()
return
err = dlg.GetErrors()
delInterData = dlg.DeleteIntermediateData()
dlg.Destroy()
if err:
GError(parent=parent, message='\n'.join(err))
return
err = list()
for key, item in six.iteritems(params):
for p in item['params']:
if p.get('value', '') == '':
err.append(
(key, p.get(
'name', ''), p.get(
'description', '')))
if err:
GError(
parent=parent,
message=_("Variables below not defined:") +
"\n\n" +
'\n'.join(
map(
lambda x: "%s: %s (%s)" %
(x[0],
x[1],
x[2]),
err)))
return
log.cmdThread.SetId(-1)
for item in self.GetItems():
if not item.IsEnabled():
continue
if isinstance(item, ModelAction):
if item.GetBlockId():
continue
self.RunAction(item, params, log)
elif isinstance(item, ModelLoop):
cond = item.GetLabel()
# substitute variables in condition
variables = self.GetVariables()
for variable in variables:
pattern = re.compile('%' + variable)
if pattern.search(cond):
value = ''
if params and 'variables' in params:
for p in params['variables']['params']:
if variable == p.get('name', ''):
value = p.get('value', '')
break
if not value:
value = variables[variable].get('value', '')
if not value:
continue
vtype = variables[variable].get('type', 'string')
if vtype == 'string':
value = '"' + value + '"'
cond = pattern.sub(value, cond)
# split condition
# TODO: this part needs some better solution
condVar, condText = map(
lambda x: x.strip(),
re.split('\s* in \s*', cond))
pattern = re.compile('%' + condVar)
# for vars()[condVar] in eval(condText): ?
vlist = list()
if condText[0] == '`' and condText[-1] == '`':
# run command
cmd, dcmd = gtask.cmdlist_to_tuple(
condText[1: -1].split(' '))
ret = RunCommand(cmd,
read=True,
**dcmd)
if ret:
vlist = ret.splitlines()
else:
vlist = eval(condText)
if 'variables' not in params:
params['variables'] = {'params': []}
varDict = {'name': condVar, 'value': ''}
params['variables']['params'].append(varDict)
for var in vlist:
for action in item.GetItems(self.GetItems()):
if not action.IsEnabled():
continue
varDict['value'] = var
self.RunAction(item=action, params=params,
log=log)
params['variables']['params'].remove(varDict)
if delInterData:
self.DeleteIntermediateData(log)
# discard values
if params:
for item in six.itervalues(params):
for p in item['params']:
p['value'] = ''
def DeleteIntermediateData(self, log):
"""Detele intermediate data"""
rast, vect, rast3d, msg = self.GetIntermediateData()
if rast:
log.RunCmd(['g.remove', '-f', 'type=raster',
'name=%s' % ','.join(rast)])
if rast3d:
log.RunCmd(['g.remove', '-f', 'type=raster_3d',
'name=%s' % ','.join(rast3d)])
if vect:
log.RunCmd(['g.remove', '-f', 'type=vector',
'name=%s' % ','.join(vect)])
def GetIntermediateData(self):
"""Get info about intermediate data"""
rast = list()
rast3d = list()
vect = list()
for data in self.GetData():
if not data.IsIntermediate():
continue
name = data.GetValue()
prompt = data.GetPrompt()
if prompt == 'raster':
rast.append(name)
elif prompt == 'vector':
vect.append(name)
elif prompt == 'raster_3d':
rast3d.append(name)
msg = ''
if rast:
msg += '\n\n%s: ' % _('Raster maps')
msg += ', '.join(rast)
if rast3d:
msg += '\n\n%s: ' % _('3D raster maps')
msg += ', '.join(rast3d)
if vect:
msg += '\n\n%s: ' % _('Vector maps')
msg += ', '.join(vect)
return rast, vect, rast3d, msg
def Update(self):
"""Update model"""
for item in self.items:
item.Update()
def IsParameterized(self):
"""Return True if model is parameterized"""
if self.Parameterize():
return True
return False
def Parameterize(self):
"""Return parameterized options"""
result = dict()
idx = 0
if self.variables:
params = list()
result["variables"] = {'flags': list(),
'params': params,
'idx': idx}
for name, values in six.iteritems(self.variables):
gtype = values.get('type', 'string')
if gtype in ('raster', 'vector', 'mapset',
'file', 'region', 'dir'):
gisprompt = True
prompt = gtype
if gtype == 'raster':
element = 'cell'
else:
element = gtype
ptype = 'string'
else:
gisprompt = False
prompt = None
element = None
ptype = gtype
params.append({'gisprompt': gisprompt,
'multiple': False,
'description': values.get('description', ''),
'guidependency': '',
'default': '',
'age': None,
'required': True,
'value': values.get('value', ''),
'label': '',
'guisection': '',
'key_desc': '',
'values': list(),
'parameterized': False,
'values_desc': list(),
'prompt': prompt,
'element': element,
'type': ptype,
'name': name})
idx += 1
for action in self.GetItems(objType=ModelAction):
if not action.IsEnabled():
continue
name = '({0}) {1}'.format(action.GetId(), action.GetLabel())
params = action.GetParams()
increment = False
for f in params['flags']:
if f.get('parameterized', False):
if name not in result:
increment = True
result[name] = {'flags': list(),
'params': list(),
'idx': idx}
result[name]['flags'].append(f)
for p in params['params']:
if p.get('parameterized', False):
if name not in result:
increment = True
result[name] = {'flags': list(),
'params': list(),
'idx': idx}
result[name]['params'].append(p)
if increment:
idx += 1
self.variablesParams = result # record parameters
return result
class ModelObject(object):
def __init__(self, id=-1, label=''):
self.id = id # internal id, should be not changed
self.label = ''
self.rels = list() # list of ModelRelations
self.isEnabled = True
self.inBlock = list() # list of related loops/conditions
def __del__(self):
pass
def GetLabel(self):
"""Get label"""
return self.label
def SetLabel(self, label=''):
"""Set label"""
self.label = label
def GetId(self):
"""Get id"""
return self.id
def SetId(self, newId):
"""Set id"""
if self.inBlock:
for loop in self.inBlock:
# update block item
loop.UpdateItem(self.id, newId)
self.id = newId
def AddRelation(self, rel):
"""Record new relation
"""
self.rels.append(rel)
def GetRelations(self, fdir=None):
"""Get list of relations
:param bool fdir: True for 'from'
"""
if fdir is None:
return self.rels
result = list()
for rel in self.rels:
if fdir == 'from':
if rel.GetFrom() == self:
result.append(rel)
else:
if rel.GetTo() == self:
result.append(rel)
return result
def IsEnabled(self):
"""Get True if action is enabled, otherwise False"""
return self.isEnabled
def Enable(self, enabled=True):
"""Enable/disable action"""
self.isEnabled = enabled
self.Update()
def Update(self):
pass
def SetBlock(self, item):
"""Add object to the block (loop/condition)
:param item: reference to ModelLoop or ModelCondition which
defines loops/condition
"""
if item not in self.inBlock:
self.inBlock.append(item)
def UnSetBlock(self, item):
"""Remove object from the block (loop/consition)
:param item: reference to ModelLoop or ModelCondition which
defines loops/codition
"""
if item in self.inBlock:
self.inBlock.remove(item)
def GetBlock(self):
"""Get list of related ModelObject(s) which defines block
(loop/condition)
:return: list of ModelObjects
"""
return self.inBlock
def GetBlockId(self):
"""Get list of related ids which defines block
:return: list of ids
"""
ret = list()
for mo in self.inBlock:
ret.append(mo.GetId())
return ret
class ModelAction(ModelObject, ogl.DividedShape):