histogram.py 10 KB

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