scatter.py 12 KB

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