frame.py 42 KB

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