temporal_algebra.py 118 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884
  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. 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"] = [] # The mapcalc and v.patch module calls
  699. self.process_chain_dict["register"] = [] # Maps that must be registered/updated or inserted in a new STDS
  700. self.process_chain_dict["remove"] = [] # The g.remove module calls
  701. self.process_chain_dict["STDS"] = {} # The STDS that must be created
  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.mapset = get_current_mapset()
  709. self.temporaltype = None
  710. self.msgr = get_tgis_message_interface()
  711. self.dbif = SQLDatabaseInterfaceConnection()
  712. self.dbif.connect()
  713. self.register_null = register_null
  714. self.removable_maps = {}
  715. self.m_mremove = pymod.Module('g.remove')
  716. self.m_copy = pymod.Module('g.copy')
  717. self.nprocs = nprocs
  718. self.use_granularity = False
  719. def __del__(self):
  720. if self.dbif.connected:
  721. self.dbif.close()
  722. def setup_common_granularity(self, expression, stdstype = 'strds', lexer = None):
  723. """Configure the temporal algebra to use the common granularity of all
  724. space time datasets in the expression to generate the map lists.
  725. This function will analyze the expression to detect space time datasets
  726. and computes the common granularity from all granularities of the input space time datasets.
  727. This granularity is then be used to generate the map lists. Hence, all
  728. maps from all STDS will have equidistant temporal extents. The only meaningful
  729. temporal relation is therefore "equal".
  730. :param expression: The algebra expression to analyze
  731. :param lexer: The temporal algebra lexer (select, raster, voxel, vector) that should be used to
  732. parse the expression, default is TemporalAlgebraLexer
  733. :return: True if successful, False otherwise
  734. """
  735. l = lexer
  736. # Split the expression to ignore the left part
  737. expressions = expression.split("=")[1:]
  738. expression = " ".join(expressions)
  739. # Check if spatio-temporal operators are present in the expression
  740. if "{" in expression or "}" in expression:
  741. self.msgr.error(_("Spatio temporal operators are not supported in granularity algebra mode"))
  742. return False
  743. # detect all STDS
  744. if l is None:
  745. l = TemporalAlgebraLexer()
  746. l.build()
  747. l.lexer.input(expression)
  748. name_list = []
  749. tokens = []
  750. count = 0
  751. while True:
  752. tok = l.lexer.token()
  753. if not tok: break
  754. # Ignore map layer
  755. tokens.append(tok.type)
  756. ignore = False
  757. if count > 1:
  758. if tokens[count - 2] == "MAP" or tokens[count - 2] == "TMAP":
  759. ignore = True
  760. if tok.type == "NAME" and ignore == False:
  761. name_list.append(tok.value)
  762. count += 1
  763. grans = []
  764. start_times = []
  765. ttypes = {}
  766. dbif, connected = init_dbif(self.dbif)
  767. for name in name_list:
  768. stds = open_old_stds(name, stdstype, dbif)
  769. # We need valid temporal topology
  770. if stds.check_temporal_topology() is False:
  771. self.msgr.error(_("All input space time datasets must have a valid temporal topology."))
  772. return False
  773. grans.append(stds.get_granularity())
  774. start_times.append(stds.get_temporal_extent_as_tuple()[0])
  775. ttypes[stds.get_temporal_type()] = stds.get_temporal_type()
  776. # Only one temporal type is allowed
  777. if len(ttypes) > 1:
  778. self.msgr.error(_("All input space time datasets must have the same temporal type."))
  779. return False
  780. # Compute the common granularity
  781. if "absolute" in ttypes.keys():
  782. self.granularity = compute_common_absolute_time_granularity(grans, start_times)
  783. else:
  784. self.granularity = compute_common_relative_time_granularity(grans)
  785. self.use_granularity = True
  786. return True
  787. def parse(self, expression, stdstype='strds',
  788. maptype='rast', mapclass=RasterDataset,
  789. basename=None, overwrite=False):
  790. """Parse the algebra expression and run the computation
  791. :param expression:
  792. :param stdstype:
  793. :param maptype:
  794. :param mapclass:
  795. :param basename:
  796. :param overwrite:
  797. :return: The process chain dictionary is dry-run was enabled, None otherwise
  798. """
  799. self.lexer = TemporalAlgebraLexer()
  800. self.lexer.build()
  801. self.parser = yacc.yacc(module=self, debug=self.debug)
  802. self.overwrite = overwrite
  803. self.count = 0
  804. self.stdstype = stdstype
  805. self.maptype = maptype
  806. self.mapclass = mapclass
  807. self.basename = basename
  808. self.expression = expression
  809. self.parser.parse(expression)
  810. if self.dry_run is True:
  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. self.process_chain_dict["remove"].append(m.get_dict())
  1011. if self.dry_run is False:
  1012. m.run()
  1013. def check_stds(self, input, clear=False, stds_type=None, check_type=True):
  1014. """ Check if input space time dataset exist in database and return its map list.
  1015. :param input: Name of space time data set as string or list of maps.
  1016. :param clear: Reset the stored conditional values to empty list.
  1017. :param check_type: Check the type of the space time dataset to match the global stds type
  1018. :param stds_type: The type of the space time dataset to be opened, if not provided
  1019. then self.stdstype will be used
  1020. :return: List of maps.
  1021. """
  1022. if isinstance(input, str):
  1023. # Check for mapset in given stds input.
  1024. if input.find("@") >= 0:
  1025. id_input = input
  1026. else:
  1027. id_input = input + "@" + self.mapset
  1028. # Create empty spacetime dataset.
  1029. if stds_type:
  1030. stds = dataset_factory(stds_type, id_input)
  1031. else:
  1032. stds = dataset_factory(self.stdstype, id_input)
  1033. # Check for occurrence of space time dataset.
  1034. if stds.is_in_db(dbif=self.dbif) == False:
  1035. raise FatalError(_("Space time %s dataset <%s> not found") %
  1036. (stds.get_new_map_instance(None).get_type(), id_input))
  1037. else:
  1038. # Select temporal dataset entry from database.
  1039. stds.select(dbif=self.dbif)
  1040. if self.use_granularity:
  1041. # We create the maplist out of the map array from none-gap objects
  1042. maplist = []
  1043. map_array = stds.get_registered_maps_as_objects_by_granularity(gran=self.granularity,
  1044. dbif=self.dbif)
  1045. for entry in map_array:
  1046. # Ignore gap objects
  1047. if entry[0].get_id() is not None:
  1048. maplist.append(entry[0])
  1049. else:
  1050. maplist = stds.get_registered_maps_as_objects(dbif=self.dbif)
  1051. # Create map_value as empty list item.
  1052. for map_i in maplist:
  1053. if "map_value" not in dir(map_i):
  1054. map_i.map_value = []
  1055. if "condition_value" not in dir(map_i):
  1056. map_i.condition_value = []
  1057. # Set and check global temporal type variable and map.
  1058. if map_i.is_time_absolute() and self.temporaltype == None:
  1059. self.temporaltype = 'absolute'
  1060. elif map_i.is_time_relative() and self.temporaltype == None:
  1061. self.temporaltype = 'relative'
  1062. elif map_i.is_time_absolute() and self.temporaltype == 'relative':
  1063. self.msgr.fatal(_("Wrong temporal type of space time dataset <%s> \
  1064. <%s> time is required") %
  1065. (id_input, self.temporaltype))
  1066. elif map_i.is_time_relative() and self.temporaltype == 'absolute':
  1067. self.msgr.fatal(_("Wrong temporal type of space time dataset <%s> \
  1068. <%s> time is required") %
  1069. (id_input, self.temporaltype))
  1070. elif isinstance(input, self.mapclass):
  1071. # Check if the input is a single map and return it as list with one entry.
  1072. maplist = [input]
  1073. elif isinstance(input, list):
  1074. maplist = input
  1075. # Create map_value as empty list item.
  1076. for map_i in maplist:
  1077. if "map_value" not in dir(map_i):
  1078. map_i.map_value = []
  1079. elif clear:
  1080. map_i.map_value = []
  1081. if "condition_value" not in dir(map_i):
  1082. map_i.condition_value = []
  1083. elif clear:
  1084. map_i.condition_value = []
  1085. else:
  1086. self.msgr.fatal(_("Wrong type of input " + str(input)))
  1087. # We generate a unique map id that will be used
  1088. # in the topology analysis, since the maplist can
  1089. # contain maps with equal map ids
  1090. for map in maplist:
  1091. map.uid = self.generate_map_name()
  1092. if self.debug:
  1093. print(map.get_name(), map.uid, map.get_temporal_extent_as_tuple())
  1094. return(maplist)
  1095. def get_temporal_topo_list(self, maplistA, maplistB = None, topolist = ["EQUAL"],
  1096. assign_val = False, count_map = False, compare_bool = False,
  1097. compop = None, aggregate = None):
  1098. """Build temporal topology for two space time data sets, copy map objects
  1099. for given relation into map list.
  1100. :param maplistA: List of maps.
  1101. :param maplistB: List of maps.
  1102. :param topolist: List of strings of temporal relations.
  1103. :param assign_val: Boolean for assigning a boolean map value based on
  1104. the map_values from the compared map list by
  1105. topological relationships.
  1106. :param count_map: Boolean if the number of topological related maps
  1107. should be returned.
  1108. :param compare_bool: Boolean for comparing boolean map values based on
  1109. related map list and compariosn operator.
  1110. :param compop: Comparison operator, && or ||.
  1111. :param aggregate: Aggregation operator for relation map list, & or |.
  1112. :return: List of maps from maplistA that fulfil the topological relationships
  1113. to maplistB specified in topolist.
  1114. .. code-block:: python
  1115. # Example with two lists of maps
  1116. >>> import grass.temporal as tgis
  1117. >>> tgis.init(True)
  1118. >>> l = tgis.TemporalAlgebraParser()
  1119. >>> # Create two list of maps with equal time stamps
  1120. >>> mapsA = []
  1121. >>> mapsB = []
  1122. >>> for i in range(10):
  1123. ... idA = "a%i@B"%(i)
  1124. ... mapA = tgis.RasterDataset(idA)
  1125. ... mapA.uid = idA
  1126. ... idB = "b%i@B"%(i)
  1127. ... mapB = tgis.RasterDataset(idB)
  1128. ... mapB.uid = idB
  1129. ... check = mapA.set_relative_time(i, i + 1, "months")
  1130. ... check = mapB.set_relative_time(i, i + 1, "months")
  1131. ... mapsA.append(mapA)
  1132. ... mapsB.append(mapB)
  1133. >>> resultlist = l.get_temporal_topo_list(mapsA, mapsB, ['EQUAL'])
  1134. >>> for map in resultlist:
  1135. ... if map.get_equal():
  1136. ... relations = map.get_equal()
  1137. ... print("Map %s has equal relation to map %s"%(map.get_name(),
  1138. ... relations[0].get_name()))
  1139. Map a0 has equal relation to map b0
  1140. Map a1 has equal relation to map b1
  1141. Map a2 has equal relation to map b2
  1142. Map a3 has equal relation to map b3
  1143. Map a4 has equal relation to map b4
  1144. Map a5 has equal relation to map b5
  1145. Map a6 has equal relation to map b6
  1146. Map a7 has equal relation to map b7
  1147. Map a8 has equal relation to map b8
  1148. Map a9 has equal relation to map b9
  1149. >>> resultlist = l.get_temporal_topo_list(mapsA, mapsB, ['DURING'])
  1150. >>> print(resultlist)
  1151. []
  1152. >>> # Create two list of maps with equal time stamps
  1153. >>> mapsA = []
  1154. >>> mapsB = []
  1155. >>> for i in range(10):
  1156. ... idA = "a%i@B"%(i)
  1157. ... mapA = tgis.RasterDataset(idA)
  1158. ... mapA.uid = idA
  1159. ... idB = "b%i@B"%(i)
  1160. ... mapB = tgis.RasterDataset(idB)
  1161. ... mapB.uid = idB
  1162. ... check = mapA.set_relative_time(i, i + 1, "months")
  1163. ... check = mapB.set_relative_time(i, i + 2, "months")
  1164. ... mapsA.append(mapA)
  1165. ... mapsB.append(mapB)
  1166. >>> resultlist = l.get_temporal_topo_list(mapsA, mapsB, ['starts','during'])
  1167. >>> for map in resultlist:
  1168. ... if map.get_starts():
  1169. ... relations = map.get_starts()
  1170. ... print("Map %s has start relation to map %s"%(map.get_name(),
  1171. ... relations[0].get_name()))
  1172. Map a0 has start relation to map b0
  1173. Map a1 has start relation to map b1
  1174. Map a2 has start relation to map b2
  1175. Map a3 has start relation to map b3
  1176. Map a4 has start relation to map b4
  1177. Map a5 has start relation to map b5
  1178. Map a6 has start relation to map b6
  1179. Map a7 has start relation to map b7
  1180. Map a8 has start relation to map b8
  1181. Map a9 has start relation to map b9
  1182. >>> for map in resultlist:
  1183. ... if map.get_during():
  1184. ... relations = map.get_during()
  1185. ... print("Map %s has during relation to map %s"%(map.get_name(),
  1186. ... relations[0].get_name()))
  1187. Map a0 has during relation to map b0
  1188. Map a1 has during relation to map b0
  1189. Map a2 has during relation to map b1
  1190. Map a3 has during relation to map b2
  1191. Map a4 has during relation to map b3
  1192. Map a5 has during relation to map b4
  1193. Map a6 has during relation to map b5
  1194. Map a7 has during relation to map b6
  1195. Map a8 has during relation to map b7
  1196. Map a9 has during relation to map b8
  1197. >>> # Create two list of maps with equal time stamps and map_value method.
  1198. >>> mapsA = []
  1199. >>> mapsB = []
  1200. >>> for i in range(10):
  1201. ... idA = "a%i@B"%(i)
  1202. ... mapA = tgis.RasterDataset(idA)
  1203. ... mapA.uid = idA
  1204. ... idB = "b%i@B"%(i)
  1205. ... mapB = tgis.RasterDataset(idB)
  1206. ... mapB.uid = idB
  1207. ... check = mapA.set_relative_time(i, i + 1, "months")
  1208. ... check = mapB.set_relative_time(i, i + 1, "months")
  1209. ... mapB.map_value = True
  1210. ... mapsA.append(mapA)
  1211. ... mapsB.append(mapB)
  1212. >>> # Create two list of maps with equal time stamps
  1213. >>> mapsA = []
  1214. >>> mapsB = []
  1215. >>> for i in range(10):
  1216. ... idA = "a%i@B"%(i)
  1217. ... mapA = tgis.RasterDataset(idA)
  1218. ... mapA.uid = idA
  1219. ... mapA.map_value = True
  1220. ... idB = "b%i@B"%(i)
  1221. ... mapB = tgis.RasterDataset(idB)
  1222. ... mapB.uid = idB
  1223. ... mapB.map_value = False
  1224. ... check = mapA.set_absolute_time(datetime(2000,1,i+1),
  1225. ... datetime(2000,1,i + 2))
  1226. ... check = mapB.set_absolute_time(datetime(2000,1,i+6),
  1227. ... datetime(2000,1,i + 7))
  1228. ... mapsA.append(mapA)
  1229. ... mapsB.append(mapB)
  1230. >>> resultlist = l.get_temporal_topo_list(mapsA, mapsB)
  1231. >>> for map in resultlist:
  1232. ... print(map.get_id())
  1233. a5@B
  1234. a6@B
  1235. a7@B
  1236. a8@B
  1237. a9@B
  1238. >>> resultlist = l.get_temporal_topo_list(mapsA, mapsB, ['during'])
  1239. >>> for map in resultlist:
  1240. ... print(map.get_id())
  1241. """
  1242. topologylist = ["EQUAL", "FOLLOWS", "PRECEDES", "OVERLAPS", "OVERLAPPED", \
  1243. "DURING", "STARTS", "FINISHES", "CONTAINS", "STARTED", \
  1244. "FINISHED"]
  1245. complementdict = {"EQUAL": "EQUAL", "FOLLOWS" : "PRECEDES",
  1246. "PRECEDES" : "FOLLOWS", "OVERLAPS" : "OVERLAPPED",
  1247. "OVERLAPPED" : "OVERLAPS", "DURING" : "CONTAINS",
  1248. "CONTAINS" : "DURING", "STARTS" : "STARTED",
  1249. "STARTED" : "STARTS", "FINISHES" : "FINISHED",
  1250. "FINISHED" : "FINISHES"}
  1251. resultdict = {}
  1252. # Check if given temporal relation are valid.
  1253. for topo in topolist:
  1254. if topo.upper() not in topologylist:
  1255. raise SyntaxError("Unpermitted temporal relation name '" + topo + "'")
  1256. # Create temporal topology for maplistA to maplistB.
  1257. tb = SpatioTemporalTopologyBuilder()
  1258. # Dictionary with different spatial variables used for topology builder.
  1259. spatialdict = {'strds' : '2D', 'stvds' : '2D', 'str3ds' : '3D'}
  1260. # Build spatial temporal topology
  1261. if self.spatial:
  1262. tb.build(maplistA, maplistB, spatial = spatialdict[self.stdstype])
  1263. else:
  1264. tb.build(maplistA, maplistB)
  1265. # Iterate through maps in maplistA and search for relationships given
  1266. # in topolist.
  1267. for map_i in maplistA:
  1268. tbrelations = map_i.get_temporal_relations()
  1269. if assign_val:
  1270. self.assign_bool_value(map_i, tbrelations, topolist)
  1271. elif compare_bool:
  1272. self.compare_bool_value(map_i, tbrelations, compop, aggregate, topolist)
  1273. for topo in topolist:
  1274. if topo.upper() in tbrelations.keys():
  1275. if count_map:
  1276. relationmaplist = tbrelations[topo.upper()]
  1277. gvar = GlobalTemporalVar()
  1278. gvar.td = len(relationmaplist)
  1279. if "map_value" in dir(map_i):
  1280. map_i.map_value.append(gvar)
  1281. else:
  1282. map_i.map_value = gvar
  1283. # Use unique identifier, since map names may be equal
  1284. resultdict[map_i.uid] = map_i
  1285. resultlist = resultdict.values()
  1286. # Sort list of maps chronological.
  1287. resultlist = sorted(resultlist, key = AbstractDatasetComparisonKeyStartTime)
  1288. return(resultlist)
  1289. def assign_bool_value(self, map_i, tbrelations, topolist = ["EQUAL"]):
  1290. """ Function to assign boolean map value based on the map_values from the
  1291. compared map list by topological relationships.
  1292. :param map_i: Map object with temporal extent.
  1293. :param tbrelations: List of temporal relation to map_i.
  1294. :param topolist: List of strings for given temporal relations.
  1295. :return: Map object with conditional value that has been assigned by
  1296. relation maps that fulfil the topological relationships to
  1297. maplistB specified in topolist.
  1298. """
  1299. condition_value_list = []
  1300. for topo in topolist:
  1301. if topo.upper() in tbrelations.keys():
  1302. #relationmaplist = tbrelations[complementdict[topo.upper()]]
  1303. relationmaplist = tbrelations[topo.upper()]
  1304. for relationmap in relationmaplist:
  1305. for boolean in relationmap.condition_value:
  1306. if isinstance(boolean, bool):
  1307. condition_value_list.append(boolean)
  1308. if self.debug:
  1309. print(str(relationmap.get_temporal_extent_as_tuple()) + str(boolean))
  1310. if all(condition_value_list):
  1311. resultbool = True
  1312. else:
  1313. resultbool = False
  1314. map_i.condition_value = [resultbool]
  1315. return(resultbool)
  1316. def compare_bool_value(self, map_i, tbrelations, compop, aggregate, topolist = ["EQUAL"]):
  1317. """ Function to evaluate two map lists with boolean values by boolean
  1318. comparison operator.
  1319. :param map_i: Map object with temporal extent.
  1320. :param tbrelations: List of temporal relation to map_i.
  1321. :param topolist: List of strings for given temporal relations.
  1322. :param compop: Comparison operator, && or ||.
  1323. :param aggregate: Aggregation operator for relation map list, & or |.
  1324. :return: Map object with conditional value that has been evaluated by
  1325. comparison operators.
  1326. """
  1327. # Build conditional list with elements from related maps and given relation operator.
  1328. leftbool = map_i.condition_value[0]
  1329. condition_value_list = [leftbool]
  1330. count = 0
  1331. for topo in topolist:
  1332. if topo.upper() in tbrelations.keys():
  1333. relationmaplist = tbrelations[topo.upper()]
  1334. if count == 0:
  1335. condition_value_list.append(compop[0])
  1336. condition_value_list.append('(')
  1337. for relationmap in relationmaplist:
  1338. for boolean in relationmap.condition_value:
  1339. if isinstance(boolean, bool):
  1340. if count > 0:
  1341. condition_value_list.append(aggregate)
  1342. condition_value_list.append(boolean)
  1343. count = count + 1
  1344. if count > 0:
  1345. condition_value_list.append(')')
  1346. # Convert conditional list to concatenated string and evaluate booleans.
  1347. condition_value_str = ''.join(map(str, condition_value_list))
  1348. if self.debug:
  1349. print(condition_value_str)
  1350. resultbool = eval(condition_value_str)
  1351. if self.debug:
  1352. print(resultbool)
  1353. # Add boolean value to result list.
  1354. map_i.condition_value = [resultbool]
  1355. return(resultbool)
  1356. def eval_toperator(self, operator, optype = 'relation'):
  1357. """This function evaluates a string containing temporal operations.
  1358. :param operator: String of temporal operations, e.g. {!=,equal|during,l}.
  1359. :param optype: String to define operator type.
  1360. :return :List of temporal relations (equal, during), the given function
  1361. (!:) and the interval/instances (l).
  1362. .. code-block:: python
  1363. >>> import grass.temporal as tgis
  1364. >>> tgis.init()
  1365. >>> p = tgis.TemporalOperatorParser()
  1366. >>> operator = "{+, during}"
  1367. >>> p.parse(operator, optype = 'raster')
  1368. >>> print((p.relations, p.temporal, p.function))
  1369. (['during'], 'l', '+')
  1370. """
  1371. p = TemporalOperatorParser()
  1372. p.parse(operator, optype)
  1373. p.relations = [rel.upper() for rel in p.relations]
  1374. return(p.relations, p.temporal, p.function, p.aggregate)
  1375. def perform_temporal_selection(self, maplistA, maplistB, topolist = ["EQUAL"],
  1376. inverse = False, assign_val = False):
  1377. """This function performs temporal selection operation.
  1378. :param maplistA: List of maps representing the left side of a temporal
  1379. expression.
  1380. :param maplistB: List of maps representing the right side of a temporal
  1381. expression.
  1382. :param topolist: List of strings of temporal relations.
  1383. :param inverse: Boolean value that specifies if the selection should be
  1384. inverted.
  1385. :param assign_val: Boolean for assigning a boolean map value based on
  1386. the map_values from the compared map list by
  1387. topological relationships.
  1388. :return: List of selected maps from maplistA.
  1389. .. code-block:: python
  1390. >>> import grass.temporal as tgis
  1391. >>> tgis.init()
  1392. >>> l = tgis.TemporalAlgebraParser()
  1393. >>> # Example with two lists of maps
  1394. >>> # Create two list of maps with equal time stamps
  1395. >>> mapsA = []
  1396. >>> mapsB = []
  1397. >>> for i in range(10):
  1398. ... idA = "a%i@B"%(i)
  1399. ... mapA = tgis.RasterDataset(idA)
  1400. ... mapA.uid = idA
  1401. ... idB = "b%i@B"%(i)
  1402. ... mapB = tgis.RasterDataset(idB)
  1403. ... mapB.uid = idB
  1404. ... check = mapA.set_relative_time(i, i + 1, "months")
  1405. ... check = mapB.set_relative_time(i + 5, i + 6, "months")
  1406. ... mapsA.append(mapA)
  1407. ... mapsB.append(mapB)
  1408. >>> resultlist = l.perform_temporal_selection(mapsA, mapsB, ['EQUAL'],
  1409. ... False)
  1410. >>> for map in resultlist:
  1411. ... if map.get_equal():
  1412. ... relations = map.get_equal()
  1413. ... print("Map %s has equal relation to map %s"%(map.get_name(),
  1414. ... relations[0].get_name()))
  1415. Map a5 has equal relation to map b0
  1416. Map a6 has equal relation to map b1
  1417. Map a7 has equal relation to map b2
  1418. Map a8 has equal relation to map b3
  1419. Map a9 has equal relation to map b4
  1420. >>> resultlist = l.perform_temporal_selection(mapsA, mapsB, ['EQUAL'],
  1421. ... True)
  1422. >>> for map in resultlist:
  1423. ... if not map.get_equal():
  1424. ... print("Map %s has no equal relation to mapset mapsB"%(map.get_name()))
  1425. Map a0 has no equal relation to mapset mapsB
  1426. Map a1 has no equal relation to mapset mapsB
  1427. Map a2 has no equal relation to mapset mapsB
  1428. Map a3 has no equal relation to mapset mapsB
  1429. Map a4 has no equal relation to mapset mapsB
  1430. """
  1431. if not inverse:
  1432. topolist = self.get_temporal_topo_list(maplistA, maplistB, topolist,
  1433. assign_val = assign_val)
  1434. resultlist = topolist
  1435. else:
  1436. topolist = self.get_temporal_topo_list(maplistA, maplistB, topolist,
  1437. assign_val = assign_val)
  1438. resultlist = []
  1439. for map_i in maplistA:
  1440. if map_i not in topolist:
  1441. resultlist.append(map_i)
  1442. #if assign_val:
  1443. # if "condition_value" in dir(map_i):
  1444. # map_i.condition_value.append(False)
  1445. # Sort list of maps chronological.
  1446. resultlist = sorted(resultlist, key = AbstractDatasetComparisonKeyStartTime)
  1447. return(resultlist)
  1448. def set_granularity(self, maplistA, maplistB, toperator = 'l', topolist = ["EQUAL"]):
  1449. """This function sets the temporal extends of a list of maps based on
  1450. another map list.
  1451. :param maplistB: List of maps.
  1452. :param maplistB: List of maps.
  1453. :param toperator: String containing the temporal operator: l, r, d, i, u.
  1454. :param topolist: List of topological relations.
  1455. :return: List of maps with the new temporal extends.
  1456. .. code-block:: python
  1457. >>> import grass.temporal as tgis
  1458. >>> tgis.init()
  1459. >>> p = tgis.TemporalAlgebraParser()
  1460. >>> # Create two list of maps with equal time stamps
  1461. >>> mapsA = []
  1462. >>> mapsB = []
  1463. >>> for i in range(10):
  1464. ... idA = "a%i@B"%(i)
  1465. ... mapA = tgis.RasterDataset(idA)
  1466. ... mapA.uid = idA
  1467. ... idB = "b%i@B"%(i)
  1468. ... mapB = tgis.RasterDataset(idB)
  1469. ... mapB.uid = idB
  1470. ... check = mapA.set_relative_time(i, i + 1, "months")
  1471. ... check = mapB.set_relative_time(i*2, i*2 + 2, "months")
  1472. ... mapsA.append(mapA)
  1473. ... mapsB.append(mapB)
  1474. >>> resultlist = p.set_granularity(mapsA, mapsB, toperator = "u", topolist = ["during"])
  1475. >>> for map in resultlist:
  1476. ... start,end,unit = map.get_relative_time()
  1477. ... print(map.get_id() + ' - start: ' + str(start) + ' end: ' + str(end))
  1478. a1@B - start: 0 end: 2
  1479. a0@B - start: 0 end: 2
  1480. a3@B - start: 2 end: 4
  1481. a2@B - start: 2 end: 4
  1482. a5@B - start: 4 end: 6
  1483. a4@B - start: 4 end: 6
  1484. a7@B - start: 6 end: 8
  1485. a6@B - start: 6 end: 8
  1486. a9@B - start: 8 end: 10
  1487. a8@B - start: 8 end: 10
  1488. """
  1489. topologylist = ["EQUAL", "FOLLOWS", "PRECEDES", "OVERLAPS", "OVERLAPPED",
  1490. "DURING", "STARTS", "FINISHES", "CONTAINS", "STARTED",
  1491. "FINISHED"]
  1492. for topo in topolist:
  1493. if topo.upper() not in topologylist:
  1494. raise SyntaxError("Unpermitted temporal relation name '" + topo + "'")
  1495. # Create temporal topology for maplistA to maplistB.
  1496. tb = SpatioTemporalTopologyBuilder()
  1497. # Dictionary with different spatial variables used for topology builder.
  1498. spatialdict = {'strds' : '2D', 'stvds' : '2D', 'str3ds' : '3D'}
  1499. # Build spatial temporal topology for maplistB to maplistB.
  1500. if self.spatial:
  1501. tb.build(maplistA, maplistB, spatial = spatialdict[self.stdstype])
  1502. else:
  1503. tb.build(maplistA, maplistB)
  1504. resultdict = {}
  1505. # Iterate through maps in maplistA and search for relationships given
  1506. # in topolist.
  1507. for map_i in maplistA:
  1508. tbrelations = map_i.get_temporal_relations()
  1509. map_extent = map_i.get_temporal_extent()
  1510. map_start = map_extent.get_start_time()
  1511. map_end = map_extent.get_end_time()
  1512. unchanged = True
  1513. for topo in topolist:
  1514. if topo.upper() in tbrelations.keys():
  1515. relationmaplist = tbrelations[topo.upper()]
  1516. for relationmap in relationmaplist:
  1517. newextent = None
  1518. if toperator == "i":
  1519. newextent = map_i.temporal_intersection(relationmap)
  1520. elif toperator == "u":
  1521. newextent = map_i.temporal_union(relationmap)
  1522. elif toperator == "d":
  1523. newextent = map_i.temporal_disjoint_union(relationmap)
  1524. elif toperator == "l":
  1525. newextent = map_i.get_temporal_extent()
  1526. elif toperator == "r":
  1527. newextent = relationmap.get_temporal_extent()
  1528. if newextent != None:
  1529. start = newextent.get_start_time()
  1530. end = newextent.get_end_time()
  1531. #print(map_i.get_id() + ' - start: ' + str(start) + ' end: ' + str(end))
  1532. # Track changes in temporal extents of maps.
  1533. if map_start != start or map_end != end :
  1534. unchanged = False
  1535. if map_i.is_time_absolute():
  1536. map_i.set_absolute_time(start, end)
  1537. else:
  1538. relunit = map_i.get_relative_time_unit()
  1539. map_i.set_relative_time(int(start), int(end), relunit)
  1540. resultdict[map_i.get_id()] = map_i
  1541. else:
  1542. if self.debug:
  1543. print('Topologic relation: ' + topo.upper() + ' not found.')
  1544. resultdict[map_i.get_id()] = map_i
  1545. if unchanged == True:
  1546. if self.debug:
  1547. print('Leave temporal extend of result map: ' + map_i.get_map_id() + ' unchanged.')
  1548. resultlist = resultdict.values()
  1549. # Sort list of maps chronological.
  1550. resultlist = sorted(resultlist, key = AbstractDatasetComparisonKeyStartTime)
  1551. # Get relations to maplistB per map in A.
  1552. # Loop over all relations from list
  1553. # temporal extent = map.temporal_intersection(map)
  1554. # if temporal extend is None = delete map.
  1555. return(resultlist)
  1556. def get_temporal_func_dict(self, map):
  1557. """ This function creates a dictionary containing temporal functions for a
  1558. map dataset with time stamp.
  1559. :param map: Map object with time stamps.
  1560. :return: Dictionary with temporal functions for given input map.
  1561. .. code-block:: python
  1562. >>> import grass.temporal as tgis
  1563. >>> import datetime
  1564. >>> tgis.init()
  1565. >>> l = tgis.TemporalAlgebraParser()
  1566. >>> # Example with one list of maps
  1567. >>> # Create one list of maps with equal time stamps
  1568. >>> for i in range(1):
  1569. ... idA = "a%i@B"%(i)
  1570. ... mapA = tgis.RasterDataset(idA)
  1571. ... mapA.uid = idA
  1572. ... check = mapA.set_absolute_time(datetime.datetime(2000,1,1),
  1573. ... datetime.datetime(2000,10,1))
  1574. ... tfuncdict = l.get_temporal_func_dict(mapA)
  1575. >>> print(tfuncdict["START_YEAR"])
  1576. 2000
  1577. >>> print(tfuncdict["START_TIME"])
  1578. 00:00:00
  1579. >>> print(tfuncdict["START_DATE"])
  1580. 2000-01-01
  1581. >>> print(tfuncdict["START_DATETIME"])
  1582. 2000-01-01 00:00:00
  1583. """
  1584. tvardict = {"START_DOY" : None, "START_DOW" : None, "START_YEAR" : None,
  1585. "START_MONTH" : None, "START_WEEK" : None, "START_DAY" : None,
  1586. "START_HOUR" : None, "START_MINUTE" : None, "START_SECOND" : None,
  1587. "END_DOY" : None, "END_DOW" : None, "END_YEAR" : None,
  1588. "END_MONTH" : None, "END_WEEK" : None, "END_DAY" : None,
  1589. "END_HOUR" : None, "END_MINUTE" : None, "END_SECOND" : None,
  1590. "START_DATE" : None, "START_DATETIME" : None, "START_TIME" : None,
  1591. "END_DATE" : None, "END_DATETIME" : None, "END_TIME" : None}
  1592. # Compute temporal function only for maps with absolute time reference.
  1593. if map.is_time_absolute:
  1594. # Get datetime of map.
  1595. start, end = map.get_absolute_time()
  1596. # Compute DOY via time deltas.
  1597. yearstart = datetime(start.year, 1, 1)
  1598. yearend = datetime(end.year, 1, 1)
  1599. deltastart = start - yearstart
  1600. deltaend = end - yearend
  1601. # Evaluate datetime objects and fill in into dict.
  1602. tvardict["START_DOY"] = deltastart.days + 1
  1603. tvardict["START_DOW"] = start.isoweekday()
  1604. tvardict["START_YEAR"] = start.year
  1605. tvardict["START_MONTH"] = start.month
  1606. tvardict["START_WEEK"] = start.isocalendar()[1]
  1607. tvardict["START_DAY"] = start.day
  1608. tvardict["START_HOUR"] = start.hour
  1609. tvardict["START_MINUTE"] = start.minute
  1610. tvardict["START_SECOND"] = start.second
  1611. tvardict["END_DOY"] = deltaend.days + 1
  1612. tvardict["END_DOW"] = end.isoweekday()
  1613. tvardict["END_YEAR"] = end.year
  1614. tvardict["END_MONTH"] = end.month
  1615. tvardict["END_WEEK"] = end.isocalendar()[1]
  1616. tvardict["END_DAY"] = end.day
  1617. tvardict["END_HOUR"] = end.hour
  1618. tvardict["END_MINUTE"] = end.minute
  1619. tvardict["END_SECOND"] = end.second
  1620. tvardict["START_DATE"] = start.date()
  1621. tvardict["START_DATETIME"] = start
  1622. tvardict["START_TIME"] = start.time()
  1623. tvardict["END_DATE"] = end.date()
  1624. tvardict["END_DATETIME"] = end
  1625. tvardict["END_TIME"] = end.time()
  1626. if not map.is_time_absolute:
  1627. tvardict["START_DATE"] = start.date()
  1628. tvardict["START_DATETIME"] = start
  1629. tvardict["START_TIME"] = start.time()
  1630. tvardict["END_DATE"] = end.date()
  1631. tvardict["END_DATETIME"] = end
  1632. tvardict["END_TIME"] = end.time()
  1633. #core.fatal(_("The temporal functions for map <%s> only supported for absolute"\
  1634. # "time." % (str(map.get_id()))))
  1635. return(tvardict)
  1636. def eval_datetime_str(self, tfuncval, comp, value):
  1637. # Evaluate date object comparison expression.
  1638. if 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. elif comp == "!=":
  1649. boolname = eval(str(tfuncval != value))
  1650. return(boolname)
  1651. def eval_global_var(self, gvar, maplist):
  1652. """ This function evaluates a global variable expression for a map list.
  1653. For example: start_day() > 5 , end_month() == 2.
  1654. :param gvar: Object of type GlobalTemporalVar containing temporal.
  1655. :param maplist: List of map objects.
  1656. :return: List of maps from maplist with added conditional boolean values.
  1657. """
  1658. boollist = []
  1659. # Loop over maps of input map list.
  1660. for map_i in maplist:
  1661. # Get dictionary with temporal variables for the map.
  1662. tfuncdict = self.get_temporal_func_dict(map_i)
  1663. # Get value from global variable.
  1664. value = gvar.value
  1665. # Get comparison operator from global variable, like <, >, <=, >=, ==, !=
  1666. comp_op = gvar.compop
  1667. # Get temporal function name for global variable.
  1668. tfunc = gvar.tfunc.upper()
  1669. # Get value for function name from dictionary.
  1670. tfuncval = tfuncdict[tfunc]
  1671. # Check if value has to be transferred to datetime object for comparison.
  1672. if tfunc in ["START_DATE", "END_DATE"]:
  1673. timeobj = datetime.strptime(value.replace("\"",""), '%Y-%m-%d')
  1674. value = timeobj.date()
  1675. boolname = self.eval_datetime_str(tfuncval, comp_op, value)
  1676. elif tfunc in ["START_TIME", "END_TIME"]:
  1677. timeobj = datetime.strptime(value.replace("\"",""), '%H:%M:%S')
  1678. value = timeobj.time()
  1679. boolname = self.eval_datetime_str(tfuncval, comp_op, value)
  1680. elif tfunc in ["START_DATETIME", "END_DATETIME"]:
  1681. timeobj = datetime.strptime(value.replace("\"",""), '%Y-%m-%d %H:%M:%S')
  1682. value = timeobj
  1683. boolname = self.eval_datetime_str(tfuncval, comp_op, value)
  1684. else:
  1685. boolname = eval(str(tfuncval) + comp_op + str(value))
  1686. # Add conditional boolean value to the map.
  1687. if "condition_value" in dir(map_i):
  1688. map_i.condition_value.append(boolname)
  1689. else:
  1690. map_i.condition_value = boolname
  1691. return(maplist)
  1692. def eval_map_list(self, maplist ,thenlist, topolist = ["EQUAL"]):
  1693. """ This function transfers boolean values from temporal expression
  1694. from one map list to another by their topology. These boolean
  1695. values are added to the maps as condition_value.
  1696. :param maplist: List of map objects containing boolean map values.
  1697. :param thenlist: List of map objects where the boolean values
  1698. should be added.
  1699. :return: List of maps from thenlist with added conditional boolean values.
  1700. """
  1701. # Get topology of then statement map list in relation to the other maplist
  1702. # and assign boolean values of the maplist to the thenlist.
  1703. containlist = self.perform_temporal_selection(thenlist, maplist,
  1704. assign_val=True,
  1705. topolist=topolist)
  1706. # Inverse selection of maps from thenlist and assigning False values.
  1707. #excludelist = self.perform_temporal_selection(thenlist, maplist,
  1708. # assign_val = True,
  1709. # inverse = True,
  1710. # topolist = topolist)
  1711. # Combining the selection and inverse selection list.
  1712. resultlist = containlist# + excludelist
  1713. return(resultlist)
  1714. def build_condition_list(self, tvarexpr, thenlist, topolist = ["EQUAL"]):
  1715. """ This function evaluates temporal variable expressions of a conditional
  1716. expression in two steps.
  1717. At first it combines stepwise the single conditions by their relations with LALR.
  1718. In this prossess sub condition map lists will be created which will include
  1719. information of the underlying single conditions. Important: The temporal
  1720. relations between conditions are evaluated by implicit aggregation.
  1721. In the second step the aggregated condition map list will be compared with the
  1722. map list of conclusion statements by the given temporal relation.
  1723. The result is writen as 'condition_value' attribute to the resulting map objects.
  1724. These attribute consists of boolean expressions and operators which can be
  1725. evaluated with the eval_condition_list function.
  1726. [True, '||', False, '&&', True]
  1727. For example: td(A) == 1 && start_day() > 5 --> [True || False]
  1728. (for one map.condition_value in a then map list)
  1729. :param tvarexpr: List of GlobalTemporalVar objects and map lists.
  1730. The list is constructed by the TemporalAlgebraParser
  1731. in order of expression evaluation in the parser.
  1732. :param thenlist: Map list object of the conclusion statement.
  1733. It will be compared and evaluated by the conditions.
  1734. :param topolist: List of temporal relations between the conditions and the
  1735. conclusions.
  1736. :return: Map list with conditional values for all temporal expressions.
  1737. """
  1738. # Evaluate the temporal variable expression and compute the temporal combination
  1739. # of conditions.
  1740. # Check if the input expression is a valid single global variable.
  1741. if isinstance(tvarexpr, GlobalTemporalVar) and tvarexpr.get_type() == "global" :
  1742. # Use method eval_global_var to evaluate expression.
  1743. resultlist = self.eval_global_var(tvarexpr, thenlist)
  1744. # Check if a given list is a list of maps.
  1745. elif all([issubclass(type(ele), AbstractMapDataset) for ele in tvarexpr]):
  1746. # Use method eval_map_list to evaluate map_list in comparison to thenlist.
  1747. resultlist = self.eval_map_list(tvarexpr, thenlist, topolist)
  1748. elif len(tvarexpr) % 2 != 0:
  1749. # Define variables for map list comparisons.
  1750. #self.msgr.fatal("Condition list is not complete. Elements missing")
  1751. for iter in range(len(tvarexpr)):
  1752. expr = tvarexpr[iter]
  1753. operator = tvarexpr[iter +1]
  1754. relexpr = tvarexpr[iter +2]
  1755. if all([issubclass(type(ele), list) for ele in [expr, relexpr]]):
  1756. resultlist = self.get_temporal_topo_list(expr, relexpr)
  1757. # Loop through the list, search for map lists or global variables.
  1758. for expr in tvarexpr:
  1759. if isinstance(expr, list):
  1760. if all([issubclass(type(ele), AbstractMapDataset) for ele in expr]):
  1761. # Use method eval_map_list to evaluate map_list
  1762. resultlist = self.eval_map_list(expr, thenlist, topolist)
  1763. else:
  1764. # Recursive function call to look into nested list elements.
  1765. self.build_condition_list(expr, thenlist)
  1766. elif isinstance(expr, GlobalTemporalVar):
  1767. # Use according functions for different global variable types.
  1768. if expr.get_type() == "operator":
  1769. if all(["condition_value" in dir(map_i) for map_i in thenlist]):
  1770. # Add operator string to the condition list.
  1771. [map_i.condition_value.extend(expr.get_type_value()) for map_i in thenlist]
  1772. if expr.get_type() == "global":
  1773. # Use method eval_global_var to evaluate expression.
  1774. resultlist = self.eval_global_var(expr, thenlist)
  1775. # Sort resulting list of maps chronological.
  1776. resultlist = sorted(resultlist, key = AbstractDatasetComparisonKeyStartTime)
  1777. return(resultlist)
  1778. def eval_condition_list(self, maplist, inverse = False):
  1779. """ This function evaluates conditional values of a map list.
  1780. A recursive function is used to evaluate comparison statements
  1781. from left to right in the given conditional list.
  1782. For example:
  1783. - [True, '||', False, '&&', True] -> True
  1784. - [True, '||', False, '&&', False] -> False
  1785. - [True, '&&', False, '&&', True] -> False
  1786. - [False, '||', True, '||', False] -> True
  1787. - [False, '&&', True, '&&', True] -> False
  1788. - [True, '&&', True, '&&', True] -> True
  1789. - [True, '&&', True] -> True
  1790. - [True, '&&', False] -> False
  1791. - [False, '||', True] -> True
  1792. :param tvarexpr: List of GlobalTemporalVar objects and map lists.
  1793. The list is constructed by the TemporalAlgebraParser
  1794. in order of expression evaluation in the parser.
  1795. :return: Map list with conditional values for all temporal expressions.
  1796. """
  1797. def recurse_compare(conditionlist):
  1798. for ele in conditionlist:
  1799. if ele == '||':
  1800. ele_index = conditionlist.index(ele)
  1801. right = conditionlist.pop(ele_index)
  1802. left = conditionlist.pop(ele_index - 2)
  1803. if any([left, right]):
  1804. result = True
  1805. else:
  1806. result = False
  1807. conditionlist[ele_index - 2] = result
  1808. recurse_compare(conditionlist)
  1809. if ele == '&&':
  1810. ele_index = conditionlist.index(ele)
  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. # Check if the map type and stds type are compatible
  1861. if count == 0:
  1862. maps_stds_type = map_i.get_new_stds_instance(None).get_type()
  1863. map_type = map_i.get_type()
  1864. if maps_stds_type != self.stdstype:
  1865. self.msgr.warning(_("The resulting space time dataset type <%(a)s> is "
  1866. "different from the requested type <%(b)s>"
  1867. %({"a":maps_stds_type, "b":self.stdstype})))
  1868. else:
  1869. map_type_2 = map_i.get_type()
  1870. if map_type != map_type_2:
  1871. self.msgr.fatal(_("Maps that should be registered in the "\
  1872. "resulting space time dataset have different types."))
  1873. count += 1
  1874. # Test if temporal extents was been modified by temporal
  1875. # relation operators (i|r).
  1876. # If it was modified, then the map will be copied
  1877. map_a_extent = map_i.get_temporal_extent_as_tuple()
  1878. map_b = map_i.get_new_instance(map_i.get_id())
  1879. map_b.select(dbif)
  1880. map_b_extent = map_b.get_temporal_extent_as_tuple()
  1881. if map_a_extent != map_b_extent:
  1882. # Create new map with basename
  1883. newident = self.basename + "_" + str(count)
  1884. map_result = map_i.get_new_instance(newident + "@" + self.mapset)
  1885. if map_result.map_exists() and self.overwrite == False:
  1886. self.msgr.fatal("Error raster maps with basename %s exist. "
  1887. "Use --o flag to overwrite existing file"%map_i.get_id())
  1888. map_result.set_temporal_extent(map_i.get_temporal_extent())
  1889. map_result.set_spatial_extent(map_i.get_spatial_extent())
  1890. # Attention we attach a new attribute
  1891. map_result.is_new = True
  1892. register_list.append(map_result)
  1893. # Copy the map
  1894. m = copy.deepcopy(self.m_copy)
  1895. m.flags["overwrite"].value = self.overwrite
  1896. if map_i.get_type() == 'raster':
  1897. m.inputs["raster"].value = map_i.get_id(), newident
  1898. elif map_i.get_type() == 'raster3d':
  1899. m.inputs["raster_3d"].value = map_i.get_id(), newident
  1900. elif map_i.get_type() == 'vector':
  1901. m.inputs["vector"].value = map_i.get_id(), newident
  1902. # Add the process description to the dict
  1903. self.process_chain_dict["processes"].append(m.get_dict())
  1904. if self.dry_run is False:
  1905. process_queue.put(m)
  1906. else:
  1907. register_list.append(map_i)
  1908. # Wait for running processes
  1909. if self.dry_run is False:
  1910. process_queue.wait()
  1911. # Open connection to temporal database.
  1912. # Create result space time dataset based on the map stds type
  1913. if self.dry_run is False:
  1914. resultstds = open_new_stds(t[1],maps_stds_type,
  1915. 'absolute', t[1], t[1],
  1916. 'mean', self.dbif,
  1917. overwrite=self.overwrite)
  1918. for map_i in register_list:
  1919. # Get meta data from grass database.
  1920. map_i.load()
  1921. # Put the map into the process dictionary
  1922. start, end = map_i.get_temporal_extent_as_tuple()
  1923. self.process_chain_dict["register"].append((map_i.get_name(), str(start), str(end)))
  1924. # Check if temporal extents have changed and a new map was created
  1925. if hasattr(map_i, "is_new") is True:
  1926. # Do not register empty maps if not required
  1927. # In case of a null map continue, do not register null maps
  1928. if map_i.get_type() is "raster" or map_i.get_type() is "raster3d":
  1929. if map_i.metadata.get_min() is None and \
  1930. map_i.metadata.get_max() is None:
  1931. if not self.register_null:
  1932. self.removable_maps[map_i.get_name()] = map_i
  1933. continue
  1934. if map_i.is_in_db(dbif) and self.overwrite:
  1935. # Update map in temporal database.
  1936. if self.dry_run is False:
  1937. map_i.update_all(dbif)
  1938. elif map_i.is_in_db(dbif) and self.overwrite is False:
  1939. # Raise error if map exists and no overwrite flag is given.
  1940. self.msgr.fatal("Error map %s exist in temporal database. "
  1941. "Use overwrite flag."%map_i.get_map_id())
  1942. else:
  1943. # Insert map into temporal database.
  1944. if self.dry_run is False:
  1945. map_i.insert(dbif)
  1946. # Register map in result space time dataset.
  1947. if self.dry_run is False:
  1948. success = resultstds.register_map(map_i, dbif)
  1949. if not success:
  1950. self.msgr.warning("Unabe to register map layers "
  1951. "in STDS %s"%(t[1]))
  1952. if self.dry_run is False:
  1953. resultstds.update_from_registered_maps(dbif)
  1954. self.process_chain_dict["STDS"]["name"] = t[1]
  1955. self.process_chain_dict["STDS"]["stdstype"] = self.stdstype
  1956. self.process_chain_dict["STDS"]["temporal_type"] = 'absolute'
  1957. elif num == 0:
  1958. self.msgr.warning("Empty result space time dataset. "
  1959. "No map has been registered in %s"%(t[1]))
  1960. # Open connection to temporal database.
  1961. # Create result space time dataset.
  1962. if self.dry_run is False:
  1963. resultstds = open_new_stds(t[1], self.stdstype,
  1964. 'absolute', t[1], t[1],
  1965. 'mean', dbif,
  1966. overwrite=self.overwrite)
  1967. if connected:
  1968. dbif.close()
  1969. t[0] = t[3]
  1970. else:
  1971. t[0] = t[3]
  1972. if self.debug:
  1973. print(t[1], "=", t[3])
  1974. def p_stds_1(self, t):
  1975. # Definition of a space time dataset
  1976. """
  1977. stds : NAME
  1978. """
  1979. t[0] = t[1]
  1980. def p_paren_expr(self, t):
  1981. """ expr : LPAREN expr RPAREN"""
  1982. t[0] = t[2]
  1983. def p_number(self,t):
  1984. """number : INT
  1985. | FLOAT
  1986. """
  1987. t[0] = t[1]
  1988. def p_expr_strds_function(self, t):
  1989. # Explicitly specify a space time raster dataset
  1990. # R = A : strds(B)
  1991. """
  1992. expr : STRDS LPAREN stds RPAREN
  1993. """
  1994. if self.run:
  1995. t[0] = self.check_stds(t[3], stds_type = "strds", check_type=False)
  1996. else:
  1997. t[0] = t[3]
  1998. if self.debug:
  1999. print("Opening STRDS: ", t[0])
  2000. def p_expr_str3ds_function(self, t):
  2001. # Explicitly specify a space time raster dataset
  2002. # R = A : str3ds(B)
  2003. """
  2004. expr : STR3DS LPAREN stds RPAREN
  2005. """
  2006. if self.run:
  2007. t[0] = self.check_stds(t[3], stds_type = "str3ds", check_type=False)
  2008. else:
  2009. t[0] = t[3]
  2010. if self.debug:
  2011. print("Opening STR3DS: ", t[0])
  2012. def p_expr_stvds_function(self, t):
  2013. # Explicitly specify a space time vector dataset
  2014. # R = A : stvds(B)
  2015. """
  2016. expr : STVDS LPAREN stds RPAREN
  2017. """
  2018. if self.run:
  2019. print(t[3])
  2020. t[0] = self.check_stds(t[3], stds_type = "stvds", check_type=False)
  2021. else:
  2022. t[0] = t[3]
  2023. if self.debug:
  2024. print("Opening STVDS: ", t[0])
  2025. def p_expr_tmap_function(self, t):
  2026. # Add a single map.
  2027. # Only the spatial extent of the map is evaluated.
  2028. # Temporal extent is not existing.
  2029. # Examples:
  2030. # R = tmap(A)
  2031. """
  2032. expr : TMAP LPAREN stds RPAREN
  2033. """
  2034. if self.run:
  2035. # Check input map.
  2036. input = t[3]
  2037. if not isinstance(input, list):
  2038. # Check for mapset in given stds input.
  2039. if input.find("@") >= 0:
  2040. id_input = input
  2041. else:
  2042. id_input = input + "@" + self.mapset
  2043. # Create empty map dataset.
  2044. map_i = dataset_factory(self.maptype, id_input)
  2045. # Check for occurrence of space time dataset.
  2046. if map_i.map_exists() == False:
  2047. raise FatalError(_("%s map <%s> not found in GRASS spatial database") %
  2048. (map_i.get_type(), id_input))
  2049. else:
  2050. # Select dataset entry from database.
  2051. map_i.select(dbif=self.dbif)
  2052. else:
  2053. raise FatalError(_("Wrong map type. TMAP only supports single "
  2054. "maps that are registered in the temporal GRASS database"))
  2055. # Return map object.
  2056. t[0] = [map_i]
  2057. else:
  2058. t[0] = "tmap(", t[3] , ")"
  2059. if self.debug:
  2060. print("tmap(", t[3] , ")")
  2061. def p_expr_tmerge_function(self, t):
  2062. # Merge two maplists of same STDS type into a result map list.
  2063. # Only possible for same data types!
  2064. # Examples:
  2065. # R = merge(A, B)
  2066. """
  2067. expr : MERGE LPAREN stds COMMA stds RPAREN
  2068. | MERGE LPAREN expr COMMA stds RPAREN
  2069. | MERGE LPAREN stds COMMA expr RPAREN
  2070. | MERGE LPAREN expr COMMA expr RPAREN
  2071. """
  2072. if self.run:
  2073. # Check input map.
  2074. maplistA = self.check_stds(t[3])
  2075. maplistB = self.check_stds(t[5])
  2076. # Check empty lists.
  2077. if len(maplistA) == 0 and len(maplistB) == 0:
  2078. self.msgr.warning(_("Merging empty map lists"))
  2079. resultlist = maplistA + maplistB
  2080. elif len(maplistA) == 0:
  2081. self.msgr.message(_("First Map list is empty, can't merge it. Return only last map list"))
  2082. resultlist = maplistB
  2083. elif len(maplistB) == 0:
  2084. self.msgr.message(_("Second Map list is empty, can't merge it. Return only first map list"))
  2085. resultlist = maplistA
  2086. else:
  2087. # Check for identical data types in map lists.
  2088. typeA = maplistA[0].metadata.get_datatype()
  2089. typeB = maplistB[0].metadata.get_datatype()
  2090. if typeA != typeB:
  2091. raise FatalError(_("Space time datasets to merge must have the same temporal type"))
  2092. resultlist = maplistA + maplistB
  2093. # Return map list.
  2094. t[0] = resultlist
  2095. else:
  2096. t[0] = "merge(", t[3], ",", t[5], ")"
  2097. if self.debug:
  2098. print("merge(", t[3], ",", t[5], ")")
  2099. def p_t_hash(self,t):
  2100. """
  2101. t_hash_var : stds HASH stds
  2102. | expr HASH stds
  2103. | stds HASH expr
  2104. | expr HASH expr
  2105. """
  2106. if self.run:
  2107. maplistA = self.check_stds(t[1])
  2108. maplistB = self.check_stds(t[3])
  2109. resultlist = self.get_temporal_topo_list(maplistA, maplistB,
  2110. count_map = True)
  2111. t[0] = resultlist
  2112. def p_t_hash2(self,t):
  2113. """
  2114. t_hash_var : stds T_HASH_OPERATOR stds
  2115. | stds T_HASH_OPERATOR expr
  2116. | expr T_HASH_OPERATOR stds
  2117. | expr T_HASH_OPERATOR expr
  2118. """
  2119. if self.run:
  2120. maplistA = self.check_stds(t[1])
  2121. maplistB = self.check_stds(t[3])
  2122. topolist = self.eval_toperator(t[2], optype='hash')[0]
  2123. resultlist = self.get_temporal_topo_list(maplistA, maplistB, topolist,
  2124. count_map = True)
  2125. t[0] = resultlist
  2126. def p_t_hash_paren(self, t):
  2127. """
  2128. t_hash_var : LPAREN t_hash_var RPAREN
  2129. """
  2130. t[0] = t[2]
  2131. def p_t_td_var(self, t):
  2132. """
  2133. t_td_var : TD LPAREN stds RPAREN
  2134. | TD LPAREN expr RPAREN
  2135. """
  2136. if self.run:
  2137. maplist = self.check_stds(t[3])
  2138. for map_i in maplist:
  2139. if map_i.is_time_absolute:
  2140. start, end = map_i.get_absolute_time()
  2141. if end is not None:
  2142. td = time_delta_to_relative_time(end - start)
  2143. else:
  2144. start, end, unit = map_i.get_relative_time()
  2145. if end is not None:
  2146. td = end - start
  2147. if "map_value" in dir(map_i):
  2148. gvar = GlobalTemporalVar()
  2149. gvar.td = td
  2150. map_i.map_value.append(gvar)
  2151. else:
  2152. map_i.map_value = gvar
  2153. t[0] = maplist
  2154. else:
  2155. t[0] = "td(" + str(t[3]) + ")"
  2156. if self.debug:
  2157. print("td(" + str(t[3]) + ")")
  2158. def p_t_time_var(self, t):
  2159. # Temporal variables that return a double or integer value
  2160. """
  2161. t_var : START_DOY
  2162. | START_DOW
  2163. | START_YEAR
  2164. | START_MONTH
  2165. | START_WEEK
  2166. | START_DAY
  2167. | START_HOUR
  2168. | START_MINUTE
  2169. | START_SECOND
  2170. | END_DOY
  2171. | END_DOW
  2172. | END_YEAR
  2173. | END_MONTH
  2174. | END_WEEK
  2175. | END_DAY
  2176. | END_HOUR
  2177. | END_MINUTE
  2178. | END_SECOND
  2179. """
  2180. t[0] = t[1]
  2181. def p_compare_op(self, t):
  2182. # Compare operators that are supported for temporal expressions
  2183. """
  2184. comp_op : CEQUALS
  2185. | UNEQUALS
  2186. | LOWER
  2187. | LOWER_EQUALS
  2188. | GREATER
  2189. | GREATER_EQUALS
  2190. """
  2191. t[0] = t[1]
  2192. def p_t_var_expr_td_hash(self, t):
  2193. # Examples:
  2194. # A # B == 2
  2195. # td(A) < 31
  2196. """
  2197. t_var_expr : t_td_var comp_op number
  2198. | t_hash_var comp_op number
  2199. """
  2200. if self.run:
  2201. maplist = self.check_stds(t[1])
  2202. comp_op = t[2]
  2203. value = str(t[3])
  2204. for map_i in maplist:
  2205. # Evaluate time diferences and hash operator statements for each map.
  2206. try:
  2207. td = map_i.map_value[0].td
  2208. boolname = eval(str(td) + comp_op + value)
  2209. # Add conditional boolean value to the map.
  2210. if "condition_value" in dir(map_i):
  2211. map_i.condition_value.append(boolname)
  2212. else:
  2213. map_i.condition_value = boolname
  2214. except:
  2215. self.msgr.fatal("Error: the given expression does not contain a correct time difference object.")
  2216. t[0] = maplist
  2217. if self.debug:
  2218. print(t[1], t[2], t[3])
  2219. def p_t_var_expr_number(self, t):
  2220. # Examples:
  2221. # start_month(A) > 2
  2222. # start_day(B) < 14
  2223. # start_day(B) < start_month(A)
  2224. """
  2225. t_var_expr : t_var LPAREN stds RPAREN comp_op number
  2226. | t_var LPAREN expr RPAREN comp_op number
  2227. """
  2228. # TODO: Implement comparison operator for map lists.
  2229. #| t_var LPAREN stds RPAREN comp_op t_var LPAREN stds RPAREN
  2230. #| t_var LPAREN stds RPAREN comp_op t_var LPAREN expr RPAREN
  2231. #| t_var LPAREN expr RPAREN comp_op t_var LPAREN expr RPAREN
  2232. #| t_var LPAREN expr RPAREN comp_op t_var LPAREN stds RPAREN
  2233. # TODO: Implement statement in backward direction:
  2234. # number comp_op t_var LPAREN stds RPAREN
  2235. if self.run:
  2236. maplist = self.check_stds(t[3])
  2237. gvar = GlobalTemporalVar()
  2238. gvar.tfunc = t[1]
  2239. gvar.compop = t[5]
  2240. gvar.value = t[6]
  2241. # Evaluate temporal variable for given maplist.
  2242. resultlist = self.eval_global_var(gvar, maplist)
  2243. t[0] = resultlist
  2244. if self.debug:
  2245. print(t[1], t[3], t[5], t[6])
  2246. def p_t_var_expr_time(self, t):
  2247. # Examples:
  2248. # start_time(A) == "12:30:00"
  2249. # start_date(B) <= "2001-01-01"
  2250. # start_datetime(C) > "2001-01-01 12:30:00"
  2251. # TODO: Implement statement in backward direction:
  2252. # TIME comp_op START_TIME LPAREN stds RPAREN
  2253. """
  2254. t_var_expr : START_TIME LPAREN stds RPAREN comp_op TIME
  2255. | START_DATE LPAREN stds RPAREN comp_op DATE
  2256. | START_DATETIME LPAREN stds RPAREN comp_op DATETIME
  2257. | END_TIME LPAREN stds RPAREN comp_op TIME
  2258. | END_DATE LPAREN stds RPAREN comp_op DATE
  2259. | END_DATETIME LPAREN stds RPAREN comp_op DATETIME
  2260. | START_TIME LPAREN expr RPAREN comp_op TIME
  2261. | START_DATE LPAREN expr RPAREN comp_op DATE
  2262. | START_DATETIME LPAREN expr RPAREN comp_op DATETIME
  2263. | END_TIME LPAREN expr RPAREN comp_op TIME
  2264. | END_DATE LPAREN expr RPAREN comp_op DATE
  2265. | END_DATETIME LPAREN expr RPAREN comp_op DATETIME
  2266. """
  2267. if self.run:
  2268. # Check input maplist.
  2269. maplist = self.check_stds(t[3])
  2270. # Build global temporal variable.
  2271. gvar = GlobalTemporalVar()
  2272. gvar.tfunc = t[1]
  2273. gvar.compop = t[5]
  2274. gvar.value = t[6]
  2275. # Evaluate temporal variable for given maplist.
  2276. resultlist = self.eval_global_var(gvar, maplist)
  2277. t[0] = resultlist
  2278. if self.debug:
  2279. print(t[1], t[3], t[5], t[6])
  2280. def p_t_var_expr_comp(self, t):
  2281. """
  2282. t_var_expr : t_var_expr AND AND t_var_expr
  2283. | t_var_expr OR OR t_var_expr
  2284. """
  2285. if self.run:
  2286. # Check input maplists and operators.
  2287. tvarexprA = t[1]
  2288. tvarexprB = t[4]
  2289. relations = ["EQUAL"]
  2290. temporal = "l"
  2291. function = t[2] + t[3]
  2292. aggregate = t[2]
  2293. # Build conditional values based on topological relationships.
  2294. complist = self.get_temporal_topo_list(tvarexprA, tvarexprB, topolist=relations,
  2295. compare_bool=True, compop=function[0],
  2296. aggregate=aggregate)
  2297. # Set temporal extent based on topological relationships.
  2298. resultlist = self.set_temporal_extent_list(complist, topolist = relations,
  2299. temporal=temporal)
  2300. t[0] = resultlist
  2301. if self.debug:
  2302. print(t[1], t[2] + t[3], t[4])
  2303. def p_t_var_expr_comp_op(self, t):
  2304. """
  2305. t_var_expr : t_var_expr T_COMP_OPERATOR t_var_expr
  2306. """
  2307. if self.run:
  2308. tvarexprA = t[1]
  2309. tvarexprB = t[3]
  2310. # Evaluate temporal comparison operator.
  2311. relations, temporal, function, aggregate = self.eval_toperator(t[2], optype='boolean')
  2312. # Build conditional values based on topological relationships.
  2313. complist = self.get_temporal_topo_list(tvarexprA, tvarexprB, topolist=relations,
  2314. compare_bool=True, compop=function[0], aggregate=aggregate)
  2315. # Set temporal extent based on topological relationships.
  2316. resultlist = self.set_temporal_extent_list(complist, topolist=relations,
  2317. temporal=temporal)
  2318. t[0] = resultlist
  2319. if self.debug:
  2320. print(t[1], t[2], t[3])
  2321. def p_expr_t_select(self, t):
  2322. # Temporal equal selection
  2323. # The temporal topology relation equals is implicit
  2324. # Examples:
  2325. # A : B # Select the part of A that is temporally equal B
  2326. """
  2327. expr : stds T_SELECT stds
  2328. | expr T_SELECT stds
  2329. | stds T_SELECT expr
  2330. | expr T_SELECT expr
  2331. """
  2332. if self.run:
  2333. # Setup database connection.
  2334. # Check input stds.
  2335. maplistA = self.check_stds(t[1])
  2336. maplistB = self.check_stds(t[3])
  2337. # Perform selection.
  2338. selectlist = self.perform_temporal_selection(maplistA, maplistB)
  2339. # Return map list.
  2340. t[0] = selectlist
  2341. else:
  2342. t[0] = t[1] + "*"
  2343. if self.debug:
  2344. print(str(t[1]), "* = ", t[1], t[2], t[3])
  2345. def p_expr_t_not_select(self, t):
  2346. # Temporal equal selection
  2347. # The temporal topology relation equals is implicit
  2348. # Examples:
  2349. # A !: B # Select the part of A that is temporally unequal to B
  2350. """
  2351. expr : stds T_NOT_SELECT stds
  2352. | expr T_NOT_SELECT stds
  2353. | stds T_NOT_SELECT expr
  2354. | expr T_NOT_SELECT expr
  2355. """
  2356. if self.run:
  2357. # Check input stds.
  2358. maplistA = self.check_stds(t[1])
  2359. maplistB = self.check_stds(t[3])
  2360. # Perform negative selection.
  2361. selectlist = self.perform_temporal_selection(maplistA, maplistB,
  2362. inverse=True)
  2363. # Return map list.
  2364. t[0] = selectlist
  2365. else:
  2366. t[0] = t[1] + "*"
  2367. if self.debug:
  2368. print(t[1] + "* = ", t[1], t[2], t[3])
  2369. def p_expr_t_select_operator(self, t):
  2370. # Temporal equal selection
  2371. # The temporal topology relation equals is implicit
  2372. # Examples:
  2373. # A {!:} B # Select the part of A that is temporally unequal to B
  2374. # A {:} B # Select the part of A that is temporally equal B
  2375. # A {!:, equals} B # Select the part of A that is temporally unequal to B
  2376. # A {!:, during} B # Select the part of A that is temporally not during B
  2377. # A {:, overlaps} B # Select the part of A that temporally overlaps B
  2378. # A {:, overlaps|equals} B # Select the part of A that temporally overlaps or equals B
  2379. """
  2380. expr : stds T_SELECT_OPERATOR stds
  2381. | expr T_SELECT_OPERATOR stds
  2382. | stds T_SELECT_OPERATOR expr
  2383. | expr T_SELECT_OPERATOR expr
  2384. """
  2385. if self.run:
  2386. # Check input stds.
  2387. maplistA = self.check_stds(t[1])
  2388. maplistB = self.check_stds(t[3])
  2389. # Evaluate temporal operator.
  2390. operators = self.eval_toperator(t[2], optype='select')
  2391. # Check for negative selection.
  2392. if operators[2] == "!:":
  2393. negation = True
  2394. else:
  2395. negation = False
  2396. # Perform selection.
  2397. selectlist = self.perform_temporal_selection(maplistA, maplistB,
  2398. topolist=operators[0],
  2399. inverse=negation)
  2400. selectlist = self.set_granularity(selectlist, maplistB, operators[1],
  2401. operators[0])
  2402. # Return map list.
  2403. t[0] = selectlist
  2404. else:
  2405. t[0] = t[1] + "*"
  2406. if self.debug:
  2407. print(t[1] + "* = ", t[1], t[2], t[3])
  2408. def p_expr_condition_if(self, t):
  2409. # Examples
  2410. # if( start_date() < "2005-06-01", A:B)
  2411. """
  2412. expr : IF LPAREN t_var_expr COMMA stds RPAREN
  2413. | IF LPAREN t_var_expr COMMA expr RPAREN
  2414. """
  2415. if self.run:
  2416. # Get stds/map list of then statement.
  2417. thenlist = self.check_stds(t[5])
  2418. # Get temporal conditional statement.
  2419. tvarexpr = t[3]
  2420. thencond = self.build_condition_list(tvarexpr, thenlist)
  2421. thenresult = self.eval_condition_list(thencond)
  2422. # Clear the map and conditional values of the map list.
  2423. resultlist = self.check_stds(thenresult, clear = True)
  2424. # Return resulting map list.
  2425. t[0] = resultlist
  2426. else:
  2427. t[0] = t[5] + "*"
  2428. if self.debug:
  2429. print(str(t[5]) + "* = ", "if condition", str(t[3]), ' then ', str(t[5]))
  2430. def p_expr_condition_if_relation(self, t):
  2431. # Examples
  2432. # if({equal} start_date() < "2005-06-01", A:B)
  2433. """
  2434. expr : IF LPAREN T_REL_OPERATOR COMMA t_var_expr COMMA stds RPAREN
  2435. | IF LPAREN T_REL_OPERATOR COMMA t_var_expr COMMA expr RPAREN
  2436. """
  2437. if self.run:
  2438. # Get stds/map list of then statement.
  2439. thenlist = self.check_stds(t[7])
  2440. # Get temporal conditional statement.
  2441. tvarexpr = t[5]
  2442. topolist = self.eval_toperator(t[3], optype='relation')[0]
  2443. thencond = self.build_condition_list(tvarexpr, thenlist, topolist)
  2444. thenresult = self.eval_condition_list(thencond)
  2445. # Clear the map and conditional values of the map list.
  2446. resultlist = self.check_stds(thenresult, clear = True)
  2447. # Return resulting map list.
  2448. t[0] = resultlist
  2449. else:
  2450. t[0] = t[7] + "*"
  2451. if self.debug:
  2452. print("result* = ", "if ", str(t[3]), "condition", str(t[5]), " then ", str(t[7]))
  2453. def p_expr_condition_elif(self, t):
  2454. # Examples
  2455. # if( start_date() < "2005-06-01", if(start_time() < "12:30:00", A:B), A!:B)
  2456. """
  2457. expr : IF LPAREN t_var_expr COMMA stds COMMA stds RPAREN
  2458. | IF LPAREN t_var_expr COMMA stds COMMA expr RPAREN
  2459. | IF LPAREN t_var_expr COMMA expr COMMA stds RPAREN
  2460. | IF LPAREN t_var_expr COMMA expr COMMA expr RPAREN
  2461. """
  2462. if self.run:
  2463. # Get stds/map list of then statement.
  2464. thenlist = self.check_stds(t[5])
  2465. elselist = self.check_stds(t[7])
  2466. # Get temporal conditional statement for then and else expressions.
  2467. tvarexpr = t[3]
  2468. thencond = self.build_condition_list(tvarexpr, thenlist)
  2469. thenresult = self.eval_condition_list(thencond)
  2470. elsecond = self.build_condition_list(tvarexpr, elselist)
  2471. elseresult = self.eval_condition_list(elsecond, inverse = True)
  2472. # Combine and sort else and then statement to result map list.
  2473. combilist = thenresult + elseresult
  2474. resultlist = sorted(combilist, key = AbstractDatasetComparisonKeyStartTime)
  2475. # Clear the map and conditional values of the map list.
  2476. resultlist = self.check_stds(resultlist, clear = True)
  2477. # Return resulting map list.
  2478. t[0] = resultlist
  2479. else:
  2480. t[0] = t[5] + "*"
  2481. if self.debug:
  2482. print(str(t[5]) + "* = ", "if condition", str(t[3]), " then ", str(t[5]), ' else ', str(t[7]))
  2483. def p_expr_condition_elif_relation(self, t):
  2484. # Examples
  2485. # if({equal}, start_date() < "2005-06-01", if(start_time() < "12:30:00", A:B), A!:B)
  2486. # The then and else statement using the same topological relationships.
  2487. # Feature request: Independent relationships for then and else to conditions.
  2488. """
  2489. expr : IF LPAREN T_REL_OPERATOR COMMA t_var_expr COMMA stds COMMA stds RPAREN
  2490. | IF LPAREN T_REL_OPERATOR COMMA t_var_expr COMMA stds COMMA expr RPAREN
  2491. | IF LPAREN T_REL_OPERATOR COMMA t_var_expr COMMA expr COMMA stds RPAREN
  2492. | IF LPAREN T_REL_OPERATOR COMMA t_var_expr COMMA expr COMMA expr RPAREN
  2493. """
  2494. if self.run:
  2495. # Get stds/map list of then statement.
  2496. thenlist = self.check_stds(t[7])
  2497. elselist = self.check_stds(t[9])
  2498. # Get temporal conditional statement.
  2499. tvarexpr = t[5]
  2500. topolist = self.eval_toperator(t[3], optype = 'relation')[0]
  2501. thencond = self.build_condition_list(tvarexpr, thenlist, topolist)
  2502. thenresult = self.eval_condition_list(thencond)
  2503. elsecond = self.build_condition_list(tvarexpr, elselist, topolist)
  2504. elseresult = self.eval_condition_list(elsecond, inverse = True)
  2505. # Combine and sort else and then statement to result map list.
  2506. combilist = thenresult + elseresult
  2507. resultlist = sorted(combilist, key = AbstractDatasetComparisonKeyStartTime)
  2508. # Clear the map and conditional values of the map list.
  2509. resultlist = self.check_stds(resultlist, clear = True)
  2510. # Return resulting map list.
  2511. t[0] = resultlist
  2512. else:
  2513. if t[5]:
  2514. t[0] = str(t[7])
  2515. else:
  2516. t[0] = str(t[9])
  2517. if self.debug:
  2518. if t[5]:
  2519. print(str(t[7]), "* = ", "if condition", str(t[5]), " then ", str(t[7]), ' else ', str(t[9]))
  2520. else:
  2521. print(str(t[9]), "* = ", "if condition", str(t[5]), " then ", str(t[7]), ' else ', str(t[9]))
  2522. def p_expr_t_buff(self, t):
  2523. # Examples
  2524. # buff_t(A : B, "10 minutes") # Select the part of A that is temporally
  2525. # equal to B and create a buffer of 10 minutes around
  2526. """
  2527. expr : BUFF_T LPAREN stds COMMA QUOTE number NAME QUOTE RPAREN
  2528. | BUFF_T LPAREN expr COMMA QUOTE number NAME QUOTE RPAREN
  2529. | BUFF_T LPAREN stds COMMA number RPAREN
  2530. | BUFF_T LPAREN expr COMMA number RPAREN
  2531. """
  2532. if self.run:
  2533. # Check input stds.
  2534. bufflist = self.check_stds(t[3])
  2535. for map in bufflist:
  2536. # Get increment format.
  2537. if len(t) == 10:
  2538. increment = str(t[6]) + " " + t[7]
  2539. elif len(t) == 7:
  2540. increment = str(t[5])
  2541. # Perform buffering.
  2542. map.temporal_buffer(increment)
  2543. t[0] = bufflist
  2544. else:
  2545. t[0] = t[3] + "*"
  2546. if self.debug:
  2547. if len(t) == 10:
  2548. print(str(t[3]) + "* = buff_t(", str(t[3]), "," , '"', str(t[6]), str(t[7]), '"', ")")
  2549. elif len(t) == 7:
  2550. print(str(t[3]) + "* = buff_t(", str(t[3]), ",", str(t[5]), ")")
  2551. def p_expr_t_snap(self, t):
  2552. # Examples
  2553. # tsnap(A : B) # Snap the maps of A temporally.
  2554. """
  2555. expr : TSNAP LPAREN stds RPAREN
  2556. | TSNAP LPAREN expr RPAREN
  2557. """
  2558. if self.run:
  2559. # Check input stds.
  2560. maplist = self.check_stds(t[3])
  2561. # Perform snapping.
  2562. snaplist = AbstractSpaceTimeDataset.snap_map_list(maplist)
  2563. t[0] = snaplist
  2564. else:
  2565. t[0] = t[3] + "*"
  2566. if self.debug:
  2567. print(str(t[3]) + "* = tsnap(", str(t[3]), ")")
  2568. def p_expr_t_shift(self, t):
  2569. # Examples
  2570. # tshift(A : B, "10 minutes") # Shift the selection from A temporally
  2571. # by 10 minutes.
  2572. """
  2573. expr : TSHIFT LPAREN stds COMMA QUOTE number NAME QUOTE RPAREN
  2574. | TSHIFT LPAREN expr COMMA QUOTE number NAME QUOTE RPAREN
  2575. | TSHIFT LPAREN stds COMMA number RPAREN
  2576. | TSHIFT LPAREN expr COMMA number RPAREN
  2577. """
  2578. if self.run:
  2579. # Check input stds.
  2580. maplist = self.check_stds(t[3])
  2581. # Get increment format.
  2582. if len(t) == 10:
  2583. increment = str(t[6]) + " " + t[7]
  2584. elif len(t) == 7:
  2585. increment = str(t[5])
  2586. # Perform shifting.
  2587. shiftlist = AbstractSpaceTimeDataset.shift_map_list(maplist, increment)
  2588. t[0] = shiftlist
  2589. else:
  2590. t[0] = t[3] + "*"
  2591. if self.debug:
  2592. if len(t) == 10:
  2593. print(str(t[3]) + "* = tshift(", str(t[3]), "," , '"', str(t[6]), str(t[7]), '"', ")")
  2594. elif len(t) == 7:
  2595. print(str(t[3]) + "* = tshift(", str(t[3]), ",", str(t[5]), ")")
  2596. # Handle errors.
  2597. def p_error(self, t):
  2598. if t:
  2599. raise SyntaxError("syntax error on line %d, token %s near '%s' expression '%s'" %
  2600. (t.lineno, t.type, t.value, self.expression))
  2601. else:
  2602. raise SyntaxError("Unexpected syntax error")
  2603. ###############################################################################
  2604. if __name__ == "__main__":
  2605. import doctest
  2606. doctest.testmod()