profile.py 18 KB

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