vclean.py 20 KB

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