temporal_algebra.py 120 KB

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