Ejemplo n.º 1
0
    def __del__(self):
        # removes temporary mask, used for import transparent or warped temp_map
        if self.cleanup_mask:
            # clear temporary mask, which was set by module
            if grass.run_command("r.mask", quiet=True, flags="r") != 0:
                grass.fatal(_("%s failed") % "r.mask")

            # restore original mask, if exists
            if grass.find_file(self.opt_output + self.original_mask_suffix, element="cell", mapset=".")["name"]:
                if (
                    grass.run_command("g.copy", quiet=True, rast=self.opt_output + self.original_mask_suffix + ",MASK")
                    != 0
                ):
                    grass.fatal(_("%s failed") % "g.copy")

        # remove temporary created rasters
        if self.cleanup_layers:
            maps = []
            for suffix in (".red", ".green", ".blue", ".alpha", self.original_mask_suffix):
                rast = self.opt_output + suffix
                if grass.find_file(rast, element="cell", mapset=".")["file"]:
                    maps.append(rast)

            if maps:
                grass.run_command("g.remove", quiet=True, flags="fb", type="rast", pattern=",".join(maps))

        # delete environmental variable which overrides region
        if "GRASS_REGION" in os.environ.keys():
            os.environ.pop("GRASS_REGION")
def main():

    # process command options
    input = options['input']
    if not gs.find_file(input)['file']:
        gs.fatal(_("Raster map <%s> not found") % input)

    output = options['output']
    if gs.find_file(output)['file'] and not gs.overwrite():
        gs.fatal(_("Output map <%s> already exists") % output)

    # set aside region for internal use
    gs.use_temp_region()

    # subset input if desired
    region = options.get('region')
    if region:
        if not gs.find_file(region)['file']:
            gs.fatal(_("Raster map <%s> not found") % region)
        gs.message("Setting region to %s" % region, flag='i')
        gs.run_command('g.region', rast=region, align=input)
    else:
        gs.message("Using existing GRASS region", flag='i')
    gs.debug('='*50)
    gs.debug('\n'.join(gs.parse_command('g.region', 'p').keys()))
    gs.debug('='*50)

    calculate_noise(input, output)

    # restore original region
    gs.del_temp_region()

    return None
Ejemplo n.º 3
0
    def AddLayer(self, name, ltype = 'auto'):
        """Add selected map to the layer tree

        :param name: name of raster/vector map to be added
        :param type: map type ('raster', 'vector', 'auto' for autodetection)
        """
        fname = None
        if ltype == 'raster' or ltype != 'vector':
            # check for raster
            fname = grass.find_file(name, element = 'cell')['fullname']
            if fname:
                ltype = 'raster'
                lcmd = 'd.rast'
        
        if not fname and (ltype == 'vector' or ltype != 'raster'):
            # if not found check for vector
            fname = grass.find_file(name, element = 'vector')['fullname']
            if fname:
                ltype = 'vector'
                lcmd = 'd.vect'
        
        if not fname:
            return _("Raster or vector map <%s> not found") % (name)
        
        self.parent.GetLayerTree().AddLayer(ltype = ltype,
                                            lname = fname,
                                            lchecked = True,
                                            lcmd = [lcmd, 'map=%s' % fname])
        if ltype == 'raster':
            return _('Raster map <%s> added') % fname
        
        return _('Vector map <%s> added') % fname
Ejemplo n.º 4
0
    def ImportMapIntoGRASS(self, raster): 
        """!Import raster into GRASS.
        """
        # importing temp_map into GRASS
        try:
            grass.run_command('r.in.gdal',
                              quiet=True, overwrite=True,
                              input=raster, output=self.opt_output)
        except CalledModuleError:
            grass.fatal(_('%s failed') % 'r.in.gdal')

        # information for destructor to cleanup temp_layers, created
        # with r.in.gdal
        self.cleanup_layers = True
        
        # setting region for full extend of imported raster
        if grass.find_file(self.opt_output + '.red', element = 'cell', mapset = '.')['file']:
            region_map = self.opt_output + '.red'
        else:
            region_map = self.opt_output
        os.environ['GRASS_REGION'] = grass.region_env(rast = region_map)
          
        # mask created from alpha layer, which describes real extend
        # of warped layer (may not be a rectangle), also mask contains
        # transparent parts of raster
        if grass.find_file( self.opt_output + '.alpha', element = 'cell', mapset = '.' )['name']:
            # saving current mask (if exists) into temp raster
            if grass.find_file('MASK', element = 'cell', mapset = '.' )['name']:
                try:
                    mask_copy = self.opt_output + self.original_mask_suffix
                    grass.run_command('g.copy', quiet=True,
                                      raster='MASK,' + mask_copy)
                except CalledModuleError:
                    grass.fatal(_('%s failed') % 'g.copy')

            # info for destructor
            self.cleanup_mask = True
            try:
                grass.run_command('r.mask',
                                  quiet=True, overwrite=True,
                                  maskcats="0",
                                  flags='i',
                                  raster=self.opt_output + '.alpha')
            except CalledModuleError:
                grass.fatal(_('%s failed') % 'r.mask')

        #TODO one band + alpha band?
        if grass.find_file(self.opt_output + '.red', element = 'cell', mapset = '.')['file']:
            try:
                grass.run_command('r.composite',
                                  quiet=True, overwrite=True,
                                  red=self.opt_output + '.red',
                                  green=self.opt_output + '.green',
                                  blue=self.opt_output + '.blue',
                                  output=self.opt_output)
            except CalledModuleError:
                grass.fatal(_('%s failed') % 'r.composite')

        grass.message(_('<%s> created.') % self.opt_output)
Ejemplo n.º 5
0
def main():
    # User inputs
    dem = options['input']          # Elevation map
    out = options['friction']       # Output friction surface
    slope = options['slope']        # Optional output slope
    formula = options['formula']    # Formula

    # Error if no friction surface is given
    if not grass.find_file(dem)['name']:
        grass.message(_("Input raster <%s> not found") % dem)
        sys.exit()

    # If output raster exists, but overwrite option isn't selected
    if not grass.overwrite():
        if grass.find_file(out)['name']:
            grass.message(_("Output raster map <%s> already exists") % out)
            sys.exit()

    # Check if slope output name is specified and give error message if it needs to be overwritten but overwrite option isn't selected
    if not slope:
        slope = "tmp_slope_%d_" %os.getpid()
    else:
        if not grass.overwrite():
            if grass.find_file(slope)['name']:
                grass.message(_("Output raster map <%s> already exists") % slope)
                sys.exit()

    # Generate slope (in percent)
    grass.run_command('r.slope.aspect', elevation=dem, slope=slope, format='percent')

    # Choose formula
    if formula == 'Hiker':
        # So-called "Hiker's formula"
        # Tobler W (1993) Three Presentations on Geographical Analysis and Modeling. Technical Report 93-1. California
        # Gorenflo LJ and Gale N (1990) Mapping Regional Settlement in information Space. Journal of Antropological Archaeology (9): 240 - 274
        expression = "$outmap = 1.0 / (( 6.0 * exp(-3.5 * abs(( $slope / 100) + 0.05 ))) * 1000)"
    elif formula == 'Minetti':
        # This formula is presentedy by I. Herzog who based the formula on the physiological data by Minetti.
        # Herzog, I. In press. "Theory and Practice of Cost Functions." In Fusion  of  Cultures.  Proceedings  of  the
        # XXXVIII  Conference  on  Computer  Applications  and Quantitative Methods in Archaeology, CAA 2010.
        expression = "$outmap = 1337.8 * ($slope / 100)^6 + 278.19 * ($slope / 100)^5 - 517.39 * ($slope / 100)^4 - 78.199 * ($slope / 100)^3 + 93.419 * ($slope / 100)^2 + 19.825 * ($slope / 100) + 1.64"
    else:
        grass.message("No valid formula chosen")
        sys.exit()

    # Create friction surface
    try:
        grass.mapcalc(expression, outmap = out, slope = slope)
        grass.message("Friction raster <" + out + "> complete")
    except:
        grass.run_command('g.remove', rast = slope)
        grass.message("Unable to finish operation. Temporary slope raster deleted.")
        sys.exit()

    # Delete temporary slope map if necessary
    if not options['slope']:
        grass.run_command('g.remove', rast = slope)

    grass.message("All done")
