frame.py 40 KB

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