profile.py 18 KB

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