Exemplo n.º 1
0
def grass_write_vect(gpdf, output, overwrite=False, flags=""):
    """
    Write a Geopandas GeoDataFrame object to the GRASS GIS db

    Occurs via an intermediate tempfile

    Parameters
    ----------
    gpdf : geopandas.GeoDataFrame
        Geodataframe to write to GRASS

    output : str
        Name to use to store the dataset in GRASS

    overwrite : bool
        Whether to overwrite existing datasets

    flags : str, list, tuple
        Flags to pass to GRASS v.in.ogr command
    """

    try:
        import geopandas as gpd
    except ImportError:
        import geopandas as gpd

    temp_out = ".".join([tempfile.NamedTemporaryFile().name, "gpkg"])
    gpdf.to_file(temp_out, driver="GPKG")

    gvect.in_ogr(input=temp_out,
                 output=output,
                 overwrite=overwrite,
                 flags=flags)
Exemplo n.º 2
0
def main(index, AOI, grass_params):
    PERMANENT = Session()
    PERMANENT.open(gisdb=grass_params[0],
                   location=grass_params[1],
                   mapset=grass_params[2])

    aoi = uniq_name('aoi')
    tiles = uniq_name('tiles')
    intersection = uniq_name('common')

    try:
        v.in_ogr(input=index, output=tiles)
        v.in_ogr(input=AOI, output=aoi)
        v.select(binput=aoi,
                 ainput=tiles,
                 output=intersection,
                 operator='overlap')
        v.db_select(map=intersection, columns='location', flags='c')
    finally:
        g.remove(type='vector', name=tiles, flags='f')
        g.remove(type='vector', name=aoi, flags='f')
        g.remove(type='vector', name=intersection, flags='f')
Exemplo n.º 3
0
def importCs():
    v.in_ogr(path + cs, output=csmap, overwrite = True)
Exemplo n.º 4
0
def resultsToTargetPoints():
    v.in_ogr(path + vpoints, output=vpmap, overwrite = True)
    v.distance(targetmap, to=vpmap, dmax=0, upload='to_attr', column=trg_cv, to_column='cost')
mapset_name = 'cut_variables_using_buffers'
g.mapset(mapset = mapset_name, flags = 'c') #-c to create

#---------------------------------------
# Import vector of points and make buffer
#
# Each point correspond to the sampling location of an ecological community
# We load them and make a 5km buffer around each point

# folder
folder_path = r'D:\bernardo\00_academico\01_artigos\ms_Lucas_world_landscape_metrics\world-landscape-metrics-repo\01_data\community_locations'
os.chdir(folder_path) # Change to this folder

# import points
v.in_ogr(input = 'comm_data_neotro_checked_2020_d11_06.shp', 
	output = 'comm_data_neotro_checked_2020_d11_06', overwrite = True)
        grass.run_command('v.import', input = i, output = name, overwrite = True) # Import maps


# make buffer of 5km
# 1km (approx, in reality 900m) = 30 arcsec = 0.008333 degrees
# 5km = 0.045 degrees (approx)
v.buffer(input = 'comm_data_neotro_checked_2020_d11_06', 
	output = 'buffers_5km_comm_data_neotro_checked_2020_d11_06',
	type = 'point', distance = 0.045, flags = 't') 

#---------------------------------------
# cutting variables using buffers
#
# Here we cut the tree cover data from GFW to each buffer.
# Then we set as 0 the tree cover of areas deforested until the correspondent year of the sampling
Exemplo n.º 6
0
params = owsConnections['default']

## END USER SETTINGS
import os
import grass.script as gscript
from grass.pygrass.modules import Module
from grass.pygrass.modules.shortcuts import raster as r, vector as v, general as g, display as d


params['username'] += username
params['password'] += password
dsn = params['dsn'] + ' user=%s password=%s' %(username,password)

g.mapset(flags='c',mapset='Gemeinde_'+bfsnum)

v.in_ogr(dsn=dsn, layer=params['layers']['gemeinde'], output='region', 
         where='bfs_nummer = 2461',overwrite=True)
g.region(vect='region',flags='a',res='2')
g.region(flags='p')

v.in_ogr(dsn=dsn, layer=params['layers']['fieldblocks'], output='fieldblocks', flags='r')

rinwcs = Module("r.in.wcs")
rinwcs.inputs.url=params['url']
rinwcs.inputs.username=username
rinwcs.inputs.password=password

rinwcs(coverage=params['coverages']['elevation'])
rinwcs(coverage=params['coverages']['rfactor'])
rinwcs(coverage=params['coverages']['kfactor'])

rsoillossbare = Module("r.soilloss.bare")
Exemplo n.º 7
0
    Layers.append(Out)
    for k in ['Start'] + block:
        cursor.execute("SELECT place_id from dustbins where block='%s'" % k)
        Order.append(cursor.fetchall()[0][0])
    Full_Query = Query.replace('\n', " ") % (T, Order)
    cursor.execute(Full_Query)
    conn.commit()
    Comm = Command % (Out, db, T)
    subprocess.call([Comm], stdin=subprocess.PIPE, shell=True)

# ----------------- Generation of Maps for the genrated Routes -----------------

