frame.py 24 KB

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