frame.py 51 KB

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