plots.py 12 KB

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