mcalc_builder.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. """!
  2. @package mcalc_builder.py
  3. @brief Map calculator, wrapper for r.mapcalc
  4. Classes:
  5. - MapCalcFrame
  6. (C) 2008, 2010 by the GRASS Development Team
  7. This program is free software under the GNU General Public License
  8. (>=v2). Read the file COPYING that comes with GRASS for details.
  9. @author Michael Barton, Arizona State University
  10. @author Martin Landa <landa.martin gmail.com>
  11. """
  12. import os
  13. import sys
  14. import time
  15. import globalvar
  16. if not os.getenv("GRASS_WXBUNDLED"):
  17. globalvar.CheckForWx()
  18. import wx
  19. import gcmd
  20. import gselect
  21. import menuform
  22. try:
  23. import subprocess
  24. except:
  25. sys.path.append(os.path.join(globalvar.ETCWXDIR, "compat"))
  26. import subprocess
  27. from preferences import globalSettings as UserSettings
  28. class MapCalcFrame(wx.Frame):
  29. """!Mapcalc Frame class. Calculator-style window to create and run
  30. r(3).mapcalc statements
  31. """
  32. def __init__(self, parent, cmd, id = wx.ID_ANY,
  33. style = wx.DEFAULT_FRAME_STYLE | wx.RESIZE_BORDER, **kwargs):
  34. self.parent = parent
  35. if self.parent:
  36. self.log = self.parent.GetLogWindow()
  37. else:
  38. self.log = None
  39. # grass command
  40. self.cmd = cmd
  41. if self.cmd == 'r.mapcalc':
  42. self.rast3d = False
  43. title = _('GRASS GIS Raster Calculator')
  44. if self.cmd == 'r3.mapcalc':
  45. self.rast3d = True
  46. title = _('GRASS GIS 3D Raster Calculator')
  47. wx.Frame.__init__(self, parent, id = id, title = title, **kwargs)
  48. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  49. self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
  50. #
  51. # variables
  52. #
  53. self.heading = _('mapcalc statement')
  54. self.funct_list = [
  55. 'abs(x)',
  56. 'acos(x)',
  57. 'asin(x)',
  58. 'atan(x)',
  59. 'atan(x,y)',
  60. 'cos(x)',
  61. 'double(x)',
  62. 'eval([x,y,...,]z)',
  63. 'exp(x)',
  64. 'exp(x,y)',
  65. 'float(x)',
  66. 'graph(x,x1,y1[x2,y2..])',
  67. 'if(x)',
  68. 'if(x,a)',
  69. 'if(x,a,b)',
  70. 'if(x,a,b,c)',
  71. 'int(x)',
  72. 'isnull(x)',
  73. 'log(x)',
  74. 'log(x,b)',
  75. 'max(x,y[,z...])',
  76. 'median(x,y[,z...])',
  77. 'min(x,y[,z...])',
  78. 'mode(x,y[,z...])',
  79. 'not(x)',
  80. 'pow(x,y)',
  81. 'rand(a,b)',
  82. 'round(x)',
  83. 'sin(x)',
  84. 'sqrt(x)',
  85. 'tan(x)',
  86. 'xor(x,y)',
  87. 'row()',
  88. 'col()',
  89. 'x()',
  90. 'y()',
  91. 'ewres()',
  92. 'nsres()',
  93. 'null()'
  94. ]
  95. if self.rast3d:
  96. indx = self.funct_list.index('y()') +1
  97. self.funct_list.insert(indx, 'z()')
  98. indx = self.funct_list.index('nsres()') +1
  99. self.funct_list.insert(indx, 'tbres()')
  100. maplabel = _('3D raster map')
  101. element = 'rast3d'
  102. else:
  103. maplabel = _('raster map')
  104. element = 'cell'
  105. self.operatorBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  106. label=" %s " % _('Operators'))
  107. self.operandBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  108. label=" %s " % _('Operands'))
  109. self.expressBox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
  110. label=" %s " % _('Expression'))
  111. #
  112. # Buttons
  113. #
  114. self.btn_clear = wx.Button(parent = self.panel, id = wx.ID_CLEAR)
  115. self.btn_help = wx.Button(parent = self.panel, id = wx.ID_HELP)
  116. self.btn_run = wx.Button(parent = self.panel, id = wx.ID_ANY, label = _("&Run"))
  117. self.btn_run.SetDefault()
  118. self.btn_close = wx.Button(parent = self.panel, id = wx.ID_CLOSE)
  119. self.btn_cmd = wx.Button(parent = self.panel, id = wx.ID_ANY,
  120. label = _("Command dialog"))
  121. self.btn_cmd.SetToolTipString(_('Open %s dialog') % self.cmd)
  122. self.btn = dict()
  123. self.btn['pow'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "^")
  124. self.btn['pow'].SetToolTipString(_('exponent'))
  125. self.btn['div'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "/")
  126. self.btn['div'].SetToolTipString(_('divide'))
  127. self.btn['add'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "+")
  128. self.btn['add'].SetToolTipString(_('add'))
  129. self.btn['minus'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "-")
  130. self.btn['minus'].SetToolTipString(_('subtract'))
  131. self.btn['mod'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "%")
  132. self.btn['mod'].SetToolTipString(_('modulus'))
  133. self.btn['mult'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "*")
  134. self.btn['mult'].SetToolTipString(_('multiply'))
  135. self.btn['paren'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "( )")
  136. self.btn['lshift'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "<<")
  137. self.btn['lshift'].SetToolTipString(_('left shift'))
  138. self.btn['rshift'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = ">>")
  139. self.btn['rshift'].SetToolTipString(_('right shift'))
  140. self.btn['rshiftu'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = ">>>")
  141. self.btn['rshiftu'].SetToolTipString(_('right shift (unsigned)'))
  142. self.btn['gt'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = ">")
  143. self.btn['gt'].SetToolTipString(_('greater than'))
  144. self.btn['gteq'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = ">=")
  145. self.btn['gteq'].SetToolTipString(_('greater than or equal to'))
  146. self.btn['lt'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "<")
  147. self.btn['lt'].SetToolTipString(_('less than or equal to'))
  148. self.btn['lteq'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "<=")
  149. self.btn['lteq'].SetToolTipString(_('less than'))
  150. self.btn['eq'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "==")
  151. self.btn['eq'].SetToolTipString(_('equal to'))
  152. self.btn['noteq'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "!=")
  153. self.btn['noteq'].SetToolTipString(_('not equal to'))
  154. self.btn['compl'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "~")
  155. self.btn['compl'].SetToolTipString(_('one\'s complement'))
  156. self.btn['not'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "!")
  157. self.btn['not'].SetToolTipString(_('NOT'))
  158. self.btn['andbit'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = '&')
  159. self.btn['andbit'].SetToolTipString(_('bitwise AND'))
  160. self.btn['orbit'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "|")
  161. self.btn['orbit'].SetToolTipString(_('bitwise OR'))
  162. self.btn['and'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "&&&")
  163. self.btn['and'].SetToolTipString(_('logical AND'))
  164. self.btn['andnull'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "&&&&&")
  165. self.btn['andnull'].SetToolTipString(_('logical AND (ignores NULLs'))
  166. self.btn['or'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "||")
  167. self.btn['or'].SetToolTipString(_('logical OR'))
  168. self.btn['ornull'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "|||")
  169. self.btn['ornull'].SetToolTipString(_('logical OR (ignores NULLs'))
  170. self.btn['cond'] = wx.Button(parent = self.panel, id = wx.ID_ANY, label = "?:")
  171. self.btn['cond'].SetToolTipString(_('conditional'))
  172. #
  173. # Text area
  174. #
  175. self.text_mcalc = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY, size = (-1, 75),
  176. style = wx.TE_MULTILINE)
  177. wx.CallAfter(self.text_mcalc.SetFocus)
  178. #
  179. # Map and function insertion text and ComboBoxes
  180. self.newmaplabel = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  181. label= _('Name for new %s to create') % maplabel)
  182. self.newmaptxt = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY, size=(250, -1))
  183. self.mapsellabel = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  184. label = _('Insert existing %s') % maplabel)
  185. self.mapselect = gselect.Select(parent = self.panel, id = wx.ID_ANY, size = (250, -1),
  186. type = element, multiple = False)
  187. self.functlabel = wx.StaticText(parent = self.panel, id = wx.ID_ANY,
  188. label = _('Insert mapcalc function'))
  189. self.function = wx.ComboBox(parent = self.panel, id = wx.ID_ANY,
  190. size = (250, -1), choices = self.funct_list,
  191. style = wx.CB_DROPDOWN |
  192. wx.CB_READONLY | wx.TE_PROCESS_ENTER)
  193. self.overwrite = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
  194. label=_("Allow output files to overwrite existing files"))
  195. self.overwrite.SetValue(UserSettings.Get(group='cmd', key='overwrite', subkey='enabled'))
  196. #
  197. # Bindings
  198. #
  199. for btn in self.btn.keys():
  200. self.btn[btn].Bind(wx.EVT_BUTTON, self.AddMark)
  201. self.btn_close.Bind(wx.EVT_BUTTON, self.OnClose)
  202. self.btn_clear.Bind(wx.EVT_BUTTON, self.OnClear)
  203. self.btn_run.Bind(wx.EVT_BUTTON, self.OnMCalcRun)
  204. self.btn_help.Bind(wx.EVT_BUTTON, self.OnHelp)
  205. self.btn_cmd.Bind(wx.EVT_BUTTON, self.OnCmdDialog)
  206. self.mapselect.Bind(wx.EVT_TEXT, self.OnSelect)
  207. self.function.Bind(wx.EVT_COMBOBOX, self.OnSelect)
  208. self.function.Bind(wx.EVT_TEXT_ENTER, self.OnSelect)
  209. self._layout()
  210. self.SetMinSize(self.GetBestSize())
  211. def _layout(self):
  212. sizer = wx.BoxSizer(wx.VERTICAL)
  213. controlSizer = wx.BoxSizer(wx.HORIZONTAL)
  214. operatorSizer = wx.StaticBoxSizer(self.operatorBox, wx.HORIZONTAL)
  215. buttonSizer1 = wx.GridBagSizer(5, 1)
  216. buttonSizer1.Add(item = self.btn['add'], pos = (0,0))
  217. buttonSizer1.Add(item = self.btn['minus'], pos = (0,1))
  218. buttonSizer1.Add(item = self.btn['mod'], pos = (5,0))
  219. buttonSizer1.Add(item = self.btn['mult'], pos = (1,0))
  220. buttonSizer1.Add(item = self.btn['div'], pos = (1,1))
  221. buttonSizer1.Add(item = self.btn['pow'], pos = (5,1))
  222. buttonSizer1.Add(item = self.btn['gt'], pos = (2,0))
  223. buttonSizer1.Add(item = self.btn['gteq'], pos = (2,1))
  224. buttonSizer1.Add(item = self.btn['eq'], pos = (4,0))
  225. buttonSizer1.Add(item = self.btn['lt'], pos = (3,0))
  226. buttonSizer1.Add(item = self.btn['lteq'], pos = (3,1))
  227. buttonSizer1.Add(item = self.btn['noteq'], pos = (4,1))
  228. buttonSizer2 = wx.GridBagSizer(5, 1)
  229. buttonSizer2.Add(item = self.btn['and'], pos = (0,0))
  230. buttonSizer2.Add(item = self.btn['andbit'], pos = (1,0))
  231. buttonSizer2.Add(item = self.btn['andnull'], pos = (2,0))
  232. buttonSizer2.Add(item = self.btn['or'], pos = (0,1))
  233. buttonSizer2.Add(item = self.btn['orbit'], pos = (1,1))
  234. buttonSizer2.Add(item = self.btn['ornull'], pos = (2,1))
  235. buttonSizer2.Add(item = self.btn['lshift'], pos = (3,0))
  236. buttonSizer2.Add(item = self.btn['rshift'], pos = (3,1))
  237. buttonSizer2.Add(item = self.btn['rshiftu'], pos = (4,0))
  238. buttonSizer2.Add(item = self.btn['cond'], pos = (5,0))
  239. buttonSizer2.Add(item = self.btn['compl'], pos = (5,1))
  240. buttonSizer2.Add(item = self.btn['not'], pos = (4,1))
  241. operandSizer = wx.StaticBoxSizer(self.operandBox, wx.HORIZONTAL)
  242. buttonSizer3 = wx.GridBagSizer(7, 1)
  243. buttonSizer3.Add(item = self.newmaplabel, pos = (0, 0),
  244. span = (1, 2), flag = wx.ALIGN_CENTER)
  245. buttonSizer3.Add(item = self.newmaptxt, pos = (1, 0),
  246. span = (1, 2))
  247. buttonSizer3.Add(item = self.mapsellabel, pos = (2, 0),
  248. span = (1, 2), flag = wx.ALIGN_CENTER)
  249. buttonSizer3.Add(item = self.mapselect, pos = (3, 0),
  250. span = (1, 2))
  251. buttonSizer3.Add(item = self.functlabel, pos = (4, 0),
  252. span = (1, 2), flag = wx.ALIGN_CENTER)
  253. buttonSizer3.Add(item = self.function, pos = (5, 0),
  254. span = (1, 2))
  255. buttonSizer3.Add(item = self.btn['paren'], pos = (6, 0),
  256. flag = wx.ALIGN_LEFT)
  257. buttonSizer3.Add(item = self.btn_clear, pos = (6, 1),
  258. flag = wx.ALIGN_RIGHT)
  259. buttonSizer4 = wx.BoxSizer(wx.HORIZONTAL)
  260. buttonSizer4.Add(item = self.btn_cmd,
  261. flag = wx.ALL, border = 5)
  262. buttonSizer4.Add(item = self.btn_close,
  263. flag = wx.ALL, border = 5)
  264. buttonSizer4.Add(item = self.btn_run,
  265. flag = wx.ALL, border = 5)
  266. buttonSizer4.Add(item = self.btn_help,
  267. flag = wx.ALL, border = 5)
  268. operatorSizer.Add(item = buttonSizer1, proportion = 0,
  269. flag = wx.ALL | wx.EXPAND, border = 5)
  270. operatorSizer.Add(item = buttonSizer2, proportion = 0,
  271. flag = wx.TOP | wx.BOTTOM | wx.RIGHT | wx.EXPAND, border = 5)
  272. operandSizer.Add(item = buttonSizer3, proportion = 0,
  273. flag = wx.TOP | wx.BOTTOM | wx.RIGHT, border = 5)
  274. controlSizer.Add(item = operatorSizer, proportion = 1,
  275. flag = wx.RIGHT, border = 5)
  276. controlSizer.Add(item = operandSizer, proportion = 0,
  277. flag = wx.EXPAND)
  278. expressSizer = wx.StaticBoxSizer(self.expressBox, wx.HORIZONTAL)
  279. expressSizer.Add(item = self.text_mcalc, proportion = 1,
  280. flag = wx.EXPAND)
  281. sizer.Add(item = controlSizer, proportion = 0,
  282. flag = wx.EXPAND | wx.ALL,
  283. border = 5)
  284. sizer.Add(item = expressSizer, proportion = 1,
  285. flag = wx.EXPAND | wx.LEFT | wx.RIGHT,
  286. border = 5)
  287. sizer.Add(item = self.overwrite, proportion = 0,
  288. flag = wx.EXPAND | wx.LEFT | wx.RIGHT,
  289. border = 5)
  290. sizer.Add(item = buttonSizer4, proportion = 0,
  291. flag = wx.ALL | wx.ALIGN_RIGHT, border = 1)
  292. self.panel.SetAutoLayout(True)
  293. self.panel.SetSizer(sizer)
  294. sizer.Fit(self.panel)
  295. self.Fit()
  296. self.Layout()
  297. def AddMark(self,event):
  298. """!Sends operators to insertion method
  299. """
  300. if event.GetId() == self.btn['compl'].GetId(): mark = "~"
  301. elif event.GetId() == self.btn['not'].GetId(): mark = "!"
  302. elif event.GetId() == self.btn['pow'].GetId(): mark = "^"
  303. elif event.GetId() == self.btn['div'].GetId(): mark = "/"
  304. elif event.GetId() == self.btn['add'].GetId(): mark = "+"
  305. elif event.GetId() == self.btn['minus'].GetId(): mark = "-"
  306. elif event.GetId() == self.btn['mod'].GetId(): mark = "%"
  307. elif event.GetId() == self.btn['mult'].GetId(): mark = "*"
  308. elif event.GetId() == self.btn['lshift'].GetId(): mark = "<<"
  309. elif event.GetId() == self.btn['rshift'].GetId(): mark = ">>"
  310. elif event.GetId() == self.btn['rshiftu'].GetId(): mark = ">>>"
  311. elif event.GetId() == self.btn['gt'].GetId(): mark = ">"
  312. elif event.GetId() == self.btn['gteq'].GetId(): mark = ">="
  313. elif event.GetId() == self.btn['lt'].GetId(): mark = "<"
  314. elif event.GetId() == self.btn['lteq'].GetId(): mark = "<="
  315. elif event.GetId() == self.btn['eq'].GetId(): mark = "=="
  316. elif event.GetId() == self.btn['noteq'].GetId(): mark = "!="
  317. elif event.GetId() == self.btn['andbit'].GetId(): mark = "&"
  318. elif event.GetId() == self.btn['orbit'].GetId(): mark = "|"
  319. elif event.GetId() == self.btn['or'].GetId(): mark = "||"
  320. elif event.GetId() == self.btn['ornull'].GetId(): mark = "|||"
  321. elif event.GetId() == self.btn['and'].GetId(): mark = "&&"
  322. elif event.GetId() == self.btn['andnull'].GetId(): mark = "&&&"
  323. elif event.GetId() == self.btn['cond'].GetId(): mark = "?:"
  324. elif event.GetId() == self.btn['paren'].GetId(): mark = "()"
  325. self._addSomething(mark)
  326. def OnSelect(self, event):
  327. """!Gets raster map or function selection and send it to
  328. insertion method
  329. """
  330. item = event.GetString()
  331. self._addSomething(item)
  332. def _addSomething(self, what):
  333. """!Inserts operators, map names, and functions into text area
  334. """
  335. self.text_mcalc.SetFocus()
  336. mcalcstr = self.text_mcalc.GetValue()
  337. position = self.text_mcalc.GetInsertionPoint()
  338. newmcalcstr = mcalcstr[:position]
  339. position_offset = 0
  340. try:
  341. if newmcalcstr[-1] != ' ':
  342. newmcalcstr += ' '
  343. position_offset += 1
  344. except:
  345. pass
  346. newmcalcstr += what
  347. position_offset += len(what)
  348. newmcalcstr += ' ' + mcalcstr[position:]
  349. self.text_mcalc.SetValue(newmcalcstr)
  350. if what == '()':
  351. position_offset -= 1
  352. self.text_mcalc.SetInsertionPoint(position + position_offset)
  353. self.text_mcalc.Update()
  354. def OnMCalcRun(self,event):
  355. """!Builds and runs r.mapcalc statement
  356. """
  357. name = self.newmaptxt.GetValue().strip()
  358. if not name:
  359. gcmd.GError(parent = self,
  360. message = _("You must enter the name of a new map to create"))
  361. return
  362. if not self.text_mcalc.GetValue().strip():
  363. gcmd.GError(parent = self,
  364. message = _("You must enter a mapcalc statement to create a new map"))
  365. return
  366. mctxt = self.text_mcalc.GetValue().strip().replace("\n"," ")
  367. mctxt = mctxt.replace(" " , "")
  368. if self.log:
  369. cmd = [self.cmd, str('expression=%s = %s' % (name, mctxt))]
  370. if self.overwrite.IsChecked():
  371. cmd.append('--overwrite')
  372. self.log.RunCmd(cmd)
  373. self.parent.Raise()
  374. else:
  375. if self.overwrite.IsChecked():
  376. overwrite = True
  377. else:
  378. overwrite = False
  379. gcmd.RunCommand(self.cmd,
  380. expression = "%s=%s" % (name, mctxt),
  381. overwrite = overwrite)
  382. def OnClear(self, event):
  383. """!Clears text area
  384. """
  385. self.text_mcalc.SetValue('')
  386. def OnHelp(self, event):
  387. """!Launches r.mapcalc help
  388. """
  389. gcmd.RunCommand('g.manual', parent = self, entry = self.cmd)
  390. def OnClose(self,event):
  391. """!Close window"""
  392. self.Destroy()
  393. def OnCmdDialog(self, event):
  394. """!Shows command dialog"""
  395. name = self.newmaptxt.GetValue().strip()
  396. mctxt = self.text_mcalc.GetValue().strip().replace("\n"," ")
  397. mctxt = mctxt.replace(" " , "")
  398. expr = name
  399. if expr:
  400. expr += '='
  401. expr += mctxt
  402. menuform.GUI().ParseCommand(cmd = [self.cmd, 'expression=' + expr],
  403. parentframe = self)
  404. if __name__ == "__main__":
  405. app = wx.App(0)
  406. frame = MapCalcFrame(None, cmd = 'r.mapcalc')
  407. frame.Show()
  408. app.MainLoop()