histogram.py 9.9 KB

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