Ejemplo n.º 6
0
def map_exists(map_name, type = "raster"):
    if(type == "raster"):
        result = grass.find_file(name = map_name, element = 'cell')
        if not result['file']:
            grass.fatal("Raster map <%s> not found" % map_name)
    else:
        result = grass.find_file(name = map_name, element = 'vector')
        if not result['file']:
            grass.fatal("Vector map <%s> not found" % map_name)
Ejemplo n.º 7
0
def main():
    input = options['input']
    maskcats = options['maskcats']
    remove = flags['r']
    invert = flags['i']

    if not remove and not input:
	grass.fatal(_("Required parameter <input> not set"))

    #check if input file exists
    if not grass.find_file(input)['file'] and not remove:
        grass.fatal(_("<%s> does not exist.") % input)

    if not 'MASKCATS' in grass.gisenv() and not remove:
        ## beware: next check is made with != , not with 'is', otherwise:
        #>>> grass.raster_info("basin_50K")['datatype'] is "CELL"
        #False
        # even if:
        #>>> "CELL" is "CELL"
        #True 
        if grass.raster_info(input)['datatype'] != "CELL":
            grass.fatal(_("Raster map %s must be integer for maskcats parameter") % input)

    mapset = grass.gisenv()['MAPSET']
    exists = bool(grass.find_file('MASK', element = 'cell', mapset = mapset)['file'])

    if remove:
	if exists:
	    grass.run_command('g.remove', rast = 'MASK')
	    grass.message(_("Raster MASK removed"))
 	else:
	    grass.fatal(_("No existing MASK to remove"))
    else:
	if exists:
            if not grass.overwrite():
                grass.fatal(_("MASK already found in current mapset. Delete first or overwrite."))
            else:
                grass.warning(_("MASK already exists and will be overwritten"))

	p = grass.feed_command('r.reclass', input = input, output = 'MASK', overwrite = True, rules = '-')
	p.stdin.write("%s = 1" % maskcats)
	p.stdin.close()
	p.wait()

	if invert:
	    global tmp
	    tmp = "r_mask_%d" % os.getpid()
	    grass.run_command('g.rename', rast = ('MASK',tmp), quiet = True)
	    grass.mapcalc("MASK=if(isnull($tmp),1,null())", tmp = tmp)
	    grass.run_command('g.remove', rast = tmp, quiet = True)
	    grass.message(_("Inverted MASK created."))
	else:
	    grass.message(_("MASK created."))

        grass.message(_("All subsequent raster operations will be limited to MASK area. ") +
		      "Removing or renaming raster file named MASK will " +
		      "restore raster operations to normal")
Ejemplo n.º 8
0
    def ImportMapIntoGRASS(self, raster):
        """!Import raster into GRASS.
        """
        # importing temp_map into GRASS
        if grass.run_command("r.in.gdal", quiet=True, overwrite=True, input=raster, output=self.opt_output) != 0:
            grass.fatal(_("%s failed") % "r.in.gdal")

        # information for destructor to cleanup temp_layers, created
        # with r.in.gdal
        self.cleanup_layers = True

        # setting region for full extend of imported raster
        if grass.find_file(self.opt_output + ".red", element="cell", mapset=".")["file"]:
            region_map = self.opt_output + ".red"
        else:
            region_map = self.opt_output
        os.environ["GRASS_REGION"] = grass.region_env(rast=region_map)

        # mask created from alpha layer, which describes real extend
        # of warped layer (may not be a rectangle), also mask contains
        # transparent parts of raster
        if grass.find_file(self.opt_output + ".alpha", element="cell", mapset=".")["name"]:
            # saving current mask (if exists) into temp raster
            if grass.find_file("MASK", element="cell", mapset=".")["name"]:
                if (
                    grass.run_command("g.copy", quiet=True, rast="MASK," + self.opt_output + self.original_mask_suffix)
                    != 0
                ):
                    grass.fatal(_("%s failed") % "g.copy")

            # info for destructor
            self.cleanup_mask = True
            if (
                grass.run_command(
                    "r.mask", quiet=True, overwrite=True, maskcats="0", flags="i", raster=self.opt_output + ".alpha"
                )
                != 0
            ):
                grass.fatal(_("%s failed") % "r.mask")

        # TODO one band + alpha band?
        if grass.find_file(self.opt_output + ".red", element="cell", mapset=".")["file"]:
            if (
                grass.run_command(
                    "r.composite",
                    quiet=True,
                    overwrite=True,
                    red=self.opt_output + ".red",
                    green=self.opt_output + ".green",
                    blue=self.opt_output + ".blue",
                    output=self.opt_output,
                )
                != 0
            ):
                grass.fatal(_("%s failed") % "r.composite")

        grass.message(_("<%s> created.") % self.opt_output)
Ejemplo n.º 9
0
def main(argv = None):
    """ Main. Calls either GUI or CLI, depending on arguments provided. """
    #@FIXME: solve this double ifelse. the control should not be done twice.
    
    controller = Controller()
    
    if argv is None:
        importR()
        argv = sys.argv[1:] # stripping first item, the full name of this script
        # wxGUI call
        import globalvar
        if not os.getenv("GRASS_WXBUNDLED"):
            globalvar.CheckForWx()
        import vkrige as GUI
        
        import wx
        
        app = wx.App()
        KrigingFrame = GUI.KrigingModule(parent = None,
                                         Rinstance = robjects,
                                         controller = controller)
        KrigingFrame.Centre()
        KrigingFrame.Show()
        app.MainLoop()
        
    else:
        #CLI
        options, flags = argv
        
        #@TODO: Work on verbosity. Sometimes it's too verbose (R), sometimes not enough.
        if grass.find_file(options['input'], element = 'vector')['fullname'] is '':
            grass.fatal(_("option: <input>: Vector map not found.")) #TODO cosmetics, insert real map name
        
        #@TODO: elaborate input string, if contains mapset or not.. thanks again to Bob for testing on 64bit.
        
        # create output map name, if not specified
        if options['output'] is '':
            try: # to strip mapset name from fullname. Ugh.
                options['input'] = options['input'].split("@")[0]
            except:
                pass
            options['output'] = options['input'] + '_kriging'

        # check for output map with same name. g.parser can't handle this, afaik.
        if grass.find_file(options['output'], element = 'cell')['fullname'] and os.getenv("GRASS_OVERWRITE") == None:
            grass.fatal(_("option: <output>: Raster map already exists."))
        if options['output_var'] is not '' and (grass.find_file(options['output_var'], element = 'cell')['fullname'] and os.getenv("GRASS_OVERWRITE") == None):
            grass.fatal(_("option: <output>: Variance raster map already exists."))

        importR()        
        if options['model'] is '':
            try:
                robjects.r.require("automap")
            except ImportError, e:
                grass.fatal(_("R package automap is missing, no variogram autofit available."))
        else:
Ejemplo n.º 10
0
def main():
    group_name = subgroup_name = map_name = trainingmap_name = None

    if options["group"]:
        if not options["subgroup"]:
            grass.fatal(_("Name of subgroup required"))
        group_name = grass.find_file(name=options["group"], element="group")["name"]
        if not group_name:
            grass.fatal(_("Group <%s> not found") % options["group"])
        if options["subgroup"] not in grass.read_command("i.group", group=group_name, flags="sg").splitlines():
            grass.fatal(_("Subgroup <%s> not found") % options["subgroup"])
        subgroup_name = options["subgroup"]

    if options["map"]:
        map_name = grass.find_file(name=options["map"], element="cell")["fullname"]
        if not map_name:
            grass.fatal(_("Raster map <%s> not found") % options["map"])

    if options["trainingmap"]:
        trainingmap_name = grass.find_file(name=options["trainingmap"], element="vector")["fullname"]
        if not trainingmap_name:
            grass.fatal(_("Vector map <%s> not found") % options["trainingmap"])

    # define display driver
    driver = UserSettings.Get(group="display", key="driver", subkey="type")
    if driver == "png":
        os.environ["GRASS_RENDER_IMMEDIATE"] = "png"
    else:
        os.environ["GRASS_RENDER_IMMEDIATE"] = "cairo"

    # launch application
    app = wx.App()
    if not CheckWxVersion([2, 9]):
        wx.InitAllImageHandlers()

    # show main frame
    giface = StandaloneGrassInterface()
    frame = IClassMapFrame(parent=None, giface=giface)
    if not flags["m"]:
        frame.CenterOnScreen()
    if group_name:
        frame.SetGroup(group_name, subgroup_name)
    if map_name:
        giface.WriteLog(_("Loading raster map <%s>...") % map_name)
        frame.trainingMapManager.AddLayer(map_name)
    if trainingmap_name:
        giface.WriteLog(_("Loading training map <%s>...") % trainingmap_name)
        frame.ImportAreas(trainingmap_name)

    frame.Show()
    if flags["m"]:
        frame.Maximize()

    app.MainLoop()
