sampling_frame.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. # -*- coding: utf-8 -*-
  2. """
  3. @package rlisetup.sampling_frame
  4. @brief r.li.setup - draw sample frame
  5. Classes:
  6. - sampling_frame::RLiSetupMapPanel
  7. - sampling_frame::RLiSetupToolbar
  8. - sampling_frame::GraphicsSetItem
  9. (C) 2013 by the GRASS Development Team
  10. This program is free software under the GNU General Public License
  11. (>=v2). Read the file COPYING that comes with GRASS for details.
  12. @author Anna Petrasova <kratochanna gmail.com>
  13. """
  14. import os
  15. import wx
  16. import wx.aui
  17. # start new import
  18. import tempfile
  19. from core.gcmd import RunCommand
  20. import grass.script.core as grass
  21. from core import gcmd
  22. try:
  23. from grass.lib.gis import *
  24. from grass.lib.vector import *
  25. from grass.lib.raster import *
  26. except ImportError:
  27. pass
  28. from core.giface import StandaloneGrassInterface
  29. from mapwin.base import MapWindowProperties
  30. from mapwin.buffered import BufferedMapWindow
  31. from core.render import Map
  32. from gui_core.toolbars import BaseToolbar, BaseIcons, ToolSwitcher
  33. from icons.icon import MetaIcon
  34. from core.gcmd import GMessage
  35. from grass.pydispatch.signal import Signal
  36. from grass.pydispatch.errors import DispatcherKeyError
  37. from .functions import SamplingType, checkMapExists
  38. class Circle:
  39. def __init__(self, pt, r):
  40. self.point = pt
  41. self.radius = r
  42. class MaskedArea(object):
  43. def __init__(self, region, raster, radius):
  44. self.region = region
  45. self.raster = raster
  46. self.radius = radius
  47. class RLiSetupMapPanel(wx.Panel):
  48. """Panel with mapwindow used in r.li.setup"""
  49. def __init__(self, parent, samplingType, icon=None, map_=None):
  50. wx.Panel.__init__(self, parent=parent)
  51. self.mapWindowProperties = MapWindowProperties()
  52. self.mapWindowProperties.setValuesFromUserSettings()
  53. giface = StandaloneGrassInterface()
  54. self.samplingtype = samplingType
  55. self.parent = parent
  56. if map_:
  57. self.map_ = map_
  58. else:
  59. self.map_ = Map()
  60. self.map_.region = self.map_.GetRegion()
  61. self._mgr = wx.aui.AuiManager(self)
  62. self.mapWindow = BufferedMapWindow(parent=self, giface=giface,
  63. Map=self.map_,
  64. properties=self.mapWindowProperties)
  65. self._mgr.AddPane(self.mapWindow, wx.aui.AuiPaneInfo().CentrePane().
  66. Dockable(True).BestSize((-1, -1)).Name('mapwindow').
  67. CloseButton(False).DestroyOnClose(True).
  68. Layer(0))
  69. self._toolSwitcher = ToolSwitcher()
  70. self._toolSwitcher.toggleToolChanged.connect(self._onToolChanged)
  71. self.toolbar = RLiSetupToolbar(self, self._toolSwitcher)
  72. self.catId = 1
  73. self._mgr.AddPane(self.toolbar,
  74. wx.aui.AuiPaneInfo().
  75. Name("maptoolbar").Caption(_("Map Toolbar")).
  76. ToolbarPane().Left().Name('mapToolbar').
  77. CloseButton(False).Layer(1).Gripper(False).
  78. BestSize((self.toolbar.GetBestSize())))
  79. self._mgr.Update()
  80. if self.samplingtype == SamplingType.REGIONS:
  81. self.afterRegionDrawn = Signal('RLiSetupMapPanel.afterRegionDrawn')
  82. self._registeredGraphics = self.mapWindow.RegisterGraphicsToDraw(
  83. graphicsType='line')
  84. elif self.samplingtype in [SamplingType.MUNITSR, SamplingType.MMVWINR]:
  85. self.sampleFrameChanged = Signal(
  86. 'RLiSetupMapPanel.sampleFrameChanged')
  87. self._registeredGraphics = self.mapWindow.RegisterGraphicsToDraw(
  88. graphicsType='rectangle')
  89. elif self.samplingtype in [SamplingType.MUNITSC, SamplingType.MMVWINC]:
  90. self.afterCircleDrawn = Signal('RLiSetupMapPanel.afterCircleDrawn')
  91. self._registeredGraphics = self.mapWindow.RegisterGraphicsToDraw(
  92. graphicsType='line')
  93. else:
  94. self.sampleFrameChanged = Signal(
  95. 'RLiSetupMapPanel.sampleFrameChanged')
  96. self._registeredGraphics = self.mapWindow.RegisterGraphicsToDraw(
  97. graphicsType='rectangle')
  98. self._registeredGraphics.AddPen('rlisetup', wx.Pen(wx.GREEN, width=2,
  99. style=wx.SOLID))
  100. self._registeredGraphics.AddItem(coords=[[0, 0], [0, 0]],
  101. penName='rlisetup', hide=True)
  102. if self.samplingtype != SamplingType.VECT:
  103. self.toolbar.SelectDefault()
  104. def GetMap(self):
  105. return self.map_
  106. def OnPan(self, event):
  107. """Panning, set mouse to drag."""
  108. self.mapWindow.SetModePan()
  109. def OnZoomIn(self, event):
  110. """Zoom in the map."""
  111. self.mapWindow.SetModeZoomIn()
  112. def OnZoomOut(self, event):
  113. """Zoom out the map."""
  114. self.mapWindow.SetModeZoomOut()
  115. def OnZoomToMap(self, event):
  116. layers = self.map_.GetListOfLayers()
  117. self.mapWindow.ZoomToMap(layers=layers, ignoreNulls=False, render=True)
  118. def OnDrawRadius(self, event):
  119. """Start draw mode"""
  120. self.mapWindow.mouse['use'] = "None"
  121. self.mapWindow.mouse['box'] = "line"
  122. self.mapWindow.pen = wx.Pen(colour=wx.RED, width=1,
  123. style=wx.SHORT_DASH)
  124. self.mapWindow.SetNamedCursor('cross')
  125. self.mapWindow.mouseLeftUp.connect(self._radiusDrawn)
  126. def OnDigitizeRegion(self, event):
  127. """Start draw mode"""
  128. self.mapWindow.mouse['use'] = "None"
  129. self.mapWindow.mouse['box'] = "line"
  130. self.mapWindow.pen = wx.Pen(colour=wx.RED, width=1,
  131. style=wx.SHORT_DASH)
  132. self.mapWindow.SetNamedCursor('cross')
  133. self.mapWindow.mouseLeftUp.connect(self._lineSegmentDrawn)
  134. self.mapWindow.mouseDClick.connect(self._mouseDbClick)
  135. self._registeredGraphics.GetItem(0).SetCoords([])
  136. def OnDraw(self, event):
  137. """Start draw mode"""
  138. self.mapWindow.mouse['use'] = "None"
  139. self.mapWindow.mouse['box'] = "box"
  140. self.mapWindow.pen = wx.Pen(colour=wx.RED, width=2,
  141. style=wx.SHORT_DASH)
  142. self.mapWindow.SetNamedCursor('cross')
  143. self.mapWindow.mouseLeftUp.connect(self._rectangleDrawn)
  144. def _lineSegmentDrawn(self, x, y):
  145. item = self._registeredGraphics.GetItem(0)
  146. coords = item.GetCoords()
  147. if len(coords) == 0:
  148. coords.extend([self.mapWindow.Pixel2Cell(
  149. self.mapWindow.mouse['begin'])])
  150. coords.extend([[x, y]])
  151. item.SetCoords(coords)
  152. item.SetPropertyVal('hide', False)
  153. self.mapWindow.ClearLines()
  154. self._registeredGraphics.Draw()
  155. def _mouseDbClick(self, x, y):
  156. item = self._registeredGraphics.GetItem(0)
  157. coords = item.GetCoords()
  158. coords.extend([[x, y]])
  159. item.SetCoords(coords)
  160. item.SetPropertyVal('hide', False)
  161. self.mapWindow.ClearLines()
  162. self._registeredGraphics.Draw()
  163. self.createRegion()
  164. def createRegion(self):
  165. dlg = wx.TextEntryDialog(None, 'Name of sample region',
  166. 'Create region', 'region' + str(self.catId))
  167. ret = dlg.ShowModal()
  168. while True:
  169. if ret == wx.ID_OK:
  170. raster = dlg.GetValue()
  171. if checkMapExists(raster):
  172. GMessage(
  173. parent=self, message=_(
  174. "The raster file %s already"
  175. " exists, please change name") %
  176. raster)
  177. ret = dlg.ShowModal()
  178. else:
  179. dlg.Destroy()
  180. marea = self.writeArea(
  181. self._registeredGraphics.GetItem(0).GetCoords(), raster)
  182. self.nextRegion(next=True, area=marea)
  183. break
  184. else:
  185. self.nextRegion(next=False)
  186. break
  187. def nextRegion(self, next=True, area=None):
  188. self.mapWindow.ClearLines()
  189. item = self._registeredGraphics.GetItem(0)
  190. item.SetCoords([])
  191. item.SetPropertyVal('hide', True)
  192. layers = self.map_.GetListOfLayers()
  193. self.mapWindow.ZoomToMap(layers=layers, ignoreNulls=False, render=True)
  194. if next is True:
  195. self.afterRegionDrawn.emit(marea=area)
  196. else:
  197. gcmd.GMessage(parent=self.parent, message=_(
  198. "Raster map not created. Please redraw region."))
  199. def writeArea(self, coords, rasterName):
  200. polyfile = tempfile.NamedTemporaryFile(delete=False)
  201. polyfile.write("AREA\n")
  202. for coor in coords:
  203. east, north = coor
  204. point = " %s %s\n" % (east, north)
  205. polyfile.write(point)
  206. catbuf = "=%d a\n" % self.catId
  207. polyfile.write(catbuf)
  208. self.catId = self.catId + 1
  209. polyfile.close()
  210. region_settings = grass.parse_command('g.region', flags='p',
  211. delimiter=':')
  212. pname = polyfile.name.split('/')[-1]
  213. tmpraster = "rast_" + pname
  214. tmpvector = "vect_" + pname
  215. wx.BeginBusyCursor()
  216. wx.GetApp().Yield()
  217. RunCommand('r.in.poly', input=polyfile.name, output=tmpraster,
  218. rows=region_settings['rows'], overwrite=True)
  219. RunCommand('r.to.vect', input=tmpraster, output=tmpvector,
  220. type='area', overwrite=True)
  221. RunCommand('v.to.rast', input=tmpvector, output=rasterName,
  222. value=1, use='val')
  223. wx.EndBusyCursor()
  224. grass.use_temp_region()
  225. grass.run_command('g.region', vector=tmpvector)
  226. region = grass.region()
  227. marea = MaskedArea(region, rasterName)
  228. RunCommand('g.remove', flags='f', type='raster', name=tmpraster)
  229. RunCommand('g.remove', flags='f', type='vector', name=tmpvector)
  230. os.unlink(polyfile.name)
  231. return marea
  232. def _onToolChanged(self):
  233. """Helper function to disconnect drawing"""
  234. try:
  235. self.mapWindow.mouseLeftUp.disconnect(self._rectangleDrawn)
  236. self.mapWindow.mouseLeftUp.disconnect(self._radiusDrawn)
  237. self.mapWindow.mouseMoving.disconnect(self._mouseMoving)
  238. self.mapWindow.mouseLeftDown.disconnect(self._mouseLeftDown)
  239. self.mapWindow.mouseDClick.disconnect(self._mouseDbClick)
  240. except DispatcherKeyError:
  241. pass
  242. def _radiusDrawn(self, x, y):
  243. """When drawing finished, get region values"""
  244. mouse = self.mapWindow.mouse
  245. item = self._registeredGraphics.GetItem(0)
  246. p1 = mouse['begin']
  247. p2 = mouse['end']
  248. dist, (north, east) = self.mapWindow.Distance(p1, p2, False)
  249. circle = Circle(p1, dist)
  250. self.mapWindow.ClearLines()
  251. self.mapWindow.pdcTmp.SetBrush(wx.Brush(wx.CYAN, wx.TRANSPARENT))
  252. pen = wx.Pen(colour=wx.RED, width=2)
  253. self.mapWindow.pdcTmp.SetPen(pen)
  254. self.mapWindow.pdcTmp.DrawCircle(circle.point[0], circle.point[1],
  255. circle.radius)
  256. self._registeredGraphics.Draw()
  257. self.createCricle(circle)
  258. def createCricle(self, c):
  259. dlg = wx.TextEntryDialog(None,
  260. 'Name of sample circle region',
  261. 'Create circle region',
  262. 'circle' + str(self.catId))
  263. ret = dlg.ShowModal()
  264. while True:
  265. if ret == wx.ID_OK:
  266. raster = dlg.GetValue()
  267. if checkMapExists(raster):
  268. GMessage(
  269. parent=self, message=_(
  270. "The raster file %s already"
  271. " exists, please change name") %
  272. raster)
  273. ret = dlg.ShowModal()
  274. else:
  275. dlg.Destroy()
  276. circle = self.writeCircle(c, raster)
  277. self.nextCircle(next=True, circle=circle)
  278. break
  279. else:
  280. self.nextCircle(next=False)
  281. break
  282. def nextCircle(self, next=True, circle=None):
  283. self.mapWindow.ClearLines()
  284. item = self._registeredGraphics.GetItem(0)
  285. item.SetPropertyVal('hide', True)
  286. layers = self.map_.GetListOfLayers()
  287. self.mapWindow.ZoomToMap(layers=layers, ignoreNulls=False, render=True)
  288. if next is True:
  289. self.afterCircleDrawn.emit(region=circle)
  290. else:
  291. gcmd.GMessage(parent=self.parent, message=_(
  292. "Raster map not created. redraw region again."))
  293. def writeCircle(self, circle, rasterName):
  294. coords = self.mapWindow.Pixel2Cell(circle.point)
  295. RunCommand('r.circle', output=rasterName, max=circle.radius,
  296. coordinate=coords, flags="b")
  297. grass.use_temp_region()
  298. grass.run_command('g.region', zoom=rasterName)
  299. region = grass.region()
  300. marea = MaskedArea(region, rasterName, circle.radius)
  301. return marea
  302. def _rectangleDrawn(self):
  303. """When drawing finished, get region values"""
  304. mouse = self.mapWindow.mouse
  305. item = self._registeredGraphics.GetItem(0)
  306. p1 = self.mapWindow.Pixel2Cell(mouse['begin'])
  307. p2 = self.mapWindow.Pixel2Cell(mouse['end'])
  308. item.SetCoords([p1, p2])
  309. region = {'n': max(p1[1], p2[1]),
  310. 's': min(p1[1], p2[1]),
  311. 'w': min(p1[0], p2[0]),
  312. 'e': max(p1[0], p2[0])}
  313. item.SetPropertyVal('hide', False)
  314. self.mapWindow.ClearLines()
  315. self._registeredGraphics.Draw()
  316. if self.samplingtype in [SamplingType.MUNITSR, SamplingType.MMVWINR]:
  317. dlg = wx.MessageDialog(self, "Is this area ok?",
  318. "select sampling unit",
  319. wx.YES_NO | wx.ICON_QUESTION)
  320. ret = dlg.ShowModal()
  321. if ret == wx.ID_YES:
  322. grass.use_temp_region()
  323. grass.run_command('g.region', n=region['n'], s=region['s'],
  324. e=region['e'], w=region['w'])
  325. tregion = grass.region()
  326. self.sampleFrameChanged.emit(region=tregion)
  327. self.mapWindow.ClearLines()
  328. item = self._registeredGraphics.GetItem(0)
  329. item.SetPropertyVal('hide', True)
  330. layers = self.map_.GetListOfLayers()
  331. self.mapWindow.ZoomToMap(layers=layers, ignoreNulls=False,
  332. render=True)
  333. else:
  334. self.nextRegion(next=False)
  335. dlg.Destroy()
  336. elif self.samplingtype != SamplingType.WHOLE:
  337. """When drawing finished, get region values"""
  338. self.sampleFrameChanged.emit(region=region)
  339. icons = {
  340. 'draw': MetaIcon(
  341. img='edit',
  342. label=_('Draw sampling frame'),
  343. desc=_('Draw sampling frame by clicking and dragging')),
  344. 'digitizeunit': MetaIcon(
  345. img='edit',
  346. label=_('Draw sampling rectangle'),
  347. desc=_('Draw sampling rectangle by clicking and dragging')),
  348. 'digitizeunitc': MetaIcon(
  349. img='line-create',
  350. label=_('Draw sampling circle'),
  351. desc=_('Draw sampling circle radius by clicking and dragging')),
  352. 'digitizeregion': MetaIcon(
  353. img='polygon-create',
  354. label=_('Draw sampling region'),
  355. desc=_('Draw sampling region by polygon. Right Double click to end drawing'))}
  356. class RLiSetupToolbar(BaseToolbar):
  357. """IClass toolbar
  358. """
  359. def __init__(self, parent, toolSwitcher):
  360. """RLiSetup toolbar constructor
  361. """
  362. BaseToolbar.__init__(self, parent, toolSwitcher,
  363. style=wx.NO_BORDER | wx.TB_VERTICAL)
  364. self.InitToolbar(self._toolbarData())
  365. if self.parent.samplingtype == SamplingType.REGIONS:
  366. self._default = self.digitizeregion
  367. elif self.parent.samplingtype in [SamplingType.MUNITSR,
  368. SamplingType.MMVWINR]:
  369. self._default = self.digitizeunit
  370. elif self.parent.samplingtype in [SamplingType.MUNITSC,
  371. SamplingType.MMVWINC]:
  372. self._default = self.digitizeunitc
  373. elif self.parent.samplingtype == SamplingType.VECT:
  374. self._default = None
  375. else:
  376. self._default = self.draw
  377. for tool in (self._default, self.pan, self.zoomIn, self.zoomOut):
  378. if tool:
  379. self.toolSwitcher.AddToolToGroup(group='mouseUse',
  380. toolbar=self, tool=tool)
  381. # realize the toolbar
  382. self.Realize()
  383. def _toolbarData(self):
  384. """Toolbar data"""
  385. if self.parent.samplingtype == SamplingType.REGIONS:
  386. drawTool = ('digitizeregion', icons['digitizeregion'],
  387. self.parent.OnDigitizeRegion, wx.ITEM_CHECK)
  388. elif self.parent.samplingtype in [SamplingType.MUNITSR,
  389. SamplingType.MMVWINR]:
  390. drawTool = ('digitizeunit', icons['digitizeunit'],
  391. self.parent.OnDraw, wx.ITEM_CHECK)
  392. elif self.parent.samplingtype in [SamplingType.MUNITSC,
  393. SamplingType.MMVWINC]:
  394. drawTool = ('digitizeunitc', icons['digitizeunitc'],
  395. self.parent.OnDrawRadius, wx.ITEM_CHECK)
  396. else:
  397. drawTool = ('draw', icons['draw'], self.parent.OnDraw,
  398. wx.ITEM_CHECK)
  399. if self.parent.samplingtype == SamplingType.VECT:
  400. return self._getToolbarData((
  401. ('pan', BaseIcons['pan'], self.parent.OnPan,
  402. wx.ITEM_CHECK),
  403. ('zoomIn', BaseIcons['zoomIn'], self.parent.OnZoomIn,
  404. wx.ITEM_CHECK),
  405. ('zoomOut', BaseIcons['zoomOut'], self.parent.OnZoomOut,
  406. wx.ITEM_CHECK),
  407. ('zoomExtent', BaseIcons['zoomExtent'],
  408. self.parent.OnZoomToMap),))
  409. else:
  410. return self._getToolbarData(
  411. (drawTool, (None,),
  412. ('pan', BaseIcons['pan'],
  413. self.parent.OnPan, wx.ITEM_CHECK),
  414. ('zoomIn', BaseIcons['zoomIn'],
  415. self.parent.OnZoomIn, wx.ITEM_CHECK),
  416. ('zoomOut', BaseIcons['zoomOut'],
  417. self.parent.OnZoomOut, wx.ITEM_CHECK),
  418. ('zoomExtent', BaseIcons['zoomExtent'],
  419. self.parent.OnZoomToMap),))