profile.py 18 KB

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