frame.py 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197
  1. #!/usr/bin/env python
  2. """
  3. @package frame
  4. @brief Temporal Plot Tool
  5. Classes:
  6. - frame::DataCursor
  7. - frame::TplotFrame
  8. - frame::LookUp
  9. (C) 2012-2016 by the GRASS Development Team
  10. This program is free software under the GNU General Public License
  11. (>=v2). Read the file COPYING that comes with GRASS for details.
  12. @author Luca Delucchi
  13. @author start stvds support Matej Krejci
  14. """
  15. import os
  16. from itertools import cycle
  17. import numpy as np
  18. import wx
  19. from grass.pygrass.modules import Module
  20. import grass.script as grass
  21. from core.utils import _
  22. from functools import reduce
  23. try:
  24. import matplotlib
  25. # The recommended way to use wx with mpl is with the WXAgg
  26. # backend.
  27. matplotlib.use('WXAgg')
  28. from matplotlib.figure import Figure
  29. from matplotlib.backends.backend_wxagg import \
  30. FigureCanvasWxAgg as FigCanvas, \
  31. NavigationToolbar2WxAgg as NavigationToolbar
  32. import matplotlib.dates as mdates
  33. from matplotlib import cbook
  34. except ImportError as e:
  35. raise ImportError(_('The Temporal Plot Tool needs the "matplotlib" '
  36. '(python-matplotlib) package to be installed. {0}').format(e))
  37. from core.utils import _
  38. import grass.temporal as tgis
  39. from core.gcmd import GMessage, GError, GException, RunCommand
  40. from gui_core.widgets import CoordinatesValidator
  41. from gui_core import gselect
  42. from core import globalvar
  43. from grass.pygrass.vector.geometry import Point
  44. from grass.pygrass.raster import RasterRow
  45. from grass.pygrass.gis.region import Region
  46. from collections import OrderedDict
  47. from subprocess import PIPE
  48. try:
  49. import wx.lib.agw.flatnotebook as FN
  50. except ImportError:
  51. import wx.lib.flatnotebook as FN
  52. import wx.lib.filebrowsebutton as filebrowse
  53. from gui_core.widgets import GNotebook
  54. ALPHA = 0.5
  55. COLORS = ['b', 'g', 'r', 'c', 'm', 'y', 'k']
  56. def check_version(*version):
  57. """Checks if given version or newer is installed"""
  58. versionInstalled = []
  59. for i in matplotlib.__version__.split('.'):
  60. try:
  61. v = int(i)
  62. versionInstalled.append(v)
  63. except ValueError:
  64. versionInstalled.append(0)
  65. if versionInstalled < list(version):
  66. return False
  67. else:
  68. return True
  69. def findBetween(s, first, last):
  70. try:
  71. start = s.rindex(first) + len(first)
  72. end = s.rindex(last, start)
  73. return s[start:end]
  74. except ValueError:
  75. return ""
  76. class TplotFrame(wx.Frame):
  77. """The main frame of the application"""
  78. def __init__(self, parent, giface):
  79. wx.Frame.__init__(self, parent, id=wx.ID_ANY,
  80. title=_("GRASS GIS Temporal Plot Tool"))
  81. tgis.init(True)
  82. self._giface = giface
  83. self.datasetsV = None
  84. self.datasetsR = None
  85. self.overwrite = False
  86. # self.vectorDraw=False
  87. # self.rasterDraw=False
  88. self.init()
  89. self._layout()
  90. # We create a database interface here to speedup the GUI
  91. self.dbif = tgis.SQLDatabaseInterfaceConnection()
  92. self.dbif.connect()
  93. self.Bind(wx.EVT_CLOSE, self.onClose)
  94. self.region = Region()
  95. def init(self):
  96. self.timeDataR = OrderedDict()
  97. self.timeDataV = OrderedDict()
  98. self.temporalType = None
  99. self.unit = None
  100. self.listWhereConditions = []
  101. self.plotNameListR = []
  102. self.plotNameListV = []
  103. self.poi = None
  104. def __del__(self):
  105. """Close the database interface and stop the messenger and C-interface
  106. subprocesses.
  107. """
  108. if self.dbif.connected is True:
  109. self.dbif.close()
  110. tgis.stop_subprocesses()
  111. def onClose(self, evt):
  112. if self._giface.GetMapDisplay():
  113. self.coorval.OnClose()
  114. self.cats.OnClose()
  115. self.__del__()
  116. self.Destroy()
  117. def _layout(self):
  118. """Creates the main panel with all the controls on it:
  119. * mpl canvas
  120. * mpl navigation toolbar
  121. * Control panel for interaction
  122. """
  123. self.mainPanel = wx.Panel(self)
  124. # Create the mpl Figure and FigCanvas objects.
  125. # 5x4 inches, 100 dots-per-inch
  126. #
  127. # color = wx.SystemSettings.GetColour(wx.SYS_COLOUR_BACKGROUND)
  128. # ------------CANVAS AND TOOLBAR------------
  129. self.fig = Figure((5.0, 4.0), facecolor=(1, 1, 1))
  130. self.canvas = FigCanvas(self.mainPanel, wx.ID_ANY, self.fig)
  131. # axes are initialized later
  132. self.axes2d = None
  133. # Create the navigation toolbar, tied to the canvas
  134. #
  135. self.toolbar = NavigationToolbar(self.canvas)
  136. #
  137. # Layout
  138. #
  139. # ------------MAIN VERTICAL SIZER------------
  140. self.vbox = wx.BoxSizer(wx.VERTICAL)
  141. self.vbox.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.EXPAND)
  142. self.vbox.Add(self.toolbar, 0, wx.EXPAND)
  143. # self.vbox.AddSpacer(10)
  144. # ------------ADD NOTEBOOK------------
  145. self.ntb = GNotebook(parent=self.mainPanel, style=FN.FNB_FANCY_TABS)
  146. # ------------ITEMS IN NOTEBOOK PAGE (RASTER)------------------------
  147. self.controlPanelRaster = wx.Panel(parent=self.ntb, id=wx.ID_ANY)
  148. self.datasetSelectLabelR = wx.StaticText(
  149. parent=self.controlPanelRaster,
  150. id=wx.ID_ANY,
  151. label=_(
  152. 'Raster temporal '
  153. 'dataset (strds)\n'
  154. 'Press ENTER after'
  155. ' typing the name or select'
  156. ' with the combobox'))
  157. self.datasetSelectR = gselect.Select(
  158. parent=self.controlPanelRaster, id=wx.ID_ANY,
  159. size=globalvar.DIALOG_GSELECT_SIZE, type='strds', multiple=True)
  160. self.coor = wx.StaticText(parent=self.controlPanelRaster, id=wx.ID_ANY,
  161. label=_('X and Y coordinates separated by '
  162. 'comma:'))
  163. try:
  164. self._giface.GetMapWindow()
  165. self.coorval = gselect.CoordinatesSelect(
  166. parent=self.controlPanelRaster, giface=self._giface)
  167. except:
  168. self.coorval = wx.TextCtrl(parent=self.controlPanelRaster,
  169. id=wx.ID_ANY,
  170. size=globalvar.DIALOG_TEXTCTRL_SIZE,
  171. validator=CoordinatesValidator())
  172. self.coorval.SetToolTipString(_("Coordinates can be obtained for example"
  173. " by right-clicking on Map Display."))
  174. self.controlPanelSizerRaster = wx.BoxSizer(wx.VERTICAL)
  175. # self.controlPanelSizer.Add(wx.StaticText(self.panel, id=wx.ID_ANY,
  176. # label=_("Select space time raster dataset(s):")),
  177. # pos=(0, 0), flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL)
  178. self.controlPanelSizerRaster.Add(self.datasetSelectLabelR,
  179. flag=wx.EXPAND)
  180. self.controlPanelSizerRaster.Add(self.datasetSelectR, flag=wx.EXPAND)
  181. self.controlPanelSizerRaster.Add(self.coor, flag=wx.EXPAND)
  182. self.controlPanelSizerRaster.Add(self.coorval, flag=wx.EXPAND)
  183. self.controlPanelRaster.SetSizer(self.controlPanelSizerRaster)
  184. self.controlPanelSizerRaster.Fit(self)
  185. self.ntb.AddPage(page=self.controlPanelRaster, text=_('STRDS'),
  186. name='STRDS')
  187. # ------------ITEMS IN NOTEBOOK PAGE (VECTOR)------------------------
  188. self.controlPanelVector = wx.Panel(parent=self.ntb, id=wx.ID_ANY)
  189. self.datasetSelectLabelV = wx.StaticText(
  190. parent=self.controlPanelVector, id=wx.ID_ANY,
  191. label=_(
  192. 'Vector temporal '
  193. 'dataset (stvds)\n'
  194. 'Press ENTER after'
  195. ' typing the name or select'
  196. ' with the combobox'))
  197. self.datasetSelectV = gselect.Select(
  198. parent=self.controlPanelVector, id=wx.ID_ANY,
  199. size=globalvar.DIALOG_GSELECT_SIZE, type='stvds', multiple=True)
  200. self.datasetSelectV.Bind(wx.EVT_TEXT,
  201. self.OnVectorSelected)
  202. self.attribute = gselect.ColumnSelect(parent=self.controlPanelVector)
  203. self.attributeLabel = wx.StaticText(parent=self.controlPanelVector,
  204. id=wx.ID_ANY,
  205. label=_('Select attribute column'))
  206. # TODO fix the category selection as done for coordinates
  207. try:
  208. self._giface.GetMapWindow()
  209. self.cats = gselect.VectorCategorySelect(
  210. parent=self.controlPanelVector, giface=self._giface)
  211. except:
  212. self.cats = wx.TextCtrl(
  213. parent=self.controlPanelVector,
  214. id=wx.ID_ANY,
  215. size=globalvar.DIALOG_TEXTCTRL_SIZE)
  216. self.catsLabel = wx.StaticText(parent=self.controlPanelVector,
  217. id=wx.ID_ANY,
  218. label=_('Select category of vector(s)'))
  219. self.controlPanelSizerVector = wx.BoxSizer(wx.VERTICAL)
  220. # self.controlPanelSizer.Add(wx.StaticText(self.panel, id=wx.ID_ANY,
  221. # label=_("Select space time raster dataset(s):")),
  222. # pos=(0, 0), flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL)
  223. self.controlPanelSizerVector.Add(self.datasetSelectLabelV,
  224. flag=wx.EXPAND)
  225. self.controlPanelSizerVector.Add(self.datasetSelectV, flag=wx.EXPAND)
  226. self.controlPanelSizerVector.Add(self.attributeLabel, flag=wx.EXPAND)
  227. self.controlPanelSizerVector.Add(self.attribute, flag=wx.EXPAND)
  228. self.controlPanelSizerVector.Add(self.catsLabel, flag=wx.EXPAND)
  229. self.controlPanelSizerVector.Add(self.cats, flag=wx.EXPAND)
  230. self.controlPanelVector.SetSizer(self.controlPanelSizerVector)
  231. self.controlPanelSizerVector.Fit(self)
  232. self.ntb.AddPage(page=self.controlPanelVector, text=_('STVDS'),
  233. name='STVDS')
  234. # ------------ITEMS IN NOTEBOOK PAGE (LABELS)------------------------
  235. self.controlPanelLabels = wx.Panel(parent=self.ntb, id=wx.ID_ANY)
  236. self.titleLabel = wx.StaticText(parent=self.controlPanelLabels,
  237. id=wx.ID_ANY,
  238. label=_('Set title for the plot'))
  239. self.title = wx.TextCtrl(parent=self.controlPanelLabels, id=wx.ID_ANY,
  240. size=globalvar.DIALOG_TEXTCTRL_SIZE)
  241. self.xLabel = wx.StaticText(parent=self.controlPanelLabels,
  242. id=wx.ID_ANY,
  243. label=_('Set label for X axis'))
  244. self.x = wx.TextCtrl(parent=self.controlPanelLabels, id=wx.ID_ANY,
  245. size=globalvar.DIALOG_TEXTCTRL_SIZE)
  246. self.yLabel = wx.StaticText(parent=self.controlPanelLabels,
  247. id=wx.ID_ANY,
  248. label=_('Set label for Y axis'))
  249. self.y = wx.TextCtrl(parent=self.controlPanelLabels, id=wx.ID_ANY,
  250. size=globalvar.DIALOG_TEXTCTRL_SIZE)
  251. self.controlPanelSizerLabels = wx.BoxSizer(wx.VERTICAL)
  252. self.controlPanelSizerLabels.Add(self.titleLabel, flag=wx.EXPAND)
  253. self.controlPanelSizerLabels.Add(self.title, flag=wx.EXPAND)
  254. self.controlPanelSizerLabels.Add(self.xLabel, flag=wx.EXPAND)
  255. self.controlPanelSizerLabels.Add(self.x, flag=wx.EXPAND)
  256. self.controlPanelSizerLabels.Add(self.yLabel, flag=wx.EXPAND)
  257. self.controlPanelSizerLabels.Add(self.y, flag=wx.EXPAND)
  258. self.controlPanelLabels.SetSizer(self.controlPanelSizerLabels)
  259. self.controlPanelSizerLabels.Fit(self)
  260. self.ntb.AddPage(page=self.controlPanelLabels, text=_('Labels'),
  261. name='Labels')
  262. # ------------ITEMS IN NOTEBOOK PAGE (EXPORT)------------------------
  263. self.controlPanelExport = wx.Panel(parent=self.ntb, id=wx.ID_ANY)
  264. self.csvLabel = wx.StaticText(parent=self.controlPanelExport,
  265. id=wx.ID_ANY,
  266. label=_('Path for output CSV file '
  267. 'with plotted data'))
  268. self.csvButton = filebrowse.FileBrowseButton(parent=self.controlPanelExport,
  269. id=wx.ID_ANY,
  270. size=globalvar.DIALOG_GSELECT_SIZE,
  271. labelText='',
  272. dialogTitle=_('CVS path'),
  273. buttonText=_('Browse'),
  274. startDirectory=os.getcwd(),
  275. fileMode=wx.FD_SAVE)
  276. self.headerLabel = wx.StaticText(parent=self.controlPanelExport,
  277. id=wx.ID_ANY,
  278. label=_('Do you want the CSV header?'
  279. ))
  280. self.headerCheck = wx.CheckBox(parent=self.controlPanelExport,
  281. id=wx.ID_ANY)
  282. self.controlPanelSizerCheck = wx.BoxSizer(wx.HORIZONTAL)
  283. self.controlPanelSizerCheck.Add(self.headerCheck)
  284. self.controlPanelSizerCheck.Add(self.headerLabel)
  285. self.controlPanelSizerExport = wx.BoxSizer(wx.VERTICAL)
  286. self.controlPanelSizerExport.Add(self.csvLabel)
  287. self.controlPanelSizerExport.Add(self.csvButton)
  288. self.controlPanelSizerExport.Add(self.controlPanelSizerCheck)
  289. self.controlPanelExport.SetSizer(self.controlPanelSizerExport)
  290. self.controlPanelSizerCheck.Fit(self)
  291. self.controlPanelSizerExport.Fit(self)
  292. self.ntb.AddPage(page=self.controlPanelExport, text=_('Export'),
  293. name='Export')
  294. # ------------Buttons on the bottom(draw,help)------------
  295. self.vButtPanel = wx.Panel(self.mainPanel, id=wx.ID_ANY)
  296. self.vButtSizer = wx.BoxSizer(wx.HORIZONTAL)
  297. self.drawButton = wx.Button(self.vButtPanel, id=wx.ID_ANY,
  298. label=_("Draw"))
  299. self.drawButton.Bind(wx.EVT_BUTTON, self.OnRedraw)
  300. self.helpButton = wx.Button(self.vButtPanel, id=wx.ID_ANY,
  301. label=_("Help"))
  302. self.helpButton.Bind(wx.EVT_BUTTON, self.OnHelp)
  303. self.vButtSizer.Add(self.drawButton)
  304. self.vButtSizer.Add(self.helpButton)
  305. self.vButtPanel.SetSizer(self.vButtSizer)
  306. self.mainPanel.SetSizer(self.vbox)
  307. self.vbox.Add(self.ntb, flag=wx.EXPAND)
  308. self.vbox.Add(self.vButtPanel, flag=wx.EXPAND)
  309. self.vbox.Fit(self)
  310. self.mainPanel.Fit()
  311. def _getSTRDdata(self, timeseries):
  312. """Load data and read properties
  313. :param list timeseries: a list of timeseries
  314. """
  315. if not self.poi:
  316. GError(parent=self, message=_("Invalid input coordinates"),
  317. showTraceback=False)
  318. return
  319. mode = None
  320. unit = None
  321. columns = ','.join(['name', 'start_time', 'end_time'])
  322. for series in timeseries:
  323. name = series[0]
  324. fullname = name + '@' + series[1]
  325. etype = series[2]
  326. sp = tgis.dataset_factory(etype, fullname)
  327. if not sp.is_in_db(dbif=self.dbif):
  328. GError(message=_("Dataset <%s> not found in temporal "
  329. "database") % (fullname), parent=self)
  330. return
  331. sp.select(dbif=self.dbif)
  332. minmin = sp.metadata.get_min_min()
  333. self.plotNameListR.append(name)
  334. self.timeDataR[name] = OrderedDict()
  335. self.timeDataR[name]['temporalDataType'] = etype
  336. self.timeDataR[name]['temporalType'] = sp.get_temporal_type()
  337. self.timeDataR[name]['granularity'] = sp.get_granularity()
  338. if mode is None:
  339. mode = self.timeDataR[name]['temporalType']
  340. elif self.timeDataR[name]['temporalType'] != mode:
  341. GError(
  342. parent=self, message=_(
  343. "Datasets have different temporal"
  344. " type (absolute x relative), "
  345. "which is not allowed."))
  346. return
  347. # check topology
  348. maps = sp.get_registered_maps_as_objects(dbif=self.dbif)
  349. self.timeDataR[name]['validTopology'] = sp.check_temporal_topology(
  350. maps=maps, dbif=self.dbif)
  351. self.timeDataR[name]['unit'] = None # only with relative
  352. if self.timeDataR[name]['temporalType'] == 'relative':
  353. start, end, self.timeDataR[name][
  354. 'unit'] = sp.get_relative_time()
  355. if unit is None:
  356. unit = self.timeDataR[name]['unit']
  357. elif self.timeDataR[name]['unit'] != unit:
  358. GError(parent=self, message=_("Datasets have different "
  359. "time unit which is not "
  360. "allowed."))
  361. return
  362. rows = sp.get_registered_maps(columns=columns, where=None,
  363. order='start_time', dbif=self.dbif)
  364. for row in rows:
  365. self.timeDataR[name][row[0]] = {}
  366. self.timeDataR[name][row[0]]['start_datetime'] = row[1]
  367. self.timeDataR[name][row[0]]['end_datetime'] = row[2]
  368. r = RasterRow(row[0])
  369. r.open()
  370. val = r.get_value(self.poi)
  371. r.close()
  372. if val == -2147483648 and val < minmin:
  373. self.timeDataR[name][row[0]]['value'] = None
  374. else:
  375. self.timeDataR[name][row[0]]['value'] = val
  376. self.unit = unit
  377. self.temporalType = mode
  378. return
  379. def _parseVDbConn(self, mapp, layerInp):
  380. '''find attribute key according to layer of input map'''
  381. vdb = Module('v.db.connect', map=mapp, flags='g', stdout_=PIPE)
  382. vdb = vdb.outputs.stdout
  383. for line in vdb.splitlines():
  384. lsplit = line.split('|')
  385. layer = lsplit[0].split('/')[0]
  386. if str(layer) == str(layerInp):
  387. return lsplit[2]
  388. return None
  389. def _getExistingCategories(self, mapp, cats):
  390. """Get a list of categories for a vector map"""
  391. vdb = grass.read_command('v.category', input=mapp, option='print')
  392. categories = vdb.splitlines()
  393. if not cats:
  394. return categories
  395. for cat in cats:
  396. if str(cat) not in categories:
  397. GMessage(message=_("Category {ca} is not on vector map"
  398. " {ma} and it will be not used").format(ma=mapp,
  399. ca=cat),
  400. parent=self)
  401. cats.remove(cat)
  402. return cats
  403. def _getSTVDData(self, timeseries):
  404. """Load data and read properties
  405. :param list timeseries: a list of timeseries
  406. """
  407. mode = None
  408. unit = None
  409. cats = None
  410. attribute = self.attribute.GetValue()
  411. if self.cats.GetValue() != '':
  412. cats = self.cats.GetValue().split(',')
  413. if cats and self.poi:
  414. GMessage(message=_("Both coordinates and categories are set, "
  415. "coordinates will be used. The use categories "
  416. "remove text from coordinate form"))
  417. if not attribute or attribute == '':
  418. GError(parent=self, showTraceback=False,
  419. message=_("With Vector temporal dataset you have to select"
  420. " an attribute column"))
  421. return
  422. columns = ','.join(['name', 'start_time', 'end_time', 'id', 'layer'])
  423. for series in timeseries:
  424. name = series[0]
  425. fullname = name + '@' + series[1]
  426. etype = series[2]
  427. sp = tgis.dataset_factory(etype, fullname)
  428. if not sp.is_in_db(dbif=self.dbif):
  429. GError(message=_("Dataset <%s> not found in temporal "
  430. "database") % (fullname), parent=self,
  431. showTraceback=False)
  432. return
  433. sp.select(dbif=self.dbif)
  434. rows = sp.get_registered_maps(dbif=self.dbif, order="start_time",
  435. columns=columns, where=None)
  436. self.timeDataV[name] = OrderedDict()
  437. self.timeDataV[name]['temporalDataType'] = etype
  438. self.timeDataV[name]['temporalType'] = sp.get_temporal_type()
  439. self.timeDataV[name]['granularity'] = sp.get_granularity()
  440. if mode is None:
  441. mode = self.timeDataV[name]['temporalType']
  442. elif self.timeDataV[name]['temporalType'] != mode:
  443. GError(
  444. parent=self, showTraceback=False, message=_(
  445. "Datasets have different temporal type ("
  446. "absolute x relative), which is not allowed."))
  447. return
  448. self.timeDataV[name]['unit'] = None # only with relative
  449. if self.timeDataV[name]['temporalType'] == 'relative':
  450. start, end, self.timeDataV[name][
  451. 'unit'] = sp.get_relative_time()
  452. if unit is None:
  453. unit = self.timeDataV[name]['unit']
  454. elif self.timeDataV[name]['unit'] != unit:
  455. GError(message=_("Datasets have different time unit which"
  456. " is not allowed."), parent=self,
  457. showTraceback=False)
  458. return
  459. if self.poi:
  460. self.plotNameListV.append(name)
  461. # TODO set an appropriate distance, right now a big one is set
  462. # to return the closer point to the selected one
  463. out = grass.vector_what(map='pois_srvds',
  464. coord=self.poi.coords(),
  465. distance=10000000000000000)
  466. if len(out) != len(rows):
  467. GError(parent=self, showTraceback=False,
  468. message=_("Difference number of vector layers and "
  469. "maps in the vector temporal dataset"))
  470. return
  471. for i in range(len(rows)):
  472. row = rows[i]
  473. values = out[i]
  474. if str(row['layer']) == str(values['Layer']):
  475. lay = "{map}_{layer}".format(map=row['name'],
  476. layer=values['Layer'])
  477. self.timeDataV[name][lay] = {}
  478. self.timeDataV[name][lay][
  479. 'start_datetime'] = row['start_time']
  480. self.timeDataV[name][lay][
  481. 'end_datetime'] = row['start_time']
  482. self.timeDataV[name][lay]['value'] = values[
  483. 'Attributes'][attribute]
  484. else:
  485. wherequery = ''
  486. cats = self._getExistingCategories(rows[0]['name'], cats)
  487. totcat = len(cats)
  488. ncat = 1
  489. for cat in cats:
  490. if ncat == 1 and totcat != 1:
  491. wherequery += '{k}={c} or'.format(c=cat, k="{key}")
  492. elif ncat == 1 and totcat == 1:
  493. wherequery += '{k}={c}'.format(c=cat, k="{key}")
  494. elif ncat == totcat:
  495. wherequery += ' {k}={c}'.format(c=cat, k="{key}")
  496. else:
  497. wherequery += ' {k}={c} or'.format(c=cat, k="{key}")
  498. catn = "cat{num}".format(num=cat)
  499. self.plotNameListV.append("{na}+{cat}".format(na=name,
  500. cat=catn))
  501. self.timeDataV[name][catn] = OrderedDict()
  502. ncat += 1
  503. for row in rows:
  504. lay = int(row['layer'])
  505. catkey = self._parseVDbConn(row['name'], lay)
  506. if not catkey:
  507. GError(
  508. parent=self, showTraceback=False, message=_(
  509. "No connection between vector map {vmap} "
  510. "and layer {la}".format(
  511. vmap=row['name'], la=lay)))
  512. return
  513. vals = grass.vector_db_select(
  514. map=row['name'], layer=lay, where=wherequery.format(
  515. key=catkey), columns=attribute)
  516. layn = "lay{num}".format(num=lay)
  517. for cat in cats:
  518. catn = "cat{num}".format(num=cat)
  519. if layn not in self.timeDataV[name][catn].keys():
  520. self.timeDataV[name][catn][layn] = {}
  521. self.timeDataV[name][catn][layn][
  522. 'start_datetime'] = row['start_time']
  523. self.timeDataV[name][catn][layn][
  524. 'end_datetime'] = row['end_time']
  525. self.timeDataV[name][catn][layn]['value'] = vals['values'][int(cat)][
  526. 0]
  527. self.unit = unit
  528. self.temporalType = mode
  529. return
  530. def _drawFigure(self):
  531. """Draws or print 2D plot (temporal extents)"""
  532. self.axes2d.clear()
  533. self.axes2d.grid(False)
  534. if self.temporalType == 'absolute':
  535. self.axes2d.xaxis_date()
  536. self.fig.autofmt_xdate()
  537. self.convert = mdates.date2num
  538. self.invconvert = mdates.num2date
  539. else:
  540. self.convert = lambda x: x
  541. self.invconvert = self.convert
  542. self.colors = cycle(COLORS)
  543. self.yticksNames = []
  544. self.yticksPos = []
  545. self.plots = []
  546. self.drawTitle = self.title.GetValue()
  547. self.drawX = self.x.GetValue()
  548. self.drawY = self.y.GetValue()
  549. if self.datasetsR:
  550. self.lookUp = LookUp(self.timeDataR, self.invconvert)
  551. else:
  552. self.lookUp = LookUp(self.timeDataV, self.invconvert)
  553. if self.datasetsR:
  554. self.drawR()
  555. if self.datasetsV:
  556. if self.poi:
  557. self.drawV()
  558. elif self.cats:
  559. self.drawVCats()
  560. self.canvas.draw()
  561. DataCursor(self.plots, self.lookUp, InfoFormat, self.convert)
  562. def _setLabels(self, x):
  563. """Function to set the right labels"""
  564. if self.drawX != '':
  565. self.axes2d.set_xlabel(self.drawX)
  566. else:
  567. if self.temporalType == 'absolute':
  568. self.axes2d.set_xlabel(_("Temporal resolution: %s" % x ))
  569. else:
  570. self.axes2d.set_xlabel(_("Time [%s]") % self.unit)
  571. if self.drawY != '':
  572. self.axes2d.set_ylabel(self.drawY)
  573. else:
  574. self.axes2d.set_ylabel(', '.join(self.yticksNames))
  575. if self.drawTitle != '':
  576. self.axes2d.set_title(self.drawTitle)
  577. def _writeCSV(self, x, y):
  578. """Used to write CSV file of plotted data"""
  579. import csv
  580. if len(y) > 1:
  581. zipped = zip(x, *y)
  582. else:
  583. zipped = zip(x, y)
  584. with open(self.csvpath, "wb") as fi:
  585. writer = csv.writer(fi)
  586. if self.header:
  587. head = ["Time"]
  588. head.extend(self.yticksNames)
  589. writer.writerow(head)
  590. writer.writerows(zipped)
  591. def drawR(self):
  592. ycsv = []
  593. for i, name in enumerate(self.datasetsR):
  594. name = name[0]
  595. # just name; with mapset it would be long
  596. self.yticksNames.append(name)
  597. self.yticksPos.append(1) # TODO
  598. xdata = []
  599. ydata = []
  600. xcsv = []
  601. for keys, values in self.timeDataR[name].iteritems():
  602. if keys in ['temporalType', 'granularity', 'validTopology',
  603. 'unit', 'temporalDataType']:
  604. continue
  605. xdata.append(self.convert(values['start_datetime']))
  606. ydata.append(values['value'])
  607. xcsv.append(values['start_datetime'])
  608. if len(ydata) == ydata.count(None):
  609. GError(parent=self, showTraceback=False,
  610. message=_("Problem getting data from raster temporal"
  611. " dataset. Empty list of values."))
  612. return
  613. self.lookUp.AddDataset(yranges=ydata, xranges=xdata,
  614. datasetName=name)
  615. color = self.colors.next()
  616. self.plots.append(self.axes2d.plot(xdata, ydata, marker='o',
  617. color=color,
  618. label=self.plotNameListR[i])[0])
  619. if self.csvpath:
  620. ycsv.append(ydata)
  621. if self.csvpath:
  622. self._writeCSV(xcsv, ycsv)
  623. self._setLabels(self.timeDataR[name]['granularity'])
  624. # legend
  625. handles, labels = self.axes2d.get_legend_handles_labels()
  626. self.axes2d.legend(loc=0)
  627. def drawVCats(self):
  628. ycsv = []
  629. for i, name in enumerate(self.plotNameListV):
  630. # just name; with mapset it would be long
  631. labelname = name.replace('+', ' ')
  632. self.yticksNames.append(labelname)
  633. name_cat = name.split('+')
  634. name = name_cat[0]
  635. self.yticksPos.append(1) # TODO
  636. xdata = []
  637. ydata = []
  638. xcsv = []
  639. for keys, values in self.timeDataV[
  640. name_cat[0]][
  641. name_cat[1]].iteritems():
  642. if keys in ['temporalType', 'granularity', 'validTopology',
  643. 'unit', 'temporalDataType']:
  644. continue
  645. xdata.append(self.convert(values['start_datetime']))
  646. if values['value'] == '':
  647. ydata.append(None)
  648. else:
  649. ydata.append(values['value'])
  650. xcsv.append(values['start_datetime'])
  651. if len(ydata) == ydata.count(None):
  652. GError(parent=self, showTraceback=False,
  653. message=_("Problem getting data from vector temporal"
  654. " dataset. Empty list of values for cat "
  655. "{ca}.".format(ca=name_cat[1].replace('cat',
  656. ''))))
  657. continue
  658. self.lookUp.AddDataset(yranges=ydata, xranges=xdata,
  659. datasetName=name)
  660. color = self.colors.next()
  661. self.plots.append(
  662. self.axes2d.plot(
  663. xdata,
  664. ydata,
  665. marker='o',
  666. color=color,
  667. label=labelname)[0])
  668. if self.csvpath:
  669. ycsv.append(ydata)
  670. if self.csvpath:
  671. self._writeCSV(xcsv, ycsv)
  672. self._setLabels(self.timeDataV[name]['granularity'])
  673. # legend
  674. handles, labels = self.axes2d.get_legend_handles_labels()
  675. self.axes2d.legend(loc=0)
  676. self.listWhereConditions = []
  677. def drawV(self):
  678. ycsv = []
  679. for i, name in enumerate(self.plotNameListV):
  680. # just name; with mapset it would be long
  681. self.yticksNames.append(self.attribute.GetValue())
  682. self.yticksPos.append(0) # TODO
  683. xdata = []
  684. ydata = []
  685. xcsv = []
  686. for keys, values in self.timeDataV[name].iteritems():
  687. if keys in ['temporalType', 'granularity', 'validTopology',
  688. 'unit', 'temporalDataType']:
  689. continue
  690. xdata.append(self.convert(values['start_datetime']))
  691. ydata.append(values['value'])
  692. xcsv.append(values['start_datetime'])
  693. if len(ydata) == ydata.count(None):
  694. GError(parent=self, showTraceback=False,
  695. message=_("Problem getting data from vector temporal"
  696. " dataset. Empty list of values."))
  697. return
  698. self.lookUp.AddDataset(yranges=ydata, xranges=xdata,
  699. datasetName=name)
  700. color = self.colors.next()
  701. self.plots.append(self.axes2d.plot(xdata, ydata, marker='o',
  702. color=color, label=name)[0])
  703. if self.csvpath:
  704. ycsv.append(ydata)
  705. if self.csvpath:
  706. self._writeCSV(xcsv, ycsv)
  707. self._setLabels(self.timeDataV[name]['granularity'])
  708. # legend
  709. handles, labels = self.axes2d.get_legend_handles_labels()
  710. self.axes2d.legend(loc=0)
  711. self.listWhereConditions = []
  712. def OnRedraw(self, event=None):
  713. """Required redrawing."""
  714. self.csvpath = self.csvButton.GetValue()
  715. self.header = self.headerCheck.IsChecked()
  716. if (os.path.exists(self.csvpath) and not self.overwrite):
  717. dlg = wx.MessageDialog(self, _("{pa} already exists, do you want "
  718. "to overwrite?".format(pa=self.csvpath)),
  719. _("File exists"),
  720. wx.OK | wx.CANCEL | wx.ICON_QUESTION)
  721. if dlg.ShowModal() != wx.ID_OK:
  722. dlg.Destroy()
  723. GError(parent=self, showTraceback=False,
  724. message=_("Please change name of output CSV file or "))
  725. return
  726. dlg.Destroy()
  727. self.init()
  728. datasetsR = self.datasetSelectR.GetValue().strip()
  729. datasetsV = self.datasetSelectV.GetValue().strip()
  730. if not datasetsR and not datasetsV:
  731. return
  732. try:
  733. getcoors = self.coorval.coordsField.GetValue()
  734. except:
  735. try:
  736. getcoors = self.coorval.GetValue()
  737. except:
  738. getcoors = None
  739. if getcoors and getcoors != '':
  740. try:
  741. coordx, coordy = getcoors.split(',')
  742. coordx, coordy = float(coordx), float(coordy)
  743. except (ValueError, AttributeError):
  744. try:
  745. coordx, coordy = self.coorval.GetValue().split(',')
  746. coordx, coordy = float(coordx), float(coordy)
  747. except (ValueError, AttributeError):
  748. GMessage(message=_("Incorrect coordinates format, should "
  749. "be: x,y"), parent=self)
  750. coors = [coordx, coordy]
  751. if coors:
  752. try:
  753. self.poi = Point(float(coors[0]), float(coors[1]))
  754. except GException:
  755. GError(parent=self, message=_("Invalid input coordinates"),
  756. showTraceback=False)
  757. return
  758. if not self.poi:
  759. GError(parent=self, message=_("Invalid input coordinates"),
  760. showTraceback=False)
  761. return
  762. bbox = self.region.get_bbox()
  763. if not bbox.contains(self.poi):
  764. GError(parent=self, message=_("Seed point outside the "
  765. "current region"),
  766. showTraceback=False)
  767. return
  768. # check raster dataset
  769. if datasetsR:
  770. datasetsR = datasetsR.split(',')
  771. try:
  772. datasetsR = self._checkDatasets(datasetsR, 'strds')
  773. if not datasetsR:
  774. return
  775. except GException:
  776. GError(parent=self, message=_("Invalid input raster dataset"),
  777. showTraceback=False)
  778. return
  779. if not self.poi:
  780. GError(parent=self, message=_("Invalid input coordinates"),
  781. showTraceback=False)
  782. return
  783. self.datasetsR = datasetsR
  784. # check vector dataset
  785. if datasetsV:
  786. datasetsV = datasetsV.split(',')
  787. try:
  788. datasetsV = self._checkDatasets(datasetsV, 'stvds')
  789. if not datasetsV:
  790. return
  791. except GException:
  792. GError(parent=self, message=_("Invalid input vector dataset"),
  793. showTraceback=False)
  794. return
  795. self.datasetsV = datasetsV
  796. self._redraw()
  797. def _redraw(self):
  798. """Readraw data.
  799. Decides if to draw also 3D and adjusts layout if needed.
  800. """
  801. if self.datasetsR:
  802. self._getSTRDdata(self.datasetsR)
  803. if self.datasetsV:
  804. self._getSTVDData(self.datasetsV)
  805. # axes3d are physically removed
  806. if not self.axes2d:
  807. self.axes2d = self.fig.add_subplot(1, 1, 1)
  808. self._drawFigure()
  809. def _checkDatasets(self, datasets, typ):
  810. """Checks and validates datasets.
  811. Reports also type of dataset (e.g. 'strds').
  812. :param list datasets: list of temporal dataset's name
  813. :return: (mapName, mapset, type)
  814. """
  815. validated = []
  816. tDict = tgis.tlist_grouped(type=typ, group_type=True, dbif=self.dbif)
  817. # nested list with '(map, mapset, etype)' items
  818. allDatasets = [[[(map, mapset, etype) for map in maps]
  819. for etype, maps in etypesDict.iteritems()]
  820. for mapset, etypesDict in tDict.iteritems()]
  821. # flatten this list
  822. if allDatasets:
  823. allDatasets = reduce(lambda x, y: x + y, reduce(lambda x, y: x + y,
  824. allDatasets))
  825. mapsets = tgis.get_tgis_c_library_interface().available_mapsets()
  826. allDatasets = [
  827. i
  828. for i in sorted(
  829. allDatasets, key=lambda l: mapsets.index(l[1]))]
  830. for dataset in datasets:
  831. errorMsg = _("Space time dataset <%s> not found.") % dataset
  832. if dataset.find("@") >= 0:
  833. nameShort, mapset = dataset.split('@', 1)
  834. indices = [n for n, (mapName, mapsetName, etype) in enumerate(
  835. allDatasets) if nameShort == mapName and mapsetName == mapset]
  836. else:
  837. indices = [n for n, (mapName, mapset, etype) in enumerate(
  838. allDatasets) if dataset == mapName]
  839. if len(indices) == 0:
  840. raise GException(errorMsg)
  841. elif len(indices) >= 2:
  842. dlg = wx.SingleChoiceDialog(
  843. self,
  844. message=_(
  845. "Please specify the "
  846. "space time dataset "
  847. "<%s>." % dataset),
  848. caption=_("Ambiguous dataset name"),
  849. choices=[
  850. ("%(map)s@%(mapset)s:"
  851. " %(etype)s" % {
  852. 'map': allDatasets[i][0],
  853. 'mapset': allDatasets[i][1],
  854. 'etype': allDatasets[i][2]}) for i in indices],
  855. style=wx.CHOICEDLG_STYLE | wx.OK)
  856. if dlg.ShowModal() == wx.ID_OK:
  857. index = dlg.GetSelection()
  858. validated.append(allDatasets[indices[index]])
  859. else:
  860. continue
  861. else:
  862. validated.append(allDatasets[indices[0]])
  863. return validated
  864. def OnHelp(self, event):
  865. """Function to show help"""
  866. RunCommand(prog='g.manual', quiet=True, entry='g.gui.tplot')
  867. def SetDatasets(self, rasters, vectors, coors, cats, attr, title, xlabel,
  868. ylabel, csvfile, head, overwrite):
  869. """Set the data
  870. :param list rasters: a list of temporal raster dataset's name
  871. :param list vectors: a list of temporal vector dataset's name
  872. :param list coors: a list with x/y coordinates
  873. :param list cats: a list with incld. categories of vector
  874. :param str attr: name of atribute of vectror data
  875. """
  876. if not (rasters or vectors) or not (coors or cats):
  877. return
  878. try:
  879. if rasters:
  880. self.datasetsR = self._checkDatasets(rasters, 'strds')
  881. if vectors:
  882. self.datasetsV = self._checkDatasets(vectors, 'stvds')
  883. if not (self.datasetsR or self.datasetsV):
  884. return
  885. except GException:
  886. GError(parent=self, message=_("Invalid input temporal dataset"),
  887. showTraceback=False)
  888. return
  889. if coors:
  890. try:
  891. self.poi = Point(float(coors[0]), float(coors[1]))
  892. except GException:
  893. GError(parent=self, message=_("Invalid input coordinates"),
  894. showTraceback=False)
  895. return
  896. try:
  897. self.coorval.coordsField.SetValue(','.join(coors))
  898. except:
  899. self.coorval.SetValue(','.join(coors))
  900. if self.datasetsV:
  901. vdatas = ','.join(map(lambda x: x[0] + '@' + x[1], self.datasetsV))
  902. self.datasetSelectV.SetValue(vdatas)
  903. if attr:
  904. self.attribute.SetValue(attr)
  905. if cats:
  906. self.cats.SetValue(cats)
  907. if self.datasetsR:
  908. self.datasetSelectR.SetValue(
  909. ','.join(map(lambda x: x[0] + '@' + x[1], self.datasetsR)))
  910. if title:
  911. self.title.SetValue(title)
  912. if xlabel:
  913. self.x.SetValue(xlabel)
  914. if ylabel:
  915. self.y.SetValue(ylabel)
  916. if csvfile:
  917. self.csvpath = csvfile
  918. self.header = head
  919. self.overwrite = overwrite
  920. self._redraw()
  921. def OnVectorSelected(self, event):
  922. """Update the controlbox related to stvds"""
  923. dataset = self.datasetSelectV.GetValue().strip()
  924. name = dataset.split('@')[0]
  925. mapset = dataset.split('@')[1] if len(dataset.split('@')) > 1 else ''
  926. found = False
  927. for each in tgis.tlist(type='stvds', dbif=self.dbif):
  928. each_name, each_mapset = each.split('@')
  929. if name == each_name:
  930. if mapset and mapset != each_mapset:
  931. continue
  932. dataset = name + '@' + each_mapset
  933. found = True
  934. break
  935. if found:
  936. try:
  937. vect_list = grass.read_command('t.vect.list', flags='u',
  938. input=dataset, column='name')
  939. except Exception:
  940. self.attribute.Clear()
  941. GError(
  942. parent=self,
  943. message=_("Invalid input temporal dataset"),
  944. showTraceback=False)
  945. return
  946. vect_list = list(set(sorted(vect_list.split())))
  947. for vec in vect_list:
  948. self.attribute.InsertColumns(vec, 1)
  949. else:
  950. self.attribute.Clear()
  951. class LookUp:
  952. """Helper class for searching info by coordinates"""
  953. def __init__(self, timeData, convert):
  954. self.data = {}
  955. self.timeData = timeData
  956. self.convert = convert
  957. def AddDataset(self, yranges, xranges, datasetName):
  958. if len(yranges) != len(xranges):
  959. GError(parent=self, showTraceback=False,
  960. message=_("Datasets have different number of values"))
  961. return
  962. self.data[datasetName] = {}
  963. for i in range(len(xranges)):
  964. self.data[datasetName][xranges[i]] = yranges[i]
  965. def GetInformation(self, x):
  966. values = {}
  967. for key, value in self.data.iteritems():
  968. if value[x]:
  969. values[key] = [self.convert(x), value[x]]
  970. if len(values) == 0:
  971. return None
  972. return self.timeData, values
  973. def InfoFormat(timeData, values):
  974. """Formats information about dataset"""
  975. text = []
  976. for key, val in values.iteritems():
  977. etype = timeData[key]['temporalDataType']
  978. if etype == 'strds':
  979. text.append(_("Space time raster dataset: %s") % key)
  980. elif etype == 'stvds':
  981. text.append(_("Space time vector dataset: %s") % key)
  982. elif etype == 'str3ds':
  983. text.append(_("Space time 3D raster dataset: %s") % key)
  984. text.append(_("Value for {date} is {val}".format(date=val[0],
  985. val=val[1])))
  986. text.append('\n')
  987. text.append(_("Press Del to dismiss."))
  988. return '\n'.join(text)
  989. class DataCursor(object):
  990. """A simple data cursor widget that displays the x,y location of a
  991. matplotlib artist when it is selected.
  992. Source: http://stackoverflow.com/questions/4652439/
  993. is-there-a-matplotlib-equivalent-of-matlabs-datacursormode/4674445
  994. """
  995. def __init__(self, artists, lookUp, formatFunction, convert,
  996. tolerance=5, offsets=(-30, 20), display_all=False):
  997. """Create the data cursor and connect it to the relevant figure.
  998. "artists" is the matplotlib artist or sequence of artists that will be
  999. selected.
  1000. "tolerance" is the radius (in points) that the mouse click must be
  1001. within to select the artist.
  1002. "offsets" is a tuple of (x,y) offsets in points from the selected
  1003. point to the displayed annotation box
  1004. "display_all" controls whether more than one annotation box will
  1005. be shown if there are multiple axes. Only one will be shown
  1006. per-axis, regardless.
  1007. """
  1008. self.lookUp = lookUp
  1009. self.formatFunction = formatFunction
  1010. self.offsets = offsets
  1011. self.display_all = display_all
  1012. if not cbook.iterable(artists):
  1013. artists = [artists]
  1014. self.artists = artists
  1015. self.convert = convert
  1016. self.axes = tuple(set(art.axes for art in self.artists))
  1017. self.figures = tuple(set(ax.figure for ax in self.axes))
  1018. self.annotations = {}
  1019. for ax in self.axes:
  1020. self.annotations[ax] = self.annotate(ax)
  1021. for artist in self.artists:
  1022. artist.set_picker(tolerance)
  1023. for fig in self.figures:
  1024. fig.canvas.mpl_connect('pick_event', self)
  1025. fig.canvas.mpl_connect('key_press_event', self.keyPressed)
  1026. def keyPressed(self, event):
  1027. """Key pressed - hide annotation if Delete was pressed"""
  1028. if event.key != 'delete':
  1029. return
  1030. for ax in self.axes:
  1031. self.annotations[ax].set_visible(False)
  1032. event.canvas.draw()
  1033. def annotate(self, ax):
  1034. """Draws and hides the annotation box for the given axis "ax"."""
  1035. annotation = ax.annotate(self.formatFunction, xy=(0, 0), ha='center',
  1036. xytext=self.offsets, va='bottom',
  1037. textcoords='offset points',
  1038. bbox=dict(boxstyle='round,pad=0.5',
  1039. fc='yellow', alpha=0.7),
  1040. arrowprops=dict(arrowstyle='->',
  1041. connectionstyle='arc3,rad=0'),
  1042. annotation_clip=False, multialignment='left')
  1043. annotation.set_visible(False)
  1044. return annotation
  1045. def __call__(self, event):
  1046. """Intended to be called through "mpl_connect"."""
  1047. # Rather than trying to interpolate, just display the clicked coords
  1048. # This will only be called if it's within "tolerance", anyway.
  1049. x, y = event.mouseevent.xdata, event.mouseevent.ydata
  1050. annotation = self.annotations[event.artist.axes]
  1051. if x is not None:
  1052. if not self.display_all:
  1053. # Hide any other annotation boxes...
  1054. for ann in self.annotations.values():
  1055. ann.set_visible(False)
  1056. if 'Line2D' in str(type(event.artist)):
  1057. xData = []
  1058. for a in event.artist.get_xdata():
  1059. try:
  1060. d = self.convert(a)
  1061. except:
  1062. d = a
  1063. xData.append(d)
  1064. x = xData[np.argmin(abs(xData - x))]
  1065. info = self.lookUp.GetInformation(x)
  1066. ys = zip(*info[1].values())[1]
  1067. if not info:
  1068. return
  1069. # Update the annotation in the current axis..
  1070. annotation.xy = x, max(ys)
  1071. text = self.formatFunction(*info)
  1072. annotation.set_text(text)
  1073. annotation.set_visible(True)
  1074. event.canvas.draw()