temporal_granularity.py 16 KB

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