frame.py 41 KB

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