temporal_algebra.py 124 KB

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