histogram.py 9.7 KB

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