temporal_algebra.py 117 KB

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