model.py 91 KB

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