temporal_algebra.py 108 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602
  1. """@package grass.temporal
  2. Temporal algebra parser class
  3. (C) 2014 by the GRASS Development Team
  4. This program is free software under the GNU General Public
  5. License (>=v2). Read the file COPYING that comes with GRASS
  6. for details.
  7. :authors: Thomas Leppelt and Soeren Gebbert
  8. .. code-block:: python
  9. >>> import grass.temporal as tgis
  10. >>> tgis.init(True)
  11. >>> p = tgis.TemporalAlgebraLexer()
  12. >>> p.build()
  13. >>> p.debug = True
  14. >>> expression = "C = A : B"
  15. >>> p.test(expression)
  16. C = A : B
  17. LexToken(NAME,'C',1,0)
  18. LexToken(EQUALS,'=',1,2)
  19. LexToken(NAME,'A',1,4)
  20. LexToken(T_SELECT,':',1,6)
  21. LexToken(NAME,'B',1,8)
  22. >>> expression = "C = test1 !: test2"
  23. >>> p.test(expression)
  24. C = test1 !: test2
  25. LexToken(NAME,'C',1,0)
  26. LexToken(EQUALS,'=',1,2)
  27. LexToken(NAME,'test1',1,4)
  28. LexToken(T_NOT_SELECT,'!:',1,10)
  29. LexToken(NAME,'test2',1,13)
  30. >>> expression = "C = test1 {:,equal} test2"
  31. >>> p.test(expression)
  32. C = test1 {:,equal} test2
  33. LexToken(NAME,'C',1,0)
  34. LexToken(EQUALS,'=',1,2)
  35. LexToken(NAME,'test1',1,4)
  36. LexToken(T_SELECT_OPERATOR,'{:,equal}',1,10)
  37. LexToken(NAME,'test2',1,20)
  38. >>> expression = "C = test1 {!:,equal} test2"
  39. >>> p.test(expression)
  40. C = test1 {!:,equal} test2
  41. LexToken(NAME,'C',1,0)
  42. LexToken(EQUALS,'=',1,2)
  43. LexToken(NAME,'test1',1,4)
  44. LexToken(T_SELECT_OPERATOR,'{!:,equal}',1,10)
  45. LexToken(NAME,'test2',1,21)
  46. >>> expression = "C = test1 # test2"
  47. >>> p.test(expression)
  48. C = test1 # test2
  49. LexToken(NAME,'C',1,0)
  50. LexToken(EQUALS,'=',1,2)
  51. LexToken(NAME,'test1',1,4)
  52. LexToken(HASH,'#',1,10)
  53. LexToken(NAME,'test2',1,12)
  54. >>> expression = "C = test1 {#} test2"
  55. >>> p.test(expression)
  56. C = test1 {#} test2
  57. LexToken(NAME,'C',1,0)
  58. LexToken(EQUALS,'=',1,2)
  59. LexToken(NAME,'test1',1,4)
  60. LexToken(T_HASH_OPERATOR,'{#}',1,10)
  61. LexToken(NAME,'test2',1,14)
  62. >>> expression = "C = test1 {#,equal} test2"
  63. >>> p.test(expression)
  64. C = test1 {#,equal} test2
  65. LexToken(NAME,'C',1,0)
  66. LexToken(EQUALS,'=',1,2)
  67. LexToken(NAME,'test1',1,4)
  68. LexToken(T_HASH_OPERATOR,'{#,equal}',1,10)
  69. LexToken(NAME,'test2',1,20)
  70. >>> expression = "C = test1 {#,equal|during} test2"
  71. >>> p.test(expression)
  72. C = test1 {#,equal|during} test2
  73. LexToken(NAME,'C',1,0)
  74. LexToken(EQUALS,'=',1,2)
  75. LexToken(NAME,'test1',1,4)
  76. LexToken(T_HASH_OPERATOR,'{#,equal|during}',1,10)
  77. LexToken(NAME,'test2',1,27)
  78. >>> expression = "E = test1 : test2 !: test1"
  79. >>> p.test(expression)
  80. E = test1 : test2 !: test1
  81. LexToken(NAME,'E',1,0)
  82. LexToken(EQUALS,'=',1,2)
  83. LexToken(NAME,'test1',1,4)
  84. LexToken(T_SELECT,':',1,10)
  85. LexToken(NAME,'test2',1,12)
  86. LexToken(T_NOT_SELECT,'!:',1,18)
  87. LexToken(NAME,'test1',1,21)
  88. >>> expression = 'D = buff_t(test1,"10 months")'
  89. >>> p.test(expression)
  90. D = buff_t(test1,"10 months")
  91. LexToken(NAME,'D',1,0)
  92. LexToken(EQUALS,'=',1,2)
  93. LexToken(BUFF_T,'buff_t',1,4)
  94. LexToken(LPAREN,'(',1,10)
  95. LexToken(NAME,'test1',1,11)
  96. LexToken(COMMA,',',1,16)
  97. LexToken(QUOTE,'"',1,17)
  98. LexToken(INT,10,1,18)
  99. LexToken(NAME,'months',1,21)
  100. LexToken(QUOTE,'"',1,27)
  101. LexToken(RPAREN,')',1,28)
  102. >>> expression = 'H = tsnap(test1)'
  103. >>> p.test(expression)
  104. H = tsnap(test1)
  105. LexToken(NAME,'H',1,0)
  106. LexToken(EQUALS,'=',1,2)
  107. LexToken(TSNAP,'tsnap',1,4)
  108. LexToken(LPAREN,'(',1,9)
  109. LexToken(NAME,'test1',1,10)
  110. LexToken(RPAREN,')',1,15)
  111. >>> expression = 'H = tsnap(test2 {:,during} buff_t(test1, "1 days"))'
  112. >>> p.test(expression)
  113. H = tsnap(test2 {:,during} buff_t(test1, "1 days"))
  114. LexToken(NAME,'H',1,0)
  115. LexToken(EQUALS,'=',1,2)
  116. LexToken(TSNAP,'tsnap',1,4)
  117. LexToken(LPAREN,'(',1,9)
  118. LexToken(NAME,'test2',1,10)
  119. LexToken(T_SELECT_OPERATOR,'{:,during}',1,16)
  120. LexToken(BUFF_T,'buff_t',1,27)
  121. LexToken(LPAREN,'(',1,33)
  122. LexToken(NAME,'test1',1,34)
  123. LexToken(COMMA,',',1,39)
  124. LexToken(QUOTE,'"',1,41)
  125. LexToken(INT,1,1,42)
  126. LexToken(NAME,'days',1,44)
  127. LexToken(QUOTE,'"',1,48)
  128. LexToken(RPAREN,')',1,49)
  129. LexToken(RPAREN,')',1,50)
  130. >>> expression = 'H = tshift(test2 {:,during} buff_t(test1, "1 days"), "1 months")'
  131. >>> p.test(expression)
  132. H = tshift(test2 {:,during} buff_t(test1, "1 days"), "1 months")
  133. LexToken(NAME,'H',1,0)
  134. LexToken(EQUALS,'=',1,2)
  135. LexToken(TSHIFT,'tshift',1,4)
  136. LexToken(LPAREN,'(',1,10)
  137. LexToken(NAME,'test2',1,11)
  138. LexToken(T_SELECT_OPERATOR,'{:,during}',1,17)
  139. LexToken(BUFF_T,'buff_t',1,28)
  140. LexToken(LPAREN,'(',1,34)
  141. LexToken(NAME,'test1',1,35)
  142. LexToken(COMMA,',',1,40)
  143. LexToken(QUOTE,'"',1,42)
  144. LexToken(INT,1,1,43)
  145. LexToken(NAME,'days',1,45)
  146. LexToken(QUOTE,'"',1,49)
  147. LexToken(RPAREN,')',1,50)
  148. LexToken(COMMA,',',1,51)
  149. LexToken(QUOTE,'"',1,53)
  150. LexToken(INT,1,1,54)
  151. LexToken(NAME,'months',1,56)
  152. LexToken(QUOTE,'"',1,62)
  153. LexToken(RPAREN,')',1,63)
  154. >>> expression = 'H = tshift(A , 10)'
  155. >>> p.test(expression)
  156. H = tshift(A , 10)
  157. LexToken(NAME,'H',1,0)
  158. LexToken(EQUALS,'=',1,2)
  159. LexToken(TSHIFT,'tshift',1,4)
  160. LexToken(LPAREN,'(',1,10)
  161. LexToken(NAME,'A',1,11)
  162. LexToken(COMMA,',',1,13)
  163. LexToken(INT,10,1,15)
  164. LexToken(RPAREN,')',1,17)
  165. >>> expression = 'H = if(td(A) > 10, A)'
  166. >>> p.test(expression)
  167. H = if(td(A) > 10, A)
  168. LexToken(NAME,'H',1,0)
  169. LexToken(EQUALS,'=',1,2)
  170. LexToken(IF,'if',1,4)
  171. LexToken(LPAREN,'(',1,6)
  172. LexToken(TD,'td',1,7)
  173. LexToken(LPAREN,'(',1,9)
  174. LexToken(NAME,'A',1,10)
  175. LexToken(RPAREN,')',1,11)
  176. LexToken(GREATER,'>',1,13)
  177. LexToken(INT,10,1,15)
  178. LexToken(COMMA,',',1,17)
  179. LexToken(NAME,'A',1,19)
  180. LexToken(RPAREN,')',1,20)
  181. >>> expression = 'H = if(td(A) > 10, A, B)'
  182. >>> p.test(expression)
  183. H = if(td(A) > 10, A, B)
  184. LexToken(NAME,'H',1,0)
  185. LexToken(EQUALS,'=',1,2)
  186. LexToken(IF,'if',1,4)
  187. LexToken(LPAREN,'(',1,6)
  188. LexToken(TD,'td',1,7)
  189. LexToken(LPAREN,'(',1,9)
  190. LexToken(NAME,'A',1,10)
  191. LexToken(RPAREN,')',1,11)
  192. LexToken(GREATER,'>',1,13)
  193. LexToken(INT,10,1,15)
  194. LexToken(COMMA,',',1,17)
  195. LexToken(NAME,'A',1,19)
  196. LexToken(COMMA,',',1,20)
  197. LexToken(NAME,'B',1,22)
  198. LexToken(RPAREN,')',1,23)
  199. >>> expression = 'I = if(equals,td(A) > 10 {||,equals} td(B) < 10, A)'
  200. >>> p.test(expression)
  201. I = if(equals,td(A) > 10 {||,equals} td(B) < 10, A)
  202. LexToken(NAME,'I',1,0)
  203. LexToken(EQUALS,'=',1,2)
  204. LexToken(IF,'if',1,4)
  205. LexToken(LPAREN,'(',1,6)
  206. LexToken(NAME,'equals',1,7)
  207. LexToken(COMMA,',',1,13)
  208. LexToken(TD,'td',1,14)
  209. LexToken(LPAREN,'(',1,16)
  210. LexToken(NAME,'A',1,17)
  211. LexToken(RPAREN,')',1,18)
  212. LexToken(GREATER,'>',1,20)
  213. LexToken(INT,10,1,22)
  214. LexToken(T_COMP_OPERATOR,'{||,equals}',1,25)
  215. LexToken(TD,'td',1,37)
  216. LexToken(LPAREN,'(',1,39)
  217. LexToken(NAME,'B',1,40)
  218. LexToken(RPAREN,')',1,41)
  219. LexToken(LOWER,'<',1,43)
  220. LexToken(INT,10,1,45)
  221. LexToken(COMMA,',',1,47)
  222. LexToken(NAME,'A',1,49)
  223. LexToken(RPAREN,')',1,50)
  224. >>> expression = 'I = if(equals,td(A) > 10 || start_day() < 10, A)'
  225. >>> p.test(expression)
  226. I = if(equals,td(A) > 10 || start_day() < 10, A)
  227. LexToken(NAME,'I',1,0)
  228. LexToken(EQUALS,'=',1,2)
  229. LexToken(IF,'if',1,4)
  230. LexToken(LPAREN,'(',1,6)
  231. LexToken(NAME,'equals',1,7)
  232. LexToken(COMMA,',',1,13)
  233. LexToken(TD,'td',1,14)
  234. LexToken(LPAREN,'(',1,16)
  235. LexToken(NAME,'A',1,17)
  236. LexToken(RPAREN,')',1,18)
  237. LexToken(GREATER,'>',1,20)
  238. LexToken(INT,10,1,22)
  239. LexToken(OR,'|',1,25)
  240. LexToken(OR,'|',1,26)
  241. LexToken(START_DAY,'start_day',1,28)
  242. LexToken(LPAREN,'(',1,37)
  243. LexToken(RPAREN,')',1,38)
  244. LexToken(LOWER,'<',1,40)
  245. LexToken(INT,10,1,42)
  246. LexToken(COMMA,',',1,44)
  247. LexToken(NAME,'A',1,46)
  248. LexToken(RPAREN,')',1,47)
  249. >>> expression = 'E = if({equals},td(A) >= 4 {&&,contain} td(B) == 2, C : D)'
  250. >>> p.test(expression)
  251. E = if({equals},td(A) >= 4 {&&,contain} td(B) == 2, C : D)
  252. LexToken(NAME,'E',1,0)
  253. LexToken(EQUALS,'=',1,2)
  254. LexToken(IF,'if',1,4)
  255. LexToken(LPAREN,'(',1,6)
  256. LexToken(T_REL_OPERATOR,'{equals}',1,7)
  257. LexToken(COMMA,',',1,15)
  258. LexToken(TD,'td',1,16)
  259. LexToken(LPAREN,'(',1,18)
  260. LexToken(NAME,'A',1,19)
  261. LexToken(RPAREN,')',1,20)
  262. LexToken(GREATER_EQUALS,'>=',1,22)
  263. LexToken(INT,4,1,25)
  264. LexToken(T_COMP_OPERATOR,'{&&,contain}',1,27)
  265. LexToken(TD,'td',1,40)
  266. LexToken(LPAREN,'(',1,42)
  267. LexToken(NAME,'B',1,43)
  268. LexToken(RPAREN,')',1,44)
  269. LexToken(CEQUALS,'==',1,46)
  270. LexToken(INT,2,1,49)
  271. LexToken(COMMA,',',1,50)
  272. LexToken(NAME,'C',1,52)
  273. LexToken(T_SELECT,':',1,54)
  274. LexToken(NAME,'D',1,56)
  275. LexToken(RPAREN,')',1,57)
  276. >>> expression = 'F = if({equals},A {#,equal}, B, C : D)'
  277. >>> p.test(expression)
  278. F = if({equals},A {#,equal}, B, C : D)
  279. LexToken(NAME,'F',1,0)
  280. LexToken(EQUALS,'=',1,2)
  281. LexToken(IF,'if',1,4)
  282. LexToken(LPAREN,'(',1,6)
  283. LexToken(T_REL_OPERATOR,'{equals}',1,7)
  284. LexToken(COMMA,',',1,15)
  285. LexToken(NAME,'A',1,16)
  286. LexToken(T_HASH_OPERATOR,'{#,equal}',1,18)
  287. LexToken(COMMA,',',1,27)
  288. LexToken(NAME,'B',1,29)
  289. LexToken(COMMA,',',1,30)
  290. LexToken(NAME,'C',1,32)
  291. LexToken(T_SELECT,':',1,34)
  292. LexToken(NAME,'D',1,36)
  293. LexToken(RPAREN,')',1,37)
  294. >>> p = tgis.TemporalAlgebraParser()
  295. >>> p.run = False
  296. >>> p.debug = True
  297. >>> expression = "D = A {!:} B {:,during} C"
  298. >>> print(expression)
  299. D = A {!:} B {:,during} C
  300. >>> p.parse(expression)
  301. A* = A {!:} B
  302. A** = A* {:,during} C
  303. D = A**
  304. >>> expression = "D = A {:} B {!:,during} C"
  305. >>> print(expression)
  306. D = A {:} B {!:,during} C
  307. >>> p.parse(expression)
  308. A* = A {:} B
  309. A** = A* {!:,during} C
  310. D = A**
  311. >>> p.run = False
  312. >>> p.debug = False
  313. >>> expression = "C = test1 : test2"
  314. >>> print(expression)
  315. C = test1 : test2
  316. >>> p.parse(expression, 'stvds')
  317. >>> expression = 'D = buff_t(test1,"10 months")'
  318. >>> print(expression)
  319. D = buff_t(test1,"10 months")
  320. >>> p.parse(expression, 'stvds')
  321. >>> expression = 'E = test2 {:,during} buff_t(test1,"1 days")'
  322. >>> print(expression)
  323. E = test2 {:,during} buff_t(test1,"1 days")
  324. >>> p.parse(expression, 'stvds')
  325. >>> expression = 'F = test2 {:,equal} buff_t(test1,"1 days")'
  326. >>> print(expression)
  327. F = test2 {:,equal} buff_t(test1,"1 days")
  328. >>> p.parse(expression, 'stvds')
  329. >>> p.debug = True
  330. >>> expression = 'H = tsnap(test2 {:,during} buff_t(test1, "1 days"))'
  331. >>> p.parse(expression, 'stvds')
  332. test1* = buff_t( test1 , " 1 days " )
  333. test2* = test2 {:,during} test1*
  334. test2** = tsnap( test2* )
  335. H = test2**
  336. >>> expression = 'H = tshift(test2 {:,during} test1, "1 days")'
  337. >>> p.parse(expression, 'stvds')
  338. test2* = test2 {:,during} test1
  339. test2** = tshift( test2* , " 1 days " )
  340. H = test2**
  341. >>> expression = 'H = tshift(H, 3)'
  342. >>> p.parse(expression, 'stvds')
  343. H* = tshift( H , 3 )
  344. H = H*
  345. >>> expression = 'C = if(td(A) == 2, A)'
  346. >>> p.parse(expression, 'stvds')
  347. td(A)
  348. td(A) == 2
  349. A* = if condition None then A
  350. C = A*
  351. >>> expression = 'C = if(td(A) == 5, A, B)'
  352. >>> p.parse(expression, 'stvds')
  353. td(A)
  354. td(A) == 5
  355. A* = if condition None then A else B
  356. C = A*
  357. >>> expression = 'C = if(td(A) == 5 || start_date(A) > "2010-01-01", A, B)'
  358. >>> p.parse(expression, 'stvds')
  359. td(A)
  360. td(A) == 5
  361. start_date A > "2010-01-01"
  362. None || None
  363. A* = if condition None then A else B
  364. C = A*
  365. """
  366. try:
  367. import ply.lex as lex
  368. import ply.yacc as yacc
  369. except:
  370. pass
  371. import os
  372. import copy
  373. import grass.pygrass.modules as pymod
  374. from space_time_datasets import *
  375. from factory import *
  376. from open_stds import *
  377. from temporal_operator import *
  378. ##############################################################################
  379. class TemporalAlgebraLexer(object):
  380. """Lexical analyzer for the GRASS GIS temporal algebra"""
  381. # Functions that defines an if condition, temporal buffering, snapping and
  382. # selection of maps with temporal extent.
  383. conditional_functions = {
  384. 'if' : 'IF',
  385. 'buff_t': 'BUFF_T',
  386. 'tsnap' : 'TSNAP',
  387. 'tshift' : 'TSHIFT',
  388. 'tmap' : 'TMAP',
  389. }
  390. # Variables with date and time strings
  391. datetime_functions = {
  392. 'start_time' : 'START_TIME', # start time as HH::MM:SS
  393. 'start_date' : 'START_DATE', # start date as yyyy-mm-DD
  394. 'start_datetime' : 'START_DATETIME', # start datetime as yyyy-mm-DD HH:MM:SS
  395. 'end_time' : 'END_TIME', # end time as HH:MM:SS
  396. 'end_date' : 'END_DATE', # end date as yyyy-mm-DD
  397. 'end_datetime' : 'END_DATETIME', # end datetime as yyyy-mm-DD HH:MM:SS
  398. }
  399. # Time functions
  400. time_functions = {
  401. 'td' : 'TD', # The size of the current
  402. # sample time interval in days and
  403. # fraction of days for absolute time,
  404. # and in relative units in case of relative time.
  405. #'start_td' : 'START_TD', # The time difference between the start
  406. # time of the sample space time raster
  407. # dataset and the start time of the
  408. # current sample interval or instance.
  409. # The time is measured in days and
  410. # fraction of days for absolute time,
  411. # and in relative units in case of relative time.
  412. #'end_td' : 'END_TD', # The time difference between the
  413. # start time of the sample
  414. # space time raster dataset and the
  415. # end time of the current sample interval.
  416. # The time is measured in days and
  417. # fraction of days for absolute time,
  418. # and in relative units in case of relative time.
  419. # The end_time() will be represented by null() in case of a time instance.
  420. 'start_doy' : 'START_DOY', # Day of year (doy) from the start time [1 - 366]
  421. 'start_dow' : 'START_DOW', # Day of week (dow) from the start time [1 - 7], the start of the week is Monday == 1
  422. 'start_year' : 'START_YEAR', # The year of the start time [0 - 9999]
  423. 'start_month' : 'START_MONTH', # The month of the start time [1 - 12]
  424. 'start_week' : 'START_WEEK', # Week of year of the start time [1 - 54]
  425. 'start_day' : 'START_DAY', # Day of month from the start time [1 - 31]
  426. 'start_hour' : 'START_HOUR', # The hour of the start time [0 - 23]
  427. 'start_minute': 'START_MINUTE', # The minute of the start time [0 - 59]
  428. 'start_second': 'START_SECOND', # The second of the start time [0 - 59]
  429. 'end_doy' : 'END_DOY', # Day of year (doy) from the end time [1 - 366]
  430. 'end_dow' : 'END_DOW', # Day of week (dow) from the end time [1 - 7], the start of the week is Monday == 1
  431. 'end_year' : 'END_YEAR', # The year of the end time [0 - 9999]
  432. 'end_month' : 'END_MONTH', # The month of the end time [1 - 12]
  433. 'end_week' : 'END_WEEK', # Week of year of the end time [1 - 54]
  434. 'end_day' : 'END_DAY', # Day of month from the start time [1 - 31]
  435. 'end_hour' : 'END_HOUR', # The hour of the end time [0 - 23]
  436. 'end_minute' : 'END_MINUTE', # The minute of the end time [0 - 59]
  437. 'end_second' : 'END_SECOND', # The second of the end time [0 - 59]
  438. }
  439. # This is the list of token names.
  440. tokens = (
  441. 'DATETIME',
  442. 'TIME',
  443. 'DATE',
  444. 'INT',
  445. 'FLOAT',
  446. 'LPAREN',
  447. 'RPAREN',
  448. 'COMMA',
  449. 'CEQUALS',
  450. 'EQUALS',
  451. 'UNEQUALS',
  452. 'LOWER',
  453. 'LOWER_EQUALS',
  454. 'GREATER',
  455. 'GREATER_EQUALS',
  456. 'HASH',
  457. 'OR',
  458. 'AND',
  459. 'T_SELECT_OPERATOR',
  460. 'T_HASH_OPERATOR',
  461. 'T_COMP_OPERATOR',
  462. 'T_REL_OPERATOR',
  463. 'T_SELECT',
  464. 'T_NOT_SELECT',
  465. 'NAME',
  466. 'QUOTE',
  467. )
  468. # Build the token list
  469. tokens = tokens + tuple(datetime_functions.values()) \
  470. + tuple(time_functions.values()) \
  471. + tuple(conditional_functions.values())
  472. # Regular expression rules for simple tokens
  473. t_T_SELECT_OPERATOR = r'\{[!]?[:][,]?[a-zA-Z\| ]*([,])?([lrudi]|left|right|union|disjoint|intersect)?\}'
  474. t_T_HASH_OPERATOR = r'\{[#][,]?[a-zA-Z\| ]*([,])?([lrudi]|left|right|union|disjoint|intersect)?\}'
  475. t_T_COMP_OPERATOR = r'\{(\|\||&&)[,][a-zA-Z\| ]*[,]?[\|&]?([,])?([lrudi]|left|right|union|disjoint|intersect)?\}'
  476. t_T_REL_OPERATOR = r'\{([a-zA-Z\| ])+\}'
  477. t_T_SELECT = r':'
  478. t_T_NOT_SELECT = r'!:'
  479. t_LPAREN = r'\('
  480. t_RPAREN = r'\)'
  481. t_COMMA = r','
  482. t_CEQUALS = r'=='
  483. t_EQUALS = r'='
  484. t_UNEQUALS = r'!='
  485. t_LOWER = r'<'
  486. t_LOWER_EQUALS = r'<='
  487. t_GREATER = r'>'
  488. t_GREATER_EQUALS = r'>='
  489. t_HASH = r'\#'
  490. t_OR = r'[\|]'
  491. t_AND = r'[&]'
  492. t_QUOTE = r'[\"\']'
  493. # These are the things that should be ignored.
  494. t_ignore = ' \t'
  495. # Read time string and convert it into a date object
  496. def t_DATETIME(self, t):
  497. r'"\d\d\d\d-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])[ T](0[0-9]|1(0-9)|2[0-4]):(0[0-9]|[1-5][0-9]|60):(0[0-9]|[1-5][0-9]|60)"'
  498. # t.value = int(t.value)
  499. return t
  500. # Read date string and convert it into a date object
  501. def t_DATE(self, t):
  502. r'"\d\d\d\d-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])"'
  503. # t.value = int(t.value)
  504. return t
  505. # Read time string and convert it into a date object
  506. def t_TIME(self, t):
  507. r'"(0[0-9]|1[0-9]|2[0-4]):(0[0-9]|[1-5][0-9]|60):(0[0-9]|[1-5][0-9]|60)"'
  508. # t.value = int(t.value)
  509. return t
  510. # Read in a float. This rule has to be done before the int rule.
  511. def t_FLOAT(self, t):
  512. r'-?\d+\.\d*(e-?\d+)?'
  513. t.value = float(t.value)
  514. return t
  515. # Read in an int.
  516. def t_INT(self, t):
  517. r'-?\d+'
  518. t.value = int(t.value)
  519. return t
  520. # Read in a list of maps.
  521. def t_LIST(self, t):
  522. r'[\[][.]*[\]]'
  523. t.value = list(t.value)
  524. return t
  525. # Ignore comments.
  526. # def t_comment(self, t):
  527. # r'^[#][^\n]*'
  528. # pass
  529. # Track line numbers.
  530. def t_newline(self, t):
  531. r'\n+'
  532. t.lineno += len(t.value)
  533. def t_NAME(self, t):
  534. r'[a-zA-Z_][a-zA-Z_0-9]*'
  535. self.temporal_symbol(t)
  536. return t
  537. # Parse symbols
  538. def temporal_symbol(self, t):
  539. # Check for reserved words
  540. if t.value in TemporalAlgebraLexer.time_functions.keys():
  541. t.type = TemporalAlgebraLexer.time_functions.get(t.value)
  542. elif t.value in TemporalAlgebraLexer.datetime_functions.keys():
  543. t.type = TemporalAlgebraLexer.datetime_functions.get(t.value)
  544. elif t.value in TemporalAlgebraLexer.conditional_functions.keys():
  545. t.type = TemporalAlgebraLexer.conditional_functions.get(t.value)
  546. else:
  547. t.type = 'NAME'
  548. return t
  549. # Handle errors.
  550. def t_error(self, t):
  551. raise SyntaxError("syntax error on line %d near '%s'" %
  552. (t.lineno, t.value))
  553. # Build the lexer
  554. def build(self,**kwargs):
  555. self.lexer = lex.lex(module=self, optimize=False, debug=False, **kwargs)
  556. # Just for testing
  557. def test(self,data):
  558. self.name_list = {}
  559. print(data)
  560. self.lexer.input(data)
  561. while True:
  562. tok = self.lexer.token()
  563. if not tok: break
  564. print tok
  565. ###############################################################################
  566. class GlobalTemporalVar(object):
  567. """ This class handles global temporal variable conditional expressions,
  568. like start_doy() == 3.
  569. The three parts of the statement are stored separately in
  570. tfunc (START_DOY), compop (==) and value (3).
  571. But also boolean values, time differences and relation operators for comparison in
  572. if-statements can be stored in this class.
  573. """
  574. def __init__(self):
  575. self.tfunc = None
  576. self.compop = None
  577. self.value = None
  578. self.boolean = None
  579. self.relationop = None
  580. self.topology = []
  581. self.td = None
  582. def get_type(self):
  583. if self.tfunc != None and self.compop != None and self.value != None:
  584. return("global")
  585. elif self.boolean != None:
  586. return("boolean")
  587. elif self.relationop != None and self.topology != []:
  588. return("operator")
  589. elif self.td != None:
  590. return("timediff")
  591. def get_type_value(self):
  592. typename = self.get_type()
  593. valuelist = []
  594. if typename == "global":
  595. valuelist = [self.tfunc, self.compop, self.value]
  596. elif typename == "operator":
  597. valuelist.append(self.topology)
  598. valuelist.append(self.relationop)
  599. elif typename == "boolean":
  600. valuelist = self.boolean
  601. elif typename == "timediff":
  602. valuelist.append(self.td)
  603. return(valuelist)
  604. def __str__(self):
  605. return str(self.tfunc) + str(self.compop) + str(self.value)
  606. ###############################################################################
  607. class FatalError(Exception):
  608. def __init__(self, msg):
  609. self.value = msg
  610. def __str__(self):
  611. return self.value
  612. ###############################################################################
  613. class TemporalAlgebraParser(object):
  614. """The temporal algebra class"""
  615. # Get the tokens from the lexer class
  616. tokens = TemporalAlgebraLexer.tokens
  617. # Setting equal precedence level for select and hash operations.
  618. precedence = (
  619. ('left', 'T_SELECT_OPERATOR', 'T_SELECT', 'T_NOT_SELECT'), # 1
  620. ('left', 'AND', 'OR', 'T_COMP_OPERATOR'), #2
  621. )
  622. def __init__(self, pid=None, run = True, debug = False, spatial = False,
  623. null = False, register_null = False, nprocs = 1):
  624. self.run = run
  625. self.debug = debug
  626. self.pid = pid
  627. # Intermediate vector map names
  628. self.names = {}
  629. # Count map names
  630. self.spatial = spatial
  631. self.null = null
  632. self.mapset = get_current_mapset()
  633. self.temporaltype = None
  634. self.msgr = get_tgis_message_interface()
  635. self.dbif = SQLDatabaseInterfaceConnection()
  636. self.dbif.connect()
  637. self.register_null = register_null
  638. self.empty_maps = {}
  639. self.m_mremove = pymod.Module('g.remove')
  640. self.m_copy = pymod.Module('g.copy')
  641. self.nprocs = nprocs
  642. self.use_granularity = False
  643. def __del__(self):
  644. if self.dbif.connected:
  645. self.dbif.close()
  646. def setup_common_granularity(self, expression, stdstype = 'strds', lexer = None):
  647. """Configure the temporal algebra to use the common granularity of all
  648. space time datasets in the expression to generate the map lists.
  649. This function will analyze the expression to detect space time datasets
  650. and computes the common granularity from all granularities.
  651. This granularity is then be used to generate the map lists. Hence, all
  652. maps from all STDS will have equidistant temporal extents. The only meaningful
  653. temporal relation is "equal".
  654. :param expression: The algebra expression to analyze
  655. :param lexer: The temporal algebra lexer (select, raster, voxel, vector) that should be used to
  656. parse the expression, default is TemporalAlgebraLexer
  657. :return: True if successful, False otherwise
  658. """
  659. l = lexer
  660. # Split the expression to ignore the left part
  661. expressions = expression.split("=")[1:]
  662. expression = " ".join(expressions)
  663. # Check if spatio-temporal operators are present in the expression
  664. if "{" in expression or "}" in expression:
  665. self.msgr.error(_("Spatio temporal operators are not supported in granularity algebra mode"))
  666. return False
  667. # detect all STDS
  668. if l is None:
  669. l = TemporalAlgebraLexer()
  670. l.build()
  671. l.lexer.input(expression)
  672. name_list = []
  673. tokens = []
  674. count = 0
  675. while True:
  676. tok = l.lexer.token()
  677. if not tok: break
  678. # Ignore map layer
  679. tokens.append(tok.type)
  680. ignore = False
  681. if count > 1:
  682. if tokens[count - 2] == "MAP" or tokens[count - 2] == "TMAP":
  683. ignore = True
  684. if tok.type == "NAME" and ignore == False:
  685. name_list.append(tok.value)
  686. count += 1
  687. grans = []
  688. ttypes = {}
  689. dbif, connected = init_dbif(self.dbif)
  690. for name in name_list:
  691. stds = open_old_stds(name, stdstype, dbif)
  692. # We need valid temporal topology
  693. if stds.check_temporal_topology() is False:
  694. self.msgr.error(_("All input space time datasets must have a valid temporal topology."))
  695. return False
  696. grans.append(stds.get_granularity())
  697. ttypes[stds.get_temporal_type()] = stds.get_temporal_type()
  698. # Only one temporal type is allowed
  699. if len(ttypes) > 1:
  700. self.msgr.error(_("All input space time datasets must have the same temporal type."))
  701. return False
  702. # Compute the common granularity
  703. if "absolute" in ttypes.keys():
  704. self.granularity = compute_common_absolute_time_granularity(grans)
  705. else:
  706. self.granularity = compute_common_relative_time_granularity(grans)
  707. self.use_granularity = True
  708. return True
  709. def parse(self, expression, stdstype = 'strds', maptype = 'rast', mapclass = RasterDataset,
  710. basename = None, overwrite=False):
  711. self.lexer = TemporalAlgebraLexer()
  712. self.lexer.build()
  713. self.parser = yacc.yacc(module=self, debug=self.debug)
  714. self.overwrite = overwrite
  715. self.count = 0
  716. self.stdstype = stdstype
  717. self.maptype = maptype
  718. self.mapclass = mapclass
  719. self.basename = basename
  720. self.expression = expression
  721. self.parser.parse(expression)
  722. def generate_map_name(self):
  723. """Generate an unique intermediate vector map name
  724. and register it in the objects map list for later removement.
  725. The vector map names are unique between processes. Do not use the
  726. same object for map name generation in multiple threads.
  727. """
  728. self.count += 1
  729. if self.pid != None:
  730. pid = self.pid
  731. else:
  732. pid = os.getpid()
  733. name = "tmp_map_name_%i_%i"%(pid, self.count)
  734. self.names[name] = name
  735. return name
  736. def generate_new_map(self, base_map, bool_op = 'and', copy = True, rename = True):
  737. """Generate a new map using the spatio-temporal extent of the base map
  738. :param base_map: This map is used to create the new map
  739. :param bool_op: The boolean operator specifying the spatial extent
  740. operation (intersection, union, disjoint union)
  741. :param copy: Specifies if the temporal extent of mapB should be
  742. copied to mapA
  743. :param rename: Specifies if the generated map get a random name or get
  744. the id from the base map.
  745. :return: Map object
  746. """
  747. # Generate an intermediate name for the result map list.
  748. name = self.generate_map_name()
  749. # Check for mapset in given stds input.
  750. mapname = name + "@" + self.mapset
  751. # Create new map based on the related map list.
  752. map_new = base_map.get_new_instance(mapname)
  753. # Set initial map extend of new vector map.
  754. self.overlay_map_extent(map_new, base_map, bool_op = bool_op, copy = copy)
  755. if not rename:
  756. name = base_map.get_id()
  757. map_new.set_id(name)
  758. # Make sure to set the uid that is used in several dictionaries
  759. map_new.uid = name
  760. return map_new
  761. def overlay_map_extent(self, mapA, mapB, bool_op = None, temp_op = 'l',
  762. copy = False):
  763. """Compute the spatio-temporal extent of two topological related maps
  764. :param mapA: The first map
  765. :param mapB: The second maps
  766. :param bool_op: The boolean operator specifying the spatial extent
  767. operation (intersection, union, disjoint union)
  768. :param temp_op: The temporal operator specifying the temporal
  769. extent operation (intersection, union, disjoint union, right reference)
  770. Left reference is the default temporal extent behaviour.
  771. :param copy: Specifies if the temporal extent of mapB should be
  772. copied to mapA
  773. :return: 0 if there is no overlay
  774. """
  775. returncode = 1
  776. if copy:
  777. map_extent_temporal = mapB.get_temporal_extent()
  778. map_extent_spatial = mapB.get_spatial_extent()
  779. # Set initial map extend of new vector map.
  780. mapA.set_spatial_extent(map_extent_spatial)
  781. mapA.set_temporal_extent(map_extent_temporal)
  782. if "cmd_list" in dir(mapB):
  783. mapA.cmd_list = mapB.cmd_list
  784. if "condition_value" in dir(mapB):
  785. mapA.condition_value = mapB.condition_value
  786. else:
  787. # Calculate spatial extent for different overlay operations.
  788. if bool_op == 'and':
  789. overlay_ext = mapA.spatial_intersection(mapB)
  790. if overlay_ext != None:
  791. mapA.set_spatial_extent(overlay_ext)
  792. else:
  793. returncode = 0
  794. elif bool_op in ['or', 'xor']:
  795. overlay_ext = mapA.spatial_union(mapB)
  796. if overlay_ext != None:
  797. mapA.set_spatial_extent(overlay_ext)
  798. else:
  799. returncode = 0
  800. elif bool_op == 'disor':
  801. overlay_ext = mapA.spatial_disjoint_union(mapB)
  802. if overlay_ext != None:
  803. mapA.set_spatial_extent(overlay_ext)
  804. else:
  805. returncode = 0
  806. # Calculate temporal extent for different temporal operators.
  807. if temp_op == 'i':
  808. temp_ext = mapA.temporal_intersection(mapB)
  809. if temp_ext != None:
  810. mapA.set_temporal_extent(temp_ext)
  811. else:
  812. returncode = 0
  813. elif temp_op == 'u':
  814. temp_ext = mapA.temporal_union(mapB)
  815. if temp_ext != None:
  816. mapA.set_temporal_extent(temp_ext)
  817. else:
  818. returncode = 0
  819. elif temp_op == 'd':
  820. temp_ext = mapA.temporal_disjoint_union(mapB)
  821. if temp_ext != None:
  822. mapA.set_temporal_extent(temp_ext)
  823. else:
  824. returncode = 0
  825. elif temp_op == 'r':
  826. temp_ext = mapB.get_temporal_extent()
  827. if temp_ext != None:
  828. mapA.set_temporal_extent(temp_ext)
  829. else:
  830. returncode = 0
  831. return(returncode)
  832. def set_temporal_extent_list(self, maplist, topolist = ["EQUAL"], temporal = 'l' ):
  833. """ Change temporal extent of map list based on temporal relations to
  834. other map list and given temporal operator.
  835. :param maplist: List of map objects for which relations has been build
  836. correctely.
  837. :param topolist: List of strings of temporal relations.
  838. :param temporal: The temporal operator specifying the temporal
  839. extent operation (intersection, union, disjoint
  840. union, right reference, left reference).
  841. :return: Map list with specified temporal extent.
  842. """
  843. resultdict = {}
  844. for map_i in maplist:
  845. # Loop over temporal related maps and create overlay modules.
  846. tbrelations = map_i.get_temporal_relations()
  847. # Generate an intermediate map for the result map list.
  848. map_new = self.generate_new_map(base_map=map_i, bool_op = 'and',
  849. copy = True, rename = True)
  850. # Combine temporal and spatial extents of intermediate map with related maps.
  851. for topo in topolist:
  852. if topo in tbrelations.keys():
  853. for map_j in (tbrelations[topo]):
  854. if temporal == 'r':
  855. # Generate an intermediate map for the result map list.
  856. map_new = self.generate_new_map(base_map=map_i, bool_op = 'and',
  857. copy = True, rename = True)
  858. # Create overlayed map extent.
  859. returncode = self.overlay_map_extent(map_new, map_j, 'and', \
  860. temp_op = temporal)
  861. # Stop the loop if no temporal or spatial relationship exist.
  862. if returncode == 0:
  863. break
  864. # Append map to result map list.
  865. elif returncode == 1:
  866. print(map_new.get_id() + " " + str(map_new.get_temporal_extent_as_tuple()))
  867. print(map_new.condition_value)
  868. # print(map_new.cmd_list)
  869. # resultlist.append(map_new)
  870. resultdict[map_new.get_id()] = map_new
  871. # Create r.mapcalc expression string for the operation.
  872. #cmdstring = self.build_command_string(s_expr_a = map_new,
  873. # s_expr_b = map_j,
  874. # operator = function)
  875. # Conditional append of module command.
  876. #map_new.cmd_list = cmdstring
  877. if returncode == 0:
  878. break
  879. # Append map to result map list.
  880. #if returncode == 1:
  881. # resultlist.append(map_new)
  882. # Get sorted map objects as values from result dictionoary.
  883. resultlist = resultdict.values()
  884. resultlist = sorted(resultlist, key = AbstractDatasetComparisonKeyStartTime)
  885. return(resultlist)
  886. ######################### Temporal functions ##############################
  887. def check_stds(self, input, clear = False):
  888. """ Check if input space time dataset exist in database and return its map list.
  889. :param input: Name of space time data set as string or list of maps.
  890. :param clear: Reset the stored conditional values to empty list.
  891. :return: List of maps.
  892. """
  893. if isinstance(input, str):
  894. # Check for mapset in given stds input.
  895. if input.find("@") >= 0:
  896. id_input = input
  897. else:
  898. id_input = input + "@" + self.mapset
  899. # Create empty spacetime dataset.
  900. stds = dataset_factory(self.stdstype, id_input)
  901. # Check for occurence of space time dataset.
  902. if stds.is_in_db(dbif=self.dbif) == False:
  903. raise FatalError(_("Space time %s dataset <%s> not found") %
  904. (stds.get_new_map_instance(None).get_type(), id_input))
  905. else:
  906. # Select temporal dataset entry from database.
  907. stds.select(dbif=self.dbif)
  908. if self.use_granularity:
  909. # We create the maplist out of the map array from none-gap objects
  910. maplist = []
  911. map_array = stds.get_registered_maps_as_objects_by_granularity(gran=self.granularity, dbif=self.dbif)
  912. for entry in map_array:
  913. # Ignore gap objects
  914. if entry[0].get_id() is not None:
  915. maplist.append(entry[0])
  916. else:
  917. maplist = stds.get_registered_maps_as_objects(dbif=self.dbif)
  918. # Create map_value as empty list item.
  919. for map_i in maplist:
  920. if "map_value" not in dir(map_i):
  921. map_i.map_value = []
  922. if "condition_value" not in dir(map_i):
  923. map_i.condition_value = []
  924. # Set and check global temporal type variable and map.
  925. if map_i.is_time_absolute() and self.temporaltype == None:
  926. self.temporaltype = 'absolute'
  927. elif map_i.is_time_relative() and self.temporaltype == None:
  928. self.temporaltype = 'relative'
  929. elif map_i.is_time_absolute() and self.temporaltype == 'relative':
  930. self.msgr.fatal(_("Wrong temporal type of space time dataset <%s> \
  931. <%s> time is required") %
  932. (id_input, self.temporaltype))
  933. elif map_i.is_time_relative() and self.temporaltype == 'absolute':
  934. self.msgr.fatal(_("Wrong temporal type of space time dataset <%s> \
  935. <%s> time is required") %
  936. (id_input, self.temporaltype))
  937. elif isinstance(input, self.mapclass):
  938. # Check if the input is a single map and return it as list with one entry.
  939. maplist = [input]
  940. elif isinstance(input, list):
  941. maplist = input
  942. # Create map_value as empty list item.
  943. for map_i in maplist:
  944. if "map_value" not in dir(map_i):
  945. map_i.map_value = []
  946. elif clear:
  947. map_i.map_value = []
  948. if "condition_value" not in dir(map_i):
  949. map_i.condition_value = []
  950. elif clear:
  951. map_i.condition_value = []
  952. else:
  953. self.msgr.fatal(_("Wrong type of input"))
  954. # We generate a unique map id that will be used
  955. # in the topology analysis, since the maplist can
  956. # contain maps with equal map ids
  957. for map in maplist:
  958. map.uid = self.generate_map_name()
  959. if self.debug:
  960. print map.get_name(), map.uid, map.get_temporal_extent_as_tuple()
  961. return(maplist)
  962. def get_temporal_topo_list(self, maplistA, maplistB = None, topolist = ["EQUAL"],
  963. assign_val = False, count_map = False, compare_bool = False,
  964. compop = None, aggregate = None):
  965. """Build temporal topology for two space time data sets, copy map objects
  966. for given relation into map list.
  967. :param maplistA: List of maps.
  968. :param maplistB: List of maps.
  969. :param topolist: List of strings of temporal relations.
  970. :param assign_val: Boolean for assigning a boolean map value based on
  971. the map_values from the compared map list by
  972. topological relationships.
  973. :param count_map: Boolean if the number of topological related maps
  974. should be returned.
  975. :param compare_bool: Boolean for comparing boolean map values based on
  976. related map list and compariosn operator.
  977. :param compop: Comparison operator, && or ||.
  978. :param aggregate: Aggregation operator for relation map list, & or |.
  979. :return: List of maps from maplistA that fulfil the topological relationships
  980. to maplistB specified in topolist.
  981. .. code-block:: python
  982. # Example with two lists of maps
  983. >>> import grass.temporal as tgis
  984. >>> tgis.init(True)
  985. >>> l = tgis.TemporalAlgebraParser()
  986. >>> # Create two list of maps with equal time stamps
  987. >>> mapsA = []
  988. >>> mapsB = []
  989. >>> for i in range(10):
  990. ... idA = "a%i@B"%(i)
  991. ... mapA = tgis.RasterDataset(idA)
  992. ... mapA.uid = idA
  993. ... idB = "b%i@B"%(i)
  994. ... mapB = tgis.RasterDataset(idB)
  995. ... mapB.uid = idB
  996. ... check = mapA.set_relative_time(i, i + 1, "months")
  997. ... check = mapB.set_relative_time(i, i + 1, "months")
  998. ... mapsA.append(mapA)
  999. ... mapsB.append(mapB)
  1000. >>> resultlist = l.get_temporal_topo_list(mapsA, mapsB, ['EQUAL'])
  1001. >>> for map in resultlist:
  1002. ... if map.get_equal():
  1003. ... relations = map.get_equal()
  1004. ... print "Map %s has equal relation to map %s"%(map.get_name(),
  1005. ... relations[0].get_name())
  1006. Map a0 has equal relation to map b0
  1007. Map a1 has equal relation to map b1
  1008. Map a2 has equal relation to map b2
  1009. Map a3 has equal relation to map b3
  1010. Map a4 has equal relation to map b4
  1011. Map a5 has equal relation to map b5
  1012. Map a6 has equal relation to map b6
  1013. Map a7 has equal relation to map b7
  1014. Map a8 has equal relation to map b8
  1015. Map a9 has equal relation to map b9
  1016. >>> resultlist = l.get_temporal_topo_list(mapsA, mapsB, ['DURING'])
  1017. >>> print(resultlist)
  1018. []
  1019. >>> # Create two list of maps with equal time stamps
  1020. >>> mapsA = []
  1021. >>> mapsB = []
  1022. >>> for i in range(10):
  1023. ... idA = "a%i@B"%(i)
  1024. ... mapA = tgis.RasterDataset(idA)
  1025. ... mapA.uid = idA
  1026. ... idB = "b%i@B"%(i)
  1027. ... mapB = tgis.RasterDataset(idB)
  1028. ... mapB.uid = idB
  1029. ... check = mapA.set_relative_time(i, i + 1, "months")
  1030. ... check = mapB.set_relative_time(i, i + 2, "months")
  1031. ... mapsA.append(mapA)
  1032. ... mapsB.append(mapB)
  1033. >>> resultlist = l.get_temporal_topo_list(mapsA, mapsB, ['starts','during'])
  1034. >>> for map in resultlist:
  1035. ... if map.get_starts():
  1036. ... relations = map.get_starts()
  1037. ... print "Map %s has start relation to map %s"%(map.get_name(),
  1038. ... relations[0].get_name())
  1039. Map a0 has start relation to map b0
  1040. Map a1 has start relation to map b1
  1041. Map a2 has start relation to map b2
  1042. Map a3 has start relation to map b3
  1043. Map a4 has start relation to map b4
  1044. Map a5 has start relation to map b5
  1045. Map a6 has start relation to map b6
  1046. Map a7 has start relation to map b7
  1047. Map a8 has start relation to map b8
  1048. Map a9 has start relation to map b9
  1049. >>> for map in resultlist:
  1050. ... if map.get_during():
  1051. ... relations = map.get_during()
  1052. ... print "Map %s has during relation to map %s"%(map.get_name(),
  1053. ... relations[0].get_name())
  1054. Map a0 has during relation to map b0
  1055. Map a1 has during relation to map b0
  1056. Map a2 has during relation to map b1
  1057. Map a3 has during relation to map b2
  1058. Map a4 has during relation to map b3
  1059. Map a5 has during relation to map b4
  1060. Map a6 has during relation to map b5
  1061. Map a7 has during relation to map b6
  1062. Map a8 has during relation to map b7
  1063. Map a9 has during relation to map b8
  1064. >>> # Create two list of maps with equal time stamps and map_value method.
  1065. >>> mapsA = []
  1066. >>> mapsB = []
  1067. >>> for i in range(10):
  1068. ... idA = "a%i@B"%(i)
  1069. ... mapA = tgis.RasterDataset(idA)
  1070. ... mapA.uid = idA
  1071. ... idB = "b%i@B"%(i)
  1072. ... mapB = tgis.RasterDataset(idB)
  1073. ... mapB.uid = idB
  1074. ... check = mapA.set_relative_time(i, i + 1, "months")
  1075. ... check = mapB.set_relative_time(i, i + 1, "months")
  1076. ... mapB.map_value = True
  1077. ... mapsA.append(mapA)
  1078. ... mapsB.append(mapB)
  1079. >>> # Create two list of maps with equal time stamps
  1080. >>> mapsA = []
  1081. >>> mapsB = []
  1082. >>> for i in range(10):
  1083. ... idA = "a%i@B"%(i)
  1084. ... mapA = tgis.RasterDataset(idA)
  1085. ... mapA.uid = idA
  1086. ... mapA.map_value = True
  1087. ... idB = "b%i@B"%(i)
  1088. ... mapB = tgis.RasterDataset(idB)
  1089. ... mapB.uid = idB
  1090. ... mapB.map_value = False
  1091. ... check = mapA.set_absolute_time(datetime(2000,1,i+1),
  1092. ... datetime(2000,1,i + 2))
  1093. ... check = mapB.set_absolute_time(datetime(2000,1,i+6),
  1094. ... datetime(2000,1,i + 7))
  1095. ... mapsA.append(mapA)
  1096. ... mapsB.append(mapB)
  1097. >>> resultlist = l.get_temporal_topo_list(mapsA, mapsB)
  1098. >>> for map in resultlist:
  1099. ... print(map.get_id())
  1100. a5@B
  1101. a6@B
  1102. a7@B
  1103. a8@B
  1104. a9@B
  1105. >>> resultlist = l.get_temporal_topo_list(mapsA, mapsB, ['during'])
  1106. >>> for map in resultlist:
  1107. ... print(map.get_id())
  1108. """
  1109. topologylist = ["EQUAL", "FOLLOWS", "PRECEDES", "OVERLAPS", "OVERLAPPED", \
  1110. "DURING", "STARTS", "FINISHES", "CONTAINS", "STARTED", \
  1111. "FINISHED"]
  1112. complementdict = {"EQUAL": "EQUAL", "FOLLOWS" : "PRECEDES",
  1113. "PRECEDES" : "FOLLOWS", "OVERLAPS" : "OVERLAPPED",
  1114. "OVERLAPPED" : "OVERLAPS", "DURING" : "CONTAINS",
  1115. "CONTAINS" : "DURING", "STARTS" : "STARTED",
  1116. "STARTED" : "STARTS", "FINISHES" : "FINISHED",
  1117. "FINISHED" : "FINISHES"}
  1118. resultdict = {}
  1119. # Check if given temporal relation are valid.
  1120. for topo in topolist:
  1121. if topo.upper() not in topologylist:
  1122. raise SyntaxError("Unpermitted temporal relation name '" + topo + "'")
  1123. # Create temporal topology for maplistA to maplistB.
  1124. tb = SpatioTemporalTopologyBuilder()
  1125. # Dictionary with different spatial variables used for topology builder.
  1126. spatialdict = {'strds' : '2D', 'stvds' : '2D', 'str3ds' : '3D'}
  1127. # Build spatial temporal topology
  1128. if self.spatial:
  1129. tb.build(maplistA, maplistB, spatial = spatialdict[self.stdstype])
  1130. else:
  1131. tb.build(maplistA, maplistB)
  1132. # Iterate through maps in maplistA and search for relationships given
  1133. # in topolist.
  1134. for map_i in maplistA:
  1135. tbrelations = map_i.get_temporal_relations()
  1136. if assign_val:
  1137. self.assign_bool_value(map_i, tbrelations, topolist)
  1138. elif compare_bool:
  1139. self.compare_bool_value(map_i, tbrelations, compop, aggregate, topolist)
  1140. for topo in topolist:
  1141. if topo.upper() in tbrelations.keys():
  1142. if count_map:
  1143. relationmaplist = tbrelations[topo.upper()]
  1144. gvar = GlobalTemporalVar()
  1145. gvar.td = len(relationmaplist)
  1146. if "map_value" in dir(map_i):
  1147. map_i.map_value.append(gvar)
  1148. else:
  1149. map_i.map_value = gvar
  1150. # Use unique identifier, since map names may be equal
  1151. resultdict[map_i.uid] = map_i
  1152. resultlist = resultdict.values()
  1153. # Sort list of maps chronological.
  1154. resultlist = sorted(resultlist, key = AbstractDatasetComparisonKeyStartTime)
  1155. return(resultlist)
  1156. def assign_bool_value(self, map_i, tbrelations, topolist = ["EQUAL"]):
  1157. """ Function to assign boolean map value based on the map_values from the
  1158. compared map list by topological relationships.
  1159. :param map_i: Map object with temporal extent.
  1160. :param tbrelations: List of temporal relation to map_i.
  1161. :param topolist: List of strings for given temporal relations.
  1162. :return: Map object with conditional value that has been assigned by
  1163. relation maps that fulfil the topological relationships to
  1164. maplistB specified in topolist.
  1165. """
  1166. condition_value_list = []
  1167. for topo in topolist:
  1168. if topo.upper() in tbrelations.keys():
  1169. #relationmaplist = tbrelations[complementdict[topo.upper()]]
  1170. relationmaplist = tbrelations[topo.upper()]
  1171. for relationmap in relationmaplist:
  1172. for boolean in relationmap.condition_value:
  1173. if isinstance(boolean, bool):
  1174. condition_value_list.append(boolean)
  1175. if self.debug:
  1176. print(str(relationmap.get_temporal_extent_as_tuple()) + str(boolean))
  1177. if all(condition_value_list):
  1178. resultbool = True
  1179. else:
  1180. resultbool = False
  1181. map_i.condition_value = [resultbool]
  1182. return(resultbool)
  1183. def compare_bool_value(self, map_i, tbrelations, compop, aggregate, topolist = ["EQUAL"]):
  1184. """ Function to evaluate two map lists with boolean values by boolean
  1185. comparison operator.
  1186. :param map_i: Map object with temporal extent.
  1187. :param tbrelations: List of temporal relation to map_i.
  1188. :param topolist: List of strings for given temporal relations.
  1189. :param compop: Comparison operator, && or ||.
  1190. :param aggregate: Aggregation operator for relation map list, & or |.
  1191. :return: Map object with conditional value that has been evaluated by
  1192. comparison operators.
  1193. """
  1194. # Build conditional list with elements from related maps and given relation operator.
  1195. leftbool = map_i.condition_value[0]
  1196. condition_value_list = [leftbool]
  1197. count = 0
  1198. for topo in topolist:
  1199. if topo.upper() in tbrelations.keys():
  1200. relationmaplist = tbrelations[topo.upper()]
  1201. if count == 0:
  1202. condition_value_list.append(compop[0])
  1203. condition_value_list.append('(')
  1204. for relationmap in relationmaplist:
  1205. for boolean in relationmap.condition_value:
  1206. if isinstance(boolean, bool):
  1207. if count > 0:
  1208. condition_value_list.append(aggregate)
  1209. condition_value_list.append(boolean)
  1210. count = count + 1
  1211. if count > 0:
  1212. condition_value_list.append(')')
  1213. # Convert conditional list to concatenated string and evaluate booleans.
  1214. condition_value_str = ''.join(map(str, condition_value_list))
  1215. if self.debug:
  1216. print(condition_value_str)
  1217. resultbool = eval(condition_value_str)
  1218. if self.debug:
  1219. print(resultbool)
  1220. # Add boolean value to result list.
  1221. map_i.condition_value = [resultbool]
  1222. return(resultbool)
  1223. def eval_toperator(self, operator, optype = 'relation'):
  1224. """This function evaluates a string containing temporal operations.
  1225. :param operator: String of temporal operations, e.g. {!=,equal|during,l}.
  1226. :param optype: String to define operator type.
  1227. :return :List of temporal relations (equal, during), the given function
  1228. (!:) and the interval/instances (l).
  1229. .. code-block:: python
  1230. >>> import grass.temporal as tgis
  1231. >>> tgis.init()
  1232. >>> p = tgis.TemporalOperatorParser()
  1233. >>> operator = "{+, during}"
  1234. >>> p.parse(operator, optype = 'raster')
  1235. >>> print(p.relations, p.temporal, p.function)
  1236. (['during'], 'l', '+')
  1237. """
  1238. p = TemporalOperatorParser()
  1239. p.parse(operator, optype)
  1240. p.relations = [rel.upper() for rel in p.relations]
  1241. return(p.relations, p.temporal, p.function, p.aggregate)
  1242. def perform_temporal_selection(self, maplistA, maplistB, topolist = ["EQUAL"],
  1243. inverse = False, assign_val = False):
  1244. """This function performs temporal selection operation.
  1245. :param maplistA: List of maps representing the left side of a temporal
  1246. expression.
  1247. :param maplistB: List of maps representing the right side of a temporal
  1248. expression.
  1249. :param topolist: List of strings of temporal relations.
  1250. :param inverse: Boolean value that specifies if the selection should be
  1251. inverted.
  1252. :param assign_val: Boolean for assigning a boolean map value based on
  1253. the map_values from the compared map list by
  1254. topological relationships.
  1255. :return: List of selected maps from maplistA.
  1256. .. code-block:: python
  1257. >>> import grass.temporal as tgis
  1258. >>> tgis.init()
  1259. >>> l = tgis.TemporalAlgebraParser()
  1260. >>> # Example with two lists of maps
  1261. >>> # Create two list of maps with equal time stamps
  1262. >>> mapsA = []
  1263. >>> mapsB = []
  1264. >>> for i in range(10):
  1265. ... idA = "a%i@B"%(i)
  1266. ... mapA = tgis.RasterDataset(idA)
  1267. ... mapA.uid = idA
  1268. ... idB = "b%i@B"%(i)
  1269. ... mapB = tgis.RasterDataset(idB)
  1270. ... mapB.uid = idB
  1271. ... check = mapA.set_relative_time(i, i + 1, "months")
  1272. ... check = mapB.set_relative_time(i + 5, i + 6, "months")
  1273. ... mapsA.append(mapA)
  1274. ... mapsB.append(mapB)
  1275. >>> resultlist = l.perform_temporal_selection(mapsA, mapsB, ['EQUAL'],
  1276. ... False)
  1277. >>> for map in resultlist:
  1278. ... if map.get_equal():
  1279. ... relations = map.get_equal()
  1280. ... print "Map %s has equal relation to map %s"%(map.get_name(),
  1281. ... relations[0].get_name())
  1282. Map a5 has equal relation to map b0
  1283. Map a6 has equal relation to map b1
  1284. Map a7 has equal relation to map b2
  1285. Map a8 has equal relation to map b3
  1286. Map a9 has equal relation to map b4
  1287. >>> resultlist = l.perform_temporal_selection(mapsA, mapsB, ['EQUAL'],
  1288. ... True)
  1289. >>> for map in resultlist:
  1290. ... if not map.get_equal():
  1291. ... print "Map %s has no equal relation to mapset mapsB"%(map.get_name())
  1292. Map a0 has no equal relation to mapset mapsB
  1293. Map a1 has no equal relation to mapset mapsB
  1294. Map a2 has no equal relation to mapset mapsB
  1295. Map a3 has no equal relation to mapset mapsB
  1296. Map a4 has no equal relation to mapset mapsB
  1297. """
  1298. if not inverse:
  1299. topolist = self.get_temporal_topo_list(maplistA, maplistB, topolist,
  1300. assign_val = assign_val)
  1301. resultlist = topolist
  1302. else:
  1303. topolist = self.get_temporal_topo_list(maplistA, maplistB, topolist,
  1304. assign_val = assign_val)
  1305. resultlist = []
  1306. for map_i in maplistA:
  1307. if map_i not in topolist:
  1308. resultlist.append(map_i)
  1309. #if assign_val:
  1310. # if "condition_value" in dir(map_i):
  1311. # map_i.condition_value.append(False)
  1312. # Sort list of maps chronological.
  1313. resultlist = sorted(resultlist, key = AbstractDatasetComparisonKeyStartTime)
  1314. return(resultlist)
  1315. def set_granularity(self, maplistA, maplistB, toperator = 'l', topolist = ["EQUAL"]):
  1316. """This function sets the temporal extends of a list of maps based on
  1317. another map list.
  1318. :param maplistB: List of maps.
  1319. :param maplistB: List of maps.
  1320. :param toperator: String containing the temporal operator: l, r, d, i, u.
  1321. :param topolist: List of topological relations.
  1322. :return: List of maps with the new temporal extends.
  1323. .. code-block:: python
  1324. >>> import grass.temporal as tgis
  1325. >>> tgis.init()
  1326. >>> p = tgis.TemporalAlgebraParser()
  1327. >>> # Create two list of maps with equal time stamps
  1328. >>> mapsA = []
  1329. >>> mapsB = []
  1330. >>> for i in range(10):
  1331. ... idA = "a%i@B"%(i)
  1332. ... mapA = tgis.RasterDataset(idA)
  1333. ... mapA.uid = idA
  1334. ... idB = "b%i@B"%(i)
  1335. ... mapB = tgis.RasterDataset(idB)
  1336. ... mapB.uid = idB
  1337. ... check = mapA.set_relative_time(i, i + 1, "months")
  1338. ... check = mapB.set_relative_time(i*2, i*2 + 2, "months")
  1339. ... mapsA.append(mapA)
  1340. ... mapsB.append(mapB)
  1341. >>> resultlist = p.set_granularity(mapsA, mapsB, toperator = "u", topolist = ["during"])
  1342. >>> for map in resultlist:
  1343. ... start,end,unit = map.get_relative_time()
  1344. ... print(map.get_id() + ' - start: ' + str(start) + ' end: ' + str(end))
  1345. a1@B - start: 0 end: 2
  1346. a0@B - start: 0 end: 2
  1347. a3@B - start: 2 end: 4
  1348. a2@B - start: 2 end: 4
  1349. a5@B - start: 4 end: 6
  1350. a4@B - start: 4 end: 6
  1351. a7@B - start: 6 end: 8
  1352. a6@B - start: 6 end: 8
  1353. a9@B - start: 8 end: 10
  1354. a8@B - start: 8 end: 10
  1355. """
  1356. topologylist = ["EQUAL", "FOLLOWS", "PRECEDES", "OVERLAPS", "OVERLAPPED", \
  1357. "DURING", "STARTS", "FINISHES", "CONTAINS", "STARTED", \
  1358. "FINISHED"]
  1359. for topo in topolist:
  1360. if topo.upper() not in topologylist:
  1361. raise SyntaxError("Unpermitted temporal relation name '" + topo + "'")
  1362. # Create temporal topology for maplistA to maplistB.
  1363. tb = SpatioTemporalTopologyBuilder()
  1364. # Dictionary with different spatial variables used for topology builder.
  1365. spatialdict = {'strds' : '2D', 'stvds' : '2D', 'str3ds' : '3D'}
  1366. # Build spatial temporal topology for maplistB to maplistB.
  1367. if self.spatial:
  1368. tb.build(maplistA, maplistB, spatial = spatialdict[self.stdstype])
  1369. else:
  1370. tb.build(maplistA, maplistB)
  1371. resultdict = {}
  1372. # Iterate through maps in maplistA and search for relationships given
  1373. # in topolist.
  1374. for map_i in maplistA:
  1375. tbrelations = map_i.get_temporal_relations()
  1376. map_extent = map_i.get_temporal_extent()
  1377. map_start = map_extent.get_start_time()
  1378. map_end = map_extent.get_end_time()
  1379. unchanged = True
  1380. for topo in topolist:
  1381. if topo.upper() in tbrelations.keys():
  1382. relationmaplist = tbrelations[topo.upper()]
  1383. for relationmap in relationmaplist:
  1384. newextent = None
  1385. if toperator == "i":
  1386. newextent = map_i.temporal_intersection(relationmap)
  1387. elif toperator == "u":
  1388. newextent = map_i.temporal_union(relationmap)
  1389. elif toperator == "d":
  1390. newextent = map_i.temporal_disjoint_union(relationmap)
  1391. elif toperator == "l":
  1392. newextent = map_i.get_temporal_extent()
  1393. elif toperator == "r":
  1394. newextent = relationmap.get_temporal_extent()
  1395. if newextent != None:
  1396. start = newextent.get_start_time()
  1397. end = newextent.get_end_time()
  1398. #print(map_i.get_id() + ' - start: ' + str(start) + ' end: ' + str(end))
  1399. # Track changes in temporal extents of maps.
  1400. if map_start != start or map_end != end :
  1401. unchanged = False
  1402. if map_i.is_time_absolute():
  1403. map_i.set_absolute_time(start, end)
  1404. else:
  1405. relunit = map_i.get_relative_time_unit()
  1406. map_i.set_relative_time(int(start), int(end), relunit)
  1407. resultdict[map_i.get_id()] = map_i
  1408. else:
  1409. if self.debug:
  1410. print('Topologic relation: ' + topo.upper() + ' not found.')
  1411. resultdict[map_i.get_id()] = map_i
  1412. if unchanged == True:
  1413. if self.debug:
  1414. print('Leave temporal extend of result map: ' + map_i.get_map_id() + ' unchanged.')
  1415. resultlist = resultdict.values()
  1416. # Sort list of maps chronological.
  1417. resultlist = sorted(resultlist, key = AbstractDatasetComparisonKeyStartTime)
  1418. # Get relations to maplistB per map in A.
  1419. # Loop over all relations from list
  1420. # temporal extent = map.temporal_intersection(map)
  1421. # if temporal extend is None = delete map.
  1422. return(resultlist)
  1423. def get_temporal_func_dict(self, map):
  1424. """ This function creates a dictionary containing temporal functions for a
  1425. map dataset with time stamp.
  1426. :param map: Map object with time stamps.
  1427. :return: Dictionary with temporal functions for given input map.
  1428. .. code-block:: python
  1429. >>> import grass.temporal as tgis
  1430. >>> import datetime
  1431. >>> tgis.init()
  1432. >>> l = tgis.TemporalAlgebraParser()
  1433. >>> # Example with one list of maps
  1434. >>> # Create one list of maps with equal time stamps
  1435. >>> for i in range(1):
  1436. ... idA = "a%i@B"%(i)
  1437. ... mapA = tgis.RasterDataset(idA)
  1438. ... mapA.uid = idA
  1439. ... check = mapA.set_absolute_time(datetime.datetime(2000,1,1),
  1440. ... datetime.datetime(2000,10,1))
  1441. ... tfuncdict = l.get_temporal_func_dict(mapA)
  1442. >>> print(tfuncdict["START_YEAR"])
  1443. 2000
  1444. >>> print(tfuncdict["START_TIME"])
  1445. 00:00:00
  1446. >>> print(tfuncdict["START_DATE"])
  1447. 2000-01-01
  1448. >>> print(tfuncdict["START_DATETIME"])
  1449. 2000-01-01 00:00:00
  1450. """
  1451. tvardict = {"START_DOY" : None, "START_DOW" : None, "START_YEAR" : None,
  1452. "START_MONTH" : None, "START_WEEK" : None, "START_DAY" : None,
  1453. "START_HOUR" : None, "START_MINUTE" : None, "START_SECOND" : None,
  1454. "END_DOY" : None, "END_DOW" : None, "END_YEAR" : None,
  1455. "END_MONTH" : None, "END_WEEK" : None, "END_DAY" : None,
  1456. "END_HOUR" : None, "END_MINUTE" : None, "END_SECOND" : None,
  1457. "START_DATE" : None, "START_DATETIME" : None, "START_TIME" : None,
  1458. "END_DATE" : None, "END_DATETIME" : None, "END_TIME" : None}
  1459. # Compute temporal function only for maps with absolute time reference.
  1460. if map.is_time_absolute:
  1461. # Get datetime of map.
  1462. start, end = map.get_absolute_time()
  1463. # Compute DOY via time deltas.
  1464. yearstart = datetime(start.year, 1, 1)
  1465. yearend = datetime(end.year, 1, 1)
  1466. deltastart = start - yearstart
  1467. deltaend = end - yearend
  1468. # Evaluate datetime objects and fill in into dict.
  1469. tvardict["START_DOY"] = deltastart.days + 1
  1470. tvardict["START_DOW"] = start.isoweekday()
  1471. tvardict["START_YEAR"] = start.year
  1472. tvardict["START_MONTH"] = start.month
  1473. tvardict["START_WEEK"] = start.isocalendar()[1]
  1474. tvardict["START_DAY"] = start.day
  1475. tvardict["START_HOUR"] = start.hour
  1476. tvardict["START_MINUTE"] = start.minute
  1477. tvardict["START_SECOND"] = start.second
  1478. tvardict["END_DOY"] = deltaend.days + 1
  1479. tvardict["END_DOW"] = end.isoweekday()
  1480. tvardict["END_YEAR"] = end.year
  1481. tvardict["END_MONTH"] = end.month
  1482. tvardict["END_WEEK"] = end.isocalendar()[1]
  1483. tvardict["END_DAY"] = end.day
  1484. tvardict["END_HOUR"] = end.hour
  1485. tvardict["END_MINUTE"] = end.minute
  1486. tvardict["END_SECOND"] = end.second
  1487. tvardict["START_DATE"] = start.date()
  1488. tvardict["START_DATETIME"] = start
  1489. tvardict["START_TIME"] = start.time()
  1490. tvardict["END_DATE"] = end.date()
  1491. tvardict["END_DATETIME"] = end
  1492. tvardict["END_TIME"] = end.time()
  1493. if not map.is_time_absolute:
  1494. tvardict["START_DATE"] = start.date()
  1495. tvardict["START_DATETIME"] = start
  1496. tvardict["START_TIME"] = start.time()
  1497. tvardict["END_DATE"] = end.date()
  1498. tvardict["END_DATETIME"] = end
  1499. tvardict["END_TIME"] = end.time()
  1500. #core.fatal(_("The temporal functions for map <%s> only supported for absolute"\
  1501. # "time." % (str(map.get_id()))))
  1502. return(tvardict)
  1503. def eval_datetime_str(self, tfuncval, comp, value):
  1504. # Evaluate date object comparison expression.
  1505. if comp == "<":
  1506. boolname = eval(str(tfuncval < value))
  1507. elif comp == ">":
  1508. boolname = eval(str(tfuncval > value))
  1509. elif comp == "==":
  1510. boolname = eval(str(tfuncval == value))
  1511. elif comp == "<=":
  1512. boolname = eval(str(tfuncval <= value))
  1513. elif comp == ">=":
  1514. boolname = eval(str(tfuncval >= value))
  1515. elif comp == "!=":
  1516. boolname = eval(str(tfuncval != value))
  1517. return(boolname)
  1518. def eval_global_var(self, gvar, maplist):
  1519. """ This function evaluates a global variable expression for a map list.
  1520. For example: start_day() > 5 , end_month() == 2.
  1521. :param gvar: Object of type GlobalTemporalVar containing temporal.
  1522. :param maplist: List of map objects.
  1523. :return: List of maps from maplist with added conditional boolean values.
  1524. """
  1525. boollist = []
  1526. # Loop over maps of input map list.
  1527. for map_i in maplist:
  1528. # Get dictionary with temporal variables for the map.
  1529. tfuncdict = self.get_temporal_func_dict(map_i)
  1530. # Get value from global variable.
  1531. value = gvar.value
  1532. # Get comparison operator from global variable, like <, >, <=, >=, ==, !=
  1533. comp_op = gvar.compop
  1534. # Get temporal function name for global variable.
  1535. tfunc = gvar.tfunc.upper()
  1536. # Get value for function name from dictionary.
  1537. tfuncval = tfuncdict[tfunc]
  1538. # Check if value has to be transfered to datetime object for comparison.
  1539. if tfunc in ["START_DATE", "END_DATE"]:
  1540. timeobj = datetime.strptime(value.replace("\"",""), '%Y-%m-%d')
  1541. value = timeobj.date()
  1542. boolname = self.eval_datetime_str(tfuncval, comp_op, value)
  1543. elif tfunc in ["START_TIME", "END_TIME"]:
  1544. timeobj = datetime.strptime(value.replace("\"",""), '%H:%M:%S')
  1545. value = timeobj.time()
  1546. boolname = self.eval_datetime_str(tfuncval, comp_op, value)
  1547. elif tfunc in ["START_DATETIME", "END_DATETIME"]:
  1548. timeobj = datetime.strptime(value.replace("\"",""), '%Y-%m-%d %H:%M:%S')
  1549. value = timeobj
  1550. boolname = self.eval_datetime_str(tfuncval, comp_op, value)
  1551. else:
  1552. boolname = eval(str(tfuncval) + comp_op + str(value))
  1553. # Add conditional boolean value to the map.
  1554. if "condition_value" in dir(map_i):
  1555. map_i.condition_value.append(boolname)
  1556. else:
  1557. map_i.condition_value = boolname
  1558. return(maplist)
  1559. def eval_map_list(self, maplist ,thenlist, topolist = ["EQUAL"]):
  1560. """ This function transfers boolean values from temporal expression
  1561. from one map list to another by their topology. These boolean
  1562. values are added to the maps as condition_value.
  1563. :param maplist: List of map objects containing boolean map values.
  1564. :param thenlist: List of map objects where the boolean values
  1565. should be added.
  1566. :return: List of maps from thenlist with added conditional boolean values.
  1567. """
  1568. # Get topology of then statement map list in relation to the other maplist
  1569. # and assign boolean values of the maplist to the thenlist.
  1570. containlist = self.perform_temporal_selection(thenlist, maplist,
  1571. assign_val = True,
  1572. topolist = topolist)
  1573. # Inverse selection of maps from thenlist and assigning False values.
  1574. #excludelist = self.perform_temporal_selection(thenlist, maplist,
  1575. # assign_val = True,
  1576. # inverse = True,
  1577. # topolist = topolist)
  1578. # Combining the selection and inverse selection list.
  1579. resultlist = containlist# + excludelist
  1580. return(resultlist)
  1581. def build_condition_list(self, tvarexpr, thenlist, topolist = ["EQUAL"]):
  1582. """ This function evaluates temporal variable expressions of a conditional
  1583. expression in two steps.
  1584. At first it combines stepwise the single conditions by their relations with LALR.
  1585. In this prossess sub condition map lists will be created which will include
  1586. information of the underlying single conditions. Important: The temporal
  1587. relations between conditions are evaluated by implicit aggregation.
  1588. In the second step the aggregated condition map list will be compared with the
  1589. map list of conclusion statements by the given temporal relation.
  1590. The result is writen as 'condition_value' attribute to the resulting map objects.
  1591. These attribute consists of boolean expressions and operators which can be
  1592. evaluated with the eval_condition_list function.
  1593. [True, '||', False, '&&', True]
  1594. For example: td(A) == 1 && start_day() > 5 --> [True || False]
  1595. (for one map.condition_value in a then map list)
  1596. :param tvarexpr: List of GlobalTemporalVar objects and map lists.
  1597. The list is constructed by the TemporalAlgebraParser
  1598. in order of expression evaluation in the parser.
  1599. :param thenlist: Map list object of the conclusion statement.
  1600. It will be compared and evaluated by the conditions.
  1601. :param topolist: List of temporal relations between the conditions and the
  1602. conclusions.
  1603. :return: Map list with conditional values for all temporal expressions.
  1604. """
  1605. # Evaluate the temporal variable expression and compute the temporal combination
  1606. # of conditions.
  1607. # Check if the input expression is a valid single global variable.
  1608. if isinstance(tvarexpr, GlobalTemporalVar) and tvarexpr.get_type() == "global" :
  1609. # Use method eval_global_var to evaluate expression.
  1610. resultlist = self.eval_global_var(tvarexpr, thenlist)
  1611. # Check if a given list is a list of maps.
  1612. elif all([issubclass(type(ele), AbstractMapDataset) for ele in tvarexpr]):
  1613. # Use method eval_map_list to evaluate map_list in comparison to thenlist.
  1614. resultlist = self.eval_map_list(tvarexpr, thenlist, topolist)
  1615. elif len(tvarexpr) % 2 != 0:
  1616. # Define variables for map list comparisons.
  1617. left_obj = []
  1618. operator = []
  1619. right_obj =[]
  1620. count = 0
  1621. #self.msgr.fatal("Condition list is not complete. Elements missing")
  1622. for iter in range(len(tvarexpr)):
  1623. expr = tvarexpr[iter]
  1624. operator = tvarexpr[iter +1]
  1625. relexpr = tvarexpr[iter +2]
  1626. if all([issubclass(type(ele), list) for ele in [expr, relexpr]]):
  1627. resultlist = self.get_temporal_topo_list(expr, relexpr)
  1628. # Loop through the list, search for map lists or global variables.
  1629. for expr in tvarexpr:
  1630. if isinstance(expr, list):
  1631. if all([issubclass(type(ele), AbstractMapDataset) for ele in expr]):
  1632. # Use method eval_map_list to evaluate map_list
  1633. resultlist = self.eval_map_list(expr, thenlist, topolist)
  1634. else:
  1635. # Recursive function call to look into nested list elements.
  1636. self.build_condition_list(expr, thenlist)
  1637. elif isinstance(expr, GlobalTemporalVar):
  1638. # Use according functions for different global variable types.
  1639. if expr.get_type() == "operator":
  1640. if all(["condition_value" in dir(map_i) for map_i in thenlist]):
  1641. # Add operator string to the condition list.
  1642. [map_i.condition_value.extend(expr.get_type_value()) for map_i in thenlist]
  1643. if expr.get_type() == "global":
  1644. # Use method eval_global_var to evaluate expression.
  1645. resultlist = self.eval_global_var(expr, thenlist)
  1646. # Sort resulting list of maps chronological.
  1647. resultlist = sorted(resultlist, key = AbstractDatasetComparisonKeyStartTime)
  1648. return(resultlist)
  1649. def eval_condition_list(self, maplist, inverse = False):
  1650. """ This function evaluates conditional values of a map list.
  1651. A recursive function is used to evaluate comparison statements
  1652. from left to right in the given conditional list.
  1653. For example:
  1654. - [True, '||', False, '&&', True] -> True
  1655. - [True, '||', False, '&&', False] -> False
  1656. - [True, '&&', False, '&&', True] -> False
  1657. - [False, '||', True, '||', False] -> True
  1658. - [False, '&&', True, '&&', True] -> False
  1659. - [True, '&&', True, '&&', True] -> True
  1660. - [True, '&&', True] -> True
  1661. - [True, '&&', False] -> False
  1662. - [False, '||', True] -> True
  1663. :param tvarexpr: List of GlobalTemporalVar objects and map lists.
  1664. The list is constructed by the TemporalAlgebraParser
  1665. in order of expression evaluation in the parser.
  1666. :return: Map list with conditional values for all temporal expressions.
  1667. """
  1668. def recurse_compare(conditionlist):
  1669. for ele in conditionlist:
  1670. if ele == '||':
  1671. ele_index = conditionlist.index(ele)
  1672. topolist = conditionlist.pop(ele_index -1)
  1673. right = conditionlist.pop(ele_index)
  1674. left = conditionlist.pop(ele_index - 2)
  1675. if any([left, right]):
  1676. result = True
  1677. else:
  1678. result = False
  1679. conditionlist[ele_index - 2] = result
  1680. recurse_compare(conditionlist)
  1681. if ele == '&&':
  1682. ele_index = conditionlist.index(ele)
  1683. topolist = conditionlist.pop(ele_index -1)
  1684. right = conditionlist.pop(ele_index)
  1685. left = conditionlist.pop(ele_index - 2)
  1686. if all([left, right]):
  1687. result = True
  1688. else:
  1689. result = False
  1690. conditionlist[ele_index - 2] = result
  1691. recurse_compare(conditionlist)
  1692. resultlist = conditionlist
  1693. return(resultlist)
  1694. resultlist = []
  1695. inverselist = []
  1696. # Loop through map list and evaluate conditional values.
  1697. for map_i in maplist:
  1698. if "condition_value" in dir(map_i):
  1699. # Get condition values from map object.
  1700. conditionlist = map_i.condition_value
  1701. # Evaluate conditions in list with recursive function.
  1702. resultbool = recurse_compare(conditionlist)
  1703. # Set conditional value of map to resulting boolean.
  1704. map_i.condition_value = resultbool
  1705. # Add all maps that fulfill the conditions to result list.
  1706. if resultbool[0]:
  1707. resultlist.append(map_i)
  1708. if self.debug:
  1709. print(map_i.get_map_id() + ' ' + str(map_i.condition_value))
  1710. else:
  1711. inverselist.append(map_i)
  1712. if inverse:
  1713. return(inverselist)
  1714. else:
  1715. return(resultlist)
  1716. ###########################################################################
  1717. def p_statement_assign(self, t):
  1718. # The expression should always return a list of maps.
  1719. """
  1720. statement : stds EQUALS expr
  1721. """
  1722. if self.run:
  1723. if isinstance(t[3], list):
  1724. num = len(t[3])
  1725. count = 0
  1726. changeflag = False
  1727. register_list = []
  1728. if num > 0:
  1729. for map_i in t[3]:
  1730. # Test if temporal extents have been changed by temporal
  1731. # relation oeprators (&|+).
  1732. map_i_extent = map_i.get_temporal_extent_as_tuple()
  1733. map_test = map_i.get_new_instance(map_i.get_id())
  1734. map_test.select()
  1735. map_test_extent = map_test.get_temporal_extent_as_tuple()
  1736. if map_test_extent != map_i_extent:
  1737. changeflag = True
  1738. for map_i in t[3]:
  1739. if changeflag:
  1740. # Check if resultmap names exist in GRASS database.
  1741. mapname = self.basename + "_" + str(count) + "@" + self.mapset
  1742. process_queue = pymod.ParallelModuleQueue(int(self.nprocs))
  1743. if self.stdstype == 'strds':
  1744. map_test = RasterDataset(mapname)
  1745. elif self.stdstype == 'stvds':
  1746. map_test = VectorDataset(mapname)
  1747. if map_test.map_exists() and self.overwrite == False:
  1748. self.msgr.fatal("Error raster maps with basename %s exist. Use --o flag to overwrite existing file" \
  1749. %(mapname))
  1750. # Create new maps with basename.
  1751. newident = self.basename + "_" + str(count)
  1752. map_result = map_i.get_new_instance(newident + "@" + self.mapset)
  1753. map_result.set_temporal_extent(map_i.get_temporal_extent())
  1754. map_result.set_spatial_extent(map_i.get_spatial_extent())
  1755. register_list.append(map_result)
  1756. if self.stdstype == 'strds':
  1757. m = copy.deepcopy(self.m_copy)
  1758. m.inputs["rast"].value = map_i.get_id(), newident
  1759. m.flags["overwrite"].value = self.overwrite
  1760. process_queue.put(m)
  1761. elif self.stdstype == 'stvds':
  1762. m = copy.deepcopy(self.m_copy)
  1763. m.inputs["vect"].value = map_i.get_id(), newident
  1764. m.flags["overwrite"].value = self.overwrite
  1765. process_queue.put(m)
  1766. else:
  1767. register_list.append(map_i)
  1768. count += 1
  1769. if changeflag:
  1770. process_queue.wait()
  1771. # Open connection to temporal database.
  1772. dbif, connect = init_dbif(self.dbif)
  1773. # Create result space time dataset.
  1774. resultstds = open_new_stds(t[1], self.stdstype, \
  1775. 'absolute', t[1], t[1], \
  1776. 'mean', self.dbif, \
  1777. overwrite = self.overwrite)
  1778. for map_i in register_list:
  1779. # Get meta data from grass database.
  1780. map_i.load()
  1781. # Check if temporal extents have changed.
  1782. if changeflag:
  1783. # Do not register empty maps if not required
  1784. # In case of a null map continue, do not register null maps
  1785. if map_i.metadata.get_min() is None and \
  1786. map_i.metadata.get_max() is None:
  1787. if not self.register_null:
  1788. self.empty_maps[map_i.get_name()] = map_i.get_name()
  1789. continue
  1790. if map_i.is_in_db(dbif) and self.overwrite:
  1791. # Update map in temporal database.
  1792. map_i.update_all(dbif)
  1793. elif map_i.is_in_db(dbif) and self.overwrite == False:
  1794. # Raise error if map exists and no overwrite flag is given.
  1795. self.msgr.fatal("Error vector map %s exist in temporal database. Use overwrite flag. : \n%s" \
  1796. %(map_i.get_map_id(), cmd.popen.stderr))
  1797. else:
  1798. # Insert map into temporal database.
  1799. map_i.insert(dbif)
  1800. # Register map in result space time dataset.
  1801. success = resultstds.register_map(map_i, dbif)
  1802. resultstds.update_from_registered_maps(dbif)
  1803. dbif.close()
  1804. elif num == 0:
  1805. self.msgr.warning('Empty result space time dataset. No map has \
  1806. been registered in %s' %(t[1] ))
  1807. # Open connection to temporal database.
  1808. dbif, connect = init_dbif(self.dbif)
  1809. # Create result space time dataset.
  1810. resultstds = open_new_stds(t[1], self.stdstype, \
  1811. 'absolute', t[1], t[1], \
  1812. 'mean', self.dbif, \
  1813. overwrite = self.overwrite)
  1814. dbif.close()
  1815. t[0] = t[3]
  1816. else:
  1817. t[0] = t[3]
  1818. if self.debug:
  1819. print t[1], "=", t[3]
  1820. def p_stds_1(self, t):
  1821. # Definition of a space time dataset
  1822. """
  1823. stds : NAME
  1824. """
  1825. t[0] = t[1]
  1826. def p_paren_expr(self, t):
  1827. """ expr : LPAREN expr RPAREN"""
  1828. t[0] = t[2]
  1829. def p_number(self,t):
  1830. """number : INT
  1831. | FLOAT
  1832. """
  1833. t[0] = t[1]
  1834. def p_expr_tmap_function(self, t):
  1835. # Add a single map.
  1836. # Only the spatial extent of the map is evaluated.
  1837. # Temporal extent is not existing.
  1838. # Examples:
  1839. # R = tmap(A)
  1840. """
  1841. expr : TMAP LPAREN stds RPAREN
  1842. """
  1843. if self.run:
  1844. # Check input map.
  1845. input = t[3]
  1846. if not isinstance(input, list):
  1847. # Check for mapset in given stds input.
  1848. if input.find("@") >= 0:
  1849. id_input = input
  1850. else:
  1851. id_input = input + "@" + self.mapset
  1852. # Create empty map dataset.
  1853. map_i = dataset_factory(self.maptype, id_input)
  1854. # Check for occurence of space time dataset.
  1855. if map_i.map_exists() == False:
  1856. raise FatalError(_("%s map <%s> not found in GRASS spatial database") %
  1857. (map_i.get_type(), id_input))
  1858. else:
  1859. # Select dataset entry from database.
  1860. map_i.select(dbif=self.dbif)
  1861. else:
  1862. raise FatalError(_("Wrong map type <%s> . TMAP only supports single maps that are registered in the temporal GRASS database") %
  1863. (map_i.get_type()))
  1864. # Return map object.
  1865. t[0] = [map_i]
  1866. else:
  1867. t[0] = "tmap(", t[3] , ")"
  1868. if self.debug:
  1869. print "tmap(", t[3] , ")"
  1870. def p_t_hash(self,t):
  1871. """
  1872. t_hash_var : stds HASH stds
  1873. """
  1874. if self.run:
  1875. maplistA = self.check_stds(t[1])
  1876. maplistB = self.check_stds(t[3])
  1877. resultlist = self.get_temporal_topo_list(maplistA, maplistB,
  1878. count_map = True)
  1879. t[0] = resultlist
  1880. def p_t_hash2(self,t):
  1881. """
  1882. t_hash_var : stds T_HASH_OPERATOR stds
  1883. """
  1884. if self.run:
  1885. maplistA = self.check_stds(t[1])
  1886. maplistB = self.check_stds(t[3])
  1887. topolist = self.eval_toperator(t[2], optype = 'hash')[0]
  1888. resultlist = self.get_temporal_topo_list(maplistA, maplistB, topolist,
  1889. count_map = True)
  1890. t[0] = resultlist
  1891. def p_t_td_var(self, t):
  1892. """
  1893. t_td_var : TD LPAREN stds RPAREN
  1894. | TD LPAREN expr RPAREN
  1895. """
  1896. if self.run:
  1897. maplist = self.check_stds(t[3])
  1898. for map_i in maplist:
  1899. if map_i.is_time_absolute:
  1900. start, end = map_i.get_absolute_time()
  1901. if end != None:
  1902. td = time_delta_to_relative_time(end - start)
  1903. else:
  1904. start, end, unit = current.get_relative_time()
  1905. if end != None:
  1906. td = end - start
  1907. if "map_value" in dir(map_i):
  1908. gvar = GlobalTemporalVar()
  1909. gvar.td = td
  1910. map_i.map_value.append(gvar)
  1911. else:
  1912. map_i.map_value = gvar
  1913. t[0] = maplist
  1914. else:
  1915. t[0] = "td(" + str(t[3]) + ")"
  1916. if self.debug:
  1917. print "td(" + str(t[3]) + ")"
  1918. def p_t_time_var(self, t):
  1919. # Temporal variables that return a double or integer value
  1920. """
  1921. t_var : START_DOY
  1922. | START_DOW
  1923. | START_YEAR
  1924. | START_MONTH
  1925. | START_WEEK
  1926. | START_DAY
  1927. | START_HOUR
  1928. | START_MINUTE
  1929. | START_SECOND
  1930. | END_DOY
  1931. | END_DOW
  1932. | END_YEAR
  1933. | END_MONTH
  1934. | END_WEEK
  1935. | END_DAY
  1936. | END_HOUR
  1937. | END_MINUTE
  1938. | END_SECOND
  1939. """
  1940. t[0] = t[1]
  1941. def p_compare_op(self, t):
  1942. # Compare operators that are supported for temporal expressions
  1943. """
  1944. comp_op : CEQUALS
  1945. | UNEQUALS
  1946. | LOWER
  1947. | LOWER_EQUALS
  1948. | GREATER
  1949. | GREATER_EQUALS
  1950. """
  1951. t[0] = t[1]
  1952. def p_t_var_expr_td_hash(self, t):
  1953. # Examples:
  1954. # A # B == 2
  1955. # td(A) < 31
  1956. """
  1957. t_var_expr : t_td_var comp_op number
  1958. | t_hash_var comp_op number
  1959. """
  1960. if self.run:
  1961. maplist = self.check_stds(t[1])
  1962. comp_op = t[2]
  1963. value = str(t[3])
  1964. for map_i in maplist:
  1965. # Evaluate time diferences and hash operator statements for each map.
  1966. try:
  1967. td = map_i.map_value[0].td
  1968. boolname = eval(str(td) + comp_op + value)
  1969. # Add conditional boolean value to the map.
  1970. if "condition_value" in dir(map_i):
  1971. map_i.condition_value.append(boolname)
  1972. else:
  1973. map_i.condition_value = boolname
  1974. except:
  1975. self.msgr.fatal("Error: the given expression does not contain a correct time difference object.")
  1976. t[0] = maplist
  1977. if self.debug:
  1978. print t[1], t[2], t[3]
  1979. def p_t_var_expr_number(self, t):
  1980. # Examples:
  1981. # start_month(A) > 2
  1982. # start_day(B) < 14
  1983. # start_day(B) < start_month(A)
  1984. """
  1985. t_var_expr : t_var LPAREN stds RPAREN comp_op number
  1986. | t_var LPAREN expr RPAREN comp_op number
  1987. """
  1988. # TODO: Implement comparison operator for map lists.
  1989. #| t_var LPAREN stds RPAREN comp_op t_var LPAREN stds RPAREN
  1990. #| t_var LPAREN stds RPAREN comp_op t_var LPAREN expr RPAREN
  1991. #| t_var LPAREN expr RPAREN comp_op t_var LPAREN expr RPAREN
  1992. #| t_var LPAREN expr RPAREN comp_op t_var LPAREN stds RPAREN
  1993. # TODO: Implement statement in backward direction:
  1994. # number comp_op t_var LPAREN stds RPAREN
  1995. if self.run:
  1996. maplist = self.check_stds(t[3])
  1997. gvar = GlobalTemporalVar()
  1998. gvar.tfunc = t[1]
  1999. gvar.compop = t[5]
  2000. gvar.value = t[6]
  2001. # Evaluate temporal variable for given maplist.
  2002. resultlist = self.eval_global_var(gvar, maplist)
  2003. t[0] = resultlist
  2004. if self.debug:
  2005. print t[1], t[3], t[5], t[6]
  2006. def p_t_var_expr_time(self, t):
  2007. # Examples:
  2008. # start_time(A) == "12:30:00"
  2009. # start_date(B) <= "2001-01-01"
  2010. # start_datetime(C) > "2001-01-01 12:30:00"
  2011. # TODO: Implement statement in backward direction:
  2012. # TIME comp_op START_TIME LPAREN stds RPAREN
  2013. """
  2014. t_var_expr : START_TIME LPAREN stds RPAREN comp_op TIME
  2015. | START_DATE LPAREN stds RPAREN comp_op DATE
  2016. | START_DATETIME LPAREN stds RPAREN comp_op DATETIME
  2017. | END_TIME LPAREN stds RPAREN comp_op TIME
  2018. | END_DATE LPAREN stds RPAREN comp_op DATE
  2019. | END_DATETIME LPAREN stds RPAREN comp_op DATETIME
  2020. | START_TIME LPAREN expr RPAREN comp_op TIME
  2021. | START_DATE LPAREN expr RPAREN comp_op DATE
  2022. | START_DATETIME LPAREN expr RPAREN comp_op DATETIME
  2023. | END_TIME LPAREN expr RPAREN comp_op TIME
  2024. | END_DATE LPAREN expr RPAREN comp_op DATE
  2025. | END_DATETIME LPAREN expr RPAREN comp_op DATETIME
  2026. """
  2027. if self.run:
  2028. # Check input maplist.
  2029. maplist = self.check_stds(t[3])
  2030. # Build global temporal variable.
  2031. gvar = GlobalTemporalVar()
  2032. gvar.tfunc = t[1]
  2033. gvar.compop = t[5]
  2034. gvar.value = t[6]
  2035. # Evaluate temporal variable for given maplist.
  2036. resultlist = self.eval_global_var(gvar, maplist)
  2037. t[0] = resultlist
  2038. if self.debug:
  2039. print t[1], t[3], t[5], t[6]
  2040. def p_t_var_expr_comp(self, t):
  2041. """
  2042. t_var_expr : t_var_expr AND AND t_var_expr
  2043. | t_var_expr OR OR t_var_expr
  2044. """
  2045. if self.run:
  2046. # Check input maplists and operators.
  2047. tvarexprA = t[1]
  2048. tvarexprB = t[4]
  2049. relations = ["EQUAL"]
  2050. temporal = "l"
  2051. function = t[2] + t[3]
  2052. aggregate = t[2]
  2053. # Build conditional values based on topological relationships.
  2054. complist = self.get_temporal_topo_list(tvarexprA, tvarexprB, topolist = relations,
  2055. compare_bool = True, compop = function[0], aggregate = aggregate)
  2056. # Set temporal extent based on topological relationships.
  2057. resultlist = self.set_temporal_extent_list(complist, topolist = relations,
  2058. temporal = temporal)
  2059. t[0] = resultlist
  2060. if self.debug:
  2061. print t[1], t[2] + t[3], t[4]
  2062. def p_t_var_expr_comp_op(self, t):
  2063. """
  2064. t_var_expr : t_var_expr T_COMP_OPERATOR t_var_expr
  2065. """
  2066. if self.run:
  2067. tvarexprA = t[1]
  2068. tvarexprB = t[3]
  2069. # Evaluate temporal comparison operator.
  2070. relations, temporal, function, aggregate = self.eval_toperator(t[2], optype = 'boolean')
  2071. # Build conditional values based on topological relationships.
  2072. complist = self.get_temporal_topo_list(tvarexprA, tvarexprB, topolist = relations,
  2073. compare_bool = True, compop = function[0], aggregate = aggregate)
  2074. # Set temporal extent based on topological relationships.
  2075. resultlist = self.set_temporal_extent_list(complist, topolist = relations,
  2076. temporal = temporal)
  2077. t[0] = resultlist
  2078. if self.debug:
  2079. print t[1], t[2], t[3]
  2080. def p_expr_t_select(self, t):
  2081. # Temporal equal selection
  2082. # The temporal topology relation equals is implicit
  2083. # Examples:
  2084. # A : B # Select the part of A that is temporally equal B
  2085. """
  2086. expr : stds T_SELECT stds
  2087. | expr T_SELECT stds
  2088. | stds T_SELECT expr
  2089. | expr T_SELECT expr
  2090. """
  2091. if self.run:
  2092. # Setup database connection.
  2093. # Check input stds.
  2094. maplistA = self.check_stds(t[1])
  2095. maplistB = self.check_stds(t[3])
  2096. # Perform selection.
  2097. selectlist = self.perform_temporal_selection(maplistA, maplistB)
  2098. # Return map list.
  2099. t[0] = selectlist
  2100. else:
  2101. t[0] = t[1] , "*"
  2102. if self.debug:
  2103. print str(t[1]), "* = ", t[1], t[2], t[3]
  2104. def p_expr_t_not_select(self, t):
  2105. # Temporal equal selection
  2106. # The temporal topology relation equals is implicit
  2107. # Examples:
  2108. # A !: B # Select the part of A that is temporally unequal to B
  2109. """
  2110. expr : stds T_NOT_SELECT stds
  2111. | expr T_NOT_SELECT stds
  2112. | stds T_NOT_SELECT expr
  2113. | expr T_NOT_SELECT expr
  2114. """
  2115. if self.run:
  2116. # Check input stds.
  2117. maplistA = self.check_stds(t[1])
  2118. maplistB = self.check_stds(t[3])
  2119. # Perform negative selection.
  2120. selectlist = self.perform_temporal_selection(maplistA, maplistB,
  2121. inverse = True)
  2122. # Return map list.
  2123. t[0] = selectlist
  2124. else:
  2125. t[0] = t[1] + "*"
  2126. if self.debug:
  2127. print t[1] + "* = ", t[1], t[2], t[3]
  2128. def p_expr_t_select_operator(self, t):
  2129. # Temporal equal selection
  2130. # The temporal topology relation equals is implicit
  2131. # Examples:
  2132. # A {!:} B # Select the part of A that is temporally unequal to B
  2133. # A {:} B # Select the part of A that is temporally equal B
  2134. # A {equals, !:} B # Select the part of A that is temporally unequal to B
  2135. # A {during, !:} B # Select the part of A that is temporally not during B
  2136. # A {overlaps, :} B # Select the part of A that temporally overlaps B
  2137. # A {overlaps|equals, :} B # Select the part of A that temporally overlaps or equals B
  2138. """
  2139. expr : stds T_SELECT_OPERATOR stds
  2140. | expr T_SELECT_OPERATOR stds
  2141. | stds T_SELECT_OPERATOR expr
  2142. | expr T_SELECT_OPERATOR expr
  2143. """
  2144. if self.run:
  2145. # Check input stds.
  2146. maplistA = self.check_stds(t[1])
  2147. maplistB = self.check_stds(t[3])
  2148. # Evaluate temporal operator.
  2149. operators = self.eval_toperator(t[2], optype = 'select')
  2150. # Check for negative selection.
  2151. if operators[2] == "!:":
  2152. negation = True
  2153. else:
  2154. negation = False
  2155. # Perform selection.
  2156. selectlist = self.perform_temporal_selection(maplistA, maplistB,
  2157. topolist = operators[0], inverse = negation)
  2158. selectlist = self.set_granularity(selectlist, maplistB, operators[1],
  2159. operators[0])
  2160. # Return map list.
  2161. t[0] = selectlist
  2162. else:
  2163. t[0] = t[1] + "*"
  2164. if self.debug:
  2165. print t[1] + "* = ", t[1], t[2], t[3]
  2166. def p_expr_condition_if(self, t):
  2167. # Examples
  2168. # if( start_date() < "2005-06-01", A:B)
  2169. """
  2170. expr : IF LPAREN t_var_expr COMMA stds RPAREN
  2171. | IF LPAREN t_var_expr COMMA expr RPAREN
  2172. """
  2173. if self.run:
  2174. # Get stds/map list of then statement.
  2175. thenlist = self.check_stds(t[5])
  2176. # Get temporal conditional statement.
  2177. tvarexpr = t[3]
  2178. thencond = self.build_condition_list(tvarexpr, thenlist)
  2179. thenresult = self.eval_condition_list(thencond)
  2180. # Clear the map and conditional values of the map list.
  2181. resultlist = self.check_stds(thenresult, clear = True)
  2182. # Return resulting map list.
  2183. t[0] = resultlist
  2184. else:
  2185. t[0] = t[5] + "*"
  2186. if self.debug:
  2187. print str(t[5]) + "* = ", "if condition", str(t[3]), ' then ', str(t[5])
  2188. def p_expr_condition_if_relation(self, t):
  2189. # Examples
  2190. # if({equal} start_date() < "2005-06-01", A:B)
  2191. """
  2192. expr : IF LPAREN T_REL_OPERATOR COMMA t_var_expr COMMA stds RPAREN
  2193. | IF LPAREN T_REL_OPERATOR COMMA t_var_expr COMMA expr RPAREN
  2194. """
  2195. if self.run:
  2196. # Get stds/map list of then statement.
  2197. thenlist = self.check_stds(t[7])
  2198. # Get temporal conditional statement.
  2199. tvarexpr = t[5]
  2200. topolist = self.eval_toperator(t[3], optype = 'relation')[0]
  2201. thencond = self.build_condition_list(tvarexpr, thenlist, topolist)
  2202. thenresult = self.eval_condition_list(thencond)
  2203. # Clear the map and conditional values of the map list.
  2204. resultlist = self.check_stds(thenresult, clear = True)
  2205. # Return resulting map list.
  2206. t[0] = resultlist
  2207. else:
  2208. t[0] = t[7] + "*"
  2209. if self.debug:
  2210. print "result* = ", "if ", str(t[3]), "condition", str(t[5]), " then ", str(t[7])
  2211. def p_expr_condition_elif(self, t):
  2212. # Examples
  2213. # if( start_date() < "2005-06-01", if(start_time() < "12:30:00", A:B), A!:B)
  2214. """
  2215. expr : IF LPAREN t_var_expr COMMA stds COMMA stds RPAREN
  2216. | IF LPAREN t_var_expr COMMA stds COMMA expr RPAREN
  2217. | IF LPAREN t_var_expr COMMA expr COMMA stds RPAREN
  2218. | IF LPAREN t_var_expr COMMA expr COMMA expr RPAREN
  2219. """
  2220. if self.run:
  2221. # Get stds/map list of then statement.
  2222. thenlist = self.check_stds(t[5])
  2223. elselist = self.check_stds(t[7])
  2224. # Get temporal conditional statement for then and else expressions.
  2225. tvarexpr = t[3]
  2226. thencond = self.build_condition_list(tvarexpr, thenlist)
  2227. thenresult = self.eval_condition_list(thencond)
  2228. elsecond = self.build_condition_list(tvarexpr, elselist)
  2229. elseresult = self.eval_condition_list(elsecond, inverse = True)
  2230. # Combine and sort else and then statement to result map list.
  2231. combilist = thenresult + elseresult
  2232. resultlist = sorted(combilist, key = AbstractDatasetComparisonKeyStartTime)
  2233. # Clear the map and conditional values of the map list.
  2234. resultlist = self.check_stds(resultlist, clear = True)
  2235. # Return resulting map list.
  2236. t[0] = resultlist
  2237. else:
  2238. t[0] = t[5] + "*"
  2239. if self.debug:
  2240. print str(t[5]) + "* = ", "if condition", str(t[3]), " then ", str(t[5]), ' else ', str(t[7])
  2241. def p_expr_condition_elif_relation(self, t):
  2242. # Examples
  2243. # if({equal}, start_date() < "2005-06-01", if(start_time() < "12:30:00", A:B), A!:B)
  2244. # The then and else statement using the same topological relationships.
  2245. # Feature request: Independent relationships for then and else to conditions.
  2246. """
  2247. expr : IF LPAREN T_REL_OPERATOR COMMA t_var_expr COMMA stds COMMA stds RPAREN
  2248. | IF LPAREN T_REL_OPERATOR COMMA t_var_expr COMMA stds COMMA expr RPAREN
  2249. | IF LPAREN T_REL_OPERATOR COMMA t_var_expr COMMA expr COMMA stds RPAREN
  2250. | IF LPAREN T_REL_OPERATOR COMMA t_var_expr COMMA expr COMMA expr RPAREN
  2251. """
  2252. if self.run:
  2253. # Get stds/map list of then statement.
  2254. thenlist = self.check_stds(t[7])
  2255. elselist = self.check_stds(t[9])
  2256. # Get temporal conditional statement.
  2257. tvarexpr = t[5]
  2258. topolist = self.eval_toperator(t[3], optype = 'relation')[0]
  2259. thencond = self.build_condition_list(tvarexpr, thenlist, topolist)
  2260. thenresult = self.eval_condition_list(thencond)
  2261. elsecond = self.build_condition_list(tvarexpr, elselist, topolist)
  2262. elseresult = self.eval_condition_list(elsecond, inverse = True)
  2263. # Combine and sort else and then statement to result map list.
  2264. combilist = thenresult + elseresult
  2265. resultlist = sorted(combilist, key = AbstractDatasetComparisonKeyStartTime)
  2266. # Clear the map and conditional values of the map list.
  2267. resultlist = self.check_stds(resultlist, clear = True)
  2268. # Return resulting map list.
  2269. t[0] = resultlist
  2270. else:
  2271. if t[5]:
  2272. t[0] = str(t[7])
  2273. else:
  2274. t[0] = str(t[9])
  2275. if self.debug:
  2276. if t[5]:
  2277. print str(t[7]), "* = ", "if condition", str(t[5]), " then ", str(t[7]), ' else ', str(t[9])
  2278. else:
  2279. print str(t[9]), "* = ", "if condition", str(t[5]), " then ", str(t[7]), ' else ', str(t[9])
  2280. def p_expr_t_buff(self, t):
  2281. # Examples
  2282. # buff_t(A : B, "10 minutes") # Select the part of A that is temporally
  2283. # equal to B and create a buffer of 10 minutes around
  2284. """
  2285. expr : BUFF_T LPAREN stds COMMA QUOTE number NAME QUOTE RPAREN
  2286. | BUFF_T LPAREN expr COMMA QUOTE number NAME QUOTE RPAREN
  2287. | BUFF_T LPAREN stds COMMA number RPAREN
  2288. | BUFF_T LPAREN expr COMMA number RPAREN
  2289. """
  2290. if self.run:
  2291. # Check input stds.
  2292. bufflist = self.check_stds(t[3])
  2293. for map in bufflist:
  2294. # Get increment format.
  2295. if len(t) == 10:
  2296. increment = str(t[6]) + " " + t[7]
  2297. elif len(t) == 7:
  2298. increment = str(t[5])
  2299. # Perform buffering.
  2300. map.temporal_buffer(increment)
  2301. t[0] = bufflist
  2302. else:
  2303. t[0] = t[3] + "*"
  2304. if self.debug:
  2305. if len(t) == 10:
  2306. print str(t[3]) + "* = buff_t(", str(t[3]), "," , '"', str(t[6]), str(t[7]), '"', ")"
  2307. elif len(t) == 7:
  2308. print str(t[3]) + "* = buff_t(", str(t[3]), ",", str(t[5]), ")"
  2309. def p_expr_t_snap(self, t):
  2310. # Examples
  2311. # tsnap(A : B) # Snap the maps of A temporally.
  2312. """
  2313. expr : TSNAP LPAREN stds RPAREN
  2314. | TSNAP LPAREN expr RPAREN
  2315. """
  2316. if self.run:
  2317. # Check input stds.
  2318. maplist = self.check_stds(t[3])
  2319. # Perform snapping.
  2320. snaplist = AbstractSpaceTimeDataset.snap_map_list(maplist)
  2321. t[0] = snaplist
  2322. else:
  2323. t[0] = t[3] + "*"
  2324. if self.debug:
  2325. print str(t[3]) + "* = tsnap(", str(t[3]), ")"
  2326. def p_expr_t_shift(self, t):
  2327. # Examples
  2328. # tshift(A : B, "10 minutes") # Shift the selection from A temporally
  2329. # by 10 minutes.
  2330. """
  2331. expr : TSHIFT LPAREN stds COMMA QUOTE number NAME QUOTE RPAREN
  2332. | TSHIFT LPAREN expr COMMA QUOTE number NAME QUOTE RPAREN
  2333. | TSHIFT LPAREN stds COMMA number RPAREN
  2334. | TSHIFT LPAREN expr COMMA number RPAREN
  2335. """
  2336. if self.run:
  2337. # Check input stds.
  2338. maplist = self.check_stds(t[3])
  2339. # Get increment format.
  2340. if len(t) == 10:
  2341. increment = str(t[6]) + " " + t[7]
  2342. elif len(t) == 7:
  2343. increment = str(t[5])
  2344. # Perform shifting.
  2345. shiftlist = AbstractSpaceTimeDataset.shift_map_list(maplist, increment)
  2346. t[0] = shiftlist
  2347. else:
  2348. t[0] = t[3] + "*"
  2349. if self.debug:
  2350. if len(t) == 10:
  2351. print str(t[3]) + "* = tshift(", str(t[3]), "," , '"', str(t[6]), str(t[7]), '"', ")"
  2352. elif len(t) == 7:
  2353. print str(t[3]) + "* = tshift(", str(t[3]), ",", str(t[5]), ")"
  2354. # Handle errors.
  2355. def p_error(self, t):
  2356. if t:
  2357. raise SyntaxError("syntax error on line %d, token %s near '%s' expression '%s'" %
  2358. (t.lineno, t.type, t.value, self.expression))
  2359. else:
  2360. raise SyntaxError("Unexpected syntax error")
  2361. ###############################################################################
  2362. if __name__ == "__main__":
  2363. import doctest
  2364. doctest.testmod()