temporal_algebra.py 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266
  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
  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 !: C)"
  298. >>> p.parse(expression)
  299. B* = B !: C
  300. A* = A : B*
  301. D = A*
  302. >>> expression = "D = A {!:} B {during,:} C"
  303. >>> print(expression)
  304. D = A {!:} B {during,:} C
  305. >>> p.parse(expression)
  306. A* = A {!:} B
  307. A** = A* {during,:} C
  308. D = A**
  309. >>> expression = "D = A {:} B {during,!:} C"
  310. >>> print(expression)
  311. D = A {:} B {during,!:} C
  312. >>> p.parse(expression)
  313. A* = A {:} B
  314. A** = A* {during,!:} C
  315. D = A**
  316. >>> expression = "D = A {:} (B {during,!:} (C : E))"
  317. >>> print(expression)
  318. D = A {:} (B {during,!:} (C : E))
  319. >>> p.parse(expression)
  320. C* = C : E
  321. B* = B {during,!:} C*
  322. A* = A {:} B*
  323. D = A*
  324. >>> p.run = False
  325. >>> p.debug = False
  326. >>> expression = "C = test1 : test2"
  327. >>> print(expression)
  328. C = test1 : test2
  329. >>> p.parse(expression, 'stvds')
  330. >>> expression = 'D = buff_t(test1,"10 months")'
  331. >>> print(expression)
  332. D = buff_t(test1,"10 months")
  333. >>> p.parse(expression, 'stvds')
  334. >>> expression = 'E = test2 {during,:} buff_t(test1,"1 days")'
  335. >>> print(expression)
  336. E = test2 {during,:} buff_t(test1,"1 days")
  337. >>> p.parse(expression, 'stvds')
  338. >>> expression = 'F = test2 {equal,:} buff_t(test1,"1 days")'
  339. >>> print(expression)
  340. F = test2 {equal,:} buff_t(test1,"1 days")
  341. >>> p.parse(expression, 'stvds')
  342. >>> p.debug = True
  343. >>> expression = 'H = tsnap(test2 {during,:} buff_t(test1, "1 days"))'
  344. >>> p.parse(expression, 'stvds')
  345. test1* = buff_t( test1 , " 1 days " )
  346. test2* = test2 {during,:} test1*
  347. test2** = tsnap( test2* )
  348. H = test2**
  349. >>> expression = 'H = tshift(test2 {during,:} test1, "1 days")'
  350. >>> p.parse(expression, 'stvds')
  351. test2* = test2 {during,:} test1
  352. test2** = tshift( test2* , " 1 days " )
  353. H = test2**
  354. >>> expression = 'H = tshift(H, 3)'
  355. >>> p.parse(expression, 'stvds')
  356. H* = tshift( H , 3 )
  357. H = H*
  358. >>> expression = 'C = if(td(A) == 2, A)'
  359. >>> p.parse(expression, 'stvds')
  360. td(A)
  361. td(A) == 2
  362. A* = if condition True then A
  363. C = A*
  364. >>> expression = 'C = if(td(A) == 5, A, B)'
  365. >>> p.parse(expression, 'stvds')
  366. td(A)
  367. td(A) == 5
  368. A* = if condition True then A else B
  369. C = A*
  370. >>> expression = 'C = if(td(A) == 5 || start_date() > "2010-01-01", A, B)'
  371. >>> p.parse(expression, 'stvds')
  372. td(A)
  373. td(A) == 5
  374. start_date > "2010-01-01"
  375. True || True
  376. A* = if condition True then A else B
  377. C = A*
  378. @endcode
  379. """
  380. try:
  381. import ply.lex as lex
  382. import ply.yacc as yacc
  383. except:
  384. pass
  385. import re
  386. import sys
  387. import os
  388. import grass.pygrass.modules as pygrass
  389. import grass.script as grass
  390. from space_time_datasets import *
  391. from factory import *
  392. from open_stds import *
  393. import copy
  394. ##############################################################################
  395. class TemporalAlgebraLexer(object):
  396. """!Lexical analyzer for the GRASS GIS temporal algebra"""
  397. # Functions that defines an if condition, temporal buffering and snapping
  398. conditional_functions = {
  399. 'if' : 'IF',
  400. 'buff_t': 'BUFF_T',
  401. 'tsnap' : 'TSNAP',
  402. 'tshift' : 'TSHIFT',
  403. }
  404. # Variables with date and time strings
  405. datetime_functions = {
  406. 'start_time' : 'START_TIME', # start time as HH::MM:SS
  407. 'start_date' : 'START_DATE', # start date as yyyy-mm-DD
  408. 'start_datetime' : 'START_DATETIME', # start datetime as yyyy-mm-DD HH:MM:SS
  409. 'end_time' : 'END_TIME', # end time as HH:MM:SS
  410. 'end_date' : 'END_DATE', # end date as yyyy-mm-DD
  411. 'end_datetime' : 'END_DATETIME', # end datetime as yyyy-mm-DD HH:MM:SS
  412. }
  413. # Time functions
  414. time_functions = {
  415. 'td' : 'TD', # The size of the current
  416. # sample time interval in days and
  417. # fraction of days for absolute time,
  418. # and in relative units in case of relative time.
  419. #'start_td' : 'START_TD', # The time difference between the start
  420. # time of the sample space time raster
  421. # dataset and the start time of the
  422. # current sample interval or instance.
  423. # The time is measured in days and
  424. # fraction of days for absolute time,
  425. # and in relative units in case of relative time.
  426. #'end_td' : 'END_TD', # The time difference between the
  427. # start time of the sample
  428. # space time raster dataset and the
  429. # end time of the current sample interval.
  430. # The time is measured in days and
  431. # fraction of days for absolute time,
  432. # and in relative units in case of relative time.
  433. # The end_time() will be represented by null() in case of a time instance.
  434. 'start_doy' : 'START_DOY', # Day of year (doy) from the start time [1 - 366]
  435. 'start_dow' : 'START_DOW', # Day of week (dow) from the start time [1 - 7], the start of the week is Monday == 1
  436. 'start_year' : 'START_YEAR', # The year of the start time [0 - 9999]
  437. 'start_month' : 'START_MONTH', # The month of the start time [1 - 12]
  438. 'start_week' : 'START_WEEK', # Week of year of the start time [1 - 54]
  439. 'start_day' : 'START_DAY', # Day of month from the start time [1 - 31]
  440. 'start_hour' : 'START_HOUR', # The hour of the start time [0 - 23]
  441. 'start_minute': 'START_MINUTE', # The minute of the start time [0 - 59]
  442. 'start_second': 'START_SECOND', # The second of the start time [0 - 59]
  443. 'end_doy' : 'END_DOY', # Day of year (doy) from the end time [1 - 366]
  444. 'end_dow' : 'END_DOW', # Day of week (dow) from the end time [1 - 7], the start of the week is Monday == 1
  445. 'end_year' : 'END_YEAR', # The year of the end time [0 - 9999]
  446. 'end_month' : 'END_MONTH', # The month of the end time [1 - 12]
  447. 'end_week' : 'END_WEEK', # Week of year of the end time [1 - 54]
  448. 'end_day' : 'END_DAY', # Day of month from the start time [1 - 31]
  449. 'end_hour' : 'END_HOUR', # The hour of the end time [0 - 23]
  450. 'end_minute' : 'END_MINUTE', # The minute of the end time [0 - 59]
  451. 'end_second' : 'END_SECOND', # The second of the end time [0 - 59]
  452. }
  453. # This is the list of token names.
  454. tokens = (
  455. 'DATETIME',
  456. 'TIME',
  457. 'DATE',
  458. 'INT',
  459. 'FLOAT',
  460. 'LPAREN',
  461. 'RPAREN',
  462. 'COMMA',
  463. 'CEQUALS',
  464. 'EQUALS',
  465. 'UNEQUALS',
  466. 'LOWER',
  467. 'LOWER_EQUALS',
  468. 'GREATER',
  469. 'GREATER_EQUALS',
  470. 'HASH',
  471. 'OR',
  472. 'AND',
  473. 'T_SELECT_OPERATOR',
  474. 'T_HASH_OPERATOR',
  475. 'T_COMP_OPERATOR',
  476. 'T_REL_OPERATOR',
  477. 'T_SELECT',
  478. 'T_NOT_SELECT',
  479. 'NAME',
  480. 'QUOTE',
  481. )
  482. # Build the token list
  483. tokens = tokens + tuple(datetime_functions.values()) \
  484. + tuple(time_functions.values()) \
  485. + tuple(conditional_functions.values())
  486. # Regular expression rules for simple tokens
  487. t_T_SELECT_OPERATOR = r'\{([a-zA-Z\| ]+[,])?([\|&+=]?[!]?[:])\}'
  488. t_T_HASH_OPERATOR = r'\{([a-zA-Z\| ]+[,])?[#]\}'
  489. t_T_COMP_OPERATOR = r'\{([a-zA-Z\| ]+[,])?(\|\||&&)\}'
  490. t_T_REL_OPERATOR = r'\{([a-zA-Z\| ])+\}'
  491. t_T_SELECT = r':'
  492. t_T_NOT_SELECT = r'!:'
  493. t_LPAREN = r'\('
  494. t_RPAREN = r'\)'
  495. t_COMMA = r','
  496. t_CEQUALS = r'=='
  497. t_EQUALS = r'='
  498. t_UNEQUALS = r'!='
  499. t_LOWER = r'<'
  500. t_LOWER_EQUALS = r'<='
  501. t_GREATER = r'>'
  502. t_GREATER_EQUALS = r'>='
  503. t_HASH = r'\#'
  504. t_OR = r'[\|]'
  505. t_AND = r'[&]'
  506. t_QUOTE = r'[\"\']'
  507. # These are the things that should be ignored.
  508. t_ignore = ' \t'
  509. # Read time string and convert it into a date object
  510. def t_DATETIME(self, t):
  511. 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)"'
  512. # t.value = int(t.value)
  513. return t
  514. # Read date string and convert it into a date object
  515. def t_DATE(self, t):
  516. r'"\d\d\d\d-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])"'
  517. # t.value = int(t.value)
  518. return t
  519. # Read time string and convert it into a date object
  520. def t_TIME(self, t):
  521. 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)"'
  522. # t.value = int(t.value)
  523. return t
  524. # Read in a float. This rule has to be done before the int rule.
  525. def t_FLOAT(self, t):
  526. r'-?\d+\.\d*(e-?\d+)?'
  527. t.value = float(t.value)
  528. return t
  529. # Read in an int.
  530. def t_INT(self, t):
  531. r'-?\d+'
  532. t.value = int(t.value)
  533. return t
  534. # Read in a list of maps.
  535. def t_LIST(self, t):
  536. r'[\[][.]*[\]]'
  537. t.value = list(t.value)
  538. return t
  539. # Ignore comments.
  540. # def t_comment(self, t):
  541. # r'^[#][^\n]*'
  542. # pass
  543. # Track line numbers.
  544. def t_newline(self, t):
  545. r'\n+'
  546. t.lineno += len(t.value)
  547. def t_NAME(self, t):
  548. r'[a-zA-Z_][a-zA-Z_0-9]*'
  549. self.temporal_symbol(t)
  550. return t
  551. # Parse symbols
  552. def temporal_symbol(self, t):
  553. # Check for reserved words
  554. if t.value in TemporalAlgebraLexer.time_functions.keys():
  555. t.type = TemporalAlgebraLexer.time_functions.get(t.value)
  556. elif t.value in TemporalAlgebraLexer.datetime_functions.keys():
  557. t.type = TemporalAlgebraLexer.datetime_functions.get(t.value)
  558. elif t.value in TemporalAlgebraLexer.conditional_functions.keys():
  559. t.type = TemporalAlgebraLexer.conditional_functions.get(t.value)
  560. else:
  561. t.type = 'NAME'
  562. return t
  563. # Handle errors.
  564. def t_error(self, t):
  565. raise SyntaxError("syntax error on line %d near '%s'" %
  566. (t.lineno, t.value))
  567. # Build the lexer
  568. def build(self,**kwargs):
  569. self.lexer = lex.lex(module=self, optimize=False, debug=False, **kwargs)
  570. # Just for testing
  571. def test(self,data):
  572. self.name_list = {}
  573. print(data)
  574. self.lexer.input(data)
  575. while True:
  576. tok = self.lexer.token()
  577. if not tok: break
  578. print tok
  579. ###############################################################################
  580. class GlobalTemporalVar(object):
  581. """ This class handles global temporal variable conditional expressions,
  582. like start_doy() == 3.
  583. The three parts of the statement are stored separately in
  584. tfunc (START_DOY), compop (==) and value (3).
  585. But also boolean values, time differences and relation operators for comparison in
  586. if-statements can be stored in this class.
  587. """
  588. def __init__(self):
  589. self.tfunc = None
  590. self.compop = None
  591. self.value = None
  592. self.boolean = None
  593. self.relationop = None
  594. self.topology = []
  595. self.td = None
  596. def get_type(self):
  597. if self.tfunc != None and self.compop != None and self.value != None:
  598. return("global")
  599. elif self.boolean != None:
  600. return("boolean")
  601. elif self.relationop != None and self.topology != []:
  602. return("operator")
  603. elif self.td != None:
  604. return("timediff")
  605. def get_type_value(self):
  606. typename = self.get_type()
  607. valuelist = []
  608. if typename == "global":
  609. valuelist = [self.tfunc, self.compop, self.value]
  610. elif typename == "operator":
  611. valuelist.append(self.topology)
  612. valuelist.append(self.relationop)
  613. elif typename == "boolean":
  614. valuelist = self.boolean
  615. elif typename == "timediff":
  616. valuelist.append(self.td)
  617. return(valuelist)
  618. ###############################################################################
  619. class TemporalAlgebraParser(object):
  620. """The temporal algebra class"""
  621. def __init__(self, pid=None, run = True, debug = False, spatial = False, null = False):
  622. self.run = run
  623. self.debug = debug
  624. self.pid = pid
  625. # Intermediate vector map names
  626. self.names = {}
  627. # Count map names
  628. self.spatial = spatial
  629. self.null = null
  630. self.mapset = get_current_mapset()
  631. self.temporaltype = None
  632. self.msgr = get_tgis_message_interface()
  633. self.dbif = SQLDatabaseInterfaceConnection()
  634. self.dbif.connect()
  635. def __del__(self):
  636. if self.dbif.connected:
  637. self.dbif.close()
  638. def parse(self, expression, stdstype = 'strds', basename = None):
  639. self.lexer = TemporalAlgebraLexer()
  640. self.lexer.build()
  641. self.parser = yacc.yacc(module=self, debug=self.debug)
  642. self.count = 0
  643. self.stdstype = stdstype
  644. self.basename = basename
  645. self.expression = expression
  646. self.parser.parse(expression)
  647. def generate_map_name(self):
  648. """!Generate an unique intermediate vector map name
  649. and register it in the objects map list for later removement.
  650. The vector map names are unique between processes. Do not use the
  651. same object for map name generation in multiple threads.
  652. """
  653. self.count += 1
  654. if self.pid != None:
  655. pid = self.pid
  656. else:
  657. pid = os.getpid()
  658. name = "tmp_map_name_%i_%i"%(pid, self.count)
  659. self.names[name] = name
  660. return name
  661. # Get the tokens from the lexer class
  662. tokens = TemporalAlgebraLexer.tokens
  663. # Setting equal precedence level for select and hash operations.
  664. precedence = (
  665. ('left', 'T_SELECT_OPERATOR', 'T_SELECT', 'T_NOT_SELECT'), # 1
  666. ('left', 'AND', 'OR', 'T_COMP_OPERATOR'), #2
  667. )
  668. ######################### Temporal functions ##############################
  669. def check_stds(self, input, clear = False):
  670. """! Check if input space time dataset exist in database and return its map list.
  671. @param input Name of space time data set as string or list of maps.
  672. @param clear Reset the stored conditional values to empty list.
  673. @return List of maps.
  674. """
  675. if not isinstance(input, list):
  676. # Get mapset input.
  677. mapset = get_current_mapset()
  678. # Check for mapset in given stds input.
  679. if input.find("@") >= 0:
  680. id_input = input
  681. else:
  682. id_input = input + "@" + mapset
  683. # Create empty spacetime dataset.
  684. stds = dataset_factory(self.stdstype, id_input)
  685. # Check for occurence of space time dataset.
  686. if stds.is_in_db(dbif=self.dbif) == False:
  687. self.msgr.fatal(_("Space time %s dataset <%s> not found") %
  688. (stds.get_new_map_instance(None).get_type(), id_input))
  689. else:
  690. # Select temporal dataset entry from database.
  691. stds.select(dbif=self.dbif)
  692. maplist = stds.get_registered_maps_as_objects(dbif=self.dbif)
  693. # Create map_value as empty list item.
  694. for map_i in maplist:
  695. if "map_value" not in dir(map_i):
  696. map_i.map_value = []
  697. if "condition_value" not in dir(map_i):
  698. map_i.condition_value = []
  699. # Set and check global temporal type variable and map.
  700. if map_i.is_time_absolute() and self.temporaltype == None:
  701. self.temporaltype = 'absolute'
  702. elif map_i.is_time_relative() and self.temporaltype == None:
  703. self.temporaltype = 'relative'
  704. elif map_i.is_time_absolute() and self.temporaltype == 'relative':
  705. self.msgr.fatal(_("Wrong temporal type of space time dataset <%s> \
  706. <%s> time is required") %
  707. (id_input, self.temporaltype))
  708. elif map_i.is_time_relative() and self.temporaltype == 'absolute':
  709. self.msgr.fatal(_("Wrong temporal type of space time dataset <%s> \
  710. <%s> time is required") %
  711. (id_input, self.temporaltype))
  712. else:
  713. maplist = input
  714. # Create map_value as empty list item.
  715. for map_i in maplist:
  716. if "map_value" not in dir(map_i):
  717. map_i.map_value = []
  718. elif clear:
  719. map_i.map_value = []
  720. if "condition_value" not in dir(map_i):
  721. map_i.condition_value = []
  722. elif clear:
  723. map_i.condition_value = []
  724. return(maplist)
  725. def get_temporal_topo_list(self, maplistA, maplistB = None, topolist = ["EQUAL"],
  726. assign_val = False, count_map = False):
  727. """!Build temporal topology for two space time data sets, copy map objects
  728. for given relation into map list.
  729. @param maplistA List of maps.
  730. @param maplistB List of maps.
  731. @param topolist List of strings of temporal relations.
  732. @param assign_val Boolean for assigning a boolean map value based on
  733. the map_values from the compared map list by
  734. topological relationships.
  735. @param count_map Boolean if the number of topological related maps
  736. should be returned.
  737. @return List of maps from maplistA that fulfil the topological relationships
  738. to maplistB specified in topolist.
  739. @code
  740. # Example with two lists of maps
  741. >>> import grass.temporal as tgis
  742. >>> tgis.init(True)
  743. >>> l = tgis.TemporalAlgebraParser()
  744. >>> # Create two list of maps with equal time stamps
  745. >>> mapsA = []
  746. >>> mapsB = []
  747. >>> for i in range(10):
  748. ... idA = "a%i@B"%(i)
  749. ... mapA = tgis.RasterDataset(idA)
  750. ... idB = "b%i@B"%(i)
  751. ... mapB = tgis.RasterDataset(idB)
  752. ... check = mapA.set_relative_time(i, i + 1, "months")
  753. ... check = mapB.set_relative_time(i, i + 1, "months")
  754. ... mapsA.append(mapA)
  755. ... mapsB.append(mapB)
  756. >>> resultlist = l.get_temporal_topo_list(mapsA, mapsB, ['EQUAL'])
  757. >>> for map in resultlist:
  758. ... if map.get_equal():
  759. ... relations = map.get_equal()
  760. ... print "Map %s has equal relation to map %s"%(map.get_name(),
  761. ... relations[0].get_name())
  762. Map a0 has equal relation to map b0
  763. Map a1 has equal relation to map b1
  764. Map a2 has equal relation to map b2
  765. Map a3 has equal relation to map b3
  766. Map a4 has equal relation to map b4
  767. Map a5 has equal relation to map b5
  768. Map a6 has equal relation to map b6
  769. Map a7 has equal relation to map b7
  770. Map a8 has equal relation to map b8
  771. Map a9 has equal relation to map b9
  772. >>> resultlist = l.get_temporal_topo_list(mapsA, mapsB, ['DURING'])
  773. >>> print(resultlist)
  774. []
  775. >>> # Create two list of maps with equal time stamps
  776. >>> mapsA = []
  777. >>> mapsB = []
  778. >>> for i in range(10):
  779. ... idA = "a%i@B"%(i)
  780. ... mapA = tgis.RasterDataset(idA)
  781. ... idB = "b%i@B"%(i)
  782. ... mapB = tgis.RasterDataset(idB)
  783. ... check = mapA.set_relative_time(i, i + 1, "months")
  784. ... check = mapB.set_relative_time(i, i + 2, "months")
  785. ... mapsA.append(mapA)
  786. ... mapsB.append(mapB)
  787. >>> resultlist = l.get_temporal_topo_list(mapsA, mapsB, ['starts','during'])
  788. >>> for map in resultlist:
  789. ... if map.get_starts():
  790. ... relations = map.get_starts()
  791. ... print "Map %s has start relation to map %s"%(map.get_name(),
  792. ... relations[0].get_name())
  793. Map a0 has start relation to map b0
  794. Map a1 has start relation to map b1
  795. Map a2 has start relation to map b2
  796. Map a3 has start relation to map b3
  797. Map a4 has start relation to map b4
  798. Map a5 has start relation to map b5
  799. Map a6 has start relation to map b6
  800. Map a7 has start relation to map b7
  801. Map a8 has start relation to map b8
  802. Map a9 has start relation to map b9
  803. >>> for map in resultlist:
  804. ... if map.get_during():
  805. ... relations = map.get_during()
  806. ... print "Map %s has during relation to map %s"%(map.get_name(),
  807. ... relations[0].get_name())
  808. Map a0 has during relation to map b0
  809. Map a1 has during relation to map b0
  810. Map a2 has during relation to map b1
  811. Map a3 has during relation to map b2
  812. Map a4 has during relation to map b3
  813. Map a5 has during relation to map b4
  814. Map a6 has during relation to map b5
  815. Map a7 has during relation to map b6
  816. Map a8 has during relation to map b7
  817. Map a9 has during relation to map b8
  818. >>> # Create two list of maps with equal time stamps and map_value method.
  819. >>> mapsA = []
  820. >>> mapsB = []
  821. >>> for i in range(10):
  822. ... idA = "a%i@B"%(i)
  823. ... mapA = tgis.RasterDataset(idA)
  824. ... idB = "b%i@B"%(i)
  825. ... mapB = tgis.RasterDataset(idB)
  826. ... check = mapA.set_relative_time(i, i + 1, "months")
  827. ... check = mapB.set_relative_time(i, i + 1, "months")
  828. ... mapB.map_value = True
  829. ... mapsA.append(mapA)
  830. ... mapsB.append(mapB)
  831. >>> # Create two list of maps with equal time stamps
  832. >>> mapsA = []
  833. >>> mapsB = []
  834. >>> for i in range(10):
  835. ... idA = "a%i@B"%(i)
  836. ... mapA = tgis.RasterDataset(idA)
  837. ... mapA.map_value = True
  838. ... idB = "b%i@B"%(i)
  839. ... mapB = tgis.RasterDataset(idB)
  840. ... mapB.map_value = False
  841. ... check = mapA.set_absolute_time(datetime(2000,1,i+1),
  842. ... datetime(2000,1,i + 2))
  843. ... check = mapB.set_absolute_time(datetime(2000,1,i+6),
  844. ... datetime(2000,1,i + 7))
  845. ... mapsA.append(mapA)
  846. ... mapsB.append(mapB)
  847. >>> resultlist = l.get_temporal_topo_list(mapsA, mapsB)
  848. >>> for map in resultlist:
  849. ... print(map.get_id())
  850. a5@B
  851. a6@B
  852. a7@B
  853. a8@B
  854. a9@B
  855. >>> resultlist = l.get_temporal_topo_list(mapsA, mapsB, ['during'])
  856. >>> for map in resultlist:
  857. ... print(map.get_id())
  858. @endcode
  859. """
  860. topologylist = ["EQUAL", "FOLLOWS", "PRECEDES", "OVERLAPS", "OVERLAPPED", \
  861. "DURING", "STARTS", "FINISHES", "CONTAINS", "STARTED", \
  862. "FINISHED"]
  863. complementdict = {"EQUAL": "EQUAL", "FOLLOWS" : "PRECEDES",
  864. "PRECEDES" : "FOLLOWS", "OVERLAPS" : "OVERLAPPED",
  865. "OVERLAPPED" : "OVERLAPS", "DURING" : "CONTAINS",
  866. "CONTAINS" : "DURING", "STARTS" : "STARTED",
  867. "STARTED" : "STARTS", "FINISHES" : "FINISHED",
  868. "FINISHED" : "FINISHES"}
  869. resultdict = {}
  870. # Check if given temporal relation are valid.
  871. for topo in topolist:
  872. if topo.upper() not in topologylist:
  873. raise SyntaxError("Unpermitted temporal relation name '" + topo + "'")
  874. # Create temporal topology for maplistA to maplistB.
  875. tb = SpatioTemporalTopologyBuilder()
  876. # Dictionary with different spatial variables used for topology builder.
  877. spatialdict = {'strds' : '2D', 'stvds' : '2D', 'str3ds' : '3D'}
  878. # Build spatial temporal topology
  879. if self.spatial:
  880. tb.build(maplistA, maplistB, spatial = spatialdict[self.stdstype])
  881. else:
  882. tb.build(maplistA, maplistB)
  883. # Iterate through maps in maplistA and search for relationships given
  884. # in topolist.
  885. # TODO: Better implementation with less nesting
  886. for map_i in maplistA:
  887. tbrelations = map_i.get_temporal_relations()
  888. for topo in topolist:
  889. if topo.upper() in tbrelations.keys():
  890. if assign_val:
  891. mapvaluelist = []
  892. if complementdict[topo.upper()] in tbrelations:
  893. relationmaplist = tbrelations[complementdict[topo.upper()]]
  894. for relationmap in relationmaplist:
  895. if "map_value" in dir(relationmap):
  896. for element in relationmap.map_value:
  897. if isinstance(element, GlobalTemporalVar):
  898. if element.get_type() == "boolean":
  899. mapvaluelist.append(element.boolean)
  900. if all(mapvaluelist):
  901. resultbool = True
  902. else:
  903. resultbool = False
  904. if "condition_value" in dir(map_i):
  905. if isinstance(map_i.condition_value, list):
  906. map_i.condition_value.append(resultbool)
  907. if count_map:
  908. relationmaplist = tbrelations[topo.upper()]
  909. gvar = GlobalTemporalVar()
  910. gvar.td = len(relationmaplist)
  911. if "map_value" in dir(map_i):
  912. map_i.map_value.append(gvar)
  913. else:
  914. map_i.map_value = gvar
  915. resultdict[map_i.get_id()] = map_i
  916. resultlist = resultdict.values()
  917. # Sort list of maps chronological.
  918. resultlist = sorted(resultlist, key = AbstractDatasetComparisonKeyStartTime)
  919. return(resultlist)
  920. def eval_toperator(self, operator):
  921. """!This function evaluates a string containing temporal operations.
  922. @param operator String of temporal operations, e.g. {equal|during,=!:}.
  923. @return List of temporal relations (equal, during), the given function
  924. (!:) and the interval/instances (=).
  925. @code
  926. >>> import grass.temporal as tgis
  927. >>> tgis.init()
  928. >>> p = tgis.TemporalAlgebraParser()
  929. >>> operator = "{equal,:}"
  930. >>> p.eval_toperator(operator)
  931. (['equal'], '=', ':')
  932. >>> operator = "{equal|during,:}"
  933. >>> p.eval_toperator(operator)
  934. (['equal', 'during'], '=', ':')
  935. >>> operator = "{equal,!:}"
  936. >>> p.eval_toperator(operator)
  937. (['equal'], '=', '!:')
  938. >>> operator = "{equal|during,!:}"
  939. >>> p.eval_toperator(operator)
  940. (['equal', 'during'], '=', '!:')
  941. >>> operator = "{equal|during,=!:}"
  942. >>> p.eval_toperator(operator)
  943. (['equal', 'during'], '=', '!:')
  944. >>> operator = "{equal|during|starts,#}"
  945. >>> p.eval_toperator(operator)
  946. (['equal', 'during', 'starts'], '=', '#')
  947. >>> operator = "{!:}"
  948. >>> p.eval_toperator(operator)
  949. (['equal'], '=', '!:')
  950. >>> operator = "{=:}"
  951. >>> p.eval_toperator(operator)
  952. (['equal'], '=', ':')
  953. >>> operator = "{#}"
  954. >>> p.eval_toperator(operator)
  955. (['equal'], '=', '#')
  956. >>> operator = "{equal|during}"
  957. >>> p.eval_toperator(operator)
  958. (['equal', 'during'], '=', '')
  959. >>> operator = "{equal}"
  960. >>> p.eval_toperator(operator)
  961. (['equal'], '=', '')
  962. >>> operator = "{equal,||}"
  963. >>> p.eval_toperator(operator)
  964. (['equal'], '=', '||')
  965. >>> operator = "{equal|during,&&}"
  966. >>> p.eval_toperator(operator)
  967. (['equal', 'during'], '=', '&&')
  968. @endcode
  969. """
  970. topologylist = ["EQUAL", "FOLLOWS", "PRECEDES", "OVERLAPS", "OVERLAPPED", \
  971. "DURING", "STARTS", "FINISHES", "CONTAINS", "STARTED", \
  972. "FINISHED"]
  973. functionlist = [":", "!:", "#"]
  974. intervallist = ["=", "|", "&", "+"]
  975. comparelist = ["||", "&&"]
  976. relations = []
  977. interval = '='
  978. function = ''
  979. op = operator.strip('{}')
  980. oplist = op.split(',')
  981. if len(oplist) > 1:
  982. relationlist = oplist[0].split('|')
  983. for relation in relationlist:
  984. if relation.upper() in topologylist and relation not in relations:
  985. relations.append(relation)
  986. else:
  987. raise SyntaxError("invalid syntax")
  988. opright = oplist[1]
  989. if opright in comparelist:
  990. function = opright
  991. elif opright[0] in intervallist:
  992. interval = opright[0]
  993. if opright[1:] in functionlist:
  994. function = opright[1:]
  995. else:
  996. raise SyntaxError("invalid syntax")
  997. elif opright in functionlist:
  998. function = opright
  999. else:
  1000. raise SyntaxError("invalid syntax")
  1001. elif all([rel.upper() in topologylist for rel in oplist[0].split('|')]):
  1002. relations = oplist[0].split('|')
  1003. else:
  1004. relations = ['equal']
  1005. opstr = str(oplist[0])
  1006. if opstr[0] in intervallist:
  1007. interval = opstr[0]
  1008. if opstr[1:] in functionlist:
  1009. function = opstr[1:]
  1010. else:
  1011. raise SyntaxError("invalid syntax")
  1012. elif opstr in functionlist:
  1013. function = opstr
  1014. #else:
  1015. #raise SyntaxError("invalid syntax")
  1016. return(relations, interval, function)
  1017. def perform_temporal_selection(self, maplistA, maplistB, topolist = ["EQUAL"],
  1018. inverse = False, assign_val = False):
  1019. """!This function performs temporal selection operation.
  1020. @param maplistA List of maps representing the left side of a temporal
  1021. expression.
  1022. @param maplistB List of maps representing the right side of a temporal
  1023. expression.
  1024. @param topolist List of strings of temporal relations.
  1025. @param inverse Boolean value that specifies if the selection should be
  1026. inverted.
  1027. @param assign_val Boolean for assigning a boolean map value based on
  1028. the map_values from the compared map list by
  1029. topological relationships.
  1030. @return List of selected maps from maplistA.
  1031. @code
  1032. >>> import grass.temporal as tgis
  1033. >>> tgis.init()
  1034. >>> l = tgis.TemporalAlgebraParser()
  1035. >>> # Example with two lists of maps
  1036. >>> # Create two list of maps with equal time stamps
  1037. >>> mapsA = []
  1038. >>> mapsB = []
  1039. >>> for i in range(10):
  1040. ... idA = "a%i@B"%(i)
  1041. ... mapA = tgis.RasterDataset(idA)
  1042. ... idB = "b%i@B"%(i)
  1043. ... mapB = tgis.RasterDataset(idB)
  1044. ... check = mapA.set_relative_time(i, i + 1, "months")
  1045. ... check = mapB.set_relative_time(i + 5, i + 6, "months")
  1046. ... mapsA.append(mapA)
  1047. ... mapsB.append(mapB)
  1048. >>> resultlist = l.perform_temporal_selection(mapsA, mapsB, ['EQUAL'],
  1049. ... False)
  1050. >>> for map in resultlist:
  1051. ... if map.get_equal():
  1052. ... relations = map.get_equal()
  1053. ... print "Map %s has equal relation to map %s"%(map.get_name(),
  1054. ... relations[0].get_name())
  1055. Map a5 has equal relation to map b0
  1056. Map a6 has equal relation to map b1
  1057. Map a7 has equal relation to map b2
  1058. Map a8 has equal relation to map b3
  1059. Map a9 has equal relation to map b4
  1060. >>> resultlist = l.perform_temporal_selection(mapsA, mapsB, ['EQUAL'],
  1061. ... True)
  1062. >>> for map in resultlist:
  1063. ... if not map.get_equal():
  1064. ... print "Map %s has no equal relation to mapset mapsB"%(map.get_name())
  1065. Map a0 has no equal relation to mapset mapsB
  1066. Map a1 has no equal relation to mapset mapsB
  1067. Map a2 has no equal relation to mapset mapsB
  1068. Map a3 has no equal relation to mapset mapsB
  1069. Map a4 has no equal relation to mapset mapsB
  1070. @endcode
  1071. """
  1072. if not inverse:
  1073. topolist = self.get_temporal_topo_list(maplistA, maplistB, topolist,
  1074. assign_val = assign_val)
  1075. resultlist = topolist
  1076. else:
  1077. topolist = self.get_temporal_topo_list(maplistA, maplistB, topolist,
  1078. assign_val = False)
  1079. resultlist = []
  1080. for map_i in maplistA:
  1081. if map_i not in topolist:
  1082. resultlist.append(map_i)
  1083. if assign_val:
  1084. if "condition_value" in dir(map_i):
  1085. map_i.condition_value.append(False)
  1086. # Sort list of maps chronological.
  1087. resultlist = sorted(resultlist, key = AbstractDatasetComparisonKeyStartTime)
  1088. return(resultlist)
  1089. def set_granularity(self, maplistA, maplistB, toperator = '=', topolist = ["EQUAL"]):
  1090. """!This function sets the temporal extends of a list of maps based on
  1091. another map list.
  1092. @param maplistB List of maps.
  1093. @param maplistB List of maps.
  1094. @param toperator String containing the temporal operator: =, +, &, |.
  1095. @param topolist List of topological relations.
  1096. @return List of maps with the new temporal extends.
  1097. @code
  1098. >>> import grass.temporal as tgis
  1099. >>> tgis.init()
  1100. >>> p = tgis.TemporalAlgebraParser()
  1101. >>> # Create two list of maps with equal time stamps
  1102. >>> mapsA = []
  1103. >>> mapsB = []
  1104. >>> for i in range(10):
  1105. ... idA = "a%i@B"%(i)
  1106. ... mapA = tgis.RasterDataset(idA)
  1107. ... idB = "b%i@B"%(i)
  1108. ... mapB = tgis.RasterDataset(idB)
  1109. ... check = mapA.set_relative_time(i, i + 1, "months")
  1110. ... check = mapB.set_relative_time(i*2, i*2 + 2, "months")
  1111. ... mapsA.append(mapA)
  1112. ... mapsB.append(mapB)
  1113. >>> resultlist = p.set_granularity(mapsA, mapsB, toperator = "|", topolist = ["during"])
  1114. >>> for map in resultlist:
  1115. ... start,end,unit = map.get_relative_time()
  1116. ... print(map.get_id() + ' - start: ' + str(start) + ' end: ' + str(end))
  1117. a1@B - start: 0 end: 2
  1118. a0@B - start: 0 end: 2
  1119. a3@B - start: 2 end: 4
  1120. a2@B - start: 2 end: 4
  1121. a5@B - start: 4 end: 6
  1122. a4@B - start: 4 end: 6
  1123. a7@B - start: 6 end: 8
  1124. a6@B - start: 6 end: 8
  1125. a9@B - start: 8 end: 10
  1126. a8@B - start: 8 end: 10
  1127. @endcode
  1128. """
  1129. topologylist = ["EQUAL", "FOLLOWS", "PRECEDES", "OVERLAPS", "OVERLAPPED", \
  1130. "DURING", "STARTS", "FINISHES", "CONTAINS", "STARTED", \
  1131. "FINISHED"]
  1132. for topo in topolist:
  1133. if topo.upper() not in topologylist:
  1134. raise SyntaxError("Unpermitted temporal relation name '" + topo + "'")
  1135. # Create temporal topology for maplistA to maplistB.
  1136. tb = SpatioTemporalTopologyBuilder()
  1137. # Dictionary with different spatial variables used for topology builder.
  1138. spatialdict = {'strds' : '2D', 'stvds' : '2D', 'str3ds' : '3D'}
  1139. # Build spatial temporal topology for maplistB to maplistB.
  1140. if self.spatial:
  1141. tb.build(maplistA, maplistB, spatial = spatialdict[self.stdstype])
  1142. else:
  1143. tb.build(maplistA, maplistB)
  1144. resultdict = {}
  1145. # Iterate through maps in maplistA and search for relationships given
  1146. # in topolist.
  1147. for map_i in maplistA:
  1148. tbrelations = map_i.get_temporal_relations()
  1149. for topo in topolist:
  1150. if topo.upper() in tbrelations.keys():
  1151. relationmaplist = tbrelations[topo.upper()]
  1152. for relationmap in relationmaplist:
  1153. newextend = None
  1154. if toperator == "&":
  1155. newextend = map_i.temporal_intersection(relationmap)
  1156. elif toperator == "|":
  1157. newextend = map_i.temporal_union(relationmap)
  1158. elif toperator == "+":
  1159. newextend = map_i.temporal_disjoint_union(relationmap)
  1160. elif toperator == "=":
  1161. resultdict[map_i.get_id()] = map_i
  1162. if newextend != None:
  1163. start = newextend.get_start_time()
  1164. end = newextend.get_end_time()
  1165. #print(map_i.get_id() + ' - start: ' + str(start) + ' end: ' + str(end))
  1166. if map_i.is_time_absolute():
  1167. map_i.set_absolute_time(start, end)
  1168. else:
  1169. relunit = map_i.get_relative_time_unit()
  1170. map_i.set_relative_time(int(start), int(end), relunit)
  1171. resultdict[map_i.get_id()] = map_i
  1172. resultlist = resultdict.values()
  1173. # Sort list of maps chronological.
  1174. resultlist = sorted(resultlist, key = AbstractDatasetComparisonKeyStartTime)
  1175. # Get relations to maplistB per map in A.
  1176. # Loop over all relations from list
  1177. # temporal extent = map.temporal_intersection(map)
  1178. # if temporal extend is None = delete map.
  1179. return(resultlist)
  1180. def get_temporal_func_dict(self, map):
  1181. """! This function creates a dictionary containing temporal functions for a
  1182. map dataset with time stamp.
  1183. @param map Map object with time stamps.
  1184. @return Dictionary with temporal functions for given input map.
  1185. @code
  1186. >>> import grass.temporal as tgis
  1187. >>> import datetime
  1188. >>> tgis.init()
  1189. >>> l = tgis.TemporalAlgebraParser()
  1190. >>> # Example with one list of maps
  1191. >>> # Create one list of maps with equal time stamps
  1192. >>> for i in range(1):
  1193. ... idA = "a%i@B"%(i)
  1194. ... mapA = tgis.RasterDataset(idA)
  1195. ... check = mapA.set_absolute_time(datetime.datetime(2000,1,1),
  1196. ... datetime.datetime(2000,10,1))
  1197. ... tfuncdict = l.get_temporal_func_dict(mapA)
  1198. >>> print(tfuncdict["START_YEAR"])
  1199. 2000
  1200. >>> print(tfuncdict["START_TIME"])
  1201. 00:00:00
  1202. >>> print(tfuncdict["START_DATE"])
  1203. 2000-01-01
  1204. >>> print(tfuncdict["START_DATETIME"])
  1205. 2000-01-01 00:00:00
  1206. @endcode
  1207. """
  1208. tvardict = {"START_DOY" : None, "START_DOW" : None, "START_YEAR" : None,
  1209. "START_MONTH" : None, "START_WEEK" : None, "START_DAY" : None,
  1210. "START_HOUR" : None, "START_MINUTE" : None, "START_SECOND" : None,
  1211. "END_DOY" : None, "END_DOW" : None, "END_YEAR" : None,
  1212. "END_MONTH" : None, "END_WEEK" : None, "END_DAY" : None,
  1213. "END_HOUR" : None, "END_MINUTE" : None, "END_SECOND" : None,
  1214. "START_DATE" : None, "START_DATETIME" : None, "START_TIME" : None,
  1215. "END_DATE" : None, "END_DATETIME" : None, "END_TIME" : None}
  1216. # Compute temporal function only for maps with absolute time reference.
  1217. if map.is_time_absolute:
  1218. # Get datetime of map.
  1219. start, end = map.get_absolute_time()
  1220. # Compute DOY via time deltas.
  1221. yearstart = datetime(start.year, 1, 1)
  1222. yearend = datetime(end.year, 1, 1)
  1223. deltastart = start - yearstart
  1224. deltaend = end - yearend
  1225. # Evaluate datetime objects and fill in into dict.
  1226. tvardict["START_DOY"] = deltastart.days + 1
  1227. tvardict["START_DOW"] = start.isoweekday()
  1228. tvardict["START_YEAR"] = start.year
  1229. tvardict["START_MONTH"] = start.month
  1230. tvardict["START_WEEK"] = start.isocalendar()[1]
  1231. tvardict["START_DAY"] = start.day
  1232. tvardict["START_HOUR"] = start.hour
  1233. tvardict["START_MINUTE"] = start.minute
  1234. tvardict["START_SECOND"] = start.second
  1235. tvardict["END_DOY"] = deltaend.days + 1
  1236. tvardict["END_DOW"] = end.isoweekday()
  1237. tvardict["END_YEAR"] = end.year
  1238. tvardict["END_MONTH"] = end.month
  1239. tvardict["END_WEEK"] = end.isocalendar()[1]
  1240. tvardict["END_DAY"] = end.day
  1241. tvardict["END_HOUR"] = end.hour
  1242. tvardict["END_MINUTE"] = end.minute
  1243. tvardict["END_SECOND"] = end.second
  1244. tvardict["START_DATE"] = start.date()
  1245. tvardict["START_DATETIME"] = start
  1246. tvardict["START_TIME"] = start.time()
  1247. tvardict["END_DATE"] = end.date()
  1248. tvardict["END_DATETIME"] = end
  1249. tvardict["END_TIME"] = end.time()
  1250. if not map.is_time_absolute:
  1251. tvardict["START_DATE"] = start.date()
  1252. tvardict["START_DATETIME"] = start
  1253. tvardict["START_TIME"] = start.time()
  1254. tvardict["END_DATE"] = end.date()
  1255. tvardict["END_DATETIME"] = end
  1256. tvardict["END_TIME"] = end.time()
  1257. #core.fatal(_("The temporal functions for map <%s> only supported for absolute"\
  1258. # "time." % (str(map.get_id()))))
  1259. return(tvardict)
  1260. def eval_datetime_str(self, tfuncval, comp, value):
  1261. # Evaluate date object comparison expression.
  1262. if comp == "<":
  1263. boolname = eval(str(tfuncval < value))
  1264. elif comp == ">":
  1265. boolname = eval(str(tfuncval > value))
  1266. elif comp == "==":
  1267. boolname = eval(str(tfuncval == value))
  1268. elif comp == "<=":
  1269. boolname = eval(str(tfuncval <= value))
  1270. elif comp == ">=":
  1271. boolname = eval(str(tfuncval >= value))
  1272. elif comp == "!=":
  1273. boolname = eval(str(tfuncval != value))
  1274. return(boolname)
  1275. def eval_global_var(self, gvar, maplist):
  1276. """! This function evaluates a global variable expression for a map list.
  1277. For example: start_day() > 5 , end_month() == 2.
  1278. @param gvar Object of type GlobalTemporalVar containing temporal.
  1279. @param maplist List of map objects.
  1280. @return List of maps from maplist with added conditional boolean values.
  1281. """
  1282. boollist = []
  1283. # Loop over maps of input map list.
  1284. for map_i in maplist:
  1285. # Get dictionary with temporal variables for the map.
  1286. tfuncdict = self.get_temporal_func_dict(map_i)
  1287. # Get value from global variable.
  1288. value = gvar.value
  1289. # Get comparison operator from global variable, like <, >, <=, >=, ==, !=
  1290. comp_op = gvar.compop
  1291. # Get temporal function name for global variable.
  1292. tfunc = gvar.tfunc.upper()
  1293. # Get value for function name from dictionary.
  1294. tfuncval = tfuncdict[tfunc]
  1295. # Check if value has to be transfered to datetime object for comparison.
  1296. if tfunc in ["START_DATE", "END_DATE"]:
  1297. timeobj = datetime.strptime(value.replace("\"",""), '%Y-%m-%d')
  1298. value = timeobj.date()
  1299. boolname = self.eval_datetime_str(tfuncval, comp_op, value)
  1300. elif tfunc in ["START_TIME", "END_TIME"]:
  1301. timeobj = datetime.strptime(value.replace("\"",""), '%H:%M:%S')
  1302. value = timeobj.time()
  1303. boolname = self.eval_datetime_str(tfuncval, comp_op, value)
  1304. elif tfunc in ["START_DATETIME", "END_DATETIME"]:
  1305. timeobj = datetime.strptime(value.replace("\"",""), '%Y-%m-%d %H:%M:%S')
  1306. value = timeobj
  1307. boolname = self.eval_datetime_str(tfuncval, comp_op, value)
  1308. else:
  1309. boolname = eval(str(tfuncval) + comp_op + str(value))
  1310. # Add conditional boolean value to the map.
  1311. if "condition_value" in dir(map_i):
  1312. map_i.condition_value.append(boolname)
  1313. else:
  1314. map_i.condition_value = boolname
  1315. return(maplist)
  1316. def eval_map_list(self, maplist ,thenlist, topolist = ["EQUAL"]):
  1317. """! This function transfers boolean values from temporal expression
  1318. from one map list to another by their topology. These boolean
  1319. values are added to the maps as condition_value.
  1320. @param maplist List of map objects containing boolean map values.
  1321. @param thenlist List of map objects where the boolean values
  1322. should be added.
  1323. @return List of maps from thenlist with added conditional boolean values.
  1324. """
  1325. # Get topology of then statement map list in relation to the other maplist
  1326. # and assign boolean values of the maplist to the thenlist.
  1327. containlist = self.perform_temporal_selection(thenlist, maplist,
  1328. assign_val = True,
  1329. topolist = topolist)
  1330. # Inverse selection of maps from thenlist and assigning False values.
  1331. excludelist = self.perform_temporal_selection(thenlist, maplist,
  1332. assign_val = True,
  1333. inverse = True,
  1334. topolist = topolist)
  1335. # Combining the selection and inverse selection list.
  1336. resultlist = containlist + excludelist
  1337. return(resultlist)
  1338. def build_condition_list(self, tvarexpr, thenlist, topolist = ["EQUAL"]):
  1339. """! This function evaluates temporal variable expressions of a conditional
  1340. expression related to the map list of the then statement.
  1341. Global variables or map lists with booleans are compared to the topology
  1342. of the conclusion map list and a conditional list will be appended to
  1343. every map. It contain the boolean expressions from these comparisons
  1344. and optional operators to combine several temporal expressions, like
  1345. "&&" or "||".
  1346. For example: td(A) == 1 && start_day() > 5 --> [True || False]
  1347. (for one map.condition_value in a then map list)
  1348. @param tvarexpr List of GlobalTemporalVar objects and map lists.
  1349. The list is constructed by the TemporalAlgebraParser
  1350. in order of expression evaluation in the parser.
  1351. @param thenlist Map list object of the conclusion statement.
  1352. It will be compared and evaluated by the conditions.
  1353. @return Map list with conditional values for all temporal expressions.
  1354. @code
  1355. >>> import grass.temporal as tgis
  1356. >>> tgis.init()
  1357. >>> p = tgis.TemporalAlgebraParser()
  1358. >>> # Example with two lists of maps
  1359. >>> # Create two list of maps with equal time stamps
  1360. >>> mapsA = []
  1361. >>> mapsB = []
  1362. >>> for i in range(10):
  1363. ... idA = "a%i@B"%(i)
  1364. ... mapA = tgis.RasterDataset(idA)
  1365. ... idB = "b%i@B"%(i)
  1366. ... mapB = tgis.RasterDataset(idB)
  1367. ... check = mapA.set_absolute_time(datetime(2000,1,i + 1),
  1368. ... datetime(2000,1,i + 2))
  1369. ... check = mapB.set_absolute_time(datetime(2000,1,i + 6),
  1370. ... datetime(2000,1,i + 7))
  1371. ... mapsA.append(mapA)
  1372. ... mapsB.append(mapB)
  1373. >>> mapsA = p.check_stds(mapsA)
  1374. >>> mapsB = p.check_stds(mapsB)
  1375. >>> # Create global expression object.
  1376. >>> gvarA = tgis.GlobalTemporalVar()
  1377. >>> gvarA.tfunc = "start_day"
  1378. >>> gvarA.compop = ">"
  1379. >>> gvarA.value = 5
  1380. >>> gvarB = tgis.GlobalTemporalVar()
  1381. >>> gvarB.tfunc = "start_day"
  1382. >>> gvarB.compop = "<="
  1383. >>> gvarB.value = 8
  1384. >>> gvarOP = tgis.GlobalTemporalVar()
  1385. >>> gvarOP.relationop = "&&"
  1386. >>> gvarOP.topology.append("EQUAL")
  1387. >>> tvarexpr = gvarA
  1388. >>> result = p.build_condition_list(tvarexpr, mapsA)
  1389. >>> for map_i in result:
  1390. ... print(map_i.get_map_id() + ' ' + str(map_i.condition_value))
  1391. a0@B [False]
  1392. a1@B [False]
  1393. a2@B [False]
  1394. a3@B [False]
  1395. a4@B [False]
  1396. a5@B [True]
  1397. a6@B [True]
  1398. a7@B [True]
  1399. a8@B [True]
  1400. a9@B [True]
  1401. >>> tvarexpr = [gvarA, gvarOP, gvarB]
  1402. >>> result = p.build_condition_list(tvarexpr, mapsB)
  1403. >>> for map_i in result:
  1404. ... print(map_i.get_map_id() + ' ' + str(map_i.condition_value))
  1405. b0@B [True, ['EQUAL'], '&&', True]
  1406. b1@B [True, ['EQUAL'], '&&', True]
  1407. b2@B [True, ['EQUAL'], '&&', True]
  1408. b3@B [True, ['EQUAL'], '&&', False]
  1409. b4@B [True, ['EQUAL'], '&&', False]
  1410. b5@B [True, ['EQUAL'], '&&', False]
  1411. b6@B [True, ['EQUAL'], '&&', False]
  1412. b7@B [True, ['EQUAL'], '&&', False]
  1413. b8@B [True, ['EQUAL'], '&&', False]
  1414. b9@B [True, ['EQUAL'], '&&', False]
  1415. @endcode
  1416. """
  1417. # Check if the input expression is a valid single global variable.
  1418. if not isinstance(tvarexpr, list):
  1419. if isinstance(tvarexpr, GlobalTemporalVar):
  1420. if tvarexpr.get_type() == "global":
  1421. # Use method eval_global_var to evaluate expression.
  1422. resultlist = self.eval_global_var(tvarexpr, thenlist)
  1423. else:
  1424. # Check if a given list is a list of maps.
  1425. if all([issubclass(type(ele), AbstractMapDataset) for ele in tvarexpr]):
  1426. # Use method eval_map_list to evaluate map_list in comparison to thenlist.
  1427. resultlist = self.eval_map_list(tvarexpr, thenlist, topolist)
  1428. # Loop through the list, search for map lists or global variables.
  1429. for expr in tvarexpr:
  1430. if isinstance(expr, list):
  1431. if all([issubclass(type(ele), AbstractMapDataset) for ele in expr]):
  1432. # Use method eval_map_list to evaluate map_list
  1433. resultlist = self.eval_map_list(expr, thenlist, topolist)
  1434. else:
  1435. # Recursive function call to look into nested list elements.
  1436. self.build_condition_list(expr, thenlist)
  1437. elif isinstance(expr, GlobalTemporalVar):
  1438. # Use according functions for different global variable types.
  1439. if expr.get_type() == "operator":
  1440. if all(["condition_value" in dir(map_i) for map_i in thenlist]):
  1441. # Add operator string to the condition list.
  1442. [map_i.condition_value.extend(expr.get_type_value()) for map_i in thenlist]
  1443. if expr.get_type() == "global":
  1444. # Use method eval_global_var to evaluate expression.
  1445. resultlist = self.eval_global_var(expr, thenlist)
  1446. # Sort resulting list of maps chronological.
  1447. resultlist = sorted(resultlist, key = AbstractDatasetComparisonKeyStartTime)
  1448. return(resultlist)
  1449. def eval_condition_list(self, maplist, inverse = False):
  1450. """! This function evaluates conditional values of a map list.
  1451. A recursive function is used to evaluate comparison statements
  1452. from left to right in the given conditional list.
  1453. For example: [True, '||', False, '&&', True] -> True
  1454. [True, '||', False, '&&', False] -> False
  1455. [True, '&&', False, '&&', True] -> False
  1456. [False, '||', True, '||', False] -> True
  1457. [False, '&&', True, '&&', True] -> False
  1458. [True, '&&', True, '&&', True] -> True
  1459. [True, '&&', True] -> True
  1460. [True, '&&', False] -> False
  1461. [False, '||', True] -> True
  1462. @param tvarexpr List of GlobalTemporalVar objects and map lists.
  1463. The list is constructed by the TemporalAlgebraParser
  1464. in order of expression evaluation in the parser.
  1465. @return Map list with conditional values for all temporal expressions.
  1466. @code
  1467. >>> import grass.temporal as tgis
  1468. >>> tgis.init()
  1469. >>> p = tgis.TemporalAlgebraParser()
  1470. >>> # Example with two lists of maps
  1471. >>> # Create two list of maps with equal time stamps
  1472. >>> mapsA = []
  1473. >>> mapsB = []
  1474. >>> for i in range(10):
  1475. ... idA = "a%i@B"%(i)
  1476. ... mapA = tgis.RasterDataset(idA)
  1477. ... idB = "b%i@B"%(i)
  1478. ... mapB = tgis.RasterDataset(idB)
  1479. ... check = mapA.set_absolute_time(datetime(2000,1,i + 1),
  1480. ... datetime(2000,1,i + 2))
  1481. ... check = mapB.set_absolute_time(datetime(2000,1,i + 6),
  1482. ... datetime(2000,1,i + 7))
  1483. ... mapsA.append(mapA)
  1484. ... mapsB.append(mapB)
  1485. >>> mapsA = p.check_stds(mapsA)
  1486. >>> mapsB = p.check_stds(mapsB)
  1487. >>> # Create global expression object.
  1488. >>> gvarA = tgis.GlobalTemporalVar()
  1489. >>> gvarA.tfunc = "start_day"
  1490. >>> gvarA.compop = ">"
  1491. >>> gvarA.value = 5
  1492. >>> gvarB = tgis.GlobalTemporalVar()
  1493. >>> gvarB.tfunc = "start_day"
  1494. >>> gvarB.compop = "<="
  1495. >>> gvarB.value = 8
  1496. >>> gvarOP = tgis.GlobalTemporalVar()
  1497. >>> gvarOP.relationop = "&&"
  1498. >>> gvarOP.topology.append("EQUAL")
  1499. >>> tvarexpr = [mapsA, gvarOP,gvarA]
  1500. @endcode
  1501. """
  1502. def recurse_compare(conditionlist):
  1503. for ele in conditionlist:
  1504. if ele == '||':
  1505. ele_index = conditionlist.index(ele)
  1506. topolist = conditionlist.pop(ele_index -1)
  1507. right = conditionlist.pop(ele_index)
  1508. left = conditionlist.pop(ele_index - 2)
  1509. if any([left, right]):
  1510. result = True
  1511. else:
  1512. result = False
  1513. conditionlist[ele_index - 2] = result
  1514. recurse_compare(conditionlist)
  1515. if ele == '&&':
  1516. ele_index = conditionlist.index(ele)
  1517. topolist = conditionlist.pop(ele_index -1)
  1518. right = conditionlist.pop(ele_index)
  1519. left = conditionlist.pop(ele_index - 2)
  1520. if all([left, right]):
  1521. result = True
  1522. else:
  1523. result = False
  1524. conditionlist[ele_index - 2] = result
  1525. recurse_compare(conditionlist)
  1526. resultlist = conditionlist
  1527. return(resultlist)
  1528. resultlist = []
  1529. inverselist = []
  1530. for map_i in maplist:
  1531. if "condition_value" in dir(map_i):
  1532. # Get condition values from map object.
  1533. conditionlist = map_i.condition_value
  1534. #print(map_i.get_map_id() + ' ' + str(map_i.condition_value))
  1535. # Evaluate conditions in list with recursive function.
  1536. resultbool = recurse_compare(conditionlist)
  1537. # Set conditional value of map to resulting boolean.
  1538. map_i.condition_value = resultbool
  1539. # Add all maps that fulfill the conditions to result list.
  1540. if resultbool[0]:
  1541. resultlist.append(map_i)
  1542. else:
  1543. inverselist.append(map_i)
  1544. #print(map_i.get_map_id() + ' ' + str(map_i.condition_value))
  1545. if inverse:
  1546. return(inverselist)
  1547. else:
  1548. return(resultlist)
  1549. ###########################################################################
  1550. def p_statement_assign(self, t):
  1551. # The expression should always return a list of maps.
  1552. """
  1553. statement : stds EQUALS expr
  1554. """
  1555. if self.run:
  1556. resultstds = open_new_space_time_dataset(t[1], self.stdstype, \
  1557. self.temporaltype, "", "", \
  1558. 'mean', None, \
  1559. overwrite = grass.overwrite())
  1560. if isinstance(t[3], list):
  1561. num = len(t[3])
  1562. count = 0
  1563. if num > 0:
  1564. dbif, connected = init_dbif(None)
  1565. for map in t[3]:
  1566. map.select(dbif=dbif)
  1567. #map.update()
  1568. resultstds.register_map(map, dbif=dbif)
  1569. count += 1
  1570. if count % 10 == 0:
  1571. self.msgr.percent(count, num, 1)
  1572. resultstds.update_from_registered_maps(dbif=dbif)
  1573. if connected:
  1574. dbif.close()
  1575. t[0] = t[3]
  1576. if self.debug:
  1577. print t[1], "=", t[3]
  1578. t[0] = t[3]
  1579. def p_stds_1(self, t):
  1580. # Definition of a space time dataset
  1581. """
  1582. stds : NAME
  1583. """
  1584. t[0] = t[1]
  1585. def p_paren_expr(self, t):
  1586. """ expr : LPAREN expr RPAREN"""
  1587. t[0] = t[2]
  1588. def p_number(self,t):
  1589. """number : INT
  1590. | FLOAT
  1591. """
  1592. t[0] = t[1]
  1593. def p_t_hash(self,t):
  1594. """
  1595. t_hash_var : stds HASH stds
  1596. | stds HASH expr
  1597. | expr HASH stds
  1598. | expr HASH expr
  1599. """
  1600. if self.run:
  1601. maplistA = self.check_stds(t[1])
  1602. maplistB = self.check_stds(t[3])
  1603. resultlist = self.get_temporal_topo_list(maplistA, maplistB,
  1604. count_map = True)
  1605. t[0] = resultlist
  1606. def p_t_hash2(self,t):
  1607. """
  1608. t_hash_var : stds T_HASH_OPERATOR stds
  1609. | stds T_HASH_OPERATOR expr
  1610. | expr T_HASH_OPERATOR stds
  1611. | expr T_HASH_OPERATOR expr
  1612. """
  1613. if self.run:
  1614. maplistA = self.check_stds(t[1])
  1615. maplistB = self.check_stds(t[3])
  1616. topolist = self.eval_toperator(t[2])[0]
  1617. resultlist = self.get_temporal_topo_list(maplistA, maplistB, topolist,
  1618. count_map = True)
  1619. t[0] = resultlist
  1620. def p_t_td_var(self, t):
  1621. """
  1622. t_td_var : TD LPAREN stds RPAREN
  1623. | TD LPAREN expr RPAREN
  1624. """
  1625. if self.run:
  1626. maplist = self.check_stds(t[3])
  1627. for map_i in maplist:
  1628. if map_i.is_time_absolute:
  1629. start, end = map_i.get_absolute_time()
  1630. if end != None:
  1631. td = time_delta_to_relative_time(end - start)
  1632. else:
  1633. start, end, unit = current.get_relative_time()
  1634. if end != None:
  1635. td = end - start
  1636. if "map_value" in dir(map_i):
  1637. gvar = GlobalTemporalVar()
  1638. gvar.td = td
  1639. map_i.map_value.append(gvar)
  1640. else:
  1641. map_i.map_value = gvar
  1642. t[0] = maplist
  1643. if self.debug:
  1644. print "td(" + t[3] + ")"
  1645. t[0] = "td(" + t[3] + ")"
  1646. def p_t_time_var(self, t):
  1647. # Temporal variables that return a double or integer value
  1648. """
  1649. t_var : START_DOY
  1650. | START_DOW
  1651. | START_YEAR
  1652. | START_MONTH
  1653. | START_WEEK
  1654. | START_DAY
  1655. | START_HOUR
  1656. | START_MINUTE
  1657. | START_SECOND
  1658. | END_DOY
  1659. | END_DOW
  1660. | END_YEAR
  1661. | END_MONTH
  1662. | END_WEEK
  1663. | END_DAY
  1664. | END_HOUR
  1665. | END_MINUTE
  1666. | END_SECOND
  1667. """
  1668. t[0] = t[1]
  1669. def p_compare_op(self, t):
  1670. # Compare operators that are supported for temporal expressions
  1671. """
  1672. comp_op : CEQUALS
  1673. | UNEQUALS
  1674. | LOWER
  1675. | LOWER_EQUALS
  1676. | GREATER
  1677. | GREATER_EQUALS
  1678. """
  1679. t[0] = t[1]
  1680. def p_t_var_expr(self, t):
  1681. # Examples:
  1682. # start_month() > 2
  1683. # start_day() < 14
  1684. # start_day() < start_month()
  1685. # td() < 31
  1686. """
  1687. t_var_expr : t_var LPAREN RPAREN comp_op number
  1688. | t_var LPAREN RPAREN comp_op t_var
  1689. | t_td_var comp_op number
  1690. | t_td_var comp_op t_var
  1691. | t_hash_var comp_op number
  1692. | t_hash_var comp_op t_var
  1693. """
  1694. if self.run:
  1695. if len(t) == 4:
  1696. maplist = self.check_stds(t[1])
  1697. comp_op = t[2]
  1698. for map_i in maplist:
  1699. for obj in map_i.map_value:
  1700. if isinstance(obj, GlobalTemporalVar):
  1701. td = obj.td
  1702. boolnum = eval(str(td) + comp_op + str(t[3]))
  1703. gvar = GlobalTemporalVar()
  1704. gvar.boolean = boolnum
  1705. if obj.get_type() == "timediff":
  1706. index = map_i.map_value.index(obj)
  1707. map_i.map_value[index] = gvar
  1708. t[0] = maplist
  1709. if len(t) == 6:
  1710. if isinstance(t[1], GlobalTemporalVar):
  1711. pass
  1712. gvar = GlobalTemporalVar()
  1713. gvar.tfunc = t[1]
  1714. gvar.compop = t[4]
  1715. gvar.value = t[5]
  1716. t[0] = gvar
  1717. if self.debug:
  1718. if len(t) == 6:
  1719. print t[1], t[4], t[5]
  1720. if len(t) == 4:
  1721. print t[1], t[2], t[3]
  1722. t[0] = True
  1723. def p_t_var_expr_time1(self, t):
  1724. # Examples:
  1725. # start_time() == "12:30:00"
  1726. # start_date() <= "2001-01-01"
  1727. # start_datetime() > "2001-01-01 12:30:00"
  1728. """
  1729. t_var_expr : START_TIME LPAREN RPAREN comp_op TIME
  1730. | START_DATE LPAREN RPAREN comp_op DATE
  1731. | START_DATETIME LPAREN RPAREN comp_op DATETIME
  1732. | END_TIME LPAREN RPAREN comp_op TIME
  1733. | END_DATE LPAREN RPAREN comp_op DATE
  1734. | END_DATETIME LPAREN RPAREN comp_op DATETIME
  1735. """
  1736. if self.run:
  1737. gvar = GlobalTemporalVar()
  1738. gvar.tfunc = t[1]
  1739. gvar.compop = t[4]
  1740. gvar.value = t[5]
  1741. t[0] = gvar
  1742. if self.debug:
  1743. print t[1], t[4], t[5]
  1744. t[0] = True
  1745. def p_t_var_expr_time2(self, t):
  1746. """
  1747. t_var_expr : TIME comp_op START_TIME LPAREN RPAREN
  1748. | DATE comp_op START_DATE LPAREN RPAREN
  1749. | DATETIME comp_op START_DATETIME LPAREN RPAREN
  1750. | TIME comp_op END_TIME LPAREN RPAREN
  1751. | DATE comp_op END_DATE LPAREN RPAREN
  1752. | DATETIME comp_op END_DATETIME LPAREN RPAREN
  1753. """
  1754. if self.run:
  1755. reverseop = {"<" : ">", ">" : "<", "<=" : ">=", ">=" : "<=",
  1756. "==" : "==", "!=" : "!="}
  1757. gvar = GlobalTemporalVar()
  1758. gvar.tfunc = t[3]
  1759. gvar.compop = reverseop[t[2]]
  1760. gvar.value = t[1]
  1761. t[0] = gvar
  1762. if self.debug:
  1763. print(t[4])
  1764. print t[1], t[4], t[5]
  1765. t[0] = True
  1766. def p_t_var_expr_comp(self, t):
  1767. """
  1768. t_var_expr : t_var_expr AND AND t_var_expr
  1769. | t_var_expr OR OR t_var_expr
  1770. """
  1771. if self.run:
  1772. tvarexprA = t[1]
  1773. tvarexprB = t[4]
  1774. operator = GlobalTemporalVar()
  1775. operator.relationop = t[2] + t[3]
  1776. operator.topology.append("EQUAL")
  1777. resultlist = []
  1778. resultlist.append(tvarexprA)
  1779. resultlist.append(operator)
  1780. resultlist.append(tvarexprB)
  1781. t[0] = resultlist
  1782. if self.debug:
  1783. print t[1], t[2] + t[3], t[4]
  1784. t[0] = True
  1785. def p_t_var_expr_comp_op(self, t):
  1786. """
  1787. t_var_expr : t_var_expr T_COMP_OPERATOR t_var_expr
  1788. """
  1789. if self.run:
  1790. tvarexprA = t[1]
  1791. tvarexprB = t[3]
  1792. operator = GlobalTemporalVar()
  1793. toperator = self.eval_toperator(t[2])[0]
  1794. relationop = toperator[2]
  1795. relations = toperator[0]
  1796. operator.relationop = relationop
  1797. operator.topology.extend(relations)
  1798. resultlist = []
  1799. resultlist.append(tvarexprA)
  1800. resultlist.append(operator)
  1801. resultlist.append(tvarexprB)
  1802. t[0] = resultlist
  1803. if self.debug:
  1804. print t[1], t[2], t[3]
  1805. t[0] = True
  1806. def p_expr_t_select(self, t):
  1807. # Temporal equal selection
  1808. # The temporal topology relation equals is implicit
  1809. # Examples:
  1810. # A : B # Select the part of A that is temporally equal B
  1811. """
  1812. expr : stds T_SELECT stds
  1813. | expr T_SELECT stds
  1814. | stds T_SELECT expr
  1815. | expr T_SELECT expr
  1816. """
  1817. if self.run:
  1818. # Setup database connection.
  1819. # Check input stds.
  1820. maplistA = self.check_stds(t[1])
  1821. maplistB = self.check_stds(t[3])
  1822. # Perform selection.
  1823. selectlist = self.perform_temporal_selection(maplistA, maplistB)
  1824. # Return map list.
  1825. t[0] = selectlist
  1826. if self.debug:
  1827. print t[1] + "* = ", t[1], t[2], t[3]
  1828. t[0] = t[1] + "*"
  1829. def p_expr_t_not_select(self, t):
  1830. # Temporal equal selection
  1831. # The temporal topology relation equals is implicit
  1832. # Examples:
  1833. # A !: B # Select the part of A that is temporally unequal to B
  1834. """
  1835. expr : stds T_NOT_SELECT stds
  1836. | expr T_NOT_SELECT stds
  1837. | stds T_NOT_SELECT expr
  1838. | expr T_NOT_SELECT expr
  1839. """
  1840. if self.run:
  1841. # Check input stds.
  1842. maplistA = self.check_stds(t[1])
  1843. maplistB = self.check_stds(t[3])
  1844. # Perform negative selection.
  1845. selectlist = self.perform_temporal_selection(maplistA, maplistB,
  1846. inverse = True)
  1847. # Return map list.
  1848. t[0] = selectlist
  1849. if self.debug:
  1850. print t[1] + "* = ", t[1], t[2], t[3]
  1851. t[0] = t[1] + "*"
  1852. def p_expr_t_select_operator(self, t):
  1853. # Temporal equal selection
  1854. # The temporal topology relation equals is implicit
  1855. # Examples:
  1856. # A {!:} B # Select the part of A that is temporally unequal to B
  1857. # A {:} B # Select the part of A that is temporally equal B
  1858. # A {equals, !:} B # Select the part of A that is temporally unequal to B
  1859. # A {during, !:} B # Select the part of A that is temporally not during B
  1860. # A {overlaps, :} B # Select the part of A that temporally overlaps B
  1861. # A {overlaps|equals, :} B # Select the part of A that temporally overlaps or equals B
  1862. """
  1863. expr : stds T_SELECT_OPERATOR stds
  1864. | expr T_SELECT_OPERATOR stds
  1865. | stds T_SELECT_OPERATOR expr
  1866. | expr T_SELECT_OPERATOR expr
  1867. """
  1868. if self.run:
  1869. # Check input stds.
  1870. maplistA = self.check_stds(t[1])
  1871. maplistB = self.check_stds(t[3])
  1872. # Evaluate temporal operator.
  1873. operators = self.eval_toperator(t[2])
  1874. # Check for negative selection.
  1875. if operators[2] == "!:":
  1876. negation = True
  1877. else:
  1878. negation = False
  1879. # Perform selection.
  1880. selectlist = self.perform_temporal_selection(maplistA, maplistB,
  1881. topolist = operators[0], inverse = negation)
  1882. selectlist = self.set_granularity(selectlist, maplistB, operators[1],
  1883. operators[0])
  1884. # Return map list.
  1885. t[0] = selectlist
  1886. if self.debug:
  1887. print t[1] + "* = ", t[1], t[2], t[3]
  1888. t[0] = t[1] + "*"
  1889. def p_expr_condition_if(self, t):
  1890. # Examples
  1891. # if( start_date() < "2005-06-01", A:B)
  1892. """
  1893. expr : IF LPAREN t_var_expr COMMA stds RPAREN
  1894. | IF LPAREN t_var_expr COMMA expr RPAREN
  1895. """
  1896. if self.run:
  1897. # Get stds/map list of then statement.
  1898. thenlist = self.check_stds(t[5])
  1899. # Get temporal conditional statement.
  1900. tvarexpr = t[3]
  1901. thencond = self.build_condition_list(tvarexpr, thenlist)
  1902. thenresult = self.eval_condition_list(thencond)
  1903. # Clear the map and conditional values of the map list.
  1904. resultlist = self.check_stds(thenresult, clear = True)
  1905. # Return resulting map list.
  1906. t[0] = resultlist
  1907. if self.debug:
  1908. print t[5] + "* = ", "if condition", t[3], ' then ', t[5]
  1909. t[0] = t[5] + "*"
  1910. def p_expr_condition_if_relation(self, t):
  1911. # Examples
  1912. # if({equal} start_date() < "2005-06-01", A:B)
  1913. """
  1914. expr : IF LPAREN T_REL_OPERATOR COMMA t_var_expr COMMA stds RPAREN
  1915. | IF LPAREN T_REL_OPERATOR COMMA t_var_expr COMMA expr RPAREN
  1916. """
  1917. if self.run:
  1918. # Get stds/map list of then statement.
  1919. thenlist = self.check_stds(t[7])
  1920. # Get temporal conditional statement.
  1921. tvarexpr = t[5]
  1922. topolist = self.eval_toperator(t[3])[0]
  1923. thencond = self.build_condition_list(tvarexpr, thenlist, topolist)
  1924. thenresult = self.eval_condition_list(thencond)
  1925. # Clear the map and conditional values of the map list.
  1926. resultlist = self.check_stds(thenresult, clear = True)
  1927. # Return resulting map list.
  1928. t[0] = resultlist
  1929. if self.debug:
  1930. print t[5] + "* = ", "if condition", t[3], ' then ', t[5]
  1931. t[0] = t[5] + "*"
  1932. def p_expr_condition_elif(self, t):
  1933. # Examples
  1934. # if( start_date() < "2005-06-01", if(start_time() < "12:30:00", A:B), A!:B)
  1935. """
  1936. expr : IF LPAREN t_var_expr COMMA stds COMMA stds RPAREN
  1937. | IF LPAREN t_var_expr COMMA stds COMMA expr RPAREN
  1938. | IF LPAREN t_var_expr COMMA expr COMMA stds RPAREN
  1939. | IF LPAREN t_var_expr COMMA expr COMMA expr RPAREN
  1940. """
  1941. if self.run:
  1942. # Get stds/map list of then statement.
  1943. thenlist = self.check_stds(t[5])
  1944. elselist = self.check_stds(t[7])
  1945. # Get temporal conditional statement for then and else expressions.
  1946. tvarexpr = t[3]
  1947. thencond = self.build_condition_list(tvarexpr, thenlist)
  1948. thenresult = self.eval_condition_list(thencond)
  1949. elsecond = self.build_condition_list(tvarexpr, elselist)
  1950. elseresult = self.eval_condition_list(elsecond, inverse = True)
  1951. # Combine and sort else and then statement to result map list.
  1952. combilist = thenresult + elseresult
  1953. resultlist = sorted(combilist, key = AbstractDatasetComparisonKeyStartTime)
  1954. # Clear the map and conditional values of the map list.
  1955. resultlist = self.check_stds(resultlist, clear = True)
  1956. # Return resulting map list.
  1957. t[0] = resultlist
  1958. if self.debug:
  1959. print t[5] + "* = ", "if condition", t[3], " then ", t[5], ' else ', t[7]
  1960. t[0] = t[5] + "*"
  1961. def p_expr_condition_elif_relation(self, t):
  1962. # Examples
  1963. # if({equal}, start_date() < "2005-06-01", if(start_time() < "12:30:00", A:B), A!:B)
  1964. # The then and else statement using the same topological relationships.
  1965. # Feature request: Independent relationships for then and else to conditions.
  1966. """
  1967. expr : IF LPAREN T_REL_OPERATOR COMMA t_var_expr COMMA stds COMMA stds RPAREN
  1968. | IF LPAREN T_REL_OPERATOR COMMA t_var_expr COMMA stds COMMA expr RPAREN
  1969. | IF LPAREN T_REL_OPERATOR COMMA t_var_expr COMMA expr COMMA stds RPAREN
  1970. | IF LPAREN T_REL_OPERATOR COMMA t_var_expr COMMA expr COMMA expr RPAREN
  1971. """
  1972. if self.run:
  1973. # Get stds/map list of then statement.
  1974. thenlist = self.check_stds(t[7])
  1975. elselist = self.check_stds(t[9])
  1976. # Get temporal conditional statement.
  1977. tvarexpr = t[5]
  1978. topolist = self.eval_toperator(t[3])[0]
  1979. thencond = self.build_condition_list(tvarexpr, thenlist, topolist)
  1980. thenresult = self.eval_condition_list(thencond)
  1981. elsecond = self.build_condition_list(tvarexpr, elselist, topolist)
  1982. elseresult = self.eval_condition_list(elsecond, inverse = True)
  1983. # Combine and sort else and then statement to result map list.
  1984. combilist = thenresult + elseresult
  1985. resultlist = sorted(combilist, key = AbstractDatasetComparisonKeyStartTime)
  1986. # Clear the map and conditional values of the map list.
  1987. resultlist = self.check_stds(resultlist, clear = True)
  1988. # Return resulting map list.
  1989. t[0] = resultlist
  1990. if self.debug:
  1991. if t[5]:
  1992. print t[7], "* = ", "if condition", t[5], " then ", t[7], ' else ', t[9]
  1993. t[0] = str(t[7])
  1994. else:
  1995. print t[9], "* = ", "if condition", t[5], " then ", t[7], ' else ', t[9]
  1996. t[0] = str(t[9])
  1997. def p_expr_t_buff(self, t):
  1998. # Examples
  1999. # buff_t(A : B, "10 minutes") # Select the part of A that is temporally
  2000. # equal to B and create a buffer of 10 minutes around
  2001. """
  2002. expr : BUFF_T LPAREN stds COMMA QUOTE number NAME QUOTE RPAREN
  2003. | BUFF_T LPAREN expr COMMA QUOTE number NAME QUOTE RPAREN
  2004. | BUFF_T LPAREN stds COMMA number RPAREN
  2005. | BUFF_T LPAREN expr COMMA number RPAREN
  2006. """
  2007. if self.run:
  2008. # Check input stds.
  2009. bufflist = self.check_stds(t[3])
  2010. for map in bufflist:
  2011. # Get increment format.
  2012. if len(t) == 10:
  2013. increment = str(t[6]) + " " + t[7]
  2014. elif len(t) == 7:
  2015. increment = str(t[5])
  2016. # Perform buffering.
  2017. map.temporal_buffer(increment)
  2018. t[0] = bufflist
  2019. if self.debug:
  2020. if len(t) == 10:
  2021. print t[3] + "* = buff_t(", t[3], "," , '"', t[6], t[7], '"', ")"
  2022. elif len(t) == 7:
  2023. print t[3] + "* = buff_t(", t[3], ",", t[5], ")"
  2024. t[0] = t[3] + "*"
  2025. def p_expr_t_snap(self, t):
  2026. # Examples
  2027. # tsnap(A : B) # Snap the maps of A temporally.
  2028. """
  2029. expr : TSNAP LPAREN stds RPAREN
  2030. | TSNAP LPAREN expr RPAREN
  2031. """
  2032. if self.run:
  2033. # Check input stds.
  2034. maplist = self.check_stds(t[3])
  2035. # Perform snapping.
  2036. snaplist = AbstractSpaceTimeDataset.snap_map_list(maplist)
  2037. t[0] = snaplist
  2038. if self.debug:
  2039. print t[3] + "* = tsnap(", t[3], ")"
  2040. t[0] = t[3] + "*"
  2041. def p_expr_t_shift(self, t):
  2042. # Examples
  2043. # tshift(A : B, "10 minutes") # Shift the selection from A temporally
  2044. # by 10 minutes.
  2045. """
  2046. expr : TSHIFT LPAREN stds COMMA QUOTE number NAME QUOTE RPAREN
  2047. | TSHIFT LPAREN expr COMMA QUOTE number NAME QUOTE RPAREN
  2048. | TSHIFT LPAREN stds COMMA number RPAREN
  2049. | TSHIFT LPAREN expr COMMA number RPAREN
  2050. """
  2051. if self.run:
  2052. # Check input stds.
  2053. maplist = self.check_stds(t[3])
  2054. # Get increment format.
  2055. if len(t) == 10:
  2056. increment = str(t[6]) + " " + t[7]
  2057. elif len(t) == 7:
  2058. increment = str(t[5])
  2059. # Perform shifting.
  2060. shiftlist = AbstractSpaceTimeDataset.shift_map_list(maplist, increment)
  2061. t[0] = shiftlist
  2062. if self.debug:
  2063. if len(t) == 10:
  2064. print t[3] + "* = tshift(", t[3], "," , '"', t[6], t[7], '"', ")"
  2065. elif len(t) == 7:
  2066. print t[3] + "* = tshift(", t[3], ",", t[5], ")"
  2067. t[0] = t[3] + "*"
  2068. # Handle errors.
  2069. def p_error(self, t):
  2070. raise SyntaxError("syntax error on line %d near '%s' expression '%s'" %
  2071. (t.lineno, t.value, self.expression))
  2072. ###############################################################################
  2073. if __name__ == "__main__":
  2074. import doctest
  2075. doctest.testmod()