histogram.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. """!
  2. @package wxplot.histogram
  3. @brief Histogramming using PyPlot
  4. Classes:
  5. - histogram::HistogramPlotFrame
  6. - histogram::HistogramPlotToolbar
  7. (C) 2011 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 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(self.parent.cursors["default"])
  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 %s') % self.group.split('@')[0]
  97. else:
  98. rastText = ''
  99. for r in self.rasterList:
  100. rs = r.split('@')[0]
  101. rastText += '%s, ' % rs
  102. rastText = rastText.rstrip(', ')
  103. self.ptitle = _('Histogram of %s') % rastText
  104. #
  105. # set xlabel based on first raster map in list to be histogrammed
  106. #
  107. units = self.raster[self.rasterList[0]]['units']
  108. if units != '' and units != '(none)' and units != None:
  109. self.xlabel = _('Raster cell values %s') % units
  110. else:
  111. self.xlabel = _('Raster cell values')
  112. #
  113. # set ylabel from self.histtype
  114. #
  115. if self.histtype == 'count': self.ylabel = _('Cell counts')
  116. if self.histtype == 'percent': self.ylabel = _('Percent of total cells')
  117. if self.histtype == 'area': self.ylabel = _('Area')
  118. def CreateDatalist(self, raster):
  119. """!Build a list of cell value, frequency pairs for histogram
  120. frequency can be in cell counts, percents, or area
  121. """
  122. datalist = []
  123. if self.histtype == 'count': freqflag = 'cn'
  124. if self.histtype == 'percent': freqflag = 'pn'
  125. if self.histtype == 'area': freqflag = 'an'
  126. try:
  127. ret = RunCommand("r.stats",
  128. parent = self,
  129. input = raster,
  130. flags = freqflag,
  131. nsteps = self.bins,
  132. sep = ',',
  133. quiet = True,
  134. read = True)
  135. if not ret:
  136. return datalist
  137. for line in ret.splitlines():
  138. cellval, histval = line.strip().split(',')
  139. histval = histval.strip()
  140. if self.raster[raster]['datatype'] != 'CELL':
  141. if cellval[0] == '-':
  142. cellval = '-' + cellval.split('-')[1]
  143. else:
  144. cellval = cellval.split('-')[0]
  145. if self.histtype == 'percent':
  146. histval = histval.rstrip('%')
  147. datalist.append((cellval,histval))
  148. return datalist
  149. except GException, e:
  150. GError(parent = self,
  151. message = e.value)
  152. return None
  153. def CreatePlotList(self):
  154. """!Make list of elements to plot
  155. """
  156. # graph the cell value, frequency pairs for the histogram
  157. self.plotlist = []
  158. for r in self.rasterList:
  159. if len(self.raster[r]['datalist']) > 0:
  160. col = wx.Colour(self.raster[r]['pcolor'][0],
  161. self.raster[r]['pcolor'][1],
  162. self.raster[r]['pcolor'][2],
  163. 255)
  164. self.raster[r]['pline'] = plot.PolyLine(self.raster[r]['datalist'],
  165. colour = col,
  166. width = self.raster[r]['pwidth'],
  167. style = self.linestyledict[self.raster[r]['pstyle']],
  168. legend = self.raster[r]['plegend'])
  169. self.plotlist.append(self.raster[r]['pline'])
  170. if len(self.plotlist) > 0:
  171. return self.plotlist
  172. else:
  173. return None
  174. def Update(self):
  175. """!Update histogram after changing options
  176. """
  177. self.SetGraphStyle()
  178. p = self.CreatePlotList()
  179. self.DrawPlot(p)
  180. def OnStats(self, event):
  181. """!Displays regression information in messagebox
  182. """
  183. message = []
  184. title = _('Statistics for Map(s) Histogrammed')
  185. for rast in self.rasterList:
  186. ret = grass.read_command('r.univar', map = rast, flags = 'e', quiet = True)
  187. stats = _('Statistics for raster map <%s>') % rast + ':\n%s\n' % ret
  188. message.append(stats)
  189. stats = PlotStatsFrame(self, id = wx.ID_ANY, message = message,
  190. title = title)
  191. if stats.Show() == wx.ID_CLOSE:
  192. stats.Destroy()
  193. class HistogramPlotToolbar(BaseToolbar):
  194. """!Toolbar for histogramming raster map
  195. """
  196. def __init__(self, parent):
  197. BaseToolbar.__init__(self, parent)
  198. self.InitToolbar(self._toolbarData())
  199. # realize the toolbar
  200. self.Realize()
  201. def _toolbarData(self):
  202. """!Toolbar data"""
  203. return self._getToolbarData((('addraster', BaseIcons["addRast"],
  204. self.parent.OnSelectRaster),
  205. (None, ),
  206. ('draw', PlotIcons["draw"],
  207. self.parent.OnCreateHist),
  208. ('erase', BaseIcons["erase"],
  209. self.parent.OnErase),
  210. ('drag', BaseIcons['pan'],
  211. self.parent.OnDrag),
  212. ('zoom', BaseIcons['zoomIn'],
  213. self.parent.OnZoom),
  214. ('unzoom', BaseIcons['zoomBack'],
  215. self.parent.OnRedraw),
  216. (None, ),
  217. ('statistics', PlotIcons['statistics'],
  218. self.parent.OnStats),
  219. ('image', BaseIcons["saveFile"],
  220. self.parent.SaveToFile),
  221. ('print', BaseIcons["print"],
  222. self.parent.PrintMenu),
  223. (None, ),
  224. ('settings', PlotIcons["options"],
  225. self.parent.PlotOptionsMenu),
  226. ('quit', PlotIcons["quit"],
  227. self.parent.OnQuit),
  228. )
  229. )