def OnBackgroundMap(self, event): value = self._backgroundSelect.GetValue() try: ret = grast.raster_info(value) self._typeChoice.SetStringSelection(ret['datatype']) except CalledModuleError: return
def load(self): """Load all info from an existing raster map into the internal structure""" # Get the data from an existing raster map kvp = raster.raster_info(self.ident) # Fill base information self.base.set_name(self.ident.split("@")[0]) self.base.set_mapset(self.ident.split("@")[1]) self.base.set_creator(str(getpass.getuser())) # Fill spatial extent self.set_spatial_extent(north=kvp["north"], south=kvp["south"], \ east=kvp["east"], west=kvp["west"]) # Fill metadata self.metadata.set_nsres(kvp["nsres"]) self.metadata.set_ewres(kvp["ewres"]) self.metadata.set_datatype(kvp["datatype"]) self.metadata.set_min(kvp["min"]) self.metadata.set_max(kvp["max"]) rows = int((kvp["north"] - kvp["south"])/kvp["nsres"] + 0.5) cols = int((kvp["east"] - kvp["west"])/kvp["ewres"] + 0.5) ncells = cols * rows self.metadata.set_cols(cols) self.metadata.set_rows(rows) self.metadata.set_number_of_cells(ncells)
def main(): options, flags = gcore.parser() probability = options['probability'] output = options['output'] count = int(options['count']) gcore.use_temp_region() # probability map probab_01 = 'probability_01_' + str(os.getpid()) TMP_RAST.append(probab_01) info = grast.raster_info(probability) gcore.write_command('r.recode', flags='d', input=probability, output=probab_01, title="Recoded probability map to 0 to 1", rules='-', stdin='{minim}:{maxim}:0:1'.format(minim=info['min'], maxim=info['max'])) mean = gcore.parse_key_val(gcore.read_command('r.univar', map=probab_01, flags='g'), val_type=float)['mean'] resolution = count / (mean * (info['north'] - info['south'] + info['east'] - info['west'])) resolution = sqrt((mean * (info['north'] - info['south']) * (info['east'] - info['west'])) / count) gcore.run_command('g.region', res=resolution) random_name = 'random_' + str(os.getpid()) point_map = 'points_' + str(os.getpid()) point_grid = 'points_' + str(os.getpid()) TMP_RAST.append(random_name) TMP_RAST.append(point_map) TMP_VECT.append(point_grid) gcore.run_command('r.surf.random', output=random_name, min=0, max=1) grast.mapcalc(exp='{point_map} = if({rand} <= {prob}, 1, null())'.format(rand=random_name, prob=probab_01, point_map=point_map)) gcore.run_command('r.to.vect', flags='t', input=point_map, output=point_grid, type='point') gcore.run_command('v.perturb', input=point_grid, output=output, parameter=resolution / 2., seed=os.getpid())
def SelectOldMap(self, name): """After selecting old raster, creates a backup copy for editing.""" try: self._backupRaster(name) except ScriptError: GError(parent=self._mapWindow, message=_( "Failed to create backup copy of edited raster map.")) return False self._editedRaster = name self._mapType = grast.raster_info(map=name)['datatype'] self._editOldRaster = True return True
def SelectOldMap(self, name): """After selecting old raster, creates a backup copy for editing.""" try: self._backupRaster(name) except ScriptError: GError( parent=self._mapWindow, message=_( "Failed to create backup copy of edited raster map."), ) return False self._editedRaster = name self._mapType = grast.raster_info(map=name)["datatype"] self._editOldRaster = True return True
def contours(scanned_elev, new, env, maxlevel=None, step=None): name = 'x' + str(uuid.uuid4()).replace('-', '') if not step: info = grast.raster_info(scanned_elev) step = (info['max'] - info['min']) / 12. try: if maxlevel is None: gcore.run_command('r.contour', input=scanned_elev, output=name, step=step, flags='t', env=env) else: gcore.run_command('r.contour', input=scanned_elev, output=name, step=step, maxlevel=maxlevel, flags='t', env=env) gcore.run_command('g.rename', vector=[name, new], env=env) except StandardError as e: # catching exception when a vector is added to GUI in the same time pass except CalledModuleError as e: gcore.run_command('g.remove', flags='f', type='vector', name=[name], env=env) remove_vector(new, deleteTable=False) print e
def difference(real_elev, scanned_elev, new, color_coeff=1, env=None): """!Computes difference of original and scanned (scan - orig). color_coeff modifies the intensity of the color, values > 1 mean the difference shows only bigger changes, values < 1 highlight smaller changes (and noise)""" tmp = 'tmp_resampled' gcore.run_command('r.resamp.interp', input=real_elev, output=tmp, method='bilinear', env=env) gcore.run_command('r.mapcalc', expression='{diff} = {scan} - {real}'.format(diff=new, real=tmp, scan=scanned_elev), env=env) info = grast.raster_info(real_elev) range = info['max'] - info['min'] percentages = [-1000, -100, -50, -5, 5, 50, 100, 1000] colors = ['black', 'black', 'blue', 'white', 'white', 'red', 'black', 'black'] rules = [] for p, c in zip(percentages, colors): p = range / 100. * p * color_coeff rules.append('{p} {c}'.format(p=p, c=c)) gcore.write_command('r.colors', map=new, rules='-', stdin='\n'.join(rules), env=env)
def test_standard_options_datatype(self): """Test if result is of integer or float data type depending on input datatype and method""" # landclass96 (values 1-7) test_case = "test_standard_options_datatype" methods = ["average", "variance", "diversity", "range", "mode"] outputs = ["{}_{}".format(test_case, method) for method in methods] self.to_remove.extend(outputs) self.assertModule( "r.neighbors", input="landclass96", output=",".join(outputs), method=methods, ) for rmap in outputs: rinfo = raster_info(rmap) self.assertTrue(rinfo["datatype"] == "CELL" if rinfo["datatype"] in ["diversity", "range", "mode"] else "DCELL")
def scale_subsurface_flat(real_elev, array, zexag, base, height_mm, info_text): raster_info = grast.raster_info(real_elev) old_min_x = np.min(array[:, 0]) old_max_x = np.max(array[:, 0]) old_min_y = np.min(array[:, 1]) old_max_y = np.max(array[:, 1]) ns_scale = (raster_info['north'] - raster_info['south']) / (old_max_y - old_min_y) ew_scale = (raster_info['east'] - raster_info['west']) / (old_max_x - old_min_x) hor_scale = (ns_scale + ew_scale) / 2 scale = float(hor_scale) / zexag real_height = base + height_mm / 1000. array[:, 2] = array[:, 2] * scale - (real_height * scale - raster_info['max']) info_text.append("Model scale 1:{0:.0f}".format(hor_scale)) info_text.append("1 cm in height ~ {0:.1f} m".format(0.01 * scale)) return array
def InitRasterOpts(self, rasterList): """!Initialize or update raster dictionary for plotting """ rdict = {} # initialize a dictionary for r in rasterList: idx = rasterList.index(r) try: ret = raster.raster_info(r) except: continue # if r.info cannot parse map, skip it # self.raster[r] = UserSettings.Get(group = 'plot', key = 'raster') # some default settings rdict[r] = {} # initialize sub-dictionaries for each raster in the list if ret['units'] == '(none)' or ret['units'] == '' or ret['units'] == None: rdict[r]['units'] = '' else: self.raster[r]['units'] = ret['units'] rdict[r]['plegend'] = r.split('@')[0] rdict[r]['datalist'] = [] # list of cell value,frequency pairs for plotting histogram rdict[r]['pline'] = None rdict[r]['datatype'] = ret['datatype'] rdict[r]['pwidth'] = 1 rdict[r]['pstyle'] = 'solid' if idx <= len(self.colorList): rdict[r]['pcolor'] = self.colorDict[self.colorList[idx]] else: r = randint(0, 255) b = randint(0, 255) g = randint(0, 255) rdict[r]['pcolor'] = ((r,g,b,255)) return rdict
def main(): # lazy imports import grass.temporal as tgis # Get the options input = options["input"] strds = options["strds"] where = options["where"] column = options["column"] method = options["method"] tempwhere = options["t_where"] sampling = options["sampling"] if where == "" or where == " " or where == "\n": where = None # Make sure the temporal database exists tgis.init() # We need a database interface dbif = tgis.SQLDatabaseInterfaceConnection() dbif.connect() sp = tgis.open_old_stds(input, "stvds", dbif) strds_sp = tgis.open_old_stds(strds, "strds", dbif) if strds_sp.get_temporal_type() != sp.get_temporal_type(): dbif.close() grass.fatal( _("Input and aggregation dataset must " "have the same temporal type")) # Check if intervals are present in the sample dataset if sp.get_temporal_type() == "absolute": map_time = sp.absolute_time.get_map_time() else: map_time = sp.relative_time.get_map_time() if map_time != "interval": dbif.close() grass.fatal( _("All registered maps of the space time vector " "dataset must have time intervals")) rows = sp.get_registered_maps("name,layer,mapset,start_time,end_time", tempwhere, "start_time", dbif) if not rows: dbif.close() grass.fatal(_("Space time vector dataset <%s> is empty") % sp.get_id()) # Sample the raster dataset with the vector dataset and run v.what.rast for row in rows: start = row["start_time"] end = row["end_time"] vectmap = row["name"] + "@" + row["mapset"] layer = row["layer"] raster_maps = tgis.collect_map_names(strds_sp, dbif, start, end, sampling) aggreagated_map_name = None if raster_maps: # Aggregation if method != "disabled" and len(raster_maps) > 1: # Generate the temporary map name aggreagated_map_name = "aggreagated_map_name_" + \ str(os.getpid()) new_map = tgis.aggregate_raster_maps(raster_maps, aggreagated_map_name, start, end, 0, method, False, dbif) aggreagated_map_name = aggreagated_map_name + "_0" if new_map is None: continue # We overwrite the raster_maps list raster_maps = (new_map.get_id(), ) for rastermap in raster_maps: if column: col_name = column else: # Create a new column with the SQL compliant # name of the sampled raster map col_name = rastermap.split("@")[0].replace(".", "_") coltype = "DOUBLE PRECISION" # Get raster type rasterinfo = raster.raster_info(rastermap) if rasterinfo["datatype"] == "CELL": coltype = "INT" try: if layer: grass.run_command("v.db.addcolumn", map=vectmap, layer=layer, column="%s %s" % (col_name, coltype), overwrite=grass.overwrite()) else: grass.run_command("v.db.addcolumn", map=vectmap, column="%s %s" % (col_name, coltype), overwrite=grass.overwrite()) except CalledModuleError: dbif.close() grass.fatal( _("Unable to add column %s to vector map <%s>") % (col_name, vectmap)) # Call v.what.rast try: if layer: grass.run_command("v.what.rast", map=vectmap, layer=layer, raster=rastermap, column=col_name, where=where) else: grass.run_command("v.what.rast", map=vectmap, raster=rastermap, column=col_name, where=where) except CalledModuleError: dbif.close() grass.fatal( _("Unable to run v.what.rast for vector map " "<%s> and raster map <%s>") % (vectmap, rastermap)) if aggreagated_map_name: try: grass.run_command("g.remove", flags='f', type='raster', name=aggreagated_map_name) except CalledModuleError: dbif.close() grass.fatal( _("Unable to remove raster map <%s>") % (aggreagated_map_name)) # Use the first map in case a column names was provided if column: break dbif.close()
python import os import grass.script as grass import grass.script.vector as v import grass.script.raster as r import grass.script.db as db cat = '20' input_shape = 'mun_teste_wgs84' input_raster = 'BR_2001_euca_9' col = 'proportion_euca' # Take resolution from raster map rast_info = r.raster_info(input_raster) ewres = rast_info['ewres'] nsres = rast_info['nsres'] ewres nsres # Create a raster for the feature grass.run_command('g.region', vector=input_shape, ewres=ewres, nsres=nsres, align=input_raster) grass.run_command('v.to.rast', input=input_shape, output='temp_rast', cats=cat,
def main(): # Get the options input = options["input"] strds = options["strds"] where = options["where"] column = options["column"] method = options["method"] tempwhere = options["t_where"] sampling = options["sampling"] if where == "" or where == " " or where == "\n": where = None # Make sure the temporal database exists tgis.init() # We need a database interface dbif = tgis.SQLDatabaseInterfaceConnection() dbif.connect() sp = tgis.open_old_stds(input, "stvds", dbif) strds_sp = tgis.open_old_stds(strds, "strds", dbif) if strds_sp.get_temporal_type() != sp.get_temporal_type(): dbif.close() grass.fatal(_("Input and aggregation dataset must " "have the same temporal type")) # Check if intervals are present in the sample dataset if sp.get_temporal_type() == "absolute": map_time = sp.absolute_time.get_map_time() else: map_time = sp.relative_time.get_map_time() if map_time != "interval": dbif.close() grass.fatal(_("All registered maps of the space time vector " "dataset must have time intervals")) rows = sp.get_registered_maps("name,layer,mapset,start_time,end_time", tempwhere, "start_time", dbif) if not rows: dbif.close() grass.fatal(_("Space time vector dataset <%s> is empty") % sp.get_id()) # Sample the raster dataset with the vector dataset and run v.what.rast for row in rows: start = row["start_time"] end = row["end_time"] vectmap = row["name"] + "@" + row["mapset"] layer = row["layer"] raster_maps = tgis.collect_map_names( strds_sp, dbif, start, end, sampling) aggreagated_map_name = None if raster_maps: # Aggregation if method != "disabled" and len(raster_maps) > 1: # Generate the temporary map name aggreagated_map_name = "aggreagated_map_name_" + \ str(os.getpid()) new_map = tgis.aggregate_raster_maps(raster_maps, aggreagated_map_name, start, end, 0, method, False, dbif) aggreagated_map_name = aggreagated_map_name + "_0" if new_map is None: continue # We overwrite the raster_maps list raster_maps = (new_map.get_id(), ) for rastermap in raster_maps: if column: col_name = column else: # Create a new column with the SQL compliant # name of the sampled raster map col_name = rastermap.split("@")[0].replace(".", "_") coltype = "DOUBLE PRECISION" # Get raster type rasterinfo = raster.raster_info(rastermap) if rasterinfo["datatype"] == "CELL": coltype = "INT" try: if layer: grass.run_command("v.db.addcolumn", map=vectmap, layer=layer, column="%s %s" % (col_name, coltype), overwrite=grass.overwrite()) else: grass.run_command("v.db.addcolumn", map=vectmap, column="%s %s" % (col_name, coltype), overwrite=grass.overwrite()) except CalledModuleError: dbif.close() grass.fatal(_("Unable to add column %s to vector map <%s>") % (col_name, vectmap)) # Call v.what.rast try: if layer: grass.run_command("v.what.rast", map=vectmap, layer=layer, raster=rastermap, column=col_name, where=where) else: grass.run_command("v.what.rast", map=vectmap, raster=rastermap, column=col_name, where=where) except CalledModuleError: dbif.close() grass.fatal(_("Unable to run v.what.rast for vector map " "<%s> and raster map <%s>") % (vectmap, rastermap)) if aggreagated_map_name: try: grass.run_command("g.remove", flags='f', type='raster', name=aggreagated_map_name) except CalledModuleError: dbif.close() grass.fatal(_("Unable to remove raster map <%s>") % (aggreagated_map_name)) # Use the first map in case a column names was provided if column: break dbif.close()
array = remove_table(array, table_mm) except StandardError, e: print e return # remove fuzzy edges try: array = remove_fuzzy_edges(array, resolution=mm_resolution, tolerance=0.3) except StandardError, e: print e return # scale Z to original and apply exaggeration raster_info = grast.raster_info(real_elev) try: array = scale_z_exag(array, raster_info, zexag, info_text) except StandardError, e: print e return # trim edges array = trim_edges_nsew(array, trim_nsew) # save resulting array np.savetxt(temp_path, array, delimiter=" ") # import if array.shape[0] < 2000: return
mapset_patch_only_PID = 'MS_HABMAT_PATCHES_ONLY_PID' grass.run_command('g.mapset', mapset = mapset_patch_only_PID, flags = 'c') # Change to the folder where the script is os.chdir(folder_scripts) # For each map, generate 3 scenarios for i in range(len(habmat_map_list)): # Name of the habitat(1)/matrix(2) map habmat_map_name = habmat_map_list[i] # Name of the initial Patch ID map (considering all patches, ss, and trees) pid_map_name = pid_map_list[i] # Resolution of maps map_info = r.raster_info(habmat_map_name+'@'+habmat_mapset_name) pixel_area = float(map_info['ewres'])*float(map_info['nsres']) # in m2 #------------------------ # Map of trees grass.run_command('g.mapset', mapset = mapset_name_trees) # Defining the GRASS GIS region as the map extension grass.run_command('g.region', raster = habmat_map_name+'@'+habmat_mapset_name, flags = '') #'p') # Map of patch size in number of cells grass.run_command('r.area', input = pid_map_name+'@'+pid_mapset_name, output = habmat_map_name+'_patch_size_cells', overwrite = True) # Map of isolated trees (3 = trees, null in the rest) expression1 = habmat_map_name+'_trees_'+str(size_tr)+'pix = if('+habmat_map_name+'_patch_size_cells <= '+str(size_tr)+' &&& '+habmat_map_name+'_patch_size_cells > 0, 3, null())' print expression1