frame.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  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 GError, GException, RunCommand
  33. from gui_core import gselect
  34. from grass.pygrass.vector.geometry import Point
  35. from grass.pygrass.raster import RasterRow
  36. from collections import OrderedDict
  37. ALPHA = 0.5
  38. COLORS = ['b', 'g', 'r', 'c', 'm', 'y', 'k']
  39. def check_version(*version):
  40. """Checks if given version or newer is installed"""
  41. versionInstalled = []
  42. for i in matplotlib.__version__.split('.'):
  43. try:
  44. v = int(i)
  45. versionInstalled.append(v)
  46. except ValueError:
  47. versionInstalled.append(0)
  48. if versionInstalled < list(version):
  49. return False
  50. else:
  51. return True
  52. class TplotFrame(wx.Frame):
  53. """The main frame of the application"""
  54. def __init__(self, parent):
  55. wx.Frame.__init__(self, parent, id=wx.ID_ANY,
  56. title=_("GRASS GIS Temporal Plot Tool"))
  57. tgis.init(True)
  58. self.datasets = []
  59. self.output = None
  60. self.timeData = {}
  61. self._layout()
  62. self.temporalType = None
  63. self.unit = None
  64. # We create a database interface here to speedup the GUI
  65. self.dbif = tgis.SQLDatabaseInterfaceConnection()
  66. self.dbif.connect()
  67. def __del__(self):
  68. """Close the database interface and stop the messenger and C-interface
  69. subprocesses.
  70. """
  71. if self.dbif.connected is True:
  72. self.dbif.close()
  73. tgis.stop_subprocesses()
  74. def _layout(self):
  75. """Creates the main panel with all the controls on it:
  76. * mpl canvas
  77. * mpl navigation toolbar
  78. * Control panel for interaction
  79. """
  80. self.panel = wx.Panel(self)
  81. # Create the mpl Figure and FigCanvas objects.
  82. # 5x4 inches, 100 dots-per-inch
  83. #
  84. # color = wx.SystemSettings.GetColour(wx.SYS_COLOUR_BACKGROUND)
  85. self.fig = Figure((5.0, 4.0), facecolor=(1, 1, 1))
  86. self.canvas = FigCanvas(self.panel, wx.ID_ANY, self.fig)
  87. # axes are initialized later
  88. self.axes2d = None
  89. self.axes3d = None
  90. # Create the navigation toolbar, tied to the canvas
  91. #
  92. self.toolbar = NavigationToolbar(self.canvas)
  93. #
  94. # Layout
  95. #
  96. self.vbox = wx.BoxSizer(wx.VERTICAL)
  97. self.vbox.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.EXPAND)
  98. self.vbox.Add(self.toolbar, 0, wx.EXPAND)
  99. self.vbox.AddSpacer(10)
  100. gridSizer = wx.GridBagSizer(hgap=5, vgap=5)
  101. self.datasetSelect = gselect.Select(parent=self.panel, id=wx.ID_ANY,
  102. type='strds', multiple=True, size=(150, -1))
  103. self.drawButton = wx.Button(self.panel, id=wx.ID_ANY, label=_("Draw"))
  104. self.drawButton.Bind(wx.EVT_BUTTON, self.OnRedraw)
  105. self.helpButton = wx.Button(self.panel, id=wx.ID_ANY, label=_("Help"))
  106. self.helpButton.Bind(wx.EVT_BUTTON, self.OnHelp)
  107. self.xcoor = wx.StaticText(parent=self.panel, id=wx.ID_ANY,
  108. label=_('Insert longitude (x) coordinate'))
  109. self.xcoorval = wx.TextCtrl(parent=self.panel, id=wx.ID_ANY,
  110. size=(150, -1))
  111. self.ycoor = wx.StaticText(parent=self.panel, id=wx.ID_ANY,
  112. label=_('Insert latitude (y) coordinate'))
  113. self.ycoorval = wx.TextCtrl(parent=self.panel, id=wx.ID_ANY,
  114. size=(150, -1))
  115. gridSizer.Add(wx.StaticText(self.panel, id=wx.ID_ANY,
  116. label=_("Select space time dataset(s):")),
  117. pos=(0, 0), flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL)
  118. gridSizer.Add(self.datasetSelect, pos=(1, 0), flag=wx.EXPAND)
  119. gridSizer.Add(self.xcoor, pos=(2, 0), flag=wx.EXPAND)
  120. gridSizer.Add(self.ycoor, pos=(2, 1), flag=wx.EXPAND)
  121. gridSizer.Add(self.xcoorval, pos=(3, 0), flag=wx.EXPAND)
  122. gridSizer.Add(self.ycoorval, pos=(3, 1), flag=wx.EXPAND)
  123. gridSizer.Add(self.drawButton, pos=(3, 2), flag=wx.EXPAND)
  124. gridSizer.Add(self.helpButton, pos=(3, 3), flag=wx.EXPAND)
  125. self.vbox.Add(gridSizer, proportion=0, flag=wx.EXPAND | wx.ALL,
  126. border=10)
  127. self.panel.SetSizer(self.vbox)
  128. self.vbox.Fit(self)
  129. def _getData(self, timeseries):
  130. """Load data and read properties
  131. :param list timeseries: a list of timeseries
  132. """
  133. self.timeData = OrderedDict()
  134. mode = None
  135. unit = None
  136. columns = ','.join(['name', 'start_time', 'end_time'])
  137. for series in timeseries:
  138. name = series[0]
  139. fullname = name + '@' + series[1]
  140. etype = series[2]
  141. sp = tgis.dataset_factory(etype, fullname)
  142. sp.select(dbif=self.dbif)
  143. self.timeData[name] = OrderedDict()
  144. if not sp.is_in_db(dbif=self.dbif):
  145. GError(self, message=_("Dataset <%s> not found in temporal "
  146. "database") % (fullname))
  147. return
  148. self.timeData[name]['temporalDataType'] = etype
  149. self.timeData[name]['temporalType'] = sp.get_temporal_type()
  150. self.timeData[name]['granularity'] = sp.get_granularity()
  151. if mode is None:
  152. mode = self.timeData[name]['temporalType']
  153. elif self.timeData[name]['temporalType'] != mode:
  154. GError(parent=self, message=_("Datasets have different temporal"
  155. " type (absolute x relative), "
  156. "which is not allowed."))
  157. return
  158. # check topology
  159. maps = sp.get_registered_maps_as_objects(dbif=self.dbif)
  160. self.timeData[name]['validTopology'] = sp.check_temporal_topology(maps=maps, dbif=self.dbif)
  161. self.timeData[name]['unit'] = None # only with relative
  162. if self.timeData[name]['temporalType'] == 'relative':
  163. start, end, self.timeData[name]['unit'] = sp.get_relative_time()
  164. if unit is None:
  165. unit = self.timeData[name]['unit']
  166. elif self.timeData[name]['unit'] != unit:
  167. GError(self, _("Datasets have different time unit which "
  168. "is not allowed."))
  169. return
  170. rows = sp.get_registered_maps(columns=columns, where=None,
  171. order='start_time', dbif=self.dbif)
  172. for row in rows:
  173. self.timeData[name][row[0]] = {}
  174. self.timeData[name][row[0]]['start_datetime'] = row[1]
  175. self.timeData[name][row[0]]['end_datetime'] = row[2]
  176. r = RasterRow(row[0])
  177. r.open()
  178. val = r.get_value(self.poi)
  179. r.close()
  180. self.timeData[name][row[0]]['value'] = val
  181. self.unit = unit
  182. self.temporalType = mode
  183. return
  184. def _drawFigure(self):
  185. """Draws or print 2D plot (temporal extents)"""
  186. self.axes2d.clear()
  187. self.axes2d.grid(False)
  188. if self.temporalType == 'absolute':
  189. self.axes2d.xaxis_date()
  190. self.fig.autofmt_xdate()
  191. self.convert = mdates.date2num
  192. self.invconvert = mdates.num2date
  193. else:
  194. self.convert = lambda x: x
  195. self.invconvert = self.convert
  196. colors = cycle(COLORS)
  197. yticksNames = []
  198. yticksPos = []
  199. plots = []
  200. lookUp = LookUp(self.timeData, self.invconvert)
  201. for i, name in enumerate(self.datasets):
  202. name = name[0]
  203. yticksNames.append(name) # just name; with mapset it would be long
  204. yticksPos.append(i)
  205. xdata = []
  206. ydata = []
  207. for keys, values in self.timeData[name].iteritems():
  208. if keys in ['temporalType', 'granularity', 'validTopology',
  209. 'unit', 'temporalDataType']:
  210. continue
  211. xdata.append(self.convert(values['start_datetime']))
  212. ydata.append(values['value'])
  213. lookUp.AddDataset(yranges=ydata, xranges=xdata, datasetName=name)
  214. color = colors.next()
  215. plots.append(self.axes2d.plot(xdata, ydata, marker='o',
  216. color=color, label=name)[0])
  217. if self.temporalType == 'absolute':
  218. self.axes2d.set_xlabel(_("Temporal resolution: %s" % self.timeData[name]['granularity']))
  219. else:
  220. self.axes2d.set_xlabel(_("Time [%s]") % self.unit)
  221. self.axes2d.set_ylabel(', '.join(yticksNames))
  222. #legend
  223. handles, labels = self.axes2d.get_legend_handles_labels()
  224. self.axes2d.legend(loc=0)
  225. if self.output:
  226. self.canvas.print_figure(filename=self.output, dpi=self.dpi)
  227. else:
  228. self.canvas.draw()
  229. DataCursor(plots, lookUp, InfoFormat, self.convert)
  230. def OnRedraw(self, event):
  231. """Required redrawing."""
  232. datasets = self.datasetSelect.GetValue().strip()
  233. if not datasets:
  234. return
  235. datasets = datasets.split(',')
  236. try:
  237. datasets = self._checkDatasets(datasets)
  238. if not datasets:
  239. return
  240. except GException:
  241. GError(parent=self, message=_("Invalid input data"))
  242. return
  243. self.datasets = datasets
  244. coors = [self.xcoorval.GetValue().strip(),
  245. self.ycoorval.GetValue().strip()]
  246. if coors:
  247. try:
  248. self.poi = Point(float(coors[0]), float(coors[1]))
  249. except GException:
  250. GError(parent=self, message=_("Invalid input coordinates"))
  251. return
  252. self._redraw()
  253. def _redraw(self):
  254. """Readraw data.
  255. Decides if to draw also 3D and adjusts layout if needed.
  256. """
  257. self._getData(self.datasets)
  258. # axes3d are physically removed
  259. if not self.axes2d:
  260. self.axes2d = self.fig.add_subplot(1, 1, 1)
  261. self._drawFigure()
  262. def _checkDatasets(self, datasets):
  263. """Checks and validates datasets.
  264. Reports also type of dataset (e.g. 'strds').
  265. :param list datasets: list of temporal dataset's name
  266. :return: (mapName, mapset, type)
  267. """
  268. validated = []
  269. tDict = tgis.tlist_grouped('stds', group_type=True, dbif=self.dbif)
  270. # nested list with '(map, mapset, etype)' items
  271. allDatasets = [[[(map, mapset, etype) for map in maps]
  272. for etype, maps in etypesDict.iteritems()]
  273. for mapset, etypesDict in tDict.iteritems()]
  274. # flatten this list
  275. if allDatasets:
  276. allDatasets = reduce(lambda x, y: x + y, reduce(lambda x, y: x + y,
  277. allDatasets))
  278. mapsets = tgis.get_tgis_c_library_interface().available_mapsets()
  279. allDatasets = [i for i in sorted(allDatasets,
  280. key=lambda l: mapsets.index(l[1]))]
  281. for dataset in datasets:
  282. errorMsg = _("Space time dataset <%s> not found.") % dataset
  283. if dataset.find("@") >= 0:
  284. nameShort, mapset = dataset.split('@', 1)
  285. indices = [n for n, (mapName, mapsetName, etype) in enumerate(allDatasets)
  286. if nameShort == mapName and mapsetName == mapset]
  287. else:
  288. indices = [n for n, (mapName, mapset, etype) in enumerate(allDatasets)
  289. if dataset == mapName]
  290. if len(indices) == 0:
  291. raise GException(errorMsg)
  292. elif len(indices) >= 2:
  293. dlg = wx.SingleChoiceDialog(self,
  294. message=_("Please specify the "
  295. "space time dataset "
  296. "<%s>." % dataset),
  297. caption=_("Ambiguous dataset name"),
  298. choices=[("%(map)s@%(mapset)s:"
  299. " %(etype)s" % {'map': allDatasets[i][0],
  300. 'mapset': allDatasets[i][1],
  301. 'etype': allDatasets[i][2]})
  302. for i in indices],
  303. style=wx.CHOICEDLG_STYLE | wx.OK)
  304. if dlg.ShowModal() == wx.ID_OK:
  305. index = dlg.GetSelection()
  306. validated.append(allDatasets[indices[index]])
  307. else:
  308. continue
  309. else:
  310. validated.append(allDatasets[indices[0]])
  311. return validated
  312. def OnHelp(self, event):
  313. """Function to show help"""
  314. RunCommand('g.manual', quiet=True, entry='g.gui.tplot')
  315. def SetDatasets(self, datasets, coors, output, dpi):
  316. """Set the data
  317. :param list datasets: a list of temporal dataset's name
  318. :param list coors: a list with x/y coordinates
  319. :param str output: the name of output png file
  320. :param int dpi: the dpi value for png file
  321. """
  322. if not datasets or not coors:
  323. return
  324. try:
  325. datasets = self._checkDatasets(datasets)
  326. if not datasets:
  327. return
  328. except GException:
  329. GError(parent=self, message=_("Invalid input temporal dataset"))
  330. return
  331. try:
  332. self.poi = Point(float(coors[0]), float(coors[1]))
  333. except GException:
  334. GError(parent=self, message=_("Invalid input coordinates"))
  335. return
  336. self.datasets = datasets
  337. self.output = output
  338. self.dpi = dpi
  339. self.datasetSelect.SetValue(','.join(map(lambda x: x[0] + '@' + x[1],
  340. datasets)))
  341. self.xcoorval.SetValue(str(coors[0]))
  342. self.ycoorval.SetValue(str(coors[1]))
  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()