scatter.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. """
  2. @package wxplot.scatter
  3. @brief Scatter plotting using PyPlot
  4. Classes:
  5. - scatter::ScatterFrame
  6. - scatter::ScatterToolbar
  7. (C) 2011 by the GRASS Development Team
  8. This program is free software under the GNU General Public License
  9. (>=v2). Read the file COPYING that comes with GRASS for details.
  10. @author Michael Barton, Arizona State University
  11. """
  12. import sys
  13. import wx
  14. import grass.script as grass
  15. import gui_core.wxlibplot as plot
  16. from wxplot.base import BasePlotFrame, PlotIcons
  17. from gui_core.toolbars import BaseToolbar, BaseIcons
  18. from wxplot.dialogs import ScatterRasterDialog, PlotStatsFrame
  19. from core.gcmd import RunCommand, GException, GError, GMessage
  20. from core.utils import _
  21. class ScatterFrame(BasePlotFrame):
  22. """Mainframe for displaying bivariate scatter plot of two raster maps. Uses wx.lib.plot.
  23. """
  24. def __init__(self, parent, id = wx.ID_ANY, style = wx.DEFAULT_FRAME_STYLE,
  25. size = wx.Size(700, 400),
  26. rasterList = [], **kwargs):
  27. BasePlotFrame.__init__(self, parent, size = size, **kwargs)
  28. self.toolbar = ScatterToolbar(parent = self)
  29. # workaround for http://trac.wxwidgets.org/ticket/13888
  30. if sys.platform != 'darwin':
  31. self.SetToolBar(self.toolbar)
  32. self.SetTitle(_("GRASS Bivariate Scatterplot Tool"))
  33. #
  34. # Init variables
  35. #
  36. self.rasterList = rasterList
  37. self.plottype = 'scatter'
  38. self.ptitle = _('Bivariate Scatterplot') # title of window
  39. self.xlabel = _("Raster cell values") # default X-axis label
  40. self.ylabel = _("Raster cell values") # default Y-axis label
  41. self.maptype = 'raster' # default type of scatterplot
  42. self.scattertype = 'normal'
  43. self.bins = 255
  44. self.colorList = ["blue", "red", "black", "green", "yellow", "magenta", "cyan", \
  45. "aqua", "grey", "orange", "brown", "purple", "violet", \
  46. "indigo"]
  47. self._initOpts()
  48. if len(self.rasterList) > 1: # set raster name(s) from layer manager if a map is selected
  49. self.InitRasterOpts(self.rasterList, 'scatter')
  50. else:
  51. self.raster = {}
  52. def _initOpts(self):
  53. """Initialize plot options
  54. """
  55. self.InitPlotOpts('scatter')
  56. def OnCreateScatter(self, event):
  57. """Main routine for creating a scatterplot. Uses r.stats to
  58. create a list of cell value pairs. This is passed to
  59. plot to create a scatterplot.
  60. """
  61. self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
  62. self.SetGraphStyle()
  63. wx.BeginBusyCursor()
  64. wx.SafeYield()
  65. self.SetupScatterplot()
  66. p = self.CreatePlotList()
  67. if p:
  68. self.DrawPlot(p)
  69. wx.EndBusyCursor()
  70. else:
  71. wx.EndBusyCursor()
  72. GMessage(_("Nothing to plot."), parent = self)
  73. def OnSelectRaster(self, event):
  74. """Select raster map(s) to profile
  75. """
  76. dlg = ScatterRasterDialog(parent = self)
  77. dlg.CenterOnParent()
  78. if dlg.ShowModal() == wx.ID_OK:
  79. self.rasterList = dlg.GetRasterPairs()
  80. if not self.rasterList:
  81. GMessage(_("At least 2 raster maps must be specified"), parent = dlg)
  82. return
  83. # scatterplot or bubbleplot
  84. # bins for r.stats with float and dcell maps
  85. self.scattertype, self.bins = dlg.GetSettings()
  86. self.raster = self.InitRasterPairs(self.rasterList, 'scatter') # dictionary of raster pairs
  87. # plot histogram
  88. if self.rasterList:
  89. self.OnCreateScatter(event = None)
  90. dlg.Destroy()
  91. def SetupScatterplot(self):
  92. """Build data list for ploting each raster
  93. """
  94. #
  95. # initialize title string
  96. #
  97. self.ptitle = _('Bivariate Scatterplot of ')
  98. #
  99. # create a datalist for plotting for each raster pair
  100. #
  101. if len(self.rasterList) == 0: return # at least 1 pair of maps needed to plot
  102. for rpair in self.rasterList:
  103. self.raster[rpair]['datalist'] = self.CreateDatalist(rpair)
  104. # update title
  105. self.ptitle += '%s vs %s, ' % (rpair[0].split('@')[0], rpair[1].split('@')[0])
  106. self.ptitle = self.ptitle.strip(', ')
  107. #
  108. # set xlabel & ylabel based on raster maps of first pair to be plotted
  109. #
  110. self.xlabel = _('Raster <%s> cell values') % rpair[0].split('@')[0]
  111. self.ylabel = _('Raster <%s> cell values') % rpair[1].split('@')[0]
  112. units = self.raster[self.rasterList[0]][0]['units']
  113. if units != '':
  114. self.xlabel += _(': %s') % units
  115. units = self.raster[self.rasterList[0]][1]['units']
  116. if units != '':
  117. self.ylabel += _(': %s') % units
  118. def CreateDatalist(self, rpair):
  119. """Build a list of cell value, frequency pairs for histogram
  120. frequency can be in cell counts, percents, or area
  121. """
  122. datalist = []
  123. if self.scattertype == 'bubble':
  124. freqflag = 'cn'
  125. else:
  126. freqflag = 'n'
  127. try:
  128. ret = RunCommand("r.stats",
  129. parent = self,
  130. input = '%s,%s' % rpair,
  131. flags = freqflag,
  132. nsteps = self.bins,
  133. sep = ',',
  134. quiet = True,
  135. read = True)
  136. if not ret:
  137. return datalist
  138. for line in ret.splitlines():
  139. rast1, rast2 = line.strip().split(',')
  140. rast1 = rast1.strip()
  141. if '-' in rast1:
  142. if rast1[0] == '-':
  143. rast1 = '-' + rast1.split('-')[1]
  144. else:
  145. rast1 = rast1.split('-')[0]
  146. rast2 = rast2.strip()
  147. if '-' in rast2:
  148. if rast2[0] == '-':
  149. rast2 = '-' + rast2.split('-')[1]
  150. else:
  151. rast2 = rast2.split('-')[0]
  152. rast1 = rast1.encode('ascii', 'ignore')
  153. rast2 = rast2.encode('ascii', 'ignore')
  154. datalist.append((rast1,rast2))
  155. return datalist
  156. except GException as e:
  157. GError(parent = self,
  158. message = e.value)
  159. return None
  160. def CreatePlotList(self):
  161. """Make list of elements to plot
  162. """
  163. # graph the cell value, frequency pairs for the histogram
  164. self.plotlist = []
  165. for rpair in self.rasterList:
  166. if 'datalist' not in self.raster[rpair] or \
  167. self.raster[rpair]['datalist'] is None:
  168. continue
  169. if len(self.raster[rpair]['datalist']) > 0:
  170. col = wx.Colour(self.raster[rpair]['pcolor'][0],
  171. self.raster[rpair]['pcolor'][1],
  172. self.raster[rpair]['pcolor'][2],
  173. 255)
  174. scatterpoints = plot.PolyMarker(self.raster[rpair]['datalist'],
  175. legend = ' ' + self.raster[rpair]['plegend'],
  176. colour = col,size = self.raster[rpair]['psize'],
  177. fillstyle = self.ptfilldict[self.raster[rpair]['pfill']],
  178. marker = self.raster[rpair]['ptype'])
  179. self.plotlist.append(scatterpoints)
  180. return self.plotlist
  181. def Update(self):
  182. """Update histogram after changing options
  183. """
  184. self.SetGraphStyle()
  185. p = self.CreatePlotList()
  186. if p:
  187. self.DrawPlot(p)
  188. else:
  189. GMessage(_("Nothing to plot."), parent = self)
  190. def OnRegression(self, event):
  191. """Displays regression information in messagebox
  192. """
  193. message = []
  194. title = _('Regression Statistics for Scatterplot(s)')
  195. for rpair in self.rasterList:
  196. if isinstance(rpair, tuple) == False: continue
  197. rast1, rast2 = rpair
  198. rast1 = rast1.split('@')[0]
  199. rast2 = rast2.split('@')[0]
  200. ret = grass.parse_command('r.regression.line',
  201. mapx = rast1,
  202. mapy = rast2,
  203. flags = 'g', quiet = True,
  204. parse = (grass.parse_key_val, { 'sep' : '=' }))
  205. eqtitle = _('Regression equation for raster map <%(rast1)s> vs. <%(rast2)s>:\n\n') % \
  206. { 'rast1' : rast1,
  207. 'rast2' : rast2 }
  208. eq = ' %s = %s + %s(%s)\n\n' % (rast2, ret['a'], ret['b'], rast1)
  209. num = 'N = %s\n' % ret['N']
  210. rval = 'R = %s\n' % ret['R']
  211. rsq = 'R-squared = %f\n' % pow(float(ret['R']), 2)
  212. ftest = 'F = %s\n' % ret['F']
  213. str = eqtitle + eq + num + rval + rsq + ftest
  214. message.append(str)
  215. stats = PlotStatsFrame(self, id = wx.ID_ANY, message = message,
  216. title = title)
  217. if stats.Show() == wx.ID_CLOSE:
  218. stats.Destroy()
  219. class ScatterToolbar(BaseToolbar):
  220. """Toolbar for bivariate scatterplots of raster map pairs
  221. """
  222. def __init__(self, parent):
  223. BaseToolbar.__init__(self, parent)
  224. # workaround for http://trac.wxwidgets.org/ticket/13888
  225. if sys.platform == 'darwin':
  226. parent.SetToolBar(self)
  227. self.InitToolbar(self._toolbarData())
  228. # realize the toolbar
  229. self.Realize()
  230. def _toolbarData(self):
  231. """Toolbar data"""
  232. return self._getToolbarData((('addraster', BaseIcons["addRast"],
  233. self.parent.OnSelectRaster),
  234. (None, ),
  235. ('draw', PlotIcons["draw"],
  236. self.parent.OnCreateScatter),
  237. ('erase', BaseIcons["erase"],
  238. self.parent.OnErase),
  239. ('drag', BaseIcons['pan'],
  240. self.parent.OnDrag),
  241. ('zoom', BaseIcons['zoomIn'],
  242. self.parent.OnZoom),
  243. ('unzoom', BaseIcons['zoomBack'],
  244. self.parent.OnRedraw),
  245. (None, ),
  246. ('statistics', PlotIcons['statistics'],
  247. self.parent.OnRegression),
  248. ('image', BaseIcons["saveFile"],
  249. self.parent.SaveToFile),
  250. ('print', BaseIcons["print"],
  251. self.parent.PrintMenu),
  252. (None, ),
  253. ('settings', PlotIcons["options"],
  254. self.parent.PlotOptionsMenu),
  255. ('quit', PlotIcons["quit"],
  256. self.parent.OnQuit),
  257. ))