temporal_vector_algebra.py 29 KB

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