profile.py 18 KB

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