frame.py 51 KB

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