model.py 90 KB

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