vclean.py 20 KB

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