model.py 88 KB

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