temporal_algebra.py 115 KB

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