profile.py 17 KB

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