O = ['overwrite']
for lyr in Layers + ['SHP/Roads', 'SHP/nBlocks']:
    v.in_ogr(input=lyr,
             output=os.path.splitext(os.path.basename(lyr))[0],
             flags=O)
v.label(map='nBlocks',
        column='Block',
        labels='Blocks',
        size='30',
        opaque='no',
        color='black')

g.region(n=1443552.0, s=1442576.0, e=416851.0, w=415482.0, rows=976, cols=1369)
ps = Module('ps.map')

Path_iden = _ = 'text 416173 1443556 '
for i in range(1, 5):
    Path = '->'.join(['Start'] + Blocks[i - 1])
    sed1 = r"sed -i 's/\bTrip%s\b/Trip%s/g' PS.psmap" % (i - 1, i)
#-------------------------------- Variables -----------------------------------
Join = os.path.join
O = ['overwrite']
Layers = ('Buildings', 'Roads', 'TankPoints')  # Available Layers
Colors = ['red', 'green', 'orange', 'purple', 'yellow', 'blue', 'black']
dia = '1'  # metres
#-------------------------------- Code ----------------------------------------

if __name__ == '__main__':

    g.remove(type='vector', pattern='*', flags=['f'])  # Cleaning the Workspace

    # Importing the ShapeFiles to GRASS
    for lr in Layers:
        v.in_ogr(input=Join('Test1', lr), output=lr, key='id', flags=O)
    #v.in_ascii(input=Join('Test1', 'TankPoints.csv'),
    #output='TankPoints',
    #cat=1, x=4, y=5, skip=1, separator='comma',
    #columns='id int, name varchar(20), type varchar(10), lat double precision, lon double precision, pipe varchar(10), litre int',
    #flags=O)
    """
    Method-1:
    This method will connect all the TankPoints with the Nearest vector lines
    (Road in this case). Using v.net.salesman the network is closed and Creating
    a buffer for this output will be our Layout of TankPoints along the Road.

    v.net(input='Roads',
          points='TankPoints',
          output='JoinedRoads',
          operation='connect',
# 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()
Exemplo n.º 10
0


owsConnections = {}
owsConnections['default'] = {
    'dsn' : 'PG:host=523.riedackerhof.ch dbname=gis user=gis password=gisHoch3',
    'url' : 'https://523.riedackerhof.ch:4433/ows?',
    'username' :'gis',
    'password' : 'gisHoch3',
    'layers' : {
        'cultures' : 'ch_gelan_kulturen_2014',
        'fieldblocks' : 'ch_blw_erk2_feldblockkarte',
        'borders' : 'ch_swisstopo_kantone'
        },
    }
    
params = owsConnections['default']

dsn = params['dsn']

g.mapset(flags='c',mapset='solothurn')

v.in_ogr(dsn=dsn, layer=params['layers']['borders'], output='region', 
         where="kantonsnum = 11")
g.region(vect='region')
g.region(flags='p')

v.in_ogr(dsn=dsn, layer=params['layers']['cultures'], output='cultures', flags='r')
v.in_ogr(dsn=dsn, layer=params['layers']['fieldblocks'],output='fieldblocks', flags='r')
v.overlay(ainput='fieldblocks', binput = 'cultures', operator='not', output='fff')
Exemplo n.º 11
0
# Create a single mapset for each environmental variables to be cut, still in lat-lon, before being reprojected to UTM
# This means that all the data for all correspondent UTm zones will be in a single mapset, in lat-lon
# The next step will be to reproject these
g.mapset(mapset="variables_cut", flags="c")

#---------------------------------------
# Import buffers
folder_path = r'E:\_neojaguardatabase\Buffer70_zones\buffers'
os.chdir(folder_path)  # Change to this folder

files = os.listdir(folder_path)  # List files in the folder
for i in files:
    if i.endswith('gpkg'):  # Select tif files
        print i
        name = i.replace('.gpkg', '')
        v.in_ogr(input=i, output=name, overwrite=True)  # Import maps

#------
# cut for buffers

# variables to be exported

# change to folder where metadata file is
pa = r'E:\_neojaguardatabase'
os.chdir(pa)
arq_maps = np.genfromtxt(
    'Environmental_spatial_data_UTM_2019_updated_rename.csv',
    delimiter=',',
    dtype=None,
    skip_header=1)
maps_to_export = [arq_maps[index][0] for index in range(len(arq_maps))]
import Calculation

#-------------------------------- Variables -----------------------------------
Join = os.path.join
O = ['overwrite']

Layers = (
    'nBlocks',
    'nPoints',
)
# Cleaning the Workspace
#g.remove(type='vector', pattern='*', flags=['f'])

# Importing the ShapeFiles to GRASS
for lr in Layers:
    v.in_ogr(input=Join('SHP', lr), output=lr, flags=O, key='id')

Blocks = Calculation.Blocks  # Calculation.py does the calculation
for ix, block in enumerate(Blocks, start=1):

    Points = 'Trip_%s' % ix
    JR = 'JoinedRoad_%s' % ix
    Path = 'Path_%s' % ix
    B = ['Start'] + sorted(block) + ['End']
    L = len(B)
    whr = 'Block IN %s' % str(tuple(B))
    v.extract(input='nPoints', output=Points, where=whr, flags=O)

    v.net(
        input='nRoads',
        points=Points,  # Trip_1