temporal_algebra.py 126 KB

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