histogram.py 10 KB

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