histogram.py 9.7 KB

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