frame.py 42 KB

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