histogram.py 11 KB

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