profile.py 18 KB

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