profile.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. """
  2. @package wxplot.profile
  3. @brief Profiling using PyPlot
  4. Classes:
  5. - profile::ProfileFrame
  6. - profile::ProfileToolbar
  7. (C) 2011-2014 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 Michael Barton, Arizona State University
  11. """
  12. import os
  13. import sys
  14. import math
  15. import wx
  16. from core.globalvar import CheckWxVersion
  17. try:
  18. if CheckWxVersion(version=[3, 0, 0]):
  19. import gui_core.wxlibplot as plot
  20. else:
  21. import wx.lib.plot as plot
  22. except ImportError as e:
  23. print >> sys.stderr, e
  24. import grass.script as grass
  25. from core.utils import _
  26. try:
  27. import numpy
  28. except ImportError:
  29. msg = _("This module requires the NumPy module, which could not be "
  30. "imported. It probably is not installed (it's not part of the "
  31. "standard Python distribution). See the Numeric Python site "
  32. "(http://numpy.scipy.org) for information on downloading source or "
  33. "binaries.")
  34. print >> sys.stderr, "wxplot.py: " + msg
  35. from wxplot.base import BasePlotFrame, PlotIcons
  36. from gui_core.toolbars import BaseToolbar, BaseIcons
  37. from wxplot.dialogs import ProfileRasterDialog, PlotStatsFrame
  38. from core.gcmd import RunCommand, GWarning, GError, GMessage
  39. class ProfileFrame(BasePlotFrame):
  40. """Mainframe for displaying profile of one or more raster maps. Uses wx.lib.plot.
  41. """
  42. def __init__(self, parent, controller, units, size=wx.Size(700, 400),
  43. rasterList = None, **kwargs):
  44. BasePlotFrame.__init__(self, parent=parent, size=size, **kwargs)
  45. self.controller = controller
  46. self.controller.transectChanged.connect(self.SetTransect)
  47. self.transect = []
  48. self.toolbar = ProfileToolbar(parent = self)
  49. # workaround for http://trac.wxwidgets.org/ticket/13888
  50. if sys.platform != 'darwin':
  51. self.SetToolBar(self.toolbar)
  52. self.SetTitle(_("GRASS Profile Analysis Tool"))
  53. # in case of degrees, we want to use meters
  54. self._units = units if 'degree' not in units else 'meters'
  55. #
  56. # Init variables
  57. #
  58. if rasterList is None:
  59. self.rasterList = []
  60. else:
  61. self.rasterList = rasterList
  62. self.plottype = 'profile'
  63. self.coordstr = '' # string of coordinates for r.profile
  64. self.seglist = [] # segment endpoint list
  65. self.ppoints = '' # segment endpoints data
  66. self.transect_length = 0.0 # total transect length
  67. self.ptitle = _('Profile of') # title of window
  68. self.colorList = ["blue", "red", "green", "yellow", "magenta", "cyan",
  69. "aqua", "black", "grey", "orange", "brown", "purple", "violet",
  70. "indigo"]
  71. self._initOpts()
  72. if len(self.rasterList) > 0: # set raster name(s) from layer manager if a map is selected
  73. self.raster = self.InitRasterOpts(self.rasterList, self.plottype)
  74. else:
  75. self.raster = {}
  76. # determine units (axis labels)
  77. # maybe, we should not accept these invalid units
  78. # but ok, trying to handle it here
  79. if self._units is not None and self._units != '':
  80. self.xlabel = _('Distance (%s)') % self._units
  81. else:
  82. self.xlabel = _("Distance along transect")
  83. self.ylabel = _("Cell values")
  84. # Bind events
  85. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  86. def _initOpts(self):
  87. """Initialize plot options
  88. """
  89. self.InitPlotOpts('profile')
  90. def SetTransect(self, coords):
  91. self.transect = coords
  92. if coords:
  93. self.OnCreateProfile(None)
  94. else:
  95. self.OnErase(None)
  96. def OnDrawTransect(self, event):
  97. """Draws transect to profile in map display
  98. """
  99. if self.controller.IsActive():
  100. self.controller.Stop()
  101. self.controller.Start()
  102. self.parent.SetFocus()
  103. self.parent.Raise()
  104. def OnSelectRaster(self, event):
  105. """Select raster map(s) to profile
  106. """
  107. dlg = ProfileRasterDialog(parent = self)
  108. dlg.CenterOnParent()
  109. if dlg.ShowModal() == wx.ID_OK:
  110. self.rasterList = dlg.rasterList
  111. self.raster = self.InitRasterOpts(self.rasterList, self.plottype)
  112. # plot profile
  113. if len(self.transect) > 0 and len(self.rasterList) > 0:
  114. self.OnCreateProfile(event = None)
  115. dlg.Destroy()
  116. def SetupProfile(self):
  117. """Create coordinate string for profiling. Create segment
  118. list for transect segment markers.
  119. """
  120. # create list of coordinate points for r.profile
  121. dist = 0
  122. cumdist = 0
  123. self.coordstr = ''
  124. lasteast = lastnorth = None
  125. region = grass.region()
  126. insideRegion = True
  127. if len(self.transect) > 0:
  128. for point in self.transect:
  129. if not (region['w'] <= point[0] <= region['e'] and region['s'] <= point[1] <= region['n']):
  130. insideRegion = False
  131. # build string of coordinate points for r.profile
  132. if self.coordstr == '':
  133. self.coordstr = '%f,%f' % (point[0], point[1])
  134. else:
  135. self.coordstr = '%s,%f,%f' % (self.coordstr, point[0], point[1])
  136. if not insideRegion:
  137. GWarning(message = _("Not all points of profile lie inside computational region."),
  138. parent = self)
  139. if len(self.rasterList) == 0:
  140. return
  141. # title of window
  142. self.ptitle = _('Profile of')
  143. # create list of coordinates for transect segment markers
  144. if len(self.transect) > 0:
  145. self.seglist = []
  146. for point in self.transect:
  147. # get value of raster cell at coordinate point
  148. ret = RunCommand('r.what',
  149. parent = self,
  150. read = True,
  151. map = self.rasterList[0],
  152. coordinates = '%f,%f' % (point[0], point[1]))
  153. val = ret.splitlines()[0].split('|')[3]
  154. if val == None or val == '*':
  155. continue
  156. val = float(val)
  157. # calculate distance between coordinate points
  158. if lasteast and lastnorth:
  159. dist = math.sqrt(math.pow((lasteast-point[0]),2) + math.pow((lastnorth-point[1]),2))
  160. cumdist += dist
  161. # store total transect length
  162. self.transect_length = cumdist
  163. # build a list of distance,value pairs for each segment of transect
  164. self.seglist.append((cumdist,val))
  165. lasteast = point[0]
  166. lastnorth = point[1]
  167. # delete extra first segment point
  168. try:
  169. self.seglist.pop(0)
  170. except:
  171. pass
  172. #
  173. # create datalist of dist/value pairs and y labels for each raster map
  174. #
  175. self.ylabel = ''
  176. i = 0
  177. for r in self.raster.iterkeys():
  178. self.raster[r]['datalist'] = []
  179. datalist = self.CreateDatalist(r, self.coordstr)
  180. if len(datalist) > 0:
  181. self.raster[r]['datalist'] = datalist
  182. # update ylabel to match units if they exist
  183. if self.raster[r]['units'] != '':
  184. self.ylabel += '%s (%d),' % (self.raster[r]['units'], i)
  185. i += 1
  186. # update title
  187. self.ptitle += ' %s ,' % r.split('@')[0]
  188. self.ptitle = self.ptitle.rstrip(',')
  189. if self.ylabel == '':
  190. self.ylabel = _('Raster values')
  191. else:
  192. self.ylabel = self.ylabel.rstrip(',')
  193. def CreateDatalist(self, raster, coords):
  194. """Build a list of distance, value pairs for points along transect using r.profile
  195. """
  196. datalist = []
  197. # keep total number of transect points to 500 or less to avoid
  198. # freezing with large, high resolution maps
  199. region = grass.region()
  200. curr_res = min(float(region['nsres']),float(region['ewres']))
  201. transect_rec = 0
  202. if self.transect_length / curr_res > 500:
  203. transect_res = self.transect_length / 500
  204. else: transect_res = curr_res
  205. ret = RunCommand("r.profile",
  206. parent = self,
  207. input = raster,
  208. coordinates = coords,
  209. resolution = transect_res,
  210. null = "nan",
  211. quiet = True,
  212. read = True)
  213. if not ret:
  214. return []
  215. for line in ret.splitlines():
  216. dist, elev = line.strip().split(' ')
  217. if dist == None or dist == '' or dist == 'nan' or \
  218. elev == None or elev == '' or elev == 'nan':
  219. continue
  220. dist = float(dist)
  221. elev = float(elev)
  222. datalist.append((dist,elev))
  223. return datalist
  224. def OnCreateProfile(self, event):
  225. """Main routine for creating a profile. Uses r.profile to
  226. create a list of distance,cell value pairs. This is passed to
  227. plot to create a line graph of the profile. If the profile
  228. transect is in multiple segments, these are drawn as
  229. points. Profile transect is drawn, using methods in mapdisp.py
  230. """
  231. if len(self.transect) == 0 or len(self.rasterList) == 0:
  232. dlg = wx.MessageDialog(parent = self,
  233. message = _('You must draw a transect to profile in the map display window.'),
  234. caption = _('Nothing to profile'),
  235. style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  236. dlg.ShowModal()
  237. dlg.Destroy()
  238. return
  239. self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
  240. self.SetupProfile()
  241. p = self.CreatePlotList()
  242. self.DrawPlot(p)
  243. def CreatePlotList(self):
  244. """Create a plot data list from transect datalist and
  245. transect segment endpoint coordinates.
  246. """
  247. # graph the distance, value pairs for the transect
  248. self.plotlist = []
  249. # Add segment marker points to plot data list
  250. if len(self.seglist) > 0 :
  251. self.ppoints = plot.PolyMarker(self.seglist,
  252. legend = ' ' + self.properties['marker']['legend'],
  253. colour = wx.Colour(self.properties['marker']['color'][0],
  254. self.properties['marker']['color'][1],
  255. self.properties['marker']['color'][2],
  256. 255),
  257. size = self.properties['marker']['size'],
  258. fillstyle = self.ptfilldict[self.properties['marker']['fill']],
  259. marker = self.properties['marker']['type'])
  260. self.plotlist.append(self.ppoints)
  261. # Add profile distance/elevation pairs to plot data list for each raster profiled
  262. for r in self.rasterList:
  263. col = wx.Colour(self.raster[r]['pcolor'][0],
  264. self.raster[r]['pcolor'][1],
  265. self.raster[r]['pcolor'][2],
  266. 255)
  267. self.raster[r]['pline'] = plot.PolyLine(self.raster[r]['datalist'],
  268. colour = col,
  269. width = self.raster[r]['pwidth'],
  270. style = self.linestyledict[self.raster[r]['pstyle']],
  271. legend = self.raster[r]['plegend'])
  272. self.plotlist.append(self.raster[r]['pline'])
  273. if len(self.plotlist) > 0:
  274. return self.plotlist
  275. else:
  276. return None
  277. def Update(self):
  278. """Update profile after changing options
  279. """
  280. self.SetGraphStyle()
  281. p = self.CreatePlotList()
  282. self.DrawPlot(p)
  283. def SaveProfileToFile(self, event):
  284. """Save r.profile data to a csv file
  285. """
  286. dlg = wx.FileDialog(parent = self,
  287. message = _("Choose prefix for file(s) where to save profile values..."),
  288. defaultDir = os.getcwd(),
  289. wildcard = _("Comma separated value (*.csv)|*.csv"), style = wx.FD_SAVE)
  290. pfile = []
  291. if dlg.ShowModal() == wx.ID_OK:
  292. path = dlg.GetPath()
  293. for r in self.rasterList:
  294. pfile.append(path + '_' + str(r.replace('@', '_')) + '.csv')
  295. if os.path.exists(pfile[-1]):
  296. dlgOv = wx.MessageDialog(self,
  297. message = _("File <%s> already exists. "
  298. "Do you want to overwrite this file?") % pfile[-1],
  299. caption = _("Overwrite file?"),
  300. style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  301. if dlgOv.ShowModal() != wx.ID_YES:
  302. pfile.pop()
  303. dlgOv.Destroy()
  304. continue
  305. try:
  306. fd = open(pfile[-1], "w")
  307. except IOError as e:
  308. GError(parent = self,
  309. message = _("Unable to open file <%s> for writing.\n"
  310. "Reason: %s") % (pfile[-1], e))
  311. dlg.Destroy()
  312. return
  313. for datapair in self.raster[r]['datalist']:
  314. fd.write('%.6f,%.6f\n' % (float(datapair[0]),float(datapair[1])))
  315. fd.close()
  316. dlg.Destroy()
  317. if pfile:
  318. message = _("%d files created:\n%s") % (len(pfile), '\n'.join(pfile))
  319. else:
  320. message = _("No files generated.")
  321. GMessage(parent = self, message = message)
  322. def OnStats(self, event):
  323. """Displays regression information in messagebox
  324. """
  325. message = []
  326. title = _('Statistics for Profile(s)')
  327. for r in self.raster.iterkeys():
  328. try:
  329. rast = r.split('@')[0]
  330. statstr = 'Profile of %s\n\n' % rast
  331. iterable = (i[1] for i in self.raster[r]['datalist'])
  332. a = numpy.fromiter(iterable, numpy.float)
  333. statstr += 'n: %f\n' % a.size
  334. statstr += 'minimum: %f\n' % numpy.amin(a)
  335. statstr += 'maximum: %f\n' % numpy.amax(a)
  336. statstr += 'range: %f\n' % numpy.ptp(a)
  337. statstr += 'mean: %f\n' % numpy.mean(a)
  338. statstr += 'standard deviation: %f\n' % numpy.std(a)
  339. statstr += 'variance: %f\n' % numpy.var(a)
  340. cv = numpy.std(a)/numpy.mean(a)
  341. statstr += 'coefficient of variation: %f\n' % cv
  342. statstr += 'sum: %f\n' % numpy.sum(a)
  343. statstr += 'median: %f\n' % numpy.median(a)
  344. statstr += 'distance along transect: %f\n\n' % self.transect_length
  345. message.append(statstr)
  346. except:
  347. pass
  348. stats = PlotStatsFrame(self, id = wx.ID_ANY, message = message,
  349. title = title)
  350. if stats.Show() == wx.ID_CLOSE:
  351. stats.Destroy()
  352. def OnCloseWindow(self, event):
  353. if self.controller.IsActive():
  354. self.controller.Stop()
  355. self.Destroy()
  356. class ProfileToolbar(BaseToolbar):
  357. """Toolbar for profiling raster map
  358. """
  359. def __init__(self, parent):
  360. BaseToolbar.__init__(self, parent)
  361. # workaround for http://trac.wxwidgets.org/ticket/13888
  362. if sys.platform == 'darwin':
  363. parent.SetToolBar(self)
  364. self.InitToolbar(self._toolbarData())
  365. # realize the toolbar
  366. self.Realize()
  367. def _toolbarData(self):
  368. """Toolbar data"""
  369. return self._getToolbarData((('addraster', BaseIcons["addRast"],
  370. self.parent.OnSelectRaster),
  371. ('transect', PlotIcons["transect"],
  372. self.parent.OnDrawTransect),
  373. (None, ),
  374. ('draw', PlotIcons["draw"],
  375. self.parent.OnCreateProfile),
  376. ('erase', BaseIcons["erase"],
  377. self.parent.OnErase),
  378. ('drag', BaseIcons['pan'],
  379. self.parent.OnDrag),
  380. ('zoom', BaseIcons['zoomIn'],
  381. self.parent.OnZoom),
  382. ('unzoom', BaseIcons['zoomBack'],
  383. self.parent.OnRedraw),
  384. (None, ),
  385. ('statistics', PlotIcons['statistics'],
  386. self.parent.OnStats),
  387. ('datasave', PlotIcons["save"],
  388. self.parent.SaveProfileToFile),
  389. ('image', BaseIcons["saveFile"],
  390. self.parent.SaveToFile),
  391. ('print', BaseIcons["print"],
  392. self.parent.PrintMenu),
  393. (None, ),
  394. ('settings', PlotIcons["options"],
  395. self.parent.PlotOptionsMenu),
  396. ('quit', PlotIcons["quit"],
  397. self.parent.OnQuit),
  398. ))