} 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'])
from grass.pygrass.modules.shortcuts import general as g from grass.pygrass.modules.shortcuts import vector as v from grass.pygrass.modules.shortcuts import raster as r #--------------------------------------- # The code below assumes you have already loaded the treecover and deforestation datasets # from Global Forest Watch (Hansen, 2000), loaded the tiles in a GRASS GIS location, in the # mapset PERMANENT, and made a mosaic out of each of them. # # The following steps will be made in a mapset called "cut_variables_using_buffers". #--------------------------------------- # Change to a new mapset 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
#------------------------------------------ # Location utm 23N # list maps in cgs-location all_maps = grass.read_command('r.proj', location='newLocation_wgs84', mapset='variables_cut', flags='l').replace('\r', '').split('\n') all_regions = grass.read_command('v.proj', location='newLocation_wgs84', mapset='variables_cut', flags='l').replace('\r', '').split('\n') # change location g.mapset(mapset="PERMANENT", location="location_S_zone_23") # get only those for zone 23 maps = [i for i in all_maps if 'zone_23' in i] regions = [ i for i in all_regions if i.endswith('zone_23') and i.startswith('region') ] # loop to reproject regions for i in regions: v.proj(location='newLocation_wgs84', mapset='variables_cut', input=i, output=i, overwrite=True)
def extract_points(self, vect_name, fields, na_rm=True, as_df=False): """Samples a list of GRASS rasters using a point dataset Parameters ---------- vect_name : str Name of GRASS GIS vector containing point features. fields : list, str Name of attribute(s) containing the vect_name variable(s). na_rm : bool (opt). Default is True Whether to remove samples containing NaNs. as_df : bool (opt). Default is False. Whether to return the extracted RasterStack values as a Pandas DataFrame. Returns ------- X : ndarray 2d array containing the extracted raster values with the dimensions ordered by (n_samples, n_features). y : ndarray 1d or 2d array of labels with the dimensions ordered by (n_samples, n_fields). df : pandas.DataFrame Extracted raster values as Pandas DataFrame if as_df = True. """ # some checks try: vname, mapset = vect_name.split("@") except ValueError: vname = vect_name mapset = (g.mapset(flags="p", stdout_=PIPE).outputs.stdout.split( os.linesep)[0]) if VectorTopo(name=vname, mapset=mapset).exist() is False: gs.fatal("The supplied vector map does not exist") if isinstance(fields, str): fields = [fields] # open grass vector with VectorTopo(name=vname, mapset=mapset, mode="r") as points: # retrieve key column key_col = points.table.key # read attribute table (ignores region) df = pd.read_sql_query( sql="select * from {name}".format(name=points.table.name), con=points.table.conn) for i in fields: if i not in df.columns.tolist(): gs.fatal(i + " not present in the attribute table") df = df.loc[:, fields + [points.table.key]] # extract raster data Xs = [] for name, layer in self.loc.items(): rast_data = v.what_rast( map=vect_name, raster=layer.fullname(), flags="p", quiet=True, stdout_=PIPE, ).outputs.stdout.strip().split(os.linesep) with RasterRow(layer.fullname()) as src: if src.mtype == "CELL": nodata = self._cell_nodata dtype = pd.Int64Dtype() else: nodata = np.nan dtype = np.float32 if len(list(itertools.chain(*rast_data))) == 0: gs.fatal("There are no training point geometries in " "the supplied vector dataset") X = [ k.split("|")[1] if k.split("|")[1] != "*" else nodata for k in rast_data ] X = np.asarray(X) cat = np.asarray([int(k.split("|")[0]) for k in rast_data]) if src.mtype == "CELL": X = [int(i) for i in X] else: X = [float(i) for i in X] X = pd.DataFrame(data=np.column_stack((X, cat)), columns=[name, key_col]) X[name] = X[name].astype(dtype) Xs.append(X) for X in Xs: df = df.merge(X, on=key_col) # set any grass integer nodata values to NaN df = df.replace(self._cell_nodata, np.nan) # remove rows with missing response data df = df.dropna(subset=fields) # remove samples containing NaNs if na_rm is True: gs.message("Removing samples with NaN values in the raster " "feature variables...") df = df.dropna() if as_df is False: if len(fields) == 1: fields = fields[0] X = df.loc[:, df.columns.isin(self.loc.keys())].values y = np.asarray(df.loc[:, fields].values) cat = np.asarray(df.loc[:, key_col].values) return X, y, cat return df
python # import modules import os, fnmatch, imp import numpy as np import subprocess import grass.script as grass from grass.pygrass.modules.shortcuts import general as g from grass.pygrass.modules.shortcuts import vector as v from grass.pygrass.modules.shortcuts import raster as r #--------------------------------------- # Change to a new mapset g.mapset(mapset = 'akde', flags = 'c') #-c to create #--------------------------------------- # Import buffers # akde 95 folder_path = r'E:\_neojaguardatabase\other_limits_cut_variables\akde\95_per' 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('shp'): # Select shp files print i name = 'akde_ind'+i.replace('.shp', '').replace('.', '_').replace('%', '_') grass.run_command('v.import', input = i, output = name, overwrite = True) # Import maps
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')
python # import modules import os, fnmatch, imp import subprocess import numpy as np import grass.script as grass from grass.pygrass.modules.shortcuts import general as g from grass.pygrass.modules.shortcuts import vector as v from grass.pygrass.modules.shortcuts import raster as r #--------------------------------------- # 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