sampling_frame.py 18 KB

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