temporal_raster_base_algebra.py 70 KB

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