frame.py 41 KB

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