base.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  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, 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.pointLabelFunc = 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.showScrollbars = True
  154. # x and y axis set to normal (non-log)
  155. self.client.logScale = (False, False)
  156. if self.properties['x-axis']['prop']['type']:
  157. self.client.xSpec = self.properties['x-axis']['prop']['type']
  158. else:
  159. self.client.xSpec = 'auto'
  160. if self.properties['y-axis']['prop']['type']:
  161. self.client.ySpec = self.properties['y-axis']['prop']['type']
  162. else:
  163. self.client.ySpec = '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.fontSizeTitle = self.properties['font']['prop']['titleSize']
  279. self.client.fontSizeAxis = self.properties['font']['prop']['axisSize']
  280. self.client.enableZoom = self.zoom
  281. self.client.enableDrag = self.drag
  282. #
  283. # axis settings
  284. #
  285. if self.properties['x-axis']['prop']['type'] == 'custom':
  286. self.client.xSpec = 'min'
  287. else:
  288. self.client.xSpec = self.properties['x-axis']['prop']['type']
  289. if self.properties['y-axis']['prop']['type'] == 'custom':
  290. self.client.ySpec = 'min'
  291. else:
  292. self.client.ySpec = self.properties['y-axis']['prop']['type']
  293. if self.properties['x-axis']['prop']['type'] == 'custom' and self.properties[
  294. 'x-axis']['prop']['min'] < self.properties['x-axis']['prop']['max']:
  295. self.properties['x-axis']['axis'] = (
  296. self.properties['x-axis']['prop']['min'],
  297. self.properties['x-axis']['prop']['max'])
  298. else:
  299. self.properties['x-axis']['axis'] = None
  300. if self.properties['y-axis']['prop']['type'] == 'custom' and self.properties[
  301. 'y-axis']['prop']['min'] < self.properties['y-axis']['prop']['max']:
  302. self.properties['y-axis']['axis'] = (
  303. self.properties['y-axis']['prop']['min'],
  304. self.properties['y-axis']['prop']['max'])
  305. else:
  306. self.properties['y-axis']['axis'] = None
  307. if self.properties['x-axis']['prop']['log'] == True:
  308. self.properties['x-axis']['axis'] = None
  309. self.client.xSpec = 'min'
  310. if self.properties['y-axis']['prop']['log'] == True:
  311. self.properties['y-axis']['axis'] = None
  312. self.client.ySpec = 'min'
  313. self.client.logScale = (self.properties['x-axis']['prop']['log'],
  314. self.properties['y-axis']['prop']['log'])
  315. #
  316. # grid settings
  317. #
  318. self.client.enableGrid = self.properties['grid']['enabled']
  319. gridpen = wx.Pen(colour=wx.Colour(self.properties['grid']['color'][0],
  320. self.properties['grid']['color'][1],
  321. self.properties['grid']['color'][2], 255))
  322. self.client.gridPen = gridpen
  323. #
  324. # legend settings
  325. #
  326. self.client.fontSizeLegend = self.properties['font']['prop']['legendSize']
  327. self.client.enableLegend = self.properties['legend']['enabled']
  328. def DrawPlot(self, plotlist):
  329. """Draw line and point plot from list plot elements.
  330. """
  331. xlabel, ylabel = self._getPlotLabels()
  332. self.plot = plot.PlotGraphics(plotlist,
  333. self.ptitle,
  334. xlabel,
  335. ylabel)
  336. if self.properties['x-axis']['prop']['type'] == 'custom':
  337. self.client.xSpec = 'min'
  338. else:
  339. self.client.xSpec = self.properties['x-axis']['prop']['type']
  340. if self.properties['y-axis']['prop']['type'] == 'custom':
  341. self.client.ySpec = 'min'
  342. else:
  343. self.client.ySpec = self.properties['y-axis']['prop']['type']
  344. self.client.Draw(self.plot, self.properties['x-axis']['axis'],
  345. self.properties['y-axis']['axis'])
  346. def DrawPointLabel(self, dc, mDataDict):
  347. """This is the fuction that defines how the pointLabels are
  348. plotted dc - DC that will be passed mDataDict - Dictionary
  349. of data that you want to use for the pointLabel
  350. As an example I have decided I want a box at the curve
  351. point with some text information about the curve plotted
  352. below. Any wxDC method can be used.
  353. """
  354. dc.SetPen(wx.Pen(wx.BLACK))
  355. dc.SetBrush(wx.Brush(wx.BLACK, wx.SOLID))
  356. sx, sy = mDataDict["scaledXY"] # scaled x,y of closest point
  357. # 10by10 square centered on point
  358. dc.DrawRectangle(sx - 5, sy - 5, 10, 10)
  359. px, py = mDataDict["pointXY"]
  360. cNum = mDataDict["curveNum"]
  361. pntIn = mDataDict["pIndex"]
  362. legend = mDataDict["legend"]
  363. # make a string to display
  364. s = "Crv# %i, '%s', Pt. (%.2f,%.2f), PtInd %i" % (
  365. cNum, legend, px, py, pntIn)
  366. dc.DrawText(s, sx, sy + 1)
  367. def OnZoom(self, event):
  368. """Enable zooming and disable dragging
  369. """
  370. self.zoom = True
  371. self.drag = False
  372. self.client.enableZoom = self.zoom
  373. self.client.enableDrag = self.drag
  374. def OnDrag(self, event):
  375. """Enable dragging and disable zooming
  376. """
  377. self.zoom = False
  378. self.drag = True
  379. self.client.enableDrag = self.drag
  380. self.client.enableZoom = self.zoom
  381. def OnRedraw(self, event):
  382. """Redraw the plot window. Unzoom to original size
  383. """
  384. self.UpdateLabels()
  385. self.client.Reset()
  386. self.client.Redraw()
  387. def OnErase(self, event):
  388. """Erase the plot window
  389. """
  390. self.client.Clear()
  391. def SaveToFile(self, event):
  392. """Save plot to graphics file
  393. """
  394. self.client.SaveFile()
  395. def OnMouseLeftDown(self, event):
  396. self.SetStatusText(_("Left Mouse Down at Point:") +
  397. " (%.4f, %.4f)" % self.client._getXY(event))
  398. event.Skip() # allows plotCanvas OnMouseLeftDown to be called
  399. def OnMotion(self, event):
  400. """Indicate when mouse is outside the plot area
  401. """
  402. if self.client.enablePointLabel:
  403. # make up dict with info for the pointLabel
  404. # I've decided to mark the closest point on the closest curve
  405. dlst = self.client.GetClosestPoint(
  406. self.client._getXY(event), pointScaled=True)
  407. if dlst != []: # returns [] if none
  408. curveNum, legend, pIndex, pointXY, scaledXY, distance = dlst
  409. # make up dictionary to pass to my user function (see
  410. # DrawPointLabel)
  411. mDataDict = {
  412. "curveNum": curveNum,
  413. "legend": legend,
  414. "pIndex": pIndex,
  415. "pointXY": pointXY,
  416. "scaledXY": scaledXY}
  417. # pass dict to update the pointLabel
  418. self.client.UpdatePointLabel(mDataDict)
  419. event.Skip() # go to next handler
  420. def PlotOptionsMenu(self, event):
  421. """Popup menu for plot and text options
  422. """
  423. point = wx.GetMousePosition()
  424. popt = Menu()
  425. # Add items to the menu
  426. settext = wx.MenuItem(popt, wx.ID_ANY, _('Text settings'))
  427. popt.AppendItem(settext)
  428. self.Bind(wx.EVT_MENU, self.PlotText, settext)
  429. setgrid = wx.MenuItem(popt, wx.ID_ANY, _('Plot settings'))
  430. popt.AppendItem(setgrid)
  431. self.Bind(wx.EVT_MENU, self.PlotOptions, setgrid)
  432. # Popup the menu. If an item is selected then its handler
  433. # will be called before PopupMenu returns.
  434. self.PopupMenu(popt)
  435. popt.Destroy()
  436. def NotFunctional(self):
  437. """Creates a 'not functional' message dialog
  438. """
  439. dlg = wx.MessageDialog(parent=self,
  440. message=_('This feature is not yet functional'),
  441. caption=_('Under Construction'),
  442. style=wx.OK | wx.ICON_INFORMATION)
  443. dlg.ShowModal()
  444. dlg.Destroy()
  445. def _getPlotLabels(self):
  446. def log(txt):
  447. return "log( " + txt + " )"
  448. x = self.xlabel
  449. if self.properties['x-axis']['prop']['log']:
  450. x = log(x)
  451. y = self.ylabel
  452. if self.properties['y-axis']['prop']['log']:
  453. y = log(y)
  454. return x, y
  455. def OnPlotText(self, dlg):
  456. """Custom text settings for histogram plot.
  457. """
  458. self.ptitle = dlg.ptitle
  459. self.xlabel = dlg.xlabel
  460. self.ylabel = dlg.ylabel
  461. if self.plot:
  462. self.plot.title = dlg.ptitle
  463. self.OnRedraw(event=None)
  464. def UpdateLabels(self):
  465. x, y = self._getPlotLabels()
  466. self.client.SetFont(self.properties['font']['wxfont'])
  467. self.client.fontSizeTitle = self.properties['font']['prop']['titleSize']
  468. self.client.fontSizeAxis = self.properties['font']['prop']['axisSize']
  469. if self.plot:
  470. self.plot.xLabel = x
  471. self.plot.yLabel = y
  472. def PlotText(self, event):
  473. """Set custom text values for profile title and axis labels.
  474. """
  475. dlg = TextDialog(parent=self, id=wx.ID_ANY,
  476. plottype=self.plottype,
  477. title=_('Text settings'))
  478. btnval = dlg.ShowModal()
  479. if btnval == wx.ID_SAVE or btnval == wx.ID_OK or btnval == wx.ID_CANCEL:
  480. dlg.Destroy()
  481. def PlotOptions(self, event):
  482. """Set various profile options, including: line width, color,
  483. style; marker size, color, fill, and style; grid and legend
  484. options. Calls OptDialog class.
  485. """
  486. dlg = OptDialog(parent=self, id=wx.ID_ANY,
  487. plottype=self.plottype,
  488. title=_('Plot settings'))
  489. btnval = dlg.ShowModal()
  490. if btnval == wx.ID_SAVE or btnval == wx.ID_OK or btnval == wx.ID_CANCEL:
  491. dlg.Destroy()
  492. self.Update()
  493. def PrintMenu(self, event):
  494. """Print options and output menu
  495. """
  496. point = wx.GetMousePosition()
  497. printmenu = Menu()
  498. for title, handler in ((_("Page setup"), self.OnPageSetup),
  499. (_("Print preview"), self.OnPrintPreview),
  500. (_("Print display"), self.OnDoPrint)):
  501. item = wx.MenuItem(printmenu, wx.ID_ANY, title)
  502. printmenu.AppendItem(item)
  503. self.Bind(wx.EVT_MENU, handler, item)
  504. # Popup the menu. If an item is selected then its handler
  505. # will be called before PopupMenu returns.
  506. self.PopupMenu(printmenu)
  507. printmenu.Destroy()
  508. def OnPageSetup(self, event):
  509. self.client.PageSetup()
  510. def OnPrintPreview(self, event):
  511. self.client.PrintPreview()
  512. def OnDoPrint(self, event):
  513. self.client.Printout()
  514. def OnQuit(self, event):
  515. self.Close(True)