histogram.py 10 KB

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