plots.py 12 KB

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