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