frame.py 39 KB

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