temporal_algebra.py 126 KB

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