frame.py 24 KB

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