plots.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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.gcmd import GError
  17. class PlotPanel(scrolled.ScrolledPanel):
  18. """Panel for drawing multiple plots.
  19. There are three types of plots: histograms, coincidence plots and scatter plots.
  20. Histograms show frequency of cell category values in training areas
  21. for each band and for one category. Coincidence plots show min max range
  22. of classes for each band.
  23. """
  24. def __init__(self, parent, giface, stats_data):
  25. scrolled.ScrolledPanel.__init__(self, parent)
  26. self.SetupScrolling(scroll_x=False, scroll_y=True)
  27. self._giface = giface
  28. self.parent = parent
  29. self.canvasList = []
  30. self.bandList = []
  31. self.stats_data = stats_data
  32. self.currentCat = None
  33. self.mainSizer = wx.BoxSizer(wx.VERTICAL)
  34. self._createControlPanel()
  35. self._createPlotPanel()
  36. self._createScatterPlotPanel()
  37. self.SetSizer(self.mainSizer)
  38. self.mainSizer.Fit(self)
  39. self.Layout()
  40. def CloseWindow(self):
  41. if self.iscatt_panel:
  42. self.iscatt_panel.CloseWindow()
  43. def _createPlotPanel(self):
  44. self.canvasPanel = wx.Panel(parent=self)
  45. self.mainSizer.Add(self.canvasPanel, proportion=1, flag=wx.EXPAND, border=0)
  46. self.canvasSizer = wx.BoxSizer(wx.VERTICAL)
  47. self.canvasPanel.SetSizer(self.canvasSizer)
  48. def _createControlPanel(self):
  49. self.plotSwitch = wx.Choice(
  50. self,
  51. id=wx.ID_ANY,
  52. choices=[_("Histograms"), _("Coincident plots"), _("Scatter plots")],
  53. )
  54. self.mainSizer.Add(
  55. self.plotSwitch, proportion=0, flag=wx.EXPAND | wx.ALL, border=5
  56. )
  57. self.plotSwitch.Bind(wx.EVT_CHOICE, self.OnPlotTypeSelected)
  58. def _createScatterPlotPanel(self):
  59. """Init interactive scatter plot tool"""
  60. try:
  61. from iscatt.frame import IClassIScattPanel
  62. self.iscatt_panel = IClassIScattPanel(
  63. parent=self,
  64. giface=self._giface,
  65. iclass_mapwin=self.parent.GetFirstWindow(),
  66. )
  67. self.mainSizer.Add(
  68. self.iscatt_panel, proportion=1, flag=wx.EXPAND, border=0
  69. )
  70. self.iscatt_panel.Hide()
  71. except ImportError as e:
  72. self.scatt_error = _(
  73. "Scatter plot functionality is disabled.\n\nReason: "
  74. "Unable to import packages needed for scatter plot.\n%s" % e
  75. )
  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.enableZoom = 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.fontSizeTitle = 10
  137. canvas.fontSizeAxis = 8
  138. self.canvasList.append(canvas)
  139. self.canvasSizer.Add(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].ySpec = "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].ySpec = "auto"
  205. histgramLine = self.CreateHistogramLine(
  206. bandValues=statistics.bands[bandIdx]
  207. )
  208. meanLine = self.CreateMean(bandValues=statistics.bands[bandIdx])
  209. minLine = self.CreateMin(bandValues=statistics.bands[bandIdx])
  210. maxLine = self.CreateMax(bandValues=statistics.bands[bandIdx])
  211. self.histogramLines.append([histgramLine, meanLine, minLine, maxLine])
  212. maxRangeLine = self.CreateMaxRange(bandValues=statistics.bands[bandIdx])
  213. minRangeLine = self.CreateMinRange(bandValues=statistics.bands[bandIdx])
  214. plotGraph = plot.PlotGraphics(
  215. self.histogramLines[bandIdx] + [minRangeLine, maxRangeLine],
  216. title=self.bandList[bandIdx],
  217. )
  218. self.canvasList[bandIdx].Draw(plotGraph)
  219. def CreateMinRange(self, bandValues):
  220. maxVal = max(bandValues.histo)
  221. rMin = bandValues.rangeMin
  222. points = [(rMin, 0), (rMin, maxVal)]
  223. return plot.PolyLine(points, colour=wx.RED, width=1)
  224. def CreateMaxRange(self, bandValues):
  225. maxVal = max(bandValues.histo)
  226. rMax = bandValues.rangeMax
  227. points = [(rMax, 0), (rMax, maxVal)]
  228. return plot.PolyLine(points, colour=wx.RED, width=1)
  229. def CreateMean(self, bandValues):
  230. maxVal = max(bandValues.histo)
  231. mean = bandValues.mean
  232. points = [(mean, 0), (mean, maxVal)]
  233. return plot.PolyLine(points, colour=wx.BLUE, width=1)
  234. def CreateMin(self, bandValues):
  235. maxVal = max(bandValues.histo)
  236. minim = bandValues.min
  237. points = [(minim, 0), (minim, maxVal)]
  238. return plot.PolyLine(points, colour=wx.Colour(200, 200, 200), width=1)
  239. def CreateMax(self, bandValues):
  240. maxVal = max(bandValues.histo)
  241. maxim = bandValues.max
  242. points = [(maxim, 0), (maxim, maxVal)]
  243. return plot.PolyLine(points, colour=wx.Colour(200, 200, 200), width=1)
  244. def CreateHistogramLine(self, bandValues):
  245. points = []
  246. for cellCat, count in enumerate(bandValues.histo):
  247. if cellCat < bandValues.min - 5:
  248. continue
  249. if cellCat > bandValues.max + 5:
  250. break
  251. points.append((cellCat, count))
  252. return plot.PolyLine(points, colour=wx.BLACK, width=1)
  253. def UpdateRanges(self, statistics):
  254. """Redraw ranges lines in histograms when std dev multiplier changes
  255. :param statistics: python Statistics instance
  256. """
  257. for bandIdx in range(len(self.bandList)):
  258. self.canvasList[bandIdx].Clear()
  259. maxRangeLine = self.CreateMaxRange(bandValues=statistics.bands[bandIdx])
  260. minRangeLine = self.CreateMinRange(bandValues=statistics.bands[bandIdx])
  261. plotGraph = plot.PlotGraphics(
  262. self.histogramLines[bandIdx] + [minRangeLine, maxRangeLine],
  263. title=self.bandList[bandIdx],
  264. )
  265. self.canvasList[bandIdx].Draw(plotGraph)