profile.py 17 KB

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