temporal_algebra.py 116 KB

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