temporal_manager.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. """!
  2. @package animation.temporal_manager
  3. @brief Management of temporal datasets used in animation
  4. Classes:
  5. - temporal_manager::DataMode
  6. - temporal_manager::GranularityMode
  7. - temporal_manager::TemporalManager
  8. (C) 2012 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 Anna Kratochvilova <kratochanna gmail.com>
  12. """
  13. import os
  14. import sys
  15. if __name__ == '__main__':
  16. sys.path.append(os.path.join(os.environ['GISBASE'], "etc", "gui", "wxpython"))
  17. import grass.script as grass
  18. import grass.temporal as tgis
  19. from core.gcmd import GException
  20. from core.utils import _
  21. from utils import validateTimeseriesName, TemporalType
  22. class DataMode:
  23. SIMPLE = 1
  24. MULTIPLE = 2
  25. class GranularityMode:
  26. ONE_UNIT = 1
  27. ORIGINAL = 2
  28. class TemporalManager(object):
  29. """!Class for temporal data processing."""
  30. def __init__(self):
  31. self.timeseriesList = []
  32. self.timeseriesInfo = {}
  33. self.dataMode = None
  34. self.temporalType = None
  35. self.granularityMode = GranularityMode.ONE_UNIT
  36. # Make sure the temporal database exists
  37. tgis.init()
  38. def GetTemporalType(self):
  39. """!Get temporal type (TemporalType.ABSOLUTE, TemporalType.RELATIVE)"""
  40. return self._temporalType
  41. def SetTemporalType(self, ttype):
  42. self._temporalType = ttype
  43. temporalType = property(fget = GetTemporalType, fset = SetTemporalType)
  44. def AddTimeSeries(self, timeseries, etype):
  45. """!Add space time dataset
  46. and collect basic information about it.
  47. Raises GException (e.g. with invalid topology).
  48. @param timeseries name of timeseries (with or without mapset)
  49. @param etype element type (strds, stvds)
  50. """
  51. self._gatherInformation(timeseries, etype, self.timeseriesList, self.timeseriesInfo)
  52. def EvaluateInputData(self):
  53. """!Checks if all timeseries are compatible (raises GException).
  54. Sets internal variables.
  55. """
  56. timeseriesCount = len(self.timeseriesList)
  57. if timeseriesCount == 1:
  58. self.dataMode = DataMode.SIMPLE
  59. elif timeseriesCount > 1:
  60. self.dataMode = DataMode.MULTIPLE
  61. else:
  62. self.dataMode = None
  63. ret, message = self._setTemporalState()
  64. if not ret:
  65. raise GException(message)
  66. if message: # warning
  67. return message
  68. return None
  69. def _setTemporalState(self):
  70. # check for absolute x relative
  71. absolute, relative = 0, 0
  72. for infoDict in self.timeseriesInfo.values():
  73. if infoDict['temporal_type'] == 'absolute':
  74. absolute += 1
  75. else:
  76. relative += 1
  77. if bool(absolute) == bool(relative):
  78. message = _("It is not allowed to display data with different temporal types (absolute and relative).")
  79. return False, message
  80. if absolute:
  81. self.temporalType = TemporalType.ABSOLUTE
  82. else:
  83. self.temporalType = TemporalType.RELATIVE
  84. # check for units for relative type
  85. if relative:
  86. units = set()
  87. for infoDict in self.timeseriesInfo.values():
  88. units.add(infoDict['unit'])
  89. if len(units) > 1:
  90. message = _("It is not allowed to display data with different units (%s).") % ','.join(units)
  91. return False, message
  92. # check for interval x point
  93. interval, point = 0, 0
  94. for infoDict in self.timeseriesInfo.values():
  95. if infoDict['map_time'] == 'interval':
  96. interval += 1
  97. else:
  98. point += 1
  99. if bool(interval) == bool(point):
  100. message = _("You are going to display data with different temporal types of maps (interval and point)."
  101. " It is recommended to use data of one temporal type to avoid confusion.")
  102. return True, message # warning
  103. return True, None
  104. def GetGranularity(self):
  105. """!Returns temporal granularity of currently loaded timeseries."""
  106. if self.dataMode == DataMode.SIMPLE:
  107. gran = self.timeseriesInfo[self.timeseriesList[0]]['granularity']
  108. if 'unit' in self.timeseriesInfo[self.timeseriesList[0]]: # relative
  109. if self.granularityMode == GranularityMode.ONE_UNIT:
  110. gran = 1
  111. gran = "%(gran)s %(unit)s" % {'gran': gran,
  112. 'unit': self.timeseriesInfo[self.timeseriesList[0]]['unit']}
  113. elif self.granularityMode == GranularityMode.ONE_UNIT: # absolute
  114. number, unit = gran.split()
  115. gran = "1 %s" % unit
  116. return gran
  117. if self.dataMode == DataMode.MULTIPLE:
  118. return self._getCommonGranularity()
  119. def _getCommonGranularity(self):
  120. allMaps = []
  121. for dataset in self.timeseriesList:
  122. maps = self.timeseriesInfo[dataset]['maps']
  123. allMaps.extend(maps)
  124. if self.temporalType == TemporalType.ABSOLUTE:
  125. gran = tgis.compute_absolute_time_granularity(allMaps)
  126. if self.granularityMode == GranularityMode.ONE_UNIT:
  127. number, unit = gran.split()
  128. gran = "1 %s" % unit
  129. return gran
  130. if self.temporalType == TemporalType.RELATIVE:
  131. gran = tgis.compute_relative_time_granularity(allMaps)
  132. if self.granularityMode == GranularityMode.ONE_UNIT:
  133. gran = 1
  134. gran = "%(gran)s %(unit)s" % {'gran': gran,
  135. 'unit': self.timeseriesInfo[self.timeseriesList[0]]['unit']}
  136. return gran
  137. def GetLabelsAndMaps(self):
  138. """!Returns time labels and map names.
  139. """
  140. mapLists = []
  141. labelLists = []
  142. for dataset in self.timeseriesList:
  143. grassLabels, listOfMaps = self._getLabelsAndMaps(dataset)
  144. mapLists.append(listOfMaps)
  145. labelLists.append(grassLabels)
  146. # choose longest time interval and fill missing maps with None
  147. timestamps = max(labelLists, key = len)
  148. newMapLists = []
  149. for mapList, labelList in zip(mapLists, labelLists):
  150. newMapList = [None] * len(timestamps)
  151. i = 0
  152. # compare start time
  153. while timestamps[i][0] != labelList[0][0]: # compare
  154. i += 1
  155. newMapList[i:i + len(mapList)] = mapList
  156. newMapLists.append(newMapList)
  157. mapDict = {}
  158. for i, dataset in enumerate(self.timeseriesList):
  159. mapDict[dataset] = newMapLists[i]
  160. return timestamps, mapDict
  161. def _getLabelsAndMaps(self, timeseries):
  162. """!Returns time labels and map names (done by sampling)
  163. for both interval and point data.
  164. """
  165. sp = tgis.dataset_factory(self.timeseriesInfo[timeseries]['etype'], timeseries)
  166. if sp.is_in_db() == False:
  167. raise GException(_("Space time dataset <%s> not found.") % timeseries)
  168. sp.select()
  169. listOfMaps = []
  170. timeLabels = []
  171. gran = self.GetGranularity()
  172. unit = None
  173. if self.temporalType == TemporalType.ABSOLUTE and \
  174. self.granularityMode == GranularityMode.ONE_UNIT:
  175. gran, unit = gran.split()
  176. gran = '%(one)d %(unit)s' % {'one': 1, 'unit': unit}
  177. elif self.temporalType == TemporalType.RELATIVE:
  178. unit = self.timeseriesInfo[timeseries]['unit']
  179. if self.granularityMode == GranularityMode.ONE_UNIT:
  180. gran = 1
  181. # start sampling - now it can be used for both interval and point data
  182. # after instance, there can be a gap or an interval
  183. # if it is a gap we remove it and put there the previous instance instead
  184. # however the first gap must be removed to avoid duplication
  185. maps = sp.get_registered_maps_as_objects_by_granularity(gran = gran)
  186. if maps and len(maps) > 0:
  187. lastTimeseries = None
  188. followsPoint = False # indicates that we are just after finding a point
  189. afterPoint = False # indicates that we are after finding a point
  190. for mymap in maps:
  191. if isinstance(mymap, list):
  192. if len(mymap) > 0:
  193. map = mymap[0]
  194. else:
  195. map = mymap
  196. series = map.get_id()
  197. start, end = map.get_temporal_extent_as_tuple()
  198. if end:
  199. end = str(end)
  200. if end is None:
  201. # point data
  202. listOfMaps.append(series)
  203. afterPoint = True
  204. followsPoint = True
  205. lastTimeseries = series
  206. else:
  207. # interval data
  208. if series:
  209. # map exists, stop point mode
  210. listOfMaps.append(series)
  211. afterPoint = False
  212. else:
  213. # check point mode
  214. if afterPoint:
  215. if followsPoint:
  216. # skip this one, already there
  217. followsPoint = False
  218. continue
  219. else:
  220. # append the last one (of point time)
  221. listOfMaps.append(lastTimeseries)
  222. end = None
  223. else:
  224. # append series which is None
  225. listOfMaps.append(series)
  226. timeLabels.append((str(start), end, unit))
  227. if self.temporalType == TemporalType.ABSOLUTE:
  228. timeLabels = self._pretifyTimeLabels(timeLabels)
  229. return timeLabels, listOfMaps
  230. def _pretifyTimeLabels(self, labels):
  231. """!Convert absolute time labels to grass time and
  232. leave only datum when time is 0.
  233. """
  234. grassLabels = []
  235. isTime = False
  236. for start, end, unit in labels:
  237. start = tgis.string_to_datetime(start)
  238. start = tgis.datetime_to_grass_datetime_string(start)
  239. if end is not None:
  240. end = tgis.string_to_datetime(end)
  241. end = tgis.datetime_to_grass_datetime_string(end)
  242. grassLabels.append((start, end, unit))
  243. if '00:00:00' not in start or (end is not None and '00:00:00' not in end):
  244. isTime = True
  245. if not isTime:
  246. for i, (start, end, unit) in enumerate(grassLabels):
  247. start = start.replace('00:00:00', '').strip()
  248. if end is not None:
  249. end = end.replace('00:00:00', '').strip()
  250. grassLabels[i] = (start, end, unit)
  251. return grassLabels
  252. def _gatherInformation(self, timeseries, etype, timeseriesList, infoDict):
  253. """!Get info about timeseries and check topology (raises GException)"""
  254. id = validateTimeseriesName(timeseries, etype)
  255. sp = tgis.dataset_factory(etype, id)
  256. # Insert content from db
  257. sp.select()
  258. # Get ordered map list
  259. maps = sp.get_registered_maps_as_objects()
  260. if not sp.check_temporal_topology(maps):
  261. raise GException(_("Topology of Space time dataset %s is invalid." % id))
  262. timeseriesList.append(id)
  263. infoDict[id] = {}
  264. infoDict[id]['etype'] = etype
  265. infoDict[id]['temporal_type'] = sp.get_temporal_type()
  266. if sp.is_time_relative():
  267. infoDict[id]['unit'] = sp.get_relative_time_unit()
  268. infoDict[id]['granularity'] = sp.get_granularity()
  269. infoDict[id]['map_time'] = sp.get_map_time()
  270. infoDict[id]['maps'] = maps
  271. def test():
  272. from pprint import pprint
  273. temp = TemporalManager()
  274. timeseries1 = 'precip_abs0'
  275. timeseries2 = 'precip_abs2'
  276. createAbsoluteInterval(timeseries1, timeseries2)
  277. temp.AddTimeSeries(timeseries1, 'strds')
  278. temp.AddTimeSeries(timeseries2, 'strds')
  279. try:
  280. warn = temp.EvaluateInputData()
  281. print warn
  282. except GException, e:
  283. print e
  284. return
  285. print '///////////////////////////'
  286. gran = temp.GetGranularity()
  287. print "granularity: " + str(gran)
  288. pprint (temp.GetLabelsAndMaps())
  289. def createAbsoluteInterval(name1, name2):
  290. grass.run_command('g.region', s=0, n=80, w=0, e=120, b=0, t=50, res=10, res3=10, flags = 'p3', quiet = True)
  291. grass.mapcalc(exp="prec_1 = rand(0, 550)", overwrite = True)
  292. grass.mapcalc(exp="prec_2 = rand(0, 450)", overwrite = True)
  293. grass.mapcalc(exp="prec_3 = rand(0, 320)", overwrite = True)
  294. grass.mapcalc(exp="prec_4 = rand(0, 510)", overwrite = True)
  295. grass.mapcalc(exp="prec_5 = rand(0, 300)", overwrite = True)
  296. grass.mapcalc(exp="prec_6 = rand(0, 650)", overwrite = True)
  297. grass.mapcalc(exp="temp_1 = rand(0, 550)", overwrite = True)
  298. grass.mapcalc(exp="temp_2 = rand(0, 450)", overwrite = True)
  299. grass.mapcalc(exp="temp_3 = rand(0, 320)", overwrite = True)
  300. grass.mapcalc(exp="temp_4 = rand(0, 510)", overwrite = True)
  301. grass.mapcalc(exp="temp_5 = rand(0, 300)", overwrite = True)
  302. grass.mapcalc(exp="temp_6 = rand(0, 650)", overwrite = True)
  303. n1 = grass.read_command("g.tempfile", pid = 1, flags = 'd').strip()
  304. fd = open(n1, 'w')
  305. fd.write(
  306. "prec_1|2001-01-01|2001-02-01\n"
  307. "prec_2|2001-04-01|2001-05-01\n"
  308. "prec_3|2001-05-01|2001-09-01\n"
  309. "prec_4|2001-09-01|2002-01-01\n"
  310. "prec_5|2002-01-01|2002-05-01\n"
  311. "prec_6|2002-05-01|2002-07-01\n"
  312. )
  313. fd.close()
  314. n2 = grass.read_command("g.tempfile", pid = 2, flags = 'd').strip()
  315. fd = open(n2, 'w')
  316. fd.write(
  317. "temp_1|2000-10-01|2001-01-01\n"
  318. "temp_2|2001-04-01|2001-05-01\n"
  319. "temp_3|2001-05-01|2001-09-01\n"
  320. "temp_4|2001-09-01|2002-01-01\n"
  321. "temp_5|2002-01-01|2002-05-01\n"
  322. "temp_6|2002-05-01|2002-07-01\n"
  323. )
  324. fd.close()
  325. grass.run_command('t.unregister', type = 'rast',
  326. maps='prec_1,prec_2,prec_3,prec_4,prec_5,prec_6,temp_1,temp_2,temp_3,temp_4,temp_5,temp_6')
  327. for name, fname in zip((name1, name2), (n1, n2)):
  328. grass.run_command('t.create', overwrite = True, type='strds',
  329. temporaltype='absolute', output=name,
  330. title="A test with input files", descr="A test with input files")
  331. grass.run_command('t.register', flags = 'i', input=name, file=fname, overwrite = True)
  332. def createRelativeInterval(name1, name2):
  333. grass.run_command('g.region', s=0, n=80, w=0, e=120, b=0, t=50, res=10, res3=10, flags = 'p3', quiet = True)
  334. grass.mapcalc(exp="prec_1 = rand(0, 550)", overwrite = True)
  335. grass.mapcalc(exp="prec_2 = rand(0, 450)", overwrite = True)
  336. grass.mapcalc(exp="prec_3 = rand(0, 320)", overwrite = True)
  337. grass.mapcalc(exp="prec_4 = rand(0, 510)", overwrite = True)
  338. grass.mapcalc(exp="prec_5 = rand(0, 300)", overwrite = True)
  339. grass.mapcalc(exp="prec_6 = rand(0, 650)", overwrite = True)
  340. grass.mapcalc(exp="temp_1 = rand(0, 550)", overwrite = True)
  341. grass.mapcalc(exp="temp_2 = rand(0, 450)", overwrite = True)
  342. grass.mapcalc(exp="temp_3 = rand(0, 320)", overwrite = True)
  343. grass.mapcalc(exp="temp_4 = rand(0, 510)", overwrite = True)
  344. grass.mapcalc(exp="temp_5 = rand(0, 300)", overwrite = True)
  345. grass.mapcalc(exp="temp_6 = rand(0, 650)", overwrite = True)
  346. n1 = grass.read_command("g.tempfile", pid = 1, flags = 'd').strip()
  347. fd = open(n1, 'w')
  348. fd.write(
  349. "prec_1|1|4\n"
  350. "prec_2|6|7\n"
  351. "prec_3|7|10\n"
  352. "prec_4|10|11\n"
  353. "prec_5|11|14\n"
  354. "prec_6|14|17\n"
  355. )
  356. fd.close()
  357. n2 = grass.read_command("g.tempfile", pid = 2, flags = 'd').strip()
  358. fd = open(n2, 'w')
  359. fd.write(
  360. "temp_1|1|4\n"
  361. "temp_2|4|7\n"
  362. "temp_3|7|10\n"
  363. "temp_4|10|11\n"
  364. "temp_5|11|14\n"
  365. "temp_6|14|17\n"
  366. )
  367. fd.close()
  368. grass.run_command('t.unregister', type = 'rast',
  369. maps='prec_1,prec_2,prec_3,prec_4,prec_5,prec_6,temp_1,temp_2,temp_3,temp_4,temp_5,temp_6')
  370. for name, fname in zip((name1, name2), (n1, n2)):
  371. grass.run_command('t.create', overwrite = True, type='strds',
  372. temporaltype='relative', output=name,
  373. title="A test with input files", descr="A test with input files")
  374. grass.run_command('t.register', flags = 'i', input = name, file = fname, unit = "years", overwrite = True)
  375. def createAbsolutePoint(name):
  376. grass.run_command('g.region', s=0, n=80, w=0, e=120, b=0, t=50, res=10, res3=10, flags = 'p3', quiet = True)
  377. grass.mapcalc(exp="prec_1 = rand(0, 550)", overwrite = True)
  378. grass.mapcalc(exp="prec_2 = rand(0, 450)", overwrite = True)
  379. grass.mapcalc(exp="prec_3 = rand(0, 320)", overwrite = True)
  380. grass.mapcalc(exp="prec_4 = rand(0, 510)", overwrite = True)
  381. grass.mapcalc(exp="prec_5 = rand(0, 300)", overwrite = True)
  382. grass.mapcalc(exp="prec_6 = rand(0, 650)", overwrite = True)
  383. n1 = grass.read_command("g.tempfile", pid = 1, flags = 'd').strip()
  384. fd = open(n1, 'w')
  385. fd.write(
  386. "prec_1|2001-01-01\n"
  387. "prec_2|2001-03-01\n"
  388. "prec_3|2001-04-01\n"
  389. "prec_4|2001-05-01\n"
  390. "prec_5|2001-08-01\n"
  391. "prec_6|2001-09-01\n"
  392. )
  393. fd.close()
  394. grass.run_command('t.create', overwrite = True, type='strds',
  395. temporaltype='absolute', output=name,
  396. title="A test with input files", descr="A test with input files")
  397. grass.run_command('t.register', flags = 'i', input=name, file=n1, overwrite = True)
  398. if __name__ == '__main__':
  399. test()