示例#1
0
def __Session_create(tmp_vars):

    from grass.pygrass.modules.shortcuts import general as g

    with Session(
            gisdb=tmp_vars["tmpdir"],
            location=tmp_vars["location_name"],
            create_opts=tmp_vars["create_opts"],
    ):
        # execute some command inside PERMANENT
        g.mapsets(flags="l")
        g.list(type="raster", flags="m")

    # check if PERMANENT has been created
    __check_PERMANENT_in_folder(tmp_vars["location_path"])

    # check files
    permanent = os.path.join(tmp_vars["location_path"], "PERMANENT")
    __check_mandatory_files_in_PERMANENT(permanent)

    # check PROJ_EPSG content
    __check_epsg(permanent, 3035)

    # check creation of a mapset
    with Session(
            gisdb=tmp_vars["tmpdir"],
            location=tmp_vars["location_name"],
            mapset=tmp_vars["mapset_name"],
            create_opts="",
    ):
        # execute some command inside user
        g.mapsets(flags="l")
        g.list(type="raster", flags="m")

    __check_mandatory_files_in_mapset(tmp_vars["mapset_path"])
示例#2
0
    def __init__(self, name, mapset=None, mode='r', stack=None, position='last', **kwargs):
        super(MVector, self).__init__(name, mapset, **kwargs)

        assert self.exist(), "%r not found" % name
        if mapset:
            self._set_mapset(mapset)
        else:
            self._get_mapset()
            glist = g.list(type='vector', pattern=name, stderr_=PIPE, stdout_=PIPE)
            assert len(glist.outputs.stdout.split()) == 1,\
                   "%r found in multiple mapsets. Specify mapset argument." % name

        path = os.path.join('$GISDBASE','$LOCATION_NAME', self.mapset,'sqlite','sqlite.db')
        self._con = sql.connect(gtable.get_path(path))
        self.region = Region()
        self.open(mode)
        #TODO: add reset method to stack
        self.stack = dict()
        if stack is None:
            self.stack = ListDict({0: {'type': 'v', 'map': self.full_name}})
        elif isinstance(stack, dict):
            stack = ListDict(stack)
            if isinstance(position, int):
                if position in stack.keys():
                    stack.insert_before(position, (max(stack.keys())+1,
                                        {'type': 'v', 'map': self.full_name}))
                else:
                    pass
            elif position is 'last':
                stack.insert_after(stack.keys()[-1], (max(stack.keys())+1,
                                   {'type': 'v', 'map' : self.full_name}))
            elif position is 'first':
                stack.insert_before(stack.keys()[0], (max(stack.keys())+1,
                                    {'type': 'v', 'map' : self.full_name}))
            self.stack = stack
示例#3
0

# set some common environmental variables, like:
os.environ.update(dict(GRASS_COMPRESS_NULLS='1',
                       GRASS_COMPRESSOR='ZSTD'))

# create a PERMANENT mapset
# create a Session instance
PERMANENT = Session()
PERMANENT.open(gisdb='/tmp', location='grassdb_test',
               create_opts='EPSG:25832')


# execute some command inside PERMANENT
g.mapsets(flags="l")
g.list(type="raster", flags="m")

# exit from PERMANENT
PERMANENT.close()

# create a new mapset in the same location
user = Session()
user.open(gisdb='/tmp', location='mytest', mapset='user',
               create_opts='')

# execute some command inside user
g.mapsets(flags="l")
g.list(type="raster", flags="m")

