histogram.py 10 KB

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