Ejemplo n.º 11
0
def main():
    group_name = subgroup_name = map_name = trainingmap_name = None

    if options['group']:
        if not options['subgroup']:
            grass.fatal(_("Name of subgroup required"))
        group_name = grass.find_file(name = options['group'], element = 'group')['name']
        if not group_name:
            grass.fatal(_("Group <%s> not found") % options['group'])
        if options['subgroup'] not in grass.read_command('i.group', group = group_name, flags = 'sg').splitlines():
            grass.fatal(_("Subgroup <%s> not found") % options['subgroup'])
        subgroup_name = options['subgroup']
    
    if options['map']:
        map_name = grass.find_file(name = options['map'], element = 'cell')['fullname']
        if not map_name:
            grass.fatal(_("Raster map <%s> not found") % options['map'])
    
    if options['trainingmap']:
        trainingmap_name = grass.find_file(name = options['trainingmap'], element = 'vector')['fullname']
        if not trainingmap_name:
            grass.fatal(_("Vector map <%s> not found") % options['trainingmap'])
    
    # define display driver
    driver = UserSettings.Get(group = 'display', key = 'driver', subkey = 'type')
    if driver == 'png':
        os.environ['GRASS_RENDER_IMMEDIATE'] = 'png'
    else:
        os.environ['GRASS_RENDER_IMMEDIATE'] = 'cairo'
    
    # launch application
    app = wx.App()
    if not CheckWxVersion([2, 9]):
        wx.InitAllImageHandlers()
    
    # show main frame
    giface = StandaloneGrassInterface()
    frame = IClassMapFrame(parent = None, giface = giface)
    if not flags['m']:
        frame.CenterOnScreen()
    if group_name:
        frame.SetGroup(group_name, subgroup_name) 
    if map_name:
        giface.WriteLog(_("Loading raster map <%s>...") % map_name)
        frame.trainingMapManager.AddLayer(map_name)
    if trainingmap_name:
        giface.WriteLog(_("Loading training map <%s>...") % trainingmap_name)
        frame.ImportAreas(trainingmap_name)

    frame.Show()    
    if flags['m']:
        frame.Maximize()
    
    app.MainLoop()
Ejemplo n.º 12
0
def main():
	river = options['river']
	stations = options['stations']
	xsections = options['xsections']
	elev = options['elevation']
	output = options['output']
	res = options['resolution']
	
	# do input maps exist in CURRENT mapset?
	mapset = grass.gisenv()['MAPSET']
	if not grass.find_file(river, element = 'vector', mapset = mapset)['file']:
		grass.fatal(_("Vector map <%s> not found in current mapset") % river)
	if not grass.find_file(stations, element = 'vector', mapset = mapset)['file']:
		grass.fatal(_("Vector map <%s> not found in current mapset") % stations)
	if not grass.find_file(xsections, element = 'vector', mapset = mapset)['file']:
		grass.fatal(_("Vector map <%s> not found in current mapset") % xsections)
	if not grass.find_file(elev, element = 'raster', mapset = mapset)['file']:
		grass.fatal(_("Raster map <%s> not found in current mapset") % elev)
	if not res:
		# No resolution given, use the resolution of the elevation raster
		info = grass.read_command('r.info', map=elev, flags="g")
		d=grass.parse_key_val(info)
		res=d['ewres']  # Assume ewres=nsres
	# Be sure region is set to dtm layer
	grass.run_command('g.region', raster=elev, res=res, quiet=True, flags="a")

	# Prepare output file
	if ".sdf" == output.lower()[-4]:
		sdf=output
	else:
		sdf=output+".sdf"
	
	sdf_file=open(sdf, 'w')

	# The work starts here
	output_headers(river, xsections, sdf_file)	
	grass.message("Headers written to %s" % sdf)
	output_centerline(river, stations, elev, sdf_file)
	grass.message("River network written to %s" % sdf)
	output_xsections(xsections, sdf_file, elev, res, river)
	grass.message("Cross sections written to %s" % sdf)

	sdf_file.close()
	
	# Replace newline chars with CR-NL for windows?
	replace_nl = True
	if flags['u']:
		replace_nl = False
	cleanup(sdf, replace_nl)
	return 0
Ejemplo n.º 13
0
def main():
    options, unused = gscript.parser()
    input = options['input']
    red = options['red']
    green = options['green']
    blue = options['blue']

    if not gscript.find_file(input)['file']:
        gscript.fatal(_("Raster map <%s> not found") % input)

    expressions = []
    maps = []
    if red:
        expressions.append('%s = r#${input}' % red)
        maps.append(red)
    if green:
        expressions.append('%s = g#${input}' % green)
        maps.append(green)
    if blue:
        expressions.append('%s = b#${input}' % blue)
        maps.append(blue)
    expr = ';'.join(expressions)
    gscript.mapcalc(expr, input=input)

    for name in maps:
        gscript.run_command('r.colors', map=name, color='grey255')
        gscript.raster_history(name)
Ejemplo n.º 14
0
def get_stats_cat(map_name, table_name, cat):
    ### Get the col names - sometimes not all values are found in the sub-catchment.
    tmp = raster.RasterRow(map_name.split('@')[0])
    tmp.has_cats()
    col_names = []
    col_master_name = grass.find_file(name = map_name, element = 'cell')['name']
    for i in range(len(tmp.cats)):
        col_names.append(col_master_name + "_" + str(tmp.cats[i][1]))
    ## Get the stats for this layer and save it to a dict.
    stats  = grass.read_command("r.stats", input=map_name, flags='pn', quiet = True)
    stats = stats.split("\n")
    area_dict = {}
    for i in range(len(stats)):
        if(len(stats[i])>0):
            tmp = stats[i].split(" ")
            area_dict[col_master_name + "_" + tmp[0]] = float(tmp[1].replace("%",""))
    ## Save the results - look up the col name in the dict from above. If nothing is found than land cover area must equal 0.
    for i in range(len(col_names)):
        if col_names[i] in area_dict:
            #query = "UPDATE " + prediction_map + "_2 SET " + col_names[i] + "=" + str(area_dict[col_names[i]]) + " WHERE cat = " + str(cat)
            query = "UPDATE " + table_name + " SET " + col_names[i] + "=" + str(area_dict[col_names[i]]) + " WHERE cat = " + str(cat)
            grass.run_command('db.execute', sql=str(query))
        else:
            query = "UPDATE " + table_name + " SET " + col_names[i] + "=" + str(0.0) + " WHERE cat = " + str(cat)
            grass.run_command('db.execute', sql=str(query))
Ejemplo n.º 15
0
def main():
    driver = UserSettings.Get(group = 'display', key = 'driver', subkey = 'type')
    if driver == 'png':
        os.environ['GRASS_RENDER_IMMEDIATE'] = 'png'
    else:
        os.environ['GRASS_RENDER_IMMEDIATE'] = 'cairo'
    
    first = options['first']
    second = options['second']
    mode = options['mode']

    for mapName in [first, second]:    
        if mapName:
            gfile = grass.find_file(name = mapName)
            if not gfile['name']:
                grass.fatal(_("Raster map <%s> not found") % mapName)

    app = wx.App()
    if not CheckWxVersion([2, 9]):
        wx.InitAllImageHandlers()

    frame = SwipeMapFrame(parent = None, giface = StandaloneGrassInterface())
    
    if first:
        frame.SetFirstRaster(first)
    if second:
        frame.SetSecondRaster(second)
    if first or second:
        frame.SetRasterNames()

    frame.SetViewMode(mode)
    frame.Show()

    app.MainLoop()
Ejemplo n.º 16
0
    def _getRegionParams(self,opt_region):
        """!Get region parameters from region specified or active default region

        @return region_params as a dictionary
        """
        self._debug("_getRegionParameters", "started")

        if opt_region:
            reg_spl = opt_region.strip().split('@', 1)
            reg_mapset = '.'
            if len(reg_spl) > 1:
                reg_mapset = reg_spl[1]

            if not gscript.find_file(name = reg_spl[0], element = 'windows',
                                   mapset = reg_mapset)['name']:
                 gscript.fatal(_("Region <%s> not found") % opt_region)

        if opt_region:
            s = gscript.read_command('g.region',
                                    quiet = True,
                                    flags = 'ug',
                                    region = opt_region)
            region_params = gscript.parse_key_val(s, val_type = float)
            gscript.verbose("Using region parameters for region %s" %opt_region)
        else:
            region_params = gscript.region()
            gscript.verbose("Using current grass region")

        self._debug("_getRegionParameters", "finished")
        return region_params
