histogram.py 11 KB

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