base.py 22 KB

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