histogram.py 10 KB

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