temporal_raster_base_algebra.py 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833
  1. """@package grass.temporal
  2. Temporal raster algebra
  3. (C) 2013 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. >>> p = TemporalRasterAlgebraLexer()
  10. >>> p.build()
  11. >>> p.debug = True
  12. >>> expression = 'R = A {+,equal,l} B'
  13. >>> p.test(expression)
  14. R = A {+,equal,l} B
  15. LexToken(NAME,'R',1,0)
  16. LexToken(EQUALS,'=',1,2)
  17. LexToken(NAME,'A',1,4)
  18. LexToken(T_ARITH2_OPERATOR,'{+,equal,l}',1,6)
  19. LexToken(NAME,'B',1,18)
  20. >>> expression = 'R = A {*,equal|during,r} B'
  21. >>> p.test(expression)
  22. R = A {*,equal|during,r} B
  23. LexToken(NAME,'R',1,0)
  24. LexToken(EQUALS,'=',1,2)
  25. LexToken(NAME,'A',1,4)
  26. LexToken(T_ARITH1_OPERATOR,'{*,equal|during,r}',1,6)
  27. LexToken(NAME,'B',1,25)
  28. >>> expression = 'R = A {+,equal|during} B'
  29. >>> p.test(expression)
  30. R = A {+,equal|during} B
  31. LexToken(NAME,'R',1,0)
  32. LexToken(EQUALS,'=',1,2)
  33. LexToken(NAME,'A',1,4)
  34. LexToken(T_ARITH2_OPERATOR,'{+,equal|during}',1,6)
  35. LexToken(NAME,'B',1,23)
  36. """
  37. from __future__ import print_function
  38. try:
  39. import ply.lex as lex
  40. import ply.yacc as yacc
  41. except:
  42. pass
  43. import copy
  44. import grass.pygrass.modules as pymod
  45. from grass.exceptions import FatalError
  46. from .temporal_algebra import TemporalAlgebraLexer, TemporalAlgebraParser, GlobalTemporalVar
  47. from .core import init_dbif
  48. from .abstract_dataset import AbstractDatasetComparisonKeyStartTime
  49. from .factory import dataset_factory
  50. from .open_stds import open_new_stds
  51. from spatio_temporal_relationships import SpatioTemporalTopologyBuilder
  52. from .space_time_datasets import Raster3DDataset, RasterDataset
  53. ##############################################################################
  54. class TemporalRasterAlgebraLexer(TemporalAlgebraLexer):
  55. """Lexical analyzer for the GRASS GIS temporal algebra"""
  56. def __init__(self):
  57. TemporalAlgebraLexer.__init__(self)
  58. # Supported r.mapcalc functions.
  59. mapcalc_functions = {
  60. 'exp' : 'EXP',
  61. 'log' : 'LOG',
  62. 'sqrt' : 'SQRT',
  63. 'abs' : 'ABS',
  64. 'cos' : 'COS',
  65. 'acos' : 'ACOS',
  66. 'sin' : 'SIN',
  67. 'asin' : 'ASIN',
  68. 'tan' : 'TAN',
  69. 'double' : 'DOUBLE',
  70. 'float' : 'FLOATEXP',
  71. 'int' : 'INTEXP',
  72. 'isnull' : 'ISNULL',
  73. 'isntnull': 'ISNTNULL',
  74. 'null' : 'NULL',
  75. 'exist' : 'EXIST',
  76. }
  77. # Functions that defines single maps with time stamp and without temporal extent.
  78. map_functions = {'map' : 'MAP'}
  79. # This is the list of token names.
  80. raster_tokens = (
  81. 'MOD',
  82. 'DIV',
  83. 'MULT',
  84. 'ADD',
  85. 'SUB',
  86. 'T_ARITH1_OPERATOR',
  87. 'T_ARITH2_OPERATOR',
  88. 'L_SPAREN',
  89. 'R_SPAREN',
  90. )
  91. # Build the token list
  92. tokens = TemporalAlgebraLexer.tokens \
  93. + raster_tokens \
  94. + tuple(mapcalc_functions.values()) \
  95. + tuple(map_functions.values())
  96. # Regular expression rules for simple tokens
  97. t_MOD = r'[\%]'
  98. t_DIV = r'[\/]'
  99. t_MULT = r'[\*]'
  100. t_ADD = r'[\+]'
  101. t_SUB = r'[-]'
  102. t_T_ARITH1_OPERATOR = r'\{[\%\*\/][,]?[a-zA-Z\| ]*([,])?([lrudi]|left|right|union|disjoint|intersect)?\}'
  103. t_T_ARITH2_OPERATOR = r'\{[+-][,]?[a-zA-Z\| ]*([,])?([lrudi]|left|right|union|disjoint|intersect)?\}'
  104. t_L_SPAREN = r'\['
  105. t_R_SPAREN = r'\]'
  106. # Parse symbols
  107. def temporal_symbol(self, t):
  108. # Check for reserved words
  109. if t.value in TemporalRasterAlgebraLexer.time_functions.keys():
  110. t.type = TemporalRasterAlgebraLexer.time_functions.get(t.value)
  111. elif t.value in TemporalRasterAlgebraLexer.datetime_functions.keys():
  112. t.type = TemporalRasterAlgebraLexer.datetime_functions.get(t.value)
  113. elif t.value in TemporalRasterAlgebraLexer.conditional_functions.keys():
  114. t.type = TemporalRasterAlgebraLexer.conditional_functions.get(t.value)
  115. elif t.value in TemporalRasterAlgebraLexer.mapcalc_functions.keys():
  116. t.type = TemporalRasterAlgebraLexer.mapcalc_functions.get(t.value)
  117. elif t.value in TemporalRasterAlgebraLexer.map_functions.keys():
  118. t.type = TemporalRasterAlgebraLexer.map_functions.get(t.value)
  119. else:
  120. t.type = 'NAME'
  121. return t
  122. ##############################################################################
  123. class TemporalRasterBaseAlgebraParser(TemporalAlgebraParser):
  124. """The temporal algebra class"""
  125. # Get the tokens from the lexer class
  126. tokens = TemporalRasterAlgebraLexer.tokens
  127. # Setting equal precedence level for select and hash operations.
  128. precedence = (
  129. ('left', 'T_SELECT_OPERATOR', 'T_SELECT', 'T_NOT_SELECT'), # 1
  130. ('left', 'ADD', 'SUB', 'T_ARITH2_OPERATOR', 'T_HASH_OPERATOR', 'HASH'), #2
  131. ('left', 'AND', 'OR', 'T_COMP_OPERATOR', 'MOD', 'DIV', 'MULT',
  132. 'T_ARITH1_OPERATOR'))
  133. def __init__(self, pid=None, run=True,
  134. debug=False, spatial=False,
  135. register_null=False,
  136. dry_run=False, nprocs=1):
  137. TemporalAlgebraParser.__init__(self,
  138. pid=pid,
  139. run=run,
  140. debug=debug,
  141. spatial=spatial,
  142. register_null=register_null,
  143. dry_run=dry_run,
  144. nprocs=nprocs)
  145. def check_null(self, t):
  146. try:
  147. int(t)
  148. return t
  149. except ValueError:
  150. return "null()"
  151. ######################### Temporal functions ##############################
  152. def build_spatio_temporal_topology_list(self, maplistA, maplistB=None, topolist=["EQUAL"],
  153. assign_val=False, count_map=False, compare_bool=False,
  154. compare_cmd=False, compop=None, aggregate=None,
  155. new=False, convert=False, operator_cmd=False):
  156. """Build temporal topology for two space time data sets, copy map objects
  157. for given relation into map list.
  158. :param maplistA: List of maps.
  159. :param maplistB: List of maps.
  160. :param topolist: List of strings of temporal relations.
  161. :param assign_val: Boolean for assigning a boolean map value based on
  162. the map_values from the compared map list by
  163. topological relationships.
  164. :param count_map: Boolean if the number of topological related maps
  165. should be returned.
  166. :param compare_bool: Boolean for comparing boolean map values based on
  167. related map list and compariosn operator.
  168. :param compare_cmd: Boolean for comparing command list values based on
  169. related map list and compariosn operator.
  170. :param compop: Comparison operator, && or ||.
  171. :param aggregate: Aggregation operator for relation map list, & or |.
  172. :param new: Boolean if new temporary maps should be created.
  173. :param convert: Boolean if conditional values should be converted to
  174. r.mapcalc command strings.
  175. :param operator_cmd: Boolean for aggregate arithmetic operators implicitly
  176. in command list values based on related map lists.
  177. :return: List of maps from maplistA that fulfil the topological relationships
  178. to maplistB specified in topolist.
  179. >>> # Create two list of maps with equal time stamps
  180. >>> from datetime import datetime
  181. >>> import grass.temporal as tgis
  182. >>> tgis.init(True)
  183. >>> l = tgis.TemporalAlgebraParser()
  184. >>> mapsA = []
  185. >>> mapsB = []
  186. >>> for i in range(10):
  187. ... idA = "a%i@B"%(i)
  188. ... mapA = tgis.RasterDataset(idA)
  189. ... mapA.uid = idA
  190. ... mapA.map_value = True
  191. ... idB = "b%i@B"%(i)
  192. ... mapB = tgis.RasterDataset(idB)
  193. ... mapB.uid = idB
  194. ... mapB.map_value = False
  195. ... check = mapA.set_absolute_time(datetime(2000,1,i+1),
  196. ... datetime(2000,1,i + 2))
  197. ... check = mapB.set_absolute_time(datetime(2000,1,i+6),
  198. ... datetime(2000,1,i + 7))
  199. ... mapsA.append(mapA)
  200. ... mapsB.append(mapB)
  201. >>> resultlist = l.build_spatio_temporal_topology_list(mapsA, mapsB)
  202. >>> for map in resultlist:
  203. ... print(map.get_id())
  204. a5@B
  205. a6@B
  206. a7@B
  207. a8@B
  208. a9@B
  209. """
  210. print(topolist, assign_val, count_map, compare_bool, compare_cmd,
  211. compop, aggregate, new, convert, operator_cmd)
  212. # Check the topology definitions and return the list of temporal and spatial
  213. # topological relations that must be fulfilled
  214. temporal_topo_list, spatial_topo_list = self._check_topology(topolist=topolist)
  215. resultdict = {}
  216. # Create temporal topology for maplistA to maplistB.
  217. tb = SpatioTemporalTopologyBuilder()
  218. # Build spatio-temporal topology
  219. if len(spatial_topo_list) > 0:
  220. # Dictionary with different spatial variables used for topology builder.
  221. spatialdict = {'strds' : '2D', 'stvds' : '2D', 'str3ds' : '3D'}
  222. tb.build(maplistA, maplistB, spatial=spatialdict[self.stdstype])
  223. else:
  224. tb.build(maplistA, maplistB)
  225. # Iterate through maps in maplistA and search for relationships given
  226. # in topolist.
  227. for map_i in maplistA:
  228. if assign_val:
  229. self.assign_bool_value(map_i, temporal_topo_list, spatial_topo_list)
  230. elif compare_bool:
  231. self.compare_bool_value(map_i, compop, aggregate, temporal_topo_list, spatial_topo_list)
  232. elif compare_cmd:
  233. self.compare_cmd_value(map_i, compop, aggregate, temporal_topo_list, spatial_topo_list, convert)
  234. elif operator_cmd:
  235. self.operator_cmd_value(map_i, compop, temporal_topo_list, spatial_topo_list)
  236. temporal_relations = map_i.get_temporal_relations()
  237. spatial_relations = map_i.get_spatial_relations()
  238. for temporal_topology in temporal_topo_list:
  239. if temporal_topology.upper() in temporal_relations.keys():
  240. if self._check_spatial_topology_entries(spatial_topo_list, spatial_relations) is True:
  241. if count_map:
  242. relationmaplist = temporal_relations[temporal_topology.upper()]
  243. gvar = GlobalTemporalVar()
  244. gvar.td = len(relationmaplist)
  245. if "map_value" in dir(map_i):
  246. map_i.map_value.append(gvar)
  247. else:
  248. map_i.map_value = gvar
  249. # Use unique identifier, since map names may be equal
  250. resultdict[map_i.uid] = map_i
  251. # map_i.print_info()
  252. resultlist = resultdict.values()
  253. # Sort list of maps chronological.
  254. resultlist = sorted(resultlist, key=AbstractDatasetComparisonKeyStartTime)
  255. return(resultlist)
  256. def build_command_string(self, map_i, relmap, operator = None, cmd_type = None):
  257. """This function build the r.mapcalc command string for conditionals,
  258. spatial variable combinations and boolean comparisons.
  259. For Example: 'if(a1 == 1, b1, c2)' or 'exist(a1) && sin(b1)'
  260. :param map_i: map object with temporal extent and built relations.
  261. :param relmap: map object with defined temporal relation to map_i.
  262. :param operator: String representing operator between two spatial variables
  263. (&&,||,+,-,*,/).
  264. :param cmd_type: map object with defined temporal relation to map_i:
  265. condition, conclusion or operator.
  266. :return: the resulting command string for conditionals or spatial variable
  267. combinations
  268. """
  269. def sub_cmdstring(map_i):
  270. """This function search for command string in a map object and
  271. return substitute string (contained commandstring or map name)"""
  272. if "cmd_list" in dir(map_i):
  273. map_sub = map_i.cmd_list
  274. elif "map_value" in dir(map_i) and len(map_i.map_value) > 0 and map_i.map_value[0].get_type() == "timediff":
  275. map_sub = map_i.map_value[0].get_type_value()[0]
  276. else:
  277. try:
  278. map_sub = map_i.get_id()
  279. except:
  280. map_sub = map_i
  281. return(map_sub)
  282. # Check for type of operation, conditional or spatial variable combination
  283. # and Create r.mapcalc expression string for the operation.
  284. cmdstring = ""
  285. if cmd_type == 'condition':
  286. conditionsub = sub_cmdstring(map_i)
  287. conclusionsub = sub_cmdstring(relmap)
  288. cmdstring = "if(%s, %s)" %(conditionsub, conclusionsub)
  289. elif cmd_type == 'conclusion':
  290. thensub = sub_cmdstring(map_i)
  291. elsesub = sub_cmdstring(relmap)
  292. cmdstring = "%s, %s" %(thensub, elsesub)
  293. elif cmd_type == 'operator':
  294. leftsub = sub_cmdstring(map_i)
  295. rightsub = sub_cmdstring(relmap)
  296. if operator == None:
  297. self.msgr.fatal("Error: Can't build command string for map %s, operator is missing"
  298. %(map_i.get_map_id()))
  299. cmdstring = "(%s %s %s)" %(leftsub, operator, rightsub)
  300. return(cmdstring)
  301. def compare_cmd_value(self, map_i, compop, aggregate,
  302. temporal_topo_list = ["EQUAL"],
  303. spatial_topo_list = [], convert = False):
  304. """ Function to evaluate two map lists with boolean values by boolean
  305. comparison operator.
  306. R = A && B
  307. R = if(A < 1 && B > 1, A, B)
  308. R = if(A < 1 {&&,equal|equivalent} B > 1, A, B)
  309. Extended temporal algebra version with command
  310. list builder for temporal raster algebra.
  311. :param map_i: Map object with temporal extent.
  312. :param temporal_relations: List of temporal relation to map_i.
  313. :param temporal_topo_list: List of strings for given temporal relations.
  314. :param compop: Comparison operator, && or ||.
  315. :param aggregate: Aggregation operator for relation map list, & or |.
  316. :param convert: Boolean if conditional values should be converted to
  317. r.mapcalc command strings.
  318. :return: Map object with conditional value that has been evaluated by
  319. comparison operators.
  320. """
  321. # Build command list list with elements from related maps and given relation operator.
  322. if convert and "condition_value" in dir(map_i):
  323. if map_i.condition_value != []:
  324. cmdstring = str(int(map_i.condition_value[0]))
  325. map_i.cmd_list = cmdstring
  326. if "cmd_list" in dir(map_i):
  327. leftcmd = map_i.cmd_list
  328. cmd_value_list = [leftcmd]
  329. count = 0
  330. temporal_relations = map_i.get_temporal_relations()
  331. for topo in temporal_topo_list:
  332. if topo.upper() in temporal_relations.keys():
  333. relationmaplist = temporal_relations[topo.upper()]
  334. if count == 0 and "cmd_list" in dir(map_i):
  335. cmd_value_list.append(compop)
  336. cmd_value_list.append('(')
  337. for relationmap in relationmaplist:
  338. if self._check_spatial_topology_relation(spatial_topo_list, map_i, relationmap) is True:
  339. if convert and "condition_value" in dir(relationmap):
  340. if relationmap.condition_value != []:
  341. cmdstring = str(int(relationmap.condition_value[0]))
  342. relationmap.cmd_list = cmdstring
  343. if "cmd_list" in dir(relationmap):
  344. if count > 0:
  345. cmd_value_list.append(aggregate + aggregate)
  346. cmd_value_list.append(relationmap.cmd_list)
  347. count = count + 1
  348. if self.debug:
  349. print("compare_cmd_value", map_i.get_id(),
  350. relationmap.get_id(), relationmap.cmd_list)
  351. if count > 0:
  352. cmd_value_list.append(')')
  353. cmd_value_str = ''.join(map(str, cmd_value_list))
  354. # Add command list to result map.
  355. map_i.cmd_list = cmd_value_str
  356. print(cmd_value_str)
  357. return(cmd_value_str)
  358. def operator_cmd_value(self, map_i, operator,
  359. temporal_topo_list = ["EQUAL"],
  360. spatial_topo_list = []):
  361. """ Function to evaluate two map lists by given arithmetic operator.
  362. :param map_i: Map object with temporal extent.
  363. :param operator: Arithmetic operator, +-*/%.
  364. :param temporal_topo_list: List of strings for given temporal relations.
  365. :param spatial_topo_list: List of strings for given spatial relations.
  366. :return: Map object with command list with operators that has been
  367. evaluated by implicit aggregation.
  368. """
  369. temporal_relations = map_i.get_temporal_relations()
  370. spatial_relations = map_i.get_spatial_relations()
  371. # Build comandlist list with elements from related maps and given relation operator.
  372. leftcmd = map_i
  373. cmdstring = ""
  374. for topo in temporal_topo_list:
  375. if topo.upper() in temporal_relations.keys():
  376. relationmaplist = temporal_relations[topo.upper()]
  377. for relationmap in relationmaplist:
  378. if self._check_spatial_topology_relation(spatial_topo_list, map_i, relationmap) is True:
  379. # Create r.mapcalc expression string for the operation.
  380. cmdstring = self.build_command_string(leftcmd,
  381. relationmap,
  382. operator=operator,
  383. cmd_type="operator")
  384. leftcmd = cmdstring
  385. if self.debug:
  386. print("operator_cmd_value", map_i.get_id(), operator, relationmap.get_id())
  387. # Add command list to result map.
  388. map_i.cmd_list = cmdstring
  389. print("map command string", cmdstring)
  390. return(cmdstring)
  391. def set_temporal_extent_list(self, maplist, topolist=["EQUAL"], temporal='l' ,
  392. cmd_bool=False, cmd_type=None, operator=None):
  393. """ Change temporal extent of map list based on temporal relations to
  394. other map list and given temporal operator.
  395. :param maplist: List of map objects for which relations has been build
  396. correctly.
  397. :param topolist: List of strings of temporal relations.
  398. :param temporal: The temporal operator specifying the temporal
  399. extent operation (intersection, union, disjoint
  400. union, right reference, left reference).
  401. :param cmd_bool: Boolean if command string should be merged for related maps.
  402. :param cmd_type: map object with defined temporal relation to map_i:
  403. condition, conclusion or operator.
  404. :param operator: String defining the type of operator.
  405. :return: Map list with specified temporal extent and optional command string.
  406. """
  407. resultdict = {}
  408. temporal_topo_list, spatial_topo_list = self._check_topology(topolist=topolist)
  409. for map_i in maplist:
  410. # Loop over temporal related maps and create overlay modules.
  411. tbrelations = map_i.get_temporal_relations()
  412. # Generate an intermediate map for the result map list.
  413. map_new = self.generate_new_map(base_map=map_i,
  414. bool_op='and',
  415. copy=True,
  416. rename=True)
  417. # Combine temporal and spatial extents of intermediate map with related maps.
  418. for topo in topolist:
  419. if topo in tbrelations.keys():
  420. for map_j in (tbrelations[topo]):
  421. if self._check_spatial_topology_relation(spatial_topo_list, map_i, map_j) is True:
  422. if temporal == 'r':
  423. # Generate an intermediate map for the result map list.
  424. map_new = self.generate_new_map(base_map=map_i,
  425. bool_op='and',
  426. copy=True,
  427. rename=True)
  428. # Create overlaid map extent.
  429. returncode = self.overlay_map_extent(map_new, map_j,
  430. 'and',
  431. temp_op=temporal)
  432. # Stop the loop if no temporal or spatial relationship exist.
  433. if returncode == 0:
  434. break
  435. # Append map to result map list.
  436. elif returncode == 1:
  437. # print(map_new.cmd_list)
  438. # resultlist.append(map_new)
  439. if cmd_bool:
  440. # Create r.mapcalc expression string for the operation.
  441. cmdstring = self.build_command_string(map_i,
  442. map_j,
  443. operator=operator,
  444. cmd_type=cmd_type)
  445. # Conditional append of module command.
  446. map_new.cmd_list = cmdstring
  447. # Write map object to result dictionary.
  448. resultdict[map_new.uid] = map_new
  449. if returncode == 0:
  450. break
  451. # Append map to result map list.
  452. #if returncode == 1:
  453. # resultlist.append(map_new)
  454. # Get sorted map objects as values from result dictionoary.
  455. resultlist = resultdict.values()
  456. resultlist = sorted(resultlist, key = AbstractDatasetComparisonKeyStartTime)
  457. return(resultlist)
  458. def build_condition_cmd_list(self, iflist, thenlist, elselist=None,
  459. condition_topolist=["EQUAL"],
  460. conclusion_topolist=["EQUAL"],
  461. temporal='l', null=False):
  462. """This function build the r.mapcalc command strings for spatial conditionals.
  463. For Example: 'if(a1 == 1, b1, c2)'
  464. :param iflist: Map list with temporal extents and command list.
  465. :param thenlist: Map list with temporal extents and command list or numeric string.
  466. :param elselist: Map list with temporal extents and command list or numeric string.
  467. :param condition_topolist: List of strings for given temporal relations between
  468. conditions and conclusions.
  469. :param conclusion_topolist: List of strings for given temporal relations between
  470. conditions (then and else).
  471. :param temporal: The temporal operator specifying the temporal
  472. extent operation (intersection, union, disjoint
  473. union, right reference, left reference).
  474. :param null: Boolean if null map support should be activated.
  475. :return: map list with resulting command string for given condition type.
  476. """
  477. resultlist = []
  478. # First merge conclusion command maplists or strings.
  479. # Check if alternative conclusion map list is given.
  480. if all([isinstance(thenlist, list), isinstance(elselist, list)]):
  481. # Build conclusion command map list.
  482. conclusiontopolist = self.build_spatio_temporal_topology_list(thenlist, elselist,
  483. conclusion_topolist)
  484. conclusionlist = self.set_temporal_extent_list(conclusiontopolist,
  485. topolist=conclusion_topolist,
  486. temporal=temporal ,
  487. cmd_bool=True,
  488. cmd_type="conclusion")
  489. # Check if any conclusion is a numeric statements.
  490. elif any([isinstance(thenlist, str), isinstance(elselist, str)]):
  491. conclusionlist = []
  492. # Check if only alternative conclusion is a numeric statements.
  493. if all([isinstance(thenlist, list), isinstance(elselist, str)]):
  494. listinput = thenlist
  495. numinput = elselist
  496. for map_i in listinput:
  497. # Create r.mapcalc expression string for the operation.
  498. cmdstring = self.build_command_string(map_i,
  499. numinput,
  500. cmd_type='conclusion')
  501. # Conditional append of module command.
  502. map_i.cmd_list = cmdstring
  503. # Append map to result map list.
  504. conclusionlist.append(map_i)
  505. # Check if only direct conclusion is a numeric statements.
  506. elif all([isinstance(thenlist, str), isinstance(elselist, list)]):
  507. listinput = elselist
  508. numinput = thenlist
  509. for map_i in listinput:
  510. # Create r.mapcalc expression string for the operation.
  511. cmdstring = self.build_command_string(numinput,
  512. map_i,
  513. cmd_type='conclusion')
  514. # Conditional append of module command.
  515. map_i.cmd_list = cmdstring
  516. # Append map to result map list.
  517. conclusionlist.append(map_i)
  518. elif all([isinstance(thenlist, str), isinstance(elselist, str)]):
  519. conclusionlist = thenlist + ',' + elselist
  520. else:
  521. # The direct conclusion is used.
  522. conclusionlist = thenlist
  523. # Use the conclusion map or string to merge it with the condition and
  524. # return maplist.
  525. if isinstance(conclusionlist, str):
  526. resultlist = []
  527. for map_i in iflist:
  528. # Create r.mapcalc expression string for the operation.
  529. cmdstring = self.build_command_string(map_i,
  530. conclusionlist,
  531. cmd_type='condition')
  532. # Conditional append of module command.
  533. map_i.cmd_list = cmdstring
  534. # Append map to result map list.
  535. resultlist.append(map_i)
  536. return(resultlist)
  537. elif isinstance(conclusionlist, list):
  538. # Build result command map list between conditions and conclusions.
  539. print("build_condition_cmd_list", condition_topolist)
  540. conditiontopolist = self.build_spatio_temporal_topology_list(iflist,
  541. conclusionlist,
  542. topolist=condition_topolist)
  543. resultlist = self.set_temporal_extent_list(conditiontopolist,
  544. topolist=condition_topolist,
  545. temporal='r',
  546. cmd_bool=True,
  547. cmd_type="condition")
  548. return(resultlist)
  549. ###########################################################################
  550. def p_statement_assign(self, t):
  551. # This function executes the processing of raster/raster3d algebra
  552. # that was build based on the expression
  553. """
  554. statement : stds EQUALS expr
  555. """
  556. if self.run:
  557. # Create the process queue for parallel mapcalc processing
  558. if self.dry_run is False:
  559. process_queue = pymod.ParallelModuleQueue(int(self.nprocs))
  560. if isinstance(t[3], list):
  561. num = len(t[3])
  562. count = 0
  563. register_list = []
  564. for i in range(num):
  565. # Check if resultmap names exist in GRASS database.
  566. map_name = self.basename + "_" + str(i) + "@" + self.mapset
  567. if self.stdstype == "strds":
  568. new_map = RasterDataset(map_name)
  569. else:
  570. new_map = Raster3DDataset(map_name)
  571. if new_map.map_exists() and self.overwrite is False:
  572. self.msgr.fatal("Error maps with basename %s exist. "
  573. "Use --o flag to overwrite existing file"%map_name)
  574. map_test_list = []
  575. for map_i in t[3]:
  576. newident = self.basename + "_" + str(count)
  577. if "cmd_list" in dir(map_i):
  578. # Build r.mapcalc module and execute expression.
  579. # Change map name to given basename.
  580. # Create deepcopy of r.mapcalc module.
  581. new_map = map_i.get_new_instance(newident + "@" + self.mapset)
  582. new_map.set_temporal_extent(map_i.get_temporal_extent())
  583. new_map.set_spatial_extent(map_i.get_spatial_extent())
  584. map_test_list.append(new_map)
  585. m = copy.deepcopy(self.m_mapcalc)
  586. m_expression = newident + "=" + map_i.cmd_list
  587. m.inputs["expression"].value = str(m_expression)
  588. m.flags["overwrite"].value = self.overwrite
  589. if self.debug:
  590. print(m.get_bash())
  591. self.process_chain_dict["processes"].append(m.get_dict())
  592. if self.dry_run is False:
  593. process_queue.put(m)
  594. elif map_i.map_exists():
  595. # Copy map if it exists b = a
  596. new_map = map_i.get_new_instance(newident + "@" + self.mapset)
  597. new_map.set_temporal_extent(map_i.get_temporal_extent())
  598. new_map.set_spatial_extent(map_i.get_spatial_extent())
  599. map_test_list.append(new_map)
  600. m = copy.deepcopy(self.m_mapcalc)
  601. m_expression = newident + "=" + map_i.get_map_id()
  602. m.inputs["expression"].value = str(m_expression)
  603. m.flags["overwrite"].value = self.overwrite
  604. if self.debug:
  605. print(m.get_bash())
  606. self.process_chain_dict["processes"].append(m.get_dict())
  607. if self.dry_run is False:
  608. process_queue.put(m)
  609. else:
  610. self.msgr.error(_("Error computing map <%s>"%map_i.get_id()))
  611. count += 1
  612. if self.dry_run is False:
  613. process_queue.wait()
  614. for map_i in map_test_list:
  615. register_list.append(map_i)
  616. # Open connection to temporal database.
  617. dbif, connect = init_dbif(self.dbif)
  618. # Create result space time dataset.
  619. if self.dry_run is False:
  620. resultstds = open_new_stds(t[1], self.stdstype,
  621. 'absolute', t[1], t[1],
  622. 'mean', self.dbif,
  623. overwrite = self.overwrite)
  624. for map_i in register_list:
  625. # Put the map into the process dictionary
  626. start, end = map_i.get_temporal_extent_as_tuple()
  627. self.process_chain_dict["register"].append((map_i.get_name(),
  628. str(start),
  629. str(end)))
  630. if self.dry_run is False:
  631. # Get meta data from grass database.
  632. map_i.load()
  633. # Do not register empty maps if not required
  634. # In case of a null map continue, do not register null maps
  635. if map_i.metadata.get_min() is None and \
  636. map_i.metadata.get_max() is None:
  637. if not self.register_null:
  638. self.removable_maps[map_i.get_name()] = map_i
  639. continue
  640. if map_i.is_in_db(dbif) and self.overwrite:
  641. # Update map in temporal database.
  642. if self.dry_run is False:
  643. map_i.update_all(dbif)
  644. elif map_i.is_in_db(dbif) and self.overwrite is False:
  645. # Raise error if map exists and no overwrite flag is given.
  646. self.msgr.fatal("Error raster map %s exist in temporal database. "
  647. "Use overwrite flag."%map_i.get_map_id())
  648. else:
  649. # Insert map into temporal database.
  650. if self.dry_run is False:
  651. map_i.insert(dbif)
  652. # Register map in result space time dataset.
  653. if self.dry_run is False:
  654. success = resultstds.register_map(map_i, dbif)
  655. if self.dry_run is False:
  656. resultstds.update_from_registered_maps(dbif)
  657. self.process_chain_dict["STDS"]["name"] = t[1]
  658. self.process_chain_dict["STDS"]["stdstype"] = self.stdstype
  659. self.process_chain_dict["STDS"]["temporal_type"] = 'absolute'
  660. dbif.close()
  661. t[0] = register_list
  662. # Remove intermediate maps
  663. self.remove_maps()
  664. def p_expr_spmap_function(self, t):
  665. # Add a single map.
  666. # Only the spatial extent of the map is evaluated.
  667. # Temporal extent is not existing.
  668. # Examples:
  669. # R = map(A)
  670. """
  671. mapexpr : MAP LPAREN stds RPAREN
  672. """
  673. if self.run:
  674. # Check input map.
  675. input = t[3]
  676. if not isinstance(input, list):
  677. # Check for mapset in given stds input.
  678. if input.find("@") >= 0:
  679. id_input = input
  680. else:
  681. id_input = input + "@" + self.mapset
  682. # Create empty map dataset.
  683. map_i = dataset_factory(self.maptype, id_input)
  684. # Check for occurrence of space time dataset.
  685. if map_i.map_exists() == False:
  686. raise FatalError(_("%s map <%s> not found in GRASS spatial database") %
  687. (map_i.get_type(), id_input))
  688. else:
  689. # Select dataset entry from database.
  690. map_i.select(dbif=self.dbif)
  691. # Create command list for map object.
  692. cmdstring = "(%s)" %(map_i.get_map_id())
  693. map_i.cmd_list = cmdstring
  694. # Return map object.
  695. t[0] = cmdstring
  696. else:
  697. t[0] = "map(" + t[3] + ")"
  698. if self.debug:
  699. print("map(" + t[3] + ")")
  700. def p_arith1_operation(self, t):
  701. # A % B
  702. # A / B
  703. # A * B
  704. # A % td(B)
  705. # A * td(B)
  706. # A / td(B)
  707. """
  708. expr : stds MOD stds
  709. | expr MOD stds
  710. | stds MOD expr
  711. | expr MOD expr
  712. | stds DIV stds
  713. | expr DIV stds
  714. | stds DIV expr
  715. | expr DIV expr
  716. | stds MULT stds
  717. | expr MULT stds
  718. | stds MULT expr
  719. | expr MULT expr
  720. | stds MOD t_td_var
  721. | expr MOD t_td_var
  722. | stds DIV t_td_var
  723. | expr DIV t_td_var
  724. | stds MULT t_td_var
  725. | expr MULT t_td_var
  726. """
  727. # Check input stds.
  728. maplistA = self.check_stds(t[1])
  729. maplistB = self.check_stds(t[3])
  730. topolist = self.build_spatio_temporal_topology_list(maplistA, maplistB)
  731. if self.run:
  732. resultlist = []
  733. for map_i in topolist:
  734. # Generate an intermediate map for the result map list.
  735. map_new = self.generate_new_map(base_map=map_i,
  736. bool_op='and',
  737. copy=True)
  738. # Loop over temporal related maps and create overlay modules.
  739. tbrelations = map_i.get_temporal_relations()
  740. count = 0
  741. for map_j in (tbrelations['EQUAL']):
  742. # Create overlaid map extent.
  743. returncode = self.overlay_map_extent(map_new, map_j,
  744. 'and',
  745. temp_op='l')
  746. # Stop the loop if no temporal or spatial relationship exist.
  747. if returncode == 0:
  748. break
  749. if count == 0:
  750. # Set map name.
  751. name = map_new.get_id()
  752. else:
  753. # Generate an intermediate map
  754. name = self.generate_map_name()
  755. # Create r.mapcalc expression string for the operation.
  756. cmdstring = self.build_command_string(map_i, map_j,
  757. operator=t[2],
  758. cmd_type="operator")
  759. # Conditional append of module command.
  760. map_new.cmd_list = cmdstring
  761. count += 1
  762. # Append map to result map list.
  763. if returncode == 1:
  764. resultlist.append(map_new)
  765. t[0] = resultlist
  766. if self.debug:
  767. for map in resultlist:
  768. print(map.cmd_list)
  769. def p_arith1_operation_numeric1(self, t):
  770. # A % 1
  771. # A / 4
  772. # A * 5
  773. # A % map(b1)
  774. # A * map(b2)
  775. # A / map(b3)
  776. """
  777. expr : stds MOD number
  778. | expr MOD number
  779. | stds DIV number
  780. | expr DIV number
  781. | stds MULT number
  782. | expr MULT number
  783. | stds MOD numberstr
  784. | expr MOD numberstr
  785. | stds DIV numberstr
  786. | expr DIV numberstr
  787. | stds MULT numberstr
  788. | expr MULT numberstr
  789. | stds MOD mapexpr
  790. | expr MOD mapexpr
  791. | stds DIV mapexpr
  792. | expr DIV mapexpr
  793. | stds MULT mapexpr
  794. | expr MULT mapexpr
  795. """
  796. # Check input stds.
  797. maplist = self.check_stds(t[1])
  798. if self.run:
  799. resultlist = []
  800. for map_i in maplist:
  801. mapinput = map_i.get_id()
  802. # Create r.mapcalc expression string for the operation.
  803. if "cmd_list" in dir(map_i):
  804. cmdstring = "(%s %s %s)" %(map_i.cmd_list, t[2], t[3])
  805. else:
  806. cmdstring = "(%s %s %s)" %(mapinput, t[2], t[3])
  807. # Conditional append of module command.
  808. map_i.cmd_list = cmdstring
  809. # Append map to result map list.
  810. resultlist.append(map_i)
  811. t[0] = resultlist
  812. if self.debug:
  813. for map in resultlist:
  814. print(map.cmd_list)
  815. def p_arith1_operation_numeric2(self, t):
  816. # 1 % A
  817. # 4 / A
  818. # 5 * A
  819. # map(b1) % A
  820. # map(b4) / A
  821. # map(b5) * A
  822. """
  823. expr : number MOD stds
  824. | number MOD expr
  825. | number DIV stds
  826. | number DIV expr
  827. | number MULT stds
  828. | number MULT expr
  829. | numberstr MOD stds
  830. | numberstr MOD expr
  831. | numberstr DIV stds
  832. | numberstr DIV expr
  833. | numberstr MULT stds
  834. | numberstr MULT expr
  835. | mapexpr MOD stds
  836. | mapexpr MOD expr
  837. | mapexpr DIV stds
  838. | mapexpr DIV expr
  839. | mapexpr MULT stds
  840. | mapexpr MULT expr
  841. """
  842. # Check input stds.
  843. maplist = self.check_stds(t[3])
  844. if self.run:
  845. resultlist = []
  846. for map_i in maplist:
  847. mapinput = map_i.get_id()
  848. # Create r.mapcalc expression string for the operation.
  849. if "cmd_list" in dir(map_i):
  850. cmdstring = "(%s %s %s)" %(t[1], t[2], map_i.cmd_list)
  851. else:
  852. cmdstring = "(%s %s %s)" %(t[1], t[2], mapinput)
  853. # Conditional append of module command.
  854. map_i.cmd_list = cmdstring
  855. # Append map to result map list.
  856. resultlist.append(map_i)
  857. t[0] = resultlist
  858. if self.debug:
  859. for map in resultlist:
  860. print(map.cmd_list)
  861. def p_arith2_operation(self, t):
  862. # A + B
  863. # A - B
  864. # A + td(B)
  865. # A - td(B)
  866. """
  867. expr : stds ADD stds
  868. | expr ADD stds
  869. | stds ADD expr
  870. | expr ADD expr
  871. | stds SUB stds
  872. | expr SUB stds
  873. | stds SUB expr
  874. | expr SUB expr
  875. | stds ADD t_td_var
  876. | expr ADD t_td_var
  877. | expr SUB t_td_var
  878. | stds SUB t_td_var
  879. """
  880. # Check input stds.
  881. maplistA = self.check_stds(t[1])
  882. maplistB = self.check_stds(t[3])
  883. topolist = self.build_spatio_temporal_topology_list(maplistA, maplistB)
  884. if self.run:
  885. resultlist = []
  886. for map_i in topolist:
  887. # Generate an intermediate map for the result map list.
  888. map_new = self.generate_new_map(base_map=map_i,
  889. bool_op='and',
  890. copy=True)
  891. # Loop over temporal related maps and create overlay modules.
  892. tbrelations = map_i.get_temporal_relations()
  893. count = 0
  894. for map_j in (tbrelations['EQUAL']):
  895. # Create overlaid map extent.
  896. returncode = self.overlay_map_extent(map_new,
  897. map_j,
  898. 'and',
  899. temp_op='l')
  900. # Stop the loop if no temporal or spatial relationship exist.
  901. if returncode == 0:
  902. break
  903. if count == 0:
  904. # Set map name.
  905. name = map_new.get_id()
  906. else:
  907. # Generate an intermediate map
  908. name = self.generate_map_name()
  909. # Create r.mapcalc expression string for the operation.
  910. cmdstring = self.build_command_string(map_i,
  911. map_j,
  912. operator=t[2],
  913. cmd_type="operator")
  914. # Conditional append of module command.
  915. map_new.cmd_list = cmdstring
  916. count += 1
  917. # Append map to result map list.
  918. if returncode == 1:
  919. resultlist.append(map_new)
  920. t[0] = resultlist
  921. if self.debug:
  922. for map in resultlist:
  923. print(map.cmd_list)
  924. def p_arith2_operation_numeric1(self, t):
  925. # A + 2
  926. # A - 3
  927. # A + map(b4)
  928. # A - map(b5)
  929. """
  930. expr : stds ADD number
  931. | expr ADD number
  932. | stds SUB number
  933. | expr SUB number
  934. | stds ADD numberstr
  935. | expr ADD numberstr
  936. | stds SUB numberstr
  937. | expr SUB numberstr
  938. | stds ADD mapexpr
  939. | expr ADD mapexpr
  940. | stds SUB mapexpr
  941. | expr SUB mapexpr
  942. """
  943. # Check input stds.
  944. maplist = self.check_stds(t[1])
  945. if self.run:
  946. resultlist = []
  947. for map_i in maplist:
  948. mapinput = map_i.get_id()
  949. # Create r.mapcalc expression string for the operation.
  950. if "cmd_list" in dir(map_i):
  951. cmdstring = "(%s %s %s)" %(map_i.cmd_list, t[2], t[3])
  952. else:
  953. cmdstring = "(%s %s %s)" %(mapinput, t[2], t[3])
  954. # Conditional append of module command.
  955. map_i.cmd_list = cmdstring
  956. # Append map to result map list.
  957. resultlist.append(map_i)
  958. t[0] = resultlist
  959. if self.debug:
  960. for map in resultlist:
  961. print(map.cmd_list)
  962. def p_arith2_operation_numeric2(self, t):
  963. # 2 + A
  964. # 3 - A
  965. # map(b2) + A
  966. # map(b3) - A
  967. """
  968. expr : number ADD stds
  969. | number ADD expr
  970. | number SUB stds
  971. | number SUB expr
  972. | numberstr ADD stds
  973. | numberstr ADD expr
  974. | numberstr SUB stds
  975. | numberstr SUB expr
  976. | mapexpr ADD stds
  977. | mapexpr ADD expr
  978. | mapexpr SUB stds
  979. | mapexpr SUB expr
  980. """
  981. # Check input stds.
  982. maplist = self.check_stds(t[3])
  983. if self.run:
  984. resultlist = []
  985. for map_i in maplist:
  986. mapinput = map_i.get_id()
  987. # Create r.mapcalc expression string for the operation.
  988. if "cmd_list" in dir(map_i):
  989. cmdstring = "(%s %s %s)" %(t[1], t[2], map_i.cmd_list)
  990. else:
  991. cmdstring = "(%s %s %s)" %(t[1], t[2], mapinput)
  992. # Conditional append of module command.
  993. map_i.cmd_list = cmdstring
  994. # Append map to result map list.
  995. resultlist.append(map_i)
  996. t[0] = resultlist
  997. if self.debug:
  998. for map in resultlist:
  999. print(map.cmd_list)
  1000. def p_arith1_operation_relation(self, t):
  1001. # A {*, equal, l} B
  1002. # A {*, equal, l} td(B)
  1003. # A {*, equal, l} B {/, during, r} C
  1004. # A {*, equal, l} B {/, equal, l} C {/, during, r} D
  1005. """
  1006. expr : stds T_ARITH1_OPERATOR stds
  1007. | expr T_ARITH1_OPERATOR stds
  1008. | stds T_ARITH1_OPERATOR expr
  1009. | expr T_ARITH1_OPERATOR expr
  1010. | stds T_ARITH1_OPERATOR t_td_var
  1011. | expr T_ARITH1_OPERATOR t_td_var
  1012. """
  1013. if self.run:
  1014. # Check input stds.
  1015. maplistA = self.check_stds(t[1])
  1016. maplistB = self.check_stds(t[3])
  1017. relations, temporal, function, aggregate = self.eval_toperator(t[2], optype='raster')
  1018. # Build conditional values based on topological relationships.
  1019. complist = self.build_spatio_temporal_topology_list(maplistA,
  1020. maplistB,
  1021. topolist=relations,
  1022. operator_cmd=True,
  1023. compop=function)
  1024. # Set temporal extent based on topological relationships.
  1025. resultlist = self.set_temporal_extent_list(complist,
  1026. topolist=relations,
  1027. temporal=temporal)
  1028. t[0] = resultlist
  1029. if self.debug:
  1030. for map in resultlist:
  1031. print(map.cmd_list)
  1032. def p_arith2_operation_relation(self, t):
  1033. # A {+, equal, l} B
  1034. # A {+, equal, l} td(b)
  1035. # A {+, equal, l} B {-, during, r} C
  1036. # A {+, equal, l} B {+, equal, l} C {-, during, r} D
  1037. """
  1038. expr : stds T_ARITH2_OPERATOR stds
  1039. | expr T_ARITH2_OPERATOR stds
  1040. | stds T_ARITH2_OPERATOR expr
  1041. | expr T_ARITH2_OPERATOR expr
  1042. | stds T_ARITH2_OPERATOR t_td_var
  1043. | expr T_ARITH2_OPERATOR t_td_var
  1044. """
  1045. if self.run:
  1046. # Check input stds.
  1047. maplistA = self.check_stds(t[1])
  1048. maplistB = self.check_stds(t[3])
  1049. relations, temporal, function, aggregate = self.eval_toperator(t[2], optype='raster')
  1050. # Build conditional values based on topological relationships.
  1051. complist = self.build_spatio_temporal_topology_list(maplistA,
  1052. maplistB,
  1053. topolist=relations,
  1054. operator_cmd=True,
  1055. compop=function)
  1056. # Set temporal extent based on topological relationships.
  1057. resultlist = self.set_temporal_extent_list(complist,
  1058. topolist=relations,
  1059. temporal=temporal)
  1060. t[0] = resultlist
  1061. if self.debug:
  1062. for map in resultlist:
  1063. print(map.cmd_list)
  1064. def p_arith_operation_numeric_string(self, t):
  1065. # 1 + 1
  1066. # 1 - 1
  1067. # 1 * 1
  1068. # 1 / 1
  1069. # 1 % 1
  1070. """
  1071. numberstr : number ADD number
  1072. | number SUB number
  1073. | number DIV number
  1074. | number MULT number
  1075. | number MOD number
  1076. """
  1077. numstring = "(%s %s %s)" %(t[1], t[2], t[3])
  1078. t[0] = numstring
  1079. if self.debug:
  1080. print(numstring)
  1081. def p_mapcalc_function(self, t):
  1082. # Supported mapcalc functions.
  1083. """
  1084. mapcalc_arith : ABS
  1085. | LOG
  1086. | SQRT
  1087. | EXP
  1088. | COS
  1089. | ACOS
  1090. | SIN
  1091. | ASIN
  1092. | TAN
  1093. | DOUBLE
  1094. | FLOATEXP
  1095. | INTEXP
  1096. """
  1097. t[0] = t[1]
  1098. if self.debug:
  1099. print(t[1])
  1100. def p_mapcalc_operation1(self, t):
  1101. # sin(A)
  1102. # log(B)
  1103. """
  1104. expr : mapcalc_arith LPAREN stds RPAREN
  1105. | mapcalc_arith LPAREN expr RPAREN
  1106. """
  1107. # Check input stds.
  1108. maplist = self.check_stds(t[3])
  1109. if self.run:
  1110. resultlist = []
  1111. for map_i in maplist:
  1112. # Create r.mapcalc expression string for the operation.
  1113. if "cmd_list" in dir(map_i):
  1114. cmdstring = "%s(%s)" %(t[1].lower(), map_i.cmd_list)
  1115. else:
  1116. cmdstring = "%s(%s)" %(t[1].lower(), map_i.get_id())
  1117. # Set new command list for map.
  1118. map_i.cmd_list = cmdstring
  1119. # Append map with updated command list to result list.
  1120. resultlist.append(map_i)
  1121. t[0] = resultlist
  1122. if self.debug:
  1123. for map in resultlist:
  1124. print(map.cmd_list)
  1125. def p_mapexpr_operation(self, t):
  1126. # sin(map(a))
  1127. """
  1128. mapexpr : mapcalc_arith LPAREN mapexpr RPAREN
  1129. """
  1130. # Check input stds.
  1131. mapstring = t[3]
  1132. if self.run:
  1133. cmdstring = "%s(%s)" %(t[1].lower(), mapstring)
  1134. t[0] = cmdstring
  1135. if self.debug:
  1136. print(mapstring)
  1137. def p_s_var_expr_1(self, t):
  1138. # isnull(A)
  1139. """
  1140. s_var_expr : ISNULL LPAREN stds RPAREN
  1141. | ISNULL LPAREN expr RPAREN
  1142. """
  1143. # Check input stds.
  1144. maplist = self.check_stds(t[3])
  1145. if self.run:
  1146. resultlist = []
  1147. for map_i in maplist:
  1148. # Create r.mapcalc expression string for the operation.
  1149. if "cmd_list" in dir(map_i):
  1150. cmdstring = "%s(%s)" %(t[1].lower(), map_i.cmd_list)
  1151. else:
  1152. cmdstring = "%s(%s)" %(t[1].lower(), map_i.get_id())
  1153. # Set new command list for map.
  1154. map_i.cmd_list = cmdstring
  1155. # Append map with updated command list to result list.
  1156. resultlist.append(map_i)
  1157. t[0] = resultlist
  1158. if self.debug:
  1159. for map in resultlist:
  1160. print(map.cmd_list)
  1161. def p_s_var_expr_2(self, t):
  1162. # isntnull(A)
  1163. """
  1164. s_var_expr : ISNTNULL LPAREN stds RPAREN
  1165. | ISNTNULL LPAREN expr RPAREN
  1166. """
  1167. # Check input stds.
  1168. maplist = self.check_stds(t[3])
  1169. if self.run:
  1170. resultlist = []
  1171. for map_i in maplist:
  1172. # Create r.mapcalc expression string for the operation.
  1173. if "cmd_list" in dir(map_i):
  1174. cmdstring = "!isnull(%s)" %(map_i.cmd_list)
  1175. else:
  1176. cmdstring = "!isnull(%s)" %(map_i.get_id())
  1177. # Set new command list for map.
  1178. map_i.cmd_list = cmdstring
  1179. # Append map with updated command list to result list.
  1180. resultlist.append(map_i)
  1181. t[0] = resultlist
  1182. if self.debug:
  1183. for map in resultlist:
  1184. print(map.cmd_list)
  1185. def p_s_var_expr_3(self, t):
  1186. # A <= 2
  1187. """
  1188. s_var_expr : stds comp_op number
  1189. | expr comp_op number
  1190. """
  1191. # Check input stds.
  1192. maplist = self.check_stds(t[1])
  1193. if self.run:
  1194. resultlist = []
  1195. for map_i in maplist:
  1196. # Create r.mapcalc expression string for the operation.
  1197. if "cmd_list" in dir(map_i):
  1198. cmdstring = "%s %s %s" %(map_i.cmd_list, t[2], t[3])
  1199. else:
  1200. cmdstring = "%s %s %s" %(map_i.get_id(), t[2], t[3])
  1201. # Set new command list for map.
  1202. map_i.cmd_list = cmdstring
  1203. # Append map with updated command list to result list.
  1204. resultlist.append(map_i)
  1205. t[0] = resultlist
  1206. if self.debug:
  1207. for map in resultlist:
  1208. print(map.cmd_list)
  1209. def p_s_var_expr_4(self, t):
  1210. # exist(B)
  1211. """
  1212. s_var_expr : EXIST LPAREN stds RPAREN
  1213. | EXIST LPAREN expr RPAREN
  1214. """
  1215. # Check input stds.
  1216. maplist = self.check_stds(t[3])
  1217. if self.run:
  1218. resultlist = []
  1219. for map_i in maplist:
  1220. # Create r.mapcalc expression string for the operation.
  1221. if "cmd_list" in dir(map_i):
  1222. cmdstring = "%s" %(map_i.cmd_list)
  1223. else:
  1224. cmdstring = "%s" %(map_i.get_id())
  1225. # Set new command list for map.
  1226. map_i.cmd_list = cmdstring
  1227. # Append map with updated command list to result list.
  1228. resultlist.append(map_i)
  1229. t[0] = resultlist
  1230. if self.debug:
  1231. for map in resultlist:
  1232. print(map.cmd_list)
  1233. def p_s_var_expr_comp(self, t):
  1234. # A <= 2 || B == 10
  1235. # A < 3 && A > 1
  1236. """
  1237. s_var_expr : s_var_expr AND AND s_var_expr
  1238. | s_var_expr OR OR s_var_expr
  1239. """
  1240. if self.run:
  1241. # Check input stds.
  1242. s_var_exprA = self.check_stds(t[1])
  1243. s_var_exprB = self.check_stds(t[4])
  1244. relations = ["EQUAL"]
  1245. temporal = "l"
  1246. function = t[2] + t[3]
  1247. aggregate = t[2]
  1248. # Build conditional values based on topological relationships.
  1249. complist = self.build_spatio_temporal_topology_list(s_var_exprA,
  1250. s_var_exprB,
  1251. topolist=relations,
  1252. compare_cmd=True,
  1253. compop=function,
  1254. aggregate=aggregate)
  1255. # Set temporal extent based on topological relationships.
  1256. resultlist = self.set_temporal_extent_list(complist,
  1257. topolist=relations,
  1258. temporal=temporal)
  1259. t[0] = resultlist
  1260. if self.debug:
  1261. for map in resultlist:
  1262. print(map.cmd_list)
  1263. def p_s_var_expr_comp_op(self, t):
  1264. # A <= 2 {||} B == 10
  1265. # A < 3 {&&, equal} A > 1
  1266. """
  1267. s_var_expr : s_var_expr T_COMP_OPERATOR s_var_expr
  1268. """
  1269. if self.run:
  1270. # Check input stds.
  1271. s_var_exprA = self.check_stds(t[1])
  1272. s_var_exprB = self.check_stds(t[3])
  1273. # Evaluate temporal comparison operator.
  1274. relations, temporal, function, aggregate = self.eval_toperator(t[2], optype='boolean')
  1275. # Build conditional values based on topological relationships.
  1276. complist = self.build_spatio_temporal_topology_list(s_var_exprA,
  1277. s_var_exprB,
  1278. topolist=relations,
  1279. compare_cmd=True,
  1280. compop=function,
  1281. aggregate=aggregate)
  1282. # Set temporal extent based on topological relationships.
  1283. resultlist = self.set_temporal_extent_list(complist,
  1284. topolist=relations,
  1285. temporal=temporal)
  1286. t[0] = resultlist
  1287. if self.debug:
  1288. for map in resultlist:
  1289. print(map.cmd_list)
  1290. def p_s_expr_condition_if(self, t):
  1291. # if(s_var_expr, B)
  1292. # if(A == 1, B)
  1293. """
  1294. expr : IF LPAREN s_var_expr COMMA stds RPAREN
  1295. | IF LPAREN s_var_expr COMMA expr RPAREN
  1296. | IF LPAREN ts_var_expr COMMA stds RPAREN
  1297. | IF LPAREN ts_var_expr COMMA expr RPAREN
  1298. """
  1299. ifmaplist = self.check_stds(t[3])
  1300. thenmaplist = self.check_stds(t[5])
  1301. resultlist = self.build_condition_cmd_list(ifmaplist,
  1302. thenmaplist,
  1303. elselist=None,
  1304. condition_topolist=["EQUAL"],
  1305. conclusion_topolist=["EQUAL"],
  1306. temporal='r',
  1307. null=False)
  1308. t[0] = resultlist
  1309. if self.debug:
  1310. for map in resultlist:
  1311. print(map.cmd_list)
  1312. def p_s_numeric_condition_if(self, t):
  1313. # if(s_var_expr, 1)
  1314. # if(A == 5, 10)
  1315. """
  1316. expr : IF LPAREN s_var_expr COMMA number RPAREN
  1317. | IF LPAREN s_var_expr COMMA NULL LPAREN RPAREN RPAREN
  1318. | IF LPAREN ts_var_expr COMMA number RPAREN
  1319. | IF LPAREN ts_var_expr COMMA NULL LPAREN RPAREN RPAREN
  1320. """
  1321. ifmaplist = self.check_stds(t[3])
  1322. resultlist = []
  1323. # Select input for r.mapcalc expression based on length of PLY object.
  1324. if len(t) == 7:
  1325. numinput = str(t[5])
  1326. elif len(t) == 9:
  1327. numinput = str(t[5] + t[6] + t[7])
  1328. # Iterate over condition map list.
  1329. for map_i in ifmaplist:
  1330. # Create r.mapcalc expression string for the operation.
  1331. cmdstring = self.build_command_string(map_i, numinput,
  1332. cmd_type='condition')
  1333. # Conditional append of module command.
  1334. map_i.cmd_list = cmdstring
  1335. # Append map to result map list.
  1336. resultlist.append(map_i)
  1337. t[0] = resultlist
  1338. if self.debug:
  1339. for map in resultlist:
  1340. print(map.cmd_list)
  1341. def p_s_expr_condition_if_relation(self, t):
  1342. # if({equal||during}, s_var_expr, A)
  1343. """
  1344. expr : IF LPAREN T_REL_OPERATOR COMMA s_var_expr COMMA stds RPAREN
  1345. | IF LPAREN T_REL_OPERATOR COMMA s_var_expr COMMA expr RPAREN
  1346. | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA stds RPAREN
  1347. | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA expr RPAREN
  1348. """
  1349. relations, temporal, function, aggregation = self.eval_toperator(t[3],
  1350. optype='relation')
  1351. ifmaplist = self.check_stds(t[5])
  1352. thenmaplist = self.check_stds(t[7])
  1353. resultlist = self.build_condition_cmd_list(ifmaplist,
  1354. thenmaplist,
  1355. elselist=None,
  1356. condition_topolist=relations,
  1357. conclusion_topolist=["EQUAL"],
  1358. temporal='r',
  1359. null=False)
  1360. t[0] = resultlist
  1361. if self.debug:
  1362. for map in resultlist:
  1363. print(map.cmd_list)
  1364. def p_s_expr_condition_elif(self, t):
  1365. # if(s_var_expr, A, B)
  1366. """
  1367. expr : IF LPAREN s_var_expr COMMA stds COMMA stds RPAREN
  1368. | IF LPAREN s_var_expr COMMA stds COMMA expr RPAREN
  1369. | IF LPAREN s_var_expr COMMA expr COMMA stds RPAREN
  1370. | IF LPAREN s_var_expr COMMA expr COMMA expr RPAREN
  1371. | IF LPAREN ts_var_expr COMMA stds COMMA stds RPAREN
  1372. | IF LPAREN ts_var_expr COMMA stds COMMA expr RPAREN
  1373. | IF LPAREN ts_var_expr COMMA expr COMMA stds RPAREN
  1374. | IF LPAREN ts_var_expr COMMA expr COMMA expr RPAREN
  1375. """
  1376. # Check map list inputs.
  1377. ifmaplist = self.check_stds(t[3])
  1378. thenmaplist = self.check_stds(t[5])
  1379. elsemaplist = self.check_stds(t[7])
  1380. # Create conditional command map list.
  1381. resultlist = self.build_condition_cmd_list(ifmaplist,
  1382. thenmaplist,
  1383. elselist=elsemaplist,
  1384. condition_topolist=["EQUAL"],
  1385. conclusion_topolist=["EQUAL"],
  1386. temporal='r',
  1387. null=False)
  1388. t[0] = resultlist
  1389. if self.debug:
  1390. for map in resultlist:
  1391. print(map.cmd_list)
  1392. def p_s_numeric_condition_elif(self, t):
  1393. # if(s_var_expr, 1, 2)
  1394. # if(A == 5, 10, 0)
  1395. """
  1396. expr : IF LPAREN s_var_expr COMMA number COMMA number RPAREN
  1397. | IF LPAREN s_var_expr COMMA NULL LPAREN RPAREN COMMA number RPAREN
  1398. | IF LPAREN s_var_expr COMMA number COMMA NULL LPAREN RPAREN RPAREN
  1399. | IF LPAREN s_var_expr COMMA NULL LPAREN RPAREN COMMA NULL LPAREN RPAREN RPAREN
  1400. | IF LPAREN ts_var_expr COMMA number COMMA number RPAREN
  1401. | IF LPAREN ts_var_expr COMMA NULL LPAREN RPAREN COMMA number RPAREN
  1402. | IF LPAREN ts_var_expr COMMA number COMMA NULL LPAREN RPAREN RPAREN
  1403. | IF LPAREN ts_var_expr COMMA NULL LPAREN RPAREN COMMA NULL LPAREN RPAREN RPAREN
  1404. """
  1405. ifmaplist = self.check_stds(t[3])
  1406. # Select input for r.mapcalc expression based on length of PLY object.
  1407. if len(t) == 9:
  1408. numthen = t[5]
  1409. numelse = t[7]
  1410. elif len(t) == 11 and t[6] == '(':
  1411. numthen = t[5] + t[6] + t[7]
  1412. numelse = t[9]
  1413. elif len(t) == 11 and t[6] == ',':
  1414. numthen = t[5]
  1415. numelse = t[7] + t[8] + t[9]
  1416. elif len(t) == 13:
  1417. numthen = t[5] + t[6] + t[7]
  1418. numelse = t[9] + t[10] + t[11]
  1419. numthen = str(numthen)
  1420. numelse = str(numelse)
  1421. print(numthen + " " +numelse )
  1422. # Create conditional command map list.
  1423. resultlist = self.build_condition_cmd_list(ifmaplist,
  1424. numthen,
  1425. numelse,
  1426. condition_topolist=["EQUAL"],
  1427. conclusion_topolist=["EQUAL"],
  1428. temporal='r',
  1429. null=False)
  1430. t[0] = resultlist
  1431. if self.debug:
  1432. for map in resultlist:
  1433. print(map.cmd_list)
  1434. def p_s_numeric_expr_condition_elif(self, t):
  1435. # if(s_var_expr, 1, A)
  1436. # if(A == 5 && C > 5, A, null())
  1437. """
  1438. expr : IF LPAREN s_var_expr COMMA number COMMA stds RPAREN
  1439. | IF LPAREN s_var_expr COMMA NULL LPAREN RPAREN COMMA stds RPAREN
  1440. | IF LPAREN s_var_expr COMMA number COMMA expr RPAREN
  1441. | IF LPAREN s_var_expr COMMA NULL LPAREN RPAREN COMMA expr RPAREN
  1442. | IF LPAREN s_var_expr COMMA stds COMMA number RPAREN
  1443. | IF LPAREN s_var_expr COMMA stds COMMA NULL LPAREN RPAREN RPAREN
  1444. | IF LPAREN s_var_expr COMMA expr COMMA number RPAREN
  1445. | IF LPAREN s_var_expr COMMA expr COMMA NULL LPAREN RPAREN RPAREN
  1446. | IF LPAREN ts_var_expr COMMA number COMMA stds RPAREN
  1447. | IF LPAREN ts_var_expr COMMA NULL LPAREN RPAREN COMMA stds RPAREN
  1448. | IF LPAREN ts_var_expr COMMA number COMMA expr RPAREN
  1449. | IF LPAREN ts_var_expr COMMA NULL LPAREN RPAREN COMMA expr RPAREN
  1450. | IF LPAREN ts_var_expr COMMA stds COMMA number RPAREN
  1451. | IF LPAREN ts_var_expr COMMA stds COMMA NULL LPAREN RPAREN RPAREN
  1452. | IF LPAREN ts_var_expr COMMA expr COMMA number RPAREN
  1453. | IF LPAREN ts_var_expr COMMA expr COMMA NULL LPAREN RPAREN RPAREN
  1454. """
  1455. ifmaplist = self.check_stds(t[3])
  1456. # Select input for r.mapcalc expression based on length of PLY object.
  1457. if len(t) == 9:
  1458. if isinstance(t[5], int):
  1459. theninput = str(t[5])
  1460. elseinput = self.check_stds(t[7])
  1461. elif isinstance(t[7], int):
  1462. theninput = self.check_stds(t[5])
  1463. elseinput = str(t[7])
  1464. elif len(t) == 11:
  1465. if t[5] == 'null':
  1466. theninput = str(t[5] + t[6] + t[7])
  1467. elseinput = self.check_stds(t[9])
  1468. elif t[7] == 'null':
  1469. theninput = self.check_stds(t[5])
  1470. elseinput = str(t[7] + t[8] + t[9])
  1471. # Create conditional command map list.
  1472. resultlist = self.build_condition_cmd_list(ifmaplist,
  1473. theninput,
  1474. elseinput,
  1475. condition_topolist=["EQUAL"],
  1476. conclusion_topolist=["EQUAL"],
  1477. temporal='r',
  1478. null=False)
  1479. t[0] = resultlist
  1480. if self.debug:
  1481. for map in resultlist:
  1482. print(map.cmd_list)
  1483. def p_s_numeric_expr_condition_elif_relation(self, t):
  1484. # if({during},s_var_expr, 1, A)
  1485. # if({during}, A == 5, A, null())
  1486. """
  1487. expr : IF LPAREN T_REL_OPERATOR COMMA s_var_expr COMMA number COMMA stds RPAREN
  1488. | IF LPAREN T_REL_OPERATOR COMMA s_var_expr COMMA NULL LPAREN RPAREN COMMA stds RPAREN
  1489. | IF LPAREN T_REL_OPERATOR COMMA s_var_expr COMMA number COMMA expr RPAREN
  1490. | IF LPAREN T_REL_OPERATOR COMMA s_var_expr COMMA NULL LPAREN RPAREN COMMA expr RPAREN
  1491. | IF LPAREN T_REL_OPERATOR COMMA s_var_expr COMMA stds COMMA number RPAREN
  1492. | IF LPAREN T_REL_OPERATOR COMMA s_var_expr COMMA stds COMMA NULL LPAREN RPAREN RPAREN
  1493. | IF LPAREN T_REL_OPERATOR COMMA s_var_expr COMMA expr COMMA number RPAREN
  1494. | IF LPAREN T_REL_OPERATOR COMMA s_var_expr COMMA expr COMMA NULL LPAREN RPAREN RPAREN
  1495. | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA number COMMA stds RPAREN
  1496. | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA NULL LPAREN RPAREN COMMA stds RPAREN
  1497. | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA number COMMA expr RPAREN
  1498. | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA NULL LPAREN RPAREN COMMA expr RPAREN
  1499. | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA stds COMMA number RPAREN
  1500. | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA stds COMMA NULL LPAREN RPAREN RPAREN
  1501. | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA expr COMMA number RPAREN
  1502. | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA expr COMMA NULL LPAREN RPAREN RPAREN
  1503. """
  1504. relations, temporal, function, aggregation = self.eval_toperator(t[3], optype='relation')
  1505. ifmaplist = self.check_stds(t[5])
  1506. # Select input for r.mapcalc expression based on length of PLY object.
  1507. if len(t) == 11:
  1508. if isinstance(t[7], int):
  1509. theninput = str(t[7])
  1510. elseinput = self.check_stds(t[9])
  1511. elif isinstance(t[9], int):
  1512. theninput = self.check_stds(t[7])
  1513. elseinput = str(t[9])
  1514. elif len(t) == 13:
  1515. if t[7] == 'null':
  1516. theninput = str(t[7] + t[8] + t[9])
  1517. elseinput = self.check_stds(t[11])
  1518. elif t[9] == 'null':
  1519. theninput = self.check_stds(t[7])
  1520. elseinput = str(t[9] + t[10] + t[11])
  1521. # Create conditional command map list.
  1522. resultlist = self.build_condition_cmd_list(ifmaplist,
  1523. theninput,
  1524. elseinput,
  1525. condition_topolist=relations,
  1526. conclusion_topolist=["EQUAL"],
  1527. temporal='r',
  1528. null=False)
  1529. t[0] = resultlist
  1530. if self.debug:
  1531. for map in resultlist:
  1532. print(map.cmd_list)
  1533. def p_s_expr_condition_elif_relation(self, t):
  1534. # if({equal||during}, s_var_expr, A, B)
  1535. """
  1536. expr : IF LPAREN T_REL_OPERATOR COMMA s_var_expr COMMA stds COMMA stds RPAREN
  1537. | IF LPAREN T_REL_OPERATOR COMMA s_var_expr COMMA stds COMMA expr RPAREN
  1538. | IF LPAREN T_REL_OPERATOR COMMA s_var_expr COMMA expr COMMA stds RPAREN
  1539. | IF LPAREN T_REL_OPERATOR COMMA s_var_expr COMMA expr COMMA expr RPAREN
  1540. | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA stds COMMA stds RPAREN
  1541. | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA stds COMMA expr RPAREN
  1542. | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA expr COMMA stds RPAREN
  1543. | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA expr COMMA expr RPAREN
  1544. """
  1545. relations, temporal, function, aggregation = self.eval_toperator(t[3], optype='relation')
  1546. ifmaplist = self.check_stds(t[5])
  1547. thenmaplist = self.check_stds(t[7])
  1548. elsemaplist = self.check_stds(t[9])
  1549. # Create conditional command map list.
  1550. resultlist = self.build_condition_cmd_list(ifmaplist,
  1551. thenmaplist,
  1552. elsemaplist,
  1553. condition_topolist=relations,
  1554. conclusion_topolist=["EQUAL"],
  1555. temporal='r',
  1556. null=False)
  1557. t[0] = resultlist
  1558. if self.debug:
  1559. for map in resultlist:
  1560. print(map.cmd_list)
  1561. def p_ts_var_expr1(self, t):
  1562. # Combination of spatial and temporal conditional expressions.
  1563. # Examples:
  1564. # A <= 2 || start_date <= 2013-01-01
  1565. # end_date > 2013-01-15 && A > 10
  1566. # IMPORTANT: Only the intersection of map lists in conditionals are
  1567. # exported.
  1568. """
  1569. ts_var_expr : s_var_expr AND AND t_var_expr
  1570. | t_var_expr AND AND s_var_expr
  1571. | t_var_expr OR OR s_var_expr
  1572. | s_var_expr OR OR t_var_expr
  1573. | ts_var_expr AND AND s_var_expr
  1574. | ts_var_expr AND AND t_var_expr
  1575. | ts_var_expr OR OR s_var_expr
  1576. | ts_var_expr OR OR t_var_expr
  1577. | s_var_expr AND AND ts_var_expr
  1578. | t_var_expr AND AND ts_var_expr
  1579. | s_var_expr OR OR ts_var_expr
  1580. | t_var_expr OR OR ts_var_expr
  1581. """
  1582. if self.run:
  1583. # Check input stds.
  1584. s_var_exprA = self.check_stds(t[1])
  1585. s_var_exprB = self.check_stds(t[4])
  1586. relations = ["EQUAL"]
  1587. temporal = "l"
  1588. function = t[2] + t[3]
  1589. aggregate = t[2]
  1590. # Build conditional values based on topological relationships.
  1591. complist = self.build_spatio_temporal_topology_list(s_var_exprA,
  1592. s_var_exprB,
  1593. topolist=relations,
  1594. compare_cmd=True,
  1595. compop=function,
  1596. aggregate=aggregate,
  1597. convert=True)
  1598. # Set temporal extent based on topological relationships.
  1599. resultlist = self.set_temporal_extent_list(complist,
  1600. topolist=relations,
  1601. temporal=temporal)
  1602. t[0] = resultlist
  1603. def p_hash_operation(self, t):
  1604. # Calculate the number of maps within an interval of another map from a
  1605. # second space time dataset.
  1606. # A # B
  1607. # A {equal,r#} B
  1608. """
  1609. expr : t_hash_var
  1610. """
  1611. # Check input stds.
  1612. maplist = self.check_stds(t[1])
  1613. if self.run:
  1614. resultlist = []
  1615. for map_i in maplist:
  1616. for obj in map_i.map_value:
  1617. if isinstance(obj, GlobalTemporalVar):
  1618. n_maps = obj.td
  1619. mapinput = map_i.get_id()
  1620. # Create r.mapcalc expression string for the operation.
  1621. cmdstring = "(%s)" %(n_maps)
  1622. # Append module command.
  1623. map_i.cmd_list = cmdstring
  1624. # Append map to result map list.
  1625. resultlist.append(map_i)
  1626. t[0] = resultlist
  1627. if self.debug:
  1628. for map in resultlist:
  1629. print(map.cmd_list)
  1630. ###############################################################################
  1631. if __name__ == "__main__":
  1632. import doctest
  1633. doctest.testmod()