frame.py 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279
  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. GError(
  810. parent=self,
  811. message=_("Incorrect coordinates format, should be: x,y"),
  812. showTraceback=False,
  813. )
  814. return
  815. coors = [coordx, coordy]
  816. if coors:
  817. try:
  818. self.poi = Point(float(coors[0]), float(coors[1]))
  819. except GException:
  820. GError(parent=self, message=_("Invalid input coordinates"),
  821. showTraceback=False)
  822. return
  823. if not self.poi:
  824. GError(parent=self, message=_("Invalid input coordinates"),
  825. showTraceback=False)
  826. return
  827. bbox = self.region.get_bbox()
  828. if not bbox.contains(self.poi):
  829. GError(parent=self, message=_("Seed point outside the "
  830. "current region"),
  831. showTraceback=False)
  832. return
  833. # check raster dataset
  834. if datasetsR:
  835. datasetsR = datasetsR.split(',')
  836. try:
  837. datasetsR = self._checkDatasets(datasetsR, 'strds')
  838. if not datasetsR:
  839. return
  840. except GException:
  841. GError(parent=self, message=_("Invalid input raster dataset"),
  842. showTraceback=False)
  843. return
  844. if not self.poi:
  845. GError(parent=self, message=_("Invalid input coordinates"),
  846. showTraceback=False)
  847. return
  848. self.datasetsR = datasetsR
  849. # check vector dataset
  850. if datasetsV:
  851. datasetsV = datasetsV.split(',')
  852. try:
  853. datasetsV = self._checkDatasets(datasetsV, 'stvds')
  854. if not datasetsV:
  855. return
  856. except GException:
  857. GError(parent=self, message=_("Invalid input vector dataset"),
  858. showTraceback=False)
  859. return
  860. self.datasetsV = datasetsV
  861. self._redraw()
  862. def _redraw(self):
  863. """Readraw data.
  864. Decides if to draw also 3D and adjusts layout if needed.
  865. """
  866. if self.datasetsR:
  867. self._getSTRDdata(self.datasetsR)
  868. if self.datasetsV:
  869. self._getSTVDData(self.datasetsV)
  870. # axes3d are physically removed
  871. if not self.axes2d:
  872. self.axes2d = self.fig.add_subplot(1, 1, 1)
  873. self._drawFigure()
  874. def _checkDatasets(self, datasets, typ):
  875. """Checks and validates datasets.
  876. Reports also type of dataset (e.g. 'strds').
  877. :param list datasets: list of temporal dataset's name
  878. :return: (mapName, mapset, type)
  879. """
  880. validated = []
  881. tDict = tgis.tlist_grouped(type=typ, group_type=True, dbif=self.dbif)
  882. # nested list with '(map, mapset, etype)' items
  883. allDatasets = [[[(map, mapset, etype) for map in maps]
  884. for etype, maps in six.iteritems(etypesDict)]
  885. for mapset, etypesDict in six.iteritems(tDict)]
  886. # flatten this list
  887. if allDatasets:
  888. allDatasets = reduce(lambda x, y: x + y, reduce(lambda x, y: x + y,
  889. allDatasets))
  890. mapsets = tgis.get_tgis_c_library_interface().available_mapsets()
  891. allDatasets = [
  892. i
  893. for i in sorted(
  894. allDatasets, key=lambda l: mapsets.index(l[1]))]
  895. for dataset in datasets:
  896. errorMsg = _("Space time dataset <%s> not found.") % dataset
  897. if dataset.find("@") >= 0:
  898. nameShort, mapset = dataset.split('@', 1)
  899. indices = [n for n, (mapName, mapsetName, etype) in enumerate(
  900. allDatasets) if nameShort == mapName and mapsetName == mapset]
  901. else:
  902. indices = [n for n, (mapName, mapset, etype) in enumerate(
  903. allDatasets) if dataset == mapName]
  904. if len(indices) == 0:
  905. raise GException(errorMsg)
  906. elif len(indices) >= 2:
  907. dlg = wx.SingleChoiceDialog(
  908. self,
  909. message=_(
  910. "Please specify the "
  911. "space time dataset "
  912. "<%s>." % dataset),
  913. caption=_("Ambiguous dataset name"),
  914. choices=[
  915. ("%(map)s@%(mapset)s:"
  916. " %(etype)s" % {
  917. 'map': allDatasets[i][0],
  918. 'mapset': allDatasets[i][1],
  919. 'etype': allDatasets[i][2]}) for i in indices],
  920. style=wx.CHOICEDLG_STYLE | wx.OK)
  921. if dlg.ShowModal() == wx.ID_OK:
  922. index = dlg.GetSelection()
  923. validated.append(allDatasets[indices[index]])
  924. else:
  925. continue
  926. else:
  927. validated.append(allDatasets[indices[0]])
  928. return validated
  929. def OnHelp(self, event):
  930. """Function to show help"""
  931. RunCommand(prog='g.manual', quiet=True, entry='g.gui.tplot')
  932. def SetDatasets(self, rasters, vectors, coors, cats, attr, title, xlabel,
  933. ylabel, csvfile, head, overwrite):
  934. """Set the data
  935. :param list rasters: a list of temporal raster dataset's name
  936. :param list vectors: a list of temporal vector dataset's name
  937. :param list coors: a list with x/y coordinates
  938. :param list cats: a list with incld. categories of vector
  939. :param str attr: name of atribute of vectror data
  940. """
  941. if not (rasters or vectors) or not (coors or cats):
  942. return
  943. try:
  944. if rasters:
  945. self.datasetsR = self._checkDatasets(rasters, 'strds')
  946. if vectors:
  947. self.datasetsV = self._checkDatasets(vectors, 'stvds')
  948. if not (self.datasetsR or self.datasetsV):
  949. return
  950. except GException:
  951. GError(parent=self, message=_("Invalid input temporal dataset"),
  952. showTraceback=False)
  953. return
  954. if coors:
  955. try:
  956. self.poi = Point(float(coors[0]), float(coors[1]))
  957. except GException:
  958. GError(parent=self, message=_("Invalid input coordinates"),
  959. showTraceback=False)
  960. return
  961. try:
  962. self.coorval.coordsField.SetValue(','.join(coors))
  963. except:
  964. self.coorval.SetValue(','.join(coors))
  965. if self.datasetsV:
  966. vdatas = ','.join(map(lambda x: x[0] + '@' + x[1], self.datasetsV))
  967. self.datasetSelectV.SetValue(vdatas)
  968. if attr:
  969. self.attribute.SetValue(attr)
  970. if cats:
  971. self.cats.SetValue(cats)
  972. if self.datasetsR:
  973. self.datasetSelectR.SetValue(
  974. ','.join(map(lambda x: x[0] + '@' + x[1], self.datasetsR)))
  975. if title:
  976. self.title.SetValue(title)
  977. if xlabel:
  978. self.x.SetValue(xlabel)
  979. if ylabel:
  980. self.y.SetValue(ylabel)
  981. if csvfile:
  982. self.csvpath = csvfile
  983. self.header = head
  984. self.overwrite = overwrite
  985. self._redraw()
  986. def OnVectorSelected(self, event):
  987. """Update the controlbox related to stvds"""
  988. dataset = self.datasetSelectV.GetValue().strip()
  989. name = dataset.split('@')[0]
  990. mapset = dataset.split('@')[1] if len(dataset.split('@')) > 1 else ''
  991. found = False
  992. for each in tgis.tlist(type='stvds', dbif=self.dbif):
  993. each_name, each_mapset = each.split('@')
  994. if name == each_name:
  995. if mapset and mapset != each_mapset:
  996. continue
  997. dataset = name + '@' + each_mapset
  998. found = True
  999. break
  1000. if found:
  1001. try:
  1002. vect_list = grass.read_command('t.vect.list', flags='u',
  1003. input=dataset, column='name')
  1004. except Exception:
  1005. self.attribute.Clear()
  1006. GError(
  1007. parent=self,
  1008. message=_("Invalid input temporal dataset"),
  1009. showTraceback=False)
  1010. return
  1011. vect_list = list(set(sorted(vect_list.split())))
  1012. for vec in vect_list:
  1013. self.attribute.InsertColumns(vec, 1)
  1014. else:
  1015. self.attribute.Clear()
  1016. class LookUp:
  1017. """Helper class for searching info by coordinates"""
  1018. def __init__(self, timeData, convert):
  1019. self.data = {}
  1020. self.timeData = timeData
  1021. self.convert = convert
  1022. def AddDataset(self, yranges, xranges, datasetName):
  1023. if len(yranges) != len(xranges):
  1024. GError(parent=self, showTraceback=False,
  1025. message=_("Datasets have different number of values"))
  1026. return
  1027. self.data[datasetName] = {}
  1028. for i in range(len(xranges)):
  1029. self.data[datasetName][xranges[i]] = yranges[i]
  1030. def GetInformation(self, x):
  1031. values = {}
  1032. for key, value in six.iteritems(self.data):
  1033. if value[x]:
  1034. values[key] = [self.convert(x), value[x]]
  1035. if len(values) == 0:
  1036. return None
  1037. return self.timeData, values
  1038. def InfoFormat(timeData, values):
  1039. """Formats information about dataset"""
  1040. text = []
  1041. for key, val in six.iteritems(values):
  1042. etype = timeData[key]['temporalDataType']
  1043. if etype == 'strds':
  1044. text.append(_("Space time raster dataset: %s") % key)
  1045. elif etype == 'stvds':
  1046. text.append(_("Space time vector dataset: %s") % key)
  1047. elif etype == 'str3ds':
  1048. text.append(_("Space time 3D raster dataset: %s") % key)
  1049. text.append(_("Value for {date} is {val}".format(date=val[0],
  1050. val=val[1])))
  1051. text.append('\n')
  1052. text.append(_("Press Del to dismiss."))
  1053. return '\n'.join(text)
  1054. class DataCursor(object):
  1055. """A simple data cursor widget that displays the x,y location of a
  1056. matplotlib artist when it is selected.
  1057. Source: http://stackoverflow.com/questions/4652439/
  1058. is-there-a-matplotlib-equivalent-of-matlabs-datacursormode/4674445
  1059. """
  1060. def __init__(self, artists, lookUp, formatFunction, convert,
  1061. tolerance=5, offsets=(-30, 20), display_all=False):
  1062. """Create the data cursor and connect it to the relevant figure.
  1063. "artists" is the matplotlib artist or sequence of artists that will be
  1064. selected.
  1065. "tolerance" is the radius (in points) that the mouse click must be
  1066. within to select the artist.
  1067. "offsets" is a tuple of (x,y) offsets in points from the selected
  1068. point to the displayed annotation box
  1069. "display_all" controls whether more than one annotation box will
  1070. be shown if there are multiple axes. Only one will be shown
  1071. per-axis, regardless.
  1072. """
  1073. self.lookUp = lookUp
  1074. self.formatFunction = formatFunction
  1075. self.offsets = offsets
  1076. self.display_all = display_all
  1077. if not np.iterable(artists):
  1078. artists = [artists]
  1079. self.artists = artists
  1080. self.convert = convert
  1081. self.axes = tuple(set(art.axes for art in self.artists))
  1082. self.figures = tuple(set(ax.figure for ax in self.axes))
  1083. self.annotations = {}
  1084. for ax in self.axes:
  1085. self.annotations[ax] = self.annotate(ax)
  1086. for artist in self.artists:
  1087. artist.set_pickradius(tolerance)
  1088. for fig in self.figures:
  1089. fig.canvas.mpl_connect('pick_event', self)
  1090. fig.canvas.mpl_connect('key_press_event', self.keyPressed)
  1091. def keyPressed(self, event):
  1092. """Key pressed - hide annotation if Delete was pressed"""
  1093. if event.key != 'delete':
  1094. return
  1095. for ax in self.axes:
  1096. self.annotations[ax].set_visible(False)
  1097. event.canvas.draw()
  1098. def annotate(self, ax):
  1099. """Draws and hides the annotation box for the given axis "ax"."""
  1100. annotation = ax.annotate(self.formatFunction, xy=(0, 0), ha='center',
  1101. xytext=self.offsets, va='bottom',
  1102. textcoords='offset points',
  1103. bbox=dict(boxstyle='round,pad=0.5',
  1104. fc='yellow', alpha=0.7),
  1105. arrowprops=dict(arrowstyle='->',
  1106. connectionstyle='arc3,rad=0'),
  1107. annotation_clip=False, multialignment='left')
  1108. annotation.set_visible(False)
  1109. return annotation
  1110. def __call__(self, event):
  1111. """Intended to be called through "mpl_connect"."""
  1112. # Rather than trying to interpolate, just display the clicked coords
  1113. # This will only be called if it's within "tolerance", anyway.
  1114. x, y = event.mouseevent.xdata, event.mouseevent.ydata
  1115. annotation = self.annotations[event.artist.axes]
  1116. if x is not None:
  1117. if not self.display_all:
  1118. # Hide any other annotation boxes...
  1119. for ann in self.annotations.values():
  1120. ann.set_visible(False)
  1121. if 'Line2D' in str(type(event.artist)):
  1122. xData = []
  1123. for a in event.artist.get_xdata():
  1124. try:
  1125. d = self.convert(a)
  1126. except:
  1127. d = a
  1128. xData.append(d)
  1129. x = xData[np.argmin(abs(xData - x))]
  1130. info = self.lookUp.GetInformation(x)
  1131. ys = list(zip(*info[1].values()))[1]
  1132. if not info:
  1133. return
  1134. # Update the annotation in the current axis..
  1135. annotation.xy = x, max(ys)
  1136. text = self.formatFunction(*info)
  1137. annotation.set_text(text)
  1138. annotation.set_visible(True)
  1139. event.canvas.draw()