temporal_raster_base_algebra.py 71 KB

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