base.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. """!
  2. @package wxplot.base
  3. @brief Base classes for iinteractive plotting using PyPlot
  4. Classes:
  5. - base::PlotIcons
  6. - base::BasePlotFrame
  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 os
  13. import sys
  14. import wx
  15. import wx.lib.plot as plot
  16. from core.globalvar import ETCICONDIR
  17. from core.settings import UserSettings
  18. from wxplot.dialogs import TextDialog, OptDialog
  19. from core.render import Map
  20. from icons.icon import MetaIcon
  21. from gui_core.toolbars import BaseIcons
  22. import grass.script as grass
  23. PlotIcons = {
  24. 'draw' : MetaIcon(img = 'show',
  25. label = _('Draw/re-draw plot')),
  26. 'transect' : MetaIcon(img = 'layer-raster-profile',
  27. label = _('Draw transect in map display window to profile')),
  28. 'options' : MetaIcon(img = 'settings',
  29. label = _('Plot options')),
  30. 'statistics' : MetaIcon(img = 'check',
  31. label = _('Plot statistics')),
  32. 'save' : MetaIcon(img = 'save',
  33. label = _('Save profile data to CSV file')),
  34. 'quit' : BaseIcons['quit'].SetLabel(_('Quit plot tool')),
  35. }
  36. class BasePlotFrame(wx.Frame):
  37. """!Abstract PyPlot display frame class"""
  38. def __init__(self, parent = None, id = wx.ID_ANY, size = wx.Size(700, 400),
  39. style = wx.DEFAULT_FRAME_STYLE, rasterList = [], **kwargs):
  40. wx.Frame.__init__(self, parent, id, size = size, style = style, **kwargs)
  41. self.parent = parent # MapFrame
  42. self.mapwin = self.parent.MapWindow
  43. self.Map = Map() # instance of render.Map to be associated with display
  44. self.rasterList = rasterList #list of rasters to plot
  45. self.raster = {} # dictionary of raster maps and their plotting parameters
  46. self.plottype = ''
  47. self.linestyledict = { 'solid' : wx.SOLID,
  48. 'dot' : wx.DOT,
  49. 'long-dash' : wx.LONG_DASH,
  50. 'short-dash' : wx.SHORT_DASH,
  51. 'dot-dash' : wx.DOT_DASH }
  52. self.ptfilldict = { 'transparent' : wx.TRANSPARENT,
  53. 'solid' : wx.SOLID }
  54. #
  55. # Icon
  56. #
  57. self.SetIcon(wx.Icon(os.path.join(ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  58. #
  59. # Add statusbar
  60. #
  61. self.statusbar = self.CreateStatusBar(number = 2, style = 0)
  62. self.statusbar.SetStatusWidths([-2, -1])
  63. #
  64. # Define canvas and settings
  65. #
  66. #
  67. self.client = plot.PlotCanvas(self)
  68. #define the function for drawing pointLabels
  69. self.client.SetPointLabelFunc(self.DrawPointLabel)
  70. # Create mouse event for showing cursor coords in status bar
  71. self.client.canvas.Bind(wx.EVT_LEFT_DOWN, self.OnMouseLeftDown)
  72. # Show closest point when enabled
  73. self.client.canvas.Bind(wx.EVT_MOTION, self.OnMotion)
  74. self.plotlist = [] # list of things to plot
  75. self.plot = None # plot draw object
  76. self.ptitle = "" # title of window
  77. self.xlabel = "" # default X-axis label
  78. self.ylabel = "" # default Y-axis label
  79. #
  80. # Bind various events
  81. #
  82. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  83. self.CentreOnScreen()
  84. self._createColorDict()
  85. def _createColorDict(self):
  86. """!Create color dictionary to return wx.Color tuples
  87. for assigning colors to images in imagery groups"""
  88. self.colorDict = {}
  89. for clr in grass.named_colors.iterkeys():
  90. if clr == 'white' or clr == 'black': continue
  91. r = grass.named_colors[clr][0] * 255
  92. g = grass.named_colors[clr][1] * 255
  93. b = grass.named_colors[clr][2] * 255
  94. self.colorDict[clr] = (r,g,b,255)
  95. def InitPlotOpts(self, plottype):
  96. """!Initialize options for entire plot
  97. """
  98. self.plottype = plottype # histogram, profile, or scatter
  99. self.properties = {} # plot properties
  100. self.properties['font'] = {}
  101. self.properties['font']['prop'] = UserSettings.Get(group = self.plottype, key = 'font')
  102. self.properties['font']['wxfont'] = wx.Font(11, wx.FONTFAMILY_SWISS,
  103. wx.FONTSTYLE_NORMAL,
  104. wx.FONTWEIGHT_NORMAL)
  105. if self.plottype == 'profile':
  106. self.properties['marker'] = UserSettings.Get(group = self.plottype, key = 'marker')
  107. # changing color string to tuple for markers/points
  108. colstr = str(self.properties['marker']['color'])
  109. self.properties['marker']['color'] = tuple(int(colval) for colval in colstr.strip('()').split(','))
  110. self.properties['grid'] = UserSettings.Get(group = self.plottype, key = 'grid')
  111. colstr = str(self.properties['grid']['color']) # changing color string to tuple
  112. self.properties['grid']['color'] = tuple(int(colval) for colval in colstr.strip('()').split(','))
  113. self.properties['x-axis'] = {}
  114. self.properties['x-axis']['prop'] = UserSettings.Get(group = self.plottype, key = 'x-axis')
  115. self.properties['x-axis']['axis'] = None
  116. self.properties['y-axis'] = {}
  117. self.properties['y-axis']['prop'] = UserSettings.Get(group = self.plottype, key = 'y-axis')
  118. self.properties['y-axis']['axis'] = None
  119. self.properties['legend'] = UserSettings.Get(group = self.plottype, key = 'legend')
  120. self.zoom = False # zooming disabled
  121. self.drag = False # draging disabled
  122. self.client.SetShowScrollbars(True) # vertical and horizontal scrollbars
  123. # x and y axis set to normal (non-log)
  124. self.client.setLogScale((False, False))
  125. if self.properties['x-axis']['prop']['type']:
  126. self.client.SetXSpec(self.properties['x-axis']['prop']['type'])
  127. else:
  128. self.client.SetXSpec('auto')
  129. if self.properties['y-axis']['prop']['type']:
  130. self.client.SetYSpec(self.properties['y-axis']['prop']['type'])
  131. else:
  132. self.client.SetYSpec('auto')
  133. def InitRasterOpts(self, rasterList, plottype):
  134. """!Initialize or update raster dictionary for plotting
  135. """
  136. rdict = {} # initialize a dictionary
  137. for r in rasterList:
  138. idx = rasterList.index(r)
  139. try:
  140. ret = grass.raster_info(r)
  141. except:
  142. continue
  143. # if r.info cannot parse map, skip it
  144. self.raster[r] = UserSettings.Get(group = plottype, key = 'raster') # some default settings
  145. rdict[r] = {} # initialize sub-dictionaries for each raster in the list
  146. rdict[r]['units'] = ''
  147. if ret['units'] not in ('(none)', '"none"', '', None):
  148. rdict[r]['units'] = ret['units']
  149. rdict[r]['plegend'] = r.split('@')[0]
  150. rdict[r]['datalist'] = [] # list of cell value,frequency pairs for plotting histogram
  151. rdict[r]['pline'] = None
  152. rdict[r]['datatype'] = ret['datatype']
  153. rdict[r]['pwidth'] = 1
  154. rdict[r]['pstyle'] = 'solid'
  155. if idx <= len(self.colorList):
  156. rdict[r]['pcolor'] = self.colorDict[self.colorList[idx]]
  157. else:
  158. r = randint(0, 255)
  159. b = randint(0, 255)
  160. g = randint(0, 255)
  161. rdict[r]['pcolor'] = ((r,g,b,255))
  162. return rdict
  163. def InitRasterPairs(self, rasterList, plottype):
  164. """!Initialize or update raster dictionary with raster pairs for
  165. bivariate scatterplots
  166. """
  167. if len(rasterList) == 0: return
  168. rdict = {} # initialize a dictionary
  169. for rpair in rasterList:
  170. idx = rasterList.index(rpair)
  171. try:
  172. ret0 = grass.raster_info(rpair[0])
  173. ret1 = grass.raster_info(rpair[1])
  174. except:
  175. continue
  176. # if r.info cannot parse map, skip it
  177. self.raster[rpair] = UserSettings.Get(group = plottype, key = 'rasters') # some default settings
  178. rdict[rpair] = {} # initialize sub-dictionaries for each raster in the list
  179. rdict[rpair][0] = {}
  180. rdict[rpair][1] = {}
  181. rdict[rpair][0]['units'] = ''
  182. rdict[rpair][1]['units'] = ''
  183. if ret0['units'] not in ('(none)', '"none"', '', None):
  184. rdict[rpair][0]['units'] = ret0['units']
  185. if ret1['units'] not in ('(none)', '"none"', '', None):
  186. rdict[rpair][1]['units'] = ret1['units']
  187. rdict[rpair]['plegend'] = rpair[0].split('@')[0] + ' vs ' + rpair[1].split('@')[0]
  188. rdict[rpair]['datalist'] = [] # list of cell value,frequency pairs for plotting histogram
  189. rdict[rpair]['ptype'] = 'dot'
  190. rdict[rpair][0]['datatype'] = ret0['datatype']
  191. rdict[rpair][1]['datatype'] = ret1['datatype']
  192. rdict[rpair]['psize'] = 1
  193. rdict[rpair]['pfill'] = 'solid'
  194. if idx <= len(self.colorList):
  195. rdict[rpair]['pcolor'] = self.colorDict[self.colorList[idx]]
  196. else:
  197. r = randint(0, 255)
  198. b = randint(0, 255)
  199. g = randint(0, 255)
  200. rdict[rpair]['pcolor'] = ((r,g,b,255))
  201. return rdict
  202. def SetGraphStyle(self):
  203. """!Set plot and text options
  204. """
  205. self.client.SetFont(self.properties['font']['wxfont'])
  206. self.client.SetFontSizeTitle(self.properties['font']['prop']['titleSize'])
  207. self.client.SetFontSizeAxis(self.properties['font']['prop']['axisSize'])
  208. self.client.SetEnableZoom(self.zoom)
  209. self.client.SetEnableDrag(self.drag)
  210. #
  211. # axis settings
  212. #
  213. if self.properties['x-axis']['prop']['type'] == 'custom':
  214. self.client.SetXSpec('min')
  215. else:
  216. self.client.SetXSpec(self.properties['x-axis']['prop']['type'])
  217. if self.properties['y-axis']['prop']['type'] == 'custom':
  218. self.client.SetYSpec('min')
  219. else:
  220. self.client.SetYSpec(self.properties['y-axis']['prop'])
  221. if self.properties['x-axis']['prop']['type'] == 'custom' and \
  222. self.properties['x-axis']['prop']['min'] < self.properties['x-axis']['prop']['max']:
  223. self.properties['x-axis']['axis'] = (self.properties['x-axis']['prop']['min'],
  224. self.properties['x-axis']['prop']['max'])
  225. else:
  226. self.properties['x-axis']['axis'] = None
  227. if self.properties['y-axis']['prop']['type'] == 'custom' and \
  228. self.properties['y-axis']['prop']['min'] < self.properties['y-axis']['prop']['max']:
  229. self.properties['y-axis']['axis'] = (self.properties['y-axis']['prop']['min'],
  230. self.properties['y-axis']['prop']['max'])
  231. else:
  232. self.properties['y-axis']['axis'] = None
  233. self.client.SetEnableGrid(self.properties['grid']['enabled'])
  234. self.client.SetGridColour(wx.Color(self.properties['grid']['color'][0],
  235. self.properties['grid']['color'][1],
  236. self.properties['grid']['color'][2],
  237. 255))
  238. self.client.SetFontSizeLegend(self.properties['font']['prop']['legendSize'])
  239. self.client.SetEnableLegend(self.properties['legend']['enabled'])
  240. if self.properties['x-axis']['prop']['log'] == True:
  241. self.properties['x-axis']['axis'] = None
  242. self.client.SetXSpec('min')
  243. if self.properties['y-axis']['prop']['log'] == True:
  244. self.properties['y-axis']['axis'] = None
  245. self.client.SetYSpec('min')
  246. self.client.setLogScale((self.properties['x-axis']['prop']['log'],
  247. self.properties['y-axis']['prop']['log']))
  248. def DrawPlot(self, plotlist):
  249. """!Draw line and point plot from list plot elements.
  250. """
  251. self.plot = plot.PlotGraphics(plotlist,
  252. self.ptitle,
  253. self.xlabel,
  254. self.ylabel)
  255. if self.properties['x-axis']['prop']['type'] == 'custom':
  256. self.client.SetXSpec('min')
  257. else:
  258. self.client.SetXSpec(self.properties['x-axis']['prop']['type'])
  259. if self.properties['y-axis']['prop']['type'] == 'custom':
  260. self.client.SetYSpec('min')
  261. else:
  262. self.client.SetYSpec(self.properties['y-axis']['prop']['type'])
  263. self.client.Draw(self.plot, self.properties['x-axis']['axis'],
  264. self.properties['y-axis']['axis'])
  265. def DrawPointLabel(self, dc, mDataDict):
  266. """!This is the fuction that defines how the pointLabels are
  267. plotted dc - DC that will be passed mDataDict - Dictionary
  268. of data that you want to use for the pointLabel
  269. As an example I have decided I want a box at the curve
  270. point with some text information about the curve plotted
  271. below. Any wxDC method can be used.
  272. """
  273. dc.SetPen(wx.Pen(wx.BLACK))
  274. dc.SetBrush(wx.Brush( wx.BLACK, wx.SOLID ) )
  275. sx, sy = mDataDict["scaledXY"] #scaled x,y of closest point
  276. dc.DrawRectangle( sx-5,sy-5, 10, 10) #10by10 square centered on point
  277. px,py = mDataDict["pointXY"]
  278. cNum = mDataDict["curveNum"]
  279. pntIn = mDataDict["pIndex"]
  280. legend = mDataDict["legend"]
  281. #make a string to display
  282. s = "Crv# %i, '%s', Pt. (%.2f,%.2f), PtInd %i" %(cNum, legend, px, py, pntIn)
  283. dc.DrawText(s, sx , sy+1)
  284. def OnZoom(self, event):
  285. """!Enable zooming and disable dragging
  286. """
  287. self.zoom = True
  288. self.drag = False
  289. self.client.SetEnableZoom(self.zoom)
  290. self.client.SetEnableDrag(self.drag)
  291. def OnDrag(self, event):
  292. """!Enable dragging and disable zooming
  293. """
  294. self.zoom = False
  295. self.drag = True
  296. self.client.SetEnableDrag(self.drag)
  297. self.client.SetEnableZoom(self.zoom)
  298. def OnRedraw(self, event):
  299. """!Redraw the plot window. Unzoom to original size
  300. """
  301. self.client.Reset()
  302. self.client.Redraw()
  303. def OnErase(self, event):
  304. """!Erase the plot window
  305. """
  306. self.client.Clear()
  307. self.mapwin.ClearLines(self.mapwin.pdc)
  308. self.mapwin.ClearLines(self.mapwin.pdcTmp)
  309. self.mapwin.polycoords = []
  310. self.mapwin.Refresh()
  311. def SaveToFile(self, event):
  312. """!Save plot to graphics file
  313. """
  314. self.client.SaveFile()
  315. def OnMouseLeftDown(self,event):
  316. self.SetStatusText(_("Left Mouse Down at Point:") + \
  317. " (%.4f, %.4f)" % self.client._getXY(event))
  318. event.Skip() # allows plotCanvas OnMouseLeftDown to be called
  319. def OnMotion(self, event):
  320. """!Indicate when mouse is outside the plot area
  321. """
  322. if self.client.OnLeave(event): print 'out of area'
  323. #show closest point (when enbled)
  324. if self.client.GetEnablePointLabel() == True:
  325. #make up dict with info for the pointLabel
  326. #I've decided to mark the closest point on the closest curve
  327. dlst = self.client.GetClosetPoint( self.client._getXY(event), pointScaled = True)
  328. if dlst != []: #returns [] if none
  329. curveNum, legend, pIndex, pointXY, scaledXY, distance = dlst
  330. #make up dictionary to pass to my user function (see DrawPointLabel)
  331. mDataDict = {"curveNum":curveNum, "legend":legend, "pIndex":pIndex,\
  332. "pointXY":pointXY, "scaledXY":scaledXY}
  333. #pass dict to update the pointLabel
  334. self.client.UpdatePointLabel(mDataDict)
  335. event.Skip() #go to next handler
  336. def PlotOptionsMenu(self, event):
  337. """!Popup menu for plot and text options
  338. """
  339. point = wx.GetMousePosition()
  340. popt = wx.Menu()
  341. # Add items to the menu
  342. settext = wx.MenuItem(popt, wx.ID_ANY, _('Text settings'))
  343. popt.AppendItem(settext)
  344. self.Bind(wx.EVT_MENU, self.PlotText, settext)
  345. setgrid = wx.MenuItem(popt, wx.ID_ANY, _('Plot settings'))
  346. popt.AppendItem(setgrid)
  347. self.Bind(wx.EVT_MENU, self.PlotOptions, setgrid)
  348. # Popup the menu. If an item is selected then its handler
  349. # will be called before PopupMenu returns.
  350. self.PopupMenu(popt)
  351. popt.Destroy()
  352. def NotFunctional(self):
  353. """!Creates a 'not functional' message dialog
  354. """
  355. dlg = wx.MessageDialog(parent = self,
  356. message = _('This feature is not yet functional'),
  357. caption = _('Under Construction'),
  358. style = wx.OK | wx.ICON_INFORMATION)
  359. dlg.ShowModal()
  360. dlg.Destroy()
  361. def OnPlotText(self, dlg):
  362. """!Custom text settings for histogram plot.
  363. """
  364. self.ptitle = dlg.ptitle
  365. self.xlabel = dlg.xlabel
  366. self.ylabel = dlg.ylabel
  367. dlg.UpdateSettings()
  368. self.client.SetFont(self.properties['font']['wxfont'])
  369. self.client.SetFontSizeTitle(self.properties['font']['prop']['titleSize'])
  370. self.client.SetFontSizeAxis(self.properties['font']['prop']['axisSize'])
  371. if self.plot:
  372. self.plot.setTitle(dlg.ptitle)
  373. self.plot.setXLabel(dlg.xlabel)
  374. self.plot.setYLabel(dlg.ylabel)
  375. self.OnRedraw(event = None)
  376. def PlotText(self, event):
  377. """!Set custom text values for profile title and axis labels.
  378. """
  379. dlg = TextDialog(parent = self, id = wx.ID_ANY,
  380. plottype = self.plottype,
  381. title = _('Histogram text settings'))
  382. if dlg.ShowModal() == wx.ID_OK:
  383. self.OnPlotText(dlg)
  384. dlg.Destroy()
  385. def PlotOptions(self, event):
  386. """!Set various profile options, including: line width, color,
  387. style; marker size, color, fill, and style; grid and legend
  388. options. Calls OptDialog class.
  389. """
  390. dlg = OptDialog(parent = self, id = wx.ID_ANY,
  391. plottype = self.plottype,
  392. title = _('Plot settings'))
  393. btnval = dlg.ShowModal()
  394. if btnval == wx.ID_SAVE:
  395. dlg.UpdateSettings()
  396. self.SetGraphStyle()
  397. dlg.Destroy()
  398. elif btnval == wx.ID_CANCEL:
  399. dlg.Destroy()
  400. def PrintMenu(self, event):
  401. """!Print options and output menu
  402. """
  403. point = wx.GetMousePosition()
  404. printmenu = wx.Menu()
  405. for title, handler in ((_("Page setup"), self.OnPageSetup),
  406. (_("Print preview"), self.OnPrintPreview),
  407. (_("Print display"), self.OnDoPrint)):
  408. item = wx.MenuItem(printmenu, wx.ID_ANY, title)
  409. printmenu.AppendItem(item)
  410. self.Bind(wx.EVT_MENU, handler, item)
  411. # Popup the menu. If an item is selected then its handler
  412. # will be called before PopupMenu returns.
  413. self.PopupMenu(printmenu)
  414. printmenu.Destroy()
  415. def OnPageSetup(self, event):
  416. self.client.PageSetup()
  417. def OnPrintPreview(self, event):
  418. self.client.PrintPreview()
  419. def OnDoPrint(self, event):
  420. self.client.Printout()
  421. def OnQuit(self, event):
  422. self.Close(True)
  423. def OnCloseWindow(self, event):
  424. """!Close plot window and clean up
  425. """
  426. try:
  427. self.mapwin.ClearLines()
  428. self.mapwin.mouse['begin'] = self.mapwin.mouse['end'] = (0.0, 0.0)
  429. self.mapwin.mouse['use'] = 'pointer'
  430. self.mapwin.mouse['box'] = 'point'
  431. self.mapwin.polycoords = []
  432. self.mapwin.UpdateMap(render = False, renderVector = False)
  433. except:
  434. pass
  435. self.mapwin.SetCursor(self.Parent.cursors["default"])
  436. self.Destroy()