temporal_manager.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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 animation.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.ORIGINAL
  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 "
  79. "temporal types (absolute and relative).")
  80. return False, message
  81. if absolute:
  82. self.temporalType = TemporalType.ABSOLUTE
  83. else:
  84. self.temporalType = TemporalType.RELATIVE
  85. # check for units for relative type
  86. if relative:
  87. units = set()
  88. for infoDict in self.timeseriesInfo.values():
  89. units.add(infoDict['unit'])
  90. if len(units) > 1:
  91. message = _("It is not allowed to display data with different units (%s).") % ','.join(units)
  92. return False, message
  93. # check for interval x point
  94. interval, point = 0, 0
  95. for infoDict in self.timeseriesInfo.values():
  96. if infoDict['map_time'] == 'interval':
  97. interval += 1
  98. else:
  99. point += 1
  100. if bool(interval) == bool(point):
  101. message = _("You are going to display data with different "
  102. "temporal types of maps (interval and point)."
  103. " It is recommended to use data of one temporal type to avoid confusion.")
  104. return True, message # warning
  105. return True, None
  106. def GetGranularity(self):
  107. """!Returns temporal granularity of currently loaded timeseries."""
  108. if self.dataMode == DataMode.SIMPLE:
  109. gran = self.timeseriesInfo[self.timeseriesList[0]]['granularity']
  110. if 'unit' in self.timeseriesInfo[self.timeseriesList[0]]: # relative:
  111. granNum = gran
  112. unit = self.timeseriesInfo[self.timeseriesList[0]]['unit']
  113. if self.granularityMode == GranularityMode.ONE_UNIT:
  114. granNum = 1
  115. else: # absolute
  116. granNum, unit = gran.split()
  117. if self.granularityMode == GranularityMode.ONE_UNIT:
  118. granNum = 1
  119. return (int(granNum), unit)
  120. if self.dataMode == DataMode.MULTIPLE:
  121. return self._getCommonGranularity()
  122. def _getCommonGranularity(self):
  123. allMaps = []
  124. for dataset in self.timeseriesList:
  125. maps = self.timeseriesInfo[dataset]['maps']
  126. allMaps.extend(maps)
  127. if self.temporalType == TemporalType.ABSOLUTE:
  128. gran = tgis.compute_absolute_time_granularity(allMaps)
  129. granNum, unit = gran.split()
  130. if self.granularityMode == GranularityMode.ONE_UNIT:
  131. granNum = 1
  132. return int(granNum), unit
  133. if self.temporalType == TemporalType.RELATIVE:
  134. unit = self.timeseriesInfo[self.timeseriesList[0]]['unit']
  135. granNum = tgis.compute_relative_time_granularity(allMaps)
  136. if self.granularityMode == GranularityMode.ONE_UNIT:
  137. granNum = 1
  138. return (granNum, unit)
  139. def GetLabelsAndMaps(self):
  140. """!Returns time labels and map names.
  141. """
  142. mapLists = []
  143. labelLists = []
  144. labelListSet = set()
  145. for dataset in self.timeseriesList:
  146. grassLabels, listOfMaps = self._getLabelsAndMaps(dataset)
  147. mapLists.append(listOfMaps)
  148. labelLists.append(tuple(grassLabels))
  149. labelListSet.update(grassLabels)
  150. # combine all timeLabels and fill missing maps with None
  151. # BUT this does not work properly if the datasets have
  152. # no temporal overlap! We would need to sample all datasets
  153. # by a temporary dataset, I don't know how it would work with point data
  154. if self.temporalType == TemporalType.ABSOLUTE:
  155. # ('1996-01-01 00:00:00', '1997-01-01 00:00:00', 'year'),
  156. timestamps = sorted(list(labelListSet), key=lambda x: x[0])
  157. else:
  158. # ('15', '16', u'years'),
  159. timestamps = sorted(list(labelListSet), key=lambda x: float(x[0]))
  160. newMapLists = []
  161. for mapList, labelList in zip(mapLists, labelLists):
  162. newMapList = [None] * len(timestamps)
  163. i = 0
  164. # compare start time
  165. while timestamps[i][0] != labelList[0][0]: # compare
  166. i += 1
  167. newMapList[i:i + len(mapList)] = mapList
  168. newMapLists.append(newMapList)
  169. mapDict = {}
  170. for i, dataset in enumerate(self.timeseriesList):
  171. mapDict[dataset] = newMapLists[i]
  172. return timestamps, mapDict
  173. def _getLabelsAndMaps(self, timeseries):
  174. """!Returns time labels and map names (done by sampling)
  175. for both interval and point data.
  176. """
  177. sp = tgis.dataset_factory(self.timeseriesInfo[timeseries]['etype'], timeseries)
  178. if sp.is_in_db() is False:
  179. raise GException(_("Space time dataset <%s> not found.") % timeseries)
  180. sp.select()
  181. listOfMaps = []
  182. timeLabels = []
  183. granNum, unit = self.GetGranularity()
  184. if self.temporalType == TemporalType.ABSOLUTE:
  185. if self.granularityMode == GranularityMode.ONE_UNIT:
  186. gran = '%(one)d %(unit)s' % {'one': 1, 'unit': unit}
  187. else:
  188. gran = '%(num)d %(unit)s' % {'num': granNum, 'unit': unit}
  189. elif self.temporalType == TemporalType.RELATIVE:
  190. unit = self.timeseriesInfo[timeseries]['unit']
  191. if self.granularityMode == GranularityMode.ONE_UNIT:
  192. gran = 1
  193. else:
  194. gran = granNum
  195. # start sampling - now it can be used for both interval and point data
  196. # after instance, there can be a gap or an interval
  197. # if it is a gap we remove it and put there the previous instance instead
  198. # however the first gap must be removed to avoid duplication
  199. maps = sp.get_registered_maps_as_objects_by_granularity(gran=gran)
  200. if maps and len(maps) > 0:
  201. lastTimeseries = None
  202. followsPoint = False # indicates that we are just after finding a point
  203. afterPoint = False # indicates that we are after finding a point
  204. for mymap in maps:
  205. if isinstance(mymap, list):
  206. if len(mymap) > 0:
  207. map = mymap[0]
  208. else:
  209. map = mymap
  210. series = map.get_id()
  211. start, end = map.get_temporal_extent_as_tuple()
  212. if self.timeseriesInfo[timeseries]['map_time'] == 'point':
  213. # point data
  214. listOfMaps.append(series)
  215. afterPoint = True
  216. followsPoint = True
  217. lastTimeseries = series
  218. end = None
  219. else:
  220. end = str(end)
  221. # interval data
  222. if series:
  223. # map exists, stop point mode
  224. listOfMaps.append(series)
  225. afterPoint = False
  226. else:
  227. # check point mode
  228. if afterPoint:
  229. if followsPoint:
  230. # skip this one, already there
  231. followsPoint = False
  232. continue
  233. else:
  234. # append the last one (of point time)
  235. listOfMaps.append(lastTimeseries)
  236. end = None
  237. else:
  238. # append series which is None
  239. listOfMaps.append(series)
  240. timeLabels.append((str(start), end, unit))
  241. return timeLabels, listOfMaps
  242. def _pretifyTimeLabels(self, labels):
  243. """!Convert absolute time labels to grass time and
  244. leave only datum when time is 0.
  245. """
  246. grassLabels = []
  247. isTime = False
  248. for start, end, unit in labels:
  249. start = tgis.string_to_datetime(start)
  250. start = tgis.datetime_to_grass_datetime_string(start)
  251. if end is not None:
  252. end = tgis.string_to_datetime(end)
  253. end = tgis.datetime_to_grass_datetime_string(end)
  254. grassLabels.append((start, end, unit))
  255. if '00:00:00' not in start or (end is not None and '00:00:00' not in end):
  256. isTime = True
  257. if not isTime:
  258. for i, (start, end, unit) in enumerate(grassLabels):
  259. start = start.replace('00:00:00', '').strip()
  260. if end is not None:
  261. end = end.replace('00:00:00', '').strip()
  262. grassLabels[i] = (start, end, unit)
  263. return grassLabels
  264. def _gatherInformation(self, timeseries, etype, timeseriesList, infoDict):
  265. """!Get info about timeseries and check topology (raises GException)"""
  266. id = validateTimeseriesName(timeseries, etype)
  267. sp = tgis.dataset_factory(etype, id)
  268. # Insert content from db
  269. sp.select()
  270. # Get ordered map list
  271. maps = sp.get_registered_maps_as_objects()
  272. if not sp.check_temporal_topology(maps):
  273. raise GException(_("Topology of Space time dataset %s is invalid." % id))
  274. timeseriesList.append(id)
  275. infoDict[id] = {}
  276. infoDict[id]['etype'] = etype
  277. infoDict[id]['temporal_type'] = sp.get_temporal_type()
  278. if sp.is_time_relative():
  279. infoDict[id]['unit'] = sp.get_relative_time_unit()
  280. infoDict[id]['granularity'] = sp.get_granularity()
  281. infoDict[id]['map_time'] = sp.get_map_time()
  282. infoDict[id]['maps'] = maps
  283. def test():
  284. from pprint import pprint
  285. temp = TemporalManager()
  286. # timeseries = createAbsolutePoint()
  287. # timeseries = createRelativePoint()
  288. # timeseries1, timeseries2 = createAbsoluteInterval()
  289. timeseries1, timeseries2 = createRelativeInterval()
  290. temp.AddTimeSeries(timeseries1, 'strds')
  291. temp.AddTimeSeries(timeseries2, 'strds')
  292. try:
  293. warn = temp.EvaluateInputData()
  294. print warn
  295. except GException, e:
  296. print e
  297. return
  298. print '///////////////////////////'
  299. gran = temp.GetGranularity()
  300. print "granularity: " + str(gran)
  301. pprint (temp.GetLabelsAndMaps())
  302. def createAbsoluteInterval():
  303. grass.run_command('g.region', s=0, n=80, w=0, e=120, b=0, t=50, res=10, res3=10,
  304. flags='p3', quiet=True)
  305. grass.mapcalc(exp="prec_1 = rand(0, 550)", overwrite=True)
  306. grass.mapcalc(exp="prec_2 = rand(0, 450)", overwrite=True)
  307. grass.mapcalc(exp="prec_3 = rand(0, 320)", overwrite=True)
  308. grass.mapcalc(exp="prec_4 = rand(0, 510)", overwrite=True)
  309. grass.mapcalc(exp="prec_5 = rand(0, 300)", overwrite=True)
  310. grass.mapcalc(exp="prec_6 = rand(0, 650)", overwrite=True)
  311. grass.mapcalc(exp="temp_1 = rand(0, 550)", overwrite=True)
  312. grass.mapcalc(exp="temp_2 = rand(0, 450)", overwrite=True)
  313. grass.mapcalc(exp="temp_3 = rand(0, 320)", overwrite=True)
  314. grass.mapcalc(exp="temp_4 = rand(0, 510)", overwrite=True)
  315. grass.mapcalc(exp="temp_5 = rand(0, 300)", overwrite=True)
  316. grass.mapcalc(exp="temp_6 = rand(0, 650)", overwrite=True)
  317. n1 = grass.read_command("g.tempfile", pid=1, flags='d').strip()
  318. fd = open(n1, 'w')
  319. fd.write(
  320. "prec_1|2001-01-01|2001-02-01\n"
  321. "prec_2|2001-04-01|2001-05-01\n"
  322. "prec_3|2001-05-01|2001-09-01\n"
  323. "prec_4|2001-09-01|2002-01-01\n"
  324. "prec_5|2002-01-01|2002-05-01\n"
  325. "prec_6|2002-05-01|2002-07-01\n"
  326. )
  327. fd.close()
  328. n2 = grass.read_command("g.tempfile", pid=2, flags='d').strip()
  329. fd = open(n2, 'w')
  330. fd.write(
  331. "temp_1|2000-10-01|2001-01-01\n"
  332. "temp_2|2001-04-01|2001-05-01\n"
  333. "temp_3|2001-05-01|2001-09-01\n"
  334. "temp_4|2001-09-01|2002-01-01\n"
  335. "temp_5|2002-01-01|2002-05-01\n"
  336. "temp_6|2002-05-01|2002-07-01\n"
  337. )
  338. fd.close()
  339. name1 = 'absinterval1'
  340. name2 = 'absinterval2'
  341. grass.run_command('t.unregister', type='rast',
  342. maps='prec_1,prec_2,prec_3,prec_4,prec_5,prec_6,'
  343. 'temp_1,temp_2,temp_3,temp_4,temp_5,temp_6')
  344. for name, fname in zip((name1, name2), (n1, n2)):
  345. grass.run_command('t.create', overwrite=True, type='strds',
  346. temporaltype='absolute', output=name,
  347. title="A test with input files", descr="A test with input files")
  348. grass.run_command('t.register', flags='i', input=name, file=fname, overwrite=True)
  349. return name1, name2
  350. def createRelativeInterval():
  351. grass.run_command('g.region', s=0, n=80, w=0, e=120, b=0, t=50, res=10, res3=10,
  352. flags='p3', quiet=True)
  353. grass.mapcalc(exp="prec_1 = rand(0, 550)", overwrite=True)
  354. grass.mapcalc(exp="prec_2 = rand(0, 450)", overwrite=True)
  355. grass.mapcalc(exp="prec_3 = rand(0, 320)", overwrite=True)
  356. grass.mapcalc(exp="prec_4 = rand(0, 510)", overwrite=True)
  357. grass.mapcalc(exp="prec_5 = rand(0, 300)", overwrite=True)
  358. grass.mapcalc(exp="prec_6 = rand(0, 650)", overwrite=True)
  359. grass.mapcalc(exp="temp_1 = rand(0, 550)", overwrite=True)
  360. grass.mapcalc(exp="temp_2 = rand(0, 450)", overwrite=True)
  361. grass.mapcalc(exp="temp_3 = rand(0, 320)", overwrite=True)
  362. grass.mapcalc(exp="temp_4 = rand(0, 510)", overwrite=True)
  363. grass.mapcalc(exp="temp_5 = rand(0, 300)", overwrite=True)
  364. grass.mapcalc(exp="temp_6 = rand(0, 650)", overwrite=True)
  365. n1 = grass.read_command("g.tempfile", pid=1, flags='d').strip()
  366. fd = open(n1, 'w')
  367. fd.write(
  368. "prec_1|1|4\n"
  369. "prec_2|6|7\n"
  370. "prec_3|7|10\n"
  371. "prec_4|10|11\n"
  372. "prec_5|11|14\n"
  373. "prec_6|14|17\n"
  374. )
  375. fd.close()
  376. n2 = grass.read_command("g.tempfile", pid=2, flags='d').strip()
  377. fd = open(n2, 'w')
  378. fd.write(
  379. "temp_1|5|6\n"
  380. "temp_2|6|7\n"
  381. "temp_3|7|10\n"
  382. "temp_4|10|11\n"
  383. "temp_5|11|18\n"
  384. "temp_6|19|22\n"
  385. )
  386. fd.close()
  387. name1 = 'relinterval1'
  388. name2 = 'relinterval2'
  389. grass.run_command('t.unregister', type='rast',
  390. maps='prec_1,prec_2,prec_3,prec_4,prec_5,prec_6,'
  391. 'temp_1,temp_2,temp_3,temp_4,temp_5,temp_6')
  392. for name, fname in zip((name1, name2), (n1, n2)):
  393. grass.run_command('t.create', overwrite=True, type='strds',
  394. temporaltype='relative', output=name,
  395. title="A test with input files", descr="A test with input files")
  396. grass.run_command('t.register', flags='i', input=name, file=fname, unit="years", overwrite=True)
  397. return name1, name2
  398. def createAbsolutePoint():
  399. grass.run_command('g.region', s=0, n=80, w=0, e=120, b=0, t=50, res=10, res3=10,
  400. flags='p3', quiet=True)
  401. grass.mapcalc(exp="prec_1 = rand(0, 550)", overwrite=True)
  402. grass.mapcalc(exp="prec_2 = rand(0, 450)", overwrite=True)
  403. grass.mapcalc(exp="prec_3 = rand(0, 320)", overwrite=True)
  404. grass.mapcalc(exp="prec_4 = rand(0, 510)", overwrite=True)
  405. grass.mapcalc(exp="prec_5 = rand(0, 300)", overwrite=True)
  406. grass.mapcalc(exp="prec_6 = rand(0, 650)", overwrite=True)
  407. n1 = grass.read_command("g.tempfile", pid=1, flags='d').strip()
  408. fd = open(n1, 'w')
  409. fd.write(
  410. "prec_1|2001-01-01\n"
  411. "prec_2|2001-03-01\n"
  412. "prec_3|2001-04-01\n"
  413. "prec_4|2001-05-01\n"
  414. "prec_5|2001-08-01\n"
  415. "prec_6|2001-09-01\n"
  416. )
  417. fd.close()
  418. name = 'abspoint'
  419. grass.run_command('t.create', overwrite=True, type='strds',
  420. temporaltype='absolute', output=name,
  421. title="A test with input files", descr="A test with input files")
  422. grass.run_command('t.register', flags='i', input=name, file=n1, overwrite=True)
  423. return name
  424. def createRelativePoint():
  425. grass.run_command('g.region', s=0, n=80, w=0, e=120, b=0, t=50, res=10, res3=10,
  426. flags='p3', quiet=True)
  427. grass.mapcalc(exp="prec_1 = rand(0, 550)", overwrite=True)
  428. grass.mapcalc(exp="prec_2 = rand(0, 450)", overwrite=True)
  429. grass.mapcalc(exp="prec_3 = rand(0, 320)", overwrite=True)
  430. grass.mapcalc(exp="prec_4 = rand(0, 510)", overwrite=True)
  431. grass.mapcalc(exp="prec_5 = rand(0, 300)", overwrite=True)
  432. grass.mapcalc(exp="prec_6 = rand(0, 650)", overwrite=True)
  433. n1 = grass.read_command("g.tempfile", pid=1, flags='d').strip()
  434. fd = open(n1, 'w')
  435. fd.write(
  436. "prec_1|1\n"
  437. "prec_2|3\n"
  438. "prec_3|5\n"
  439. "prec_4|7\n"
  440. "prec_5|11\n"
  441. "prec_6|13\n"
  442. )
  443. fd.close()
  444. name = 'relpoint'
  445. grass.run_command('t.create', overwrite=True, type='strds',
  446. temporaltype='relative', output=name,
  447. title="A test with input files", descr="A test with input files")
  448. grass.run_command('t.register', unit="day", input=name, file=n1, overwrite=True)
  449. return name
  450. if __name__ == '__main__':
  451. test()