temporal_vector_algebra.py 29 KB

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