temporal_vector_algebra.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. """@package grass.temporal
  2. Temporal vector algebra
  3. (C) 2014 by the GRASS Development Team
  4. This program is free software under the GNU General Public
  5. License (>=v2). Read the file COPYING that comes with GRASS
  6. for details.
  7. :authors: Thomas Leppelt and Soeren Gebbert
  8. .. code-block:: python
  9. >>> import grass.temporal as tgis
  10. >>> tgis.init(True)
  11. >>> p = tgis.TemporalVectorAlgebraLexer()
  12. >>> p.build()
  13. >>> p.debug = True
  14. >>> expression = 'E = A : B ^ C : D'
  15. >>> p.test(expression)
  16. E = A : B ^ C : D
  17. LexToken(NAME,'E',1,0)
  18. LexToken(EQUALS,'=',1,2)
  19. LexToken(NAME,'A',1,4)
  20. LexToken(T_SELECT,':',1,6)
  21. LexToken(NAME,'B',1,8)
  22. LexToken(XOR,'^',1,10)
  23. LexToken(NAME,'C',1,12)
  24. LexToken(T_SELECT,':',1,14)
  25. LexToken(NAME,'D',1,16)
  26. >>> expression = 'E = buff_a(A, 10)'
  27. >>> p.test(expression)
  28. E = buff_a(A, 10)
  29. LexToken(NAME,'E',1,0)
  30. LexToken(EQUALS,'=',1,2)
  31. LexToken(BUFF_AREA,'buff_a',1,4)
  32. LexToken(LPAREN,'(',1,10)
  33. LexToken(NAME,'A',1,11)
  34. LexToken(COMMA,',',1,12)
  35. LexToken(INT,10,1,14)
  36. LexToken(RPAREN,')',1,16)
  37. """
  38. from __future__ import print_function
  39. try:
  40. import ply.lex as lex
  41. import ply.yacc as yacc
  42. except:
  43. pass
  44. import grass.pygrass.modules as pygrass
  45. import copy
  46. from .temporal_algebra import TemporalAlgebraLexer, TemporalAlgebraParser, GlobalTemporalVar
  47. from .core import init_dbif, get_current_mapset
  48. from .abstract_dataset import AbstractDatasetComparisonKeyStartTime
  49. from .open_stds import open_new_stds
  50. from spatio_temporal_relationships import SpatioTemporalTopologyBuilder
  51. from .space_time_datasets import VectorDataset
  52. ##############################################################################
  53. class TemporalVectorAlgebraLexer(TemporalAlgebraLexer):
  54. """Lexical analyzer for the GRASS GIS temporal vector algebra"""
  55. def __init__(self):
  56. TemporalAlgebraLexer.__init__(self)
  57. # Buffer functions from v.buffer
  58. vector_buff_functions = {
  59. 'buff_p' : 'BUFF_POINT',
  60. 'buff_l' : 'BUFF_LINE',
  61. 'buff_a' : 'BUFF_AREA',
  62. }
  63. # This is the list of token names.
  64. vector_tokens = (
  65. 'DISOR',
  66. 'XOR',
  67. 'NOT',
  68. 'T_OVERLAY_OPERATOR',
  69. )
  70. # Build the token list
  71. tokens = TemporalAlgebraLexer.tokens \
  72. + vector_tokens \
  73. + tuple(vector_buff_functions.values())
  74. # Regular expression rules for simple tokens
  75. t_DISOR = r'\+'
  76. t_XOR = r'\^'
  77. t_NOT = r'\~'
  78. #t_T_OVERLAY_OPERATOR = r'\{([a-zA-Z\|]+[,])?([\|&+=]?[\|&+=\^\~])\}'
  79. t_T_OVERLAY_OPERATOR = r'\{[\|&+\^\~][,]?[a-zA-Z\| ]*([,])?([lrudi]|left|right|union|disjoint|intersect)?\}'
  80. # Parse symbols
  81. def temporal_symbol(self, t):
  82. # Check for reserved words
  83. if t.value in TemporalVectorAlgebraLexer.time_functions.keys():
  84. t.type = TemporalVectorAlgebraLexer.time_functions.get(t.value)
  85. elif t.value in TemporalVectorAlgebraLexer.datetime_functions.keys():
  86. t.type = TemporalVectorAlgebraLexer.datetime_functions.get(t.value)
  87. elif t.value in TemporalVectorAlgebraLexer.conditional_functions.keys():
  88. t.type = TemporalVectorAlgebraLexer.conditional_functions.get(t.value)
  89. elif t.value in TemporalVectorAlgebraLexer.vector_buff_functions.keys():
  90. t.type = TemporalVectorAlgebraLexer.vector_buff_functions.get(t.value)
  91. else:
  92. t.type = 'NAME'
  93. return t
  94. ##############################################################################
  95. class TemporalVectorAlgebraParser(TemporalAlgebraParser):
  96. """The temporal algebra class"""
  97. # Get the tokens from the lexer class
  98. tokens = TemporalVectorAlgebraLexer.tokens
  99. # Setting equal precedence level for select and hash operations.
  100. precedence = (
  101. ('left', 'T_SELECT_OPERATOR', 'T_SELECT', 'T_NOT_SELECT', 'T_HASH_OPERATOR', 'HASH'), # 1
  102. ('left', 'AND', 'OR', 'T_COMP_OPERATOR', 'T_OVERLAY_OPERATOR', 'DISOR', \
  103. 'NOT', 'XOR'), #2
  104. )
  105. def __init__(self, pid=None, run=False, debug=True, spatial = False):
  106. TemporalAlgebraParser.__init__(self, pid, run, debug, spatial)
  107. self.m_overlay = pygrass.Module('v.overlay', quiet=True, run_=False)
  108. self.m_rename = pygrass.Module('g.rename', quiet=True, run_=False)
  109. self.m_patch = pygrass.Module('v.patch', quiet=True, run_=False)
  110. self.m_mremove = pygrass.Module('g.remove', quiet=True, run_=False)
  111. self.m_buffer = pygrass.Module('v.buffer', quiet=True, run_=False)
  112. def parse(self, expression, basename = None, overwrite = False):
  113. # Check for space time dataset type definitions from temporal algebra
  114. l = TemporalVectorAlgebraLexer()
  115. l.build()
  116. l.lexer.input(expression)
  117. while True:
  118. tok = l.lexer.token()
  119. if not tok: break
  120. if tok.type == "STVDS" or tok.type == "STRDS" or tok.type == "STR3DS":
  121. raise SyntaxError("Syntax error near '%s'" %(tok.type))
  122. self.lexer = TemporalVectorAlgebraLexer()
  123. self.lexer.build()
  124. self.parser = yacc.yacc(module=self, debug=self.debug)
  125. self.overwrite = overwrite
  126. self.count = 0
  127. self.stdstype = "stvds"
  128. self.maptype = "vector"
  129. self.mapclass = VectorDataset
  130. self.basename = basename
  131. self.expression = expression
  132. self.parser.parse(expression)
  133. ######################### Temporal functions ##############################
  134. def get_temporal_topo_list(self, maplistA, maplistB = None, topolist = ["EQUAL"],
  135. assign_val = False, count_map = False, compare_bool = False,
  136. compare_cmd = False, compop = None, aggregate = None,
  137. new = False, convert = False, overlay_cmd = False):
  138. """Build temporal topology for two space time data sets, copy map objects
  139. for given relation into map list.
  140. :param maplistA: List of maps.
  141. :param maplistB: List of maps.
  142. :param topolist: List of strings of temporal relations.
  143. :param assign_val: Boolean for assigning a boolean map value based on
  144. the map_values from the compared map list by
  145. topological relationships.
  146. :param count_map: Boolean if the number of topological related maps
  147. should be returned.
  148. :param compare_bool: Boolean for comparing boolean map values based on
  149. related map list and compariosn operator.
  150. :param compare_cmd: Boolean for comparing command list values based on
  151. related map list and compariosn operator.
  152. :param compop: Comparison operator, && or ||.
  153. :param aggregate: Aggregation operator for relation map list, & or |.
  154. :param new: Boolean if new temporary maps should be created.
  155. :param convert: Boolean if conditional values should be converted to
  156. r.mapcalc command strings.
  157. :param overlay_cmd: Boolean for aggregate overlay operators implicitly
  158. in command list values based on related map lists.
  159. :return: List of maps from maplistA that fulfil the topological relationships
  160. to maplistB specified in topolist.
  161. """
  162. topologylist = ["EQUAL", "FOLLOWS", "PRECEDES", "OVERLAPS", "OVERLAPPED", \
  163. "DURING", "STARTS", "FINISHES", "CONTAINS", "STARTED", \
  164. "FINISHED"]
  165. complementdict = {"EQUAL": "EQUAL", "FOLLOWS" : "PRECEDES",
  166. "PRECEDES" : "FOLLOWS", "OVERLAPS" : "OVERLAPPED",
  167. "OVERLAPPED" : "OVERLAPS", "DURING" : "CONTAINS",
  168. "CONTAINS" : "DURING", "STARTS" : "STARTED",
  169. "STARTED" : "STARTS", "FINISHES" : "FINISHED",
  170. "FINISHED" : "FINISHES"}
  171. resultdict = {}
  172. # Check if given temporal relation are valid.
  173. for topo in topolist:
  174. if topo.upper() not in topologylist:
  175. raise SyntaxError("Unpermitted temporal relation name '" + topo + "'")
  176. # Create temporal topology for maplistA to maplistB.
  177. tb = SpatioTemporalTopologyBuilder()
  178. # Dictionary with different spatial variables used for topology builder.
  179. spatialdict = {'strds' : '2D', 'stvds' : '2D', 'str3ds' : '3D'}
  180. # Build spatial temporal topology
  181. if self.spatial:
  182. tb.build(maplistA, maplistB, spatial = spatialdict[self.stdstype])
  183. else:
  184. tb.build(maplistA, maplistB)
  185. # Iterate through maps in maplistA and search for relationships given
  186. # in topolist.
  187. for map_i in maplistA:
  188. tbrelations = map_i.get_temporal_relations()
  189. # Check for boolean parameters for further calculations.
  190. if assign_val:
  191. self.assign_bool_value(map_i, tbrelations, topolist)
  192. elif compare_bool:
  193. self.compare_bool_value(map_i, tbrelations, compop, aggregate, topolist)
  194. elif compare_cmd:
  195. self.compare_cmd_value(map_i, tbrelations, compop, aggregate, topolist, convert)
  196. elif overlay_cmd:
  197. self.overlay_cmd_value(map_i, tbrelations, compop, topolist)
  198. for topo in topolist:
  199. if topo.upper() in tbrelations.keys():
  200. if count_map:
  201. relationmaplist = tbrelations[topo.upper()]
  202. gvar = GlobalTemporalVar()
  203. gvar.td = len(relationmaplist)
  204. if "map_value" in dir(map_i):
  205. map_i.map_value.append(gvar)
  206. else:
  207. map_i.map_value = gvar
  208. # Use unique identifier, since map names may be equal
  209. resultdict[map_i.uid] = map_i
  210. resultlist = resultdict.values()
  211. # Sort list of maps chronological.
  212. resultlist = sorted(resultlist, key = AbstractDatasetComparisonKeyStartTime)
  213. return(resultlist)
  214. def overlay_cmd_value(self, map_i, tbrelations, function, topolist = ["EQUAL"]):
  215. """ Function to evaluate two map lists by given overlay operator.
  216. :param map_i: Map object with temporal extent.
  217. :param tbrelations: List of temporal relation to map_i.
  218. :param topolist: List of strings for given temporal relations.
  219. :param function: Overlay operator, &|+^~.
  220. :return: Map object with command list with operators that has been
  221. evaluated by implicit aggregration.
  222. """
  223. # Build comandlist list with elements from related maps and given relation operator.
  224. resultlist = []
  225. # Define overlay operation dictionary.
  226. overlaydict = {"&":"and", "|":"or", "^":"xor", "~":"not", "+":"disor"}
  227. operator = overlaydict[function]
  228. # Set first input for overlay module.
  229. mapainput = map_i.get_id()
  230. # Append command list of given map to result command list.
  231. if "cmd_list" in dir(map_i):
  232. resultlist = resultlist + map_i.cmd_list
  233. for topo in topolist:
  234. if topo.upper() in tbrelations.keys():
  235. relationmaplist = tbrelations[topo.upper()]
  236. for relationmap in relationmaplist:
  237. # Append command list of given map to result command list.
  238. if "cmd_list" in dir(relationmap):
  239. resultlist = resultlist + relationmap.cmd_list
  240. # Generate an intermediate name
  241. name = self.generate_map_name()
  242. # Put it into the removalbe map list
  243. self.removable_maps[name] = VectorDataset(name + "@%s"%(self.mapset))
  244. map_i.set_id(name + "@" + self.mapset)
  245. # Set second input for overlay module.
  246. mapbinput = relationmap.get_id()
  247. # Create module command in PyGRASS for v.overlay and v.patch.
  248. if operator != "disor":
  249. m = copy.deepcopy(self.m_overlay)
  250. m.run_ = False
  251. m.inputs["operator"].value = operator
  252. m.inputs["ainput"].value = str(mapainput)
  253. m.inputs["binput"].value = str(mapbinput)
  254. m.outputs["output"].value = name
  255. m.flags["overwrite"].value = self.overwrite
  256. else:
  257. patchinput = str(mapainput) + ',' + str(mapbinput)
  258. m = copy.deepcopy(self.m_patch)
  259. m.run_ = False
  260. m.inputs["input"].value = patchinput
  261. m.outputs["output"].value = name
  262. m.flags["overwrite"].value = self.overwrite
  263. # Conditional append of module command.
  264. resultlist.append(m)
  265. # Set new map name to temporary map name.
  266. mapainput = name
  267. # Add command list to result map.
  268. map_i.cmd_list = resultlist
  269. return(resultlist)
  270. def set_temporal_extent_list(self, maplist, topolist = ["EQUAL"], temporal = 'l' ):
  271. """ Change temporal extent of map list based on temporal relations to
  272. other map list and given temporal operator.
  273. :param maplist: List of map objects for which relations has been build
  274. correctely.
  275. :param topolist: List of strings of temporal relations.
  276. :param temporal: The temporal operator specifying the temporal
  277. extent operation (intersection, union, disjoint
  278. union, right reference, left reference).
  279. :return: Map list with specified temporal extent.
  280. """
  281. resultdict = {}
  282. for map_i in maplist:
  283. # Loop over temporal related maps and create overlay modules.
  284. tbrelations = map_i.get_temporal_relations()
  285. # Generate an intermediate map for the result map list.
  286. map_new = self.generate_new_map(base_map=map_i, bool_op = 'and',
  287. copy = True, rename = False,
  288. remove = True)
  289. # Combine temporal and spatial extents of intermediate map with related maps.
  290. for topo in topolist:
  291. if topo in tbrelations.keys():
  292. for map_j in (tbrelations[topo]):
  293. if temporal == 'r':
  294. # Generate an intermediate map for the result map list.
  295. map_new = self.generate_new_map(base_map=map_i, bool_op = 'and',
  296. copy = True, rename = False,
  297. remove = True)
  298. # Create overlayed map extent.
  299. returncode = self.overlay_map_extent(map_new, map_j, 'and', \
  300. temp_op = temporal)
  301. # Stop the loop if no temporal or spatial relationship exist.
  302. if returncode == 0:
  303. break
  304. # Append map to result map list.
  305. elif returncode == 1:
  306. # resultlist.append(map_new)
  307. resultdict[map_new.get_id()] = map_new
  308. if returncode == 0:
  309. break
  310. # Append map to result map list.
  311. #if returncode == 1:
  312. # resultlist.append(map_new)
  313. # Get sorted map objects as values from result dictionoary.
  314. resultlist = resultdict.values()
  315. resultlist = sorted(resultlist, key = AbstractDatasetComparisonKeyStartTime)
  316. return(resultlist)
  317. ###########################################################################
  318. def p_statement_assign(self, t):
  319. # The expression should always return a list of maps.
  320. """
  321. statement : stds EQUALS expr
  322. """
  323. # Execute the command lists
  324. if self.run:
  325. # Open connection to temporal database.
  326. dbif, connected = init_dbif(dbif=self.dbif)
  327. if isinstance(t[3], list):
  328. num = len(t[3])
  329. count = 0
  330. returncode = 0
  331. register_list = []
  332. for i in range(num):
  333. # Check if resultmap names exist in GRASS database.
  334. vectorname = self.basename + "_" + str(i)
  335. vectormap = VectorDataset(vectorname + "@" + get_current_mapset())
  336. if vectormap.map_exists() and self.overwrite == False:
  337. self.msgr.fatal(_("Error vector maps with basename %s exist. "
  338. "Use --o flag to overwrite existing file") \
  339. %(vectorname))
  340. for map_i in t[3]:
  341. if "cmd_list" in dir(map_i):
  342. # Execute command list.
  343. for cmd in map_i.cmd_list:
  344. try:
  345. # We need to check if the input maps have areas in case of v.overlay
  346. # otherwise v.overlay will break
  347. if cmd.name == "v.overlay":
  348. for name in (cmd.inputs["ainput"].value,
  349. cmd.inputs["binput"].value):
  350. #self.msgr.message("Check if map <" + name + "> exists")
  351. if name.find("@") < 0:
  352. name = name + "@" + get_current_mapset()
  353. tmp_map = map_i.get_new_instance(name)
  354. if not tmp_map.map_exists():
  355. raise Exception
  356. #self.msgr.message("Check if map <" + name + "> has areas")
  357. tmp_map.load()
  358. if tmp_map.metadata.get_number_of_areas() == 0:
  359. raise Exception
  360. except Exception:
  361. returncode = 1
  362. break
  363. # run the command
  364. # print the command that will be executed
  365. self.msgr.message("Run command:\n" + cmd.get_bash())
  366. cmd.run()
  367. if cmd.popen.returncode != 0:
  368. self.msgr.fatal(_("Error starting %s : \n%s")
  369. %(cmd.get_bash(),
  370. cmd.popen.stderr))
  371. mapname = cmd.outputs['output'].value
  372. if mapname.find("@") >= 0:
  373. map_test = map_i.get_new_instance(mapname)
  374. else:
  375. map_test = map_i.get_new_instance(mapname + "@" + self.mapset)
  376. if not map_test.map_exists():
  377. returncode = 1
  378. break
  379. if returncode == 0:
  380. # We remove the invalid vector name from the remove list.
  381. if map_i.get_name() in self.removable_maps:
  382. self.removable_maps.pop(map_i.get_name())
  383. mapset = map_i.get_mapset()
  384. # Change map name to given basename.
  385. newident = self.basename + "_" + str(count)
  386. m = copy.deepcopy(self.m_rename)
  387. m.inputs["vector"].value = (map_i.get_name(),newident)
  388. m.flags["overwrite"].value = self.overwrite
  389. m.run()
  390. map_i.set_id(newident + "@" + mapset)
  391. count += 1
  392. register_list.append(map_i)
  393. else:
  394. # Test if temporal extents have been changed by temporal
  395. # relation operators (i|r). This is a code copy from temporal_algebra.py
  396. map_i_extent = map_i.get_temporal_extent_as_tuple()
  397. map_test = map_i.get_new_instance(map_i.get_id())
  398. map_test.select(dbif)
  399. map_test_extent = map_test.get_temporal_extent_as_tuple()
  400. if map_test_extent != map_i_extent:
  401. # Create new map with basename
  402. newident = self.basename + "_" + str(count)
  403. map_result = map_i.get_new_instance(newident + "@" + self.mapset)
  404. if map_test.map_exists() and self.overwrite is False:
  405. self.msgr.fatal("Error raster maps with basename %s exist. "
  406. "Use --o flag to overwrite existing file"
  407. %(mapname))
  408. map_result.set_temporal_extent(map_i.get_temporal_extent())
  409. map_result.set_spatial_extent(map_i.get_spatial_extent())
  410. # Attention we attach a new attribute
  411. map_result.is_new = True
  412. count += 1
  413. register_list.append(map_result)
  414. # Copy the map
  415. m = copy.deepcopy(self.m_copy)
  416. m.inputs["vector"].value = map_i.get_id(), newident
  417. m.flags["overwrite"].value = self.overwrite
  418. m.run()
  419. else:
  420. register_list.append(map_i)
  421. if len(register_list) > 0:
  422. # Create result space time dataset.
  423. resultstds = open_new_stds(t[1], self.stdstype,
  424. 'absolute', t[1], t[1],
  425. "temporal vector algebra", self.dbif,
  426. overwrite=self.overwrite)
  427. for map_i in register_list:
  428. # Check if modules should be executed from command list.
  429. if hasattr(map_i, "cmd_list") or hasattr(map_i, "is_new"):
  430. # Get meta data from grass database.
  431. map_i.load()
  432. if map_i.is_in_db(dbif=dbif) and self.overwrite:
  433. # Update map in temporal database.
  434. map_i.update_all(dbif=dbif)
  435. elif map_i.is_in_db(dbif=dbif) and self.overwrite == False:
  436. # Raise error if map exists and no overwrite flag is given.
  437. self.msgr.fatal(_("Error vector map %s exist in temporal database. "
  438. "Use overwrite flag. : \n%s") \
  439. %(map_i.get_map_id(), cmd.popen.stderr))
  440. else:
  441. # Insert map into temporal database.
  442. map_i.insert(dbif=dbif)
  443. else:
  444. # Map is original from an input STVDS
  445. map_i.load()
  446. # Register map in result space time dataset.
  447. print(map_i.get_temporal_extent_as_tuple())
  448. success = resultstds.register_map(map_i, dbif=dbif)
  449. resultstds.update_from_registered_maps(dbif)
  450. # Remove intermediate maps
  451. self.remove_maps()
  452. if connected:
  453. dbif.close()
  454. t[0] = t[3]
  455. def p_overlay_operation(self, t):
  456. """
  457. expr : stds AND stds
  458. | expr AND stds
  459. | stds AND expr
  460. | expr AND expr
  461. | stds OR stds
  462. | expr OR stds
  463. | stds OR expr
  464. | expr OR expr
  465. | stds XOR stds
  466. | expr XOR stds
  467. | stds XOR expr
  468. | expr XOR expr
  469. | stds NOT stds
  470. | expr NOT stds
  471. | stds NOT expr
  472. | expr NOT expr
  473. | stds DISOR stds
  474. | expr DISOR stds
  475. | stds DISOR expr
  476. | expr DISOR expr
  477. """
  478. if self.run:
  479. # Check input stds and operator.
  480. maplistA = self.check_stds(t[1])
  481. maplistB = self.check_stds(t[3])
  482. relations = ["EQUAL"]
  483. temporal = 'l'
  484. function = t[2]
  485. # Build commmand list for related maps.
  486. complist = self.get_temporal_topo_list(maplistA, maplistB, topolist = relations,
  487. compop = function, overlay_cmd = True)
  488. # Set temporal extent based on topological relationships.
  489. resultlist = self.set_temporal_extent_list(complist, topolist = relations,
  490. temporal = temporal)
  491. t[0] = resultlist
  492. if self.debug:
  493. str(t[1]) + t[2] + str(t[3])
  494. def p_overlay_operation_relation(self, t):
  495. """
  496. expr : stds T_OVERLAY_OPERATOR stds
  497. | expr T_OVERLAY_OPERATOR stds
  498. | stds T_OVERLAY_OPERATOR expr
  499. | expr T_OVERLAY_OPERATOR expr
  500. """
  501. if self.run:
  502. # Check input stds and operator.
  503. maplistA = self.check_stds(t[1])
  504. maplistB = self.check_stds(t[3])
  505. relations, temporal, function, aggregate = self.eval_toperator(t[2], optype = 'overlay')
  506. # Build commmand list for related maps.
  507. complist = self.get_temporal_topo_list(maplistA, maplistB, topolist = relations,
  508. compop = function, overlay_cmd = True)
  509. # Set temporal extent based on topological relationships.
  510. resultlist = self.set_temporal_extent_list(complist, topolist = relations,
  511. temporal = temporal)
  512. t[0] = resultlist
  513. if self.debug:
  514. str(t[1]) + t[2] + str(t[3])
  515. def p_buffer_operation(self,t):
  516. """
  517. expr : buff_function LPAREN stds COMMA number RPAREN
  518. | buff_function LPAREN expr COMMA number RPAREN
  519. """
  520. if self.run:
  521. # Check input stds.
  522. bufflist = self.check_stds(t[3])
  523. # Create empty result list.
  524. resultlist = []
  525. for map_i in bufflist:
  526. # Generate an intermediate name for the result map list.
  527. map_new = self.generate_new_map(base_map=map_i, bool_op=None,
  528. copy=True, remove = True)
  529. # Change spatial extent based on buffer size.
  530. map_new.spatial_buffer(float(t[5]))
  531. # Check buff type.
  532. if t[1] == "buff_p":
  533. buff_type = "point"
  534. elif t[1] == "buff_l":
  535. buff_type = "line"
  536. elif t[1] == "buff_a":
  537. buff_type = "area"
  538. m = copy.deepcopy(self.m_buffer)
  539. m.run_ = False
  540. m.inputs["type"].value = buff_type
  541. m.inputs["input"].value = str(map_i.get_id())
  542. m.inputs["distance"].value = float(t[5])
  543. m.outputs["output"].value = map_new.get_name()
  544. m.flags["overwrite"].value = self.overwrite
  545. # Conditional append of module command.
  546. if "cmd_list" in dir(map_new):
  547. map_new.cmd_list.append(m)
  548. else:
  549. map_new.cmd_list = [m]
  550. resultlist.append(map_new)
  551. t[0] = resultlist
  552. def p_buff_function(self, t):
  553. """buff_function : BUFF_POINT
  554. | BUFF_LINE
  555. | BUFF_AREA
  556. """
  557. t[0] = t[1]
  558. # Handle errors.
  559. def p_error(self, t):
  560. raise SyntaxError("syntax error on line %d near '%s' expression '%s'" %
  561. (t.lineno, t.value, self.expression))
  562. ###############################################################################
  563. if __name__ == "__main__":
  564. import doctest
  565. doctest.testmod()