sampling_frame.py 18 KB

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