temporal_algebra.py 117 KB

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