# exit from user
user.close()
示例#4
0
    def __init__(self, rasters=None, group=None):
        """A RasterStack enables a collection of raster layers to be bundled
        into a single RasterStack object

        Parameters
        ----------
        rasters : list, str
            List of names of GRASS GIS raster maps. Note that although the
            maps can reside in different mapsets, they cannot have the same
            names.

        group : str (opt)
            Create a RasterStack from rasters contained in a GRASS GIS imagery
            group. This parameter is mutually exclusive with the `rasters`
            parameter.

        Attributes
        ----------
        loc : dict
            Name-based indexing of RasterRow objects within the RasterStack.

        iloc : int
            Index-based indexing of RasterRow objects within the RasterStack.

        mtypes : dict
            Dict of key, value pairs of full_names and GRASS data types.

        count : int
            Number of RasterRow objects within the RasterStack.
        """
        try:
            import pandas as pd

        except ImportError:
            gs.fatal("Package python3-pandas 0.25 or newer is not installed")

        self.loc = _LocIndexer(self)
        self.iloc = _ILocIndexer(self, self.loc)

        # key, value pairs of full name and GRASS data type
        self.mtypes = {}
        self.count = 0
        self._categorical_idx = []
        self._cell_nodata = -2147483648

        # some checks
        if rasters and group:
            gs.fatal('arguments "rasters" and "group" are mutually exclusive')

        if group:
            groups_in_mapset = (g.list(
                type="group",
                stdout_=PIPE).outputs.stdout.strip().split(os.linesep))
            groups_in_mapset = [i.split("@")[0] for i in groups_in_mapset]
            group = group.split("@")[0]

            if group not in groups_in_mapset:
                gs.fatal(
                    "Imagery group {group} does not exist".format(group=group))
            else:
                map_list = im.group(group=group,
                                    flags=["l", "g"],
                                    quiet=True,
                                    stdout_=PIPE)
                rasters = map_list.outputs.stdout.strip().split(os.linesep)

        self.layers = rasters  # call property
                 width=width,
                 height=height,
                 overlap=20,
                 processes=cpus,
                 input=grassfile,
                 output=grasscontoursfile,
                 minlevel=200,
                 maxlevel=800,
                 step=10,
                 overwrite=True)
grd.run()

#Write output to file
v.out_ogr(input=grasscontoursfile, output=contoursfile, overwrite=True)

# These can be left out, just debug info
print("\n\n ***DEBUG INFO***")
print("GRASS version")
print(g.version())

print("GRASS env settings: gisdatabase, location, mapset")
g.gisenv()

print("Available datasets:")
g.list(type="all", flags='m')

print("Input file info")
r.info(map=grassfile, verbose=True)

print("Output  info")
v.info(map=grasscontoursfile, verbose=True)
# hint: EPSG code lookup: https://epsg.io
PERMANENT.open(gisdb=mygisdb, location=mylocation, create_opts='EPSG:4326')

# exit from PERMANENT right away in order to perform analysis in our own mapset
PERMANENT.close()

# create a new mapset in the same location
user = Session()
user.open(gisdb=mygisdb, location=mylocation, mapset=mymapset, create_opts='')

# execute some command inside user mapset

# import admin0 vector data - it downloads and imports including topological cleaning on the fly
#   Data source: https://www.naturalearthdata.com/downloads/10m-cultural-vectors/
#   VSI driver for remote access: http://www.gdal.org/gdal_virtual_file_systems.html#gdal_virtual_file_systems_vsicurl
inputfile = "/vsizip/vsicurl/https://www.naturalearthdata.com/http//www.naturalearthdata.com/download/10m/cultural/ne_10m_admin_0_countries.zip"

# note the pythonic underscore
v.in_ogr(input=inputfile, output="countries", overwrite=True)

# show the attribute column names
v.info(map="countries", flags="c")

# list vector maps available in the current mapset
g.list(type="vector", flags="m")

# now do anaylsis with the map...

# exit from user mapset (the data will remain)
user.close()
# Set GRASS region
g.region(raster=grassfile)

# Perform GRASS analysis, here calculate contours from DEM
r.contour(input=grassfile,
          output=grasscontoursfile,
          minlevel=200,
          maxlevel=800,
          step=10,
          overwrite=True)

#Write output to file
v.out_ogr(input=grasscontoursfile, output=contoursfile, overwrite=True)

# These can be left out, just debug info
# TODO: not working properly!
print("\n\n ***DEBUG INFO***")
print("GRASS version")
print(g.version())

print("GRASS env settings: gisdatabase, location, mapset")
print(g.gisenv())

print("Available datasets:")
print(g.list(type="all", flags='m'))

print("Input file info")
print(r.info(map=grassfile, verbose=True))

print("Output  info")
print(v.info(map=grasscontoursfile, verbose=True))