temporal_algebra.py 117 KB

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