profile.py 17 KB

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