frame.py 42 KB

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