temporal_algebra.py 119 KB

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