histogram.py 10 KB

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