temporal_granularity.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. """!@package grass.temporal
  2. @brief GRASS Python scripting module (temporal GIS functions)
  3. Temporal GIS related functions to be used in temporal GIS Python library package.
  4. Usage:
  5. @code
  6. import grass.temporal as tgis
  7. tgis.compute_relative_time_granularity(maps)
  8. ...
  9. @endcode
  10. (C) 2008-2011 by the GRASS Development Team
  11. This program is free software under the GNU General Public
  12. License (>=v2). Read the file COPYING that comes with GRASS
  13. for details.
  14. @author Soeren Gebbert
  15. """
  16. from abstract_dataset import *
  17. from datetime_math import *
  18. ###############################################################################
  19. def check_granularity_string(granularity, temporal_type):
  20. """!Check if the granularity string is valid
  21. @param granularity The granularity string
  22. @param temporal_type The temporal type of the granularity relative or absolute
  23. @return True if valid, False if invalid
  24. @code
  25. >>> check_granularity_string("1 year", "absolute")
  26. True
  27. >>> check_granularity_string("1 month", "absolute")
  28. True
  29. >>> check_granularity_string("1 day", "absolute")
  30. True
  31. >>> check_granularity_string("1 minute", "absolute")
  32. True
  33. >>> check_granularity_string("1 hour", "absolute")
  34. True
  35. >>> check_granularity_string("1 second", "absolute")
  36. True
  37. >>> check_granularity_string("5 months", "absolute")
  38. True
  39. >>> check_granularity_string("5 days", "absolute")
  40. True
  41. >>> check_granularity_string("5 minutes", "absolute")
  42. True
  43. >>> check_granularity_string("5 years", "absolute")
  44. True
  45. >>> check_granularity_string("5 hours", "absolute")
  46. True
  47. >>> check_granularity_string("2 seconds", "absolute")
  48. True
  49. >>> check_granularity_string("1 secondo", "absolute")
  50. False
  51. >>> check_granularity_string("bla second", "absolute")
  52. False
  53. >>> check_granularity_string(1, "relative")
  54. True
  55. >>> check_granularity_string("bla", "relative")
  56. False
  57. @endcode
  58. """
  59. temporal_type
  60. if granularity is None:
  61. return False
  62. if temporal_type == "absolute":
  63. num, unit = granularity.split(" ")
  64. if unit not in ["second", "seconds", "minute", "minutes", "hour",
  65. "hours", "day", "days", "week", "weeks", "month",
  66. "months", "year", "years"]:
  67. return False
  68. try:
  69. integer = int(num)
  70. except:
  71. return False
  72. elif temporal_type == "relative":
  73. try:
  74. integer = int(granularity)
  75. except:
  76. return False
  77. else:
  78. return False
  79. return True
  80. ###############################################################################
  81. def compute_relative_time_granularity(maps):
  82. """!Compute the relative time granularity
  83. Attention: The computation of the granularity
  84. is only correct in case of not overlapping intervals.
  85. Hence a correct temporal topology is required for computation.
  86. @param maps a ordered by start_time list of map objects
  87. @return An integer
  88. @code
  89. >>> import grass.temporal as tgis
  90. >>> tgis.init()
  91. >>> maps = []
  92. >>> for i in range(5):
  93. ... map = tgis.RasterDataset("a%i@P"%i)
  94. ... check = map.set_relative_time(i,i + 1,"seconds")
  95. ... if check:
  96. ... maps.append(map)
  97. >>> tgis.compute_relative_time_granularity(maps)
  98. 1
  99. >>> maps = []
  100. >>> count = 0
  101. >>> timelist = ((0,3), (3,6), (6,9))
  102. >>> for t in timelist:
  103. ... map = tgis.RasterDataset("a%i@P"%count)
  104. ... check = map.set_relative_time(t[0],t[1],"years")
  105. ... if check:
  106. ... maps.append(map)
  107. ... count += 1
  108. >>> tgis.compute_relative_time_granularity(maps)
  109. 3
  110. >>> maps = []
  111. >>> count = 0
  112. >>> timelist = ((0,3), (4,6), (8,11))
  113. >>> for t in timelist:
  114. ... map = tgis.RasterDataset("a%i@P"%count)
  115. ... check = map.set_relative_time(t[0],t[1],"years")
  116. ... if check:
  117. ... maps.append(map)
  118. ... count += 1
  119. >>> tgis.compute_relative_time_granularity(maps)
  120. 1
  121. >>> maps = []
  122. >>> count = 0
  123. >>> timelist = ((0,8), (2,6), (5,9))
  124. >>> for t in timelist:
  125. ... map = tgis.RasterDataset("a%i@P"%count)
  126. ... check = map.set_relative_time(t[0],t[1],"months")
  127. ... if check:
  128. ... maps.append(map)
  129. ... count += 1
  130. >>> tgis.compute_relative_time_granularity(maps)
  131. 4
  132. >>> maps = []
  133. >>> count = 0
  134. >>> timelist = ((0,8), (8,12), (12,18))
  135. >>> for t in timelist:
  136. ... map = tgis.RasterDataset("a%i@P"%count)
  137. ... check = map.set_relative_time(t[0],t[1],"days")
  138. ... if check:
  139. ... maps.append(map)
  140. ... count += 1
  141. >>> tgis.compute_relative_time_granularity(maps)
  142. 2
  143. >>> maps = []
  144. >>> count = 0
  145. >>> timelist = ((0,None), (8,None), (12,None), (24,None))
  146. >>> for t in timelist:
  147. ... map = tgis.RasterDataset("a%i@P"%count)
  148. ... check = map.set_relative_time(t[0],t[1],"minutes")
  149. ... if check:
  150. ... maps.append(map)
  151. ... count += 1
  152. >>> tgis.compute_relative_time_granularity(maps)
  153. 4
  154. >>> maps = []
  155. >>> count = 0
  156. >>> timelist = ((0,None), (8,14), (18,None), (24,None))
  157. >>> for t in timelist:
  158. ... map = tgis.RasterDataset("a%i@P"%count)
  159. ... check = map.set_relative_time(t[0],t[1],"hours")
  160. ... if check:
  161. ... maps.append(map)
  162. ... count += 1
  163. >>> tgis.compute_relative_time_granularity(maps)
  164. 2
  165. @endcode
  166. """
  167. # The interval time must be scaled to days resolution
  168. granularity = None
  169. delta = []
  170. # First we compute the timedelta of the intervals
  171. for map in maps:
  172. start, end = map.get_temporal_extent_as_tuple()
  173. if start and end:
  174. t = abs(end - start)
  175. delta.append(int(t))
  176. # Compute the timedelta of the gaps
  177. for i in range(len(maps)):
  178. if i < len(maps) - 1:
  179. relation = maps[i + 1].temporal_relation(maps[i])
  180. if relation == "after":
  181. start1, end1 = maps[i].get_temporal_extent_as_tuple()
  182. start2, end2 = maps[i + 1].get_temporal_extent_as_tuple()
  183. # Gaps are between intervals, intervals and
  184. # points, points and points
  185. if end1 and start2:
  186. t = abs(end1 - start2)
  187. delta.append(int(t))
  188. if not end1 and start2:
  189. t = abs(start1 - start2)
  190. delta.append(int(t))
  191. delta.sort()
  192. ulist = list(set(delta))
  193. if len(ulist) > 1:
  194. # Find greatest common divisor
  195. granularity = gcd_list(ulist)
  196. elif len(ulist) == 1:
  197. granularity = ulist[0]
  198. else:
  199. granularity = 0
  200. return granularity
  201. ###############################################################################
  202. def compute_absolute_time_granularity(maps):
  203. """!Compute the absolute time granularity
  204. Attention: The computation of the granularity
  205. is only correct in case of not overlapping intervals.
  206. Hence a correct temporal topology is required for computation.
  207. The computed granularity is returned as number of seconds or minutes or hours
  208. or days or months or years.
  209. @param maps a ordered by start_time list of map objects
  210. @return The temporal topology as string "integer unit"
  211. @code
  212. >>> import grass.temporal as tgis
  213. >>> import datetime
  214. >>> dt = datetime.datetime
  215. >>> tgis.init()
  216. >>> maps = []
  217. >>> count = 0
  218. >>> timelist = ((dt(2000,01,01),None), (dt(2000,02,01),None))
  219. >>> for t in timelist:
  220. ... map = tgis.RasterDataset("a%i@P"%count)
  221. ... check = map.set_absolute_time(t[0],t[1])
  222. ... if check:
  223. ... maps.append(map)
  224. ... count += 1
  225. >>> tgis.compute_absolute_time_granularity(maps)
  226. '1 month'
  227. >>> maps = []
  228. >>> count = 0
  229. >>> timelist = ((dt(2000,01,01),None), (dt(2000,01,02),None), (dt(2000,01,03),None))
  230. >>> for t in timelist:
  231. ... map = tgis.RasterDataset("a%i@P"%count)
  232. ... check = map.set_absolute_time(t[0],t[1])
  233. ... if check:
  234. ... maps.append(map)
  235. ... count += 1
  236. >>> tgis.compute_absolute_time_granularity(maps)
  237. '1 day'
  238. >>> maps = []
  239. >>> count = 0
  240. >>> timelist = ((dt(2000,01,01),None), (dt(2000,01,02),None), (dt(2000,05,04,0,5,30),None))
  241. >>> for t in timelist:
  242. ... map = tgis.RasterDataset("a%i@P"%count)
  243. ... check = map.set_absolute_time(t[0],t[1])
  244. ... if check:
  245. ... maps.append(map)
  246. ... count += 1
  247. >>> tgis.compute_absolute_time_granularity(maps)
  248. '30 seconds'
  249. >>> maps = []
  250. >>> count = 0
  251. >>> timelist = ((dt(2000,01,01),dt(2000,05,02)), (dt(2000,05,04,2),None))
  252. >>> for t in timelist:
  253. ... map = tgis.RasterDataset("a%i@P"%count)
  254. ... check = map.set_absolute_time(t[0],t[1])
  255. ... if check:
  256. ... maps.append(map)
  257. ... count += 1
  258. >>> tgis.compute_absolute_time_granularity(maps)
  259. '2 hours'
  260. >>> maps = []
  261. >>> count = 0
  262. >>> timelist = ((dt(2000,01,01),dt(2000,02,01)), (dt(2005,05,04,12),dt(2007,05,20,6)))
  263. >>> for t in timelist:
  264. ... map = tgis.RasterDataset("a%i@P"%count)
  265. ... check = map.set_absolute_time(t[0],t[1])
  266. ... if check:
  267. ... maps.append(map)
  268. ... count += 1
  269. >>> tgis.compute_absolute_time_granularity(maps)
  270. '6 hours'
  271. @endcode
  272. """
  273. has_seconds = False
  274. has_minutes = False
  275. has_hours = False
  276. has_days = False
  277. has_months = False
  278. has_years = False
  279. use_seconds = False
  280. use_minutes = False
  281. use_hours = False
  282. use_days = False
  283. use_months = False
  284. use_years = False
  285. delta = []
  286. datetime_delta = []
  287. # First we compute the timedelta of the intervals
  288. for map in maps:
  289. start, end = map.get_temporal_extent_as_tuple()
  290. if start and end:
  291. delta.append(end - start)
  292. datetime_delta.append(compute_datetime_delta(start, end))
  293. # Compute the timedelta of the gaps
  294. for i in range(len(maps)):
  295. if i < len(maps) - 1:
  296. relation = maps[i + 1].temporal_relation(maps[i])
  297. if relation == "after":
  298. start1, end1 = maps[i].get_temporal_extent_as_tuple()
  299. start2, end2 = maps[i + 1].get_temporal_extent_as_tuple()
  300. # Gaps are between intervals, intervals and
  301. # points, points and points
  302. if end1 and start2:
  303. delta.append(end1 - start2)
  304. datetime_delta.append(compute_datetime_delta(end1, start2))
  305. if not end1 and start2:
  306. delta.append(start2 - start1)
  307. datetime_delta.append(compute_datetime_delta(
  308. start1, start2))
  309. # Check what changed
  310. dlist = []
  311. for d in datetime_delta:
  312. if "second" in d and d["second"] > 0:
  313. has_seconds = True
  314. #print "has second"
  315. if "minute" in d and d["minute"] > 0:
  316. has_minutes = True
  317. #print "has minute"
  318. if "hour" in d and d["hour"] > 0:
  319. has_hours = True
  320. #print "has hour"
  321. if "day" in d and d["day"] > 0:
  322. has_days = True
  323. #print "has day"
  324. if "month" in d and d["month"] > 0:
  325. has_months = True
  326. #print "has month"
  327. if "year" in d and d["year"] > 0:
  328. has_years = True
  329. #print "has year"
  330. # Create a list with a single time unit only
  331. if has_seconds:
  332. for d in datetime_delta:
  333. if "second" in d and d["second"] > 0:
  334. dlist.append(d["second"])
  335. elif "minute" in d and d["minute"] > 0:
  336. dlist.append(d["minute"] * 60)
  337. elif "hour" in d and d["hour"] > 0:
  338. dlist.append(d["hour"] * 3600)
  339. elif "day" in d and d["day"] > 0:
  340. dlist.append(d["day"] * 24 * 3600)
  341. else:
  342. dlist.append(d["max_days"] * 24 * 3600)
  343. use_seconds = True
  344. elif has_minutes:
  345. for d in datetime_delta:
  346. if "minute" in d and d["minute"] > 0:
  347. dlist.append(d["minute"])
  348. elif "hour" in d and d["hour"] > 0:
  349. dlist.append(d["hour"] * 60)
  350. elif "day" in d:
  351. dlist.append(d["day"] * 24 * 60)
  352. else:
  353. dlist.append(d["max_days"] * 24 * 60)
  354. use_minutes = True
  355. elif has_hours:
  356. for d in datetime_delta:
  357. if "hour" in d and d["hour"] > 0:
  358. dlist.append(d["hour"])
  359. elif "day" in d and d["day"] > 0:
  360. dlist.append(d["day"] * 24)
  361. else:
  362. dlist.append(d["max_days"] * 24)
  363. use_hours = True
  364. elif has_days:
  365. for d in datetime_delta:
  366. if "day" in d and d["day"] > 0:
  367. dlist.append(d["day"])
  368. else:
  369. dlist.append(d["max_days"])
  370. use_days = True
  371. elif has_months:
  372. for d in datetime_delta:
  373. if "month" in d and d["month"] > 0:
  374. dlist.append(d["month"])
  375. elif "year" in d and d["year"] > 0:
  376. dlist.append(d["year"] * 12)
  377. use_months = True
  378. elif has_years:
  379. for d in datetime_delta:
  380. if "year" in d:
  381. dlist.append(d["year"])
  382. use_years = True
  383. dlist.sort()
  384. ulist = list(set(dlist))
  385. if len(ulist) == 0:
  386. return None
  387. if len(ulist) > 1:
  388. # Find greatest common divisor
  389. granularity = gcd_list(ulist)
  390. else:
  391. granularity = ulist[0]
  392. if use_seconds:
  393. if granularity == 1:
  394. return "%i second" % granularity
  395. else:
  396. return "%i seconds" % granularity
  397. elif use_minutes:
  398. if granularity == 1:
  399. return "%i minute" % granularity
  400. else:
  401. return "%i minutes" % granularity
  402. elif use_hours:
  403. if granularity == 1:
  404. return "%i hour" % granularity
  405. else:
  406. return "%i hours" % granularity
  407. elif use_days:
  408. if granularity == 1:
  409. return "%i day" % granularity
  410. else:
  411. return "%i days" % granularity
  412. elif use_months:
  413. if granularity == 1:
  414. return "%i month" % granularity
  415. else:
  416. return "%i months" % granularity
  417. elif use_years:
  418. if granularity == 1:
  419. return "%i year" % granularity
  420. else:
  421. return "%i years" % granularity
  422. return None
  423. ###############################################################################
  424. # http://akiscode.com/articles/gcd_of_a_list.shtml
  425. # Copyright (c) 2010 Stephen Akiki
  426. # MIT License (Means you can do whatever you want with this)
  427. # See http://www.opensource.org/licenses/mit-license.php
  428. # Error Codes:
  429. # None
  430. def gcd(a, b):
  431. """!The Euclidean Algorithm """
  432. a = abs(a)
  433. b = abs(b)
  434. while a:
  435. a, b = b % a, a
  436. return b
  437. ###############################################################################
  438. def gcd_list(list):
  439. """!Finds the GCD of numbers in a list.
  440. Input: List of numbers you want to find the GCD of
  441. E.g. [8, 24, 12]
  442. Returns: GCD of all numbers
  443. """
  444. return reduce(gcd, list)
  445. ###############################################################################
  446. if __name__ == "__main__":
  447. import doctest
  448. doctest.testmod()