profile.py 18 KB

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