model.py 90 KB

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