profile.py 18 KB

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