frame.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. """
  2. @package frame
  3. @brief Temporal Plot Tool
  4. Classes:
  5. - frame::DataCursor
  6. - frame::TplotFrame
  7. - frame::LookUp
  8. (C) 2012-2014 by the GRASS Development Team
  9. This program is free software under the GNU General Public License
  10. (>=v2). Read the file COPYING that comes with GRASS for details.
  11. @author Luca Delucchi
  12. """
  13. from itertools import cycle
  14. import numpy as np
  15. import wx
  16. try:
  17. import matplotlib
  18. # The recommended way to use wx with mpl is with the WXAgg
  19. # backend.
  20. matplotlib.use('WXAgg')
  21. from matplotlib.figure import Figure
  22. from matplotlib.backends.backend_wxagg import \
  23. FigureCanvasWxAgg as FigCanvas, \
  24. NavigationToolbar2WxAgg as NavigationToolbar
  25. import matplotlib.dates as mdates
  26. from matplotlib import cbook
  27. except ImportError:
  28. raise ImportError(_('The Temporal Plot Tool needs the "matplotlib" '
  29. '(python-matplotlib) package to be installed.'))
  30. from core.utils import _
  31. import grass.temporal as tgis
  32. from core.gcmd import GMessage, GError, GException, RunCommand
  33. from gui_core import gselect
  34. from core import globalvar
  35. from grass.pygrass.vector.geometry import Point
  36. from grass.pygrass.raster import RasterRow
  37. from collections import OrderedDict
  38. ALPHA = 0.5
  39. COLORS = ['b', 'g', 'r', 'c', 'm', 'y', 'k']
  40. def check_version(*version):
  41. """Checks if given version or newer is installed"""
  42. versionInstalled = []
  43. for i in matplotlib.__version__.split('.'):
  44. try:
  45. v = int(i)
  46. versionInstalled.append(v)
  47. except ValueError:
  48. versionInstalled.append(0)
  49. if versionInstalled < list(version):
  50. return False
  51. else:
  52. return True
  53. class TplotFrame(wx.Frame):
  54. """The main frame of the application"""
  55. def __init__(self, parent):
  56. wx.Frame.__init__(self, parent, id=wx.ID_ANY,
  57. title=_("GRASS GIS Temporal Plot Tool"))
  58. tgis.init(True)
  59. self.datasets = []
  60. self.output = None
  61. self.timeData = {}
  62. self._layout()
  63. self.temporalType = None
  64. self.unit = None
  65. # We create a database interface here to speedup the GUI
  66. self.dbif = tgis.SQLDatabaseInterfaceConnection()
  67. self.dbif.connect()
  68. def __del__(self):
  69. """Close the database interface and stop the messenger and C-interface
  70. subprocesses.
  71. """
  72. if self.dbif.connected is True:
  73. self.dbif.close()
  74. tgis.stop_subprocesses()
  75. def _layout(self):
  76. """Creates the main panel with all the controls on it:
  77. * mpl canvas
  78. * mpl navigation toolbar
  79. * Control panel for interaction
  80. """
  81. self.panel = wx.Panel(self)
  82. # Create the mpl Figure and FigCanvas objects.
  83. # 5x4 inches, 100 dots-per-inch
  84. #
  85. # color = wx.SystemSettings.GetColour(wx.SYS_COLOUR_BACKGROUND)
  86. self.fig = Figure((5.0, 4.0), facecolor=(1, 1, 1))
  87. self.canvas = FigCanvas(self.panel, wx.ID_ANY, self.fig)
  88. # axes are initialized later
  89. self.axes2d = None
  90. self.axes3d = None
  91. # Create the navigation toolbar, tied to the canvas
  92. #
  93. self.toolbar = NavigationToolbar(self.canvas)
  94. #
  95. # Layout
  96. #
  97. self.vbox = wx.BoxSizer(wx.VERTICAL)
  98. self.vbox.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.EXPAND)
  99. self.vbox.Add(self.toolbar, 0, wx.EXPAND)
  100. self.vbox.AddSpacer(10)
  101. gridSizer = wx.GridBagSizer(hgap=5, vgap=5)
  102. self.datasetSelect = gselect.Select(parent=self.panel, id=wx.ID_ANY,
  103. size=globalvar.DIALOG_GSELECT_SIZE,
  104. type='strds', multiple=True)
  105. self.drawButton = wx.Button(self.panel, id=wx.ID_ANY, label=_("Draw"))
  106. self.drawButton.Bind(wx.EVT_BUTTON, self.OnRedraw)
  107. self.helpButton = wx.Button(self.panel, id=wx.ID_ANY, label=_("Help"))
  108. self.helpButton.Bind(wx.EVT_BUTTON, self.OnHelp)
  109. self.coor = wx.StaticText(parent=self.panel, id=wx.ID_ANY,
  110. label=_('X and Y coordinates separated by comma:'))
  111. self.coorval = wx.TextCtrl(parent=self.panel, id=wx.ID_ANY)
  112. self.coorval.SetToolTipString(_("Coordinates can be obtained for example "
  113. "by right-clicking on Map Display."))
  114. gridSizer.Add(wx.StaticText(self.panel, id=wx.ID_ANY,
  115. label=_("Select space time raster dataset(s):")),
  116. pos=(0, 0), flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL)
  117. gridSizer.Add(self.datasetSelect, pos=(1, 0), flag=wx.EXPAND)
  118. gridSizer.Add(self.coor, pos=(2, 0), flag=wx.EXPAND)
  119. gridSizer.Add(self.coorval, pos=(3, 0), flag=wx.EXPAND)
  120. gridSizer.Add(self.drawButton, pos=(3, 1), flag=wx.EXPAND)
  121. gridSizer.Add(self.helpButton, pos=(3, 2), flag=wx.EXPAND)
  122. self.vbox.Add(gridSizer, proportion=0, flag=wx.EXPAND | wx.ALL,
  123. border=10)
  124. self.panel.SetSizer(self.vbox)
  125. self.vbox.Fit(self)
  126. def _getData(self, timeseries):
  127. """Load data and read properties
  128. :param list timeseries: a list of timeseries
  129. """
  130. self.timeData = OrderedDict()
  131. mode = None
  132. unit = None
  133. columns = ','.join(['name', 'start_time', 'end_time'])
  134. for series in timeseries:
  135. name = series[0]
  136. fullname = name + '@' + series[1]
  137. etype = series[2]
  138. sp = tgis.dataset_factory(etype, fullname)
  139. sp.select(dbif=self.dbif)
  140. self.timeData[name] = OrderedDict()
  141. if not sp.is_in_db(dbif=self.dbif):
  142. GError(self, message=_("Dataset <%s> not found in temporal "
  143. "database") % (fullname))
  144. return
  145. self.timeData[name]['temporalDataType'] = etype
  146. self.timeData[name]['temporalType'] = sp.get_temporal_type()
  147. self.timeData[name]['granularity'] = sp.get_granularity()
  148. if mode is None:
  149. mode = self.timeData[name]['temporalType']
  150. elif self.timeData[name]['temporalType'] != mode:
  151. GError(parent=self, message=_("Datasets have different temporal"
  152. " type (absolute x relative), "
  153. "which is not allowed."))
  154. return
  155. # check topology
  156. maps = sp.get_registered_maps_as_objects(dbif=self.dbif)
  157. self.timeData[name]['validTopology'] = sp.check_temporal_topology(maps=maps, dbif=self.dbif)
  158. self.timeData[name]['unit'] = None # only with relative
  159. if self.timeData[name]['temporalType'] == 'relative':
  160. start, end, self.timeData[name]['unit'] = sp.get_relative_time()
  161. if unit is None:
  162. unit = self.timeData[name]['unit']
  163. elif self.timeData[name]['unit'] != unit:
  164. GError(self, _("Datasets have different time unit which "
  165. "is not allowed."))
  166. return
  167. rows = sp.get_registered_maps(columns=columns, where=None,
  168. order='start_time', dbif=self.dbif)
  169. for row in rows:
  170. self.timeData[name][row[0]] = {}
  171. self.timeData[name][row[0]]['start_datetime'] = row[1]
  172. self.timeData[name][row[0]]['end_datetime'] = row[2]
  173. r = RasterRow(row[0])
  174. r.open()
  175. val = r.get_value(self.poi)
  176. r.close()
  177. self.timeData[name][row[0]]['value'] = val
  178. self.unit = unit
  179. self.temporalType = mode
  180. return
  181. def _drawFigure(self):
  182. """Draws or print 2D plot (temporal extents)"""
  183. self.axes2d.clear()
  184. self.axes2d.grid(False)
  185. if self.temporalType == 'absolute':
  186. self.axes2d.xaxis_date()
  187. self.fig.autofmt_xdate()
  188. self.convert = mdates.date2num
  189. self.invconvert = mdates.num2date
  190. else:
  191. self.convert = lambda x: x
  192. self.invconvert = self.convert
  193. colors = cycle(COLORS)
  194. yticksNames = []
  195. yticksPos = []
  196. plots = []
  197. lookUp = LookUp(self.timeData, self.invconvert)
  198. for i, name in enumerate(self.datasets):
  199. name = name[0]
  200. yticksNames.append(name) # just name; with mapset it would be long
  201. yticksPos.append(i)
  202. xdata = []
  203. ydata = []
  204. for keys, values in self.timeData[name].iteritems():
  205. if keys in ['temporalType', 'granularity', 'validTopology',
  206. 'unit', 'temporalDataType']:
  207. continue
  208. xdata.append(self.convert(values['start_datetime']))
  209. ydata.append(values['value'])
  210. lookUp.AddDataset(yranges=ydata, xranges=xdata, datasetName=name)
  211. color = colors.next()
  212. plots.append(self.axes2d.plot(xdata, ydata, marker='o',
  213. color=color, label=name)[0])
  214. if self.temporalType == 'absolute':
  215. self.axes2d.set_xlabel(_("Temporal resolution: %s" % self.timeData[name]['granularity']))
  216. else:
  217. self.axes2d.set_xlabel(_("Time [%s]") % self.unit)
  218. self.axes2d.set_ylabel(', '.join(yticksNames))
  219. #legend
  220. handles, labels = self.axes2d.get_legend_handles_labels()
  221. self.axes2d.legend(loc=0)
  222. if self.output:
  223. self.canvas.print_figure(filename=self.output, dpi=self.dpi)
  224. else:
  225. self.canvas.draw()
  226. DataCursor(plots, lookUp, InfoFormat, self.convert)
  227. def OnRedraw(self, event):
  228. """Required redrawing."""
  229. datasets = self.datasetSelect.GetValue().strip()
  230. if not datasets:
  231. return
  232. datasets = datasets.split(',')
  233. try:
  234. datasets = self._checkDatasets(datasets)
  235. if not datasets:
  236. return
  237. except GException:
  238. GError(parent=self, message=_("Invalid input data"))
  239. return
  240. self.datasets = datasets
  241. try:
  242. coordx, coordy = self.coorval.GetValue().split(',')
  243. coordx, coordy = float(coordx), float(coordy)
  244. except ValueError:
  245. GMessage(_("Incorrect format of coordinates, should be: x,y"))
  246. coors = [coordx, coordy]
  247. if coors:
  248. try:
  249. self.poi = Point(float(coors[0]), float(coors[1]))
  250. except GException:
  251. GError(parent=self, message=_("Invalid input coordinates"))
  252. return
  253. self._redraw()
  254. def _redraw(self):
  255. """Readraw data.
  256. Decides if to draw also 3D and adjusts layout if needed.
  257. """
  258. self._getData(self.datasets)
  259. # axes3d are physically removed
  260. if not self.axes2d:
  261. self.axes2d = self.fig.add_subplot(1, 1, 1)
  262. self._drawFigure()
  263. def _checkDatasets(self, datasets):
  264. """Checks and validates datasets.
  265. Reports also type of dataset (e.g. 'strds').
  266. :param list datasets: list of temporal dataset's name
  267. :return: (mapName, mapset, type)
  268. """
  269. validated = []
  270. tDict = tgis.tlist_grouped('stds', group_type=True, dbif=self.dbif)
  271. # nested list with '(map, mapset, etype)' items
  272. allDatasets = [[[(map, mapset, etype) for map in maps]
  273. for etype, maps in etypesDict.iteritems()]
  274. for mapset, etypesDict in tDict.iteritems()]
  275. # flatten this list
  276. if allDatasets:
  277. allDatasets = reduce(lambda x, y: x + y, reduce(lambda x, y: x + y,
  278. allDatasets))
  279. mapsets = tgis.get_tgis_c_library_interface().available_mapsets()
  280. allDatasets = [i for i in sorted(allDatasets,
  281. key=lambda l: mapsets.index(l[1]))]
  282. for dataset in datasets:
  283. errorMsg = _("Space time dataset <%s> not found.") % dataset
  284. if dataset.find("@") >= 0:
  285. nameShort, mapset = dataset.split('@', 1)
  286. indices = [n for n, (mapName, mapsetName, etype) in enumerate(allDatasets)
  287. if nameShort == mapName and mapsetName == mapset]
  288. else:
  289. indices = [n for n, (mapName, mapset, etype) in enumerate(allDatasets)
  290. if dataset == mapName]
  291. if len(indices) == 0:
  292. raise GException(errorMsg)
  293. elif len(indices) >= 2:
  294. dlg = wx.SingleChoiceDialog(self,
  295. message=_("Please specify the "
  296. "space time dataset "
  297. "<%s>." % dataset),
  298. caption=_("Ambiguous dataset name"),
  299. choices=[("%(map)s@%(mapset)s:"
  300. " %(etype)s" % {'map': allDatasets[i][0],
  301. 'mapset': allDatasets[i][1],
  302. 'etype': allDatasets[i][2]})
  303. for i in indices],
  304. style=wx.CHOICEDLG_STYLE | wx.OK)
  305. if dlg.ShowModal() == wx.ID_OK:
  306. index = dlg.GetSelection()
  307. validated.append(allDatasets[indices[index]])
  308. else:
  309. continue
  310. else:
  311. validated.append(allDatasets[indices[0]])
  312. return validated
  313. def OnHelp(self, event):
  314. """Function to show help"""
  315. RunCommand('g.manual', quiet=True, entry='g.gui.tplot')
  316. def SetDatasets(self, datasets, coors, output, dpi):
  317. """Set the data
  318. :param list datasets: a list of temporal dataset's name
  319. :param list coors: a list with x/y coordinates
  320. :param str output: the name of output png file
  321. :param int dpi: the dpi value for png file
  322. """
  323. if not datasets or not coors:
  324. return
  325. try:
  326. datasets = self._checkDatasets(datasets)
  327. if not datasets:
  328. return
  329. except GException:
  330. GError(parent=self, message=_("Invalid input temporal dataset"))
  331. return
  332. try:
  333. self.poi = Point(float(coors[0]), float(coors[1]))
  334. except GException:
  335. GError(parent=self, message=_("Invalid input coordinates"))
  336. return
  337. self.datasets = datasets
  338. self.output = output
  339. self.dpi = dpi
  340. self.datasetSelect.SetValue(','.join(map(lambda x: x[0] + '@' + x[1],
  341. datasets)))
  342. self.coorval.SetValue(','.join(coors))
  343. self._redraw()
  344. class LookUp:
  345. """Helper class for searching info by coordinates"""
  346. def __init__(self, timeData, convert):
  347. self.data = {}
  348. self.timeData = timeData
  349. self.convert = convert
  350. def AddDataset(self, yranges, xranges, datasetName):
  351. if len(yranges) != len(xranges):
  352. GError(parent=self, message=_("Datasets have different number of"
  353. "values"))
  354. self.data[datasetName] = {}
  355. for i in range(len(xranges)):
  356. self.data[datasetName][xranges[i]] = yranges[i]
  357. def GetInformation(self, x):
  358. values = {}
  359. for key, value in self.data.iteritems():
  360. if value[x]:
  361. values[key] = [self.convert(x), value[x]]
  362. if len(values) == 0:
  363. return None
  364. return self.timeData, values
  365. def InfoFormat(timeData, values):
  366. """Formats information about dataset"""
  367. text = []
  368. for key, val in values.iteritems():
  369. etype = timeData[key]['temporalDataType']
  370. if etype == 'strds':
  371. text.append(_("Space time raster dataset: %s") % key)
  372. elif etype == 'stvds':
  373. text.append(_("Space time vector dataset: %s") % key)
  374. elif etype == 'str3ds':
  375. text.append(_("Space time 3D raster dataset: %s") % key)
  376. text.append(_("Value for {date} is {val}".format(date=val[0], val=val[1])))
  377. text.append('\n')
  378. text.append(_("Press Del to dismiss."))
  379. return '\n'.join(text)
  380. class DataCursor(object):
  381. """A simple data cursor widget that displays the x,y location of a
  382. matplotlib artist when it is selected.
  383. Source: http://stackoverflow.com/questions/4652439/
  384. is-there-a-matplotlib-equivalent-of-matlabs-datacursormode/4674445
  385. """
  386. def __init__(self, artists, lookUp, formatFunction, convert,
  387. tolerance=5, offsets=(-30, 20), display_all=False):
  388. """Create the data cursor and connect it to the relevant figure.
  389. "artists" is the matplotlib artist or sequence of artists that will be
  390. selected.
  391. "tolerance" is the radius (in points) that the mouse click must be
  392. within to select the artist.
  393. "offsets" is a tuple of (x,y) offsets in points from the selected
  394. point to the displayed annotation box
  395. "display_all" controls whether more than one annotation box will
  396. be shown if there are multiple axes. Only one will be shown
  397. per-axis, regardless.
  398. """
  399. self.lookUp = lookUp
  400. self.formatFunction = formatFunction
  401. self.offsets = offsets
  402. self.display_all = display_all
  403. if not cbook.iterable(artists):
  404. artists = [artists]
  405. self.artists = artists
  406. self.convert = convert
  407. self.axes = tuple(set(art.axes for art in self.artists))
  408. self.figures = tuple(set(ax.figure for ax in self.axes))
  409. self.annotations = {}
  410. for ax in self.axes:
  411. self.annotations[ax] = self.annotate(ax)
  412. for artist in self.artists:
  413. artist.set_picker(tolerance)
  414. for fig in self.figures:
  415. fig.canvas.mpl_connect('pick_event', self)
  416. fig.canvas.mpl_connect('key_press_event', self.keyPressed)
  417. def keyPressed(self, event):
  418. """Key pressed - hide annotation if Delete was pressed"""
  419. if event.key != 'delete':
  420. return
  421. for ax in self.axes:
  422. self.annotations[ax].set_visible(False)
  423. event.canvas.draw()
  424. def annotate(self, ax):
  425. """Draws and hides the annotation box for the given axis "ax"."""
  426. annotation = ax.annotate(self.formatFunction, xy=(0, 0), ha='center',
  427. xytext=self.offsets, va='bottom',
  428. textcoords='offset points',
  429. bbox=dict(boxstyle='round,pad=0.5',
  430. fc='yellow', alpha=0.7),
  431. arrowprops=dict(arrowstyle='->',
  432. connectionstyle='arc3,rad=0'),
  433. annotation_clip=False, multialignment='left')
  434. annotation.set_visible(False)
  435. return annotation
  436. def __call__(self, event):
  437. """Intended to be called through "mpl_connect"."""
  438. # Rather than trying to interpolate, just display the clicked coords
  439. # This will only be called if it's within "tolerance", anyway.
  440. x, y = event.mouseevent.xdata, event.mouseevent.ydata
  441. annotation = self.annotations[event.artist.axes]
  442. if x is not None:
  443. if not self.display_all:
  444. # Hide any other annotation boxes...
  445. for ann in self.annotations.values():
  446. ann.set_visible(False)
  447. if 'Line2D' in str(type(event.artist)):
  448. xData = []
  449. for a in event.artist.get_xdata():
  450. try:
  451. d = self.convert(a)
  452. except:
  453. d = a
  454. xData.append(d)
  455. x = xData[np.argmin(abs(xData - x))]
  456. info = self.lookUp.GetInformation(x)
  457. ys = zip(*info[1].values())[1]
  458. if not info:
  459. return
  460. # Update the annotation in the current axis..
  461. annotation.xy = x, max(ys)
  462. text = self.formatFunction(*info)
  463. annotation.set_text(text)
  464. annotation.set_visible(True)
  465. event.canvas.draw()
  466. def run(parent=None, datasets=None):
  467. frame = TplotFrame(parent)
  468. if datasets:
  469. frame.SetDatasets(datasets)
  470. frame.Show()
  471. if __name__ == '__main__':
  472. run()