temporal_manager.py 20 KB

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