frame.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  1. """
  2. @package frame
  3. @brief Timeline Tool
  4. Classes:
  5. - frame::DataCursor
  6. - frame::TimelineFrame
  7. - frame::LookUp
  8. (C) 2012-2016 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. from math import ceil
  16. from itertools import cycle
  17. import numpy as np
  18. import wx
  19. from functools import reduce
  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 as e:
  32. raise ImportError(_('The Timeline Tool needs the "matplotlib" '
  33. '(python-matplotlib) package to be installed. {0}').format(e))
  34. import grass.script as grass
  35. from core.utils import _
  36. import grass.temporal as tgis
  37. from core.gcmd import GError, GException, RunCommand
  38. from gui_core import gselect
  39. from core import globalvar
  40. ALPHA = 0.5
  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 = wx.Button(self.panel, id=wx.ID_ANY, label=_("Draw"))
  112. self.drawButton.Bind(wx.EVT_BUTTON, self.OnRedraw)
  113. self.helpButton = wx.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(wx.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 = colors.next()
  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 = zip(start, end)
  285. duration = end - np.array(start)
  286. barData = 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 = colors.next()
  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. alpha=ALPHA))
  307. else:
  308. plots.append(
  309. self.axes2d.plot(
  310. pointData,
  311. [i] * len(pointData),
  312. marker='o',
  313. linestyle='None',
  314. color=color)[0])
  315. if self.temporalType == 'absolute':
  316. self.axes2d.xaxis_date()
  317. self.fig.autofmt_xdate()
  318. # self.axes2d.set_xlabel(_("Time"))
  319. else:
  320. self.axes2d.set_xlabel(_("Time [%s]") % self.unit)
  321. self.axes2d.set_yticks(yticksPos)
  322. self.axes2d.set_yticklabels(yticksNames)
  323. self.axes2d.set_ylim(min(yticksPos) - 1, max(yticksPos) + 1)
  324. # adjust xlim
  325. xlim = self.axes2d.get_xlim()
  326. padding = ceil((xlim[1] - xlim[0]) / 20.)
  327. self.axes2d.set_xlim(xlim[0] - padding, xlim[1] + padding)
  328. self.canvas.draw()
  329. DataCursor(plots, lookUp, InfoFormat)
  330. def OnRedraw(self, event):
  331. """Required redrawing."""
  332. datasets = self.datasetSelect.GetValue().strip()
  333. if not datasets:
  334. return
  335. datasets = datasets.split(',')
  336. try:
  337. datasets = self._checkDatasets(datasets)
  338. if not datasets:
  339. return
  340. except GException as e:
  341. GError(parent=self, message=unicode(e), showTraceback=False)
  342. return
  343. self.datasets = datasets
  344. self._redraw()
  345. def _redraw(self):
  346. """Readraw data.
  347. Decides if to draw also 3D and adjusts layout if needed.
  348. """
  349. self._getData(self.datasets)
  350. # axes3d are physically removed
  351. if not self.axes2d:
  352. self.axes2d = self.fig.add_subplot(1, 1, 1)
  353. self._draw2dFigure()
  354. if check_version(1, 0, 0):
  355. if self.view3dCheck.IsChecked():
  356. self.axes2d.change_geometry(2, 1, 1)
  357. if not self.axes3d:
  358. # do not remove this import - unused but it is required for
  359. # 3D
  360. from mpl_toolkits.mplot3d import Axes3D # pylint: disable=W0611
  361. self.axes3d = self.fig.add_subplot(
  362. 2, 1, 2, projection='3d')
  363. self.axes3d.set_visible(True)
  364. self._draw3dFigure()
  365. else:
  366. if self.axes3d:
  367. self.fig.delaxes(self.axes3d)
  368. self.axes3d = None
  369. self.axes2d.change_geometry(1, 1, 1)
  370. self.canvas.draw()
  371. def _checkDatasets(self, datasets):
  372. """Checks and validates datasets.
  373. Reports also type of dataset (e.g. 'strds').
  374. :return: (mapName, mapset, type)
  375. """
  376. validated = []
  377. tDict = tgis.tlist_grouped('stds', group_type=True, dbif=self.dbif)
  378. # nested list with '(map, mapset, etype)' items
  379. allDatasets = [[[(map, mapset, etype) for map in maps]
  380. for etype, maps in etypesDict.iteritems()]
  381. for mapset, etypesDict in tDict.iteritems()]
  382. # flatten this list
  383. if allDatasets:
  384. allDatasets = reduce(
  385. lambda x,
  386. y: x + y,
  387. reduce(
  388. lambda x,
  389. y: x + y,
  390. allDatasets))
  391. mapsets = tgis.get_tgis_c_library_interface().available_mapsets()
  392. allDatasets = [
  393. i
  394. for i in sorted(
  395. allDatasets, key=lambda l: mapsets.index(l[1]))]
  396. for dataset in datasets:
  397. errorMsg = _("Space time dataset <%s> not found.") % dataset
  398. if dataset.find("@") >= 0:
  399. nameShort, mapset = dataset.split('@', 1)
  400. indices = [n for n, (mapName, mapsetName, etype) in enumerate(
  401. allDatasets) if nameShort == mapName and mapsetName == mapset]
  402. else:
  403. indices = [n for n, (mapName, mapset, etype) in enumerate(
  404. allDatasets) if dataset == mapName]
  405. if len(indices) == 0:
  406. raise GException(errorMsg)
  407. elif len(indices) >= 2:
  408. dlg = wx.SingleChoiceDialog(
  409. self,
  410. message=_(
  411. "Please specify the space time dataset <%s>." %
  412. dataset),
  413. caption=_("Ambiguous dataset name"),
  414. choices=[("%(map)s@%(mapset)s: %(etype)s" %
  415. {'map': allDatasets[i][0],
  416. 'mapset': allDatasets[i][1],
  417. 'etype': allDatasets[i][2]}) for i in indices],
  418. style=wx.CHOICEDLG_STYLE | wx.OK)
  419. if dlg.ShowModal() == wx.ID_OK:
  420. index = dlg.GetSelection()
  421. validated.append(allDatasets[indices[index]])
  422. else:
  423. continue
  424. else:
  425. validated.append(allDatasets[indices[0]])
  426. return validated
  427. def OnHelp(self, event):
  428. RunCommand('g.manual', quiet=True, entry='g.gui.timeline')
  429. # interface
  430. def SetDatasets(self, datasets):
  431. """Set data"""
  432. if not datasets:
  433. return
  434. try:
  435. datasets = self._checkDatasets(datasets)
  436. if not datasets:
  437. return
  438. except GException as e:
  439. GError(parent=self, message=unicode(e), showTraceback=False)
  440. return
  441. self.datasets = datasets
  442. self.datasetSelect.SetValue(
  443. ','.join(map(lambda x: x[0] + '@' + x[1], datasets)))
  444. self._redraw()
  445. def Show3D(self, show):
  446. """Show also 3D if possible"""
  447. if check_version(1, 0, 0):
  448. self.view3dCheck.SetValue(show)
  449. class LookUp:
  450. """Helper class for searching info by coordinates"""
  451. def __init__(self, timeData):
  452. self.data = {}
  453. self.timeData = timeData
  454. def AddDataset(self, type_, yrange, xranges, datasetName):
  455. if type_ == 'bar':
  456. self.data[yrange] = {'name': datasetName}
  457. for i, (start, end) in enumerate(xranges):
  458. self.data[yrange][(start, end)] = i
  459. elif type_ == 'point':
  460. self.data[(yrange, yrange)] = {'name': datasetName}
  461. for i, start in enumerate(xranges):
  462. self.data[(yrange, yrange)][(start, start)] = i
  463. def GetInformation(self, x, y):
  464. keys = None
  465. for keyY in self.data.keys():
  466. if keyY[0] <= y <= keyY[1]:
  467. for keyX in self.data[keyY].keys():
  468. if keyX != 'name' and keyX[0] <= x <= keyX[1]:
  469. keys = keyY, keyX
  470. break
  471. if keys:
  472. break
  473. if not keys:
  474. return None
  475. datasetName = self.data[keys[0]]['name']
  476. mapIndex = self.data[keys[0]][keys[1]]
  477. return self.timeData, datasetName, mapIndex
  478. def InfoFormat(timeData, datasetName, mapIndex):
  479. """Formats information about dataset"""
  480. text = []
  481. etype = timeData[datasetName]['elementType']
  482. name, mapset = datasetName.split('@')
  483. if etype == 'strds':
  484. text.append(_("Space time raster dataset: %s") % name)
  485. elif etype == 'stvds':
  486. text.append(_("Space time vector dataset: %s") % name)
  487. elif etype == 'str3ds':
  488. text.append(_("Space time 3D raster dataset: %s") % name)
  489. text.append(_("Mapset: %s") % mapset)
  490. text.append(_("Map name: %s") % timeData[datasetName]['names'][mapIndex])
  491. text.append(
  492. _("Start time: %s") %
  493. timeData[datasetName]['start_datetime'][mapIndex])
  494. text.append(
  495. _("End time: %s") %
  496. timeData[datasetName]['end_datetime'][mapIndex])
  497. if not timeData[datasetName]['validTopology']:
  498. text.append(_("WARNING: invalid topology"))
  499. text.append(_("\nPress Del to dismiss."))
  500. return '\n'.join(text)
  501. class DataCursor(object):
  502. """A simple data cursor widget that displays the x,y location of a
  503. matplotlib artist when it is selected.
  504. Source: http://stackoverflow.com/questions/4652439/
  505. is-there-a-matplotlib-equivalent-of-matlabs-datacursormode/4674445
  506. """
  507. def __init__(
  508. self, artists, lookUp, formatFunction, tolerance=5,
  509. offsets=(-30, 30),
  510. display_all=False):
  511. """Create the data cursor and connect it to the relevant figure.
  512. "artists" is the matplotlib artist or sequence of artists that will be
  513. selected.
  514. "tolerance" is the radius (in points) that the mouse click must be
  515. within to select the artist.
  516. "offsets" is a tuple of (x,y) offsets in points from the selected
  517. point to the displayed annotation box
  518. "display_all" controls whether more than one annotation box will
  519. be shown if there are multiple axes. Only one will be shown
  520. per-axis, regardless.
  521. """
  522. self.lookUp = lookUp
  523. self.formatFunction = formatFunction
  524. self.offsets = offsets
  525. self.display_all = display_all
  526. if not cbook.iterable(artists):
  527. artists = [artists]
  528. self.artists = artists
  529. self.axes = tuple(set(art.axes for art in self.artists))
  530. self.figures = tuple(set(ax.figure for ax in self.axes))
  531. self.annotations = {}
  532. for ax in self.axes:
  533. self.annotations[ax] = self.annotate(ax)
  534. for artist in self.artists:
  535. artist.set_picker(tolerance)
  536. for fig in self.figures:
  537. fig.canvas.mpl_connect('pick_event', self)
  538. fig.canvas.mpl_connect('key_press_event', self.keyPressed)
  539. def keyPressed(self, event):
  540. """Key pressed - hide annotation if Delete was pressed"""
  541. if event.key != 'delete':
  542. return
  543. for ax in self.axes:
  544. self.annotations[ax].set_visible(False)
  545. event.canvas.draw()
  546. def annotate(self, ax):
  547. """Draws and hides the annotation box for the given axis "ax"."""
  548. annotation = ax.annotate(
  549. self.formatFunction, xy=(0, 0),
  550. ha='center', xytext=self.offsets, textcoords='offset points',
  551. va='bottom',
  552. bbox=dict(
  553. boxstyle='round,pad=0.5', fc='yellow', alpha=0.7),
  554. arrowprops=dict(
  555. arrowstyle='->', connectionstyle='arc3,rad=0'),
  556. annotation_clip=False, multialignment='left')
  557. annotation.set_visible(False)
  558. return annotation
  559. def __call__(self, event):
  560. """Intended to be called through "mpl_connect"."""
  561. # Rather than trying to interpolate, just display the clicked coords
  562. # This will only be called if it's within "tolerance", anyway.
  563. x, y = event.mouseevent.xdata, event.mouseevent.ydata
  564. annotation = self.annotations[event.artist.axes]
  565. if x is not None:
  566. if not self.display_all:
  567. # Hide any other annotation boxes...
  568. for ann in self.annotations.values():
  569. ann.set_visible(False)
  570. # Update the annotation in the current axis..
  571. annotation.xy = x, y
  572. if 'Line2D' in str(type(event.artist)):
  573. y = event.artist.get_ydata()[0]
  574. xData = event.artist.get_xdata()
  575. x = xData[np.argmin(abs(xData - x))]
  576. info = self.lookUp.GetInformation(x, y)
  577. if not info:
  578. return
  579. text = self.formatFunction(*info)
  580. annotation.set_text(text)
  581. annotation.set_visible(True)
  582. event.canvas.draw()
  583. def run(parent=None, datasets=None):
  584. frame = TimelineFrame(parent)
  585. if datasets:
  586. frame.SetDatasets(datasets)
  587. frame.Show()
  588. if __name__ == '__main__':
  589. run()