scatter.py 11 KB

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