vclean.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  1. """
  2. @package modules.vclean
  3. @brief Dialog for interactive construction of vector cleaning
  4. operations
  5. Classes:
  6. - vclean::VectorCleaningFrame
  7. (C) 2010-2011 by the GRASS Development Team
  8. This program is free software under the GNU General Public License
  9. (>=v2). Read the file COPYING that comes with GRASS for details.
  10. @author Markus Metz
  11. """
  12. import os
  13. import sys
  14. import wx
  15. import wx.lib.scrolledpanel as scrolled
  16. if __name__ == '__main__':
  17. gui_wx_path = os.path.join(os.getenv('GISBASE'), 'etc', 'gui', 'wxpython')
  18. if gui_wx_path not in sys.path:
  19. sys.path.append(gui_wx_path)
  20. from core.gcmd import RunCommand, GError
  21. from core import globalvar
  22. from gui_core.gselect import Select
  23. from core.settings import UserSettings
  24. from grass.script import core as grass
  25. class VectorCleaningFrame(wx.Frame):
  26. def __init__(self, parent, id=wx.ID_ANY, title=_('Set up vector cleaning tools'),
  27. style=wx.DEFAULT_FRAME_STYLE | wx.RESIZE_BORDER,
  28. **kwargs):
  29. """!
  30. Dialog for interactively defining vector cleaning tools
  31. """
  32. wx.Frame.__init__(self, parent, id, title, style=style, **kwargs)
  33. self.parent = parent # GMFrame
  34. if self.parent:
  35. self.log = self.parent.GetLogWindow()
  36. else:
  37. self.log = None
  38. # grass command
  39. self.cmd = 'v.clean'
  40. # statusbar
  41. self.CreateStatusBar()
  42. # icon
  43. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  44. self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
  45. # input map to clean
  46. self.inmap = ''
  47. # cleaned output map
  48. self.outmap = ''
  49. self.ftype = ''
  50. # cleaning tools
  51. self.toolslines = {}
  52. self.tool_desc_list = [
  53. _('break lines/boundaries'),
  54. _('remove duplicates'),
  55. _('remove dangles'),
  56. _('change boundary dangles to lines'),
  57. _('remove bridges'),
  58. _('change bridges to lines'),
  59. _('snap lines/boundaries'),
  60. _('remove duplicate area centroids'),
  61. _('break polygons'),
  62. _('prune lines/boundaries'),
  63. _('remove small areas'),
  64. _('remove lines/boundaries of zero length'),
  65. _('remove small angles at nodes')
  66. ]
  67. self.tool_list = [
  68. 'break',
  69. 'rmdupl',
  70. 'rmdangle',
  71. 'chdangle',
  72. 'rmbridge',
  73. 'chbridge',
  74. 'snap',
  75. 'rmdac',
  76. 'bpol',
  77. 'prune',
  78. 'rmarea',
  79. 'rmline',
  80. 'rmsa'
  81. ]
  82. self.ftype = [
  83. 'point',
  84. 'line',
  85. 'boundary',
  86. 'centroid',
  87. 'area',
  88. 'face']
  89. self.n_ftypes = len(self.ftype)
  90. self.tools_string = ''
  91. self.thresh_string = ''
  92. self.ftype_string = ''
  93. self.SetStatusText(_("Set up vector cleaning tools"))
  94. self.elem = 'vector'
  95. self.ctlabel = _('Choose cleaning tools and set thresholds')
  96. # top controls
  97. self.inmaplabel = wx.StaticText(parent=self.panel, id=wx.ID_ANY,
  98. label=_('Select input vector map:'))
  99. self.selectionInput = Select(parent=self.panel, id=wx.ID_ANY,
  100. size=globalvar.DIALOG_GSELECT_SIZE,
  101. type='vector')
  102. self.ftype_check = {}
  103. ftypeBox = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
  104. label=_(' Feature type: '))
  105. self.ftypeSizer = wx.StaticBoxSizer(ftypeBox, wx.HORIZONTAL)
  106. self.outmaplabel = wx.StaticText(parent=self.panel, id=wx.ID_ANY,
  107. label=_('Select output vector map:'))
  108. self.selectionOutput = Select(parent=self.panel, id=wx.ID_ANY,
  109. size=globalvar.DIALOG_GSELECT_SIZE,
  110. mapsets=[grass.gisenv()['MAPSET'],],
  111. fullyQualified = False,
  112. type='vector')
  113. self.overwrite = wx.CheckBox(parent=self.panel, id=wx.ID_ANY,
  114. label=_('Allow output files to overwrite existing files'))
  115. self.overwrite.SetValue(UserSettings.Get(group='cmd', key='overwrite', subkey='enabled'))
  116. # cleaning tools
  117. self.ct_label = wx.StaticText(parent=self.panel, id=wx.ID_ANY,
  118. label=self.ctlabel)
  119. self.ct_panel = self._toolsPanel()
  120. # buttons to manage cleaning tools
  121. self.btn_add = wx.Button(parent=self.panel, id=wx.ID_ADD)
  122. self.btn_remove = wx.Button(parent=self.panel, id=wx.ID_REMOVE)
  123. self.btn_moveup = wx.Button(parent=self.panel, id=wx.ID_UP)
  124. self.btn_movedown = wx.Button(parent=self.panel, id=wx.ID_DOWN)
  125. # add one tool as default
  126. self.AddTool()
  127. self.selected = -1
  128. # Buttons
  129. self.btn_close = wx.Button(parent=self.panel, id=wx.ID_CLOSE)
  130. self.btn_run = wx.Button(parent=self.panel, id=wx.ID_ANY, label=_("&Run"))
  131. self.btn_run.SetDefault()
  132. self.btn_clipboard = wx.Button(parent=self.panel, id=wx.ID_COPY)
  133. self.btn_clipboard.SetToolTipString(_("Copy the current command string to the clipboard (Ctrl+C)"))
  134. self.btn_help = wx.Button(parent=self.panel, id=wx.ID_HELP)
  135. # bindings
  136. self.btn_close.Bind(wx.EVT_BUTTON, self.OnClose)
  137. self.btn_run.Bind(wx.EVT_BUTTON, self.OnCleaningRun)
  138. self.btn_clipboard.Bind(wx.EVT_BUTTON, self.OnCopy)
  139. self.btn_help.Bind(wx.EVT_BUTTON, self.OnHelp)
  140. self.btn_add.Bind(wx.EVT_BUTTON, self.OnAddTool)
  141. self.btn_remove.Bind(wx.EVT_BUTTON, self.OnClearTool)
  142. self.btn_moveup.Bind(wx.EVT_BUTTON, self.OnMoveToolUp)
  143. self.btn_movedown.Bind(wx.EVT_BUTTON, self.OnMoveToolDown)
  144. # layout
  145. self._layout()
  146. self.SetMinSize(self.GetBestSize())
  147. self.CentreOnScreen()
  148. def _layout(self):
  149. sizer = wx.BoxSizer(wx.VERTICAL)
  150. #
  151. # input output
  152. #
  153. inSizer = wx.GridBagSizer(hgap=5, vgap=5)
  154. inSizer.Add(item=self.inmaplabel, pos=(0, 0),
  155. flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL | wx.EXPAND, border=1)
  156. inSizer.Add(item=self.selectionInput, pos=(1, 0),
  157. flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL | wx.EXPAND, border=1)
  158. self.ftype_check = [
  159. wx.CheckBox(parent=self.panel, id=wx.ID_ANY, label=_('point')),
  160. wx.CheckBox(parent=self.panel, id=wx.ID_ANY, label=_('line')),
  161. wx.CheckBox(parent=self.panel, id=wx.ID_ANY, label=_('boundary')),
  162. wx.CheckBox(parent=self.panel, id=wx.ID_ANY, label=_('centroid')),
  163. wx.CheckBox(parent=self.panel, id=wx.ID_ANY, label=_('area')),
  164. wx.CheckBox(parent=self.panel, id=wx.ID_ANY, label=_('face'))
  165. ]
  166. typeoptSizer = wx.BoxSizer(wx.HORIZONTAL)
  167. for num in range(0, self.n_ftypes):
  168. type_box = self.ftype_check[num]
  169. if self.ftype[num] in ('point', 'line', 'area'):
  170. type_box.SetValue(True);
  171. typeoptSizer.Add(item=type_box, flag=wx.ALIGN_LEFT, border=1)
  172. self.ftypeSizer.Add(item=typeoptSizer,
  173. flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=2)
  174. outSizer = wx.GridBagSizer(hgap=5, vgap=5)
  175. outSizer.Add(item=self.outmaplabel, pos=(0, 0),
  176. flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL | wx.EXPAND, border=1)
  177. outSizer.Add(item=self.selectionOutput, pos=(1, 0),
  178. flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL | wx.EXPAND, border=1)
  179. replaceSizer = wx.BoxSizer(wx.HORIZONTAL)
  180. replaceSizer.Add(item=self.overwrite, proportion=1,
  181. flag=wx.ALL | wx.EXPAND, border=1)
  182. outSizer.Add(item=replaceSizer, pos=(2, 0),
  183. flag=wx.ALL | wx.EXPAND, border=1)
  184. #
  185. # tools selection
  186. #
  187. bodySizer = wx.GridBagSizer(hgap=5, vgap=5)
  188. bodySizer.Add(item=self.ct_label, pos=(0, 0), span=(1, 2),
  189. flag=wx.ALL, border=5)
  190. bodySizer.Add(item=self.ct_panel, pos=(1, 0), span=(1, 2))
  191. manageBoxSizer = wx.GridBagSizer(hgap=10, vgap=1)
  192. # start with row 1 for nicer layout
  193. manageBoxSizer.Add(item=self.btn_add, pos=(1, 0), border=2, flag=wx.ALL | wx.EXPAND)
  194. manageBoxSizer.Add(item=self.btn_remove, pos=(2, 0), border=2, flag=wx.ALL | wx.EXPAND)
  195. manageBoxSizer.Add(item=self.btn_moveup, pos=(3, 0), border=2, flag=wx.ALL | wx.EXPAND)
  196. manageBoxSizer.Add(item=self.btn_movedown, pos=(4, 0), border=2, flag=wx.ALL | wx.EXPAND)
  197. bodySizer.Add(item=manageBoxSizer, pos=(1, 2),
  198. flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=5)
  199. bodySizer.AddGrowableCol(2)
  200. #
  201. # standard buttons
  202. #
  203. btnSizer = wx.BoxSizer(wx.HORIZONTAL)
  204. btnSizer.Add(self.btn_close,
  205. flag=wx.LEFT | wx.RIGHT, border=5)
  206. btnSizer.Add(self.btn_run,
  207. flag=wx.LEFT | wx.RIGHT, border=5)
  208. btnSizer.Add(self.btn_clipboard,
  209. flag=wx.LEFT | wx.RIGHT, border=5)
  210. btnSizer.Add(self.btn_help,
  211. flag=wx.LEFT | wx.RIGHT, border=5)
  212. #
  213. # put it all together
  214. #
  215. sizer.Add(item=inSizer, proportion=0,
  216. flag=wx.ALL | wx.EXPAND, border=5)
  217. sizer.Add(item=self.ftypeSizer, proportion=0,
  218. flag=wx.ALL | wx.EXPAND, border=5)
  219. sizer.Add(item=outSizer, proportion=0,
  220. flag=wx.ALL | wx.EXPAND, border=5)
  221. sizer.Add(item=wx.StaticLine(parent=self, id=wx.ID_ANY,
  222. style=wx.LI_HORIZONTAL), proportion=0,
  223. flag=wx.EXPAND | wx.ALL, border=5)
  224. sizer.Add(item=bodySizer, proportion=1,
  225. flag=wx.ALL | wx.EXPAND, border=5)
  226. sizer.Add(item=wx.StaticLine(parent=self, id=wx.ID_ANY,
  227. style=wx.LI_HORIZONTAL), proportion=0,
  228. flag=wx.EXPAND | wx.ALL, border=5)
  229. sizer.Add(item=btnSizer, proportion=0,
  230. flag=wx.ALL | wx.ALIGN_RIGHT, border=5)
  231. self.panel.SetAutoLayout(True)
  232. self.panel.SetSizer(sizer)
  233. sizer.Fit(self.panel)
  234. self.Layout()
  235. def _toolsPanel(self):
  236. ct_panel = scrolled.ScrolledPanel(parent=self.panel, id=wx.ID_ANY,
  237. size=(500, 240),
  238. style=wx.SUNKEN_BORDER)
  239. self.ct_sizer = wx.GridBagSizer(vgap=2, hgap=4)
  240. ct_panel.SetSizer(self.ct_sizer)
  241. ct_panel.SetAutoLayout(True)
  242. return ct_panel
  243. def OnAddTool(self, event):
  244. """!Add tool button pressed"""
  245. self.AddTool()
  246. def AddTool(self):
  247. snum = len(self.toolslines.keys())
  248. num = snum + 1
  249. # tool
  250. tool_cbox = wx.ComboBox(parent=self.ct_panel, id=1000 + num,
  251. size=(300, -1), choices=self.tool_desc_list,
  252. style=wx.CB_DROPDOWN |
  253. wx.CB_READONLY | wx.TE_PROCESS_ENTER)
  254. self.Bind(wx.EVT_COMBOBOX, self.OnSetTool, tool_cbox)
  255. # threshold
  256. txt_ctrl = wx.TextCtrl(parent=self.ct_panel, id=2000 + num, value='0.00',
  257. size=(100, -1),
  258. style=wx.TE_NOHIDESEL)
  259. self.Bind(wx.EVT_TEXT, self.OnThreshValue, txt_ctrl)
  260. # select with tool number
  261. select = wx.CheckBox(parent=self.ct_panel, id=num, label=str(num) + '.')
  262. select.SetValue(False)
  263. self.Bind(wx.EVT_CHECKBOX, self.OnSelect, select)
  264. # start with row 1 and col 1 for nicer layout
  265. self.ct_sizer.Add(item=select, pos=(num, 1),
  266. flag=wx.ALIGN_CENTER | wx.RIGHT)
  267. self.ct_sizer.Add(item=tool_cbox, pos=(num, 2),
  268. flag=wx.ALIGN_CENTER | wx.RIGHT, border=5)
  269. self.ct_sizer.Add(item=txt_ctrl, pos=(num, 3),
  270. flag=wx.ALIGN_CENTER | wx.RIGHT, border=5)
  271. self.toolslines[num] = {'tool_desc': '',
  272. 'tool': '',
  273. 'thresh': '0.00'}
  274. self.ct_panel.Layout()
  275. self.ct_panel.SetupScrolling()
  276. def OnClearTool(self, event):
  277. """!Remove tool button pressed"""
  278. id = self.selected
  279. if id > 0:
  280. self.FindWindowById(id + 1000).SetValue('')
  281. self.toolslines[id]['tool_desc'] = ''
  282. self.toolslines[id]['tool'] = ''
  283. self.SetStatusText(_("%s. cleaning tool removed, will be ignored") % id)
  284. else:
  285. self.SetStatusText(_("Please select a cleaning tool to remove"))
  286. def OnMoveToolUp(self, event):
  287. """!Move up tool button pressed"""
  288. id = self.selected
  289. if id > 1:
  290. id_up = id - 1
  291. this_toolline = self.toolslines[id]
  292. up_toolline = self.toolslines[id_up]
  293. self.FindWindowById(id_up).SetValue(True)
  294. self.FindWindowById(id_up + 1000).SetValue(this_toolline['tool_desc'])
  295. self.FindWindowById(id_up + 2000).SetValue(this_toolline['thresh'])
  296. self.toolslines[id_up] = this_toolline
  297. self.FindWindowById(id).SetValue(False)
  298. self.FindWindowById(id + 1000).SetValue(up_toolline['tool_desc'])
  299. self.FindWindowById(id + 2000).SetValue(up_toolline['thresh'])
  300. self.toolslines[id] = up_toolline
  301. self.selected = id_up
  302. self.SetStatusText(_("%s. cleaning tool moved up") % id)
  303. elif id == 1:
  304. self.SetStatusText(_("1. cleaning tool can not be moved up "))
  305. elif id == -1:
  306. self.SetStatusText(_("Please select a cleaning tool to move up"))
  307. def OnMoveToolDown(self, event):
  308. """!Move down tool button pressed"""
  309. id = self.selected
  310. snum = len(self.toolslines.keys())
  311. if id > 0 and id < snum:
  312. id_down = id + 1
  313. this_toolline = self.toolslines[id]
  314. down_toolline = self.toolslines[id_down]
  315. self.FindWindowById(id_down).SetValue(True)
  316. self.FindWindowById(id_down + 1000).SetValue(this_toolline['tool_desc'])
  317. self.FindWindowById(id_down + 2000).SetValue(this_toolline['thresh'])
  318. self.toolslines[id_down] = this_toolline
  319. self.FindWindowById(id).SetValue(False)
  320. self.FindWindowById(id + 1000).SetValue(down_toolline['tool_desc'])
  321. self.FindWindowById(id + 2000).SetValue(down_toolline['thresh'])
  322. self.toolslines[id] = down_toolline
  323. self.selected = id_down
  324. self.SetStatusText(_("%s. cleaning tool moved down") % id)
  325. elif id == snum:
  326. self.SetStatusText(_("Last cleaning tool can not be moved down "))
  327. elif id == -1:
  328. self.SetStatusText(_("Please select a cleaning tool to move down"))
  329. def OnSetTool(self, event):
  330. """!Tool was defined"""
  331. id = event.GetId()
  332. tool_no = id - 1000
  333. num = self.FindWindowById(id).GetCurrentSelection()
  334. self.toolslines[tool_no]['tool_desc'] = self.tool_desc_list[num]
  335. self.toolslines[tool_no]['tool'] = self.tool_list[num]
  336. self.SetStatusText(str(tool_no) + '. ' + _("cleaning tool: '%s'") % (self.tool_list[num]))
  337. def OnThreshValue(self, event):
  338. """!Threshold value was entered"""
  339. id = event.GetId()
  340. num = id - 2000
  341. self.toolslines[num]['thresh'] = self.FindWindowById(id).GetValue()
  342. self.SetStatusText(_("Threshold for %(num)s. tool '%(tool)s': %(thresh)s") % \
  343. {'num': num,
  344. 'tool': self.toolslines[num]['tool'],
  345. 'thresh': self.toolslines[num]['thresh']})
  346. def OnSelect(self, event):
  347. """!Tool was selected"""
  348. id = event.GetId()
  349. if self.selected > -1 and self.selected != id:
  350. win = self.FindWindowById(self.selected)
  351. win.SetValue(False)
  352. if self.selected != id:
  353. self.selected = id
  354. else:
  355. self.selected = -1
  356. def OnDone(self, cmd, returncode):
  357. """!Command done"""
  358. self.SetStatusText('')
  359. def OnCleaningRun(self, event):
  360. """!Builds options and runs v.clean
  361. """
  362. self.GetCmdStrings()
  363. err = list()
  364. for p, name in ((self.inmap, _('Name of input vector map')),
  365. (self.outmap, _('Name for output vector map')),
  366. (self.tools_string, _('Tools')),
  367. (self.thresh_string, _('Threshold'))):
  368. if not p:
  369. err.append(_("'%s' not defined") % name)
  370. if err:
  371. GError(_("Some parameters not defined. Operation "
  372. "canceled.\n\n%s") % '\n'.join(err),
  373. parent=self)
  374. return
  375. self.SetStatusText(_("Executing selected cleaning operations..."))
  376. snum = len(self.toolslines.keys())
  377. if self.log:
  378. cmd = [self.cmd,
  379. 'input=%s' % self.inmap,
  380. 'output=%s' % self.outmap,
  381. 'tool=%s' % self.tools_string,
  382. 'thres=%s' % self.thresh_string]
  383. if self.ftype_string:
  384. cmd.append('type=%s' % self.ftype_string)
  385. if self.overwrite.IsChecked():
  386. cmd.append('--overwrite')
  387. self.log.RunCmd(cmd, onDone=self.OnDone)
  388. self.parent.Raise()
  389. else:
  390. if self.overwrite.IsChecked():
  391. overwrite = True
  392. else:
  393. overwrite = False
  394. RunCommand(self.cmd,
  395. input=self.inmap,
  396. output=self.outmap,
  397. type=self.ftype_string,
  398. tool=self.tools_string,
  399. thresh=self.thresh_string,
  400. overwrite=overwrite)
  401. def OnClose(self, event):
  402. self.Destroy()
  403. def OnHelp(self, event):
  404. """!Show GRASS manual page"""
  405. RunCommand('g.manual',
  406. quiet=True,
  407. parent=self,
  408. entry=self.cmd)
  409. def OnCopy(self, event):
  410. """!Copy the command"""
  411. cmddata = wx.TextDataObject()
  412. # get tool and thresh strings
  413. self.GetCmdStrings()
  414. cmdstring = '%s' % (self.cmd)
  415. # list -> string
  416. cmdstring += ' input=%s output=%s type=%s tool=%s thres=%s' % \
  417. (self.inmap, self.outmap, self.ftype_string, self.tools_string, self.thresh_string)
  418. if self.overwrite.IsChecked():
  419. cmdstring += ' --overwrite'
  420. cmddata.SetText(cmdstring)
  421. if wx.TheClipboard.Open():
  422. wx.TheClipboard.SetData(cmddata)
  423. wx.TheClipboard.Close()
  424. self.SetStatusText(_("Vector cleaning command copied to clipboard"))
  425. def GetCmdStrings(self):
  426. self.tools_string = ''
  427. self.thresh_string = ''
  428. self.ftype_string = ''
  429. # feature types
  430. first = 1
  431. for num in range(0, self.n_ftypes - 1):
  432. if self.ftype_check[num].IsChecked():
  433. if first:
  434. self.ftype_string = '%s' % self.ftype[num]
  435. first = 0
  436. else:
  437. self.ftype_string += ',%s' % self.ftype[num]
  438. # cleaning tools
  439. first = 1
  440. snum = len(self.toolslines.keys())
  441. for num in range(1, snum + 1):
  442. if self.toolslines[num]['tool']:
  443. if first:
  444. self.tools_string = '%s' % self.toolslines[num]['tool']
  445. self.thresh_string = '%s' % self.toolslines[num]['thresh']
  446. first = 0
  447. else:
  448. self.tools_string += ',%s' % self.toolslines[num]['tool']
  449. self.thresh_string += ',%s' % self.toolslines[num]['thresh']
  450. self.inmap = self.selectionInput.GetValue()
  451. self.outmap = self.selectionOutput.GetValue()
  452. if __name__ == '__main__':
  453. app = wx.App()
  454. frame = VectorCleaningFrame(parent=None)
  455. frame.Show()
  456. app.MainLoop()