histogram.py 9.6 KB

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