temporal_raster_base_algebra.py 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652
  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. # This function executes the processing of raster/raster3d algebra
  480. # that was build based on the expression
  481. """
  482. statement : stds EQUALS expr
  483. """
  484. if self.run:
  485. # Create the process queue for parallel mapcalc processing
  486. if self.dry_run is False:
  487. process_queue = pymod.ParallelModuleQueue(int(self.nprocs))
  488. if isinstance(t[3], list):
  489. num = len(t[3])
  490. count = 0
  491. returncode = 0
  492. register_list = []
  493. for i in range(num):
  494. # Check if resultmap names exist in GRASS database.
  495. map_name = self.basename + "_" + str(i) + "@" + self.mapset
  496. if self.stdstype == "strds":
  497. new_map = RasterDataset(map_name)
  498. else:
  499. new_map = Raster3DDataset(map_name)
  500. if new_map.map_exists() and self.overwrite == False:
  501. self.msgr.fatal("Error maps with basename %s exist. "
  502. "Use --o flag to overwrite existing file"%map_name)
  503. map_test_list = []
  504. for map_i in t[3]:
  505. newident = self.basename + "_" + str(count)
  506. if "cmd_list" in dir(map_i):
  507. # Build r.mapcalc module and execute expression.
  508. # Change map name to given basename.
  509. # Create deepcopy of r.mapcalc module.
  510. map_test = map_i.get_new_instance(newident + "@" + self.mapset)
  511. map_test.set_temporal_extent(map_i.get_temporal_extent())
  512. map_test.set_spatial_extent(map_i.get_spatial_extent())
  513. map_test_list.append(map_test)
  514. m = copy.deepcopy(self.m_mapcalc)
  515. m_expression = newident + "=" + map_i.cmd_list
  516. m.inputs["expression"].value = str(m_expression)
  517. m.flags["overwrite"].value = self.overwrite
  518. if self.dry_run is False:
  519. process_queue.put(m)
  520. elif map_i.map_exists():
  521. # Copy map if it exists
  522. map_test = map_i.get_new_instance(newident + "@" + self.mapset)
  523. map_test.set_temporal_extent(map_i.get_temporal_extent())
  524. map_test.set_spatial_extent(map_i.get_spatial_extent())
  525. map_test_list.append(map_test)
  526. m = copy.deepcopy(self.m_mapcalc)
  527. m_expression = newident + "=" + map_i.get_map_id()
  528. m.inputs["expression"].value = str(m_expression)
  529. m.flags["overwrite"].value = self.overwrite
  530. if self.dry_run is False:
  531. process_queue.put(m)
  532. else:
  533. self.msgr.error(_("Error computing map <%s>"%map_i.get_id()))
  534. count += 1
  535. if self.dry_run is False:
  536. process_queue.wait()
  537. for map_i in map_test_list:
  538. register_list.append(map_i)
  539. # Open connection to temporal database.
  540. dbif, connect = init_dbif(self.dbif)
  541. # Create result space time dataset.
  542. if self.dry_run is False:
  543. resultstds = open_new_stds(t[1], self.stdstype,
  544. 'absolute', t[1], t[1],
  545. 'mean', self.dbif,
  546. overwrite = self.overwrite)
  547. for map_i in register_list:
  548. # Get meta data from grass database.
  549. map_i.load()
  550. # Do not register empty maps if not required
  551. # In case of a null map continue, do not register null maps
  552. if map_i.metadata.get_min() is None and \
  553. map_i.metadata.get_max() is None:
  554. if not self.register_null:
  555. self.removable_maps[map_i.get_name()] = map_i
  556. continue
  557. if map_i.is_in_db(dbif) and self.overwrite:
  558. # Update map in temporal database.
  559. if self.dry_run is False:
  560. map_i.update_all(dbif)
  561. elif map_i.is_in_db(dbif) and self.overwrite == False:
  562. # Raise error if map exists and no overwrite flag is given.
  563. self.msgr.fatal("Error raster map %s exist in temporal database. "
  564. "Use overwrite flag."%map_i.get_map_id())
  565. else:
  566. # Insert map into temporal database.
  567. if self.dry_run is False:
  568. map_i.insert(dbif)
  569. # Register map in result space time dataset.
  570. if self.dry_run is False:
  571. success = resultstds.register_map(map_i, dbif)
  572. if self.dry_run is False:
  573. resultstds.update_from_registered_maps(dbif)
  574. dbif.close()
  575. t[0] = register_list
  576. # Remove intermediate maps
  577. self.remove_maps()
  578. def p_expr_spmap_function(self, t):
  579. # Add a single map.
  580. # Only the spatial extent of the map is evaluated.
  581. # Temporal extent is not existing.
  582. # Examples:
  583. # R = map(A)
  584. """
  585. mapexpr : MAP LPAREN stds RPAREN
  586. """
  587. if self.run:
  588. # Check input map.
  589. input = t[3]
  590. if not isinstance(input, list):
  591. # Check for mapset in given stds input.
  592. if input.find("@") >= 0:
  593. id_input = input
  594. else:
  595. id_input = input + "@" + self.mapset
  596. # Create empty map dataset.
  597. map_i = dataset_factory(self.maptype, id_input)
  598. # Check for occurrence of space time dataset.
  599. if map_i.map_exists() == False:
  600. raise FatalError(_("%s map <%s> not found in GRASS spatial database") %
  601. (map_i.get_type(), id_input))
  602. else:
  603. # Select dataset entry from database.
  604. map_i.select(dbif=self.dbif)
  605. # Create command list for map object.
  606. cmdstring = "(%s)" %(map_i.get_map_id())
  607. map_i.cmd_list = cmdstring
  608. # Return map object.
  609. t[0] = cmdstring
  610. else:
  611. t[0] = "map(" + t[3] + ")"
  612. if self.debug:
  613. print("map(" + t[3] + ")")
  614. def p_arith1_operation(self, t):
  615. """
  616. expr : stds MOD stds
  617. | expr MOD stds
  618. | stds MOD expr
  619. | expr MOD expr
  620. | stds DIV stds
  621. | expr DIV stds
  622. | stds DIV expr
  623. | expr DIV expr
  624. | stds MULT stds
  625. | expr MULT stds
  626. | stds MULT expr
  627. | expr MULT expr
  628. | stds MOD t_td_var
  629. | expr MOD t_td_var
  630. | stds DIV t_td_var
  631. | expr DIV t_td_var
  632. | stds MULT t_td_var
  633. | expr MULT t_td_var
  634. """
  635. # Check input stds.
  636. maplistA = self.check_stds(t[1])
  637. maplistB = self.check_stds(t[3])
  638. topolist = self.get_temporal_topo_list(maplistA, maplistB)
  639. if self.run:
  640. resultlist = []
  641. for map_i in topolist:
  642. # Generate an intermediate map for the result map list.
  643. map_new = self.generate_new_map(base_map=map_i, bool_op = 'and', copy = True)
  644. # Loop over temporal related maps and create overlay modules.
  645. tbrelations = map_i.get_temporal_relations()
  646. count = 0
  647. for map_j in (tbrelations['EQUAL']):
  648. # Create overlayed map extent.
  649. returncode = self.overlay_map_extent(map_new, map_j, 'and', \
  650. temp_op = 'l')
  651. # Stop the loop if no temporal or spatial relationship exist.
  652. if returncode == 0:
  653. break
  654. if count == 0:
  655. # Set map name.
  656. name = map_new.get_id()
  657. else:
  658. # Generate an intermediate map
  659. name = self.generate_map_name()
  660. # Create r.mapcalc expression string for the operation.
  661. cmdstring = self.build_command_string(map_i, map_j,
  662. operator = t[2],
  663. cmd_type = "operator")
  664. # Conditional append of module command.
  665. map_new.cmd_list = cmdstring
  666. count += 1
  667. # Append map to result map list.
  668. if returncode == 1:
  669. resultlist.append(map_new)
  670. t[0] = resultlist
  671. if self.debug:
  672. for map in resultlist:
  673. print(map.cmd_list)
  674. def p_arith1_operation_numeric1(self, t):
  675. """
  676. expr : stds MOD number
  677. | expr MOD number
  678. | stds DIV number
  679. | expr DIV number
  680. | stds MULT number
  681. | expr MULT number
  682. | stds MOD numberstr
  683. | expr MOD numberstr
  684. | stds DIV numberstr
  685. | expr DIV numberstr
  686. | stds MULT numberstr
  687. | expr MULT numberstr
  688. | stds MOD mapexpr
  689. | expr MOD mapexpr
  690. | stds DIV mapexpr
  691. | expr DIV mapexpr
  692. | stds MULT mapexpr
  693. | expr MULT mapexpr
  694. """
  695. # Check input stds.
  696. maplist = self.check_stds(t[1])
  697. if self.run:
  698. resultlist = []
  699. for map_i in maplist:
  700. mapinput = map_i.get_id()
  701. # Create r.mapcalc expression string for the operation.
  702. if "cmd_list" in dir(map_i):
  703. cmdstring = "(%s %s %s)" %(map_i.cmd_list, t[2], t[3])
  704. else:
  705. cmdstring = "(%s %s %s)" %(mapinput, t[2], t[3])
  706. # Conditional append of module command.
  707. map_i.cmd_list = cmdstring
  708. # Append map to result map list.
  709. resultlist.append(map_i)
  710. t[0] = resultlist
  711. if self.debug:
  712. for map in resultlist:
  713. print(map.cmd_list)
  714. def p_arith1_operation_numeric2(self, t):
  715. """
  716. expr : number MOD stds
  717. | number MOD expr
  718. | number DIV stds
  719. | number DIV expr
  720. | number MULT stds
  721. | number MULT expr
  722. | numberstr MOD stds
  723. | numberstr MOD expr
  724. | numberstr DIV stds
  725. | numberstr DIV expr
  726. | numberstr MULT stds
  727. | numberstr MULT expr
  728. | mapexpr MOD stds
  729. | mapexpr MOD expr
  730. | mapexpr DIV stds
  731. | mapexpr DIV expr
  732. | mapexpr MULT stds
  733. | mapexpr MULT expr
  734. """
  735. # Check input stds.
  736. maplist = self.check_stds(t[3])
  737. if self.run:
  738. resultlist = []
  739. for map_i in maplist:
  740. mapinput = map_i.get_id()
  741. # Create r.mapcalc expression string for the operation.
  742. if "cmd_list" in dir(map_i):
  743. cmdstring = "(%s %s %s)" %(t[1], t[2], map_i.cmd_list)
  744. else:
  745. cmdstring = "(%s %s %s)" %(t[1], t[2], mapinput)
  746. # Conditional append of module command.
  747. map_i.cmd_list = cmdstring
  748. # Append map to result map list.
  749. resultlist.append(map_i)
  750. t[0] = resultlist
  751. if self.debug:
  752. for map in resultlist:
  753. print(map.cmd_list)
  754. def p_arith2_operation(self, t):
  755. """
  756. expr : stds ADD stds
  757. | expr ADD stds
  758. | stds ADD expr
  759. | expr ADD expr
  760. | stds SUB stds
  761. | expr SUB stds
  762. | stds SUB expr
  763. | expr SUB expr
  764. | stds ADD t_td_var
  765. | expr ADD t_td_var
  766. | expr SUB t_td_var
  767. | stds SUB t_td_var
  768. """
  769. # Check input stds.
  770. maplistA = self.check_stds(t[1])
  771. maplistB = self.check_stds(t[3])
  772. topolist = self.get_temporal_topo_list(maplistA, maplistB)
  773. if self.run:
  774. resultlist = []
  775. for map_i in topolist:
  776. # Generate an intermediate map for the result map list.
  777. map_new = self.generate_new_map(base_map=map_i, bool_op = 'and', copy = True)
  778. # Loop over temporal related maps and create overlay modules.
  779. tbrelations = map_i.get_temporal_relations()
  780. count = 0
  781. for map_j in (tbrelations['EQUAL']):
  782. # Create overlayed map extent.
  783. returncode = self.overlay_map_extent(map_new, map_j, 'and', \
  784. temp_op = 'l')
  785. # Stop the loop if no temporal or spatial relationship exist.
  786. if returncode == 0:
  787. break
  788. if count == 0:
  789. # Set map name.
  790. name = map_new.get_id()
  791. else:
  792. # Generate an intermediate map
  793. name = self.generate_map_name()
  794. # Create r.mapcalc expression string for the operation.
  795. cmdstring = self.build_command_string(map_i, map_j,
  796. operator = t[2],
  797. cmd_type = "operator")
  798. # Conditional append of module command.
  799. map_new.cmd_list = cmdstring
  800. count += 1
  801. # Append map to result map list.
  802. if returncode == 1:
  803. resultlist.append(map_new)
  804. t[0] = resultlist
  805. if self.debug:
  806. for map in resultlist:
  807. print(map.cmd_list)
  808. def p_arith2_operation_numeric1(self, t):
  809. """
  810. expr : stds ADD number
  811. | expr ADD number
  812. | stds SUB number
  813. | expr SUB number
  814. | stds ADD numberstr
  815. | expr ADD numberstr
  816. | stds SUB numberstr
  817. | expr SUB numberstr
  818. | stds ADD mapexpr
  819. | expr ADD mapexpr
  820. | stds SUB mapexpr
  821. | expr SUB mapexpr
  822. """
  823. # Check input stds.
  824. maplist = self.check_stds(t[1])
  825. if self.run:
  826. resultlist = []
  827. for map_i in maplist:
  828. mapinput = map_i.get_id()
  829. # Create r.mapcalc expression string for the operation.
  830. if "cmd_list" in dir(map_i):
  831. cmdstring = "(%s %s %s)" %(map_i.cmd_list, t[2], t[3])
  832. else:
  833. cmdstring = "(%s %s %s)" %(mapinput, t[2], t[3])
  834. # Conditional append of module command.
  835. map_i.cmd_list = cmdstring
  836. # Append map to result map list.
  837. resultlist.append(map_i)
  838. t[0] = resultlist
  839. if self.debug:
  840. for map in resultlist:
  841. print(map.cmd_list)
  842. def p_arith2_operation_numeric2(self, t):
  843. """
  844. expr : number ADD stds
  845. | number ADD expr
  846. | number SUB stds
  847. | number SUB expr
  848. | numberstr ADD stds
  849. | numberstr ADD expr
  850. | numberstr SUB stds
  851. | numberstr SUB expr
  852. | mapexpr ADD stds
  853. | mapexpr ADD expr
  854. | mapexpr SUB stds
  855. | mapexpr SUB expr
  856. """
  857. # Check input stds.
  858. maplist = self.check_stds(t[3])
  859. if self.run:
  860. resultlist = []
  861. for map_i in maplist:
  862. mapinput = map_i.get_id()
  863. # Create r.mapcalc expression string for the operation.
  864. if "cmd_list" in dir(map_i):
  865. cmdstring = "(%s %s %s)" %(t[1], t[2], map_i.cmd_list)
  866. else:
  867. cmdstring = "(%s %s %s)" %(t[1], t[2], mapinput)
  868. # Conditional append of module command.
  869. map_i.cmd_list = cmdstring
  870. # Append map to result map list.
  871. resultlist.append(map_i)
  872. t[0] = resultlist
  873. if self.debug:
  874. for map in resultlist:
  875. print(map.cmd_list)
  876. def p_arith1_operation_relation(self, t):
  877. """
  878. expr : stds T_ARITH1_OPERATOR stds
  879. | expr T_ARITH1_OPERATOR stds
  880. | stds T_ARITH1_OPERATOR expr
  881. | expr T_ARITH1_OPERATOR expr
  882. | stds T_ARITH1_OPERATOR t_td_var
  883. | expr T_ARITH1_OPERATOR t_td_var
  884. """
  885. if self.run:
  886. # Check input stds.
  887. maplistA = self.check_stds(t[1])
  888. maplistB = self.check_stds(t[3])
  889. relations, temporal, function, aggregate = self.eval_toperator(t[2], optype = 'raster')
  890. # Build conditional values based on topological relationships.
  891. complist = self.get_temporal_topo_list(maplistA, maplistB, topolist = relations,
  892. operator_cmd = True, compop = function)
  893. # Set temporal extent based on topological relationships.
  894. resultlist = self.set_temporal_extent_list(complist, topolist = relations,
  895. temporal = temporal)
  896. t[0] = resultlist
  897. if self.debug:
  898. for map in resultlist:
  899. print(map.cmd_list)
  900. def p_arith2_operation_relation(self, t):
  901. """
  902. expr : stds T_ARITH2_OPERATOR stds
  903. | expr T_ARITH2_OPERATOR stds
  904. | stds T_ARITH2_OPERATOR expr
  905. | expr T_ARITH2_OPERATOR expr
  906. | stds T_ARITH2_OPERATOR t_td_var
  907. | expr T_ARITH2_OPERATOR t_td_var
  908. """
  909. if self.run:
  910. # Check input stds.
  911. maplistA = self.check_stds(t[1])
  912. maplistB = self.check_stds(t[3])
  913. relations, temporal, function, aggregate = self.eval_toperator(t[2], optype = 'raster')
  914. # Build conditional values based on topological relationships.
  915. complist = self.get_temporal_topo_list(maplistA, maplistB, topolist = relations,
  916. operator_cmd = True, compop = function)
  917. # Set temporal extent based on topological relationships.
  918. resultlist = self.set_temporal_extent_list(complist, topolist = relations,
  919. temporal = temporal)
  920. t[0] = resultlist
  921. if self.debug:
  922. for map in resultlist:
  923. print(map.cmd_list)
  924. def p_arith_operation_numeric_string(self, t):
  925. """
  926. numberstr : number ADD number
  927. | number SUB number
  928. | number DIV number
  929. | number MULT number
  930. | number MOD number
  931. """
  932. numstring = "(%s %s %s)" %(t[1], t[2], t[3])
  933. t[0] = numstring
  934. if self.debug:
  935. print(numstring)
  936. def p_mapcalc_function(self, t):
  937. # Supported mapcalc functions.
  938. """
  939. mapcalc_arith : ABS
  940. | LOG
  941. | SQRT
  942. | EXP
  943. | COS
  944. | ACOS
  945. | SIN
  946. | ASIN
  947. | TAN
  948. | DOUBLE
  949. | FLOATEXP
  950. | INTEXP
  951. """
  952. t[0] = t[1]
  953. if self.debug:
  954. for map in resultlist:
  955. print(map.cmd_list)
  956. def p_mapcalc_operation1(self, t):
  957. # Examples:
  958. # sin(A)
  959. # log(B)
  960. """
  961. expr : mapcalc_arith LPAREN stds RPAREN
  962. | mapcalc_arith LPAREN expr RPAREN
  963. """
  964. # Check input stds.
  965. maplist = self.check_stds(t[3])
  966. if self.run:
  967. resultlist = []
  968. for map_i in maplist:
  969. # Create r.mapcalc expression string for the operation.
  970. if "cmd_list" in dir(map_i):
  971. cmdstring = "%s(%s)" %(t[1].lower(), map_i.cmd_list)
  972. else:
  973. cmdstring = "%s(%s)" %(t[1].lower(), map_i.get_id())
  974. # Set new command list for map.
  975. map_i.cmd_list = cmdstring
  976. # Append map with updated command list to result list.
  977. resultlist.append(map_i)
  978. t[0] = resultlist
  979. if self.debug:
  980. for map in resultlist:
  981. print(map.cmd_list)
  982. def p_mapexpr_operation(self, t):
  983. # Examples:
  984. # sin(map(a))
  985. """
  986. mapexpr : mapcalc_arith LPAREN mapexpr RPAREN
  987. """
  988. # Check input stds.
  989. mapstring = t[3]
  990. if self.run:
  991. cmdstring = "%s(%s)" %(t[1].lower(), mapstring)
  992. t[0] = cmdstring
  993. if self.debug:
  994. print(mapstring)
  995. def p_s_var_expr_1(self, t):
  996. # Examples:
  997. # isnull(A)
  998. """
  999. s_var_expr : ISNULL LPAREN stds RPAREN
  1000. | ISNULL LPAREN expr RPAREN
  1001. """
  1002. # Check input stds.
  1003. maplist = self.check_stds(t[3])
  1004. if self.run:
  1005. resultlist = []
  1006. for map_i in maplist:
  1007. # Create r.mapcalc expression string for the operation.
  1008. if "cmd_list" in dir(map_i):
  1009. cmdstring = "%s(%s)" %(t[1].lower(), map_i.cmd_list)
  1010. else:
  1011. cmdstring = "%s(%s)" %(t[1].lower(), map_i.get_id())
  1012. # Set new command list for map.
  1013. map_i.cmd_list = cmdstring
  1014. # Append map with updated command list to result list.
  1015. resultlist.append(map_i)
  1016. t[0] = resultlist
  1017. if self.debug:
  1018. for map in resultlist:
  1019. print(map.cmd_list)
  1020. def p_s_var_expr_2(self, t):
  1021. # Examples:
  1022. # isntnull(A)
  1023. """
  1024. s_var_expr : ISNTNULL LPAREN stds RPAREN
  1025. | ISNTNULL LPAREN expr RPAREN
  1026. """
  1027. # Check input stds.
  1028. maplist = self.check_stds(t[3])
  1029. if self.run:
  1030. resultlist = []
  1031. for map_i in maplist:
  1032. # Create r.mapcalc expression string for the operation.
  1033. if "cmd_list" in dir(map_i):
  1034. cmdstring = "!isnull(%s)" %(map_i.cmd_list)
  1035. else:
  1036. cmdstring = "!isnull(%s)" %(map_i.get_id())
  1037. # Set new command list for map.
  1038. map_i.cmd_list = cmdstring
  1039. # Append map with updated command list to result list.
  1040. resultlist.append(map_i)
  1041. t[0] = resultlist
  1042. if self.debug:
  1043. for map in resultlist:
  1044. print(map.cmd_list)
  1045. def p_s_var_expr_3(self, t):
  1046. # Examples:
  1047. # A <= 2
  1048. """
  1049. s_var_expr : stds comp_op number
  1050. | expr comp_op number
  1051. """
  1052. # Check input stds.
  1053. maplist = self.check_stds(t[1])
  1054. if self.run:
  1055. resultlist = []
  1056. for map_i in maplist:
  1057. # Create r.mapcalc expression string for the operation.
  1058. if "cmd_list" in dir(map_i):
  1059. cmdstring = "%s %s %s" %(map_i.cmd_list, t[2], t[3])
  1060. else:
  1061. cmdstring = "%s %s %s" %(map_i.get_id(), t[2], t[3])
  1062. # Set new command list for map.
  1063. map_i.cmd_list = cmdstring
  1064. # Append map with updated command list to result list.
  1065. resultlist.append(map_i)
  1066. t[0] = resultlist
  1067. if self.debug:
  1068. for map in resultlist:
  1069. print(map.cmd_list)
  1070. def p_s_var_expr_4(self, t):
  1071. # Examples:
  1072. # exist(B)
  1073. """
  1074. s_var_expr : EXIST LPAREN stds RPAREN
  1075. | EXIST LPAREN expr RPAREN
  1076. """
  1077. # Check input stds.
  1078. maplist = self.check_stds(t[3])
  1079. if self.run:
  1080. resultlist = []
  1081. for map_i in maplist:
  1082. # Create r.mapcalc expression string for the operation.
  1083. if "cmd_list" in dir(map_i):
  1084. cmdstring = "%s" %(map_i.cmd_list)
  1085. else:
  1086. cmdstring = "%s" %(map_i.get_id())
  1087. # Set new command list for map.
  1088. map_i.cmd_list = cmdstring
  1089. # Append map with updated command list to result list.
  1090. resultlist.append(map_i)
  1091. t[0] = resultlist
  1092. if self.debug:
  1093. for map in resultlist:
  1094. print(map.cmd_list)
  1095. def p_s_var_expr_comp(self, t):
  1096. # Examples:
  1097. # A <= 2 || B == 10
  1098. # A < 3 && A > 1
  1099. """
  1100. s_var_expr : s_var_expr AND AND s_var_expr
  1101. | s_var_expr OR OR s_var_expr
  1102. """
  1103. if self.run:
  1104. # Check input stds.
  1105. s_var_exprA = self.check_stds(t[1])
  1106. s_var_exprB = self.check_stds(t[4])
  1107. relations = ["EQUAL"]
  1108. temporal = "l"
  1109. function = t[2] + t[3]
  1110. aggregate = t[2]
  1111. # Build conditional values based on topological relationships.
  1112. complist = self.get_temporal_topo_list(s_var_exprA, s_var_exprB, topolist = relations,
  1113. compare_cmd = True, compop = function, aggregate = aggregate)
  1114. # Set temporal extent based on topological relationships.
  1115. resultlist = self.set_temporal_extent_list(complist, topolist = relations,
  1116. temporal = temporal)
  1117. t[0] = resultlist
  1118. if self.debug:
  1119. for map in resultlist:
  1120. print(map.cmd_list)
  1121. def p_s_var_expr_comp_op(self, t):
  1122. # Examples:
  1123. # A <= 2 {||} B == 10
  1124. # A < 3 {&&, equal} A > 1
  1125. """
  1126. s_var_expr : s_var_expr T_COMP_OPERATOR s_var_expr
  1127. """
  1128. if self.run:
  1129. # Check input stds.
  1130. s_var_exprA = self.check_stds(t[1])
  1131. s_var_exprB = self.check_stds(t[3])
  1132. # Evaluate temporal comparison operator.
  1133. relations, temporal, function, aggregate = self.eval_toperator(t[2], optype = 'boolean')
  1134. # Build conditional values based on topological relationships.
  1135. complist = self.get_temporal_topo_list(s_var_exprA, s_var_exprB, topolist = relations,
  1136. compare_cmd = True, compop = function, aggregate = aggregate)
  1137. # Set temporal extent based on topological relationships.
  1138. resultlist = self.set_temporal_extent_list(complist, topolist = relations,
  1139. temporal = temporal)
  1140. t[0] = resultlist
  1141. if self.debug:
  1142. for map in resultlist:
  1143. print(map.cmd_list)
  1144. def p_s_expr_condition_if(self, t):
  1145. # Examples:
  1146. # if(s_var_expr, B)
  1147. # if(A == 1, B)
  1148. """
  1149. expr : IF LPAREN s_var_expr COMMA stds RPAREN
  1150. | IF LPAREN s_var_expr COMMA expr RPAREN
  1151. | IF LPAREN ts_var_expr COMMA stds RPAREN
  1152. | IF LPAREN ts_var_expr COMMA expr RPAREN
  1153. """
  1154. ifmaplist = self.check_stds(t[3])
  1155. thenmaplist = self.check_stds(t[5])
  1156. resultlist = self.build_condition_cmd_list(ifmaplist, thenmaplist,
  1157. elselist = None,
  1158. condition_topolist = ["EQUAL"],
  1159. conclusion_topolist = ["EQUAL"],
  1160. temporal = 'r', null = False)
  1161. t[0] = resultlist
  1162. if self.debug:
  1163. for map in resultlist:
  1164. print(map.cmd_list)
  1165. def p_s_numeric_condition_if(self, t):
  1166. # Examples:
  1167. # if(s_var_expr, 1)
  1168. # if(A == 5, 10)
  1169. """
  1170. expr : IF LPAREN s_var_expr COMMA number RPAREN
  1171. | IF LPAREN s_var_expr COMMA NULL LPAREN RPAREN RPAREN
  1172. | IF LPAREN ts_var_expr COMMA number RPAREN
  1173. | IF LPAREN ts_var_expr COMMA NULL LPAREN RPAREN RPAREN
  1174. """
  1175. ifmaplist = self.check_stds(t[3])
  1176. resultlist = []
  1177. # Select input for r.mapcalc expression based on length of PLY object.
  1178. if len(t) == 7:
  1179. numinput = str(t[5])
  1180. elif len(t) == 9:
  1181. numinput = str(t[5] + t[6] + t[7])
  1182. # Iterate over condition map list.
  1183. for map_i in ifmaplist:
  1184. # Create r.mapcalc expression string for the operation.
  1185. cmdstring = self.build_command_string(map_i, numinput, cmd_type = 'condition')
  1186. # Conditional append of module command.
  1187. map_i.cmd_list = cmdstring
  1188. # Append map to result map list.
  1189. resultlist.append(map_i)
  1190. t[0] = resultlist
  1191. if self.debug:
  1192. for map in resultlist:
  1193. print(map.cmd_list)
  1194. def p_s_expr_condition_if_relation(self, t):
  1195. # Examples:
  1196. # if({equal||during}, s_var_expr, A)
  1197. """
  1198. expr : IF LPAREN T_REL_OPERATOR COMMA s_var_expr COMMA stds RPAREN
  1199. | IF LPAREN T_REL_OPERATOR COMMA s_var_expr COMMA expr RPAREN
  1200. | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA stds RPAREN
  1201. | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA expr RPAREN
  1202. """
  1203. relations, temporal, function, aggregation = self.eval_toperator(t[3],
  1204. optype = 'relation')
  1205. ifmaplist = self.check_stds(t[5])
  1206. thenmaplist = self.check_stds(t[7])
  1207. resultlist = self.build_condition_cmd_list(ifmaplist, thenmaplist,
  1208. elselist = None,
  1209. condition_topolist = relations,
  1210. conclusion_topolist = ["EQUAL"],
  1211. temporal = 'r', null = False)
  1212. t[0] = resultlist
  1213. if self.debug:
  1214. for map in resultlist:
  1215. print(map.cmd_list)
  1216. def p_s_expr_condition_elif(self, t):
  1217. # Examples:
  1218. # if(s_var_expr, A, B)
  1219. """
  1220. expr : IF LPAREN s_var_expr COMMA stds COMMA stds RPAREN
  1221. | IF LPAREN s_var_expr COMMA stds COMMA expr RPAREN
  1222. | IF LPAREN s_var_expr COMMA expr COMMA stds RPAREN
  1223. | IF LPAREN s_var_expr COMMA expr COMMA expr RPAREN
  1224. | IF LPAREN ts_var_expr COMMA stds COMMA stds RPAREN
  1225. | IF LPAREN ts_var_expr COMMA stds COMMA expr RPAREN
  1226. | IF LPAREN ts_var_expr COMMA expr COMMA stds RPAREN
  1227. | IF LPAREN ts_var_expr COMMA expr COMMA expr RPAREN
  1228. """
  1229. # Check map list inputs.
  1230. ifmaplist = self.check_stds(t[3])
  1231. thenmaplist = self.check_stds(t[5])
  1232. elsemaplist = self.check_stds(t[7])
  1233. # Create conditional command map list.
  1234. resultlist = self.build_condition_cmd_list(ifmaplist, thenmaplist,
  1235. elselist = elsemaplist,
  1236. condition_topolist = ["EQUAL"],
  1237. conclusion_topolist = ["EQUAL"],
  1238. temporal = 'r', null = False)
  1239. t[0] = resultlist
  1240. if self.debug:
  1241. for map in resultlist:
  1242. print(map.cmd_list)
  1243. def p_s_numeric_condition_elif(self, t):
  1244. # Examples:
  1245. # if(s_var_expr, 1, 2)
  1246. # if(A == 5, 10, 0)
  1247. """
  1248. expr : IF LPAREN s_var_expr COMMA number COMMA number RPAREN
  1249. | IF LPAREN s_var_expr COMMA NULL LPAREN RPAREN COMMA number RPAREN
  1250. | IF LPAREN s_var_expr COMMA number COMMA NULL LPAREN RPAREN RPAREN
  1251. | IF LPAREN s_var_expr COMMA NULL LPAREN RPAREN COMMA NULL LPAREN RPAREN RPAREN
  1252. | IF LPAREN ts_var_expr COMMA number COMMA number RPAREN
  1253. | IF LPAREN ts_var_expr COMMA NULL LPAREN RPAREN COMMA number RPAREN
  1254. | IF LPAREN ts_var_expr COMMA number COMMA NULL LPAREN RPAREN RPAREN
  1255. | IF LPAREN ts_var_expr COMMA NULL LPAREN RPAREN COMMA NULL LPAREN RPAREN RPAREN
  1256. """
  1257. ifmaplist = self.check_stds(t[3])
  1258. resultlist = []
  1259. # Select input for r.mapcalc expression based on length of PLY object.
  1260. if len(t) == 9:
  1261. numthen = t[5]
  1262. numelse = t[7]
  1263. elif len(t) == 11 and t[6] == '(':
  1264. numthen = t[5] + t[6] + t[7]
  1265. numelse = t[9]
  1266. elif len(t) == 11 and t[6] == ',':
  1267. numthen = t[5]
  1268. numelse = t[7] + t[8] + t[9]
  1269. elif len(t) == 13:
  1270. numthen = t[5] + t[6] + t[7]
  1271. numelse = t[9] + t[10] + t[11]
  1272. numthen = str(numthen)
  1273. numelse = str(numelse)
  1274. print(numthen + " " +numelse )
  1275. # Create conditional command map list.
  1276. resultlist = self.build_condition_cmd_list(ifmaplist, numthen, numelse,
  1277. condition_topolist = ["EQUAL"],
  1278. conclusion_topolist = ["EQUAL"],
  1279. temporal = 'r', null = False)
  1280. t[0] = resultlist
  1281. if self.debug:
  1282. for map in resultlist:
  1283. print(map.cmd_list)
  1284. def p_s_numeric_expr_condition_elif(self, t):
  1285. # Examples:
  1286. # if(s_var_expr, 1, A)
  1287. # if(A == 5 && C > 5, A, null())
  1288. """
  1289. expr : IF LPAREN s_var_expr COMMA number COMMA stds RPAREN
  1290. | IF LPAREN s_var_expr COMMA NULL LPAREN RPAREN COMMA stds RPAREN
  1291. | IF LPAREN s_var_expr COMMA number COMMA expr RPAREN
  1292. | IF LPAREN s_var_expr COMMA NULL LPAREN RPAREN COMMA expr RPAREN
  1293. | IF LPAREN s_var_expr COMMA stds COMMA number RPAREN
  1294. | IF LPAREN s_var_expr COMMA stds COMMA NULL LPAREN RPAREN RPAREN
  1295. | IF LPAREN s_var_expr COMMA expr COMMA number RPAREN
  1296. | IF LPAREN s_var_expr COMMA expr COMMA NULL LPAREN RPAREN RPAREN
  1297. | IF LPAREN ts_var_expr COMMA number COMMA stds RPAREN
  1298. | IF LPAREN ts_var_expr COMMA NULL LPAREN RPAREN COMMA stds RPAREN
  1299. | IF LPAREN ts_var_expr COMMA number COMMA expr RPAREN
  1300. | IF LPAREN ts_var_expr COMMA NULL LPAREN RPAREN COMMA expr RPAREN
  1301. | IF LPAREN ts_var_expr COMMA stds COMMA number RPAREN
  1302. | IF LPAREN ts_var_expr COMMA stds COMMA NULL LPAREN RPAREN RPAREN
  1303. | IF LPAREN ts_var_expr COMMA expr COMMA number RPAREN
  1304. | IF LPAREN ts_var_expr COMMA expr COMMA NULL LPAREN RPAREN RPAREN
  1305. """
  1306. ifmaplist = self.check_stds(t[3])
  1307. # Select input for r.mapcalc expression based on length of PLY object.
  1308. if len(t) == 9:
  1309. if isinstance(t[5], int):
  1310. theninput = str(t[5])
  1311. elseinput = self.check_stds(t[7])
  1312. elif isinstance(t[7], int):
  1313. theninput = self.check_stds(t[5])
  1314. elseinput = str(t[7])
  1315. elif len(t) == 11:
  1316. if t[5] == 'null':
  1317. theninput = str(t[5] + t[6] + t[7])
  1318. elseinput = self.check_stds(t[9])
  1319. elif t[7] == 'null':
  1320. theninput = self.check_stds(t[5])
  1321. elseinput = str(t[7] + t[8] + t[9])
  1322. # Create conditional command map list.
  1323. resultlist = self.build_condition_cmd_list(ifmaplist, theninput, elseinput,
  1324. condition_topolist = ["EQUAL"],
  1325. conclusion_topolist = ["EQUAL"],
  1326. temporal = 'r', null = False)
  1327. t[0] = resultlist
  1328. if self.debug:
  1329. for map in resultlist:
  1330. print(map.cmd_list)
  1331. def p_s_numeric_expr_condition_elif_relation(self, t):
  1332. # Examples:
  1333. # if({during},s_var_expr, 1, A)
  1334. # if({during}, A == 5, A, null())
  1335. """
  1336. expr : IF LPAREN T_REL_OPERATOR COMMA s_var_expr COMMA number COMMA stds RPAREN
  1337. | IF LPAREN T_REL_OPERATOR COMMA s_var_expr COMMA NULL LPAREN RPAREN COMMA stds RPAREN
  1338. | IF LPAREN T_REL_OPERATOR COMMA s_var_expr COMMA number COMMA expr RPAREN
  1339. | IF LPAREN T_REL_OPERATOR COMMA s_var_expr COMMA NULL LPAREN RPAREN COMMA expr RPAREN
  1340. | IF LPAREN T_REL_OPERATOR COMMA s_var_expr COMMA stds COMMA number RPAREN
  1341. | IF LPAREN T_REL_OPERATOR COMMA s_var_expr COMMA stds COMMA NULL LPAREN RPAREN RPAREN
  1342. | IF LPAREN T_REL_OPERATOR COMMA s_var_expr COMMA expr COMMA number RPAREN
  1343. | IF LPAREN T_REL_OPERATOR COMMA s_var_expr COMMA expr COMMA NULL LPAREN RPAREN RPAREN
  1344. | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA number COMMA stds RPAREN
  1345. | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA NULL LPAREN RPAREN COMMA stds RPAREN
  1346. | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA number COMMA expr RPAREN
  1347. | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA NULL LPAREN RPAREN COMMA expr RPAREN
  1348. | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA stds COMMA number RPAREN
  1349. | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA stds COMMA NULL LPAREN RPAREN RPAREN
  1350. | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA expr COMMA number RPAREN
  1351. | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA expr COMMA NULL LPAREN RPAREN RPAREN
  1352. """
  1353. relations, temporal, function, aggregation = self.eval_toperator(t[3], optype = 'relation')
  1354. ifmaplist = self.check_stds(t[5])
  1355. # Select input for r.mapcalc expression based on length of PLY object.
  1356. if len(t) == 11:
  1357. if isinstance(t[7], int):
  1358. theninput = str(t[7])
  1359. elseinput = self.check_stds(t[9])
  1360. elif isinstance(t[9], int):
  1361. theninput = self.check_stds(t[7])
  1362. elseinput = str(t[9])
  1363. elif len(t) == 13:
  1364. if t[7] == 'null':
  1365. theninput = str(t[7] + t[8] + t[9])
  1366. elseinput = self.check_stds(t[11])
  1367. elif t[9] == 'null':
  1368. theninput = self.check_stds(t[7])
  1369. elseinput = str(t[9] + t[10] + t[11])
  1370. # Create conditional command map list.
  1371. resultlist = self.build_condition_cmd_list(ifmaplist, theninput, elseinput,
  1372. condition_topolist = relations,
  1373. conclusion_topolist = ["EQUAL"],
  1374. temporal = 'r', null = False)
  1375. t[0] = resultlist
  1376. if self.debug:
  1377. for map in resultlist:
  1378. print(map.cmd_list)
  1379. def p_s_expr_condition_elif_relation(self, t):
  1380. # Examples:
  1381. # if({equal||during}, s_var_expr, A, B)
  1382. """
  1383. expr : IF LPAREN T_REL_OPERATOR COMMA s_var_expr COMMA stds COMMA stds RPAREN
  1384. | IF LPAREN T_REL_OPERATOR COMMA s_var_expr COMMA stds COMMA expr RPAREN
  1385. | IF LPAREN T_REL_OPERATOR COMMA s_var_expr COMMA expr COMMA stds RPAREN
  1386. | IF LPAREN T_REL_OPERATOR COMMA s_var_expr COMMA expr COMMA expr RPAREN
  1387. | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA stds COMMA stds RPAREN
  1388. | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA stds COMMA expr RPAREN
  1389. | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA expr COMMA stds RPAREN
  1390. | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA expr COMMA expr RPAREN
  1391. """
  1392. relations, temporal, function, aggregation = self.eval_toperator(t[3], optype = 'relation')
  1393. ifmaplist = self.check_stds(t[5])
  1394. thenmaplist = self.check_stds(t[7])
  1395. elsemaplist = self.check_stds(t[9])
  1396. # Create conditional command map list.
  1397. resultlist = self.build_condition_cmd_list(ifmaplist, thenmaplist, elsemaplist,
  1398. condition_topolist = relations,
  1399. conclusion_topolist = ["EQUAL"],
  1400. temporal = 'r', null = False)
  1401. t[0] = resultlist
  1402. if self.debug:
  1403. for map in resultlist:
  1404. print(map.cmd_list)
  1405. def p_ts_var_expr1(self, t):
  1406. # Combination of spatial and temporal conditional expressions.
  1407. # Examples:
  1408. # A <= 2 || start_date <= 2013-01-01
  1409. # end_date > 2013-01-15 && A > 10
  1410. # IMPORTANT: Only the intersection of map lists in conditionals are
  1411. # exported.
  1412. """
  1413. ts_var_expr : s_var_expr AND AND t_var_expr
  1414. | t_var_expr AND AND s_var_expr
  1415. | t_var_expr OR OR s_var_expr
  1416. | s_var_expr OR OR t_var_expr
  1417. | ts_var_expr AND AND s_var_expr
  1418. | ts_var_expr AND AND t_var_expr
  1419. | ts_var_expr OR OR s_var_expr
  1420. | ts_var_expr OR OR t_var_expr
  1421. | s_var_expr AND AND ts_var_expr
  1422. | t_var_expr AND AND ts_var_expr
  1423. | s_var_expr OR OR ts_var_expr
  1424. | t_var_expr OR OR ts_var_expr
  1425. """
  1426. if self.run:
  1427. # Check input stds.
  1428. s_var_exprA = self.check_stds(t[1])
  1429. s_var_exprB = self.check_stds(t[4])
  1430. relations = ["EQUAL"]
  1431. temporal = "l"
  1432. function = t[2] + t[3]
  1433. aggregate = t[2]
  1434. # Build conditional values based on topological relationships.
  1435. complist = self.get_temporal_topo_list(s_var_exprA, s_var_exprB,
  1436. topolist = relations, compare_cmd = True,
  1437. compop = function, aggregate = aggregate,
  1438. convert = True)
  1439. # Set temporal extent based on topological relationships.
  1440. resultlist = self.set_temporal_extent_list(complist, topolist = relations,
  1441. temporal = temporal)
  1442. t[0] = resultlist
  1443. def p_hash_operation(self, t):
  1444. # Calculate the number of maps within an interval of another map from a
  1445. # second space time dataset.
  1446. # A # B
  1447. # A {equal,r#} B
  1448. """
  1449. expr : t_hash_var
  1450. """
  1451. # Check input stds.
  1452. maplist = self.check_stds(t[1])
  1453. if self.run:
  1454. resultlist = []
  1455. for map_i in maplist:
  1456. for obj in map_i.map_value:
  1457. if isinstance(obj, GlobalTemporalVar):
  1458. n_maps = obj.td
  1459. mapinput = map_i.get_id()
  1460. # Create r.mapcalc expression string for the operation.
  1461. cmdstring = "(%s)" %(n_maps)
  1462. # Append module command.
  1463. map_i.cmd_list = cmdstring
  1464. # Append map to result map list.
  1465. resultlist.append(map_i)
  1466. t[0] = resultlist
  1467. if self.debug:
  1468. for map in resultlist:
  1469. print(map.cmd_list)
  1470. ###############################################################################
  1471. if __name__ == "__main__":
  1472. import doctest
  1473. doctest.testmod()