frame.py 24 KB

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