frame.py 45 KB

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