model.py 91 KB

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