sampling_frame.py 18 KB

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