frame.py 35 KB

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