Ejemplo n.º 17
0
    def SetData(self):

        dlg = IClassGroupDialog(self.scatt_mgr.guiparent,
                                group=self.set_g['group'],
                                subgroup=self.set_g['subg'])

        bands = []
        while True:
            if dlg.ShowModal() == wx.ID_OK:

                bands = dlg.GetGroupBandsErr(parent=self.scatt_mgr.guiparent)
                if bands:
                    name, s = dlg.GetData()
                    group = grass.find_file(name=name, element='group')
                    self.set_g['group'] = group['name']
                    self.set_g['subg'] = s

                    break
            else:
                break

        dlg.Destroy()
        self.added_cats_rasts = {}

        if bands:
            self.scatt_mgr.SetBands(bands)
Ejemplo n.º 18
0
    def UpdateCategoryRaster(self, cat_id, attrs, render=True):
        if not self.scatt_mgr.data_set:
            return

        cat_rast = self.scatt_mgr.core.GetCatRast(cat_id)
        if not cat_rast:
            return

        if not grass.find_file(cat_rast, element='cell', mapset='.')['file']:
            return
        cats_attrs = self.cats_mgr.GetCategoryAttrs(cat_id)
        train_mgr, preview_mgr = self.iclass_frame.GetMapManagers()

        if "color" in attrs:
            ret, err_msg = RunCommand('r.colors',
                                      map=cat_rast,
                                      rules="-",
                                      stdin="1 %s" % cats_attrs["color"],
                                      getErrorMsg=True)

            if ret != 0:
                GError("r.colors failed\n%s" % err_msg)
            if render:
                train_mgr.Render()

        if "name" in attrs:
            cat_rast = self.scatt_mgr.core.GetCatRast(cat_id)

            train_mgr.SetAlias(original=cat_rast, alias=cats_attrs['name'])
            cats_attrs["name"]
Ejemplo n.º 19
0
    def _initializeParameters(self, options, flags):
        '''
        Initialize all given and needed parameters. Get region information and
        calculate boundingbox according to it

        '''
        self._debug("_initializeParameters", "started")

        self._env = os.environ.copy()
        self._env['GRASS_MESSAGE_FORMAT'] = 'gui'
        g.gisenv(set="GRASS_MESSAGE_FORMAT=gui")

        for key in ['url', 'coverage','output','location']:
            self.params[key] = options[key].strip()

        if not self.params['output']:
            self.params['output'] = self.params['coverage']
            if not gscript.overwrite():
                result = gscript.find_file(name = self.params['output'], element = 'cell')
                if  result['file']:
                    gscript.fatal("Raster map <%s> does already exist. Choose other output name or toggle flag --o." % self.params['output'])

        for key in ['password', 'username', 'version','region']:
            self.params[key] = options[key]

        # check if authentication information is complete
        if (self.params['password'] and self.params['username'] == '') or \
           (self.params['password'] == '' and self.params['username']):
                gscript.fatal(_("Please insert both %s and %s parameters or none of them." % ('password', 'username')))


        # configure region extent (specified name or current region)
        self.params['region'] = self._getRegionParams(options['region'])
        self.params['boundingbox'] = self._computeBbox(self.params['region'])
        self._debug("_initializeParameters", "finished")
Ejemplo n.º 20
0
def main():
    options, flags = gscript.parser()

    import wx

    from grass.script.setup import set_gui_path
    set_gui_path()
    
    from core.utils import _
    from dbmgr.manager import AttributeManager

    mapName = gscript.find_file(options['map'], element='vector')['fullname']
    if not mapName:
        gscript.set_raise_on_error(False)
        gscript.fatal(_("Vector map <%s> not found") % options['map'])

    app = wx.App()
    gscript.message(_("Loading attribute data for vector map <%s>...") % mapName)
    f = AttributeManager(parent=None, id=wx.ID_ANY,
                         title="%s - <%s>" % (_("GRASS GIS Attribute Table Manager"),
                                              mapName),
                         size=(900, 600), vectorName=mapName)
    f.Show()

    app.MainLoop()
def mask_data(band_filter, cfmask_filter, cloud_mask_value, file_separator):
    # do cleanup first
    grass.run_command('g.remove', type='raster', pattern='*_masked', flags='f', quiet=True)
    
    # find band1 raster maps first
    bands1 = grass.list_grouped('raster', pattern='*{}1*'.format(band_filter))[mapset]
    count = len(bands1)
    i = 0
    for b1 in bands1:
        i += 1
        basename = b1.split(file_separator)[0]
        grass.message("Processing <{0}> ({1}/{2})...".format(basename, i, count))
        grass.percent(i, count, 5)
        # set computational region based on first band
        grass.run_command('g.region', raster=b1)
        maskname = '{}{}{}'.format(basename, file_separator, cfmask_filter)
        mask = grass.find_file(maskname, element='raster')['fullname']
        # apply cloud mask if found
        if mask:
            grass.run_command('r.mask', flags='i', raster=maskname, maskcats=cloud_mask_value, overwrite=True, quiet=True)
        else:
            grass.warning("Mask missing for <{}>".format(basename))
        # create copy of band with mask applied
        bands = grass.list_grouped('raster', pattern='{}{}{}*'.format(basename, file_separator, band_filter))[mapset]
        for b in bands:
            grass.mapcalc('{name}_masked={name}'.format(name=b), quiet=True, overwrite=True)
            grass.run_command('r.colors', map=b, color='grey.eq')
        # remove mask if applied
        if mask:
            grass.run_command('r.mask', flags='r', quiet=True)
Ejemplo n.º 22
0
    def __init__(self, parent, title, vectmap, modeChoices, id = wx.ID_ANY,
                 layer = 1):
        wx.Frame.__init__(self, parent, id, title)
        
        self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, 'grass_sql.ico'),
                             wx.BITMAP_TYPE_ICO))
        
        self.parent     = parent
        
        # variables
        self.vectmap = vectmap # fullname
        if not "@" in self.vectmap:
            self.vectmap = grass.find_file(self.vectmap, element = 'vector')['fullname']
            if not self.vectmap:
                grass.fatal(_("Vector map <%s> not found") % vectmap)
        self.mapname, self.mapset = self.vectmap.split("@", 1)
        
        # db info
        self.layer = layer
        self.dbInfo = VectorDBInfo(self.vectmap)
        self.tablename = self.dbInfo.GetTable(self.layer)
        self.driver, self.database = self.dbInfo.GetDbSettings(self.layer)
        
        self.colvalues = []     # array with unique values in selected column
        
        self.panel = wx.Panel(parent = self, id = wx.ID_ANY)

        # statusbar
        self.statusbar = self.CreateStatusBar(number=1)
        
        self._doLayout(modeChoices)
Ejemplo n.º 23
0
def main():
    map = options['map']
    layer = options['layer']
    column = options['column']

    mapset = grass.gisenv()['MAPSET']

    if not grass.find_file(map, element = 'vector', mapset = mapset):
        grass.fatal(_("Vector map <%s> not found in current mapset") % map)

    f = grass.vector_layer_db(map, layer)

    table = f['table']
    keycol = f['key']
    database = f['database']
    driver = f['driver']

    if not table:
        grass.fatal(_("There is no table connected to the input vector map. Cannot rename any column"))

    cols = column.split(',')
    oldcol = cols[0]
    newcol = cols[1]

    if driver == "dbf":
        if len(newcol) > 10:
            grass.fatal(_("Column name <%s> too long. The DBF driver supports column names not longer than 10 characters") % newcol)

    if oldcol == keycol:
        grass.fatal(_("Cannot rename column <%s> as it is needed to keep table <%s> connected to the input vector map") % (oldcol, table))

    # describe old col
    oldcoltype = None
    for f in grass.db_describe(table)['cols']:
        if f[0] != oldcol:
            continue
        oldcoltype = f[1]
        oldcollength = f[2]

    # old col there?
    if not oldcoltype:
        grass.fatal(_("Column <%s> not found in table <%s>") % (oldcol, table))

    # some tricks
    if driver in ['sqlite', 'dbf']:
        if oldcoltype.upper() == "CHARACTER":
            colspec = "%s varchar(%s)" % (newcol, oldcollength)
        else:
            colspec = "%s %s" % (newcol, oldcoltype)

        grass.run_command('v.db.addcolumn', map = map, layer = layer, column = colspec)
        sql = "UPDATE %s SET %s=%s" % (table, newcol, oldcol)
        grass.write_command('db.execute', input = '-', database = database, driver = driver, stdin = sql)
        grass.run_command('v.db.dropcolumn', map = map, layer = layer, column = oldcol)
    else:
        sql = "ALTER TABLE %s RENAME %s TO %s" % (table, oldcol, newcol)
        grass.write_command('db.execute', input = '-', database = database, driver = driver, stdin = sql)

    # write cmd history:
    grass.vector_history(map)
