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