frame.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889
  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. minmin = sp.metadata.get_min_min()
  247. self.plotNameListR.append(series)
  248. self.timeDataR[name] = OrderedDict()
  249. if not sp.is_in_db(dbif=self.dbif):
  250. GError(self, message=_("Dataset <%s> not found in temporal "
  251. "database") % (fullname))
  252. return
  253. self.timeDataR[name]['temporalDataType'] = etype
  254. self.timeDataR[name]['temporalType'] = sp.get_temporal_type()
  255. self.timeDataR[name]['granularity'] = sp.get_granularity()
  256. if mode is None:
  257. mode = self.timeDataR[name]['temporalType']
  258. elif self.timeDataR[name]['temporalType'] != mode:
  259. GError(parent=self, message=_("Datasets have different temporal"
  260. " type (absolute x relative), "
  261. "which is not allowed."))
  262. return
  263. # check topology
  264. maps = sp.get_registered_maps_as_objects(dbif=self.dbif)
  265. self.timeDataR[name]['validTopology'] = sp.check_temporal_topology(maps=maps, dbif=self.dbif)
  266. self.timeDataR[name]['unit'] = None # only with relative
  267. if self.timeDataR[name]['temporalType'] == 'relative':
  268. start, end, self.timeDataR[name]['unit'] = sp.get_relative_time()
  269. if unit is None:
  270. unit = self.timeDataR[name]['unit']
  271. elif self.timeDataR[name]['unit'] != unit:
  272. GError(self, _("Datasets have different time unit which "
  273. "is not allowed."))
  274. return
  275. rows = sp.get_registered_maps(columns=columns, where=None,
  276. order='start_time', dbif=self.dbif)
  277. for row in rows:
  278. self.timeDataR[name][row[0]] = {}
  279. self.timeDataR[name][row[0]]['start_datetime'] = row[1]
  280. self.timeDataR[name][row[0]]['end_datetime'] = row[2]
  281. r = RasterRow(row[0])
  282. r.open()
  283. val = r.get_value(self.poi)
  284. r.close()
  285. if val == -2147483648 and val < minmin:
  286. self.timeDataR[name][row[0]]['value'] = None
  287. else:
  288. self.timeDataR[name][row[0]]['value'] = val
  289. self.unit = unit
  290. self.temporalType = mode
  291. return
  292. def parseVDbConn(self, map, layerInp):
  293. '''find attribute key according to layer of input map'''
  294. vdb = Module('v.db.connect', map=map, flags='g', stdout_=PIPE)
  295. vdb = vdb.outputs.stdout
  296. for line in vdb.splitlines():
  297. lsplit = line.split('|')
  298. layer = lsplit[0].split('/')[0]
  299. if layer == layerInp:
  300. return lsplit[2]
  301. return None
  302. def _getSTVDData(self, timeseries):
  303. """Load data and read properties
  304. :param list timeseries: a list of timeseries
  305. """
  306. try:
  307. len(self.timeDataV)
  308. except:
  309. self.timeDataV = OrderedDict()
  310. # TODO parse categories to where condition
  311. # cats = self.cats.GetValue()
  312. cats = [str(i) for i in range(1,137)]
  313. cats = ','.join(cats)
  314. # idKye = 'linkid' #TODO
  315. mode = None
  316. unit = None
  317. attributes = self.attribute.GetValue()
  318. columns = ','.join(['name', 'start_time', 'end_time', 'id', 'layer'])
  319. for series in timeseries:
  320. name = series[0]
  321. fullname = name + '@' + series[1]
  322. etype = series[2]
  323. sp = tgis.dataset_factory(etype, fullname)
  324. sp.select(dbif=self.dbif)
  325. rows = sp.get_registered_maps(dbif=self.dbif, order="start_time",
  326. columns=columns, where=None)
  327. for attr in attributes.split(','):
  328. for x, cat in enumerate(cats.split(',')):
  329. # TODO chck
  330. idKye = self.parseVDbConn(rows[x]['name'],
  331. rows[x]['layer'])
  332. conditionWhere = idKye + '=' + cat
  333. self.listWhereConditions.append(conditionWhere)
  334. name = str(series) + str(conditionWhere)
  335. self.plotNameListV.append(name)
  336. self.timeDataV[name] = OrderedDict()
  337. if not sp.is_in_db(dbif=self.dbif):
  338. GError(self, message=_("Dataset <%s> not found in "
  339. "temporal database") % (fullname))
  340. return
  341. self.timeDataV[name]['temporalDataType'] = etype
  342. self.timeDataV[name]['temporalType'] = sp.get_temporal_type()
  343. self.timeDataV[name]['granularity'] = sp.get_granularity()
  344. if mode is None:
  345. mode = self.timeDataV[name]['temporalType']
  346. elif self.timeDataV[name]['temporalType'] != mode:
  347. GError(parent=self, message=_("Datasets have different temporal"
  348. " type (absolute x relative), "
  349. "which is not allowed."))
  350. return
  351. # check topology
  352. maps = sp.get_registered_maps_as_objects(dbif=self.dbif)
  353. self.timeDataV[name]['validTopology'] = sp.check_temporal_topology(maps=maps, dbif=self.dbif)
  354. self.timeDataV[name]['unit'] = None # only with relative
  355. if self.timeDataV[name]['temporalType'] == 'relative':
  356. start, end, self.timeDataV[name]['unit'] = sp.get_relative_time()
  357. if unit is None:
  358. unit = self.timeDataV[name]['unit']
  359. elif self.timeDataV[name]['unit'] != unit:
  360. GError(self, _("Datasets have different time unit"
  361. " which is not allowed."))
  362. return
  363. workers = multi.cpu_count()
  364. # Check if workers are already being used
  365. # run all bands in parallel
  366. if "WORKERS" in os.environ:
  367. workers = int(os.environ["WORKERS"])
  368. else:
  369. workers = len(rows)
  370. # Initialize process dictionary
  371. proc = {}
  372. pout = {}
  373. for j, row in enumerate(rows):
  374. self.timeDataV[name][row[3]] = {}
  375. self.timeDataV[name][row[3]]['start_datetime'] = row[1]
  376. self.timeDataV[name][row[3]]['end_datetime'] = row[2]
  377. if self.timeDataV[name][row[3]]['end_datetime'] is None:
  378. self.timeDataV[name][row[3]]['end_datetime'] = row[1]
  379. proc[j] = grass.pipe_command('v.db.select',
  380. map=row['name'],
  381. layer=row['layer'],
  382. where=conditionWhere,
  383. columns=attr,
  384. flags='c')
  385. if j % workers is 0:
  386. # wait for the ones launched so far to finish
  387. for jj in range(j):
  388. if not proc[jj].stdout.closed:
  389. pout[jj] = proc[jj].communicate()[0]
  390. proc[jj].wait()
  391. for row in range(len(proc)):
  392. if not proc[row].stdout.closed:
  393. pout[row] = proc[row].communicate()[0]
  394. proc[row].wait()
  395. for i, row in enumerate(rows):
  396. self.timeDataV[name][row[3]]['value'] = pout[i]
  397. ipdb.set_trace()
  398. self.unit = unit
  399. self.temporalType = mode
  400. return
  401. def _drawFigure(self):
  402. """Draws or print 2D plot (temporal extents)"""
  403. self.axes2d.clear()
  404. self.axes2d.grid(False)
  405. if self.temporalType == 'absolute':
  406. self.axes2d.xaxis_date()
  407. self.fig.autofmt_xdate()
  408. self.convert = mdates.date2num
  409. self.invconvert = mdates.num2date
  410. else:
  411. self.convert = lambda x: x
  412. self.invconvert = self.convert
  413. self.colors = cycle(COLORS)
  414. self.yticksNames = []
  415. self.yticksPos = []
  416. self.plots = []
  417. if self.datasetsR:
  418. self.lookUp = LookUp(self.timeDataR, self.invconvert)
  419. else:
  420. self.lookUp = LookUp(self.timeDataV, self.invconvert)
  421. if self.datasetsR:
  422. self.drawR()
  423. if self.datasetsV:
  424. self.drawV()
  425. self.canvas.draw()
  426. DataCursor(self.plots, self.lookUp, InfoFormat, self.convert)
  427. def drawR(self):
  428. for i, name in enumerate(self.datasetsR):
  429. name = name[0]
  430. # just name; with mapset it would be long
  431. self.yticksNames.append(name)
  432. self.yticksPos.append(1) # TODO
  433. xdata = []
  434. ydata = []
  435. for keys, values in self.timeDataR[name].iteritems():
  436. if keys in ['temporalType', 'granularity', 'validTopology',
  437. 'unit', 'temporalDataType']:
  438. continue
  439. xdata.append(self.convert(values['start_datetime']))
  440. ydata.append(values['value'])
  441. self.lookUp.AddDataset(yranges=ydata, xranges=xdata,
  442. datasetName=name)
  443. color = self.colors.next()
  444. self.plots.append(self.axes2d.plot(xdata, ydata, marker='o',
  445. color=color,
  446. label=self.plotNameListR[i])[0])
  447. if self.temporalType == 'absolute':
  448. self.axes2d.set_xlabel(_("Temporal resolution: %s" % self.timeDataR[name]['granularity']))
  449. else:
  450. self.axes2d.set_xlabel(_("Time [%s]") % self.unit)
  451. self.axes2d.set_ylabel(', '.join(self.yticksNames))
  452. # legend
  453. handles, labels = self.axes2d.get_legend_handles_labels()
  454. self.axes2d.legend(loc=0)
  455. def drawV(self):
  456. for i, name in enumerate(self.plotNameListV):
  457. # just name; with mapset it would be long
  458. self.yticksNames.append(self.attribute.GetValue())
  459. self.yticksPos.append(0) # TODO
  460. xdata = []
  461. ydata = []
  462. for keys, values in self.timeDataV[name].iteritems():
  463. if keys in ['temporalType', 'granularity', 'validTopology',
  464. 'unit', 'temporalDataType']:
  465. continue
  466. xdata.append(self.convert(values['start_datetime']))
  467. ydata.append(values['value'])
  468. self.lookUp.AddDataset(yranges=ydata, xranges=xdata,
  469. datasetName=name)
  470. color = self.colors.next()
  471. #print xdata
  472. #print ydata
  473. self.plots.append(self.axes2d.plot(xdata, ydata, marker='o',
  474. color=color, label=name)[0])
  475. # ============================
  476. if self.temporalType == 'absolute':
  477. self.axes2d.set_xlabel(_("Temporal resolution: %s" % self.timeDataV[name]['granularity']))
  478. else:
  479. self.axes2d.set_xlabel(_("Time [%s]") % self.unit)
  480. self.axes2d.set_ylabel(', '.join(self.yticksNames))
  481. # legend
  482. handles, labels = self.axes2d.get_legend_handles_labels()
  483. self.axes2d.legend(loc=0)
  484. self.listWhereConditions = []
  485. def OnRedraw(self, event=None):
  486. """Required redrawing."""
  487. self.init()
  488. datasetsR = self.datasetSelectR.GetValue().strip()
  489. datasetsV = self.datasetSelectV.GetValue().strip()
  490. if not datasetsR and not datasetsV:
  491. return
  492. # check raster dataset
  493. if datasetsR:
  494. datasetsR = datasetsR.split(',')
  495. try:
  496. datasetsR = self._checkDatasets(datasetsR)
  497. if not datasetsR:
  498. return
  499. except GException:
  500. GError(parent=self, message=_("Invalid input raster dataset"))
  501. return
  502. try:
  503. coordx, coordy = self.coorval.coordsField.GetValue().split(',')
  504. coordx, coordy = float(coordx), float(coordy)
  505. except (ValueError, AttributeError):
  506. try:
  507. coordx, coordy = self.coorval.GetValue().split(',')
  508. coordx, coordy = float(coordx), float(coordy)
  509. except (ValueError, AttributeError):
  510. GMessage(_("Incorrect format of coordinates, should be: x,y"))
  511. coors = [coordx, coordy]
  512. if coors:
  513. try:
  514. self.poi = Point(float(coors[0]), float(coors[1]))
  515. except GException:
  516. GError(parent=self, message=_("Invalid input coordinates"))
  517. return
  518. self.datasetsR = datasetsR
  519. # check vector dataset
  520. if datasetsV:
  521. datasetsV = datasetsV.split(',')
  522. try:
  523. datasetsV = self._checkDatasets(datasetsV)
  524. if not datasetsV:
  525. return
  526. except GException:
  527. GError(parent=self, message=_("Invalid input vector dataset"))
  528. return
  529. self.datasetsV = datasetsV
  530. self._redraw()
  531. def _redraw(self):
  532. """Readraw data.
  533. Decides if to draw also 3D and adjusts layout if needed.
  534. """
  535. if self.datasetsR:
  536. self._getSTRDdata(self.datasetsR)
  537. if self.datasetsV:
  538. self._getSTVDData(self.datasetsV)
  539. # axes3d are physically removed
  540. if not self.axes2d:
  541. self.axes2d = self.fig.add_subplot(1, 1, 1)
  542. self._drawFigure()
  543. def _checkDatasets(self, datasets):
  544. """Checks and validates datasets.
  545. Reports also type of dataset (e.g. 'strds').
  546. :param list datasets: list of temporal dataset's name
  547. :return: (mapName, mapset, type)
  548. """
  549. validated = []
  550. tDict = tgis.tlist_grouped('stds', group_type=True, dbif=self.dbif)
  551. # nested list with '(map, mapset, etype)' items
  552. allDatasets = [[[(map, mapset, etype) for map in maps]
  553. for etype, maps in etypesDict.iteritems()]
  554. for mapset, etypesDict in tDict.iteritems()]
  555. # flatten this list
  556. if allDatasets:
  557. allDatasets = reduce(lambda x, y: x + y, reduce(lambda x, y: x + y,
  558. allDatasets))
  559. mapsets = tgis.get_tgis_c_library_interface().available_mapsets()
  560. allDatasets = [i for i in sorted(allDatasets,
  561. key=lambda l: mapsets.index(l[1]))]
  562. for dataset in datasets:
  563. errorMsg = _("Space time dataset <%s> not found.") % dataset
  564. if dataset.find("@") >= 0:
  565. nameShort, mapset = dataset.split('@', 1)
  566. indices = [n for n, (mapName, mapsetName, etype) in enumerate(allDatasets)
  567. if nameShort == mapName and mapsetName == mapset]
  568. else:
  569. indices = [n for n, (mapName, mapset, etype) in enumerate(allDatasets)
  570. if dataset == mapName]
  571. if len(indices) == 0:
  572. raise GException(errorMsg)
  573. elif len(indices) >= 2:
  574. dlg = wx.SingleChoiceDialog(self,
  575. message=_("Please specify the "
  576. "space time dataset "
  577. "<%s>." % dataset),
  578. caption=_("Ambiguous dataset name"),
  579. choices=[("%(map)s@%(mapset)s:"
  580. " %(etype)s" % {'map': allDatasets[i][0],
  581. 'mapset': allDatasets[i][1],
  582. 'etype': allDatasets[i][2]})
  583. for i in indices],
  584. style=wx.CHOICEDLG_STYLE | wx.OK)
  585. if dlg.ShowModal() == wx.ID_OK:
  586. index = dlg.GetSelection()
  587. validated.append(allDatasets[indices[index]])
  588. else:
  589. continue
  590. else:
  591. validated.append(allDatasets[indices[0]])
  592. return validated
  593. def OnHelp(self, event):
  594. """Function to show help"""
  595. RunCommand('g.manual', quiet=True, entry='g.gui.tplot')
  596. def SetDatasets(self, rasters, vectors, coors, cats, attr):
  597. """Set the data
  598. #TODO
  599. :param list rasters: a list of temporal raster dataset's name
  600. :param list vectors: a list of temporal vector dataset's name
  601. :param list coors: a list with x/y coordinates
  602. :param list cats: a list with incld. categories of vector
  603. :param str attr: name of atribute of vectror data
  604. """
  605. if not (rasters or vectors) or not coors:
  606. return
  607. try:
  608. if rasters:
  609. self.datasetsR = self._checkDatasets(rasters)
  610. if vectors:
  611. self.datasetsV = self._checkDatasets(vectors)
  612. if not (self.datasetsR or self.datasetsV):
  613. return
  614. except GException:
  615. GError(parent=self, message=_("Invalid input temporal dataset"))
  616. return
  617. try:
  618. self.poi = Point(float(coors[0]), float(coors[1]))
  619. except GException:
  620. GError(parent=self, message=_("Invalid input coordinates"))
  621. return
  622. if self.datasetsV:
  623. self.datasetSelectV.SetValue(','.join(map(lambda x: x[0] + '@' + x[1],
  624. self.datasetsV)))
  625. self.attribute.SetValue(attr)
  626. if self.datasetsR:
  627. self.datasetSelectR.SetValue(','.join(map(lambda x: x[0] + '@' + x[1],
  628. self.datasetsR)))
  629. try:
  630. self.coorval.coordsField.SetValue(','.join(coors))
  631. except:
  632. self.coorval.SetValue(','.join(coors))
  633. self._redraw()
  634. def OnVectorSelected(self, event):
  635. """Update the controlbox related to stvds"""
  636. dataset = self.datasetSelectV.GetValue().strip()
  637. vect_list = grass.read_command('t.vect.list', flags='s', input=dataset,
  638. col='name')
  639. vect_list = list(set(sorted(vect_list.split())))
  640. for vec in vect_list:
  641. self.attribute.InsertColumns(vec, 1)
  642. class LookUp:
  643. """Helper class for searching info by coordinates"""
  644. def __init__(self, timeData, convert):
  645. self.data = {}
  646. self.timeData = timeData
  647. self.convert = convert
  648. def AddDataset(self, yranges, xranges, datasetName):
  649. if len(yranges) != len(xranges):
  650. GError(parent=self, message=_("Datasets have different number of"
  651. "values"))
  652. self.data[datasetName] = {}
  653. for i in range(len(xranges)):
  654. self.data[datasetName][xranges[i]] = yranges[i]
  655. def GetInformation(self, x):
  656. values = {}
  657. for key, value in self.data.iteritems():
  658. if value[x]:
  659. values[key] = [self.convert(x), value[x]]
  660. if len(values) == 0:
  661. return None
  662. return self.timeData, values
  663. def InfoFormat(timeData, values):
  664. """Formats information about dataset"""
  665. text = []
  666. for key, val in values.iteritems():
  667. etype = timeData[key]['temporalDataType']
  668. if etype == 'strds':
  669. text.append(_("Space time raster dataset: %s") % key)
  670. elif etype == 'stvds':
  671. text.append(_("Space time vector dataset: %s") % key)
  672. elif etype == 'str3ds':
  673. text.append(_("Space time 3D raster dataset: %s") % key)
  674. text.append(_("Value for {date} is {val}".format(date=val[0],
  675. val=val[1])))
  676. text.append('\n')
  677. text.append(_("Press Del to dismiss."))
  678. return '\n'.join(text)
  679. class DataCursor(object):
  680. """A simple data cursor widget that displays the x,y location of a
  681. matplotlib artist when it is selected.
  682. Source: http://stackoverflow.com/questions/4652439/
  683. is-there-a-matplotlib-equivalent-of-matlabs-datacursormode/4674445
  684. """
  685. def __init__(self, artists, lookUp, formatFunction, convert,
  686. tolerance=5, offsets=(-30, 20), display_all=False):
  687. """Create the data cursor and connect it to the relevant figure.
  688. "artists" is the matplotlib artist or sequence of artists that will be
  689. selected.
  690. "tolerance" is the radius (in points) that the mouse click must be
  691. within to select the artist.
  692. "offsets" is a tuple of (x,y) offsets in points from the selected
  693. point to the displayed annotation box
  694. "display_all" controls whether more than one annotation box will
  695. be shown if there are multiple axes. Only one will be shown
  696. per-axis, regardless.
  697. """
  698. self.lookUp = lookUp
  699. self.formatFunction = formatFunction
  700. self.offsets = offsets
  701. self.display_all = display_all
  702. if not cbook.iterable(artists):
  703. artists = [artists]
  704. self.artists = artists
  705. self.convert = convert
  706. self.axes = tuple(set(art.axes for art in self.artists))
  707. self.figures = tuple(set(ax.figure for ax in self.axes))
  708. self.annotations = {}
  709. for ax in self.axes:
  710. self.annotations[ax] = self.annotate(ax)
  711. for artist in self.artists:
  712. artist.set_picker(tolerance)
  713. for fig in self.figures:
  714. fig.canvas.mpl_connect('pick_event', self)
  715. fig.canvas.mpl_connect('key_press_event', self.keyPressed)
  716. def keyPressed(self, event):
  717. """Key pressed - hide annotation if Delete was pressed"""
  718. if event.key != 'delete':
  719. return
  720. for ax in self.axes:
  721. self.annotations[ax].set_visible(False)
  722. event.canvas.draw()
  723. def annotate(self, ax):
  724. """Draws and hides the annotation box for the given axis "ax"."""
  725. annotation = ax.annotate(self.formatFunction, xy=(0, 0), ha='center',
  726. xytext=self.offsets, va='bottom',
  727. textcoords='offset points',
  728. bbox=dict(boxstyle='round,pad=0.5',
  729. fc='yellow', alpha=0.7),
  730. arrowprops=dict(arrowstyle='->',
  731. connectionstyle='arc3,rad=0'),
  732. annotation_clip=False, multialignment='left')
  733. annotation.set_visible(False)
  734. return annotation
  735. def __call__(self, event):
  736. """Intended to be called through "mpl_connect"."""
  737. # Rather than trying to interpolate, just display the clicked coords
  738. # This will only be called if it's within "tolerance", anyway.
  739. x, y = event.mouseevent.xdata, event.mouseevent.ydata
  740. annotation = self.annotations[event.artist.axes]
  741. if x is not None:
  742. if not self.display_all:
  743. # Hide any other annotation boxes...
  744. for ann in self.annotations.values():
  745. ann.set_visible(False)
  746. if 'Line2D' in str(type(event.artist)):
  747. xData = []
  748. for a in event.artist.get_xdata():
  749. try:
  750. d = self.convert(a)
  751. except:
  752. d = a
  753. xData.append(d)
  754. x = xData[np.argmin(abs(xData - x))]
  755. info = self.lookUp.GetInformation(x)
  756. ys = zip(*info[1].values())[1]
  757. if not info:
  758. return
  759. # Update the annotation in the current axis..
  760. annotation.xy = x, max(ys)
  761. text = self.formatFunction(*info)
  762. annotation.set_text(text)
  763. annotation.set_visible(True)
  764. event.canvas.draw()