frame.py 43 KB

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