model.py 91 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666
  1. """
  2. @package gmodeler.model
  3. @brief wxGUI Graphical Modeler (base classes & read/write)
  4. Classes:
  5. - model::Model
  6. - model::ModelObject
  7. - model::ModelAction
  8. - model::ModelData
  9. - model::ModelRelation
  10. - model::ModelItem
  11. - model::ModelLoop
  12. - model::ModelCondition
  13. - model::ModelComment
  14. - model::ProcessModelFile
  15. - model::WriteModelFile
  16. - model::WritePythonFile
  17. - model::ModelParamDialog
  18. (C) 2010-2016 by the GRASS Development Team
  19. This program is free software under the GNU General Public License
  20. (>=v2). Read the file COPYING that comes with GRASS for details.
  21. @author Martin Landa <landa.martin gmail.com>
  22. """
  23. import os
  24. import getpass
  25. import copy
  26. import re
  27. import mimetypes
  28. import time
  29. try:
  30. import xml.etree.ElementTree as etree
  31. except ImportError:
  32. import elementtree.ElementTree as etree # Python <= 2.4
  33. import xml.sax.saxutils as saxutils
  34. import wx
  35. from wx.lib import ogl
  36. from core import globalvar
  37. from core import utils
  38. from core.utils import _
  39. from core.gcmd import GMessage, GException, GError, RunCommand, EncodeString, GWarning, GetDefaultEncoding
  40. from core.settings import UserSettings
  41. from gui_core.forms import GUI, CmdPanel
  42. from gui_core.widgets import GNotebook
  43. from gmodeler.giface import GraphicalModelerGrassInterface
  44. from grass.script import core as grass
  45. from grass.script import task as gtask
  46. class Model(object):
  47. """Class representing the model"""
  48. def __init__(self, canvas = None):
  49. self.items = list() # list of ordered items (action/loop/condition)
  50. # model properties
  51. self.properties = { 'name' : _("model"),
  52. 'description' : _("Script generated by wxGUI Graphical Modeler."),
  53. 'author' : getpass.getuser() }
  54. # model variables
  55. self.variables = dict()
  56. self.variablesParams = dict()
  57. self.canvas = canvas
  58. def GetCanvas(self):
  59. """Get canvas or None"""
  60. return self.canvas
  61. def GetItems(self, objType = None):
  62. """Get list of model items
  63. :param objType: Object type to filter model objects
  64. """
  65. if not objType:
  66. return self.items
  67. result = list()
  68. for item in self.items:
  69. if isinstance(item, objType):
  70. result.append(item)
  71. return result
  72. def GetItem(self, aId, objType=None):
  73. """Get item of given id
  74. :param aId: item id
  75. :return: Model* instance
  76. :return: None if no item found
  77. """
  78. ilist = self.GetItems(objType)
  79. for item in ilist:
  80. if item.GetId() == aId:
  81. return item
  82. return None
  83. def GetItemIndex(self, item):
  84. """Return list index of given item"""
  85. return self.items.index(item)
  86. def GetNumItems(self, actionOnly = False):
  87. """Get number of items"""
  88. if actionOnly:
  89. return len(self.GetItems(objType = ModelAction))
  90. return len(self.GetItems())
  91. def ReorderItems(self, idxList):
  92. items = list()
  93. for oldIdx, newIdx in idxList.iteritems():
  94. item = self.items.pop(oldIdx)
  95. items.append(item)
  96. self.items.insert(newIdx, item)
  97. try:
  98. nextItem = self.items[newIdx+1]
  99. except IndexError:
  100. continue # newIdx is the last item in the list
  101. items.append(nextItem)
  102. x = item.GetX()
  103. y = item.GetY()
  104. item.SetX(nextItem.GetX())
  105. item.SetY(nextItem.GetY())
  106. nextItem.SetX(x)
  107. nextItem.SetY(y)
  108. dc = wx.ClientDC(self.canvas)
  109. for item in items:
  110. item.MoveLinks(dc)
  111. for mo in item.GetBlock():
  112. if isinstance(mo, ModelLoop):
  113. self.canvas.parent.DefineLoop(mo)
  114. elif isinstance(mo, ModelCondition):
  115. self.canvas.parent.DefineCondition(mo)
  116. def Normalize(self):
  117. # check for inconsistecies
  118. for idx in range(1, len(self.items)):
  119. if not self.items[idx].GetBlock() and \
  120. isinstance(self.items[idx-1], ModelLoop):
  121. # swap action not-in-block with previously defined
  122. # loop
  123. itemPrev = self.items[idx-1]
  124. self.items[idx-1] = self.items[idx]
  125. self.items[idx] = itemPrev
  126. # update ids
  127. iId = 1
  128. for item in self.items:
  129. item.SetId(iId)
  130. item.SetLabel()
  131. iId += 1
  132. def GetNextId(self):
  133. """Get next id (data ignored)
  134. :return: next id to be used (default: 1)
  135. """
  136. if len(self.items) < 1:
  137. return 1
  138. currId = self.items[-1].GetId()
  139. if currId > 0:
  140. return currId + 1
  141. return 1
  142. def GetProperties(self):
  143. """Get model properties"""
  144. return self.properties
  145. def GetVariables(self, params = False):
  146. """Get model variables"""
  147. if params:
  148. return self.variablesParams
  149. return self.variables
  150. def SetVariables(self, data):
  151. """Set model variables"""
  152. self.variables = data
  153. def Reset(self):
  154. """Reset model"""
  155. self.items = list()
  156. def RemoveItem(self, item):
  157. """Remove item from model
  158. :return: list of related items to remove/update
  159. """
  160. relList = list()
  161. upList = list()
  162. self.items.remove(item)
  163. if isinstance(item, ModelAction):
  164. for rel in item.GetRelations():
  165. relList.append(rel)
  166. data = rel.GetData()
  167. if len(data.GetRelations()) < 2:
  168. relList.append(data)
  169. else:
  170. upList.append(data)
  171. elif isinstance(item, ModelData):
  172. for rel in item.GetRelations():
  173. relList.append(rel)
  174. if rel.GetFrom() == self:
  175. relList.append(rel.GetTo())
  176. else:
  177. relList.append(rel.GetFrom())
  178. elif isinstance(item, ModelLoop):
  179. for rel in item.GetRelations():
  180. relList.append(rel)
  181. for action in self.GetItems():
  182. action.UnSetBlock(item)
  183. return relList, upList
  184. def FindAction(self, aId):
  185. """Find action by id"""
  186. alist = self.GetItems(objType = ModelAction)
  187. for action in alist:
  188. if action.GetId() == aId:
  189. return action
  190. return None
  191. def GetMaps(self, prompt):
  192. """Get list of maps of selected type
  193. :param prompt: to filter maps"""
  194. maps = list()
  195. for data in self.GetData():
  196. if prompt == data.GetPrompt():
  197. mapName = data.GetValue()
  198. if not mapName or mapName[0] is '%':
  199. continue # skip variables
  200. maps.append(mapName)
  201. return maps
  202. def GetData(self):
  203. """Get list of data items"""
  204. result = list()
  205. dataItems = self.GetItems(objType = ModelData)
  206. for action in self.GetItems(objType = ModelAction):
  207. for rel in action.GetRelations():
  208. dataItem = rel.GetData()
  209. if dataItem not in result:
  210. result.append(dataItem)
  211. if dataItem in dataItems:
  212. dataItems.remove(dataItem)
  213. # standalone data
  214. if dataItems:
  215. result += dataItems
  216. return result
  217. def FindData(self, value, prompt):
  218. """Find data item in the model
  219. :param value: value
  220. :param prompt: prompt
  221. :return: ModelData instance
  222. :return: None if not found
  223. """
  224. for data in self.GetData():
  225. if data.GetValue() == value and \
  226. data.GetPrompt() == prompt:
  227. return data
  228. return None
  229. def LoadModel(self, filename):
  230. """Load model definition stored in GRASS Model XML file (gxm)
  231. .. todo::
  232. Validate against DTD
  233. Raise exception on error.
  234. """
  235. dtdFilename = os.path.join(globalvar.WXGUIDIR, "xml", "grass-gxm.dtd")
  236. # parse workspace file
  237. try:
  238. gxmXml = ProcessModelFile(etree.parse(filename))
  239. except StandardError as e:
  240. raise GException(unicode(e))
  241. if self.canvas:
  242. win = self.canvas.parent
  243. if gxmXml.pos:
  244. win.SetPosition(gxmXml.pos)
  245. if gxmXml.size:
  246. win.SetSize(gxmXml.size)
  247. # load properties
  248. self.properties = gxmXml.properties
  249. self.variables = gxmXml.variables
  250. # load actions
  251. for action in gxmXml.actions:
  252. actionItem = ModelAction(parent = self,
  253. x = action['pos'][0],
  254. y = action['pos'][1],
  255. width = action['size'][0],
  256. height = action['size'][1],
  257. task = action['task'],
  258. id = action['id'],
  259. label = action['label'],
  260. comment = action['comment'])
  261. if action['disabled']:
  262. actionItem.Enable(False)
  263. self.AddItem(actionItem, pos = actionItem.GetId()-1)
  264. actionItem.SetValid(actionItem.GetTask().get_options())
  265. actionItem.GetLog() # substitute variables (-> valid/invalid)
  266. # load data & relations
  267. for data in gxmXml.data:
  268. dataItem = ModelData(parent = self,
  269. x = data['pos'][0],
  270. y = data['pos'][1],
  271. width = data['size'][0],
  272. height = data['size'][1],
  273. prompt = data['prompt'],
  274. value = data['value'])
  275. dataItem.SetIntermediate(data['intermediate'])
  276. for rel in data['rels']:
  277. actionItem = self.FindAction(rel['id'])
  278. if rel['dir'] == 'from':
  279. relation = ModelRelation(parent = self, fromShape = dataItem,
  280. toShape = actionItem, param = rel['name'])
  281. else:
  282. relation = ModelRelation(parent = self, fromShape = actionItem,
  283. toShape = dataItem, param = rel['name'])
  284. relation.SetControlPoints(rel['points'])
  285. actionItem.AddRelation(relation)
  286. dataItem.AddRelation(relation)
  287. if self.canvas:
  288. dataItem.Update()
  289. # load loops
  290. for loop in gxmXml.loops:
  291. loopItem = ModelLoop(parent = self,
  292. x = loop['pos'][0],
  293. y = loop['pos'][1],
  294. width = loop['size'][0],
  295. height = loop['size'][1],
  296. label = loop['text'],
  297. id = loop['id'])
  298. self.AddItem(loopItem, pos = loopItem.GetId()-1)
  299. # load conditions
  300. for condition in gxmXml.conditions:
  301. conditionItem = ModelCondition(parent = self,
  302. x = condition['pos'][0],
  303. y = condition['pos'][1],
  304. width = condition['size'][0],
  305. height = condition['size'][1],
  306. label = condition['text'],
  307. id = condition['id'])
  308. self.AddItem(conditionItem, pos = conditionItem.GetId()-1)
  309. # define loops & if/else items
  310. for loop in gxmXml.loops:
  311. loopItem = self.GetItem(loop['id'], objType=ModelLoop)
  312. loopItem.SetItems(loop['items'])
  313. for idx in loop['items']:
  314. action = self.GetItem(idx, objType=ModelAction)
  315. action.SetBlock(loopItem)
  316. for condition in gxmXml.conditions:
  317. conditionItem = self.GetItem(condition['id'])
  318. for b in condition['items'].keys():
  319. alist = list()
  320. for aId in condition['items'][b]:
  321. action = self.GetItem(aId)
  322. alist.append(action)
  323. conditionItem.SetItems(alist, branch = b)
  324. items = conditionItem.GetItems()
  325. for b in items.keys():
  326. for action in items[b]:
  327. action.SetBlock(conditionItem)
  328. # load comments
  329. for comment in gxmXml.comments:
  330. commentItem = ModelComment(parent = self,
  331. x = comment['pos'][0],
  332. y = comment['pos'][1],
  333. width = comment['size'][0],
  334. height = comment['size'][1],
  335. id = comment['id'],
  336. label = comment['text'])
  337. self.AddItem(commentItem, pos = commentItem.GetId()-1)
  338. def AddItem(self, newItem, pos = -1):
  339. """Add item to the list"""
  340. if pos != -1:
  341. self.items.insert(pos, newItem)
  342. else:
  343. self.items.append(newItem)
  344. # i = 1
  345. # for item in self.items:
  346. # item.SetId(i)
  347. # i += 1
  348. def IsValid(self):
  349. """Return True if model is valid"""
  350. if self.Validate():
  351. return False
  352. return True
  353. def Validate(self):
  354. """Validate model, return None if model is valid otherwise
  355. error string"""
  356. errList = list()
  357. variables = self.GetVariables().keys()
  358. pattern = re.compile(r'(.*)(%.+\s?)(.*)')
  359. for action in self.GetItems(objType = ModelAction):
  360. cmd = action.GetLog(string = False)
  361. task = GUI(show = None).ParseCommand(cmd = cmd)
  362. errList += map(lambda x: cmd[0] + ': ' + x, task.get_cmd_error())
  363. # check also variables
  364. for opt in cmd[1:]:
  365. if '=' not in opt:
  366. continue
  367. key, value = opt.split('=', 1)
  368. sval = pattern.search(value)
  369. if sval:
  370. var = sval.group(2).strip()[1:] # strip '%' from beginning
  371. found = False
  372. for v in variables:
  373. if var.startswith(v):
  374. found = True
  375. break
  376. if not found:
  377. report = True
  378. for item in filter(lambda x: isinstance(x, ModelLoop), action.GetBlock()):
  379. if var in item.GetLabel():
  380. report = False
  381. break
  382. if report:
  383. errList.append(cmd[0] + ": " + _("undefined variable '%s'") % var)
  384. ### TODO: check variables in file only optionally
  385. ### errList += self._substituteFile(action, checkOnly = True)
  386. return errList
  387. def _substituteFile(self, item, params = None, checkOnly = False):
  388. """Subsitute variables in command file inputs
  389. :param bool checkOnly: tuble - True to check variable, don't touch files
  390. :return: list of undefined variables
  391. """
  392. errList = list()
  393. self.fileInput = dict()
  394. # collect ascii inputs
  395. for p in item.GetParams()['params']:
  396. if p.get('element', '') == 'file' and \
  397. p.get('prompt', '') == 'input' and \
  398. p.get('age', '') == 'old':
  399. filename = p.get('value', p.get('default', ''))
  400. if filename and \
  401. mimetypes.guess_type(filename)[0] == 'text/plain':
  402. self.fileInput[filename] = None
  403. for finput in self.fileInput:
  404. # read lines
  405. fd = open(finput, "r")
  406. try:
  407. data = self.fileInput[finput] = fd.read()
  408. finally:
  409. fd.close()
  410. # substitute variables
  411. write = False
  412. variables = self.GetVariables()
  413. for variable in variables:
  414. pattern = re.compile('%' + variable)
  415. value = ''
  416. if params and 'variables' in params:
  417. for p in params['variables']['params']:
  418. if variable == p.get('name', ''):
  419. if p.get('type', 'string') == 'string':
  420. value = p.get('value', '')
  421. else:
  422. value = str(p.get('value', ''))
  423. break
  424. if not value:
  425. value = variables[variable].get('value', '')
  426. data = pattern.sub(value, data)
  427. if not checkOnly:
  428. write = True
  429. pattern = re.compile(r'(.*)(%.+\s?)(.*)')
  430. sval = pattern.search(data)
  431. if sval:
  432. var = sval.group(2).strip()[1:] # ignore '%'
  433. cmd = item.GetLog(string = False)[0]
  434. errList.append(cmd + ": " + _("undefined variable '%s'") % var)
  435. if not checkOnly:
  436. if write:
  437. fd = open(finput, "w")
  438. try:
  439. fd.write(data)
  440. finally:
  441. fd.close()
  442. else:
  443. self.fileInput[finput] = None
  444. return errList
  445. def OnPrepare(self, item, params):
  446. self._substituteFile(item, params, checkOnly = False)
  447. def RunAction(self, item, params, log, onDone, onPrepare = None, statusbar = None):
  448. """Run given action
  449. :param item: action item
  450. :param params: parameters dict
  451. :param log: logging window
  452. :param onDone: on-done method
  453. :param onPrepare: on-prepare method
  454. :param statusbar: wx.StatusBar instance or None
  455. """
  456. name = '({0}) {1}'.format(item.GetId(), item.GetLabel())
  457. if name in params:
  458. paramsOrig = item.GetParams(dcopy = True)
  459. item.MergeParams(params[name])
  460. if statusbar:
  461. statusbar.SetStatusText(_('Running model...'), 0)
  462. data = { 'item' : item,
  463. 'params' : copy.deepcopy(params) }
  464. log.RunCmd(command = item.GetLog(string = False, substitute = params),
  465. onDone = onDone, onPrepare = self.OnPrepare, userData = data)
  466. if name in params:
  467. item.SetParams(paramsOrig)
  468. def Run(self, log, onDone, parent = None):
  469. """Run model
  470. :param log: logging window (see gconsole.GConsole)
  471. :param onDone: on-done method
  472. :param parent: window for messages or None
  473. """
  474. if self.GetNumItems() < 1:
  475. GMessage(parent = parent,
  476. message = _('Model is empty. Nothing to run.'))
  477. return
  478. statusbar = None
  479. if isinstance(parent, wx.Frame):
  480. statusbar = parent.GetStatusBar()
  481. # validation
  482. if statusbar:
  483. statusbar.SetStatusText(_('Validating model...'), 0)
  484. errList = self.Validate()
  485. if statusbar:
  486. statusbar.SetStatusText('', 0)
  487. if errList:
  488. dlg = wx.MessageDialog(parent = parent,
  489. message = _('Model is not valid. Do you want to '
  490. 'run the model anyway?\n\n%s') % '\n'.join(errList),
  491. caption = _("Run model?"),
  492. style = wx.YES_NO | wx.NO_DEFAULT |
  493. wx.ICON_QUESTION | wx.CENTRE)
  494. ret = dlg.ShowModal()
  495. dlg.Destroy()
  496. if ret != wx.ID_YES:
  497. return
  498. # parametrization
  499. params = self.Parameterize()
  500. delInterData = False
  501. if params:
  502. dlg = ModelParamDialog(parent = parent,
  503. model = self,
  504. params = params)
  505. dlg.CenterOnParent()
  506. ret = dlg.ShowModal()
  507. if ret != wx.ID_OK:
  508. dlg.Destroy()
  509. return
  510. err = dlg.GetErrors()
  511. delInterData = dlg.DeleteIntermediateData()
  512. dlg.Destroy()
  513. if err:
  514. GError(parent = parent, message = unicode('\n'.join(err)))
  515. return
  516. err = list()
  517. for key, item in params.iteritems():
  518. for p in item['params']:
  519. if p.get('value', '') == '':
  520. err.append((key, p.get('name', ''), p.get('description', '')))
  521. if err:
  522. GError(parent = parent,
  523. message = _("Variables below not defined:") + \
  524. "\n\n" + unicode('\n'.join(map(lambda x: "%s: %s (%s)" % (x[0], x[1], x[2]), err))))
  525. return
  526. log.cmdThread.SetId(-1)
  527. for item in self.GetItems():
  528. if not item.IsEnabled():
  529. continue
  530. if isinstance(item, ModelAction):
  531. if item.GetBlockId():
  532. continue
  533. self.RunAction(item, params, log, onDone)
  534. elif isinstance(item, ModelLoop):
  535. cond = item.GetLabel()
  536. # substitute variables in condition
  537. variables = self.GetVariables()
  538. for variable in variables:
  539. pattern = re.compile('%' + variable)
  540. if pattern.search(cond):
  541. value = ''
  542. if params and 'variables' in params:
  543. for p in params['variables']['params']:
  544. if variable == p.get('name', ''):
  545. value = p.get('value', '')
  546. break
  547. if not value:
  548. value = variables[variable].get('value', '')
  549. if not value:
  550. continue
  551. vtype = variables[variable].get('type', 'string')
  552. if vtype == 'string':
  553. value = '"' + value + '"'
  554. cond = pattern.sub(value, cond)
  555. # split condition
  556. ### TODO: this part needs some better solution
  557. condVar, condText = map(lambda x: x.strip(), re.split('\s* in \s*', cond))
  558. pattern = re.compile('%' + condVar)
  559. ### for vars()[condVar] in eval(condText): ?
  560. vlist = list()
  561. if condText[0] == '`' and condText[-1] == '`':
  562. # run command
  563. cmd, dcmd = utils.CmdToTuple(condText[1:-1].split(' '))
  564. ret = RunCommand(cmd,
  565. read = True,
  566. **dcmd)
  567. if ret:
  568. vlist = ret.splitlines()
  569. else:
  570. vlist = eval(condText)
  571. if 'variables' not in params:
  572. params['variables'] = { 'params' : [] }
  573. varDict = { 'name' : condVar, 'value' : '' }
  574. params['variables']['params'].append(varDict)
  575. for var in vlist:
  576. for action in item.GetItems(self.GetItems()):
  577. if not action.IsEnabled():
  578. continue
  579. varDict['value'] = var
  580. self.RunAction(item = action, params = params,
  581. log = log, onDone = onDone)
  582. params['variables']['params'].remove(varDict)
  583. if delInterData:
  584. self.DeleteIntermediateData(log)
  585. # discard values
  586. if params:
  587. for item in params.itervalues():
  588. for p in item['params']:
  589. p['value'] = ''
  590. def DeleteIntermediateData(self, log):
  591. """Detele intermediate data"""
  592. rast, vect, rast3d, msg = self.GetIntermediateData()
  593. if rast:
  594. log.RunCmd(['g.remove', '-f', 'type=raster', 'name=%s' %','.join(rast)])
  595. if rast3d:
  596. log.RunCmd(['g.remove', '-f', 'type=raster_3d', 'name=%s' %','.join(rast3d)])
  597. if vect:
  598. log.RunCmd(['g.remove', '-f', 'type=vector', 'name=%s' %','.join(vect)])
  599. def GetIntermediateData(self):
  600. """Get info about intermediate data"""
  601. rast = list()
  602. rast3d = list()
  603. vect = list()
  604. for data in self.GetData():
  605. if not data.IsIntermediate():
  606. continue
  607. name = data.GetValue()
  608. prompt = data.GetPrompt()
  609. if prompt == 'raster':
  610. rast.append(name)
  611. elif prompt == 'vector':
  612. vect.append(name)
  613. elif prompt == 'raster_3d':
  614. rast3d.append(name)
  615. msg = ''
  616. if rast:
  617. msg += '\n\n%s: ' % _('Raster maps')
  618. msg += ', '.join(rast)
  619. if rast3d:
  620. msg += '\n\n%s: ' % _('3D raster maps')
  621. msg += ', '.join(rast3d)
  622. if vect:
  623. msg += '\n\n%s: ' % _('Vector maps')
  624. msg += ', '.join(vect)
  625. return rast, vect, rast3d, msg
  626. def Update(self):
  627. """Update model"""
  628. for item in self.items:
  629. item.Update()
  630. def IsParameterized(self):
  631. """Return True if model is parameterized"""
  632. if self.Parameterize():
  633. return True
  634. return False
  635. def Parameterize(self):
  636. """Return parameterized options"""
  637. result = dict()
  638. idx = 0
  639. if self.variables:
  640. params = list()
  641. result["variables"] = { 'flags' : list(),
  642. 'params' : params,
  643. 'idx' : idx }
  644. for name, values in self.variables.iteritems():
  645. gtype = values.get('type', 'string')
  646. if gtype in ('raster', 'vector', 'mapset', 'file', 'region', 'dir'):
  647. gisprompt = True
  648. prompt = gtype
  649. if gtype == 'raster':
  650. element = 'cell'
  651. else:
  652. element = gtype
  653. ptype = 'string'
  654. else:
  655. gisprompt = False
  656. prompt = None
  657. element = None
  658. ptype = gtype
  659. params.append({ 'gisprompt' : gisprompt,
  660. 'multiple' : False,
  661. 'description' : values.get('description', ''),
  662. 'guidependency' : '',
  663. 'default' : '',
  664. 'age' : None,
  665. 'required' : True,
  666. 'value' : values.get('value', ''),
  667. 'label' : '',
  668. 'guisection' : '',
  669. 'key_desc' : '',
  670. 'values' : list(),
  671. 'parameterized' : False,
  672. 'values_desc' : list(),
  673. 'prompt' : prompt,
  674. 'element' : element,
  675. 'type' : ptype,
  676. 'name' : name })
  677. idx += 1
  678. for action in self.GetItems(objType = ModelAction):
  679. if not action.IsEnabled():
  680. continue
  681. name = '({0}) {1}'.format(action.GetId(), action.GetLabel())
  682. params = action.GetParams()
  683. increment = False
  684. for f in params['flags']:
  685. if f.get('parameterized', False):
  686. if name not in result:
  687. increment = True
  688. result[name] = { 'flags' : list(),
  689. 'params': list(),
  690. 'idx' : idx }
  691. result[name]['flags'].append(f)
  692. for p in params['params']:
  693. if p.get('parameterized', False):
  694. if name not in result:
  695. increment = True
  696. result[name] = { 'flags' : list(),
  697. 'params': list(),
  698. 'idx' : idx }
  699. result[name]['params'].append(p)
  700. if increment:
  701. idx += 1
  702. self.variablesParams = result # record parameters
  703. return result
  704. class ModelObject(object):
  705. def __init__(self, id = -1, label = ''):
  706. self.id = id # internal id, should be not changed
  707. self.label = ''
  708. self.rels = list() # list of ModelRelations
  709. self.isEnabled = True
  710. self.inBlock = list() # list of related loops/conditions
  711. def __del__(self):
  712. pass
  713. def GetLabel(self):
  714. """Get label"""
  715. return self.label
  716. def SetLabel(self, label=''):
  717. """Set label"""
  718. self.label = label
  719. def GetId(self):
  720. """Get id"""
  721. return self.id
  722. def SetId(self, newId):
  723. """Set id"""
  724. if self.inBlock:
  725. for loop in self.inBlock:
  726. # update block item
  727. loop.UpdateItem(self.id, newId)
  728. self.id = newId
  729. def AddRelation(self, rel):
  730. """Record new relation
  731. """
  732. self.rels.append(rel)
  733. def GetRelations(self, fdir = None):
  734. """Get list of relations
  735. :param bool fdir: True for 'from'
  736. """
  737. if fdir is None:
  738. return self.rels
  739. result = list()
  740. for rel in self.rels:
  741. if fdir == 'from':
  742. if rel.GetFrom() == self:
  743. result.append(rel)
  744. else:
  745. if rel.GetTo() == self:
  746. result.append(rel)
  747. return result
  748. def IsEnabled(self):
  749. """Get True if action is enabled, otherwise False"""
  750. return self.isEnabled
  751. def Enable(self, enabled = True):
  752. """Enable/disable action"""
  753. self.isEnabled = enabled
  754. self.Update()
  755. def Update(self):
  756. pass
  757. def SetBlock(self, item):
  758. """Add object to the block (loop/condition)
  759. :param item: reference to ModelLoop or ModelCondition which
  760. defines loops/condition
  761. """
  762. if item not in self.inBlock:
  763. self.inBlock.append(item)
  764. def UnSetBlock(self, item):
  765. """Remove object from the block (loop/consition)
  766. :param item: reference to ModelLoop or ModelCondition which
  767. defines loops/codition
  768. """
  769. if item in self.inBlock:
  770. self.inBlock.remove(item)
  771. def GetBlock(self):
  772. """Get list of related ModelObject(s) which defines block
  773. (loop/condition)
  774. :return: list of ModelObjects
  775. """
  776. return self.inBlock
  777. def GetBlockId(self):
  778. """Get list of related ids which defines block
  779. :return: list of ids
  780. """
  781. ret = list()
  782. for mo in self.inBlock:
  783. ret.append(mo.GetId())
  784. return ret
  785. class ModelAction(ModelObject, ogl.DividedShape):
  786. """Action class (GRASS module)"""
  787. def __init__(self, parent, x, y, id = -1, cmd = None, task = None,
  788. width = None, height = None, label = None, comment = ''):
  789. ModelObject.__init__(self, id, label)
  790. self.parent = parent
  791. self.task = task
  792. self.comment = comment
  793. if not width:
  794. width = UserSettings.Get(group='modeler', key='action', subkey=('size', 'width'))
  795. if not height:
  796. height = UserSettings.Get(group='modeler', key='action', subkey=('size', 'height'))
  797. if cmd:
  798. self.task = GUI(show = None).ParseCommand(cmd = cmd)
  799. else:
  800. if task:
  801. self.task = task
  802. else:
  803. self.task = None
  804. self.propWin = None
  805. self.data = list() # list of connected data items
  806. self.isValid = False
  807. self.isParameterized = False
  808. if self.parent.GetCanvas():
  809. ogl.DividedShape.__init__(self, width, height)
  810. self.regionLabel = ogl.ShapeRegion()
  811. self.regionLabel.SetFormatMode(ogl.FORMAT_CENTRE_HORIZ | ogl.FORMAT_CENTRE_VERT)
  812. self.AddRegion(self.regionLabel)
  813. self.regionComment = None
  814. self.SetCanvas(self.parent)
  815. self.SetX(x)
  816. self.SetY(y)
  817. self._setPen()
  818. self._setBrush()
  819. self.SetLabel(label)
  820. if comment:
  821. self.SetComment(comment)
  822. self.SetRegionSizes()
  823. self.ReformatRegions()
  824. if self.task:
  825. self.SetValid(self.task.get_options())
  826. def _setBrush(self, running = False):
  827. """Set brush"""
  828. if running:
  829. color = UserSettings.Get(group='modeler', key='action',
  830. subkey=('color', 'running'))
  831. elif not self.isEnabled:
  832. color = UserSettings.Get(group='modeler', key='disabled',
  833. subkey='color')
  834. elif self.isValid:
  835. color = UserSettings.Get(group='modeler', key='action',
  836. subkey=('color', 'valid'))
  837. else:
  838. color = UserSettings.Get(group='modeler', key='action',
  839. subkey=('color', 'invalid'))
  840. wxColor = wx.Colour(color[0], color[1], color[2])
  841. self.SetBrush(wx.Brush(wxColor))
  842. def _setPen(self):
  843. """Set pen"""
  844. if self.isParameterized:
  845. width = int(UserSettings.Get(group='modeler', key='action',
  846. subkey=('width', 'parameterized')))
  847. else:
  848. width = int(UserSettings.Get(group='modeler', key='action',
  849. subkey=('width', 'default')))
  850. if self.isEnabled:
  851. style = wx.SOLID
  852. else:
  853. style = wx.DOT
  854. pen = wx.Pen(wx.BLACK, width, style)
  855. self.SetPen(pen)
  856. def ReformatRegions(self):
  857. rnum = 0
  858. canvas = self.parent.GetCanvas()
  859. dc = wx.ClientDC(canvas) # used for measuring
  860. for region in self.GetRegions():
  861. text = region.GetText()
  862. self.FormatText(dc, text, rnum)
  863. rnum += 1
  864. def OnSizingEndDragLeft(self, pt, x, y, keys, attch):
  865. ogl.DividedShape.OnSizingEndDragLeft(self, pt, x, y, keys, attch)
  866. self.SetRegionSizes()
  867. self.ReformatRegions()
  868. self.GetCanvas().Refresh()
  869. def SetLabel(self, label=None):
  870. """Set label
  871. :param label: if None use command string instead
  872. """
  873. if label:
  874. self.label = label
  875. elif self.label:
  876. label = self.label
  877. else:
  878. try:
  879. label = self.task.get_cmd(ignoreErrors = True)[0]
  880. except:
  881. label = _("unknown")
  882. idx = self.GetId()
  883. self.regionLabel.SetText('(%d) %s' % (idx, label))
  884. self.SetRegionSizes()
  885. self.ReformatRegions()
  886. def SetComment(self, comment):
  887. """Set comment"""
  888. self.comment = comment
  889. if self.regionComment is None:
  890. self.regionComment = ogl.ShapeRegion()
  891. self.regionComment.SetFormatMode(ogl.FORMAT_CENTRE_HORIZ)
  892. font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
  893. font.SetStyle(wx.ITALIC)
  894. self.regionComment.SetFont(font)
  895. ### clear doesn't work
  896. ### self.regionComment.ClearText()
  897. self.regionComment.SetText(comment)
  898. self.ClearRegions()
  899. self.AddRegion(self.regionLabel)
  900. self.regionLabel.SetProportions(0.0, 1.0)
  901. if self.comment:
  902. self.AddRegion(self.regionComment)
  903. self.regionLabel.SetProportions(0.0, 0.4)
  904. self.SetRegionSizes()
  905. self.ReformatRegions()
  906. def GetComment(self):
  907. """Get comment"""
  908. return self.comment
  909. def SetProperties(self, params, propwin):
  910. """Record properties dialog"""
  911. self.task.params = params['params']
  912. self.task.flags = params['flags']
  913. self.propWin = propwin
  914. def GetPropDialog(self):
  915. """Get properties dialog"""
  916. return self.propWin
  917. def GetLog(self, string = True, substitute = None):
  918. """Get logging info
  919. :param string: True to get cmd as a string otherwise a list
  920. :param substitute: dictionary of parameter to substitute or None
  921. """
  922. cmd = self.task.get_cmd(ignoreErrors = True, ignoreRequired = True,
  923. ignoreDefault = False)
  924. # substitute variables
  925. if substitute:
  926. variables = []
  927. if 'variables' in substitute:
  928. for p in substitute['variables']['params']:
  929. variables.append(p.get('name', ''))
  930. else:
  931. variables = self.parent.GetVariables()
  932. # order variables by length
  933. for variable in sorted(variables, key=len, reverse=True):
  934. pattern= re.compile('%' + variable)
  935. value = ''
  936. if substitute and 'variables' in substitute:
  937. for p in substitute['variables']['params']:
  938. if variable == p.get('name', ''):
  939. if p.get('type', 'string') == 'string':
  940. value = p.get('value', '')
  941. else:
  942. value = str(p.get('value', ''))
  943. break
  944. if not value:
  945. value = variables[variable].get('value', '')
  946. if not value:
  947. continue
  948. for idx in range(len(cmd)):
  949. if pattern.search(cmd[idx]):
  950. cmd[idx] = pattern.sub(value, cmd[idx])
  951. break
  952. idx += 1
  953. if string:
  954. if cmd is None:
  955. return ''
  956. else:
  957. return ' '.join(cmd)
  958. return cmd
  959. def GetLabel(self):
  960. """Get name"""
  961. if self.label:
  962. return self.label
  963. cmd = self.task.get_cmd(ignoreErrors = True)
  964. if cmd and len(cmd) > 0:
  965. return cmd[0]
  966. return _('unknown')
  967. def GetParams(self, dcopy = False):
  968. """Get dictionary of parameters"""
  969. if dcopy:
  970. return copy.deepcopy(self.task.get_options())
  971. return self.task.get_options()
  972. def GetTask(self):
  973. """Get grassTask instance"""
  974. return self.task
  975. def SetParams(self, params):
  976. """Set dictionary of parameters"""
  977. self.task.params = params['params']
  978. self.task.flags = params['flags']
  979. def MergeParams(self, params):
  980. """Merge dictionary of parameters"""
  981. if 'flags' in params:
  982. for f in params['flags']:
  983. self.task.set_flag(f['name'],
  984. f.get('value', False))
  985. if 'params' in params:
  986. for p in params['params']:
  987. self.task.set_param(p['name'],
  988. p.get('value', ''))
  989. def SetValid(self, options):
  990. """Set validity for action
  991. :param options: dictionary with flags and params (gtask)
  992. """
  993. self.isValid = True
  994. for f in options['flags']:
  995. if f.get('parameterized', False):
  996. self.isParameterized = True
  997. break
  998. for p in options['params']:
  999. if self.isValid and p.get('required', False) and \
  1000. p.get('value', '') == '' and \
  1001. p.get('default', '') == '':
  1002. self.isValid = False
  1003. if not self.isParameterized and p.get('parameterized', False):
  1004. self.isParameterized = True
  1005. if self.parent.GetCanvas():
  1006. self._setBrush()
  1007. self._setPen()
  1008. def IsValid(self):
  1009. """Check validity (all required parameters set)"""
  1010. return self.isValid
  1011. def IsParameterized(self):
  1012. """Check if action is parameterized"""
  1013. return self.isParameterized
  1014. def GetParameterizedParams(self):
  1015. """Return parameterized flags and options"""
  1016. param = { 'flags': [], 'params' : [] }
  1017. options = self.GetParams()
  1018. for f in options['flags']:
  1019. if f.get('parameterized', False):
  1020. param['flags'].append(f)
  1021. for p in options['params']:
  1022. if p.get('parameterized', False):
  1023. param['params'].append(p)
  1024. return param
  1025. def FindData(self, name):
  1026. """Find data item by name"""
  1027. for rel in self.GetRelations():
  1028. data = rel.GetData()
  1029. if name == rel.GetLabel() and name in data.GetLabel():
  1030. return data
  1031. return None
  1032. def Update(self, running = False):
  1033. """Update action"""
  1034. if running:
  1035. self._setBrush(running = True)
  1036. else:
  1037. self._setBrush()
  1038. self._setPen()
  1039. def OnDraw(self, dc):
  1040. """Draw action in canvas"""
  1041. self._setBrush()
  1042. self._setPen()
  1043. ogl.RectangleShape.Recentre(self, dc) # re-center text
  1044. ogl.RectangleShape.OnDraw(self, dc)
  1045. class ModelData(ModelObject, ogl.EllipseShape):
  1046. def __init__(self, parent, x, y, value = '', prompt = '', width = None, height = None):
  1047. """Data item class
  1048. :param parent: window parent
  1049. :param x, y: position of the shape
  1050. :param fname, tname: list of parameter names from / to
  1051. :param value: value
  1052. :param prompt: type of GIS element
  1053. :param width, height: dimension of the shape
  1054. """
  1055. ModelObject.__init__(self)
  1056. self.parent = parent
  1057. self.value = value
  1058. self.prompt = prompt
  1059. self.intermediate = False
  1060. self.propWin = None
  1061. if not width:
  1062. width = UserSettings.Get(group='modeler', key='data', subkey=('size', 'width'))
  1063. if not height:
  1064. height = UserSettings.Get(group='modeler', key='data', subkey=('size', 'height'))
  1065. if self.parent.GetCanvas():
  1066. ogl.EllipseShape.__init__(self, width, height)
  1067. self.SetCanvas(self.parent)
  1068. self.SetX(x)
  1069. self.SetY(y)
  1070. self._setPen()
  1071. self._setBrush()
  1072. self.SetLabel()
  1073. def IsIntermediate(self):
  1074. """Checks if data item is intermediate"""
  1075. return self.intermediate
  1076. def SetIntermediate(self, im):
  1077. """Set intermediate flag"""
  1078. self.intermediate = im
  1079. def OnDraw(self, dc):
  1080. self._setPen()
  1081. ogl.EllipseShape.OnDraw(self, dc)
  1082. def GetLog(self, string = True):
  1083. """Get logging info"""
  1084. name = list()
  1085. for rel in self.GetRelations():
  1086. name.append(rel.GetLabel())
  1087. if name:
  1088. return '/'.join(name) + '=' + self.value + ' (' + self.prompt + ')'
  1089. else:
  1090. return self.value + ' (' + self.prompt + ')'
  1091. def GetLabel(self):
  1092. """Get list of names"""
  1093. name = list()
  1094. for rel in self.GetRelations():
  1095. name.append(rel.GetLabel())
  1096. return name
  1097. def GetPrompt(self):
  1098. """Get prompt"""
  1099. return self.prompt
  1100. def SetPrompt(self, prompt):
  1101. """Set prompt
  1102. :param prompt:
  1103. """
  1104. self.prompt = prompt
  1105. def GetValue(self):
  1106. """Get value"""
  1107. return self.value
  1108. def SetValue(self, value):
  1109. """Set value
  1110. :param value:
  1111. """
  1112. self.value = value
  1113. self.SetLabel()
  1114. for direction in ('from', 'to'):
  1115. for rel in self.GetRelations(direction):
  1116. if direction == 'from':
  1117. action = rel.GetTo()
  1118. else:
  1119. action = rel.GetFrom()
  1120. task = GUI(show = None).ParseCommand(cmd = action.GetLog(string = False))
  1121. task.set_param(rel.GetLabel(), self.value)
  1122. action.MergeParams(task.get_options())
  1123. def GetPropDialog(self):
  1124. """Get properties dialog"""
  1125. return self.propWin
  1126. def SetPropDialog(self, win):
  1127. """Get properties dialog"""
  1128. self.propWin = win
  1129. def _setBrush(self):
  1130. """Set brush"""
  1131. if self.prompt == 'raster':
  1132. color = UserSettings.Get(group = 'modeler', key = 'data',
  1133. subkey = ('color', 'raster'))
  1134. elif self.prompt == 'raster_3d':
  1135. color = UserSettings.Get(group = 'modeler', key = 'data',
  1136. subkey = ('color', 'raster3d'))
  1137. elif self.prompt == 'vector':
  1138. color = UserSettings.Get(group = 'modeler', key = 'data',
  1139. subkey = ('color', 'vector'))
  1140. elif self.prompt == 'dbtable':
  1141. color = UserSettings.Get(group = 'modeler', key = 'data',
  1142. subkey = ('color', 'dbtable'))
  1143. else:
  1144. color = UserSettings.Get(group = 'modeler', key = 'action',
  1145. subkey = ('color', 'invalid'))
  1146. wxColor = wx.Colour(color[0], color[1], color[2])
  1147. self.SetBrush(wx.Brush(wxColor))
  1148. def _setPen(self):
  1149. """Set pen"""
  1150. isParameterized = False
  1151. for rel in self.GetRelations('from'):
  1152. if rel.GetTo().IsParameterized():
  1153. isParameterized = True
  1154. break
  1155. if not isParameterized:
  1156. for rel in self.GetRelations('to'):
  1157. if rel.GetFrom().IsParameterized():
  1158. isParameterized = True
  1159. break
  1160. if isParameterized:
  1161. width = int(UserSettings.Get(group = 'modeler', key = 'action',
  1162. subkey = ('width', 'parameterized')))
  1163. else:
  1164. width = int(UserSettings.Get(group = 'modeler', key = 'action',
  1165. subkey = ('width', 'default')))
  1166. if self.intermediate:
  1167. style = wx.DOT
  1168. else:
  1169. style = wx.SOLID
  1170. pen = wx.Pen(wx.BLACK, width, style)
  1171. self.SetPen(pen)
  1172. def SetLabel(self):
  1173. """Update text"""
  1174. self.ClearText()
  1175. name = []
  1176. for rel in self.GetRelations():
  1177. name.append(rel.GetLabel())
  1178. self.AddText('/'.join(name))
  1179. if self.value:
  1180. self.AddText(self.value)
  1181. else:
  1182. self.AddText(_('<not defined>'))
  1183. def Update(self):
  1184. """Update action"""
  1185. self._setBrush()
  1186. self._setPen()
  1187. self.SetLabel()
  1188. class ModelRelation(ogl.LineShape):
  1189. """Data - action relation"""
  1190. def __init__(self, parent, fromShape, toShape, param = ''):
  1191. self.fromShape = fromShape
  1192. self.toShape = toShape
  1193. self.param = param
  1194. self.parent = parent
  1195. self._points = None
  1196. if self.parent.GetCanvas():
  1197. ogl.LineShape.__init__(self)
  1198. def __del__(self):
  1199. if self in self.fromShape.rels:
  1200. self.fromShape.rels.remove(self)
  1201. if self in self.toShape.rels:
  1202. self.toShape.rels.remove(self)
  1203. def GetFrom(self):
  1204. """Get id of 'from' shape"""
  1205. return self.fromShape
  1206. def GetTo(self):
  1207. """Get id of 'to' shape"""
  1208. return self.toShape
  1209. def GetData(self):
  1210. """Get related ModelData instance
  1211. :return: ModelData instance
  1212. :return: None if not found
  1213. """
  1214. if isinstance(self.fromShape, ModelData):
  1215. return self.fromShape
  1216. elif isinstance(self.toShape, ModelData):
  1217. return self.toShape
  1218. return None
  1219. def GetLabel(self):
  1220. """Get parameter name"""
  1221. return self.param
  1222. def ResetShapes(self):
  1223. """Reset related objects"""
  1224. self.fromShape.ResetControlPoints()
  1225. self.toShape.ResetControlPoints()
  1226. self.ResetControlPoints()
  1227. def SetControlPoints(self, points):
  1228. """Set control points"""
  1229. self._points = points
  1230. def GetControlPoints(self):
  1231. """Get list of control points"""
  1232. return self._points
  1233. def _setPen(self):
  1234. """Set pen"""
  1235. pen = wx.Pen(wx.BLACK, 1, wx.SOLID)
  1236. self.SetPen(pen)
  1237. def OnDraw(self, dc):
  1238. """Draw relation"""
  1239. self._setPen()
  1240. ogl.LineShape.OnDraw(self, dc)
  1241. def SetName(self, param):
  1242. self.param = param
  1243. class ModelItem(ModelObject):
  1244. def __init__(self, parent, x, y, id = -1, width = None, height = None, label = '', items = []):
  1245. """Abstract class for loops and conditions"""
  1246. ModelObject.__init__(self, id, label)
  1247. self.parent = parent
  1248. def _setPen(self):
  1249. """Set pen"""
  1250. if self.isEnabled:
  1251. style = wx.SOLID
  1252. else:
  1253. style = wx.DOT
  1254. pen = wx.Pen(wx.BLACK, 1, style)
  1255. self.SetPen(pen)
  1256. def SetId(self, id):
  1257. """Set loop id"""
  1258. self.id = id
  1259. def SetLabel(self, label=''):
  1260. """Set loop text (condition)"""
  1261. if label:
  1262. self.label = label
  1263. self.ClearText()
  1264. self.AddText('(' + str(self.id) + ') ' + self.label)
  1265. def GetLog(self):
  1266. """Get log info"""
  1267. if self.label:
  1268. return _("Condition: ") + self.label
  1269. else:
  1270. return _("Condition: not defined")
  1271. def AddRelation(self, rel):
  1272. """Record relation"""
  1273. self.rels.append(rel)
  1274. def Clear(self):
  1275. """Clear object, remove rels"""
  1276. self.rels = list()
  1277. class ModelLoop(ModelItem, ogl.RectangleShape):
  1278. def __init__(self, parent, x, y, id=-1, idx=-1, width = None, height = None, label = '', items = []):
  1279. """Defines a loop"""
  1280. ModelItem.__init__(self, parent, x, y, id, width, height, label, items)
  1281. self.itemIds = list() # unordered
  1282. if not width:
  1283. width = UserSettings.Get(group='modeler', key='loop', subkey=('size', 'width'))
  1284. if not height:
  1285. height = UserSettings.Get(group='modeler', key='loop', subkey=('size', 'height'))
  1286. if self.parent.GetCanvas():
  1287. ogl.RectangleShape.__init__(self, width, height)
  1288. self.SetCanvas(self.parent)
  1289. self.SetX(x)
  1290. self.SetY(y)
  1291. self._setPen()
  1292. self._setBrush()
  1293. self.SetCornerRadius(100)
  1294. self.SetLabel(label)
  1295. def _setBrush(self):
  1296. """Set brush"""
  1297. if not self.isEnabled:
  1298. color = UserSettings.Get(group='modeler', key='disabled',
  1299. subkey='color')
  1300. else:
  1301. color = UserSettings.Get(group='modeler', key='loop',
  1302. subkey=('color', 'valid'))
  1303. wxColor = wx.Colour(color[0], color[1], color[2])
  1304. self.SetBrush(wx.Brush(wxColor))
  1305. def Enable(self, enabled = True):
  1306. """Enable/disable action"""
  1307. for idx in self.itemIds:
  1308. item = self.parent.FindAction(idx)
  1309. if item:
  1310. item.Enable(enabled)
  1311. ModelObject.Enable(self, enabled)
  1312. self.Update()
  1313. def Update(self):
  1314. self._setPen()
  1315. self._setBrush()
  1316. def GetItems(self, items):
  1317. """Get sorted items by id"""
  1318. result = list()
  1319. for item in items:
  1320. if item.GetId() in self.itemIds:
  1321. result.append(item)
  1322. return result
  1323. def SetItems(self, items):
  1324. """Set items (id)"""
  1325. self.itemIds = items
  1326. def UpdateItem(self, oldId, newId):
  1327. """Update item in the list"""
  1328. idx = self.itemIds.index(oldId)
  1329. if idx != -1:
  1330. self.itemIds[idx] = newId
  1331. def OnDraw(self, dc):
  1332. """Draw loop in canvas"""
  1333. self._setBrush()
  1334. ogl.RectangleShape.Recentre(self, dc) # re-center text
  1335. ogl.RectangleShape.OnDraw(self, dc)
  1336. class ModelCondition(ModelItem, ogl.PolygonShape):
  1337. def __init__(self, parent, x, y, id = -1, width = None, height = None, label = '',
  1338. items = { 'if' : [], 'else' : [] }):
  1339. """Defines a if-else condition"""
  1340. ModelItem.__init__(self, parent, x, y, id, width, height, label, items)
  1341. self.itemIds = {'if' : [], 'else': []}
  1342. if not width:
  1343. self.width = UserSettings.Get(group='modeler', key='if-else', subkey=('size', 'width'))
  1344. else:
  1345. self.width = width
  1346. if not height:
  1347. self.height = UserSettings.Get(group='modeler', key='if-else', subkey=('size', 'height'))
  1348. else:
  1349. self.height = height
  1350. if self.parent.GetCanvas():
  1351. ogl.PolygonShape.__init__(self)
  1352. points = [(0, - self.height / 2),
  1353. (self.width / 2, 0),
  1354. (0, self.height / 2),
  1355. (- self.width / 2, 0)]
  1356. self.Create(points)
  1357. self.SetCanvas(self.parent)
  1358. self.SetX(x)
  1359. self.SetY(y)
  1360. self.SetPen(wx.BLACK_PEN)
  1361. if label:
  1362. self.AddText('(' + str(self.id) + ') ' + label)
  1363. else:
  1364. self.AddText('(' + str(self.id) + ')')
  1365. def GetLabel(self):
  1366. """Get name"""
  1367. return _("if-else")
  1368. def GetWidth(self):
  1369. """Get object width"""
  1370. return self.width
  1371. def GetHeight(self):
  1372. """Get object height"""
  1373. return self.height
  1374. def GetItems(self, items):
  1375. """Get sorted items by id"""
  1376. result = {'if' : [], 'else': []}
  1377. for item in items:
  1378. if item.GetId() in self.itemIds['if']:
  1379. result['if'].append(item)
  1380. elif item.GetId() in self.itemIds['else']:
  1381. result['else'].append(item)
  1382. return result
  1383. def SetItems(self, items, branch = 'if'):
  1384. """Set items (id)
  1385. :param items: list of items
  1386. :param branch: 'if' / 'else'
  1387. """
  1388. if branch in ['if', 'else']:
  1389. self.itemIds[branch] = items
  1390. class ModelComment(ModelObject, ogl.RectangleShape):
  1391. def __init__(self, parent, x, y, id = -1, width = None, height = None, label = ''):
  1392. """Defines a model comment"""
  1393. ModelObject.__init__(self, id, label)
  1394. if not width:
  1395. width = UserSettings.Get(group='modeler', key='comment', subkey=('size', 'width'))
  1396. if not height:
  1397. height = UserSettings.Get(group='modeler', key='comment', subkey=('size', 'height'))
  1398. if parent.GetCanvas():
  1399. ogl.RectangleShape.__init__(self, width, height)
  1400. self.SetCanvas(parent)
  1401. self.SetX(x)
  1402. self.SetY(y)
  1403. font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
  1404. font.SetStyle(wx.ITALIC)
  1405. self.SetFont(font)
  1406. self._setPen()
  1407. self._setBrush()
  1408. self.SetLabel(label)
  1409. def _setBrush(self, running = False):
  1410. """Set brush"""
  1411. color = UserSettings.Get(group='modeler', key='comment',
  1412. subkey='color')
  1413. wxColor = wx.Colour(color[0], color[1], color[2])
  1414. self.SetBrush(wx.Brush(wxColor))
  1415. def _setPen(self):
  1416. """Set pen"""
  1417. pen = wx.Pen(wx.BLACK, 1, wx.DOT)
  1418. self.SetPen(pen)
  1419. def SetLabel(self, label=None):
  1420. """Set label
  1421. :param label: if None use command string instead
  1422. """
  1423. if label:
  1424. self.label = label
  1425. elif self.label:
  1426. label = self.label
  1427. else:
  1428. label = ''
  1429. idx = self.GetId()
  1430. self.ClearText()
  1431. self.AddText('(%d) %s' % (idx, label))
  1432. def GetComment(self):
  1433. return self.GetLabel()
  1434. def SetComment(self, comment):
  1435. self.SetLabel(comment)
  1436. self.GetCanvas().Refresh()
  1437. class ProcessModelFile:
  1438. """Process GRASS model file (gxm)"""
  1439. def __init__(self, tree):
  1440. """A ElementTree handler for the GXM XML file, as defined in
  1441. grass-gxm.dtd.
  1442. """
  1443. self.tree = tree
  1444. self.root = self.tree.getroot()
  1445. # check if input is a valid GXM file
  1446. if self.root is None or self.root.tag != 'gxm':
  1447. if self.root is not None:
  1448. tagName = self.root.tag
  1449. else:
  1450. tabName = _("empty")
  1451. raise GException(_("Details: unsupported tag name '{}'.").format(tagName))
  1452. # list of actions, data
  1453. self.properties = dict()
  1454. self.variables = dict()
  1455. self.actions = list()
  1456. self.data = list()
  1457. self.loops = list()
  1458. self.conditions = list()
  1459. self.comments = list()
  1460. self._processWindow()
  1461. self._processProperties()
  1462. self._processVariables()
  1463. self._processItems()
  1464. self._processData()
  1465. def _filterValue(self, value):
  1466. """Filter value
  1467. :param value:
  1468. """
  1469. value = value.replace('&lt;', '<')
  1470. value = value.replace('&gt;', '>')
  1471. return value
  1472. def _getNodeText(self, node, tag, default = ''):
  1473. """Get node text"""
  1474. p = node.find(tag)
  1475. if p is not None:
  1476. if p.text:
  1477. return utils.normalize_whitespace(p.text)
  1478. else:
  1479. return ''
  1480. return default
  1481. def _processWindow(self):
  1482. """Process window properties"""
  1483. node = self.root.find('window')
  1484. if node is None:
  1485. self.pos = self.size = None
  1486. return
  1487. self.pos, self.size = self._getDim(node)
  1488. def _processProperties(self):
  1489. """Process model properties"""
  1490. node = self.root.find('properties')
  1491. if node is None:
  1492. return
  1493. for key in ('name', 'description', 'author'):
  1494. self._processProperty(node, key)
  1495. for f in node.findall('flag'):
  1496. name = f.get('name', '')
  1497. if name == 'overwrite':
  1498. self.properties['overwrite'] = True
  1499. def _processProperty(self, pnode, name):
  1500. """Process given property"""
  1501. node = pnode.find(name)
  1502. if node is not None:
  1503. self.properties[name] = node.text
  1504. else:
  1505. self.properties[name] = ''
  1506. def _processVariables(self):
  1507. """Process model variables"""
  1508. vnode = self.root.find('variables')
  1509. if vnode is None:
  1510. return
  1511. for node in vnode.findall('variable'):
  1512. name = node.get('name', '')
  1513. if not name:
  1514. continue # should not happen
  1515. self.variables[name] = { 'type' : node.get('type', 'string') }
  1516. for key in ('description', 'value'):
  1517. self._processVariable(node, name, key)
  1518. def _processVariable(self, pnode, name, key):
  1519. """Process given variable"""
  1520. node = pnode.find(key)
  1521. if node is not None:
  1522. if node.text:
  1523. self.variables[name][key] = node.text
  1524. def _processItems(self):
  1525. """Process model items (actions, loops, conditions)"""
  1526. self._processActions()
  1527. self._processLoops()
  1528. self._processConditions()
  1529. self._processComments()
  1530. def _processActions(self):
  1531. """Process model file"""
  1532. for action in self.root.findall('action'):
  1533. pos, size = self._getDim(action)
  1534. disabled = False
  1535. task = action.find('task')
  1536. if task is not None:
  1537. if task.find('disabled') is not None:
  1538. disabled = True
  1539. task = self._processTask(task)
  1540. else:
  1541. task = None
  1542. aId = int(action.get('id', -1))
  1543. label = action.get('name')
  1544. comment = action.find('comment')
  1545. if comment is not None:
  1546. commentString = comment.text
  1547. else:
  1548. commentString = ''
  1549. self.actions.append({ 'pos' : pos,
  1550. 'size' : size,
  1551. 'task' : task,
  1552. 'id' : aId,
  1553. 'disabled' : disabled,
  1554. 'label' : label,
  1555. 'comment' : commentString})
  1556. def _getDim(self, node):
  1557. """Get position and size of shape"""
  1558. pos = size = None
  1559. posAttr = node.get('pos', None)
  1560. if posAttr:
  1561. posVal = map(int, posAttr.split(','))
  1562. try:
  1563. pos = (posVal[0], posVal[1])
  1564. except:
  1565. pos = None
  1566. sizeAttr = node.get('size', None)
  1567. if sizeAttr:
  1568. sizeVal = map(int, sizeAttr.split(','))
  1569. try:
  1570. size = (sizeVal[0], sizeVal[1])
  1571. except:
  1572. size = None
  1573. return pos, size
  1574. def _processData(self):
  1575. """Process model file"""
  1576. for data in self.root.findall('data'):
  1577. pos, size = self._getDim(data)
  1578. param = data.find('data-parameter')
  1579. prompt = value = None
  1580. if param is not None:
  1581. prompt = param.get('prompt', None)
  1582. value = self._filterValue(self._getNodeText(param, 'value'))
  1583. if data.find('intermediate') is None:
  1584. intermediate = False
  1585. else:
  1586. intermediate = True
  1587. rels = list()
  1588. for rel in data.findall('relation'):
  1589. defrel = { 'id' : int(rel.get('id', -1)),
  1590. 'dir' : rel.get('dir', 'to'),
  1591. 'name' : rel.get('name', '') }
  1592. points = list()
  1593. for point in rel.findall('point'):
  1594. x = self._filterValue(self._getNodeText(point, 'x'))
  1595. y = self._filterValue(self._getNodeText(point, 'y'))
  1596. points.append((float(x), float(y)))
  1597. defrel['points'] = points
  1598. rels.append(defrel)
  1599. self.data.append({ 'pos' : pos,
  1600. 'size': size,
  1601. 'prompt' : prompt,
  1602. 'value' : value,
  1603. 'intermediate' : intermediate,
  1604. 'rels' : rels })
  1605. def _processTask(self, node):
  1606. """Process task
  1607. :return: grassTask instance
  1608. :return: None on error
  1609. """
  1610. cmd = list()
  1611. parameterized = list()
  1612. name = node.get('name', None)
  1613. if not name:
  1614. return None
  1615. cmd.append(name)
  1616. # flags
  1617. for f in node.findall('flag'):
  1618. flag = f.get('name', '')
  1619. if f.get('parameterized', '0') == '1':
  1620. parameterized.append(('flag', flag))
  1621. if f.get('value', '1') == '0':
  1622. continue
  1623. if len(flag) > 1:
  1624. cmd.append('--' + flag)
  1625. else:
  1626. cmd.append('-' + flag)
  1627. # parameters
  1628. for p in node.findall('parameter'):
  1629. name = p.get('name', '')
  1630. if p.find('parameterized') is not None:
  1631. parameterized.append(('param', name))
  1632. cmd.append('%s=%s' % (name,
  1633. self._filterValue(self._getNodeText(p, 'value'))))
  1634. task, err = GUI(show = None, checkError = True).ParseCommand(cmd = cmd)
  1635. if err:
  1636. GWarning(os.linesep.join(err))
  1637. for opt, name in parameterized:
  1638. if opt == 'flag':
  1639. task.set_flag(name, True, element = 'parameterized')
  1640. else:
  1641. task.set_param(name, True, element = 'parameterized')
  1642. return task
  1643. def _processLoops(self):
  1644. """Process model loops"""
  1645. for node in self.root.findall('loop'):
  1646. pos, size = self._getDim(node)
  1647. text = self._filterValue(self._getNodeText(node, 'condition')).strip()
  1648. aid = list()
  1649. for anode in node.findall('item'):
  1650. try:
  1651. aid.append(int(anode.text))
  1652. except ValueError:
  1653. pass
  1654. self.loops.append({ 'pos' : pos,
  1655. 'size' : size,
  1656. 'text' : text,
  1657. 'id' : int(node.get('id', -1)),
  1658. 'items' : aid })
  1659. def _processConditions(self):
  1660. """Process model conditions"""
  1661. for node in self.root.findall('if-else'):
  1662. pos, size = self._getDim(node)
  1663. text = self._filterValue(self._getNodeText(node, 'condition')).strip()
  1664. aid = { 'if' : list(),
  1665. 'else' : list() }
  1666. for b in aid.keys():
  1667. bnode = node.find(b)
  1668. if bnode is None:
  1669. continue
  1670. for anode in bnode.findall('item'):
  1671. try:
  1672. aid[b].append(int(anode.text))
  1673. except ValueError:
  1674. pass
  1675. self.conditions.append({ 'pos' : pos,
  1676. 'size' : size,
  1677. 'text' : text,
  1678. 'id' : int(node.get('id', -1)),
  1679. 'items' : aid })
  1680. def _processComments(self):
  1681. """Process model comments"""
  1682. for node in self.root.findall('comment'):
  1683. pos, size = self._getDim(node)
  1684. text = self._filterValue(node.text)
  1685. self.comments.append({ 'pos' : pos,
  1686. 'size' : size,
  1687. 'text' : text,
  1688. 'id' : int(node.get('id', -1)),
  1689. 'text' : text })
  1690. class WriteModelFile:
  1691. """Generic class for writing model file"""
  1692. def __init__(self, fd, model):
  1693. self.fd = fd
  1694. self.model = model
  1695. self.properties = model.GetProperties()
  1696. self.variables = model.GetVariables()
  1697. self.items = model.GetItems()
  1698. self.indent = 0
  1699. self._header()
  1700. self._window()
  1701. self._properties()
  1702. self._variables()
  1703. self._items()
  1704. dataList = list()
  1705. for action in model.GetItems(objType = ModelAction):
  1706. for rel in action.GetRelations():
  1707. dataItem = rel.GetData()
  1708. if dataItem not in dataList:
  1709. dataList.append(dataItem)
  1710. self._data(dataList)
  1711. self._footer()
  1712. def _filterValue(self, value):
  1713. """Escapes value to be stored in XML.
  1714. :param value: string to be escaped as XML
  1715. :return: a XML-valid string
  1716. """
  1717. value = saxutils.escape(value)
  1718. return value
  1719. def _header(self):
  1720. """Write header"""
  1721. self.fd.write('<?xml version="1.0" encoding="%s"?>\n' % GetDefaultEncoding(forceUTF8 = True))
  1722. self.fd.write('<!DOCTYPE gxm SYSTEM "grass-gxm.dtd">\n')
  1723. self.fd.write('%s<gxm>\n' % (' ' * self.indent))
  1724. self.indent += 4
  1725. def _footer(self):
  1726. """Write footer"""
  1727. self.indent -= 4
  1728. self.fd.write('%s</gxm>\n' % (' ' * self.indent))
  1729. def _window(self):
  1730. """Write window properties"""
  1731. canvas = self.model.GetCanvas()
  1732. if canvas is None:
  1733. return
  1734. win = canvas.parent
  1735. pos = win.GetPosition()
  1736. size = win.GetSize()
  1737. self.fd.write('%s<window pos="%d,%d" size="%d,%d" />\n' % \
  1738. (' ' * self.indent, pos[0], pos[1], size[0], size[1]))
  1739. def _properties(self):
  1740. """Write model properties"""
  1741. self.fd.write('%s<properties>\n' % (' ' * self.indent))
  1742. self.indent += 4
  1743. if self.properties['name']:
  1744. self.fd.write('%s<name>%s</name>\n' % (' ' * self.indent, EncodeString(self.properties['name'])))
  1745. if self.properties['description']:
  1746. self.fd.write('%s<description>%s</description>\n' % (' ' * self.indent,
  1747. EncodeString(self.properties['description'])))
  1748. if self.properties['author']:
  1749. self.fd.write('%s<author>%s</author>\n' % (' ' * self.indent,
  1750. EncodeString(self.properties['author'])))
  1751. if 'overwrite' in self.properties and \
  1752. self.properties['overwrite']:
  1753. self.fd.write('%s<flag name="overwrite" />\n' % (' ' * self.indent))
  1754. self.indent -= 4
  1755. self.fd.write('%s</properties>\n' % (' ' * self.indent))
  1756. def _variables(self):
  1757. """Write model variables"""
  1758. if not self.variables:
  1759. return
  1760. self.fd.write('%s<variables>\n' % (' ' * self.indent))
  1761. self.indent += 4
  1762. for name, values in self.variables.iteritems():
  1763. self.fd.write('%s<variable name="%s" type="%s">\n' % \
  1764. (' ' * self.indent, EncodeString(name), values['type']))
  1765. self.indent += 4
  1766. if 'value' in values:
  1767. self.fd.write('%s<value>%s</value>\n' % \
  1768. (' ' * self.indent, EncodeString(values['value'])))
  1769. if 'description' in values:
  1770. self.fd.write('%s<description>%s</description>\n' % \
  1771. (' ' * self.indent, EncodeString(values['description'])))
  1772. self.indent -= 4
  1773. self.fd.write('%s</variable>\n' % (' ' * self.indent))
  1774. self.indent -= 4
  1775. self.fd.write('%s</variables>\n' % (' ' * self.indent))
  1776. def _items(self):
  1777. """Write actions/loops/conditions"""
  1778. for item in self.items:
  1779. if isinstance(item, ModelAction):
  1780. self._action(item)
  1781. elif isinstance(item, ModelLoop):
  1782. self._loop(item)
  1783. elif isinstance(item, ModelCondition):
  1784. self._condition(item)
  1785. elif isinstance(item, ModelComment):
  1786. self._comment(item)
  1787. def _action(self, action):
  1788. """Write actions"""
  1789. self.fd.write('%s<action id="%d" name="%s" pos="%d,%d" size="%d,%d">\n' % \
  1790. (' ' * self.indent, action.GetId(), EncodeString(action.GetLabel()), action.GetX(), action.GetY(),
  1791. action.GetWidth(), action.GetHeight()))
  1792. self.indent += 4
  1793. comment = action.GetComment()
  1794. if comment:
  1795. self.fd.write('%s<comment>%s</comment>\n' % (' ' * self.indent, EncodeString(comment)))
  1796. self.fd.write('%s<task name="%s">\n' % (' ' * self.indent, action.GetLog(string = False)[0]))
  1797. self.indent += 4
  1798. if not action.IsEnabled():
  1799. self.fd.write('%s<disabled />\n' % (' ' * self.indent))
  1800. for key, val in action.GetParams().iteritems():
  1801. if key == 'flags':
  1802. for f in val:
  1803. if f.get('value', False) or f.get('parameterized', False):
  1804. if f.get('parameterized', False):
  1805. if f.get('value', False) == False:
  1806. self.fd.write('%s<flag name="%s" value="0" parameterized="1" />\n' %
  1807. (' ' * self.indent, f.get('name', '')))
  1808. else:
  1809. self.fd.write('%s<flag name="%s" parameterized="1" />\n' %
  1810. (' ' * self.indent, f.get('name', '')))
  1811. else:
  1812. self.fd.write('%s<flag name="%s" />\n' %
  1813. (' ' * self.indent, f.get('name', '')))
  1814. else: # parameter
  1815. for p in val:
  1816. if not p.get('value', '') and not p.get('parameterized', False):
  1817. continue
  1818. self.fd.write('%s<parameter name="%s">\n' %
  1819. (' ' * self.indent, p.get('name', '')))
  1820. self.indent += 4
  1821. if p.get('parameterized', False):
  1822. self.fd.write('%s<parameterized />\n' % (' ' * self.indent))
  1823. self.fd.write('%s<value>%s</value>\n' %
  1824. (' ' * self.indent, self._filterValue(p.get('value', ''))))
  1825. self.indent -= 4
  1826. self.fd.write('%s</parameter>\n' % (' ' * self.indent))
  1827. self.indent -= 4
  1828. self.fd.write('%s</task>\n' % (' ' * self.indent))
  1829. self.indent -= 4
  1830. self.fd.write('%s</action>\n' % (' ' * self.indent))
  1831. def _data(self, dataList):
  1832. """Write data"""
  1833. for data in dataList:
  1834. self.fd.write('%s<data pos="%d,%d" size="%d,%d">\n' % \
  1835. (' ' * self.indent, data.GetX(), data.GetY(),
  1836. data.GetWidth(), data.GetHeight()))
  1837. self.indent += 4
  1838. self.fd.write('%s<data-parameter prompt="%s">\n' % \
  1839. (' ' * self.indent, data.GetPrompt()))
  1840. self.indent += 4
  1841. self.fd.write('%s<value>%s</value>\n' %
  1842. (' ' * self.indent, self._filterValue(data.GetValue())))
  1843. self.indent -= 4
  1844. self.fd.write('%s</data-parameter>\n' % (' ' * self.indent))
  1845. if data.IsIntermediate():
  1846. self.fd.write('%s<intermediate />\n' % (' ' * self.indent))
  1847. # relations
  1848. for ft in ('from', 'to'):
  1849. for rel in data.GetRelations(ft):
  1850. if ft == 'from':
  1851. aid = rel.GetTo().GetId()
  1852. else:
  1853. aid = rel.GetFrom().GetId()
  1854. self.fd.write('%s<relation dir="%s" id="%d" name="%s">\n' % \
  1855. (' ' * self.indent, ft, aid, rel.GetLabel()))
  1856. self.indent += 4
  1857. for point in rel.GetLineControlPoints()[1:-1]:
  1858. self.fd.write('%s<point>\n' % (' ' * self.indent))
  1859. self.indent += 4
  1860. x, y = point.Get()
  1861. self.fd.write('%s<x>%d</x>\n' % (' ' * self.indent, int(x)))
  1862. self.fd.write('%s<y>%d</y>\n' % (' ' * self.indent, int(y)))
  1863. self.indent -= 4
  1864. self.fd.write('%s</point>\n' % (' ' * self.indent))
  1865. self.indent -= 4
  1866. self.fd.write('%s</relation>\n' % (' ' * self.indent))
  1867. self.indent -= 4
  1868. self.fd.write('%s</data>\n' % (' ' * self.indent))
  1869. def _loop(self, loop):
  1870. """Write loops"""
  1871. self.fd.write('%s<loop id="%d" pos="%d,%d" size="%d,%d">\n' % \
  1872. (' ' * self.indent, loop.GetId(), loop.GetX(), loop.GetY(),
  1873. loop.GetWidth(), loop.GetHeight()))
  1874. self.indent += 4
  1875. cond = loop.GetLabel()
  1876. if cond:
  1877. self.fd.write('%s<condition>%s</condition>\n' %
  1878. (' ' * self.indent, self._filterValue(cond)))
  1879. for item in loop.GetItems(self.model.GetItems(objType=ModelAction)):
  1880. self.fd.write('%s<item>%d</item>\n' %
  1881. (' ' * self.indent, item.GetId()))
  1882. self.indent -= 4
  1883. self.fd.write('%s</loop>\n' % (' ' * self.indent))
  1884. def _condition(self, condition):
  1885. """Write conditions"""
  1886. bbox = condition.GetBoundingBoxMin()
  1887. self.fd.write('%s<if-else id="%d" pos="%d,%d" size="%d,%d">\n' % \
  1888. (' ' * self.indent, condition.GetId(), condition.GetX(), condition.GetY(),
  1889. bbox[0], bbox[1]))
  1890. text = condition.GetLabel()
  1891. self.indent += 4
  1892. if text:
  1893. self.fd.write('%s<condition>%s</condition>\n' %
  1894. (' ' * self.indent, self._filterValue(text)))
  1895. items = condition.GetItems()
  1896. for b in items.keys():
  1897. if len(items[b]) < 1:
  1898. continue
  1899. self.fd.write('%s<%s>\n' % (' ' * self.indent, b))
  1900. self.indent += 4
  1901. for item in items[b]:
  1902. self.fd.write('%s<item>%d</item>\n' %
  1903. (' ' * self.indent, item.GetId()))
  1904. self.indent -= 4
  1905. self.fd.write('%s</%s>\n' % (' ' * self.indent, b))
  1906. self.indent -= 4
  1907. self.fd.write('%s</if-else>\n' % (' ' * self.indent))
  1908. def _comment(self, comment):
  1909. """Write comment"""
  1910. self.fd.write('%s<comment id="%d" pos="%d,%d" size="%d,%d">%s</comment>\n' % \
  1911. (' ' * self.indent, comment.GetId(), comment.GetX(), comment.GetY(),
  1912. comment.GetWidth(), comment.GetHeight(), EncodeString(comment.GetLabel())))
  1913. class WritePythonFile:
  1914. def __init__(self, fd, model):
  1915. """Class for exporting model to Python script
  1916. :param fd: file descriptor
  1917. """
  1918. self.fd = fd
  1919. self.model = model
  1920. self.indent = 4
  1921. self._writePython()
  1922. def _getStandardizedOption(self, string):
  1923. if string == 'raster':
  1924. return 'G_OPT_R_MAP'
  1925. elif string == 'vector':
  1926. return 'G_OPT_V_MAP'
  1927. elif string == 'mapset':
  1928. return 'G_OPT_M_MAPSET'
  1929. elif string == 'file':
  1930. return 'G_OPT_F_INPUT'
  1931. elif string == 'dir':
  1932. return 'G_OPT_M_DIR'
  1933. elif string == 'region':
  1934. return 'G_OPT_M_REGION'
  1935. return ''
  1936. def _writePython(self):
  1937. """Write model to file"""
  1938. properties = self.model.GetProperties()
  1939. # header
  1940. self.fd.write(
  1941. r"""#!/usr/bin/env python
  1942. #
  1943. #%s
  1944. #
  1945. # MODULE: %s
  1946. #
  1947. # AUTHOR(S): %s
  1948. #
  1949. # PURPOSE: %s
  1950. #
  1951. # DATE: %s
  1952. #
  1953. #%s
  1954. """% ('#' * 77,
  1955. EncodeString(properties['name']),
  1956. EncodeString(properties['author']),
  1957. EncodeString('\n# '.join(properties['description'].splitlines())),
  1958. time.asctime(),
  1959. '#' * 77))
  1960. # UI
  1961. self.fd.write(
  1962. r"""
  1963. #%%module
  1964. #%% description: %s
  1965. #%%end
  1966. """% (EncodeString(' '.join(properties['description'].splitlines()))))
  1967. variables = self.model.GetVariables()
  1968. for key, data in variables.iteritems():
  1969. otype = self._getStandardizedOption(data['type'])
  1970. self.fd.write(
  1971. r"""
  1972. #%%option %s
  1973. #%% key: %s
  1974. #%% description: %s
  1975. #%% required: yes
  1976. """% (otype, key, data['description']))
  1977. if 'value' in data:
  1978. self.fd.write("#%% answer: %s\n" % data['value'])
  1979. self.fd.write("#% end\n")
  1980. # import modules
  1981. self.fd.write(
  1982. r"""
  1983. import sys
  1984. import os
  1985. import atexit
  1986. from grass.script import parser, run_command
  1987. """)
  1988. # cleanup()
  1989. rast, vect, rast3d, msg = self.model.GetIntermediateData()
  1990. self.fd.write(
  1991. r"""
  1992. def cleanup():
  1993. """)
  1994. if rast:
  1995. self.fd.write(
  1996. r""" run_command('g.remove', flags='f', type='raster',
  1997. name=%s)
  1998. """% ','.join(map(lambda x: "'" + x + "'", rast)))
  1999. if vect:
  2000. self.fd.write(
  2001. r""" run_command('g.remove', flags='f', type='vector',
  2002. name=%s)
  2003. """% ','.join(map(lambda x: "'" + x + "'", vect)))
  2004. if rast3d:
  2005. self.fd.write(
  2006. r""" run_command('g.remove', flags='f', type='raster_3d',
  2007. name=%s)
  2008. """% ','.join(map(lambda x: "'" + x + "'", rast3d)))
  2009. if not rast and not vect and not rast3d:
  2010. self.fd.write(' pass\n')
  2011. self.fd.write("\ndef main():\n")
  2012. for item in self.model.GetItems():
  2013. self._writePythonItem(item, variables = self.model.GetVariables())
  2014. self.fd.write("\n return 0\n")
  2015. self.fd.write(
  2016. r"""
  2017. if __name__ == "__main__":
  2018. options, flags = parser()
  2019. atexit.register(cleanup)
  2020. sys.exit(main())
  2021. """)
  2022. def _writePythonItem(self, item, ignoreBlock = True, variables = {}):
  2023. """Write model object to Python file"""
  2024. if isinstance(item, ModelAction):
  2025. if ignoreBlock and item.GetBlockId(): # ignore items in loops of conditions
  2026. return
  2027. self._writePythonAction(item, variables = variables)
  2028. elif isinstance(item, ModelLoop) or isinstance(item, ModelCondition):
  2029. # substitute condition
  2030. cond = item.GetLabel()
  2031. for variable in self.model.GetVariables():
  2032. pattern = re.compile('%' + variable)
  2033. if pattern.search(cond):
  2034. value = variables[variable].get('value', '')
  2035. if variables[variable].get('type', 'string') == 'string':
  2036. value = '"' + value + '"'
  2037. cond = pattern.sub(value, cond)
  2038. if isinstance(item, ModelLoop):
  2039. condVar, condText = map(lambda x: x.strip(), re.split('\s* in \s*', cond))
  2040. cond = "%sfor %s in " % (' ' * self.indent, condVar)
  2041. if condText[0] == '`' and condText[-1] == '`':
  2042. task = GUI(show = None).ParseCommand(cmd = utils.split(condText[1:-1]))
  2043. cond += "grass.read_command("
  2044. cond += self._getPythonActionCmd(task, len(cond), variables = [condVar]) + ".splitlines()"
  2045. else:
  2046. cond += condText
  2047. self.fd.write('%s:\n' % cond)
  2048. self.indent += 4
  2049. variablesLoop = variables.copy()
  2050. variablesLoop[condVar] = None
  2051. for action in item.GetItems(self.model.GetItems(objType=ModelAction)):
  2052. self._writePythonItem(action, ignoreBlock = False, variables = variablesLoop)
  2053. self.indent -= 4
  2054. if isinstance(item, ModelCondition):
  2055. self.fd.write('%sif %s:\n' % (' ' * self.indent, cond))
  2056. self.indent += 4
  2057. condItems = item.GetItems()
  2058. for action in condItems['if']:
  2059. self._writePythonItem(action, ignoreBlock = False)
  2060. if condItems['else']:
  2061. self.indent -= 4
  2062. self.fd.write('%selse:\n' % (' ' * self.indent))
  2063. self.indent += 4
  2064. for action in condItems['else']:
  2065. self._writePythonItem(action, ignoreBlock = False)
  2066. self.indent += 4
  2067. self.fd.write('\n')
  2068. if isinstance(item, ModelComment):
  2069. self._writePythonComment(item)
  2070. def _writePythonAction(self, item, variables = {}):
  2071. """Write model action to Python file"""
  2072. task = GUI(show = None).ParseCommand(cmd = item.GetLog(string = False))
  2073. strcmd = "%srun_command(" % (' ' * self.indent)
  2074. self.fd.write(strcmd + self._getPythonActionCmd(task, len(strcmd), variables) + '\n')
  2075. def _getPythonActionCmd(self, task, cmdIndent, variables = {}):
  2076. opts = task.get_options()
  2077. ret = ''
  2078. flags = ''
  2079. params = list()
  2080. for f in opts['flags']:
  2081. if f.get('value', False):
  2082. name = f.get('name', '')
  2083. if len(name) > 1:
  2084. params.append('%s = True' % name)
  2085. else:
  2086. flags += name
  2087. for p in opts['params']:
  2088. name = p.get('name', None)
  2089. value = p.get('value', None)
  2090. if name and value:
  2091. ptype = p.get('type', 'string')
  2092. foundVar = False
  2093. for var in sorted(variables, key=len, reverse=True):
  2094. data = variables[var]
  2095. if '%' + var in value:
  2096. value = self._substituteVariable(value, var, data)
  2097. foundVar = True
  2098. if foundVar or ptype != 'string':
  2099. params.append("%s = %s" % (name, value))
  2100. else:
  2101. params.append('%s = "%s"' % (name, value))
  2102. ret += '"%s"' % task.get_name()
  2103. if flags:
  2104. ret += ",\n%sflags = '%s'" % (' ' * cmdIndent, flags)
  2105. if len(params) > 0:
  2106. ret += ",\n"
  2107. for opt in params[:-1]:
  2108. ret += "%s%s,\n" % (' ' * cmdIndent, opt)
  2109. ret += "%s%s)" % (' ' * cmdIndent, params[-1])
  2110. else:
  2111. ret += ")"
  2112. return ret
  2113. def _writePythonComment(self, item):
  2114. """Write model comment to Python file"""
  2115. for line in item.GetLabel().splitlines():
  2116. self.fd.write('#' + line + '\n')
  2117. def _substituteVariable(self, string, variable, data):
  2118. """Substitute variable in the string
  2119. :param string: string to be modified
  2120. :param variable: variable to be substituted
  2121. :param data: data related to the variable
  2122. :return: modified string
  2123. """
  2124. result = ''
  2125. ss = re.split("\w*(%"+variable+")w*", string)
  2126. if not ss[0] and not ss[-1]:
  2127. if data:
  2128. return "options['%s']" % variable
  2129. else:
  2130. return variable
  2131. for s in ss:
  2132. if not s or s == '"':
  2133. continue
  2134. if s == '%' + variable:
  2135. if data:
  2136. result += "+options['%s']+" % variable
  2137. else:
  2138. result += '+%s+' % variable
  2139. else:
  2140. result += '"' + s
  2141. if not s.endswith(']'): # options
  2142. result += '"'
  2143. return result.strip('+')
  2144. class ModelParamDialog(wx.Dialog):
  2145. def __init__(self, parent, model, params, id = wx.ID_ANY, title = _("Model parameters"),
  2146. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
  2147. """Model parameters dialog
  2148. """
  2149. self.parent = parent
  2150. self._model = model
  2151. self.params = params
  2152. self.tasks = list() # list of tasks/pages
  2153. wx.Dialog.__init__(self, parent = parent, id = id, title = title, style = style, **kwargs)
  2154. self.notebook = GNotebook(parent = self,
  2155. style = globalvar.FNPageDStyle)
  2156. panel = self._createPages()
  2157. wx.CallAfter(self.notebook.SetSelection, 0)
  2158. # intermediate data?
  2159. self.interData = wx.CheckBox(parent = self, label = _("Delete intermediate data when finish"))
  2160. self.interData.SetValue(True)
  2161. rast, vect, rast3d, msg = self._model.GetIntermediateData()
  2162. if not rast and not vect and not rast3d:
  2163. self.interData.Hide()
  2164. self.btnCancel = wx.Button(parent = self, id = wx.ID_CANCEL)
  2165. self.btnRun = wx.Button(parent = self, id = wx.ID_OK,
  2166. label = _("&Run"))
  2167. self.btnRun.SetDefault()
  2168. self._layout()
  2169. size = self.GetBestSize()
  2170. self.SetMinSize(size)
  2171. self.SetSize((size.width, size.height +
  2172. panel.constrained_size[1] -
  2173. panel.panelMinHeight))
  2174. def _layout(self):
  2175. btnSizer = wx.StdDialogButtonSizer()
  2176. btnSizer.AddButton(self.btnCancel)
  2177. btnSizer.AddButton(self.btnRun)
  2178. btnSizer.Realize()
  2179. mainSizer = wx.BoxSizer(wx.VERTICAL)
  2180. mainSizer.Add(item = self.notebook, proportion = 1,
  2181. flag = wx.EXPAND)
  2182. if self.interData.IsShown():
  2183. mainSizer.Add(item = self.interData, proportion = 0,
  2184. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
  2185. mainSizer.Add(item = wx.StaticLine(parent = self, id = wx.ID_ANY,
  2186. style = wx.LI_HORIZONTAL),
  2187. proportion = 0,
  2188. flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 5)
  2189. mainSizer.Add(item = btnSizer, proportion = 0,
  2190. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
  2191. self.SetSizer(mainSizer)
  2192. mainSizer.Fit(self)
  2193. def _createPages(self):
  2194. """Create for each parameterized module its own page"""
  2195. nameOrdered = [''] * len(self.params.keys())
  2196. for name, params in self.params.iteritems():
  2197. nameOrdered[params['idx']] = name
  2198. for name in nameOrdered:
  2199. params = self.params[name]
  2200. panel = self._createPage(name, params)
  2201. if name == 'variables':
  2202. name = _('Variables')
  2203. self.notebook.AddPage(page = panel, text = name)
  2204. return panel
  2205. def _createPage(self, name, params):
  2206. """Define notebook page"""
  2207. if name in globalvar.grassCmd:
  2208. task = gtask.grassTask(name)
  2209. else:
  2210. task = gtask.grassTask()
  2211. task.flags = params['flags']
  2212. task.params = params['params']
  2213. panel = CmdPanel(parent = self, id = wx.ID_ANY, task = task,
  2214. giface = GraphicalModelerGrassInterface(self._model))
  2215. self.tasks.append(task)
  2216. return panel
  2217. def GetErrors(self):
  2218. """Check for errors, get list of messages"""
  2219. errList = list()
  2220. for task in self.tasks:
  2221. errList += task.get_cmd_error()
  2222. return errList
  2223. def DeleteIntermediateData(self):
  2224. """Check if to detele intermediate data"""
  2225. if self.interData.IsShown() and self.interData.IsChecked():
  2226. return True
  2227. return False