model.py 89 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616
  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. self.isParameterized = False
  978. for f in options['flags']:
  979. if f.get('parameterized', False):
  980. self.IsParameterized = True
  981. break
  982. for p in options['params']:
  983. if self.isValid and p.get('required', False) and \
  984. p.get('value', '') == '' and \
  985. p.get('default', '') == '':
  986. self.isValid = False
  987. if not self.isParameterized and p.get('parameterized', False):
  988. self.isParameterized = True
  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 FindData(self, name):
  999. """Find data item by name"""
  1000. for rel in self.GetRelations():
  1001. data = rel.GetData()
  1002. if name == rel.GetLabel() and name in data.GetLabel():
  1003. return data
  1004. return None
  1005. def Update(self, running = False):
  1006. """Update action"""
  1007. if running:
  1008. self._setBrush(running = True)
  1009. else:
  1010. self._setBrush()
  1011. self._setPen()
  1012. def OnDraw(self, dc):
  1013. """Draw action in canvas"""
  1014. self._setBrush()
  1015. self._setPen()
  1016. ogl.RectangleShape.Recentre(self, dc) # re-center text
  1017. ogl.RectangleShape.OnDraw(self, dc)
  1018. class ModelData(ModelObject, ogl.EllipseShape):
  1019. def __init__(self, parent, x, y, value = '', prompt = '', width = None, height = None):
  1020. """Data item class
  1021. :param parent: window parent
  1022. :param x, y: position of the shape
  1023. :param fname, tname: list of parameter names from / to
  1024. :param value: value
  1025. :param prompt: type of GIS element
  1026. :param width, height: dimension of the shape
  1027. """
  1028. ModelObject.__init__(self)
  1029. self.parent = parent
  1030. self.value = value
  1031. self.prompt = prompt
  1032. self.intermediate = False
  1033. self.propWin = None
  1034. if not width:
  1035. width = UserSettings.Get(group='modeler', key='data', subkey=('size', 'width'))
  1036. if not height:
  1037. height = UserSettings.Get(group='modeler', key='data', subkey=('size', 'height'))
  1038. if self.parent.GetCanvas():
  1039. ogl.EllipseShape.__init__(self, width, height)
  1040. self.SetCanvas(self.parent)
  1041. self.SetX(x)
  1042. self.SetY(y)
  1043. self._setPen()
  1044. self._setBrush()
  1045. self.SetLabel()
  1046. def IsIntermediate(self):
  1047. """Checks if data item is intermediate"""
  1048. return self.intermediate
  1049. def SetIntermediate(self, im):
  1050. """Set intermediate flag"""
  1051. self.intermediate = im
  1052. def OnDraw(self, dc):
  1053. self._setPen()
  1054. ogl.EllipseShape.OnDraw(self, dc)
  1055. def GetLog(self, string = True):
  1056. """Get logging info"""
  1057. name = list()
  1058. for rel in self.GetRelations():
  1059. name.append(rel.GetLabel())
  1060. if name:
  1061. return '/'.join(name) + '=' + self.value + ' (' + self.prompt + ')'
  1062. else:
  1063. return self.value + ' (' + self.prompt + ')'
  1064. def GetLabel(self):
  1065. """Get list of names"""
  1066. name = list()
  1067. for rel in self.GetRelations():
  1068. name.append(rel.GetLabel())
  1069. return name
  1070. def GetPrompt(self):
  1071. """Get prompt"""
  1072. return self.prompt
  1073. def SetPrompt(self, prompt):
  1074. """Set prompt
  1075. :param prompt:
  1076. """
  1077. self.prompt = prompt
  1078. def GetValue(self):
  1079. """Get value"""
  1080. return self.value
  1081. def SetValue(self, value):
  1082. """Set value
  1083. :param value:
  1084. """
  1085. self.value = value
  1086. self.SetLabel()
  1087. for direction in ('from', 'to'):
  1088. for rel in self.GetRelations(direction):
  1089. if direction == 'from':
  1090. action = rel.GetTo()
  1091. else:
  1092. action = rel.GetFrom()
  1093. task = GUI(show = None).ParseCommand(cmd = action.GetLog(string = False))
  1094. task.set_param(rel.GetLabel(), self.value)
  1095. action.SetParams(params = task.get_options())
  1096. def GetPropDialog(self):
  1097. """Get properties dialog"""
  1098. return self.propWin
  1099. def SetPropDialog(self, win):
  1100. """Get properties dialog"""
  1101. self.propWin = win
  1102. def _setBrush(self):
  1103. """Set brush"""
  1104. if self.prompt == 'raster':
  1105. color = UserSettings.Get(group = 'modeler', key = 'data',
  1106. subkey = ('color', 'raster'))
  1107. elif self.prompt == 'raster3d':
  1108. color = UserSettings.Get(group = 'modeler', key = 'data',
  1109. subkey = ('color', 'raster3d'))
  1110. elif self.prompt == 'vector':
  1111. color = UserSettings.Get(group = 'modeler', key = 'data',
  1112. subkey = ('color', 'vector'))
  1113. else:
  1114. color = UserSettings.Get(group = 'modeler', key = 'action',
  1115. subkey = ('color', 'invalid'))
  1116. wxColor = wx.Colour(color[0], color[1], color[2])
  1117. self.SetBrush(wx.Brush(wxColor))
  1118. def _setPen(self):
  1119. """Set pen"""
  1120. isParameterized = False
  1121. for rel in self.GetRelations('from'):
  1122. if rel.GetTo().IsParameterized():
  1123. isParameterized = True
  1124. break
  1125. if not isParameterized:
  1126. for rel in self.GetRelations('to'):
  1127. if rel.GetFrom().IsParameterized():
  1128. isParameterized = True
  1129. break
  1130. if isParameterized:
  1131. width = int(UserSettings.Get(group = 'modeler', key = 'action',
  1132. subkey = ('width', 'parameterized')))
  1133. else:
  1134. width = int(UserSettings.Get(group = 'modeler', key = 'action',
  1135. subkey = ('width', 'default')))
  1136. if self.intermediate:
  1137. style = wx.DOT
  1138. else:
  1139. style = wx.SOLID
  1140. pen = wx.Pen(wx.BLACK, width, style)
  1141. self.SetPen(pen)
  1142. def SetLabel(self):
  1143. """Update text"""
  1144. self.ClearText()
  1145. name = []
  1146. for rel in self.GetRelations():
  1147. name.append(rel.GetLabel())
  1148. self.AddText('/'.join(name))
  1149. if self.value:
  1150. self.AddText(self.value)
  1151. else:
  1152. self.AddText(_('<not defined>'))
  1153. def Update(self):
  1154. """Update action"""
  1155. self._setBrush()
  1156. self._setPen()
  1157. self.SetLabel()
  1158. class ModelRelation(ogl.LineShape):
  1159. """Data - action relation"""
  1160. def __init__(self, parent, fromShape, toShape, param = ''):
  1161. self.fromShape = fromShape
  1162. self.toShape = toShape
  1163. self.param = param
  1164. self.parent = parent
  1165. self._points = None
  1166. if self.parent.GetCanvas():
  1167. ogl.LineShape.__init__(self)
  1168. def __del__(self):
  1169. if self in self.fromShape.rels:
  1170. self.fromShape.rels.remove(self)
  1171. if self in self.toShape.rels:
  1172. self.toShape.rels.remove(self)
  1173. def GetFrom(self):
  1174. """Get id of 'from' shape"""
  1175. return self.fromShape
  1176. def GetTo(self):
  1177. """Get id of 'to' shape"""
  1178. return self.toShape
  1179. def GetData(self):
  1180. """Get related ModelData instance
  1181. :return: ModelData instance
  1182. :return: None if not found
  1183. """
  1184. if isinstance(self.fromShape, ModelData):
  1185. return self.fromShape
  1186. elif isinstance(self.toShape, ModelData):
  1187. return self.toShape
  1188. return None
  1189. def GetLabel(self):
  1190. """Get parameter name"""
  1191. return self.param
  1192. def ResetShapes(self):
  1193. """Reset related objects"""
  1194. self.fromShape.ResetControlPoints()
  1195. self.toShape.ResetControlPoints()
  1196. self.ResetControlPoints()
  1197. def SetControlPoints(self, points):
  1198. """Set control points"""
  1199. self._points = points
  1200. def GetControlPoints(self):
  1201. """Get list of control points"""
  1202. return self._points
  1203. def _setPen(self):
  1204. """Set pen"""
  1205. pen = wx.Pen(wx.BLACK, 1, wx.SOLID)
  1206. self.SetPen(pen)
  1207. def OnDraw(self, dc):
  1208. """Draw relation"""
  1209. self._setPen()
  1210. ogl.LineShape.OnDraw(self, dc)
  1211. def SetName(self, param):
  1212. self.param = param
  1213. class ModelItem(ModelObject):
  1214. def __init__(self, parent, x, y, id = -1, width = None, height = None, label = '', items = []):
  1215. """Abstract class for loops and conditions"""
  1216. ModelObject.__init__(self, id, label)
  1217. self.parent = parent
  1218. def _setPen(self):
  1219. """Set pen"""
  1220. if self.isEnabled:
  1221. style = wx.SOLID
  1222. else:
  1223. style = wx.DOT
  1224. pen = wx.Pen(wx.BLACK, 1, style)
  1225. self.SetPen(pen)
  1226. def SetId(self, id):
  1227. """Set loop id"""
  1228. self.id = id
  1229. def SetLabel(self, label=''):
  1230. """Set loop text (condition)"""
  1231. if label:
  1232. self.label = label
  1233. self.ClearText()
  1234. self.AddText('(' + str(self.id) + ') ' + self.label)
  1235. def GetLog(self):
  1236. """Get log info"""
  1237. if self.label:
  1238. return _("Condition: ") + self.label
  1239. else:
  1240. return _("Condition: not defined")
  1241. def AddRelation(self, rel):
  1242. """Record relation"""
  1243. self.rels.append(rel)
  1244. def Clear(self):
  1245. """Clear object, remove rels"""
  1246. self.rels = list()
  1247. class ModelLoop(ModelItem, ogl.RectangleShape):
  1248. def __init__(self, parent, x, y, id=-1, idx=-1, width = None, height = None, label = '', items = []):
  1249. """Defines a loop"""
  1250. ModelItem.__init__(self, parent, x, y, id, width, height, label, items)
  1251. self.itemIds = list() # unordered
  1252. if not width:
  1253. width = UserSettings.Get(group='modeler', key='loop', subkey=('size', 'width'))
  1254. if not height:
  1255. height = UserSettings.Get(group='modeler', key='loop', subkey=('size', 'height'))
  1256. if self.parent.GetCanvas():
  1257. ogl.RectangleShape.__init__(self, width, height)
  1258. self.SetCanvas(self.parent)
  1259. self.SetX(x)
  1260. self.SetY(y)
  1261. self._setPen()
  1262. self._setBrush()
  1263. self.SetCornerRadius(100)
  1264. self.SetLabel(label)
  1265. def _setBrush(self):
  1266. """Set brush"""
  1267. if not self.isEnabled:
  1268. color = UserSettings.Get(group='modeler', key='disabled',
  1269. subkey='color')
  1270. else:
  1271. color = UserSettings.Get(group='modeler', key='loop',
  1272. subkey=('color', 'valid'))
  1273. wxColor = wx.Colour(color[0], color[1], color[2])
  1274. self.SetBrush(wx.Brush(wxColor))
  1275. def Enable(self, enabled = True):
  1276. """Enable/disable action"""
  1277. for idx in self.itemIds:
  1278. item = self.parent.FindAction(idx)
  1279. if item:
  1280. item.Enable(enabled)
  1281. ModelObject.Enable(self, enabled)
  1282. self.Update()
  1283. def Update(self):
  1284. self._setPen()
  1285. self._setBrush()
  1286. def GetItems(self, items):
  1287. """Get sorted items by id"""
  1288. result = list()
  1289. for item in items:
  1290. if item.GetId() in self.itemIds:
  1291. result.append(item)
  1292. return result
  1293. def SetItems(self, items):
  1294. """Set items (id)"""
  1295. self.itemIds = items
  1296. def UpdateItem(self, oldId, newId):
  1297. """Update item in the list"""
  1298. idx = self.itemIds.index(oldId)
  1299. if idx != -1:
  1300. self.itemIds[idx] = newId
  1301. def OnDraw(self, dc):
  1302. """Draw loop in canvas"""
  1303. self._setBrush()
  1304. ogl.RectangleShape.Recentre(self, dc) # re-center text
  1305. ogl.RectangleShape.OnDraw(self, dc)
  1306. class ModelCondition(ModelItem, ogl.PolygonShape):
  1307. def __init__(self, parent, x, y, id = -1, width = None, height = None, label = '',
  1308. items = { 'if' : [], 'else' : [] }):
  1309. """Defines a if-else condition"""
  1310. ModelItem.__init__(self, parent, x, y, id, width, height, label, items)
  1311. self.itemIds = {'if' : [], 'else': []}
  1312. if not width:
  1313. self.width = UserSettings.Get(group='modeler', key='if-else', subkey=('size', 'width'))
  1314. else:
  1315. self.width = width
  1316. if not height:
  1317. self.height = UserSettings.Get(group='modeler', key='if-else', subkey=('size', 'height'))
  1318. else:
  1319. self.height = height
  1320. if self.parent.GetCanvas():
  1321. ogl.PolygonShape.__init__(self)
  1322. points = [(0, - self.height / 2),
  1323. (self.width / 2, 0),
  1324. (0, self.height / 2),
  1325. (- self.width / 2, 0)]
  1326. self.Create(points)
  1327. self.SetCanvas(self.parent)
  1328. self.SetX(x)
  1329. self.SetY(y)
  1330. self.SetPen(wx.BLACK_PEN)
  1331. if label:
  1332. self.AddText('(' + str(self.id) + ') ' + label)
  1333. else:
  1334. self.AddText('(' + str(self.id) + ')')
  1335. def GetLabel(self):
  1336. """Get name"""
  1337. return _("if-else")
  1338. def GetWidth(self):
  1339. """Get object width"""
  1340. return self.width
  1341. def GetHeight(self):
  1342. """Get object height"""
  1343. return self.height
  1344. def GetItems(self, items):
  1345. """Get sorted items by id"""
  1346. result = {'if' : [], 'else': []}
  1347. for item in items:
  1348. if item.GetId() in self.itemIds['if']:
  1349. result['if'].append(item)
  1350. elif item.GetId() in self.itemIds['else']:
  1351. result['else'].append(item)
  1352. return result
  1353. def SetItems(self, items, branch = 'if'):
  1354. """Set items (id)
  1355. :param items: list of items
  1356. :param branch: 'if' / 'else'
  1357. """
  1358. if branch in ['if', 'else']:
  1359. self.itemIds[branch] = items
  1360. class ModelComment(ModelObject, ogl.RectangleShape):
  1361. def __init__(self, parent, x, y, id = -1, width = None, height = None, label = ''):
  1362. """Defines a model comment"""
  1363. ModelObject.__init__(self, id, label)
  1364. if not width:
  1365. width = UserSettings.Get(group='modeler', key='comment', subkey=('size', 'width'))
  1366. if not height:
  1367. height = UserSettings.Get(group='modeler', key='comment', subkey=('size', 'height'))
  1368. if parent.GetCanvas():
  1369. ogl.RectangleShape.__init__(self, width, height)
  1370. self.SetCanvas(parent)
  1371. self.SetX(x)
  1372. self.SetY(y)
  1373. font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
  1374. font.SetStyle(wx.ITALIC)
  1375. self.SetFont(font)
  1376. self._setPen()
  1377. self._setBrush()
  1378. self.SetLabel(label)
  1379. def _setBrush(self, running = False):
  1380. """Set brush"""
  1381. color = UserSettings.Get(group='modeler', key='comment',
  1382. subkey='color')
  1383. wxColor = wx.Colour(color[0], color[1], color[2])
  1384. self.SetBrush(wx.Brush(wxColor))
  1385. def _setPen(self):
  1386. """Set pen"""
  1387. pen = wx.Pen(wx.BLACK, 1, wx.DOT)
  1388. self.SetPen(pen)
  1389. def SetLabel(self, label=None):
  1390. """Set label
  1391. :param label: if None use command string instead
  1392. """
  1393. if label:
  1394. self.label = label
  1395. elif self.label:
  1396. label = self.label
  1397. else:
  1398. label = ''
  1399. idx = self.GetId()
  1400. self.ClearText()
  1401. self.AddText('(%d) %s' % (idx, label))
  1402. def GetComment(self):
  1403. return self.GetLabel()
  1404. def SetComment(self, comment):
  1405. self.SetLabel(comment)
  1406. self.GetCanvas().Refresh()
  1407. class ProcessModelFile:
  1408. """Process GRASS model file (gxm)"""
  1409. def __init__(self, tree):
  1410. """A ElementTree handler for the GXM XML file, as defined in
  1411. grass-gxm.dtd.
  1412. """
  1413. self.tree = tree
  1414. self.root = self.tree.getroot()
  1415. # list of actions, data
  1416. self.properties = dict()
  1417. self.variables = dict()
  1418. self.actions = list()
  1419. self.data = list()
  1420. self.loops = list()
  1421. self.conditions = list()
  1422. self.comments = list()
  1423. self._processWindow()
  1424. self._processProperties()
  1425. self._processVariables()
  1426. self._processItems()
  1427. self._processData()
  1428. def _filterValue(self, value):
  1429. """Filter value
  1430. :param value:
  1431. """
  1432. value = value.replace('&lt;', '<')
  1433. value = value.replace('&gt;', '>')
  1434. return value
  1435. def _getNodeText(self, node, tag, default = ''):
  1436. """Get node text"""
  1437. p = node.find(tag)
  1438. if p is not None:
  1439. if p.text:
  1440. return utils.normalize_whitespace(p.text)
  1441. else:
  1442. return ''
  1443. return default
  1444. def _processWindow(self):
  1445. """Process window properties"""
  1446. node = self.root.find('window')
  1447. if node is None:
  1448. self.pos = self.size = None
  1449. return
  1450. self.pos, self.size = self._getDim(node)
  1451. def _processProperties(self):
  1452. """Process model properties"""
  1453. node = self.root.find('properties')
  1454. if node is None:
  1455. return
  1456. for key in ('name', 'description', 'author'):
  1457. self._processProperty(node, key)
  1458. for f in node.findall('flag'):
  1459. name = f.get('name', '')
  1460. if name == 'overwrite':
  1461. self.properties['overwrite'] = True
  1462. def _processProperty(self, pnode, name):
  1463. """Process given property"""
  1464. node = pnode.find(name)
  1465. if node is not None:
  1466. self.properties[name] = node.text
  1467. else:
  1468. self.properties[name] = ''
  1469. def _processVariables(self):
  1470. """Process model variables"""
  1471. vnode = self.root.find('variables')
  1472. if vnode is None:
  1473. return
  1474. for node in vnode.findall('variable'):
  1475. name = node.get('name', '')
  1476. if not name:
  1477. continue # should not happen
  1478. self.variables[name] = { 'type' : node.get('type', 'string') }
  1479. for key in ('description', 'value'):
  1480. self._processVariable(node, name, key)
  1481. def _processVariable(self, pnode, name, key):
  1482. """Process given variable"""
  1483. node = pnode.find(key)
  1484. if node is not None:
  1485. if node.text:
  1486. self.variables[name][key] = node.text
  1487. def _processItems(self):
  1488. """Process model items (actions, loops, conditions)"""
  1489. self._processActions()
  1490. self._processLoops()
  1491. self._processConditions()
  1492. self._processComments()
  1493. def _processActions(self):
  1494. """Process model file"""
  1495. for action in self.root.findall('action'):
  1496. pos, size = self._getDim(action)
  1497. disabled = False
  1498. task = action.find('task')
  1499. if task is not None:
  1500. if task.find('disabled') is not None:
  1501. disabled = True
  1502. task = self._processTask(task)
  1503. else:
  1504. task = None
  1505. aId = int(action.get('id', -1))
  1506. label = action.get('name')
  1507. comment = action.find('comment')
  1508. if comment is not None:
  1509. commentString = comment.text
  1510. else:
  1511. commentString = ''
  1512. self.actions.append({ 'pos' : pos,
  1513. 'size' : size,
  1514. 'task' : task,
  1515. 'id' : aId,
  1516. 'disabled' : disabled,
  1517. 'label' : label,
  1518. 'comment' : commentString})
  1519. def _getDim(self, node):
  1520. """Get position and size of shape"""
  1521. pos = size = None
  1522. posAttr = node.get('pos', None)
  1523. if posAttr:
  1524. posVal = map(int, posAttr.split(','))
  1525. try:
  1526. pos = (posVal[0], posVal[1])
  1527. except:
  1528. pos = None
  1529. sizeAttr = node.get('size', None)
  1530. if sizeAttr:
  1531. sizeVal = map(int, sizeAttr.split(','))
  1532. try:
  1533. size = (sizeVal[0], sizeVal[1])
  1534. except:
  1535. size = None
  1536. return pos, size
  1537. def _processData(self):
  1538. """Process model file"""
  1539. for data in self.root.findall('data'):
  1540. pos, size = self._getDim(data)
  1541. param = data.find('data-parameter')
  1542. prompt = value = None
  1543. if param is not None:
  1544. prompt = param.get('prompt', None)
  1545. value = self._filterValue(self._getNodeText(param, 'value'))
  1546. if data.find('intermediate') is None:
  1547. intermediate = False
  1548. else:
  1549. intermediate = True
  1550. rels = list()
  1551. for rel in data.findall('relation'):
  1552. defrel = { 'id' : int(rel.get('id', -1)),
  1553. 'dir' : rel.get('dir', 'to'),
  1554. 'name' : rel.get('name', '') }
  1555. points = list()
  1556. for point in rel.findall('point'):
  1557. x = self._filterValue(self._getNodeText(point, 'x'))
  1558. y = self._filterValue(self._getNodeText(point, 'y'))
  1559. points.append((float(x), float(y)))
  1560. defrel['points'] = points
  1561. rels.append(defrel)
  1562. self.data.append({ 'pos' : pos,
  1563. 'size': size,
  1564. 'prompt' : prompt,
  1565. 'value' : value,
  1566. 'intermediate' : intermediate,
  1567. 'rels' : rels })
  1568. def _processTask(self, node):
  1569. """Process task
  1570. :return: grassTask instance
  1571. :return: None on error
  1572. """
  1573. cmd = list()
  1574. parameterized = list()
  1575. name = node.get('name', None)
  1576. if not name:
  1577. return None
  1578. cmd.append(name)
  1579. # flags
  1580. for f in node.findall('flag'):
  1581. flag = f.get('name', '')
  1582. if f.get('parameterized', '0') == '1':
  1583. parameterized.append(('flag', flag))
  1584. if f.get('value', '1') == '0':
  1585. continue
  1586. if len(flag) > 1:
  1587. cmd.append('--' + flag)
  1588. else:
  1589. cmd.append('-' + flag)
  1590. # parameters
  1591. for p in node.findall('parameter'):
  1592. name = p.get('name', '')
  1593. if p.find('parameterized') is not None:
  1594. parameterized.append(('param', name))
  1595. cmd.append('%s=%s' % (name,
  1596. self._filterValue(self._getNodeText(p, 'value'))))
  1597. task, err = GUI(show = None, checkError = True).ParseCommand(cmd = cmd)
  1598. if err:
  1599. GWarning(os.linesep.join(err))
  1600. for opt, name in parameterized:
  1601. if opt == 'flag':
  1602. task.set_flag(name, True, element = 'parameterized')
  1603. else:
  1604. task.set_param(name, True, element = 'parameterized')
  1605. return task
  1606. def _processLoops(self):
  1607. """Process model loops"""
  1608. for node in self.root.findall('loop'):
  1609. pos, size = self._getDim(node)
  1610. text = self._filterValue(self._getNodeText(node, 'condition')).strip()
  1611. aid = list()
  1612. for anode in node.findall('item'):
  1613. try:
  1614. aid.append(int(anode.text))
  1615. except ValueError:
  1616. pass
  1617. self.loops.append({ 'pos' : pos,
  1618. 'size' : size,
  1619. 'text' : text,
  1620. 'id' : int(node.get('id', -1)),
  1621. 'items' : aid })
  1622. def _processConditions(self):
  1623. """Process model conditions"""
  1624. for node in self.root.findall('if-else'):
  1625. pos, size = self._getDim(node)
  1626. text = self._filterValue(self._getNodeText(node, 'condition')).strip()
  1627. aid = { 'if' : list(),
  1628. 'else' : list() }
  1629. for b in aid.keys():
  1630. bnode = node.find(b)
  1631. if bnode is None:
  1632. continue
  1633. for anode in bnode.findall('item'):
  1634. try:
  1635. aid[b].append(int(anode.text))
  1636. except ValueError:
  1637. pass
  1638. self.conditions.append({ 'pos' : pos,
  1639. 'size' : size,
  1640. 'text' : text,
  1641. 'id' : int(node.get('id', -1)),
  1642. 'items' : aid })
  1643. def _processComments(self):
  1644. """Process model comments"""
  1645. for node in self.root.findall('comment'):
  1646. pos, size = self._getDim(node)
  1647. text = self._filterValue(node.text)
  1648. self.comments.append({ 'pos' : pos,
  1649. 'size' : size,
  1650. 'text' : text,
  1651. 'id' : int(node.get('id', -1)),
  1652. 'text' : text })
  1653. class WriteModelFile:
  1654. """Generic class for writing model file"""
  1655. def __init__(self, fd, model):
  1656. self.fd = fd
  1657. self.model = model
  1658. self.properties = model.GetProperties()
  1659. self.variables = model.GetVariables()
  1660. self.items = model.GetItems()
  1661. self.indent = 0
  1662. self._header()
  1663. self._window()
  1664. self._properties()
  1665. self._variables()
  1666. self._items()
  1667. dataList = list()
  1668. for action in model.GetItems(objType = ModelAction):
  1669. for rel in action.GetRelations():
  1670. dataItem = rel.GetData()
  1671. if dataItem not in dataList:
  1672. dataList.append(dataItem)
  1673. self._data(dataList)
  1674. self._footer()
  1675. def _filterValue(self, value):
  1676. """Escapes value to be stored in XML.
  1677. :param value: string to be escaped as XML
  1678. :return: a XML-valid string
  1679. """
  1680. value = saxutils.escape(value)
  1681. return value
  1682. def _header(self):
  1683. """Write header"""
  1684. self.fd.write('<?xml version="1.0" encoding="%s"?>\n' % GetDefaultEncoding(forceUTF8 = True))
  1685. self.fd.write('<!DOCTYPE gxm SYSTEM "grass-gxm.dtd">\n')
  1686. self.fd.write('%s<gxm>\n' % (' ' * self.indent))
  1687. self.indent += 4
  1688. def _footer(self):
  1689. """Write footer"""
  1690. self.indent -= 4
  1691. self.fd.write('%s</gxm>\n' % (' ' * self.indent))
  1692. def _window(self):
  1693. """Write window properties"""
  1694. canvas = self.model.GetCanvas()
  1695. if canvas is None:
  1696. return
  1697. win = canvas.parent
  1698. pos = win.GetPosition()
  1699. size = win.GetSize()
  1700. self.fd.write('%s<window pos="%d,%d" size="%d,%d" />\n' % \
  1701. (' ' * self.indent, pos[0], pos[1], size[0], size[1]))
  1702. def _properties(self):
  1703. """Write model properties"""
  1704. self.fd.write('%s<properties>\n' % (' ' * self.indent))
  1705. self.indent += 4
  1706. if self.properties['name']:
  1707. self.fd.write('%s<name>%s</name>\n' % (' ' * self.indent, EncodeString(self.properties['name'])))
  1708. if self.properties['description']:
  1709. self.fd.write('%s<description>%s</description>\n' % (' ' * self.indent,
  1710. EncodeString(self.properties['description'])))
  1711. if self.properties['author']:
  1712. self.fd.write('%s<author>%s</author>\n' % (' ' * self.indent,
  1713. EncodeString(self.properties['author'])))
  1714. if 'overwrite' in self.properties and \
  1715. self.properties['overwrite']:
  1716. self.fd.write('%s<flag name="overwrite" />\n' % (' ' * self.indent))
  1717. self.indent -= 4
  1718. self.fd.write('%s</properties>\n' % (' ' * self.indent))
  1719. def _variables(self):
  1720. """Write model variables"""
  1721. if not self.variables:
  1722. return
  1723. self.fd.write('%s<variables>\n' % (' ' * self.indent))
  1724. self.indent += 4
  1725. for name, values in self.variables.iteritems():
  1726. self.fd.write('%s<variable name="%s" type="%s">\n' % \
  1727. (' ' * self.indent, EncodeString(name), values['type']))
  1728. self.indent += 4
  1729. if 'value' in values:
  1730. self.fd.write('%s<value>%s</value>\n' % \
  1731. (' ' * self.indent, EncodeString(values['value'])))
  1732. if 'description' in values:
  1733. self.fd.write('%s<description>%s</description>\n' % \
  1734. (' ' * self.indent, EncodeString(values['description'])))
  1735. self.indent -= 4
  1736. self.fd.write('%s</variable>\n' % (' ' * self.indent))
  1737. self.indent -= 4
  1738. self.fd.write('%s</variables>\n' % (' ' * self.indent))
  1739. def _items(self):
  1740. """Write actions/loops/conditions"""
  1741. for item in self.items:
  1742. if isinstance(item, ModelAction):
  1743. self._action(item)
  1744. elif isinstance(item, ModelLoop):
  1745. self._loop(item)
  1746. elif isinstance(item, ModelCondition):
  1747. self._condition(item)
  1748. elif isinstance(item, ModelComment):
  1749. self._comment(item)
  1750. def _action(self, action):
  1751. """Write actions"""
  1752. self.fd.write('%s<action id="%d" name="%s" pos="%d,%d" size="%d,%d">\n' % \
  1753. (' ' * self.indent, action.GetId(), EncodeString(action.GetLabel()), action.GetX(), action.GetY(),
  1754. action.GetWidth(), action.GetHeight()))
  1755. self.indent += 4
  1756. comment = action.GetComment()
  1757. if comment:
  1758. self.fd.write('%s<comment>%s</comment>\n' % (' ' * self.indent, EncodeString(comment)))
  1759. self.fd.write('%s<task name="%s">\n' % (' ' * self.indent, action.GetLog(string = False)[0]))
  1760. self.indent += 4
  1761. if not action.IsEnabled():
  1762. self.fd.write('%s<disabled />\n' % (' ' * self.indent))
  1763. for key, val in action.GetParams().iteritems():
  1764. if key == 'flags':
  1765. for f in val:
  1766. if f.get('value', False) or f.get('parameterized', False):
  1767. if f.get('parameterized', False):
  1768. if f.get('value', False) == False:
  1769. self.fd.write('%s<flag name="%s" value="0" parameterized="1" />\n' %
  1770. (' ' * self.indent, f.get('name', '')))
  1771. else:
  1772. self.fd.write('%s<flag name="%s" parameterized="1" />\n' %
  1773. (' ' * self.indent, f.get('name', '')))
  1774. else:
  1775. self.fd.write('%s<flag name="%s" />\n' %
  1776. (' ' * self.indent, f.get('name', '')))
  1777. else: # parameter
  1778. for p in val:
  1779. if not p.get('value', '') and not p.get('parameterized', False):
  1780. continue
  1781. self.fd.write('%s<parameter name="%s">\n' %
  1782. (' ' * self.indent, p.get('name', '')))
  1783. self.indent += 4
  1784. if p.get('parameterized', False):
  1785. self.fd.write('%s<parameterized />\n' % (' ' * self.indent))
  1786. self.fd.write('%s<value>%s</value>\n' %
  1787. (' ' * self.indent, self._filterValue(p.get('value', ''))))
  1788. self.indent -= 4
  1789. self.fd.write('%s</parameter>\n' % (' ' * self.indent))
  1790. self.indent -= 4
  1791. self.fd.write('%s</task>\n' % (' ' * self.indent))
  1792. self.indent -= 4
  1793. self.fd.write('%s</action>\n' % (' ' * self.indent))
  1794. def _data(self, dataList):
  1795. """Write data"""
  1796. for data in dataList:
  1797. self.fd.write('%s<data pos="%d,%d" size="%d,%d">\n' % \
  1798. (' ' * self.indent, data.GetX(), data.GetY(),
  1799. data.GetWidth(), data.GetHeight()))
  1800. self.indent += 4
  1801. self.fd.write('%s<data-parameter prompt="%s">\n' % \
  1802. (' ' * self.indent, data.GetPrompt()))
  1803. self.indent += 4
  1804. self.fd.write('%s<value>%s</value>\n' %
  1805. (' ' * self.indent, self._filterValue(data.GetValue())))
  1806. self.indent -= 4
  1807. self.fd.write('%s</data-parameter>\n' % (' ' * self.indent))
  1808. if data.IsIntermediate():
  1809. self.fd.write('%s<intermediate />\n' % (' ' * self.indent))
  1810. # relations
  1811. for ft in ('from', 'to'):
  1812. for rel in data.GetRelations(ft):
  1813. if ft == 'from':
  1814. aid = rel.GetTo().GetId()
  1815. else:
  1816. aid = rel.GetFrom().GetId()
  1817. self.fd.write('%s<relation dir="%s" id="%d" name="%s">\n' % \
  1818. (' ' * self.indent, ft, aid, rel.GetLabel()))
  1819. self.indent += 4
  1820. for point in rel.GetLineControlPoints()[1:-1]:
  1821. self.fd.write('%s<point>\n' % (' ' * self.indent))
  1822. self.indent += 4
  1823. x, y = point.Get()
  1824. self.fd.write('%s<x>%d</x>\n' % (' ' * self.indent, int(x)))
  1825. self.fd.write('%s<y>%d</y>\n' % (' ' * self.indent, int(y)))
  1826. self.indent -= 4
  1827. self.fd.write('%s</point>\n' % (' ' * self.indent))
  1828. self.indent -= 4
  1829. self.fd.write('%s</relation>\n' % (' ' * self.indent))
  1830. self.indent -= 4
  1831. self.fd.write('%s</data>\n' % (' ' * self.indent))
  1832. def _loop(self, loop):
  1833. """Write loops"""
  1834. self.fd.write('%s<loop id="%d" pos="%d,%d" size="%d,%d">\n' % \
  1835. (' ' * self.indent, loop.GetId(), loop.GetX(), loop.GetY(),
  1836. loop.GetWidth(), loop.GetHeight()))
  1837. self.indent += 4
  1838. cond = loop.GetLabel()
  1839. if cond:
  1840. self.fd.write('%s<condition>%s</condition>\n' %
  1841. (' ' * self.indent, self._filterValue(cond)))
  1842. for item in loop.GetItems(self.model.GetItems(objType=ModelAction)):
  1843. self.fd.write('%s<item>%d</item>\n' %
  1844. (' ' * self.indent, item.GetId()))
  1845. self.indent -= 4
  1846. self.fd.write('%s</loop>\n' % (' ' * self.indent))
  1847. def _condition(self, condition):
  1848. """Write conditions"""
  1849. bbox = condition.GetBoundingBoxMin()
  1850. self.fd.write('%s<if-else id="%d" pos="%d,%d" size="%d,%d">\n' % \
  1851. (' ' * self.indent, condition.GetId(), condition.GetX(), condition.GetY(),
  1852. bbox[0], bbox[1]))
  1853. text = condition.GetLabel()
  1854. self.indent += 4
  1855. if text:
  1856. self.fd.write('%s<condition>%s</condition>\n' %
  1857. (' ' * self.indent, self._filterValue(text)))
  1858. items = condition.GetItems()
  1859. for b in items.keys():
  1860. if len(items[b]) < 1:
  1861. continue
  1862. self.fd.write('%s<%s>\n' % (' ' * self.indent, b))
  1863. self.indent += 4
  1864. for item in items[b]:
  1865. self.fd.write('%s<item>%d</item>\n' %
  1866. (' ' * self.indent, item.GetId()))
  1867. self.indent -= 4
  1868. self.fd.write('%s</%s>\n' % (' ' * self.indent, b))
  1869. self.indent -= 4
  1870. self.fd.write('%s</if-else>\n' % (' ' * self.indent))
  1871. def _comment(self, comment):
  1872. """Write comment"""
  1873. self.fd.write('%s<comment id="%d" pos="%d,%d" size="%d,%d">%s</comment>\n' % \
  1874. (' ' * self.indent, comment.GetId(), comment.GetX(), comment.GetY(),
  1875. comment.GetWidth(), comment.GetHeight(), EncodeString(comment.GetLabel())))
  1876. class WritePythonFile:
  1877. def __init__(self, fd, model):
  1878. """Class for exporting model to Python script
  1879. :param fd: file descriptor
  1880. """
  1881. self.fd = fd
  1882. self.model = model
  1883. self.indent = 4
  1884. self._writePython()
  1885. def _getStandardizedOption(self, string):
  1886. if string == 'raster':
  1887. return 'G_OPT_R_MAP'
  1888. elif string == 'vector':
  1889. return 'G_OPT_V_MAP'
  1890. elif string == 'mapset':
  1891. return 'G_OPT_M_MAPSET'
  1892. elif string == 'file':
  1893. return 'G_OPT_F_INPUT'
  1894. elif string == 'region':
  1895. return 'G_OPT_M_REGION'
  1896. return ''
  1897. def _writePython(self):
  1898. """Write model to file"""
  1899. properties = self.model.GetProperties()
  1900. # header
  1901. self.fd.write(
  1902. r"""#!/usr/bin/env python
  1903. #
  1904. #%s
  1905. #
  1906. # MODULE: %s
  1907. #
  1908. # AUTHOR(S): %s
  1909. #
  1910. # PURPOSE: %s
  1911. #
  1912. # DATE: %s
  1913. #
  1914. #%s
  1915. """% ('#' * 77,
  1916. EncodeString(properties['name']),
  1917. EncodeString(properties['author']),
  1918. EncodeString('\n# '.join(properties['description'].splitlines())),
  1919. time.asctime(),
  1920. '#' * 77))
  1921. # UI
  1922. self.fd.write(
  1923. r"""
  1924. #%%module
  1925. #%% description: %s
  1926. #%%end
  1927. """% (EncodeString(' '.join(properties['description'].splitlines()))))
  1928. variables = self.model.GetVariables()
  1929. for key, data in variables.iteritems():
  1930. otype = self._getStandardizedOption(data['type'])
  1931. self.fd.write(
  1932. r"""
  1933. #%%option %s
  1934. #%% key: %s
  1935. #%% description: %s
  1936. #%% required: yes
  1937. """% (otype, key, data['description']))
  1938. if 'value' in data:
  1939. self.fd.write("#%% answer: %s\n" % data['value'])
  1940. self.fd.write("#% end\n")
  1941. # import modules
  1942. self.fd.write(
  1943. r"""
  1944. import sys
  1945. import os
  1946. import atexit
  1947. from grass.script import parser, run_command
  1948. """)
  1949. # cleanup()
  1950. rast, vect, rast3d, msg = self.model.GetIntermediateData()
  1951. self.fd.write(
  1952. r"""
  1953. def cleanup():
  1954. """)
  1955. if rast:
  1956. self.fd.write(
  1957. r""" run_command('g.remove', flags='f', type='raster',
  1958. name=%s)
  1959. """% ','.join(map(lambda x: "'" + x + "'", rast)))
  1960. if vect:
  1961. self.fd.write(
  1962. r""" run_command('g.remove', flags='f', type='vector',
  1963. name=%s)
  1964. """% ','.join(map(lambda x: "'" + x + "'", vect)))
  1965. if rast3d:
  1966. self.fd.write(
  1967. r""" run_command('g.remove', flags='f', type='raster_3d',
  1968. name=%s)
  1969. """% ','.join(map(lambda x: "'" + x + "'", rast3d)))
  1970. if not rast and not vect and not rast3d:
  1971. self.fd.write(' pass\n')
  1972. self.fd.write("\ndef main():\n")
  1973. for item in self.model.GetItems():
  1974. self._writePythonItem(item, variables = self.model.GetVariables())
  1975. self.fd.write("\n return 0\n")
  1976. self.fd.write(
  1977. r"""
  1978. if __name__ == "__main__":
  1979. options, flags = parser()
  1980. atexit.register(cleanup)
  1981. sys.exit(main())
  1982. """)
  1983. def _writePythonItem(self, item, ignoreBlock = True, variables = {}):
  1984. """Write model object to Python file"""
  1985. if isinstance(item, ModelAction):
  1986. if ignoreBlock and item.GetBlockId(): # ignore items in loops of conditions
  1987. return
  1988. self._writePythonAction(item, variables = variables)
  1989. elif isinstance(item, ModelLoop) or isinstance(item, ModelCondition):
  1990. # substitute condition
  1991. cond = item.GetLabel()
  1992. for variable in self.model.GetVariables():
  1993. pattern = re.compile('%' + variable)
  1994. if pattern.search(cond):
  1995. value = variables[variable].get('value', '')
  1996. if variables[variable].get('type', 'string') == 'string':
  1997. value = '"' + value + '"'
  1998. cond = pattern.sub(value, cond)
  1999. if isinstance(item, ModelLoop):
  2000. condVar, condText = map(lambda x: x.strip(), re.split('\s* in \s*', cond))
  2001. cond = "%sfor %s in " % (' ' * self.indent, condVar)
  2002. if condText[0] == '`' and condText[-1] == '`':
  2003. task = GUI(show = None).ParseCommand(cmd = utils.split(condText[1:-1]))
  2004. cond += "grass.read_command("
  2005. cond += self._getPythonActionCmd(task, len(cond), variables = [condVar]) + ".splitlines()"
  2006. else:
  2007. cond += condText
  2008. self.fd.write('%s:\n' % cond)
  2009. self.indent += 4
  2010. variablesLoop = variables.copy()
  2011. variablesLoop[condVar] = None
  2012. for action in item.GetItems(self.model.GetItems(objType=ModelAction)):
  2013. self._writePythonItem(action, ignoreBlock = False, variables = variablesLoop)
  2014. self.indent -= 4
  2015. if isinstance(item, ModelCondition):
  2016. self.fd.write('%sif %s:\n' % (' ' * self.indent, cond))
  2017. self.indent += 4
  2018. condItems = item.GetItems()
  2019. for action in condItems['if']:
  2020. self._writePythonItem(action, ignoreBlock = False)
  2021. if condItems['else']:
  2022. self.indent -= 4
  2023. self.fd.write('%selse:\n' % (' ' * self.indent))
  2024. self.indent += 4
  2025. for action in condItems['else']:
  2026. self._writePythonItem(action, ignoreBlock = False)
  2027. self.indent += 4
  2028. self.fd.write('\n')
  2029. if isinstance(item, ModelComment):
  2030. self._writePythonComment(item)
  2031. def _writePythonAction(self, item, variables = {}):
  2032. """Write model action to Python file"""
  2033. task = GUI(show = None).ParseCommand(cmd = item.GetLog(string = False))
  2034. strcmd = "%srun_command(" % (' ' * self.indent)
  2035. self.fd.write(strcmd + self._getPythonActionCmd(task, len(strcmd), variables) + '\n')
  2036. def _getPythonActionCmd(self, task, cmdIndent, variables = {}):
  2037. opts = task.get_options()
  2038. ret = ''
  2039. flags = ''
  2040. params = list()
  2041. for f in opts['flags']:
  2042. if f.get('value', False):
  2043. name = f.get('name', '')
  2044. if len(name) > 1:
  2045. params.append('%s = True' % name)
  2046. else:
  2047. flags += name
  2048. for p in opts['params']:
  2049. name = p.get('name', None)
  2050. value = p.get('value', None)
  2051. if name and value:
  2052. ptype = p.get('type', 'string')
  2053. foundVar = False
  2054. for var in sorted(variables, key=len, reverse=True):
  2055. data = variables[var]
  2056. if '%' + var in value:
  2057. value = self._substituteVariable(value, var, data)
  2058. foundVar = True
  2059. if foundVar or ptype != 'string':
  2060. params.append("%s = %s" % (name, value))
  2061. else:
  2062. params.append('%s = "%s"' % (name, value))
  2063. ret += '"%s"' % task.get_name()
  2064. if flags:
  2065. ret += ",\n%sflags = '%s'" % (' ' * cmdIndent, flags)
  2066. if len(params) > 0:
  2067. ret += ",\n"
  2068. for opt in params[:-1]:
  2069. ret += "%s%s,\n" % (' ' * cmdIndent, opt)
  2070. ret += "%s%s)" % (' ' * cmdIndent, params[-1])
  2071. else:
  2072. ret += ")"
  2073. return ret
  2074. def _writePythonComment(self, item):
  2075. """Write model comment to Python file"""
  2076. for line in item.GetLabel().splitlines():
  2077. self.fd.write('#' + line + '\n')
  2078. def _substituteVariable(self, string, variable, data):
  2079. """Substitute variable in the string
  2080. :param string: string to be modified
  2081. :param variable: variable to be substituted
  2082. :param data: data related to the variable
  2083. :return: modified string
  2084. """
  2085. result = ''
  2086. ss = re.split("\w*(%"+variable+")w*", string)
  2087. if not ss[0]:
  2088. if data:
  2089. return "options['%s']" % variable
  2090. else:
  2091. return variable
  2092. for s in ss:
  2093. if s == '"':
  2094. continue
  2095. if s == '%' + variable:
  2096. if data:
  2097. result += "+options['%s']+" % variable
  2098. else:
  2099. result += '+%s+' % variable
  2100. else:
  2101. result += '"' + s + '"'
  2102. return result.strip('+')
  2103. class ModelParamDialog(wx.Dialog):
  2104. def __init__(self, parent, model, params, id = wx.ID_ANY, title = _("Model parameters"),
  2105. style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER, **kwargs):
  2106. """Model parameters dialog
  2107. """
  2108. self.parent = parent
  2109. self._model = model
  2110. self.params = params
  2111. self.tasks = list() # list of tasks/pages
  2112. wx.Dialog.__init__(self, parent = parent, id = id, title = title, style = style, **kwargs)
  2113. self.notebook = GNotebook(parent = self,
  2114. style = globalvar.FNPageDStyle)
  2115. panel = self._createPages()
  2116. wx.CallAfter(self.notebook.SetSelection, 0)
  2117. # intermediate data?
  2118. self.interData = wx.CheckBox(parent = self, label = _("Delete intermediate data when finish"))
  2119. self.interData.SetValue(True)
  2120. rast, vect, rast3d, msg = self._model.GetIntermediateData()
  2121. if not rast and not vect and not rast3d:
  2122. self.interData.Hide()
  2123. self.btnCancel = wx.Button(parent = self, id = wx.ID_CANCEL)
  2124. self.btnRun = wx.Button(parent = self, id = wx.ID_OK,
  2125. label = _("&Run"))
  2126. self.btnRun.SetDefault()
  2127. self._layout()
  2128. size = self.GetBestSize()
  2129. self.SetMinSize(size)
  2130. self.SetSize((size.width, size.height +
  2131. panel.constrained_size[1] -
  2132. panel.panelMinHeight))
  2133. def _layout(self):
  2134. btnSizer = wx.StdDialogButtonSizer()
  2135. btnSizer.AddButton(self.btnCancel)
  2136. btnSizer.AddButton(self.btnRun)
  2137. btnSizer.Realize()
  2138. mainSizer = wx.BoxSizer(wx.VERTICAL)
  2139. mainSizer.Add(item = self.notebook, proportion = 1,
  2140. flag = wx.EXPAND)
  2141. if self.interData.IsShown():
  2142. mainSizer.Add(item = self.interData, proportion = 0,
  2143. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
  2144. mainSizer.Add(item = wx.StaticLine(parent = self, id = wx.ID_ANY,
  2145. style = wx.LI_HORIZONTAL),
  2146. proportion = 0,
  2147. flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 5)
  2148. mainSizer.Add(item = btnSizer, proportion = 0,
  2149. flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
  2150. self.SetSizer(mainSizer)
  2151. mainSizer.Fit(self)
  2152. def _createPages(self):
  2153. """Create for each parameterized module its own page"""
  2154. nameOrdered = [''] * len(self.params.keys())
  2155. for name, params in self.params.iteritems():
  2156. nameOrdered[params['idx']] = name
  2157. for name in nameOrdered:
  2158. params = self.params[name]
  2159. panel = self._createPage(name, params)
  2160. if name == 'variables':
  2161. name = _('Variables')
  2162. self.notebook.AddPage(page = panel, text = name)
  2163. return panel
  2164. def _createPage(self, name, params):
  2165. """Define notebook page"""
  2166. if name in globalvar.grassCmd:
  2167. task = gtask.grassTask(name)
  2168. else:
  2169. task = gtask.grassTask()
  2170. task.flags = params['flags']
  2171. task.params = params['params']
  2172. panel = CmdPanel(parent = self, id = wx.ID_ANY, task = task,
  2173. giface = GraphicalModelerGrassInterface(self._model))
  2174. self.tasks.append(task)
  2175. return panel
  2176. def GetErrors(self):
  2177. """Check for errors, get list of messages"""
  2178. errList = list()
  2179. for task in self.tasks:
  2180. errList += task.get_cmd_error()
  2181. return errList
  2182. def DeleteIntermediateData(self):
  2183. """Check if to detele intermediate data"""
  2184. if self.interData.IsShown() and self.interData.IsChecked():
  2185. return True
  2186. return False