histogram.py 10 KB

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