frame.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  1. """!
  2. @package frame
  3. @brief Timeline Tool
  4. Classes:
  5. - frame::DataCursor
  6. - frame::TimelineFrame
  7. - frame::LookUp
  8. (C) 2012-13 by the GRASS Development Team
  9. This program is free software under the GNU General Public License
  10. (>=v2). Read the file COPYING that comes with GRASS for details.
  11. @author Anna Kratochvilova <kratochanna gmail.com>
  12. """
  13. import os
  14. import sys
  15. import wx
  16. import signal
  17. from math import ceil
  18. from itertools import cycle
  19. import numpy as np
  20. try:
  21. import matplotlib
  22. # The recommended way to use wx with mpl is with the WXAgg
  23. # backend.
  24. matplotlib.use('WXAgg')
  25. from matplotlib.figure import Figure
  26. from matplotlib.backends.backend_wxagg import \
  27. FigureCanvasWxAgg as FigCanvas, \
  28. NavigationToolbar2WxAgg as NavigationToolbar
  29. import matplotlib.dates as mdates
  30. from matplotlib import cbook
  31. except ImportError:
  32. raise ImportError(_('The Timeline Tool needs "Matplotlib" package to be installed.'))
  33. if __name__ == '__main__':
  34. sys.path.append(os.path.join(os.environ['GISBASE'], "etc", "gui", "wxpython"))
  35. import grass.script as grass
  36. from core.utils import _
  37. import grass.temporal as tgis
  38. from core.gcmd import GError, GException, RunCommand
  39. from gui_core import gselect
  40. from core import globalvar
  41. ALPHA = 0.5
  42. COLORS = ['b', 'g', 'r', 'c', 'm', 'y', 'k']
  43. def check_version(*version):
  44. """!Checks if given version or newer is installed"""
  45. versionInstalled = []
  46. for i in matplotlib.__version__.split('.'):
  47. try:
  48. v = int(i)
  49. versionInstalled.append(v)
  50. except ValueError:
  51. versionInstalled.append(0)
  52. if versionInstalled < list(version):
  53. return False
  54. else:
  55. return True
  56. class TimelineFrame(wx.Frame):
  57. """!The main frame of the application"""
  58. def __init__(self, parent):
  59. wx.Frame.__init__(self, parent, id=wx.ID_ANY, title=_("Timeline Tool"))
  60. tgis.init()
  61. self.is_standalone = False
  62. # Check if a parent exists. The module g.gui.timeline runs in stand alone mode
  63. # in case there is no parent.
  64. if parent is None:
  65. self.is_standalone = True
  66. self.datasets = []
  67. self.timeData = {}
  68. self._layout()
  69. self.temporalType = None
  70. self.unit = None
  71. # We create a database interface here to speedup the GUI
  72. self.dbif = tgis.SQLDatabaseInterfaceConnection()
  73. self.dbif.connect()
  74. def __del__(self):
  75. """!Close the database interface and stop the messenger and C-interface
  76. subprocesses.
  77. """
  78. if self.dbif.connected is True:
  79. self.dbif.close()
  80. tgis.stop_subprocesses()
  81. # We need to kill the child process explicitely to avoid
  82. # orphaned g.gui.timeline stand-alone processes.
  83. if self.is_standalone is True:
  84. pid = os.getpid()
  85. os.kill(pid, signal.SIGQUIT) #or signal.SIGKILL
  86. def _layout(self):
  87. """!Creates the main panel with all the controls on it:
  88. * mpl canvas
  89. * mpl navigation toolbar
  90. * Control panel for interaction
  91. """
  92. self.panel = wx.Panel(self)
  93. # Create the mpl Figure and FigCanvas objects.
  94. # 5x4 inches, 100 dots-per-inch
  95. #
  96. # color = wx.SystemSettings.GetColour(wx.SYS_COLOUR_BACKGROUND)
  97. self.fig = Figure((5.0, 4.0), facecolor=(1, 1, 1))
  98. self.canvas = FigCanvas(self.panel, wx.ID_ANY, self.fig)
  99. # axes are initialized later
  100. self.axes2d = None
  101. self.axes3d = None
  102. # Create the navigation toolbar, tied to the canvas
  103. #
  104. self.toolbar = NavigationToolbar(self.canvas)
  105. #
  106. # Layout
  107. #
  108. self.vbox = wx.BoxSizer(wx.VERTICAL)
  109. self.vbox.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.EXPAND)
  110. self.vbox.Add(self.toolbar, 0, wx.EXPAND)
  111. self.vbox.AddSpacer(10)
  112. gridSizer = wx.GridBagSizer(hgap=5, vgap=5)
  113. self.datasetSelect = gselect.Select(parent=self.panel, id=wx.ID_ANY,
  114. size=globalvar.DIALOG_GSELECT_SIZE,
  115. type='stds', multiple=True)
  116. self.drawButton = wx.Button(self.panel, id=wx.ID_ANY, label=_("Draw"))
  117. self.drawButton.Bind(wx.EVT_BUTTON, self.OnRedraw)
  118. self.helpButton = wx.Button(self.panel, id=wx.ID_ANY, label=_("Help"))
  119. self.helpButton.Bind(wx.EVT_BUTTON, self.OnHelp)
  120. self.view3dCheck = wx.CheckBox(self.panel, id=wx.ID_ANY,
  121. label=_("3D plot of spatio-temporal extents"))
  122. self.view3dCheck.Bind(wx.EVT_CHECKBOX, self.OnRedraw)
  123. if not check_version(1, 0, 0):
  124. self.view3dCheck.SetLabel(_("3D plot of spatio-temporal extents "
  125. "(matplotlib >= 1.0.0)"))
  126. self.view3dCheck.Disable()
  127. gridSizer.Add(wx.StaticText(self.panel, id=wx.ID_ANY,
  128. label=_("Select space time dataset(s):")),
  129. pos=(0, 0), flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL)
  130. gridSizer.Add(self.datasetSelect, pos=(1, 0), flag=wx.EXPAND)
  131. gridSizer.Add(self.drawButton, pos=(1, 1), flag=wx.EXPAND)
  132. gridSizer.Add(self.helpButton, pos=(1, 2), flag=wx.EXPAND)
  133. gridSizer.Add(self.view3dCheck, pos=(2, 0), flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL)
  134. self.vbox.Add(gridSizer, proportion=0, flag=wx.EXPAND | wx.ALL, border=10)
  135. self.panel.SetSizer(self.vbox)
  136. self.vbox.Fit(self)
  137. def _getData(self, timeseries):
  138. """!Load data and read properties"""
  139. self.timeData = {}
  140. mode = None
  141. unit = None
  142. for series in timeseries:
  143. name = series[0] + '@' + series[1]
  144. etype = series[2]
  145. sp = tgis.dataset_factory(etype, name)
  146. if not sp.is_in_db(dbif=self.dbif):
  147. GError(self, message=_("Dataset <%s> not found in temporal database") % (name))
  148. return
  149. sp.select(dbif=self.dbif)
  150. self.timeData[name] = {}
  151. self.timeData[name]['elementType'] = series[2]
  152. self.timeData[name]['temporalType'] = sp.get_temporal_type() # abs/rel
  153. if mode is None:
  154. mode = self.timeData[name]['temporalType']
  155. elif self.timeData[name]['temporalType'] != mode:
  156. GError(parent=self, message=_("Datasets have different temporal type "
  157. "(absolute x relative), which is not allowed."))
  158. return
  159. # check topology
  160. maps = sp.get_registered_maps_as_objects(dbif=self.dbif)
  161. self.timeData[name]['validTopology'] = sp.check_temporal_topology(maps=maps, dbif=self.dbif)
  162. self.timeData[name]['temporalMapType'] = sp.get_map_time() # point/interval
  163. self.timeData[name]['unit'] = None # only with relative
  164. if self.timeData[name]['temporalType'] == 'relative':
  165. start, end, self.timeData[name]['unit'] = sp.get_relative_time()
  166. if unit is None:
  167. unit = self.timeData[name]['unit']
  168. elif self.timeData[name]['unit'] != unit:
  169. GError(self, _("Datasets have different time unit which is not allowed."))
  170. return
  171. self.timeData[name]['start_datetime'] = []
  172. # self.timeData[name]['start_plot'] = []
  173. self.timeData[name]['end_datetime'] = []
  174. # self.timeData[name]['end_plot'] = []
  175. self.timeData[name]['names'] = []
  176. self.timeData[name]['north'] = []
  177. self.timeData[name]['south'] = []
  178. self.timeData[name]['west'] = []
  179. self.timeData[name]['east'] = []
  180. columns = ','.join(['name', 'start_time', 'end_time',
  181. 'north', 'south', 'west', 'east'])
  182. rows = sp.get_registered_maps(columns=columns, where=None,
  183. order='start_time', dbif=self.dbif)
  184. if rows is None:
  185. rows = []
  186. for row in rows:
  187. mapName, start, end, north, south, west, east = row
  188. self.timeData[name]['start_datetime'].append(start)
  189. self.timeData[name]['end_datetime'].append(end)
  190. self.timeData[name]['names'].append(mapName)
  191. self.timeData[name]['north'].append(north)
  192. self.timeData[name]['south'].append(south)
  193. self.timeData[name]['west'].append(west)
  194. self.timeData[name]['east'].append(east)
  195. self.temporalType = mode
  196. self.unit = unit
  197. def _draw3dFigure(self):
  198. """!Draws 3d view (spatio-temporal extents).
  199. Only for matplotlib versions >= 1.0.0.
  200. Earlier versions cannot draw time ticks and alpha
  201. and it has a slightly different API.
  202. """
  203. self.axes3d.clear()
  204. self.axes3d.grid(False)
  205. # self.axes3d.grid(True)
  206. if self.temporalType == 'absolute':
  207. if check_version(1, 1, 0):
  208. self.axes3d.zaxis_date()
  209. convert = mdates.date2num
  210. else:
  211. convert = lambda x: x
  212. colors = cycle(COLORS)
  213. plots = []
  214. for name in self.datasets:
  215. name = name[0] + '@' + name[1]
  216. startZ = convert(self.timeData[name]['start_datetime'])
  217. mapType = self.timeData[name]['temporalMapType']
  218. if mapType == 'interval':
  219. dZ = convert(self.timeData[name]['end_datetime']) - startZ
  220. else:
  221. dZ = [0] * len(startZ)
  222. startX = self.timeData[name]['west']
  223. dX = self.timeData[name]['east'] - np.array(startX)
  224. startY = self.timeData[name]['south']
  225. dY = self.timeData[name]['north'] - np.array(startY)
  226. color = colors.next()
  227. plots.append(self.axes3d.bar3d(startX, startY, startZ, dX, dY, dZ,
  228. color=color, alpha=ALPHA))
  229. params = grass.read_command('g.proj', flags='g')
  230. params = grass.parse_key_val(params)
  231. if 'unit' in params:
  232. self.axes3d.set_xlabel(_("X [%s]") % params['unit'])
  233. self.axes3d.set_ylabel(_("Y [%s]") % params['unit'])
  234. else:
  235. self.axes3d.set_xlabel(_("X"))
  236. self.axes3d.set_ylabel(_("Y"))
  237. self.axes3d.set_zlabel(_('Time'))
  238. self.axes3d.mouse_init()
  239. self.canvas.draw()
  240. def _draw2dFigure(self):
  241. """!Draws 2D plot (temporal extents)"""
  242. self.axes2d.clear()
  243. self.axes2d.grid(True)
  244. if self.temporalType == 'absolute':
  245. self.axes2d.xaxis_date()
  246. self.fig.autofmt_xdate()
  247. convert = mdates.date2num
  248. else:
  249. convert = lambda x: x
  250. colors = cycle(COLORS)
  251. yticksNames = []
  252. yticksPos = []
  253. plots = []
  254. lookUp = LookUp(self.timeData)
  255. for i, name in enumerate(self.datasets):
  256. yticksNames.append(name[0]) # just name; with mapset it would be long
  257. name = name[0] + '@' + name[1]
  258. yticksPos.append(i)
  259. barData = []
  260. pointData = []
  261. mapType = self.timeData[name]['temporalMapType']
  262. start = convert(self.timeData[name]['start_datetime'])
  263. # TODO: mixed
  264. if mapType == 'interval':
  265. end = convert(self.timeData[name]['end_datetime'])
  266. lookUpData = zip(start, end)
  267. duration = end - np.array(start)
  268. barData = zip(start, duration)
  269. lookUp.AddDataset(type_='bar', yrange=(i - 0.1, i + 0.1),
  270. xranges=lookUpData, datasetName=name)
  271. else:
  272. # self.timeData[name]['end_plot'] = None
  273. pointData = start
  274. lookUp.AddDataset(type_='point', yrange=i, xranges=pointData, datasetName=name)
  275. color = colors.next()
  276. if mapType == 'interval':
  277. plots.append(self.axes2d.broken_barh(xranges=barData, yrange=(i - 0.1, 0.2),
  278. facecolors=color, alpha=ALPHA))
  279. else:
  280. plots.append(self.axes2d.plot(pointData, [i] * len(pointData),
  281. marker='o', linestyle='None', color=color)[0])
  282. if self.temporalType == 'absolute':
  283. pass
  284. # self.axes2d.set_xlabel(_("Time"))
  285. else:
  286. self.axes2d.set_xlabel(_("Time [%s]") % self.unit)
  287. self.axes2d.set_yticks(yticksPos)
  288. self.axes2d.set_yticklabels(yticksNames)
  289. self.axes2d.set_ylim(min(yticksPos) - 1, max(yticksPos) + 1)
  290. # adjust xlim
  291. xlim = self.axes2d.get_xlim()
  292. padding = ceil((xlim[1] - xlim[0]) / 20.)
  293. self.axes2d.set_xlim(xlim[0] - padding, xlim[1] + padding)
  294. self.canvas.draw()
  295. DataCursor(plots, lookUp, InfoFormat)
  296. def OnRedraw(self, event):
  297. """!Required redrawing."""
  298. datasets = self.datasetSelect.GetValue().strip()
  299. if not datasets:
  300. return
  301. datasets = datasets.split(',')
  302. try:
  303. datasets = self._checkDatasets(datasets)
  304. except GException:
  305. GError(parent=self, message=_("Invalid input data"))
  306. return
  307. self.datasets = datasets
  308. self._redraw()
  309. def _redraw(self):
  310. """!Readraw data.
  311. Decides if to draw also 3D and adjusts layout if needed.
  312. """
  313. self._getData(self.datasets)
  314. # axes3d are physically removed
  315. if not self.axes2d:
  316. self.axes2d = self.fig.add_subplot(1, 1, 1)
  317. self._draw2dFigure()
  318. if check_version(1, 0, 0):
  319. if self.view3dCheck.IsChecked():
  320. self.axes2d.change_geometry(2, 1, 1)
  321. if not self.axes3d:
  322. # do not remove this import - unused but it is required for 3D
  323. from mpl_toolkits.mplot3d import Axes3D # pylint: disable=W0611
  324. self.axes3d = self.fig.add_subplot(2, 1, 2, projection='3d')
  325. self.axes3d.set_visible(True)
  326. self._draw3dFigure()
  327. else:
  328. if self.axes3d:
  329. self.fig.delaxes(self.axes3d)
  330. self.axes3d = None
  331. self.axes2d.change_geometry(1, 1, 1)
  332. self.canvas.draw()
  333. def _checkDatasets(self, datasets):
  334. """!Checks and validates datasets.
  335. Reports also type of dataset (e.g. 'strds').
  336. @return (mapName, mapset, type)
  337. """
  338. validated = []
  339. tDict = tgis.tlist_grouped('stds', group_type=True, dbif=self.dbif)
  340. # nested list with '(map, mapset, etype)' items
  341. allDatasets = [[[(map, mapset, etype) for map in maps]
  342. for etype, maps in etypesDict.iteritems()]
  343. for mapset, etypesDict in tDict.iteritems()]
  344. # flatten this list
  345. allDatasets = reduce(lambda x, y: x + y, reduce(lambda x, y: x + y, allDatasets))
  346. for dataset in datasets:
  347. errorMsg = _("Space time dataset <%s> not found.") % dataset
  348. if dataset.find("@") >= 0:
  349. nameShort, mapset = dataset.split('@', 1)
  350. indices = [n for n, (mapName, mapsetName, etype) in enumerate(allDatasets)
  351. if nameShort == mapName and mapsetName == mapset]
  352. else:
  353. indices = [n for n, (mapName, mapset, etype) in enumerate(allDatasets)
  354. if dataset == mapName]
  355. if len(indices) == 0:
  356. raise GException(errorMsg)
  357. elif len(indices) >= 2:
  358. dlg = wx.SingleChoiceDialog(self,
  359. message=_("Please specify the space time dataset <%s>." % dataset),
  360. caption=_("Ambiguous dataset name"),
  361. choices=[("%(map)s@%(mapset)s: %(etype)s" % {'map': allDatasets[i][0],
  362. 'mapset': allDatasets[i][1],
  363. 'etype': allDatasets[i][2]})
  364. for i in indices],
  365. style=wx.CHOICEDLG_STYLE | wx.OK)
  366. if dlg.ShowModal() == wx.ID_OK:
  367. index = dlg.GetSelection()
  368. validated.append(allDatasets[indices[index]])
  369. else:
  370. validated.append(allDatasets[indices[0]])
  371. return validated
  372. def OnHelp(self, event):
  373. RunCommand('g.manual', quiet=True, entry='g.gui.timeline')
  374. # interface
  375. def SetDatasets(self, datasets):
  376. """!Set data"""
  377. if not datasets:
  378. return
  379. try:
  380. datasets = self._checkDatasets(datasets)
  381. except GException:
  382. GError(parent=self, message=_("Invalid input data"))
  383. return
  384. self.datasets = datasets
  385. self.datasetSelect.SetValue(','.join(map(lambda x: x[0] + '@' + x[1], datasets)))
  386. self._redraw()
  387. def Show3D(self, show):
  388. """!Show also 3D if possible"""
  389. if check_version(1, 0, 0):
  390. self.view3dCheck.SetValue(show)
  391. class LookUp:
  392. """!Helper class for searching info by coordinates"""
  393. def __init__(self, timeData):
  394. self.data = {}
  395. self.timeData = timeData
  396. def AddDataset(self, type_, yrange, xranges, datasetName):
  397. if type_ == 'bar':
  398. self.data[yrange] = {'name': datasetName}
  399. for i, (start, end) in enumerate(xranges):
  400. self.data[yrange][(start, end)] = i
  401. elif type_ == 'point':
  402. self.data[(yrange, yrange)] = {'name': datasetName}
  403. for i, start in enumerate(xranges):
  404. self.data[(yrange, yrange)][(start, start)] = i
  405. def GetInformation(self, x, y):
  406. keys = None
  407. for keyY in self.data.keys():
  408. if keyY[0] <= y <= keyY[1]:
  409. for keyX in self.data[keyY].keys():
  410. if keyX != 'name' and keyX[0] <= x <= keyX[1]:
  411. keys = keyY, keyX
  412. break
  413. if keys:
  414. break
  415. if not keys:
  416. return None
  417. datasetName = self.data[keys[0]]['name']
  418. mapIndex = self.data[keys[0]][keys[1]]
  419. return self.timeData, datasetName, mapIndex
  420. def InfoFormat(timeData, datasetName, mapIndex):
  421. """!Formats information about dataset"""
  422. text = []
  423. etype = timeData[datasetName]['elementType']
  424. name, mapset = datasetName.split('@')
  425. if etype == 'strds':
  426. text.append(_("Space time raster dataset: %s") % name)
  427. elif etype == 'stvds':
  428. text.append(_("Space time vector dataset: %s") % name)
  429. elif etype == 'str3ds':
  430. text.append(_("Space time 3D raster dataset: %s") % name)
  431. text.append(_("Mapset: %s") % mapset)
  432. text.append(_("Map name: %s") % timeData[datasetName]['names'][mapIndex])
  433. text.append(_("Start time: %s") % timeData[datasetName]['start_datetime'][mapIndex])
  434. text.append(_("End time: %s") % timeData[datasetName]['end_datetime'][mapIndex])
  435. if not timeData[datasetName]['validTopology']:
  436. text.append(_("WARNING: invalid topology"))
  437. text.append(_("\nPress Del to dismiss."))
  438. return '\n'.join(text)
  439. class DataCursor(object):
  440. """A simple data cursor widget that displays the x,y location of a
  441. matplotlib artist when it is selected.
  442. Source: http://stackoverflow.com/questions/4652439/
  443. is-there-a-matplotlib-equivalent-of-matlabs-datacursormode/4674445
  444. """
  445. def __init__(self, artists, lookUp, formatFunction, tolerance=5, offsets=(-30, 30),
  446. display_all=False):
  447. """Create the data cursor and connect it to the relevant figure.
  448. "artists" is the matplotlib artist or sequence of artists that will be
  449. selected.
  450. "tolerance" is the radius (in points) that the mouse click must be
  451. within to select the artist.
  452. "offsets" is a tuple of (x,y) offsets in points from the selected
  453. point to the displayed annotation box
  454. "display_all" controls whether more than one annotation box will
  455. be shown if there are multiple axes. Only one will be shown
  456. per-axis, regardless.
  457. """
  458. self.lookUp = lookUp
  459. self.formatFunction = formatFunction
  460. self.offsets = offsets
  461. self.display_all = display_all
  462. if not cbook.iterable(artists):
  463. artists = [artists]
  464. self.artists = artists
  465. self.axes = tuple(set(art.axes for art in self.artists))
  466. self.figures = tuple(set(ax.figure for ax in self.axes))
  467. self.annotations = {}
  468. for ax in self.axes:
  469. self.annotations[ax] = self.annotate(ax)
  470. for artist in self.artists:
  471. artist.set_picker(tolerance)
  472. for fig in self.figures:
  473. fig.canvas.mpl_connect('pick_event', self)
  474. fig.canvas.mpl_connect('key_press_event', self.keyPressed)
  475. def keyPressed(self, event):
  476. """!Key pressed - hide annotation if Delete was pressed"""
  477. if event.key != 'delete':
  478. return
  479. for ax in self.axes:
  480. self.annotations[ax].set_visible(False)
  481. event.canvas.draw()
  482. def annotate(self, ax):
  483. """Draws and hides the annotation box for the given axis "ax"."""
  484. annotation = ax.annotate(self.formatFunction, xy=(0, 0), ha='center',
  485. xytext=self.offsets, textcoords='offset points', va='bottom',
  486. bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.7),
  487. arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0'),
  488. annotation_clip=False, multialignment='left')
  489. annotation.set_visible(False)
  490. return annotation
  491. def __call__(self, event):
  492. """Intended to be called through "mpl_connect"."""
  493. # Rather than trying to interpolate, just display the clicked coords
  494. # This will only be called if it's within "tolerance", anyway.
  495. x, y = event.mouseevent.xdata, event.mouseevent.ydata
  496. annotation = self.annotations[event.artist.axes]
  497. if x is not None:
  498. if not self.display_all:
  499. # Hide any other annotation boxes...
  500. for ann in self.annotations.values():
  501. ann.set_visible(False)
  502. # Update the annotation in the current axis..
  503. annotation.xy = x, y
  504. if 'Line2D' in str(type(event.artist)):
  505. y = event.artist.get_ydata()[0]
  506. xData = event.artist.get_xdata()
  507. x = xData[np.argmin(abs(xData - x))]
  508. info = self.lookUp.GetInformation(x, y)
  509. if not info:
  510. return
  511. text = self.formatFunction(*info)
  512. annotation.set_text(text)
  513. annotation.set_visible(True)
  514. event.canvas.draw()
  515. def run(parent=None, datasets=None):
  516. frame = TimelineFrame(parent)
  517. if datasets:
  518. frame.SetDatasets(datasets)
  519. frame.Show()
  520. if __name__ == '__main__':
  521. run()