Ejemplo n.º 24
0
    def __init__(self, opt_output):

        self.cleanup_mask = False
        self.cleanup_layers = False

        # output map name
        self.opt_output = opt_output

        # suffix for existing mask (during overriding will be saved
        # into raster named:self.opt_output + this suffix)
        self.original_mask_suffix = "_temp_MASK"

        # check names of temporary rasters, which module may create
        maps = []
        for suffix in (".red", ".green", ".blue", ".alpha", self.original_mask_suffix):
            rast = self.opt_output + suffix
            if grass.find_file(rast, element="cell", mapset=".")["file"]:
                maps.append(rast)

        if len(maps) != 0:
            grass.fatal(
                _(
                    "Please change output name, or change names of these rasters: %s, "
                    "module needs to create this temporary maps during execution."
                )
                % ",".join(maps)
            )
Ejemplo n.º 25
0
def main():
    infile = options['input']
    value = options['value']
    mode = options['mode']
    outfile = options['output']
    global method
    method = options['method']
    clumped = flags['c']
    diagonal = flags['d']

    # check for unsupported locations
    in_proj = grass.parse_command('g.proj', flags='g')
    if in_proj['unit'].lower() == 'degree':
        grass.fatal(_("Latitude-longitude locations are not supported"))
    if in_proj['name'].lower() == 'xy_location_unprojected':
        grass.fatal(_("xy-locations are not supported"))

    # check lesser and greater parameters
    limit = float(value)
    if mode == 'greater' and method == 'rmarea':
        grass.fatal(_("You have to specify mode='lesser' with method='rmarea'"))

    if not grass.find_file(infile)['name']:
        grass.fatal(_("Raster map <%s> not found") % infile)

    if method == 'reclass':
        reclass(infile, outfile, limit, clumped, diagonal, mode == 'lesser')
    elif method == 'rmarea':
        rmarea(infile, outfile, limit, in_proj['meters'])

    grass.message(_("Generating output raster map <%s>...") % outfile)
Ejemplo n.º 26
0
def cleanup():
    grass.verbose("Cleaning up ...")
    if tmp:
	grass.try_remove(tmp)
    if tmp_proj:
	grass.try_remove(tmp_proj)
    if tmp_gpx:
	grass.try_remove(tmp_gpx)

    # only try to remove map if it exists to avoid ugly warnings
    if tmp_vogb:
	if grass.find_file(tmp_vogb, element = 'vector')['name']:
	    grass.run_command('g.remove', vect = tmp_vogb, quiet = True)
    if tmp_extr:
	if grass.find_file(tmp_extr, element = 'vector')['name']:
	    grass.run_command('g.remove', vect = tmp_vogb, quiet = True)
Ejemplo n.º 27
0
def main():
    first = options['first']
    second = options['second']
    output = options['output_prefix']
    percent = options['percent']

    mapset = grass.gisenv()['MAPSET']

    if not grass.overwrite():
	for ch in ['r','g','b']:
	    map = '%s.%s' % (output, ch)
	    if grass.find_file(map, element = 'cell', mapset = mapset)['file']:
		grass.fatal(_("Raster map <%s> already exists.") % map)

    percent = float(percent)
    perc_inv = 100.0 - percent

    frac1 = percent / 100.0
    frac2 = perc_inv / 100.0

    grass.message(_("Calculating the three component maps..."))

    template = string.Template("$$output.$ch = if(isnull($$first), $ch#$$second, if(isnull($$second), $ch#$$first, $$frac1 * $ch#$$first + $$frac2 * $ch#$$second))")
    cmd = [template.substitute(ch = ch) for ch in ['r','g','b']]
    cmd = ';'.join(cmd)

    grass.mapcalc(cmd,
		  output = output,
		  first = first, second = second,
		  frac1 = frac1, frac2 = frac2)

    for ch in ['r','g','b']:
	map = "%s.%s" % (output, ch)
	grass.run_command('r.colors', map = map, color = 'grey255')
	grass.run_command('r.support', map = map, history="",
			  title = "Color blend of %s and %s" % (first, second),
			  description = "generated by r.blend")
	grass.run_command('r.support', map = map,
			  history = "r.blend %s channel." % ch)
	grass.run_command('r.support', map = map,
			  history = "  %d%% of %s, %d%% of %s" % (percent, first, perc_inv, second))
	grass.run_command('r.support', map = map, history = "")
	grass.run_command('r.support', map = map, history = os.environ['CMDLINE'])


    if flags['c']:
        grass.run_command('r.composite', r = '%s.r' % output,
	    g = '%s.g' % output, b = '%s.b' % output, output = output)

	grass.run_command('r.support', map = output, history="",
	    title = "Color blend of %s and %s" % (first, second),
	    description = "generated by r.blend")
	grass.run_command('r.support', map = output,
	    history = "  %d%% of %s, %d%% of %s" % (percent, first, perc_inv, second))
	grass.run_command('r.support', map = output, history = "")
	grass.run_command('r.support', map = output, history = os.environ['CMDLINE'])
    else:
        grass.message(_("Done. Use the following command to visualize the result:"))
        grass.message(_("d.rgb r=%s.r g=%s.g b=%s.b") % (output, output, output))
Ejemplo n.º 28
0
 def OnAddRast(self, event):
     dlg = IClassMapDialog(self, title = _("Add raster map"), element = 'raster')
     if dlg.ShowModal() == wx.ID_OK:
         raster = grass.find_file(name = dlg.GetMap(), element = 'cell')
         if raster['fullname']:
             self.mapManager.AddLayer(name = raster['fullname'])
             
     dlg.Destroy()
Ejemplo n.º 29
0
    def SetSecondRaster(self, name):
        """Set raster map to second Map"""
        raster = grass.find_file(name = name, element = 'cell')
        if raster['fullname']:
            self.rasters['second'] = raster['fullname']
            self.SetLayer(name = raster['fullname'], mapInstance = self.GetSecondMap())
            return True

        return False
def cleanup():
    """
    Clean up temporary maps
    """
    grass.run_command('g.remove', flags='f', type="rast",
                      pattern='tmp.{pid}*'.format(pid=os.getpid()), quiet=True)

    if grass.find_file(name='MASK', element='cell')['file']:
        r.mask(flags='r', verbose=True)
Ejemplo n.º 31
0
    def SetSecondRaster(self, name):
        """Set raster map to second Map"""
        if name:
            raster = grass.find_file(name=name, element="cell")
            if raster.get("fullname"):
                self.rasters["second"] = raster["fullname"]
                self.SetLayer(name=raster["fullname"], mapInstance=self.GetSecondMap())
                return True

        return False
Ejemplo n.º 32
0
    def SetFirstRaster(self, name):
        """Set raster map to first Map"""
        raster = grass.find_file(name=name, element='cell')
        if raster['fullname']:
            self.rasters['first'] = raster['fullname']
            self.SetLayer(name=raster['fullname'],
                          mapInstance=self.GetFirstMap())
            return True

        return False
Ejemplo n.º 33
0
 def appendVector(self):
     if not self.settings['drawing']['append']:
         return
     ff = gscript.find_file(self.settings['drawing']['appendName'],
                            element='vector', mapset=gscript.gisenv()['MAPSET'])
     if not(ff and ff['fullname']):
         self._newAppendedVector()
     gscript.run_command('v.patch', input=self.settings['drawing']['name'],
                         output=self.settings['drawing']['appendName'],
                         flags='a', overwrite=True, quiet=True)
