Skip to content

Instantly share code, notes, and snippets.

@quommit
Last active June 1, 2018 08:51
Show Gist options
  • Save quommit/4b0636ed28bac17a1b0c to your computer and use it in GitHub Desktop.
Save quommit/4b0636ed28bac17a1b0c to your computer and use it in GitHub Desktop.
GRASS 7 Python script for configuring polygon shapefile attributes using SIGUA schema
#!/usr/bin/env python
#%module
#% description: configure attributes using SIGUA schema
#%end
#%option
#% key: input
#% type: string
#% description: Input building floor polygon shapefile
#% required: yes
#%end
#%option
#% key: epsg
#% type: integer
#% description: EPSG id of input shapefile
#% required: yes
#%end
import sys
import os
import errno
from grass.script import core as g
class InputError(Exception):
def __init__(self, value):
self.value = value
super(InputError, self).__init__()
def __str__(self):
return repr(self.value)
def main():
g.run_command("v.in.ogr", flags="o", input_=options["input"],
output="pol", overwrite=True)
report = g.parse_command("v.info", flags="t", map_="pol")
if report["areas"] == "0":
raise InputError("Input must be a polygon shapefile")
ignore_cols = g.parse_command("db.columns", table="pol")
for key in ignore_cols:
if key != "cat":
g.run_command("v.db.dropcolumn", map_="pol", column=key)
c1 = "codigo varchar(9)"
c2 = "coddpto varchar(25)"
c3 = "actividad int"
c4 = "denominaci varchar(100)"
c5 = "observacio varchar(100)"
schema = "{0},{1},{2},{3},{4}".format(c1, c2, c3, c4, c5)
g.run_command("v.db.addcolumn", map_="pol", columns=schema)
noext = os.path.splitext(options["input"])[0]
floor_id = os.path.basename(noext).upper()
g.run_command("db.execute", sql="update pol set codigo = '{0}000', actividad = 93, coddpto='07.018'".format(floor_id))
try:
os.remove("{0}.shp".format(noext))
os.remove("{0}.dbf".format(noext))
os.remove("{0}.shx".format(noext))
os.remove("{0}.prj".format(noext))
except OSError as e:
if e.errno != errno.ENOENT:
raise
g.run_command("v.out.ogr", flags="cs", input_="pol",
format="ESRI_Shapefile", output=options["input"], type_="area")
wkt = g.read_command("g.proj", flags="wf", epsg=options["epsg"])[:-2]
wkt += ',AUTHORITY["{}","{}"]]'
wkt = wkt.format("EPSG", options["epsg"])
with open("{0}.prj".format(noext), "w") as projfile:
projfile.write(wkt)
with open("{0}.cpg".format(noext), "w") as encodingfile:
encodingfile.write("UTF-8")
if __name__ == "__main__":
options, flags = g.parser()
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment