temporal_algebra.py 126 KB

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