Ejemplo n.º 34
0
def cleanup():
    # remove temp location
    if TMPLOC:
        grass.try_rmdir(os.path.join(GISDBASE, TMPLOC))
    if SRCGISRC:
        grass.try_remove(SRCGISRC)
    if TMP_REG_NAME and grass.find_file(name=TMP_REG_NAME, element='vector',
                                        mapset=grass.gisenv()['MAPSET'])['fullname']:
        grass.run_command('g.remove', type='vector', name=TMP_REG_NAME,
                          flags='f', quiet=True)
Ejemplo n.º 35
0
def main():

    # check if GISBASE is set
    if "GISBASE" not in os.environ:
        # return an error advice
        grass.fatal("You must be in GRASS GIS to run this program")

    # input raster map and parameters
    inputmap = options['input']
    outBase = options['output']
    rules = options['rules']
    outNames = outBase.split(',')
    lengthNames = len(outNames)
    flag_a = flags['a']

    # Get attribute data
    myData = np.genfromtxt(rules, delimiter=',', skip_header=1)
    nmsData = np.genfromtxt(rules, delimiter=',', names=True)
    dimData = myData.shape
    nmsData = nmsData.dtype.names

    # Create recode maps
    numVar = xrange(dimData[1] - 1)
    for x in numVar:
        y = x + 1
        myRecode = np.column_stack((myData[:, 0], myData[:, 0], myData[:, y]))

        fd1, tmpname = tempfile.mkstemp()
        np.savetxt(tmpname, myRecode, delimiter=":")

        if len(numVar) == lengthNames:
            nmOutput = outNames[x]
        else:
            nmOutput = outNames[0] + '_' + nmsData[y]

        cf = grass.find_file(name=nmOutput,
                             element='cell',
                             mapset=grass.gisenv()['MAPSET'])
        if cf['fullname'] != '':
            grass.fatal("The layer " + nmOutput +
                        " already exist in this mapset")

        if flag_a:
            grass.run_command('r.recode',
                              input=inputmap,
                              output=nmOutput,
                              rules=tmpname,
                              flags="a")
        else:
            grass.run_command('r.recode',
                              input=inputmap,
                              output=nmOutput,
                              rules=tmpname)
        os.close(fd1)
        os.remove(tmpname)
Ejemplo n.º 36
0
def main():

    # process command options
    input = options['input']
    if not gs.find_file(input)['file']:
        gs.fatal(_("Raster map <%s> not found") % input)

    smooth = options['output']
    if gs.find_file(smooth)['file'] and not gs.overwrite():
        gs.fatal(_("Output map <%s> already exists") % smooth)

    sd = options['sd']
    try:
        sd = float(sd)
    except ValueError:
        if not gs.find_file(sd)['file']:
            gs.fatal(_("Raster map <%s> not found") % sd)

    alpha = float(options['alpha'])

    # set aside region for internal use
    gs.use_temp_region()

    # subset input if desired
    region = options.get('region')
    if region:
        if not gs.find_file(region)['file']:
            gs.fatal(_("Raster map <%s> not found") % region)
        gs.message("Setting region to %s" % region, flag='i')
        gs.run_command('g.region', rast=region, align=input)
    else:
        gs.message("Using existing GRASS region", flag='i')
    gs.debug('='*50)
    gs.debug('\n'.join(gs.parse_command('g.region', 'p').keys()))
    gs.debug('='*50)

    multiscalesmooth(input, smooth, sd, alpha)

    # restore original region
    gs.del_temp_region()

    return None
Ejemplo n.º 37
0
def cleanup():
    if gscript.find_file(name='MASK',
                         element='cell',
                         mapset=gscript.gisenv()['MAPSET'])['name']:
        gscript.run_command('r.mask', flags='r', quiet=True)
    if TMP:
        gscript.run_command('g.remove',
                            flags='f',
                            type=['raster', 'vector'],
                            name=TMP,
                            quiet=True)
Ejemplo n.º 38
0
def cleanup():
    """Remove temporary maps specified in the global list"""
    list_temporary_layers = list(reversed(clean_layers))
    for temporary_layer in list_temporary_layers:
        ffile = gs.find_file(
            name=temporary_layer, element="vector", mapset=gs.gisenv()["MAPSET"]
        )
        if ffile["file"]:
            gs.run_command(
                "g.remove", flags="f", type="vector", name=temporary_layer, quiet=True
            )
Ejemplo n.º 39
0
    def _initializeParameters(self, options, flags):
        self._debug("_initialize_parameters", "started")

        # initialization of module parameters (options, flags)
        self.o_url = options["url"].strip() + "?"
        self.o_layers = options["layers"].strip()
        self.o_output = options["output"]

        self.o_wds_version = options["wfs_version"]
        self.projection_name = "SRSNAME"

        self.o_wfs_version = options["wfs_version"]

        self.o_urlparams = options["urlparams"].strip()

        self.o_srs = int(options["srs"])
        if self.o_srs <= 0:
            grass.fatal(_("Invalid EPSG code %d") % self.o_srs)

        try:
            self.o_maximum_features = int(options["maximum_features"])
            if int(options["maximum_features"]) < 1:
                grass.fatal(_("Invalid maximum number of features (must be >1)"))
        except ValueError:
            self.o_maximum_features = None

        # read projection info
        self.proj_location = grass.read_command("g.proj", flags="jf").rstrip("\n")

        self.proj_srs = grass.read_command(
            "g.proj", flags="jf", epsg=str(self.o_srs)
        ).rstrip("\n")

        if not self.proj_srs or not self.proj_location:
            grass.fatal(_("Unable to get projection info"))

        # set region
        self.o_region = options["region"]
        if self.o_region:
            if not grass.find_file(name=self.o_region, element="windows", mapset=".")[
                "name"
            ]:
                grass.fatal(_("Region <%s> not found") % self.o_region)

        if self.o_region:
            s = grass.read_command(
                "g.region", quiet=True, flags="ug", region=self.o_region
            )
            self.region = grass.parse_key_val(s, val_type=float)
        else:
            self.region = grass.region()

        self.ogr_drv_format = "ESRI Shapefile"
        self._debug("_initialize_parameters", "finished")
Ejemplo n.º 40
0
def cleanup():
    grass.verbose("Cleaning up ...")
    if tmp:
        grass.try_remove(tmp)
    if tmp_proj:
        grass.try_remove(tmp_proj)
    if tmp_gpx:
        grass.try_remove(tmp_gpx)

    # only try to remove map if it exists to avoid ugly warnings
    if tmp_vogb:
        if grass.find_file(tmp_vogb, element="vector")["name"]:
            grass.run_command(
                "g.remove", flags="f", type="vector", name=tmp_vogb, quiet=True
            )
    if tmp_extr:
        if grass.find_file(tmp_extr, element="vector")["name"]:
            grass.run_command(
                "g.remove", flags="f", type="vector", name=tmp_vogb, quiet=True
            )
Ejemplo n.º 41
0
    def _initializeParameters(self, options, flags):
        self._debug("_initialize_parameters", "started")

        # initialization of module parameters (options, flags)
        self.o_url = options['url'].strip() + "?"
        self.o_layers = options['layers'].strip()
        self.o_output = options['output']

        self.o_wds_version = options['wfs_version']
        self.projection_name = "SRSNAME"

        self.o_wfs_version = options['wfs_version']

        self.o_urlparams = options['urlparams'].strip()

        self.o_srs = int(options['srs'])
        if self.o_srs <= 0:
            grass.fatal(_("Invalid EPSG code %d") % self.o_srs)

        try:
            self.o_maximum_features = int(options['maximum_features'])
            if int(options['maximum_features']) < 1:
                grass.fatal(_('Invalid maximum number of features (must be >1)'))
        except ValueError:
            self.o_maximum_features = None

        # read projection info
        self.proj_location = grass.read_command('g.proj',
                                                flags ='jf').rstrip('\n')

        self.proj_srs = grass.read_command('g.proj',
                                           flags = 'jf',
                                           epsg = str(self.o_srs)).rstrip('\n')

        if not self.proj_srs or not self.proj_location:
            grass.fatal(_("Unable to get projection info"))

        # set region
        self.o_region = options['region']
        if self.o_region:
            if not grass.find_file(name = self.o_region, element = 'windows', mapset = '.')['name']:
                grass.fatal(_("Region <%s> not found") % self.o_region)

        if self.o_region:
            s = grass.read_command('g.region',
                                   quiet = True,
                                   flags = 'ug',
                                   region = self.o_region)
            self.region = grass.parse_key_val(s, val_type = float)
        else:
            self.region = grass.region()

        self.ogr_drv_format = "ESRI Shapefile"
        self._debug("_initialize_parameters", "finished")
