temporal_algebra.py 125 KB

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