histogram.py 9.5 KB

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