Ejemplo n.º 42
0
    def SetSecondRaster(self, name):
        """Set raster map to second Map"""
        if name:
            raster = grass.find_file(name=name, element='cell')
            if raster.get('fullname'):
                self.rasters['second'] = raster['fullname']
                self.SetLayer(name=raster['fullname'],
                              mapInstance=self.GetSecondMap())
                return True

        return False
Ejemplo n.º 43
0
def main():
    options, flags = gscript.parser()

    import wx

    from grass.script.setup import set_gui_path

    set_gui_path()

    from core.settings import UserSettings
    from core.giface import StandaloneGrassInterface
    from core import globalvar
    from mapswipe.frame import SwipeMapDisplay

    driver = UserSettings.Get(group="display", key="driver", subkey="type")
    if driver == "png":
        os.environ["GRASS_RENDER_IMMEDIATE"] = "png"
    else:
        os.environ["GRASS_RENDER_IMMEDIATE"] = "cairo"

    first = options["first"]
    second = options["second"]
    mode = options["mode"]

    for mapName in [first, second]:
        if mapName:
            gfile = gscript.find_file(name=mapName)
            if not gfile["name"]:
                gscript.fatal(_("Raster map <%s> not found") % mapName)

    app = wx.App()

    # show main frame
    frame = wx.Frame(
        parent=None,
        size=globalvar.MAP_WINDOW_SIZE,
        title=_("Map Swipe Tool - GRASS GIS"),
    )
    frame = SwipeMapDisplay(
        parent=frame,
        giface=StandaloneGrassInterface(),
    )

    if first:
        frame.SetFirstRaster(first)
    if second:
        frame.SetSecondRaster(second)
    if first or second:
        frame.SetRasterNames()

    frame.SetViewMode(mode)
    frame.Show()

    app.MainLoop()
Ejemplo n.º 44
0
def main():
    global output, tmp

    input = options['input']
    output = options['output']
    layer = options['layer']
    column = options['column']

    # setup temporary file
    tmp = str(os.getpid())

    # does map exist?
    if not grass.find_file(input, element='vector')['file']:
        grass.fatal(_("Vector map <%s> not found") % input)

    if not column:
        grass.warning(
            _("No '%s' option specified. Dissolving based on category values from layer <%s>.") %
            ("column", layer))
        grass.run_command('v.extract', flags='d', input=input,
                          output=output, type='area', layer=layer)
    else:
        if int(layer) == -1:
            grass.warning(_("Invalid layer number (%d). "
                            "Parameter '%s' specified, assuming layer '1'.") %
                          (int(layer), 'column'))
            layer = '1'
        try:
            coltype = grass.vector_columns(input, layer)[column]
        except KeyError:
            grass.fatal(_('Column <%s> not found') % column)

        if coltype['type'] not in ('INTEGER', 'SMALLINT', 'CHARACTER', 'TEXT'):
            grass.fatal(_("Key column must be of type integer or string"))

        f = grass.vector_layer_db(input, layer)

        table = f['table']

        tmpfile = '%s_%s' % (output, tmp)

        try:
            grass.run_command('v.reclass', input=input, output=tmpfile,
                              layer=layer, column=column)
            grass.run_command('v.extract', flags='d', input=tmpfile,
                              output=output, type='area', layer=layer)
        except CalledModuleError as e:
            grass.fatal(_("Final extraction steps failed."
                          " Check above error messages and"
                          " see following details:\n%s") % e)

    # write cmd history:
    grass.vector_history(output)
Ejemplo n.º 45
0
def find_existing_band(band):
    """
    Check if band exists in the current mapset

    Parameter "element": 'raster', 'raster_3d', 'vector'
    """
    result = grass.find_file(name=band, element='cell', mapset='.')
    if result['file']:
        # grass.verbose(_("Band {band} exists".format(band=band)))
        return True
    else:
        return False
Ejemplo n.º 46
0
def cleanup():
    """
    Clean up temporary maps
    """
    grass.run_command('g.remove',
                      flags='f',
                      type="rast",
                      pattern='tmp.{pid}*'.format(pid=os.getpid()),
                      quiet=True)

    if grass.find_file(name='MASK', element='cell')['file']:
        r.mask(flags='r', verbose=True)
Ejemplo n.º 47
0
def add_column_names_cat(map_name, vect_name, layer):
    tmp = raster.RasterRow(map_name)
    tmp.has_cats()
    if(tmp.num_cats()>0):
        col_names = []
        col_master_name = grass.find_file(name = map_name, element = 'cell')['name']
        for i in range(len(tmp.cats)):
            col_names.append(col_master_name + "_" + str(tmp.cats[i][1]))
        master_string = " double precision,".join(col_names) + " double precision"
        Module('v.db.addcolumn', map=vect_name, columns=master_string, layer = layer)
    else:
        grass.fatal("Map <%s> does not have layer number" % map_name)
Ejemplo n.º 48
0
def cleanup():
    nuldev = open(os.devnull, 'w')
    kwargs = {
        'flags': 'f',
        'quiet': True,
        'stderr': nuldev
    }
    for rmr in rm_regions:
        if rmr in [x for x in grass.parse_command('g.list', type='region')]:
            grass.run_command(
                'g.remove', type='region', name=rmr, **kwargs)
    for rmv in rm_vectors:
        if grass.find_file(name=rmv, element='vector')['file']:
            grass.run_command(
                'g.remove', type='vector', name=rmv, **kwargs)
    for rmrast in rm_rasters:
        if grass.find_file(name=rmrast, element='raster')['file']:
            grass.run_command(
                'g.remove', type='raster', name=rmrast, **kwargs)
    if tmpfolder:
        grass.try_rmdir(os.path.join(tmpfolder))
Ejemplo n.º 49
0
def cleanup():
    if temporary_vect:
        if gscript.find_file(temporary_vect, element="vector")["name"]:
            gscript.run_command("g.remove",
                                flags="f",
                                type_="vector",
                                name=temporary_vect,
                                quiet=True)
        if gscript.db_table_exist(temporary_vect):
            gscript.run_command("db.execute",
                                sql="DROP TABLE %s" % temporary_vect,
                                quiet=True)
Ejemplo n.º 50
0
def cleanup():
    """Remove temporary maps specified in the global list"""
    for rast in CLEAN_RAST:
        cf = gs.find_file(name=rast,
                          element="cell",
                          mapset=gs.gisenv()["MAPSET"])
        if cf["fullname"] != "":
            gs.run_command("g.remove",
                           type="raster",
                           name=rast,
                           quiet=True,
                           flags="f")
Ejemplo n.º 51
0
def main():
    # Input data
    inraster = options['input']
    outraster = options['output']
    nsize = options['nsize']
    statistic = options['statistic']
    circular = "c" if flags['c'] else ""

    # Get process id
    pid = os.getpid()

    # Check overwrite settings
    # If output raster file exists, but overwrite option isn't selected
    if not grass.overwrite():
        if grass.find_file(outraster)['name']:
            grass.message(
                _("Output raster map <%s> already exists") % outraster)
            sys.exit()

    # Choose the statistic
    if statistic == "Deviation from Mean":

        # First, get neighbourhood mean rasters
        tmp_avg = "tmp_avg_%d" % pid  # Create a temporary filename
        tmp_rlayers.append(tmp_avg)
        proc_avg = grass.start_command('r.neighbors',
                                       overwrite=True,
                                       flags=circular,
                                       input=inraster,
                                       output=tmp_avg,
                                       size=nsize)

        # Get neighbourhood standard deviation rasters
        tmp_stddev = "tmp_stddev_%d" % pid  # Create a temporary filename
        tmp_rlayers.append(tmp_stddev)
        proc_stddev = grass.start_command('r.neighbors',
                                          overwrite=True,
                                          flags=circular,
                                          method="stddev",
                                          input=inraster,
                                          output=tmp_stddev,
                                          size=nsize)

        # Wait for the processes to finish
        proc_avg.wait()
        proc_stddev.wait()

        # Calculate Deviation from Mean
        grass.mapcalc("$outmap = ($inraster - $avgraster) / $stddevraster",
                      outmap=outraster,
                      inraster=inraster,
                      avgraster=tmp_avg,
                      stddevraster=tmp_stddev)
Ejemplo n.º 52
0
def cleanup():
    if temporary_vect:
        if gscript.find_file(temporary_vect, element='vector')['name']:
            gscript.run_command('g.remove',
                                flags='f',
                                type_='vector',
                                name=temporary_vect,
                                quiet=True)
        if gscript.db_table_exist(temporary_vect):
            gscript.run_command('db.execute',
                                sql='DROP TABLE %s' % temporary_vect,
                                quiet=True)
Ejemplo n.º 53
0
    def __del__(self):
        # removes temporary mask, used for import transparent or warped temp_map
        if self.cleanup_mask:
            # clear temporary mask, which was set by module
            try:
                grass.run_command('r.mask', quiet=True, flags='r')
            except CalledModuleError:
                grass.fatal(_('%s failed') % 'r.mask')

            # restore original mask, if exists
            if grass.find_file(self.opt_output + self.original_mask_suffix,
                               element='cell',
                               mapset='.')['name']:
                try:
                    mask_copy = self.opt_output + self.original_mask_suffix
                    grass.run_command('g.copy',
                                      quiet=True,
                                      raster=mask_copy + ',MASK')
                except CalledModuleError:
                    grass.fatal(_('%s failed') % 'g.copy')

        # remove temporary created rasters
        if self.cleanup_layers:
            maps = []
            for suffix in ('.red', '.green', '.blue', '.alpha',
                           self.original_mask_suffix):
                rast = self.opt_output + suffix
                if grass.find_file(rast, element='cell', mapset='.')['file']:
                    maps.append(rast)

            if maps:
                grass.run_command('g.remove',
                                  quiet=True,
                                  flags='fb',
                                  type='raster',
                                  name=','.join(maps))

        # delete environmental variable which overrides region
        if 'GRASS_REGION' in os.environ.keys():
            os.environ.pop('GRASS_REGION')
def fertility_maintenance(opts, flgs):

    energy_tops_hf = float(opts['energy_tops_hf'])
    energy_cormometric_vol_hf = float(opts['energy_cormometric_vol_hf'])
    management = opts['management']
    treatment = opts['treatment']

    yield_pix_process(opts, flgs, yield_, yield_surface)

    expr_prodFF = 'site_prod_bioenergyFF = if((' + management + '==1 || ' + management + '==2) && (' + treatment + '==1 || ' + treatment + '==99999), ' + opts[
        'energy_map'] + '*0.9)'
    expr_prodT = 'site_prod_bioenergyT = if(' + treatment + '==2 && (' + opts[
        'soilp_map'] + '==1 || ' + opts[
            'soilp_map'] + '==2), analysis_surface*yield_pix*%f*0+yield_pix*%f, if(' + treatment + '==2 && ' + opts[
                'soilp_map'] + '>2, analysis_surface*yield_pix*%f*0.7+yield_pix*%f))'
    # Fertility maintenance
    run_command("r.mapcalc", overwrite=ow, expression=expr_prodFF)
    run_command("r.mapcalc",
                overwrite=ow,
                expression=expr_prodT %
                (energy_tops_hf, energy_cormometric_vol_hf, energy_tops_hf,
                 energy_cormometric_vol_hf))

    listmapsite = ''
    map_site_prod_bioenergyT = grass.find_file('site_prod_bioenergyT',
                                               element='cell')
    map_site_prod_bioenergyFF = grass.find_file('site_prod_bioenergyFF',
                                                element='cell')

    if map_site_prod_bioenergyT['fullname'] != '':
        listmapsite += map_site_prod_bioenergyT['fullname']
        if map_site_prod_bioenergyFF['fullname'] != '':
            listmapsite += "," + map_site_prod_bioenergyFF['fullname']
    else:
        if map_site_prod_bioenergyFF['fullname'] != '':
            listmapsite += map_site_prod_bioenergyFF['fullname']

    run_command("r.mapcalc",
                overwrite=ow,
                expression=opts['output_fert_map'] + '= max(%s)' % listmapsite)
Ejemplo n.º 55
0
def cleanup():
    grass.message("Deleting intermediate files...")

    for k, v in TMP_RAST.items():
        for f in v:
            if len(grass.find_file(f)['fullname']) > 0:
                grass.run_command("g.remove",
                                  type="raster",
                                  name=f,
                                  flags="f",
                                  quiet=True)

    Region.write(current_region)
Ejemplo n.º 56
0
def check_daily_map_names(basename, mapset, start_day, end_day, day_step):
    """
    Check if maps exist with name(s) identical to the scripts intented outputs
    """
    if not basename:
        return
    for day in range(start_day, end_day + 1, day_step):
        map_ = '{base}_{day}'.format(base=basename, day=format_order(day))
        if grass.find_file(map_, element='cell', mapset=mapset)['file']:
            grass.fatal(
                _('Raster map <{name}> already exists. '
                  'Change the base name or allow overwrite.'
                  ''.format(name=map_)))
Ejemplo n.º 57
0
def cleanup():
    """Remove temporary maps specified in the global list"""
    cleanrast = list(reversed(CLEAN_LAY))
    for rast in cleanrast:
        ffile = gs.find_file(name=rast,
                             element="cell",
                             mapset=gs.gisenv()["MAPSET"])
        if ffile["file"]:
            gs.run_command("g.remove",
                           flags="f",
                           type="raster",
                           name=rast,
                           quiet=True)
Ejemplo n.º 58
0
def read_data(raster, n, flag_s, seed):
    """Read in the raster layers as a numpy array."""
    gs.message("Reading in the data ...")
    if n:
        # Create mask random locations
        new_mask = tmpname("rvif")
        if flag_s:
            gs.run_command(
                "r.random",
                input=raster[0],
                flags="s",
                npoints=n,
                raster=new_mask,
                quiet=True,
            )
        else:
            gs.run_command(
                "r.random",
                input=raster[0],
                seed=seed,
                npoints=n,
                raster=new_mask,
                quiet=True,
            )
        exist_mask = gs.find_file(name="MASK",
                                  element="cell",
                                  mapset=gs.gisenv()["MAPSET"])
        if exist_mask["fullname"]:
            mask_backup = tmpname("rvifoldmask")
            gs.run_command("g.rename",
                           raster=["MASK", mask_backup],
                           quiet=True)
        gs.run_command("r.mask", raster=new_mask, quiet=True)

    # Get the raster values at sample points
    tmpcov = StringIO(
        gs.read_command("r.stats",
                        flags="1n",
                        input=raster,
                        quiet=True,
                        separator="comma").rstrip("\n"))
    p = np.loadtxt(tmpcov, skiprows=0, delimiter=",")

    if n:
        gs.run_command("r.mask", flags="r", quiet=True)
        if exist_mask["fullname"]:
            gs.run_command("g.rename",
                           raster=[mask_backup, "MASK"],
                           quiet=True)
    return p
Ejemplo n.º 59
0
def main():
    sys.path.insert(1, os.path.join(os.path.dirname(sys.path[0]), 'etc', 'v.surf.nnbathy'))
    try:
        from nnbathy import Nnbathy_raster
    except ImportError:
        grass.fatal("r.surf.nnbathy requires 'v.surf.nnbathy'. "
                    "Please install this module by running:\ng.extension v.surf.nnbathy")

    if not grass.find_file(options['input'], element='cell')['fullname']:
        grass.fatal("Raster map <%s> not found" % options['input'])
    
    obj = Nnbathy_raster(options)
    obj.compute()
    obj.create_output()
Ejemplo n.º 60
0
def main():
    options, flags = gs.parser()

    vector = options["input"]
    layer = 1
    raster = options["output"]
    method = options["method"]
    z = 3
    sep = "pipe"
    out_args = {}

    if not gs.find_file(vector, element="vector")["fullname"]:
        gs.fatal("Vector map <{0}> not found".format(vector))

    if options["column"]:
        z = 4
        out_args["column"] = options["column"]
        out_args["where"] = "{0} IS NOT NULL".format(options["column"])

        columns = gs.vector_columns(vector)

        if options["column"] not in columns:
            gs.fatal(_("Column <{0}> not found".format(options["column"])))
        if columns[options["column"]]["type"] not in ("INTEGER",
                                                      "DOUBLE PRECISION"):
            gs.fatal(_("Column <{0}> is not numeric".format(
                options["column"])))

    out_process = gs.pipe_command(
        "v.out.ascii",
        input=vector,
        layer=layer,
        format="point",
        separator=sep,
        flags="r",
        **out_args,
    )
    in_process = gs.start_command(
        "r.in.xyz",
        input="-",
        output=raster,
        method=method,
        z=z,
        separator=sep,
        stdin=out_process.stdout,
    )
    in_process.communicate()
    out_process.wait()

    return 0