histogram.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. """
  2. @package wxplot.histogram
  3. @brief Histogramming using PyPlot
  4. Classes:
  5. - histogram::HistogramPlotFrame
  6. - histogram::HistogramPlotToolbar
  7. (C) 2011-2013 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 sys
  13. import wx
  14. from core.globalvar import CheckWxVersion
  15. try:
  16. if CheckWxVersion(version=[3, 0, 0]):
  17. import gui_core.wxlibplot as plot
  18. else:
  19. import wx.lib.plot as plot
  20. except ImportError as e:
  21. print >> sys.stderr, e
  22. import grass.script as grass
  23. from gui_core.toolbars import BaseToolbar, BaseIcons
  24. from wxplot.base import BasePlotFrame, PlotIcons
  25. from wxplot.dialogs import HistRasterDialog, PlotStatsFrame
  26. from core.gcmd import RunCommand, GException, GError
  27. from core.utils import _
  28. class HistogramPlotFrame(BasePlotFrame):
  29. """Mainframe for displaying histogram of raster map. Uses wx.lib.plot.
  30. """
  31. def __init__(self, parent, id=wx.ID_ANY, style=wx.DEFAULT_FRAME_STYLE,
  32. size=wx.Size(700, 400), rasterList=[], **kwargs):
  33. BasePlotFrame.__init__(self, parent, size=size, **kwargs)
  34. self.toolbar = HistogramPlotToolbar(parent=self)
  35. # workaround for http://trac.wxwidgets.org/ticket/13888
  36. if sys.platform != 'darwin':
  37. self.SetToolBar(self.toolbar)
  38. self.SetTitle(_("GRASS GIS Histogramming Tool"))
  39. #
  40. # Init variables
  41. #
  42. self.rasterList = rasterList
  43. self.plottype = 'histogram'
  44. self.group = ''
  45. self.ptitle = _('Histogram of') # title of window
  46. self.xlabel = _("Raster cell values") # default X-axis label
  47. self.ylabel = _("Cell counts") # default Y-axis label
  48. self.maptype = 'raster' # default type of histogram to plot
  49. self.histtype = 'count'
  50. self.bins = 255
  51. self.colorList = [
  52. "blue",
  53. "green",
  54. "red",
  55. "yellow",
  56. "magenta",
  57. "cyan",
  58. "aqua",
  59. "black",
  60. "grey",
  61. "orange",
  62. "brown",
  63. "purple",
  64. "violet",
  65. "indigo"]
  66. self._initOpts()
  67. if len(
  68. self.rasterList) > 0: # set raster name(s) from layer manager if a map is selected
  69. self.raster = self.InitRasterOpts(self.rasterList, self.plottype)
  70. wx.CallAfter(self.OnCreateHist, None)
  71. else:
  72. self.raster = {}
  73. def _initOpts(self):
  74. """Initialize plot options
  75. """
  76. self.InitPlotOpts('histogram')
  77. def OnCreateHist(self, event):
  78. """Main routine for creating a histogram. Uses r.stats to
  79. create a list of cell value and count/percent/area pairs. This is passed to
  80. plot to create a line graph of the histogram.
  81. """
  82. try:
  83. self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
  84. except:
  85. pass
  86. self.SetGraphStyle()
  87. wx.BeginBusyCursor()
  88. wx.SafeYield()
  89. self.SetupHistogram()
  90. p = self.CreatePlotList()
  91. self.DrawPlot(p)
  92. wx.EndBusyCursor()
  93. def OnSelectRaster(self, event):
  94. """Select raster map(s) to profile
  95. """
  96. dlg = HistRasterDialog(parent=self)
  97. if dlg.ShowModal() == wx.ID_OK:
  98. self.rasterList = dlg.rasterList
  99. self.group = dlg.group
  100. self.bins = dlg.bins
  101. self.histtype = dlg.histtype
  102. self.maptype = dlg.maptype
  103. self.raster = self.InitRasterOpts(self.rasterList, self.plottype)
  104. # plot histogram
  105. if len(self.rasterList) > 0:
  106. self.OnCreateHist(event=None)
  107. dlg.Destroy()
  108. def SetupHistogram(self):
  109. """Build data list for ploting each raster
  110. """
  111. #
  112. # populate raster dictionary
  113. #
  114. if len(self.rasterList) == 0:
  115. return # nothing selected
  116. for r in self.rasterList:
  117. self.raster[r]['datalist'] = self.CreateDatalist(r)
  118. #
  119. # update title
  120. #
  121. if self.maptype == 'group':
  122. self.ptitle = _('Histogram of image group <%s>') % self.group
  123. else:
  124. if len(self.rasterList) == 1:
  125. self.ptitle = _(
  126. 'Histogram of raster map <%s>') % self.rasterList[0]
  127. else:
  128. self.ptitle = _('Histogram of selected raster maps')
  129. #
  130. # set xlabel based on first raster map in list to be histogrammed
  131. #
  132. units = self.raster[self.rasterList[0]]['units']
  133. if units != '' and units != '(none)' and units is not None:
  134. self.xlabel = _('Raster cell values %s') % units
  135. else:
  136. self.xlabel = _('Raster cell values')
  137. #
  138. # set ylabel from self.histtype
  139. #
  140. if self.histtype == 'count':
  141. self.ylabel = _('Cell counts')
  142. if self.histtype == 'percent':
  143. self.ylabel = _('Percent of total cells')
  144. if self.histtype == 'area':
  145. self.ylabel = _('Area')
  146. def CreateDatalist(self, raster):
  147. """Build a list of cell value, frequency pairs for histogram
  148. frequency can be in cell counts, percents, or area
  149. """
  150. datalist = []
  151. if self.histtype == 'count':
  152. freqflag = 'cn'
  153. if self.histtype == 'percent':
  154. freqflag = 'pn'
  155. if self.histtype == 'area':
  156. freqflag = 'an'
  157. try:
  158. ret = RunCommand("r.stats",
  159. parent=self,
  160. input=raster,
  161. flags=freqflag,
  162. nsteps=self.bins,
  163. sep=',',
  164. quiet=True,
  165. read=True)
  166. if not ret:
  167. return datalist
  168. for line in ret.splitlines():
  169. cellval, histval = line.strip().split(',')
  170. histval = histval.strip()
  171. if self.raster[raster]['datatype'] != 'CELL':
  172. if cellval[0] == '-':
  173. cellval = '-' + cellval.split('-')[1]
  174. else:
  175. cellval = cellval.split('-')[0]
  176. if self.histtype == 'percent':
  177. histval = histval.rstrip('%')
  178. datalist.append((cellval, histval))
  179. return datalist
  180. except GException as e:
  181. GError(parent=self,
  182. message=e.value)
  183. return None
  184. def CreatePlotList(self):
  185. """Make list of elements to plot
  186. """
  187. # graph the cell value, frequency pairs for the histogram
  188. self.plotlist = []
  189. for r in self.rasterList:
  190. if len(self.raster[r]['datalist']) > 0:
  191. col = wx.Colour(self.raster[r]['pcolor'][0],
  192. self.raster[r]['pcolor'][1],
  193. self.raster[r]['pcolor'][2],
  194. 255)
  195. self.raster[r]['pline'] = plot.PolyLine(
  196. self.raster[r]['datalist'],
  197. colour=col, width=self.raster[r]['pwidth'],
  198. style=self.linestyledict[self.raster[r]['pstyle']],
  199. legend=self.raster[r]['plegend'])
  200. self.plotlist.append(self.raster[r]['pline'])
  201. if len(self.plotlist) > 0:
  202. return self.plotlist
  203. else:
  204. return None
  205. def Update(self):
  206. """Update histogram after changing options
  207. """
  208. self.SetGraphStyle()
  209. p = self.CreatePlotList()
  210. self.DrawPlot(p)
  211. def OnStats(self, event):
  212. """Displays regression information in messagebox
  213. """
  214. message = []
  215. title = _('Statistics for Map(s) Histogrammed')
  216. for rast in self.rasterList:
  217. ret = grass.read_command(
  218. 'r.univar', map=rast, flags='e', quiet=True)
  219. stats = _('Statistics for raster map <%s>') % rast + ':\n%s\n' % ret
  220. message.append(stats)
  221. stats = PlotStatsFrame(self, id=wx.ID_ANY, message=message,
  222. title=title)
  223. if stats.Show() == wx.ID_CLOSE:
  224. stats.Destroy()
  225. class HistogramPlotToolbar(BaseToolbar):
  226. """Toolbar for histogramming raster map
  227. """
  228. def __init__(self, parent):
  229. BaseToolbar.__init__(self, parent)
  230. # workaround for http://trac.wxwidgets.org/ticket/13888
  231. if sys.platform == 'darwin':
  232. parent.SetToolBar(self)
  233. self.InitToolbar(self._toolbarData())
  234. # realize the toolbar
  235. self.Realize()
  236. def _toolbarData(self):
  237. """Toolbar data"""
  238. return self._getToolbarData((('addraster', BaseIcons["addRast"],
  239. self.parent.OnSelectRaster),
  240. (None, ),
  241. ('draw', PlotIcons["draw"],
  242. self.parent.OnCreateHist),
  243. ('erase', BaseIcons["erase"],
  244. self.parent.OnErase),
  245. ('drag', BaseIcons['pan'],
  246. self.parent.OnDrag),
  247. ('zoom', BaseIcons['zoomIn'],
  248. self.parent.OnZoom),
  249. ('unzoom', BaseIcons['zoomExtent'],
  250. self.parent.OnRedraw),
  251. (None, ),
  252. ('statistics', PlotIcons['statistics'],
  253. self.parent.OnStats),
  254. ('image', BaseIcons["saveFile"],
  255. self.parent.SaveToFile),
  256. ('print', BaseIcons["print"],
  257. self.parent.PrintMenu),
  258. (None, ),
  259. ('settings', PlotIcons["options"],
  260. self.parent.PlotOptionsMenu),
  261. ('quit', PlotIcons["quit"],
  262. self.parent.OnQuit),
  263. )
  264. )