base.py 22 KB

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