histogram.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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. self.ptitle = _('Histogram of %s') % self.rasterList[0].split('@')[0]
  95. #
  96. # set xlabel based on first raster map in list to be histogrammed
  97. #
  98. units = self.raster[self.rasterList[0]]['units']
  99. if units != '' and units != '(none)' and units != None:
  100. self.xlabel = _('Raster cell values %s') % units
  101. else:
  102. self.xlabel = _('Raster cell values')
  103. #
  104. # set ylabel from self.histtype
  105. #
  106. if self.histtype == 'count': self.ylabel = _('Cell counts')
  107. if self.histtype == 'percent': self.ylabel = _('Percent of total cells')
  108. if self.histtype == 'area': self.ylabel = _('Area')
  109. def CreateDatalist(self, raster):
  110. """!Build a list of cell value, frequency pairs for histogram
  111. frequency can be in cell counts, percents, or area
  112. """
  113. datalist = []
  114. if self.histtype == 'count': freqflag = 'cn'
  115. if self.histtype == 'percent': freqflag = 'pn'
  116. if self.histtype == 'area': freqflag = 'an'
  117. try:
  118. ret = RunCommand("r.stats",
  119. parent = self,
  120. input = raster,
  121. flags = freqflag,
  122. nsteps = self.bins,
  123. fs = ',',
  124. quiet = True,
  125. read = True)
  126. if not ret:
  127. return datalist
  128. for line in ret.splitlines():
  129. cellval, histval = line.strip().split(',')
  130. histval = histval.strip()
  131. if self.raster[raster]['datatype'] != 'CELL':
  132. if cellval[0] == '-':
  133. cellval = '-' + cellval.split('-')[1]
  134. else:
  135. cellval = cellval.split('-')[0]
  136. if self.histtype == 'percent':
  137. histval = histval.rstrip('%')
  138. datalist.append((cellval,histval))
  139. return datalist
  140. except GException, e:
  141. GError(parent = self,
  142. message = e.value)
  143. return None
  144. def CreatePlotList(self):
  145. """!Make list of elements to plot
  146. """
  147. # graph the cell value, frequency pairs for the histogram
  148. self.plotlist = []
  149. for r in self.rasterList:
  150. if len(self.raster[r]['datalist']) > 0:
  151. col = wx.Color(self.raster[r]['pcolor'][0],
  152. self.raster[r]['pcolor'][1],
  153. self.raster[r]['pcolor'][2],
  154. 255)
  155. self.raster[r]['pline'] = plot.PolyLine(self.raster[r]['datalist'],
  156. colour = col,
  157. width = self.raster[r]['pwidth'],
  158. style = self.linestyledict[self.raster[r]['pstyle']],
  159. legend = self.raster[r]['plegend'])
  160. self.plotlist.append(self.raster[r]['pline'])
  161. if len(self.plotlist) > 0:
  162. return self.plotlist
  163. else:
  164. return None
  165. def Update(self):
  166. """!Update histogram after changing options
  167. """
  168. self.SetGraphStyle()
  169. p = self.CreatePlotList()
  170. self.DrawPlot(p)
  171. def OnStats(self, event):
  172. """!Displays regression information in messagebox
  173. """
  174. message = []
  175. title = _('Statistics for Map(s) Histogrammed')
  176. for rast in self.rasterList:
  177. ret = grass.read_command('r.univar', map = r, flags = 'e', quiet = True)
  178. stats = _('Statistics for raster map <%s>') % rast + ':\n%s\n' % ret
  179. message.append(stats)
  180. stats = PlotStatsFrame(self, id = wx.ID_ANY, message = message,
  181. title = title)
  182. if stats.Show() == wx.ID_CLOSE:
  183. stats.Destroy()
  184. class Histogram2Toolbar(BaseToolbar):
  185. """!Toolbar for histogramming raster map
  186. """
  187. def __init__(self, parent):
  188. BaseToolbar.__init__(self, parent)
  189. self.InitToolbar(self._toolbarData())
  190. # realize the toolbar
  191. self.Realize()
  192. def _toolbarData(self):
  193. """!Toolbar data"""
  194. return self._getToolbarData((('addraster', BaseIcons["addRast"],
  195. self.parent.OnSelectRaster),
  196. (None, ),
  197. ('draw', PlotIcons["draw"],
  198. self.parent.OnCreateHist),
  199. ('erase', BaseIcons["erase"],
  200. self.parent.OnErase),
  201. ('drag', BaseIcons['pan'],
  202. self.parent.OnDrag),
  203. ('zoom', BaseIcons['zoomIn'],
  204. self.parent.OnZoom),
  205. ('unzoom', BaseIcons['zoomBack'],
  206. self.parent.OnRedraw),
  207. (None, ),
  208. ('statistics', PlotIcons['statistics'],
  209. self.parent.OnStats),
  210. ('image', BaseIcons["saveFile"],
  211. self.parent.SaveToFile),
  212. ('print', BaseIcons["print"],
  213. self.parent.PrintMenu),
  214. (None, ),
  215. ('settings', PlotIcons["options"],
  216. self.parent.PlotOptionsMenu),
  217. ('quit', PlotIcons["quit"],
  218. self.parent.OnQuit),
  219. )
  220. )