frame.py 42 KB

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