frame.py 24 KB

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