temporal_algebra.py 108 KB

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