base.py 20 KB

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