frame.py 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197
  1. #!/usr/bin/env python3
  2. """
  3. @package frame
  4. @brief Temporal Plot Tool
  5. Classes:
  6. - frame::DataCursor
  7. - frame::TplotFrame
  8. - frame::LookUp
  9. (C) 2012-2016 by the GRASS Development Team
  10. This program is free software under the GNU General Public License
  11. (>=v2). Read the file COPYING that comes with GRASS for details.
  12. @author Luca Delucchi
  13. @author start stvds support Matej Krejci
  14. """
  15. import os
  16. import six
  17. from itertools import cycle
  18. import numpy as np
  19. import wx
  20. from grass.pygrass.modules import Module
  21. import grass.script as grass
  22. from functools import reduce
  23. try:
  24. import matplotlib
  25. # The recommended way to use wx with mpl is with the WXAgg
  26. # backend.
  27. matplotlib.use('WXAgg')
  28. from matplotlib.figure import Figure
  29. from matplotlib.backends.backend_wxagg import \
  30. FigureCanvasWxAgg as FigCanvas, \
  31. NavigationToolbar2WxAgg as NavigationToolbar
  32. import matplotlib.dates as mdates
  33. from matplotlib import cbook
  34. except ImportError as e:
  35. raise ImportError(_('The Temporal Plot Tool needs the "matplotlib" '
  36. '(python-matplotlib) package to be installed. {0}').format(e))
  37. import grass.temporal as tgis
  38. from core.gcmd import GMessage, GError, GException, RunCommand
  39. from gui_core.widgets import CoordinatesValidator
  40. from gui_core import gselect
  41. from core import globalvar
  42. from grass.pygrass.vector.geometry import Point
  43. from grass.pygrass.raster import RasterRow
  44. from grass.pygrass.gis.region import Region
  45. from collections import OrderedDict
  46. from subprocess import PIPE
  47. try:
  48. import wx.lib.agw.flatnotebook as FN
  49. except ImportError:
  50. import wx.lib.flatnotebook as FN
  51. import wx.lib.filebrowsebutton as filebrowse
  52. from gui_core.widgets import GNotebook
  53. from gui_core.wrap import TextCtrl, Button, StaticText
  54. ALPHA = 0.5
  55. COLORS = ['b', 'g', 'r', 'c', 'm', 'y', 'k']
  56. def check_version(*version):
  57. """Checks if given version or newer is installed"""
  58. versionInstalled = []
  59. for i in matplotlib.__version__.split('.'):
  60. try:
  61. v = int(i)
  62. versionInstalled.append(v)
  63. except ValueError:
  64. versionInstalled.append(0)
  65. if versionInstalled < list(version):
  66. return False
  67. else:
  68. return True
  69. def findBetween(s, first, last):
  70. try:
  71. start = s.rindex(first) + len(first)
  72. end = s.rindex(last, start)
  73. return s[start:end]
  74. except ValueError:
  75. return ""
  76. class TplotFrame(wx.Frame):
  77. """The main frame of the application"""
  78. def __init__(self, parent, giface):
  79. wx.Frame.__init__(self, parent, id=wx.ID_ANY,
  80. title=_("GRASS GIS Temporal Plot Tool"))
  81. tgis.init(True)
  82. self._giface = giface
  83. self.datasetsV = None
  84. self.datasetsR = None
  85. self.overwrite = False
  86. # self.vectorDraw=False
  87. # self.rasterDraw=False
  88. self.init()
  89. self._layout()
  90. # We create a database interface here to speedup the GUI
  91. self.dbif = tgis.SQLDatabaseInterfaceConnection()
  92. self.dbif.connect()
  93. self.Bind(wx.EVT_CLOSE, self.onClose)
  94. self.region = Region()
  95. def init(self):
  96. self.timeDataR = OrderedDict()
  97. self.timeDataV = OrderedDict()
  98. self.temporalType = None
  99. self.unit = None
  100. self.listWhereConditions = []
  101. self.plotNameListR = []
  102. self.plotNameListV = []
  103. self.poi = None
  104. self.csvpath = None
  105. def __del__(self):
  106. """Close the database interface and stop the messenger and C-interface
  107. subprocesses.
  108. """
  109. if self.dbif.connected is True:
  110. self.dbif.close()
  111. tgis.stop_subprocesses()
  112. def onClose(self, evt):
  113. if self._giface.GetMapDisplay():
  114. self.coorval.OnClose()
  115. self.cats.OnClose()
  116. self.__del__()
  117. self.Destroy()
  118. def _layout(self):
  119. """Creates the main panel with all the controls on it:
  120. * mpl canvas
  121. * mpl navigation toolbar
  122. * Control panel for interaction
  123. """
  124. self.mainPanel = wx.Panel(self)
  125. # Create the mpl Figure and FigCanvas objects.
  126. # 5x4 inches, 100 dots-per-inch
  127. #
  128. # color = wx.SystemSettings.GetColour(wx.SYS_COLOUR_BACKGROUND)
  129. # ------------CANVAS AND TOOLBAR------------
  130. self.fig = Figure((5.0, 4.0), facecolor=(1, 1, 1))
  131. self.canvas = FigCanvas(self.mainPanel, wx.ID_ANY, self.fig)
  132. # axes are initialized later
  133. self.axes2d = None
  134. # Create the navigation toolbar, tied to the canvas
  135. #
  136. self.toolbar = NavigationToolbar(self.canvas)
  137. #
  138. # Layout
  139. #
  140. # ------------MAIN VERTICAL SIZER------------
  141. self.vbox = wx.BoxSizer(wx.VERTICAL)
  142. self.vbox.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.EXPAND)
  143. self.vbox.Add(self.toolbar, 0, wx.EXPAND)
  144. # self.vbox.AddSpacer(10)
  145. # ------------ADD NOTEBOOK------------
  146. self.ntb = GNotebook(parent=self.mainPanel,
  147. style=FN.FNB_FANCY_TABS | FN.FNB_NODRAG)
  148. # ------------ITEMS IN NOTEBOOK PAGE (RASTER)------------------------
  149. self.controlPanelRaster = wx.Panel(parent=self.ntb, id=wx.ID_ANY)
  150. self.datasetSelectLabelR = StaticText(
  151. parent=self.controlPanelRaster,
  152. id=wx.ID_ANY,
  153. label=_(
  154. 'Raster temporal '
  155. 'dataset (strds)\n'
  156. 'Press ENTER after'
  157. ' typing the name or select'
  158. ' with the combobox'))
  159. self.datasetSelectR = gselect.Select(
  160. parent=self.controlPanelRaster, id=wx.ID_ANY,
  161. size=globalvar.DIALOG_GSELECT_SIZE, type='strds', multiple=True)
  162. self.coor = StaticText(parent=self.controlPanelRaster, id=wx.ID_ANY,
  163. label=_('X and Y coordinates separated by '
  164. 'comma:'))
  165. try:
  166. self._giface.GetMapWindow()
  167. self.coorval = gselect.CoordinatesSelect(
  168. parent=self.controlPanelRaster, giface=self._giface)
  169. except:
  170. self.coorval = TextCtrl(parent=self.controlPanelRaster,
  171. id=wx.ID_ANY,
  172. size=globalvar.DIALOG_TEXTCTRL_SIZE,
  173. validator=CoordinatesValidator())
  174. self.coorval.SetToolTip(_("Coordinates can be obtained for example"
  175. " by right-clicking on Map Display."))
  176. self.controlPanelSizerRaster = wx.BoxSizer(wx.VERTICAL)
  177. # self.controlPanelSizer.Add(wx.StaticText(self.panel, id=wx.ID_ANY,
  178. # label=_("Select space time raster dataset(s):")),
  179. # pos=(0, 0), flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL)
  180. self.controlPanelSizerRaster.Add(self.datasetSelectLabelR,
  181. flag=wx.EXPAND)
  182. self.controlPanelSizerRaster.Add(self.datasetSelectR, flag=wx.EXPAND)
  183. self.controlPanelSizerRaster.Add(self.coor, flag=wx.EXPAND)
  184. self.controlPanelSizerRaster.Add(self.coorval, flag=wx.EXPAND)
  185. self.controlPanelRaster.SetSizer(self.controlPanelSizerRaster)
  186. self.controlPanelSizerRaster.Fit(self)
  187. self.ntb.AddPage(page=self.controlPanelRaster, text=_('STRDS'),
  188. name='STRDS')
  189. # ------------ITEMS IN NOTEBOOK PAGE (VECTOR)------------------------
  190. self.controlPanelVector = wx.Panel(parent=self.ntb, id=wx.ID_ANY)
  191. self.datasetSelectLabelV = StaticText(
  192. parent=self.controlPanelVector, id=wx.ID_ANY,
  193. label=_(
  194. 'Vector temporal '
  195. 'dataset (stvds)\n'
  196. 'Press ENTER after'
  197. ' typing the name or select'
  198. ' with the combobox'))
  199. self.datasetSelectV = gselect.Select(
  200. parent=self.controlPanelVector, id=wx.ID_ANY,
  201. size=globalvar.DIALOG_GSELECT_SIZE, type='stvds', multiple=True)
  202. self.datasetSelectV.Bind(wx.EVT_TEXT,
  203. self.OnVectorSelected)
  204. self.attribute = gselect.ColumnSelect(parent=self.controlPanelVector)
  205. self.attributeLabel = StaticText(parent=self.controlPanelVector,
  206. id=wx.ID_ANY,
  207. label=_('Select attribute column'))
  208. # TODO fix the category selection as done for coordinates
  209. try:
  210. self._giface.GetMapWindow()
  211. self.cats = gselect.VectorCategorySelect(
  212. parent=self.controlPanelVector, giface=self._giface)
  213. except:
  214. self.cats = TextCtrl(
  215. parent=self.controlPanelVector,
  216. id=wx.ID_ANY,
  217. size=globalvar.DIALOG_TEXTCTRL_SIZE)
  218. self.catsLabel = StaticText(parent=self.controlPanelVector,
  219. id=wx.ID_ANY,
  220. label=_('Select category of vector(s)'))
  221. self.controlPanelSizerVector = wx.BoxSizer(wx.VERTICAL)
  222. # self.controlPanelSizer.Add(wx.StaticText(self.panel, id=wx.ID_ANY,
  223. # label=_("Select space time raster dataset(s):")),
  224. # pos=(0, 0), flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL)
  225. self.controlPanelSizerVector.Add(self.datasetSelectLabelV,
  226. flag=wx.EXPAND)
  227. self.controlPanelSizerVector.Add(self.datasetSelectV, flag=wx.EXPAND)
  228. self.controlPanelSizerVector.Add(self.attributeLabel, flag=wx.EXPAND)
  229. self.controlPanelSizerVector.Add(self.attribute, flag=wx.EXPAND)
  230. self.controlPanelSizerVector.Add(self.catsLabel, flag=wx.EXPAND)
  231. self.controlPanelSizerVector.Add(self.cats, flag=wx.EXPAND)
  232. self.controlPanelVector.SetSizer(self.controlPanelSizerVector)
  233. self.controlPanelSizerVector.Fit(self)
  234. self.ntb.AddPage(page=self.controlPanelVector, text=_('STVDS'),
  235. name='STVDS')
  236. # ------------ITEMS IN NOTEBOOK PAGE (LABELS)------------------------
  237. self.controlPanelLabels = wx.Panel(parent=self.ntb, id=wx.ID_ANY)
  238. self.titleLabel = StaticText(parent=self.controlPanelLabels,
  239. id=wx.ID_ANY,
  240. label=_('Set title for the plot'))
  241. self.title = TextCtrl(parent=self.controlPanelLabels, id=wx.ID_ANY,
  242. size=globalvar.DIALOG_TEXTCTRL_SIZE)
  243. self.xLabel = StaticText(parent=self.controlPanelLabels,
  244. id=wx.ID_ANY,
  245. label=_('Set label for X axis'))
  246. self.x = TextCtrl(parent=self.controlPanelLabels, id=wx.ID_ANY,
  247. size=globalvar.DIALOG_TEXTCTRL_SIZE)
  248. self.yLabel = StaticText(parent=self.controlPanelLabels,
  249. id=wx.ID_ANY,
  250. label=_('Set label for Y axis'))
  251. self.y = TextCtrl(parent=self.controlPanelLabels, id=wx.ID_ANY,
  252. size=globalvar.DIALOG_TEXTCTRL_SIZE)
  253. self.controlPanelSizerLabels = wx.BoxSizer(wx.VERTICAL)
  254. self.controlPanelSizerLabels.Add(self.titleLabel, flag=wx.EXPAND)
  255. self.controlPanelSizerLabels.Add(self.title, flag=wx.EXPAND)
  256. self.controlPanelSizerLabels.Add(self.xLabel, flag=wx.EXPAND)
  257. self.controlPanelSizerLabels.Add(self.x, flag=wx.EXPAND)
  258. self.controlPanelSizerLabels.Add(self.yLabel, flag=wx.EXPAND)
  259. self.controlPanelSizerLabels.Add(self.y, flag=wx.EXPAND)
  260. self.controlPanelLabels.SetSizer(self.controlPanelSizerLabels)
  261. self.controlPanelSizerLabels.Fit(self)
  262. self.ntb.AddPage(page=self.controlPanelLabels, text=_('Labels'),
  263. name='Labels')
  264. # ------------ITEMS IN NOTEBOOK PAGE (EXPORT)------------------------
  265. self.controlPanelExport = wx.Panel(parent=self.ntb, id=wx.ID_ANY)
  266. self.csvLabel = StaticText(parent=self.controlPanelExport,
  267. id=wx.ID_ANY,
  268. label=_('Path for output CSV file '
  269. 'with plotted data'))
  270. self.csvButton = filebrowse.FileBrowseButton(parent=self.controlPanelExport,
  271. id=wx.ID_ANY,
  272. size=globalvar.DIALOG_GSELECT_SIZE,
  273. labelText='',
  274. dialogTitle=_('CVS path'),
  275. buttonText=_('Browse'),
  276. startDirectory=os.getcwd(),
  277. fileMode=wx.FD_SAVE)
  278. self.headerLabel = StaticText(parent=self.controlPanelExport,
  279. id=wx.ID_ANY,
  280. label=_('Do you want the CSV header?'))
  281. self.headerCheck = wx.CheckBox(parent=self.controlPanelExport,
  282. id=wx.ID_ANY)
  283. self.controlPanelSizerCheck = wx.BoxSizer(wx.HORIZONTAL)
  284. self.controlPanelSizerCheck.Add(self.headerCheck)
  285. self.controlPanelSizerCheck.Add(self.headerLabel)
  286. self.controlPanelSizerExport = wx.BoxSizer(wx.VERTICAL)
  287. self.controlPanelSizerExport.Add(self.csvLabel)
  288. self.controlPanelSizerExport.Add(self.csvButton)
  289. self.controlPanelSizerExport.Add(self.controlPanelSizerCheck)
  290. self.controlPanelExport.SetSizer(self.controlPanelSizerExport)
  291. self.controlPanelSizerCheck.Fit(self)
  292. self.controlPanelSizerExport.Fit(self)
  293. self.ntb.AddPage(page=self.controlPanelExport, text=_('Export'),
  294. name='Export')
  295. # ------------Buttons on the bottom(draw,help)------------
  296. self.vButtPanel = wx.Panel(self.mainPanel, id=wx.ID_ANY)
  297. self.vButtSizer = wx.BoxSizer(wx.HORIZONTAL)
  298. self.drawButton = Button(self.vButtPanel, id=wx.ID_ANY,
  299. label=_("Draw"))
  300. self.drawButton.Bind(wx.EVT_BUTTON, self.OnRedraw)
  301. self.helpButton = Button(self.vButtPanel, id=wx.ID_ANY,
  302. label=_("Help"))
  303. self.helpButton.Bind(wx.EVT_BUTTON, self.OnHelp)
  304. self.vButtSizer.Add(self.drawButton)
  305. self.vButtSizer.Add(self.helpButton)
  306. self.vButtPanel.SetSizer(self.vButtSizer)
  307. self.mainPanel.SetSizer(self.vbox)
  308. self.vbox.Add(self.ntb, flag=wx.EXPAND)
  309. self.vbox.Add(self.vButtPanel, flag=wx.EXPAND)
  310. self.vbox.Fit(self)
  311. self.mainPanel.Fit()
  312. def _getSTRDdata(self, timeseries):
  313. """Load data and read properties
  314. :param list timeseries: a list of timeseries
  315. """
  316. if not self.poi:
  317. GError(parent=self, message=_("Invalid input coordinates"),
  318. showTraceback=False)
  319. return
  320. mode = None
  321. unit = None
  322. columns = ','.join(['name', 'start_time', 'end_time'])
  323. for series in timeseries:
  324. name = series[0]
  325. fullname = name + '@' + series[1]
  326. etype = series[2]
  327. sp = tgis.dataset_factory(etype, fullname)
  328. if not sp.is_in_db(dbif=self.dbif):
  329. GError(message=_("Dataset <%s> not found in temporal "
  330. "database") % (fullname), parent=self)
  331. return
  332. sp.select(dbif=self.dbif)
  333. minmin = sp.metadata.get_min_min()
  334. self.plotNameListR.append(name)
  335. self.timeDataR[name] = OrderedDict()
  336. self.timeDataR[name]['temporalDataType'] = etype
  337. self.timeDataR[name]['temporalType'] = sp.get_temporal_type()
  338. self.timeDataR[name]['granularity'] = sp.get_granularity()
  339. if mode is None:
  340. mode = self.timeDataR[name]['temporalType']
  341. elif self.timeDataR[name]['temporalType'] != mode:
  342. GError(
  343. parent=self, message=_(
  344. "Datasets have different temporal"
  345. " type (absolute x relative), "
  346. "which is not allowed."))
  347. return
  348. # check topology
  349. maps = sp.get_registered_maps_as_objects(dbif=self.dbif)
  350. self.timeDataR[name]['validTopology'] = sp.check_temporal_topology(
  351. maps=maps, dbif=self.dbif)
  352. self.timeDataR[name]['unit'] = None # only with relative
  353. if self.timeDataR[name]['temporalType'] == 'relative':
  354. start, end, self.timeDataR[name][
  355. 'unit'] = sp.get_relative_time()
  356. if unit is None:
  357. unit = self.timeDataR[name]['unit']
  358. elif self.timeDataR[name]['unit'] != unit:
  359. GError(parent=self, message=_("Datasets have different "
  360. "time unit which is not "
  361. "allowed."))
  362. return
  363. rows = sp.get_registered_maps(columns=columns, where=None,
  364. order='start_time', dbif=self.dbif)
  365. for row in rows:
  366. self.timeDataR[name][row[0]] = {}
  367. self.timeDataR[name][row[0]]['start_datetime'] = row[1]
  368. self.timeDataR[name][row[0]]['end_datetime'] = row[2]
  369. r = RasterRow(row[0])
  370. r.open()
  371. val = r.get_value(self.poi)
  372. r.close()
  373. if val == -2147483648 and val < minmin:
  374. self.timeDataR[name][row[0]]['value'] = None
  375. else:
  376. self.timeDataR[name][row[0]]['value'] = val
  377. self.unit = unit
  378. self.temporalType = mode
  379. return
  380. def _parseVDbConn(self, mapp, layerInp):
  381. '''find attribute key according to layer of input map'''
  382. vdb = Module('v.db.connect', map=mapp, flags='g', stdout_=PIPE)
  383. vdb = vdb.outputs.stdout
  384. for line in vdb.splitlines():
  385. lsplit = line.split('|')
  386. layer = lsplit[0].split('/')[0]
  387. if str(layer) == str(layerInp):
  388. return lsplit[2]
  389. return None
  390. def _getExistingCategories(self, mapp, cats):
  391. """Get a list of categories for a vector map"""
  392. vdb = grass.read_command('v.category', input=mapp, option='print')
  393. categories = vdb.splitlines()
  394. if not cats:
  395. return categories
  396. for cat in cats:
  397. if str(cat) not in categories:
  398. GMessage(message=_("Category {ca} is not on vector map"
  399. " {ma} and it will be not used").format(ma=mapp,
  400. ca=cat),
  401. parent=self)
  402. cats.remove(cat)
  403. return cats
  404. def _getSTVDData(self, timeseries):
  405. """Load data and read properties
  406. :param list timeseries: a list of timeseries
  407. """
  408. mode = None
  409. unit = None
  410. cats = None
  411. attribute = self.attribute.GetValue()
  412. if self.cats.GetValue() != '':
  413. cats = self.cats.GetValue().split(',')
  414. if cats and self.poi:
  415. GMessage(message=_("Both coordinates and categories are set, "
  416. "coordinates will be used. The use categories "
  417. "remove text from coordinate form"))
  418. if not attribute or attribute == '':
  419. GError(parent=self, showTraceback=False,
  420. message=_("With Vector temporal dataset you have to select"
  421. " an attribute column"))
  422. return
  423. columns = ','.join(['name', 'start_time', 'end_time', 'id', 'layer'])
  424. for series in timeseries:
  425. name = series[0]
  426. fullname = name + '@' + series[1]
  427. etype = series[2]
  428. sp = tgis.dataset_factory(etype, fullname)
  429. if not sp.is_in_db(dbif=self.dbif):
  430. GError(message=_("Dataset <%s> not found in temporal "
  431. "database") % (fullname), parent=self,
  432. showTraceback=False)
  433. return
  434. sp.select(dbif=self.dbif)
  435. rows = sp.get_registered_maps(dbif=self.dbif, order="start_time",
  436. columns=columns, where=None)
  437. self.timeDataV[name] = OrderedDict()
  438. self.timeDataV[name]['temporalDataType'] = etype
  439. self.timeDataV[name]['temporalType'] = sp.get_temporal_type()
  440. self.timeDataV[name]['granularity'] = sp.get_granularity()
  441. if mode is None:
  442. mode = self.timeDataV[name]['temporalType']
  443. elif self.timeDataV[name]['temporalType'] != mode:
  444. GError(
  445. parent=self, showTraceback=False, message=_(
  446. "Datasets have different temporal type ("
  447. "absolute x relative), which is not allowed."))
  448. return
  449. self.timeDataV[name]['unit'] = None # only with relative
  450. if self.timeDataV[name]['temporalType'] == 'relative':
  451. start, end, self.timeDataV[name][
  452. 'unit'] = sp.get_relative_time()
  453. if unit is None:
  454. unit = self.timeDataV[name]['unit']
  455. elif self.timeDataV[name]['unit'] != unit:
  456. GError(message=_("Datasets have different time unit which"
  457. " is not allowed."), parent=self,
  458. showTraceback=False)
  459. return
  460. if self.poi:
  461. self.plotNameListV.append(name)
  462. # TODO set an appropriate distance, right now a big one is set
  463. # to return the closer point to the selected one
  464. out = grass.vector_what(map='pois_srvds',
  465. coord=self.poi.coords(),
  466. distance=10000000000000000)
  467. if len(out) != len(rows):
  468. GError(parent=self, showTraceback=False,
  469. message=_("Difference number of vector layers and "
  470. "maps in the vector temporal dataset"))
  471. return
  472. for i in range(len(rows)):
  473. row = rows[i]
  474. values = out[i]
  475. if str(row['layer']) == str(values['Layer']):
  476. lay = "{map}_{layer}".format(map=row['name'],
  477. layer=values['Layer'])
  478. self.timeDataV[name][lay] = {}
  479. self.timeDataV[name][lay][
  480. 'start_datetime'] = row['start_time']
  481. self.timeDataV[name][lay][
  482. 'end_datetime'] = row['start_time']
  483. self.timeDataV[name][lay]['value'] = values[
  484. 'Attributes'][attribute]
  485. else:
  486. wherequery = ''
  487. cats = self._getExistingCategories(rows[0]['name'], cats)
  488. totcat = len(cats)
  489. ncat = 1
  490. for cat in cats:
  491. if ncat == 1 and totcat != 1:
  492. wherequery += '{k}={c} or'.format(c=cat, k="{key}")
  493. elif ncat == 1 and totcat == 1:
  494. wherequery += '{k}={c}'.format(c=cat, k="{key}")
  495. elif ncat == totcat:
  496. wherequery += ' {k}={c}'.format(c=cat, k="{key}")
  497. else:
  498. wherequery += ' {k}={c} or'.format(c=cat, k="{key}")
  499. catn = "cat{num}".format(num=cat)
  500. self.plotNameListV.append("{na}+{cat}".format(na=name,
  501. cat=catn))
  502. self.timeDataV[name][catn] = OrderedDict()
  503. ncat += 1
  504. for row in rows:
  505. lay = int(row['layer'])
  506. catkey = self._parseVDbConn(row['name'], lay)
  507. if not catkey:
  508. GError(
  509. parent=self, showTraceback=False, message=_(
  510. "No connection between vector map {vmap} "
  511. "and layer {la}".format(
  512. vmap=row['name'], la=lay)))
  513. return
  514. vals = grass.vector_db_select(
  515. map=row['name'], layer=lay, where=wherequery.format(
  516. key=catkey), columns=attribute)
  517. layn = "lay{num}".format(num=lay)
  518. for cat in cats:
  519. catn = "cat{num}".format(num=cat)
  520. if layn not in self.timeDataV[name][catn].keys():
  521. self.timeDataV[name][catn][layn] = {}
  522. self.timeDataV[name][catn][layn][
  523. 'start_datetime'] = row['start_time']
  524. self.timeDataV[name][catn][layn][
  525. 'end_datetime'] = row['end_time']
  526. self.timeDataV[name][catn][layn]['value'] = vals['values'][int(cat)][
  527. 0]
  528. self.unit = unit
  529. self.temporalType = mode
  530. return
  531. def _drawFigure(self):
  532. """Draws or print 2D plot (temporal extents)"""
  533. self.axes2d.clear()
  534. self.axes2d.grid(False)
  535. if self.temporalType == 'absolute':
  536. self.axes2d.xaxis_date()
  537. self.fig.autofmt_xdate()
  538. self.convert = mdates.date2num
  539. self.invconvert = mdates.num2date
  540. else:
  541. self.convert = lambda x: x
  542. self.invconvert = self.convert
  543. self.colors = cycle(COLORS)
  544. self.yticksNames = []
  545. self.yticksPos = []
  546. self.plots = []
  547. self.drawTitle = self.title.GetValue()
  548. self.drawX = self.x.GetValue()
  549. self.drawY = self.y.GetValue()
  550. if self.datasetsR:
  551. self.lookUp = LookUp(self.timeDataR, self.invconvert)
  552. else:
  553. self.lookUp = LookUp(self.timeDataV, self.invconvert)
  554. if self.datasetsR:
  555. self.drawR()
  556. if self.datasetsV:
  557. if self.poi:
  558. self.drawV()
  559. elif self.cats:
  560. self.drawVCats()
  561. self.canvas.draw()
  562. DataCursor(self.plots, self.lookUp, InfoFormat, self.convert)
  563. def _setLabels(self, x):
  564. """Function to set the right labels"""
  565. if self.drawX != '':
  566. self.axes2d.set_xlabel(self.drawX)
  567. else:
  568. if self.temporalType == 'absolute':
  569. self.axes2d.set_xlabel(_("Temporal resolution: %s" % x ))
  570. else:
  571. self.axes2d.set_xlabel(_("Time [%s]") % self.unit)
  572. if self.drawY != '':
  573. self.axes2d.set_ylabel(self.drawY)
  574. else:
  575. self.axes2d.set_ylabel(', '.join(self.yticksNames))
  576. if self.drawTitle != '':
  577. self.axes2d.set_title(self.drawTitle)
  578. def _writeCSV(self, x, y):
  579. """Used to write CSV file of plotted data"""
  580. import csv
  581. if isinstance(y[0], list):
  582. zipped = list(zip(x, *y))
  583. else:
  584. zipped = list(zip(x, y))
  585. with open(self.csvpath, "w", newline='') as fi:
  586. writer = csv.writer(fi)
  587. if self.header:
  588. head = ["Time"]
  589. head.extend(self.yticksNames)
  590. writer.writerow(head)
  591. writer.writerows(zipped)
  592. def drawR(self):
  593. ycsv = []
  594. xcsv = []
  595. for i, name in enumerate(self.datasetsR):
  596. name = name[0]
  597. # just name; with mapset it would be long
  598. self.yticksNames.append(name)
  599. self.yticksPos.append(1) # TODO
  600. xdata = []
  601. ydata = []
  602. for keys, values in six.iteritems(self.timeDataR[name]):
  603. if keys in ['temporalType', 'granularity', 'validTopology',
  604. 'unit', 'temporalDataType']:
  605. continue
  606. xdata.append(self.convert(values['start_datetime']))
  607. ydata.append(values['value'])
  608. xcsv.append(values['start_datetime'])
  609. if len(ydata) == ydata.count(None):
  610. GError(parent=self, showTraceback=False,
  611. message=_("Problem getting data from raster temporal"
  612. " dataset. Empty list of values."))
  613. return
  614. self.lookUp.AddDataset(yranges=ydata, xranges=xdata,
  615. datasetName=name)
  616. color = next(self.colors)
  617. self.plots.append(self.axes2d.plot(xdata, ydata, marker='o',
  618. color=color,
  619. label=self.plotNameListR[i])[0])
  620. if self.csvpath:
  621. ycsv.append(ydata)
  622. if self.csvpath:
  623. self._writeCSV(xcsv, ycsv)
  624. self._setLabels(self.timeDataR[name]['granularity'])
  625. # legend
  626. handles, labels = self.axes2d.get_legend_handles_labels()
  627. self.axes2d.legend(loc=0)
  628. def drawVCats(self):
  629. ycsv = []
  630. for i, name in enumerate(self.plotNameListV):
  631. # just name; with mapset it would be long
  632. labelname = name.replace('+', ' ')
  633. self.yticksNames.append(labelname)
  634. name_cat = name.split('+')
  635. name = name_cat[0]
  636. self.yticksPos.append(1) # TODO
  637. xdata = []
  638. ydata = []
  639. xcsv = []
  640. for keys, values in six.iteritems(self.timeDataV[name_cat[0]]
  641. [name_cat[1]]):
  642. if keys in ['temporalType', 'granularity', 'validTopology',
  643. 'unit', 'temporalDataType']:
  644. continue
  645. xdata.append(self.convert(values['start_datetime']))
  646. if values['value'] == '':
  647. ydata.append(None)
  648. else:
  649. ydata.append(values['value'])
  650. xcsv.append(values['start_datetime'])
  651. if len(ydata) == ydata.count(None):
  652. GError(parent=self, showTraceback=False,
  653. message=_("Problem getting data from vector temporal"
  654. " dataset. Empty list of values for cat "
  655. "{ca}.".format(ca=name_cat[1].replace('cat',
  656. ''))))
  657. continue
  658. self.lookUp.AddDataset(yranges=ydata, xranges=xdata,
  659. datasetName=name)
  660. color = next(self.colors)
  661. self.plots.append(
  662. self.axes2d.plot(
  663. xdata,
  664. ydata,
  665. marker='o',
  666. color=color,
  667. label=labelname)[0])
  668. if self.csvpath:
  669. ycsv.append(ydata)
  670. if self.csvpath:
  671. self._writeCSV(xcsv, ycsv)
  672. self._setLabels(self.timeDataV[name]['granularity'])
  673. # legend
  674. handles, labels = self.axes2d.get_legend_handles_labels()
  675. self.axes2d.legend(loc=0)
  676. self.listWhereConditions = []
  677. def drawV(self):
  678. ycsv = []
  679. for i, name in enumerate(self.plotNameListV):
  680. # just name; with mapset it would be long
  681. self.yticksNames.append(self.attribute.GetValue())
  682. self.yticksPos.append(0) # TODO
  683. xdata = []
  684. ydata = []
  685. xcsv = []
  686. for keys, values in six.iteritems(self.timeDataV[name]):
  687. if keys in ['temporalType', 'granularity', 'validTopology',
  688. 'unit', 'temporalDataType']:
  689. continue
  690. xdata.append(self.convert(values['start_datetime']))
  691. ydata.append(values['value'])
  692. xcsv.append(values['start_datetime'])
  693. if len(ydata) == ydata.count(None):
  694. GError(parent=self, showTraceback=False,
  695. message=_("Problem getting data from vector temporal"
  696. " dataset. Empty list of values."))
  697. return
  698. self.lookUp.AddDataset(yranges=ydata, xranges=xdata,
  699. datasetName=name)
  700. color = next(self.colors)
  701. self.plots.append(self.axes2d.plot(xdata, ydata, marker='o',
  702. color=color, label=name)[0])
  703. if self.csvpath:
  704. ycsv.append(ydata)
  705. if self.csvpath:
  706. self._writeCSV(xcsv, ycsv)
  707. self._setLabels(self.timeDataV[name]['granularity'])
  708. # legend
  709. handles, labels = self.axes2d.get_legend_handles_labels()
  710. self.axes2d.legend(loc=0)
  711. self.listWhereConditions = []
  712. def OnRedraw(self, event=None):
  713. """Required redrawing."""
  714. self.csvpath = self.csvButton.GetValue()
  715. self.header = self.headerCheck.IsChecked()
  716. if (os.path.exists(self.csvpath) and not self.overwrite):
  717. dlg = wx.MessageDialog(self, _("{pa} already exists, do you want "
  718. "to overwrite?".format(pa=self.csvpath)),
  719. _("File exists"),
  720. wx.OK | wx.CANCEL | wx.ICON_QUESTION)
  721. if dlg.ShowModal() != wx.ID_OK:
  722. dlg.Destroy()
  723. GError(parent=self, showTraceback=False,
  724. message=_("Please change name of output CSV file or "))
  725. return
  726. dlg.Destroy()
  727. self.init()
  728. datasetsR = self.datasetSelectR.GetValue().strip()
  729. datasetsV = self.datasetSelectV.GetValue().strip()
  730. if not datasetsR and not datasetsV:
  731. return
  732. try:
  733. getcoors = self.coorval.coordsField.GetValue()
  734. except:
  735. try:
  736. getcoors = self.coorval.GetValue()
  737. except:
  738. getcoors = None
  739. if getcoors and getcoors != '':
  740. try:
  741. coordx, coordy = getcoors.split(',')
  742. coordx, coordy = float(coordx), float(coordy)
  743. except (ValueError, AttributeError):
  744. try:
  745. coordx, coordy = self.coorval.GetValue().split(',')
  746. coordx, coordy = float(coordx), float(coordy)
  747. except (ValueError, AttributeError):
  748. GMessage(message=_("Incorrect coordinates format, should "
  749. "be: x,y"), parent=self)
  750. coors = [coordx, coordy]
  751. if coors:
  752. try:
  753. self.poi = Point(float(coors[0]), float(coors[1]))
  754. except GException:
  755. GError(parent=self, message=_("Invalid input coordinates"),
  756. showTraceback=False)
  757. return
  758. if not self.poi:
  759. GError(parent=self, message=_("Invalid input coordinates"),
  760. showTraceback=False)
  761. return
  762. bbox = self.region.get_bbox()
  763. if not bbox.contains(self.poi):
  764. GError(parent=self, message=_("Seed point outside the "
  765. "current region"),
  766. showTraceback=False)
  767. return
  768. # check raster dataset
  769. if datasetsR:
  770. datasetsR = datasetsR.split(',')
  771. try:
  772. datasetsR = self._checkDatasets(datasetsR, 'strds')
  773. if not datasetsR:
  774. return
  775. except GException:
  776. GError(parent=self, message=_("Invalid input raster dataset"),
  777. showTraceback=False)
  778. return
  779. if not self.poi:
  780. GError(parent=self, message=_("Invalid input coordinates"),
  781. showTraceback=False)
  782. return
  783. self.datasetsR = datasetsR
  784. # check vector dataset
  785. if datasetsV:
  786. datasetsV = datasetsV.split(',')
  787. try:
  788. datasetsV = self._checkDatasets(datasetsV, 'stvds')
  789. if not datasetsV:
  790. return
  791. except GException:
  792. GError(parent=self, message=_("Invalid input vector dataset"),
  793. showTraceback=False)
  794. return
  795. self.datasetsV = datasetsV
  796. self._redraw()
  797. def _redraw(self):
  798. """Readraw data.
  799. Decides if to draw also 3D and adjusts layout if needed.
  800. """
  801. if self.datasetsR:
  802. self._getSTRDdata(self.datasetsR)
  803. if self.datasetsV:
  804. self._getSTVDData(self.datasetsV)
  805. # axes3d are physically removed
  806. if not self.axes2d:
  807. self.axes2d = self.fig.add_subplot(1, 1, 1)
  808. self._drawFigure()
  809. def _checkDatasets(self, datasets, typ):
  810. """Checks and validates datasets.
  811. Reports also type of dataset (e.g. 'strds').
  812. :param list datasets: list of temporal dataset's name
  813. :return: (mapName, mapset, type)
  814. """
  815. validated = []
  816. tDict = tgis.tlist_grouped(type=typ, group_type=True, dbif=self.dbif)
  817. # nested list with '(map, mapset, etype)' items
  818. allDatasets = [[[(map, mapset, etype) for map in maps]
  819. for etype, maps in six.iteritems(etypesDict)]
  820. for mapset, etypesDict in six.iteritems(tDict)]
  821. # flatten this list
  822. if allDatasets:
  823. allDatasets = reduce(lambda x, y: x + y, reduce(lambda x, y: x + y,
  824. allDatasets))
  825. mapsets = tgis.get_tgis_c_library_interface().available_mapsets()
  826. allDatasets = [
  827. i
  828. for i in sorted(
  829. allDatasets, key=lambda l: mapsets.index(l[1]))]
  830. for dataset in datasets:
  831. errorMsg = _("Space time dataset <%s> not found.") % dataset
  832. if dataset.find("@") >= 0:
  833. nameShort, mapset = dataset.split('@', 1)
  834. indices = [n for n, (mapName, mapsetName, etype) in enumerate(
  835. allDatasets) if nameShort == mapName and mapsetName == mapset]
  836. else:
  837. indices = [n for n, (mapName, mapset, etype) in enumerate(
  838. allDatasets) if dataset == mapName]
  839. if len(indices) == 0:
  840. raise GException(errorMsg)
  841. elif len(indices) >= 2:
  842. dlg = wx.SingleChoiceDialog(
  843. self,
  844. message=_(
  845. "Please specify the "
  846. "space time dataset "
  847. "<%s>." % dataset),
  848. caption=_("Ambiguous dataset name"),
  849. choices=[
  850. ("%(map)s@%(mapset)s:"
  851. " %(etype)s" % {
  852. 'map': allDatasets[i][0],
  853. 'mapset': allDatasets[i][1],
  854. 'etype': allDatasets[i][2]}) for i in indices],
  855. style=wx.CHOICEDLG_STYLE | wx.OK)
  856. if dlg.ShowModal() == wx.ID_OK:
  857. index = dlg.GetSelection()
  858. validated.append(allDatasets[indices[index]])
  859. else:
  860. continue
  861. else:
  862. validated.append(allDatasets[indices[0]])
  863. return validated
  864. def OnHelp(self, event):
  865. """Function to show help"""
  866. RunCommand(prog='g.manual', quiet=True, entry='g.gui.tplot')
  867. def SetDatasets(self, rasters, vectors, coors, cats, attr, title, xlabel,
  868. ylabel, csvfile, head, overwrite):
  869. """Set the data
  870. :param list rasters: a list of temporal raster dataset's name
  871. :param list vectors: a list of temporal vector dataset's name
  872. :param list coors: a list with x/y coordinates
  873. :param list cats: a list with incld. categories of vector
  874. :param str attr: name of atribute of vectror data
  875. """
  876. if not (rasters or vectors) or not (coors or cats):
  877. return
  878. try:
  879. if rasters:
  880. self.datasetsR = self._checkDatasets(rasters, 'strds')
  881. if vectors:
  882. self.datasetsV = self._checkDatasets(vectors, 'stvds')
  883. if not (self.datasetsR or self.datasetsV):
  884. return
  885. except GException:
  886. GError(parent=self, message=_("Invalid input temporal dataset"),
  887. showTraceback=False)
  888. return
  889. if coors:
  890. try:
  891. self.poi = Point(float(coors[0]), float(coors[1]))
  892. except GException:
  893. GError(parent=self, message=_("Invalid input coordinates"),
  894. showTraceback=False)
  895. return
  896. try:
  897. self.coorval.coordsField.SetValue(','.join(coors))
  898. except:
  899. self.coorval.SetValue(','.join(coors))
  900. if self.datasetsV:
  901. vdatas = ','.join(map(lambda x: x[0] + '@' + x[1], self.datasetsV))
  902. self.datasetSelectV.SetValue(vdatas)
  903. if attr:
  904. self.attribute.SetValue(attr)
  905. if cats:
  906. self.cats.SetValue(cats)
  907. if self.datasetsR:
  908. self.datasetSelectR.SetValue(
  909. ','.join(map(lambda x: x[0] + '@' + x[1], self.datasetsR)))
  910. if title:
  911. self.title.SetValue(title)
  912. if xlabel:
  913. self.x.SetValue(xlabel)
  914. if ylabel:
  915. self.y.SetValue(ylabel)
  916. if csvfile:
  917. self.csvpath = csvfile
  918. self.header = head
  919. self.overwrite = overwrite
  920. self._redraw()
  921. def OnVectorSelected(self, event):
  922. """Update the controlbox related to stvds"""
  923. dataset = self.datasetSelectV.GetValue().strip()
  924. name = dataset.split('@')[0]
  925. mapset = dataset.split('@')[1] if len(dataset.split('@')) > 1 else ''
  926. found = False
  927. for each in tgis.tlist(type='stvds', dbif=self.dbif):
  928. each_name, each_mapset = each.split('@')
  929. if name == each_name:
  930. if mapset and mapset != each_mapset:
  931. continue
  932. dataset = name + '@' + each_mapset
  933. found = True
  934. break
  935. if found:
  936. try:
  937. vect_list = grass.read_command('t.vect.list', flags='u',
  938. input=dataset, column='name')
  939. except Exception:
  940. self.attribute.Clear()
  941. GError(
  942. parent=self,
  943. message=_("Invalid input temporal dataset"),
  944. showTraceback=False)
  945. return
  946. vect_list = list(set(sorted(vect_list.split())))
  947. for vec in vect_list:
  948. self.attribute.InsertColumns(vec, 1)
  949. else:
  950. self.attribute.Clear()
  951. class LookUp:
  952. """Helper class for searching info by coordinates"""
  953. def __init__(self, timeData, convert):
  954. self.data = {}
  955. self.timeData = timeData
  956. self.convert = convert
  957. def AddDataset(self, yranges, xranges, datasetName):
  958. if len(yranges) != len(xranges):
  959. GError(parent=self, showTraceback=False,
  960. message=_("Datasets have different number of values"))
  961. return
  962. self.data[datasetName] = {}
  963. for i in range(len(xranges)):
  964. self.data[datasetName][xranges[i]] = yranges[i]
  965. def GetInformation(self, x):
  966. values = {}
  967. for key, value in six.iteritems(self.data):
  968. if value[x]:
  969. values[key] = [self.convert(x), value[x]]
  970. if len(values) == 0:
  971. return None
  972. return self.timeData, values
  973. def InfoFormat(timeData, values):
  974. """Formats information about dataset"""
  975. text = []
  976. for key, val in six.iteritems(values):
  977. etype = timeData[key]['temporalDataType']
  978. if etype == 'strds':
  979. text.append(_("Space time raster dataset: %s") % key)
  980. elif etype == 'stvds':
  981. text.append(_("Space time vector dataset: %s") % key)
  982. elif etype == 'str3ds':
  983. text.append(_("Space time 3D raster dataset: %s") % key)
  984. text.append(_("Value for {date} is {val}".format(date=val[0],
  985. val=val[1])))
  986. text.append('\n')
  987. text.append(_("Press Del to dismiss."))
  988. return '\n'.join(text)
  989. class DataCursor(object):
  990. """A simple data cursor widget that displays the x,y location of a
  991. matplotlib artist when it is selected.
  992. Source: http://stackoverflow.com/questions/4652439/
  993. is-there-a-matplotlib-equivalent-of-matlabs-datacursormode/4674445
  994. """
  995. def __init__(self, artists, lookUp, formatFunction, convert,
  996. tolerance=5, offsets=(-30, 20), display_all=False):
  997. """Create the data cursor and connect it to the relevant figure.
  998. "artists" is the matplotlib artist or sequence of artists that will be
  999. selected.
  1000. "tolerance" is the radius (in points) that the mouse click must be
  1001. within to select the artist.
  1002. "offsets" is a tuple of (x,y) offsets in points from the selected
  1003. point to the displayed annotation box
  1004. "display_all" controls whether more than one annotation box will
  1005. be shown if there are multiple axes. Only one will be shown
  1006. per-axis, regardless.
  1007. """
  1008. self.lookUp = lookUp
  1009. self.formatFunction = formatFunction
  1010. self.offsets = offsets
  1011. self.display_all = display_all
  1012. if not cbook.iterable(artists):
  1013. artists = [artists]
  1014. self.artists = artists
  1015. self.convert = convert
  1016. self.axes = tuple(set(art.axes for art in self.artists))
  1017. self.figures = tuple(set(ax.figure for ax in self.axes))
  1018. self.annotations = {}
  1019. for ax in self.axes:
  1020. self.annotations[ax] = self.annotate(ax)
  1021. for artist in self.artists:
  1022. artist.set_picker(tolerance)
  1023. for fig in self.figures:
  1024. fig.canvas.mpl_connect('pick_event', self)
  1025. fig.canvas.mpl_connect('key_press_event', self.keyPressed)
  1026. def keyPressed(self, event):
  1027. """Key pressed - hide annotation if Delete was pressed"""
  1028. if event.key != 'delete':
  1029. return
  1030. for ax in self.axes:
  1031. self.annotations[ax].set_visible(False)
  1032. event.canvas.draw()
  1033. def annotate(self, ax):
  1034. """Draws and hides the annotation box for the given axis "ax"."""
  1035. annotation = ax.annotate(self.formatFunction, xy=(0, 0), ha='center',
  1036. xytext=self.offsets, va='bottom',
  1037. textcoords='offset points',
  1038. bbox=dict(boxstyle='round,pad=0.5',
  1039. fc='yellow', alpha=0.7),
  1040. arrowprops=dict(arrowstyle='->',
  1041. connectionstyle='arc3,rad=0'),
  1042. annotation_clip=False, multialignment='left')
  1043. annotation.set_visible(False)
  1044. return annotation
  1045. def __call__(self, event):
  1046. """Intended to be called through "mpl_connect"."""
  1047. # Rather than trying to interpolate, just display the clicked coords
  1048. # This will only be called if it's within "tolerance", anyway.
  1049. x, y = event.mouseevent.xdata, event.mouseevent.ydata
  1050. annotation = self.annotations[event.artist.axes]
  1051. if x is not None:
  1052. if not self.display_all:
  1053. # Hide any other annotation boxes...
  1054. for ann in self.annotations.values():
  1055. ann.set_visible(False)
  1056. if 'Line2D' in str(type(event.artist)):
  1057. xData = []
  1058. for a in event.artist.get_xdata():
  1059. try:
  1060. d = self.convert(a)
  1061. except:
  1062. d = a
  1063. xData.append(d)
  1064. x = xData[np.argmin(abs(xData - x))]
  1065. info = self.lookUp.GetInformation(x)
  1066. ys = list(zip(*info[1].values()))[1]
  1067. if not info:
  1068. return
  1069. # Update the annotation in the current axis..
  1070. annotation.xy = x, max(ys)
  1071. text = self.formatFunction(*info)
  1072. annotation.set_text(text)
  1073. annotation.set_visible(True)
  1074. event.canvas.draw()