temporal_algebra.py 115 KB

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