temporal_algebra.py 92 KB

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