plots.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. """
  2. @package iclass.plots
  3. @brief wxIClass plots (histograms, coincidence plots).
  4. Classes:
  5. - plots::PlotPanel
  6. (C) 2006-2011,2013 by the GRASS Development Team
  7. This program is free software under the GNU General Public
  8. License (>=v2). Read the file COPYING that comes with GRASS
  9. for details.
  10. @author Vaclav Petras <wenzeslaus gmail.com>
  11. @author Anna Kratochvilova <kratochanna gmail.com>
  12. """
  13. import wx
  14. from core.globalvar import CheckWxVersion
  15. try:
  16. if CheckWxVersion(version=[3, 0, 0]):
  17. import gui_core.wxlibplot as plot
  18. else:
  19. import wx.lib.plot as plot
  20. except ImportError as e:
  21. print >> sys.stderr, e
  22. import wx.lib.scrolledpanel as scrolled
  23. from core.utils import _
  24. from core.gcmd import GError
  25. class PlotPanel(scrolled.ScrolledPanel):
  26. """Panel for drawing multiple plots.
  27. There are three types of plots: histograms, coincidence plots and scatter plots.
  28. Histograms show frequency of cell category values in training areas
  29. for each band and for one category. Coincidence plots show min max range
  30. of classes for each band.
  31. """
  32. def __init__(self, parent, giface, stats_data):
  33. scrolled.ScrolledPanel.__init__(self, parent)
  34. self.SetupScrolling(scroll_x = False, scroll_y = True)
  35. self._giface = giface
  36. self.parent = parent
  37. self.canvasList = []
  38. self.bandList = []
  39. self.stats_data = stats_data
  40. self.currentCat = None
  41. self.mainSizer = wx.BoxSizer(wx.VERTICAL)
  42. self._createControlPanel()
  43. self._createPlotPanel()
  44. self._createScatterPlotPanel()
  45. self.SetSizer(self.mainSizer)
  46. self.mainSizer.Fit(self)
  47. self.Layout()
  48. def CloseWindow(self):
  49. if self.iscatt_panel:
  50. self.iscatt_panel.CloseWindow()
  51. def _createPlotPanel(self):
  52. self.canvasPanel = wx.Panel(parent=self)
  53. self.mainSizer.Add(item = self.canvasPanel, proportion = 1, flag = wx.EXPAND, border = 0)
  54. self.canvasSizer = wx.BoxSizer(wx.VERTICAL)
  55. self.canvasPanel.SetSizer(self.canvasSizer)
  56. def _createControlPanel(self):
  57. self.plotSwitch = wx.Choice(self, id = wx.ID_ANY,
  58. choices = [_("Histograms"),
  59. _("Coincident plots"),
  60. _("Scatter plots")])
  61. self.mainSizer.Add(self.plotSwitch, proportion = 0, flag = wx.EXPAND|wx.ALL, border = 5)
  62. self.plotSwitch.Bind(wx.EVT_CHOICE, self.OnPlotTypeSelected)
  63. def _createScatterPlotPanel(self):
  64. """Init interactive scatter plot tool
  65. """
  66. try:
  67. from iscatt.frame import IClassIScattPanel
  68. self.iscatt_panel = IClassIScattPanel(parent=self,
  69. giface=self._giface,
  70. iclass_mapwin = self.parent.GetFirstWindow())
  71. self.mainSizer.Add(self.iscatt_panel, proportion = 1, flag = wx.EXPAND, border = 0)
  72. self.iscatt_panel.Hide()
  73. except ImportError as e:
  74. self.scatt_error = _("Scatter plot functionality is disabled.\n\nReason: " \
  75. "Unable to import packages needed for scatter plot.\n%s" % e)
  76. wx.CallAfter(GError, self.scatt_error, showTraceback=False, parent=self)
  77. self.iscatt_panel = None
  78. def OnPlotTypeSelected(self, event):
  79. """Plot type selected"""
  80. if self.plotSwitch.GetSelection() in [0, 1]:
  81. self.SetupScrolling(scroll_x = False, scroll_y = True)
  82. if self.iscatt_panel:
  83. self.iscatt_panel.Hide()
  84. self.canvasPanel.Show()
  85. self.Layout()
  86. elif self.plotSwitch.GetSelection() == 2:
  87. self.SetupScrolling(scroll_x = False, scroll_y = False)
  88. if self.iscatt_panel:
  89. self.iscatt_panel.Show()
  90. else:
  91. GError(self.scatt_error)
  92. self.canvasPanel.Hide()
  93. self.Layout()
  94. if self.currentCat is None:
  95. return
  96. if self.plotSwitch.GetSelection() == 0:
  97. stat = self.stats_data.GetStatistics(self.currentCat)
  98. if not stat.IsReady():
  99. self.ClearPlots()
  100. return
  101. self.DrawHistograms(stat)
  102. else:
  103. self.DrawCoincidencePlots()
  104. self.Layout()
  105. def StddevChanged(self):
  106. """Standard deviation multiplier changed, redraw histograms"""
  107. if self.plotSwitch.GetSelection() == 0:
  108. stat = self.stats_data.GetStatistics(self.currentCat)
  109. self.UpdateRanges(stat)
  110. def EnableZoom(self, type, enable = True):
  111. for canvas in self.canvasList:
  112. canvas.SetEnableZoom(enable)
  113. #canvas.zoom = type
  114. def EnablePan(self, enable = True):
  115. for canvas in self.canvasList:
  116. canvas.SetEnableDrag(enable)
  117. def DestroyPlots(self):
  118. """Destroy all plot canvases"""
  119. for panel in self.canvasList:
  120. panel.Destroy()
  121. self.canvasList = []
  122. def ClearPlots(self):
  123. """Clears plot canvases"""
  124. for bandIdx in range(len(self.bandList)):
  125. self.canvasList[bandIdx].Clear()
  126. def Reset(self):
  127. """Reset plots (when new map imported)"""
  128. self.currentCat = None
  129. self.ClearPlots()
  130. # bands are still the same
  131. def CreatePlotCanvases(self):
  132. """Create plot canvases according to the number of bands"""
  133. for band in self.bandList:
  134. canvas = plot.PlotCanvas(self.canvasPanel)
  135. canvas.SetMinSize((-1, 140))
  136. canvas.SetFontSizeTitle(10)
  137. canvas.SetFontSizeAxis(8)
  138. self.canvasList.append(canvas)
  139. self.canvasSizer.Add(item = canvas, proportion = 1, flag = wx.EXPAND, border = 0)
  140. self.SetVirtualSize(self.GetBestVirtualSize())
  141. self.Layout()
  142. def UpdatePlots(self, group, subgroup, currentCat, stats_data):
  143. """Update plots after new analysis
  144. :param group: imagery group
  145. :param subgroup: imagery group
  146. :param currentCat: currently selected category (class)
  147. :param stats_data: StatisticsData instance (defined in statistics.py)
  148. """
  149. self.stats_data = stats_data
  150. self.currentCat = currentCat
  151. self.bandList = self.parent.GetGroupLayers(group, subgroup)
  152. graphType = self.plotSwitch.GetSelection()
  153. stat = self.stats_data.GetStatistics(currentCat)
  154. if not stat.IsReady() and graphType == 0:
  155. return
  156. self.DestroyPlots()
  157. self.CreatePlotCanvases()
  158. self.OnPlotTypeSelected(None)
  159. def UpdateCategory(self, cat):
  160. self.currentCat = cat
  161. def DrawCoincidencePlots(self):
  162. """Draw coincidence plots"""
  163. for bandIdx in range(len(self.bandList)):
  164. self.canvasList[bandIdx].SetYSpec(type = 'none')
  165. lines = []
  166. level = 0.5
  167. lines.append(self.DrawInvisibleLine(level))
  168. cats = self.stats_data.GetCategories()
  169. for i, cat in enumerate(cats):
  170. stat = self.stats_data.GetStatistics(cat)
  171. if not stat.IsReady():
  172. continue
  173. color = stat.color
  174. level = i + 1
  175. line = self.DrawCoincidenceLine(level, color, stat.bands[bandIdx])
  176. lines.append(line)
  177. # invisible
  178. level += 0.5
  179. lines.append(self.DrawInvisibleLine(level))
  180. plotGraph = plot.PlotGraphics(lines, title = self.bandList[bandIdx])
  181. self.canvasList[bandIdx].Draw(plotGraph)
  182. def DrawCoincidenceLine(self, level, color, bandValues):
  183. """Draw line between band min and max values
  184. :param level: y coordinate of line
  185. :param color: class color
  186. :param bandValues: BandStatistics instance
  187. """
  188. minim = bandValues.min
  189. maxim = bandValues.max
  190. points = [(minim, level), (maxim, level)]
  191. color = wx.Colour(*map(int, color.split(':')))
  192. return plot.PolyLine(points, colour = color, width = 4)
  193. def DrawInvisibleLine(self, level):
  194. """Draw white line to achieve better margins"""
  195. points = [(100, level), (101, level)]
  196. return plot.PolyLine(points, colour = wx.WHITE, width = 1)
  197. def DrawHistograms(self, statistics):
  198. """Draw histograms for one class
  199. :param statistics: statistics for one class
  200. """
  201. self.histogramLines = []
  202. for bandIdx in range(len(self.bandList)):
  203. self.canvasList[bandIdx].Clear()
  204. self.canvasList[bandIdx].SetYSpec(type = 'auto')
  205. histgramLine = self.CreateHistogramLine(bandValues = statistics.bands[bandIdx])
  206. meanLine = self.CreateMean(bandValues = statistics.bands[bandIdx])
  207. minLine = self.CreateMin(bandValues = statistics.bands[bandIdx])
  208. maxLine = self.CreateMax(bandValues = statistics.bands[bandIdx])
  209. self.histogramLines.append([histgramLine, meanLine, minLine, maxLine])
  210. maxRangeLine = self.CreateMaxRange(bandValues = statistics.bands[bandIdx])
  211. minRangeLine = self.CreateMinRange(bandValues = statistics.bands[bandIdx])
  212. plotGraph = plot.PlotGraphics(self.histogramLines[bandIdx] + [minRangeLine, maxRangeLine],
  213. title = self.bandList[bandIdx])
  214. self.canvasList[bandIdx].Draw(plotGraph)
  215. def CreateMinRange(self, bandValues):
  216. maxVal = max(bandValues.histo)
  217. rMin = bandValues.rangeMin
  218. points = [(rMin, 0), (rMin, maxVal)]
  219. return plot.PolyLine(points, colour = wx.RED, width = 1)
  220. def CreateMaxRange(self, bandValues):
  221. maxVal = max(bandValues.histo)
  222. rMax = bandValues.rangeMax
  223. points = [(rMax, 0), (rMax, maxVal)]
  224. return plot.PolyLine(points, colour = wx.RED, width = 1)
  225. def CreateMean(self, bandValues):
  226. maxVal = max(bandValues.histo)
  227. mean = bandValues.mean
  228. points = [(mean, 0), (mean, maxVal)]
  229. return plot.PolyLine(points, colour = wx.BLUE, width = 1)
  230. def CreateMin(self, bandValues):
  231. maxVal = max(bandValues.histo)
  232. minim = bandValues.min
  233. points = [(minim, 0), (minim, maxVal)]
  234. return plot.PolyLine(points, colour = wx.Colour(200, 200, 200), width = 1)
  235. def CreateMax(self, bandValues):
  236. maxVal = max(bandValues.histo)
  237. maxim = bandValues.max
  238. points = [(maxim, 0), (maxim, maxVal)]
  239. return plot.PolyLine(points, colour = wx.Colour(200, 200, 200), width = 1)
  240. def CreateHistogramLine(self, bandValues):
  241. points = []
  242. for cellCat, count in enumerate(bandValues.histo):
  243. if cellCat < bandValues.min - 5:
  244. continue
  245. if cellCat > bandValues.max + 5:
  246. break
  247. points.append((cellCat, count))
  248. return plot.PolyLine(points, colour = wx.BLACK, width = 1)
  249. def UpdateRanges(self, statistics):
  250. """Redraw ranges lines in histograms when std dev multiplier changes
  251. :param statistics: python Statistics instance
  252. """
  253. for bandIdx in range(len(self.bandList)):
  254. self.canvasList[bandIdx].Clear()
  255. maxRangeLine = self.CreateMaxRange(bandValues = statistics.bands[bandIdx])
  256. minRangeLine = self.CreateMinRange(bandValues = statistics.bands[bandIdx])
  257. plotGraph = plot.PlotGraphics(self.histogramLines[bandIdx] + [minRangeLine, maxRangeLine],
  258. title = self.bandList[bandIdx])
  259. self.canvasList[bandIdx].Draw(plotGraph)