histogram.py 10 KB

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