temporal_vector_algebra.py 28 KB

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