plots.py 12 KB

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