frame.py 24 KB

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