Esempio n. 1
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)
Esempio n. 2
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()
Esempio n. 3
0
def main():
    options, flags = gscript.parser()

    import wx

    from grass.script.setup import set_gui_path
    set_gui_path()
    
    try:
        from timeline.frame import TimelineFrame
    except ImportError as e:
        # TODO: why do we need this special check here, the reason of error
        # is wrong intallation or something, no need to report this to the
        # user in a nice way
        gscript.fatal(e.message)

    datasets = options['inputs'].strip().split(',')
    datasets = [data for data in datasets if data]
    view3d = flags['3']

    app = wx.App()
    frame = TimelineFrame(None)
    frame.SetDatasets(datasets)
    frame.Show3D(view3d)
    frame.Show()
    app.MainLoop()
Esempio n. 4
0
def main():
    """
    Compute cell areas
    """
    
    projinfo = grass.parse_command('g.proj', flags='g')
    
    options, flags = grass.parser()
    output = options['output']
    units = options['units']
    
    # First check if output exists
    if len(grass.parse_command('g.list', type='rast', 
                               pattern=options['output'])):
        if not grass.overwrite():
            grass.fatal("Raster map '" + options['output'] + 
                        "' already exists. Use '--o' to overwrite.")

    # Then compute
    if projinfo['units'] == 'meters':
        if units == 'm2':
            grass.mapcalc(output+' = nsres() * ewres()')
        elif units == 'km2':
            grass.mapcalc(output+' = nsres() * ewres() / 10.^6')
    elif projinfo['units'] == 'degrees':
        if units == 'm2':
            grass.mapcalc(output+' = ( 111195. * nsres() ) * \
                          ( ewres() * '+str(np.pi/180.)+' * 6371000. * cos(y()) )')
        elif units == 'km2':
            grass.mapcalc(output+' = ( 111.195 * nsres() ) * \
                          ( ewres() * '+str(np.pi/180.)+' * 6371. * cos(y()) )')
    else:
        print 'Units: ', + projinfo['units'] + ' not currently supported'
Esempio n. 5
0
def main():
    """Sets the GRASS display driver

    .. todo::
        use command line options as an alternative to wizard
    """
    options, flags = gscript.parser()

    import wx

    from grass.script.setup import set_gui_path

    set_gui_path()

    from core.settings import UserSettings
    from core.globalvar import CheckWxVersion
    from core.giface import StandaloneGrassInterface
    from gcp.manager import GCPWizard

    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"

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

    wizard = GCPWizard(parent=None, giface=StandaloneGrassInterface())

    app.MainLoop()
Esempio n. 6
0
def main():
    options, flags = grass.parser()
    satellite = options['satellite']
    output_basename = options['basename']
    inputs = options['input'].split(',')
    num_of_bands = 6
    if len(inputs) != num_of_bands:
        grass.fatal(_("The number of input raster maps (bands) should be %s") % num_of_bands)

    # this is here just for the compatibility with r.mapcalc expression
    # remove this if not really needed in new implementation
    bands = {}
    for i, band in enumerate(inputs):
        band_num = i + 1
        if band_num == 6:
            band_num = 7
        bands['band' + str(band_num)] = band
    print bands

    if satellite == 'landsat4_tm':
        calcN(output_basename, bands, 0, 4)
    elif satellite == 'landsat5_tm':
        calcN(output_basename, bands, 1, 5)
    elif satellite == 'landsat7_etm':
        calcN(output_basename, bands, 2, 7)
    elif satellite == 'modis':
        calcN(output_basename, bands, 3, 7)
    else:
        raise RuntimeError("Invalid satellite: " + satellite)

    grass.message(_("Tasseled Cap components calculated"))
Esempio n. 7
0
def main():
    """Sets the GRASS 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'

    # TODO: message format should not be GUI
    # TODO: should messages here be translatable?
    # (for test its great, for translator not)

    options, flags = grass.parser()
    test = options['test']

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

    map_ = Map()

    if options['raster']:
        names = options['raster']
        for name in names.split(','):
            cmdlist = ['d.rast', 'map=%s' % name]
            map_.AddLayer(ltype='raster', command=cmdlist, active=True,
                          name=name, hidden=False, opacity=1.0,
                          render=True)
    if options['vector']:
        names = options['vector']
        for name in names.split(','):
            cmdlist = ['d.vect', 'map=%s' % name]
            map_.AddLayer(ltype='vector', command=cmdlist, active=True,
                          name=name, hidden=False, opacity=1.0,
                          render=True)

    giface = MapdispGrassInterface(map_=map_)
    tester = Tester()

    if test == 'mapwindow':
        tester.testMapWindow(giface, map_)
    elif test == 'mapdisplay':
        tester.testMapDisplay(giface, map_)
    elif test == 'apitest':
        tester.testMapWindowApi(giface, map_)
    elif test == 'distance':
        tester.testMapWindowDistance(giface, map_)
    elif test == 'profile':
        tester.testMapWindowProfile(giface, map_)
    elif test == 'rlisetup':
        tester.testMapWindowRlisetup(map_)
    else:
        # TODO: this should not happen but happens
        import grass.script as sgrass
        sgrass.fatal(_("Unknown value %s of test parameter." % test))

    app.MainLoop()
Esempio n. 8
0
def main():
    options, flags = gscript.parser()
    araster = options['araster']
    braster = options['braster']
    output = options['output']

    gscript.mapcalc('{r} = {a} + {b}'.format(r=output, a=araster, b=braster))

    return 0
Esempio n. 9
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 core.giface import StandaloneGrassInterface
    try:
        from tplot.frame import TplotFrame
    except ImportError as e:
        gscript.fatal(e.message)
    rasters = None
    if options['strds']:
        rasters = options['strds'].strip().split(',')
    coords = None
    if options['coordinates']:
        coords = options['coordinates'].strip().split(',')
    cats = None
    if options['cats']:
        cats = options['cats']
    output = options['output']
    vectors = None
    attr = None
    if options['stvds']:
        vectors = options['stvds'].strip().split(',')
        if not options['attr']:
            gscript.fatal(_("With stvds you have to set 'attr' option"))
        else:
            attr = options['attr']
        if coords and cats:
            gscript.fatal(_("With stvds it is not possible to use 'coordinates' "
                            "and 'cats' options together"))
        elif not coords and not cats:
            gscript.warning(_("With stvds you have to use 'coordinates' or "
                              "'cats' option"))
    app = wx.App()
    frame = TplotFrame(parent=None, giface=StandaloneGrassInterface())
    frame.SetDatasets(rasters, vectors, coords, cats, attr)
    if output:
        frame.OnRedraw()
        if options['size']:
            sizes = options['size'].strip().split(',')
            sizes = [int(s) for s in sizes]
            frame.canvas.SetSize(sizes)
        if output.split('.')[-1].lower() == 'png':
            frame.canvas.print_png(output)
        if output.split('.')[-1].lower() in ['jpg', 'jpeg']:
            frame.canvas.print_jpg(output)
        if output.split('.')[-1].lower() in ['tif', 'tiff']:
            frame.canvas.print_tif(output)
    else:
        frame.Show()
        app.MainLoop()
Esempio n. 10
0
def main():
    gscript.parser()

    import wx

    from grass.script.setup import set_gui_path
    set_gui_path()

    from core.giface import StandaloneGrassInterface
    from core.globalvar import CheckWxVersion
    from rlisetup.frame import RLiSetupFrame

    app = wx.App()
    if not CheckWxVersion([2, 9]):
        wx.InitAllImageHandlers()
    frame = RLiSetupFrame(parent=None, giface=StandaloneGrassInterface())
    frame.Show()
    frame.CenterOnScreen()

    app.MainLoop()
Esempio n. 11
0
def main():
    single_command = preparse_exec()
    options, flags = gscript.parser()

    script_path = options['grass_script']
    # TODO: read script from stdin

    # TODO: support creating grassdata in a tmp place
    remote_grassdata = options['grassdata']
    remote_location = options['location']
    remote_mapset = options['mapset']

    raster_inputs = as_list(options['raster_input'])
    raster_outputs = as_list(options['raster_output'])
    vector_inputs = as_list(options['vector_input'])
    vector_outputs = as_list(options['vector_output'])

    grass_version = version_to_number(options['grass_version'])

    session = get_session(options)

    # TODO: use variable, e.g. for packing
    if options['local_workdir']:
        local_workdir = options['local_workdir']
    else:
        # TODO: this should be tmp
        local_workdir = '.'

    from grasssession import GrassSession
    # TODO: default grass binary should be derived from the version we are running
    gsession = GrassSession(connection=session, grassdata=remote_grassdata,
                            location=remote_location, mapset=remote_mapset,
                            grass_command=options['grass_command'],
                            grass_version=grass_version,
                            directory=options['remote_workdir'])
    if flags['l']:
        gsession.create_location()
    gsession.put_region()
    gsession.put_rasters(raster_inputs)
    gsession.put_vectors(vector_inputs)
    if script_path:
        gsession.run_script(script_path)
    elif single_command:
        gsession.run_bash_command(single_command)
    # TODO: add also Python code as an input
    gsession.get_rasters(raster_outputs)
    gsession.get_vectors(vector_outputs)
    gsession.close()
Esempio n. 12
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.globalvar import CheckWxVersion
    from core.giface import StandaloneGrassInterface
    from core.utils import _
    from mapswipe.frame import SwipeMapFrame

    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()
    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()
Esempio n. 13
0
def main():
    options, flags = gscript.parser()

    # import wx only after running parser
    # to avoid issues when only interface is needed
    import wx
    
    from grass.script.setup import set_gui_path
    set_gui_path()
    
    from core.giface import StandaloneGrassInterface
    from datacatalog.frame import DataCatalogFrame

    app = wx.App()

    frame = DataCatalogFrame(parent=None, giface=StandaloneGrassInterface())
    frame.CentreOnScreen()
    frame.Show()
    app.MainLoop()
def main():
    options, flags = gs.parser()

    # main options
    map_name = options['input']
    output_file = options['output']
    # TODO: other options of g.proj are not supported
    epsg_code = int(options['epsg'])
    # r.out.png options
    compression = int(options['compression'])
    # both flags (tw) passed to r.out.png
    routpng_flags = ''
    if flags['t']:
        routpng_flags += 't'
    if flags['w']:
        routpng_flags += 'w'
    if flags['l']:
        wgs84_file = output_file + '.wgs84'
    else:
        wgs84_file = None

    if flags['m']:
        use_region = False
    else:
        use_region = True

    # TODO: mixing current and map's mapset at this point
    # or perhaps not an issue if parser adds mapset automatically (?)
    if '@' in map_name:
        map_name, src_mapset_name = map_name.split('@')
    else:
        src_mapset_name = gs.gisenv()['MAPSET']

    export_png_in_projection(map_name=map_name,
                             src_mapset_name=src_mapset_name,
                             output_file=output_file,
                             epsg_code=epsg_code,
                             compression=compression,
                             routpng_flags=routpng_flags,
                             wgs84_file=wgs84_file,
                             use_region=use_region)
Esempio n. 15
0
def main():
    options, flags = gscript.parser()

    import wx
    
    from grass.script.setup import set_gui_path
    set_gui_path()
    
    from core.giface import StandaloneGrassInterface
    from core.globalvar import CheckWxVersion
    from gmodeler.frame import ModelFrame

    app = wx.App()
    if not CheckWxVersion([2, 9]):
        wx.InitAllImageHandlers()
    frame = ModelFrame(parent=None, giface=StandaloneGrassInterface())
    if options['file']:
        frame.LoadModelFile(options['file'])
    frame.Show()

    app.MainLoop()
Esempio n. 16
0
def main():
    options, flags = gscript.parser()

    import wx
    
    from grass.script.setup import set_gui_path
    set_gui_path()
    
    from core.globalvar import CheckWxVersion
    from psmap.frame import PsMapFrame

    app = wx.App()
    if not CheckWxVersion([2, 9]):
        wx.InitAllImageHandlers()
    frame = PsMapFrame(parent=None)
    frame.Show()

    if options['file']:
        frame.LoadFile(options['file'])

    app.MainLoop()
Esempio n. 17
0
def loadDefs():
    if '--ui' in sys.argv: sys.argv.remove('--ui')
    # get names of module parameters
    options, flags = grass.parser()
    # get default values for the arguments
    defoptions = p.__dict__
    defoptions.update(p.readPar())
    
    defflags = []
    switches = dict(zip(components.values(),components.keys()))
    # update options
    for a in defoptions:
        # parameter in header and not already set
        if a in options and options[a]=='':
            options[a] = defoptions[a]
        # check flags
        if a in switches and (defoptions[a] != 0 or (a in flags and flags[a])):
            defflags += [switches[a]]
    
    # recreate commandline arguments
    sys.argv += ['-%s' %''.join(defflags)]
    sys.argv += ['%s=%s' %s for s in options.items()]
    sys.argv += ['--ui']
    return
Esempio n. 18
0
def main():
    options, flags = grass.parser()
    satellite = options['sensor']
    output_basename = options['output']
    inputs = options['input'].split(',')
    num_of_bands = used_bands[satellites.index(satellite)]
    if len(inputs) != num_of_bands:
        grass.fatal(_("The number of input raster maps (bands) should be %s") % num_of_bands)

    bands = {}
    for i, band in enumerate(inputs):
        band_num = i + 1
        bands['in' + str(band_num) + 'band'] = band
    grass.debug(1, bands)

    # core tasseled cap components computation
    calcN(output_basename, bands, satellite)

    # assign "Data Description" field in all four component maps
    for i, comp in enumerate(names):
        grass.run_command('r.support', map="%s.%d" % (output_basename, i + 1),
                          description="Tasseled Cap %d: %s" % (i + 1, comp))

    grass.message(_("Tasseled Cap components calculated"))
Esempio n. 19
0
        else:
            end = start_time + int(gran)
            granule.set_relative_time(start, end,  sp.get_relative_time_unit())
        start_time = end
        
        granularity_list.append(granule)

    output_list = tgis.aggregate_by_topology(granularity_list=granularity_list,  granularity=gran,  
                                                                       map_list=map_list,  
                                                                       topo_list=topo_list,  basename=base, time_suffix=time_suffix,
                                                                       offset=offset,  method=method,  nprocs=nprocs,  spatial=None, 
                                                                       overwrite=gcore.overwrite())

    if output_list:
        temporal_type, semantic_type, title, description = sp.get_initial_values()
        output_strds = tgis.open_new_stds(output, "strds", temporal_type,
                                                                 title, description, semantic_type,
                                                                 dbif, gcore.overwrite())
        tgis.register_map_object_list("rast", output_list,  output_strds,  register_null,  
                                                       sp.get_relative_time_unit(),  dbif)

        # Update the raster metadata table entries with aggregation type
        output_strds.set_aggregation_type(method)
        output_strds.metadata.update(dbif)

    dbif.close()

if __name__ == "__main__":
    options, flags = gcore.parser()
    main()
Esempio n. 20
0
            if dtypes[c] in [float, int]:
                dtypes[c] = float
                tbl[c][i] = 'nan'
        # actual type conversion
        convertedvals += [np.array(tbl[c], dtype=dtypes[c])]
    # now properly make it
    tbl = np.array(zip(*convertedvals), dtype=[(c, dtypes[c]) for c in cols])
    tbl.sort()
    return tbl


if __name__ == '__main__':
    # start time
    st = dt.datetime.now()
    # get options and flags
    o, f = grass.parser()
    fmt = lambda d: '\n'.join(['%s: %s' % (k, v) for k, v in d.items()])+'\n'
    grass.message('GIS Environment:\n'+fmt(grass.gisenv()))
    grass.message('Parameters:\n'+fmt(o)+fmt(f))

    # warn if MASKED
    if 'MASK' in grass.list_grouped('rast')[grass.gisenv()['MAPSET']]:
        maskcells = gread('r.stats', input='MASK', flags='nc').split()[1]
        grass.message('!!! MASK active with %s cells, will only process those !!!'
                      % maskcells)

    # send all to main
    keywords = o
    keywords.update(f)
    main = main(**keywords)
Esempio n. 21
0
def main():
    options, flags = gscript.parser()

    # import wx only after running parser
    # to avoid issues when only interface is needed
    import grass.temporal as tgis
    import wx

    from grass.script.setup import set_gui_path
    set_gui_path()

    from core.globalvar import CheckWxVersion
    from core.utils import _
    from core.giface import StandaloneGrassInterface
    from core.layerlist import LayerList
    from animation.frame import AnimationFrame, MAX_COUNT
    from animation.data import AnimLayer

    rast = options['raster']
    vect = options['vector']
    strds = options['strds']
    stvds = options['stvds']

    numInputs = 0

    if rast:
        numInputs += 1
    if vect:
        numInputs += 1
    if strds:
        numInputs += 1
    if stvds:
        numInputs += 1

    if numInputs > 1:
        gscript.fatal(
            _("%s=, %s=, %s= and %s= are mutually exclusive.") %
            ("raster", "vector", "strds", "stvds"))

    if numInputs > 0:
        # We need to initialize the temporal framework in case
        # a space time dataset was set on the command line so that
        # the AnimLayer() class works correctly
        tgis.init()

    layerList = LayerList()
    if rast:
        layer = AnimLayer()
        layer.mapType = 'raster'
        layer.name = rast
        layer.cmd = ['d.rast', 'map={name}'.format(name=rast.split(',')[0])]
        layerList.AddLayer(layer)
    if vect:
        layer = AnimLayer()
        layer.mapType = 'vector'
        layer.name = vect
        layer.cmd = ['d.vect', 'map={name=}'.format(name=vect.split(',')[0])]
        layerList.AddLayer(layer)
    if strds:
        layer = AnimLayer()
        layer.mapType = 'strds'
        layer.name = strds
        layer.cmd = ['d.rast', 'map=']
        layerList.AddLayer(layer)
    if stvds:
        layer = AnimLayer()
        layer.mapType = 'stvds'
        layer.name = stvds
        layer.cmd = ['d.vect', 'map=']
        layerList.AddLayer(layer)

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

    frame = AnimationFrame(parent=None, giface=StandaloneGrassInterface())
    frame.CentreOnScreen()
    frame.Show()
    if len(layerList) >= 1:
        # CallAfter added since it was crashing with wxPython 3 gtk
        wx.CallAfter(frame.SetAnimations,
                     [layerList] + [None] * (MAX_COUNT - 1))
    app.MainLoop()
Esempio n. 22
0
        # Write layer metadata
        gs.run_command("r.support",
                       map=mod4,
                       title="Number of layers with negative values",
                       units="-",
                       source1="Based on {}".format(opc),
                       description="Number of layers with negative values",
                       loadhistory=tmphist)

    # Remove IES layers
    if fli:
        gs.run_command("g.remove",
                       quiet=True,
                       flags="f",
                       type="raster",
                       name=ipi)
    # Clean up tmp file
    os.remove(tmphist)

    gs.message(_("Finished ...\n"))
    if region_1 != region_2:
        gs.message(
            _("\nPlease note that the region has been changes to match"
              " the set of projection (env_proj) variables.\n"))


if __name__ == "__main__":
    atexit.register(cleanup)
    sys.exit(main(*gs.parser()))
Esempio n. 23
0
def main():
    options, flags = grass.parser()
    xAmap = options['xaraster']
    xBmap = options['xbraster']
    yAmap = options['yaraster']
    yBmap = options['ybraster']
    output_basename = options['output']
    custom_threshold = options['custom_threshold']
    stat_threshold = options['stat_threshold']
    Xdelta_name = 'deltaX'
    Ydelta_name = 'deltaY'
    anglemap_name = output_basename + '_angle'
    anglemap_class = anglemap_name + '_class'
    magnitudemap_name = output_basename + '_magnitude'
    changemap_name = output_basename + '_change'

    # Checking that the input maps exist
    if not grass.find_file(name=xAmap, element='cell')['file']:
        grass.fatal("xaraster map <%s> not found" % xAmap)
    if not grass.find_file(name=xBmap, element='cell')['file']:
        grass.fatal("xbraster map <%s> not found" % xBmap)
    if not grass.find_file(name=yAmap, element='cell')['file']:
        grass.fatal("yaraster map <%s> not found" % yAmap)
    if not grass.find_file(name=xBmap, element='cell')['file']:
        grass.fatal("ybraster map <%s> not found" % yBmap)

    TMPRAST.append(Xdelta_name)
    TMPRAST.append(Ydelta_name)

    # Calculating delta for X and Y bands
    grass.message(_("Calculating DeltaX and DeltaY"))
    delta_calculation(Xdelta_name, xBmap, xAmap)
    delta_calculation(Ydelta_name, yBmap, yAmap)

    #Calculating angle and magnitude maps
    grass.message(_("Writing angle map %s") % anglemap_name)
    angle_calculation(anglemap_name, Xdelta_name, Ydelta_name)

    grass.message(_("Writing magnitude map %s") % magnitudemap_name)
    magnitude_calculation(magnitudemap_name, Xdelta_name, Ydelta_name)

    # Reclassifing angle map to get a map with the four quadrants
    keys = ['1', '2', '3', '4']
    vals = [0, 90, 180, 270, 360]
    rvals = [(int(vals[i-1]), int(vals[i]), keys[i-1], vals[i-1], vals[i]) for i in range(1, len(vals))]
    rules = '\n'.join(['%3d thru %3d = %s   %s-%s' % v for v in rvals])
    script.write_command('r.reclass', input=anglemap_name, output=anglemap_class, rules='-', overwrite=True, stdin=rules.encode())

    # Generating the change detection map using the given threshold
    if custom_threshold:
        threshold = custom_threshold
        grass.message(_("Threshold is %s") % threshold)
        grass.message(_("Writing change detection map %s") % changemap_name)
        # Creating the final map of the change, using a custom threshold
        change_map_calculation(changemap_name, magnitudemap_name, threshold, anglemap_class)
    elif stat_threshold:
        #Getting values of mean and standard dev of magnitude to calculate the change detection criteria (> mean + N*stdev)
        univar = grass.read_command('r.univar', map=magnitudemap_name, flags='g')
 
        found = 0
        for line in univar.splitlines():
            name,val = line.split('=')
            if name == 'mean':
                grass.message(_("Mean of magnitude values is: %s") % val)
                mean = val
                found += 1
            if name == 'stddev':
                grass.message(_("Standard deviation of magnitude values is: %s") % val)
                stddev = val
                found += 1
        if found != 2:
            grass.fatal("Couldn\'t find mean or stddev!")

        adding_value = float(stat_threshold) * float(stddev)
        threshold = float(mean) + float(adding_value)
        grass.message(_("Threshold is %s") % threshold)
        #Creating the final map of the change, using a statistical threshold
        change_map_calculation(changemap_name, magnitudemap_name, threshold, anglemap_class)
    else:
        grass.message(_("No threshold given, only angle and magnitude maps have been created"))


    return 0
Esempio n. 24
0
                              name=outname)
            grass.run_command('r.reclass',
                              input=i,
                              out=outname,
                              rules=outfile.name)
        elif result['fullname'] and not grass.overwrite():
            grass.warning(
                _("Raster map %s already exists and will not be overwritten" %
                  i))
        else:
            grass.run_command('r.reclass',
                              input=i,
                              out=outname,
                              rules=outfile.name)
        output_names.append(outname)
        # remove the rules file
        grass.try_remove(outfile.name)
        # write cmd history:
        grass.raster_history(outname)
    db.commit()
    db.close()
    if mosaic:
        grass.message(_("Processing mosaic <%s>..." % mosaic))
        grass.run_command('g.region', raster=all_images)
        grass.run_command('r.patch', input=output_names, output=mosaic)


if __name__ == "__main__":
    options, flags = grass.parser()
    sys.exit(main())
def main():
    options, flags = gs.parser()

    # it does not check if pngs and other files exists,
    # maybe it could check the any/all file(s) dir

    if options['raster'] and options['strds']:
        gs.fatal(_("Options raster and strds cannot be specified together."
                   " Please decide for one of them."))
    if options['raster'] and options['where']:
        gs.fatal(_("Option where cannot be combined with the option raster."
                   " Please don't set where option or use strds option"
                   " instead of raster option."))
    if options['raster']:
        if ',' in options['raster']:
            maps = options['raster'].split(',')  # TODO: skip empty parts
        else:
            maps = [options['raster']]
    elif options['strds']:
        # import and init only when needed
        # init is called anyway when the generated form is used
        import grass.temporal as tgis

        strds = options['strds']
        where = options['where']

        # make sure the temporal database exists
        tgis.init()

        # create the space time raster object
        ds = tgis.open_old_space_time_dataset(strds, 'strds')
        # check if the dataset is in the temporal database
        if not ds.is_in_db():
            gs.fatal(_("Space time dataset <%s> not found") % strds)

        # we need a database interface
        dbiface = tgis.SQLDatabaseInterfaceConnection()
        dbiface.connect()

        # the query
        rows = ds.get_registered_maps(columns='id', where=where,
                                      order='start_time')
        if not rows:
            gs.fatal(_("Cannot get any maps for spatio-temporal raster"
                       " dataset <%s>."
                       " Dataset is empty or you temporal WHERE"
                       " condition filtered all maps out."
                       " Please, specify another dataset,"
                       " put maps into this dataset"
                       " or correct your WHERE condition.") % strds)
        maps = [row['id'] for row in rows]
    else:
        gs.fatal(_("Either raster or strds option must be specified."
                   " Please specify one of them."))
    # get the number of maps for later use
    num_maps = len(maps)

    out_dir = options['output']
    if not os.path.exists(out_dir):
        # TODO: maybe we could create the last dir on specified path?
        gs.fatal(_("Output path <%s> does not exists."
                   " You need to create the (empty) output directory"
                   " yourself before running this module.") % out_dir)
    epsg = int(options['epsg'])

    if ',' in options['opacity']:
        opacities = [float(opacity)
                     for opacity in options['opacity'].split(',')]
        if len(opacities) != num_maps:
            gs.fatal(_("Number of opacities <{no}> does not match number"
                       " of maps <{nm}>.").format(no=len(opacities),
                                                  nm=num_maps))
    else:
        opacities = [float(options['opacity'])] * num_maps

    if ',' in options['info']:
        infos = options['info'].split(',')
    else:
        infos = [options['info']]

    if 'geotiff' in infos and not gs.find_program('r.out.tiff', '--help'):
        gs.fatal(_("Install r.out.tiff add-on module to export GeoTIFF"))

    # r.out.png options
    compression = int(options['compression'])
    # flag w is passed to r.out.png.proj
    # our flag n is inversion of r.out.png.proj's t flag
    # (transparent NULLs are better for overlay)
    # we always need the l flag (ll .wgs84 file)
    routpng_flags = ''
    if not flags['n']:
        routpng_flags += 't'
    if flags['w']:
        routpng_flags += 'w'
    # r.out.png.proj l flag for LL .wgs84 file is now function parameter
    # and is specified bellow

    if flags['m']:
        use_region = False
        # we will use map extent
        gs.use_temp_region()
    else:
        use_region = True

    # hard coded file names
    data_file_name = 'data_file.csv'
    js_data_file_name = 'data_file.js'

    data_file = open(os.path.join(out_dir, data_file_name), 'w')
    js_data_file = open(os.path.join(out_dir, js_data_file_name), 'w')
    js_data_file.write('/* This file was generated by r.out.leaflet GRASS GIS'
                       ' module. */\n\n')
    js_data_file.write('var layerInfos = [\n')

    for i, map_name in enumerate(maps):
        if not use_region:
            gs.run_command('g.region', rast=map_name)
        if '@' in map_name:
            pure_map_name = map_name.split('@')[0]
        else:
            pure_map_name = map_name
        # TODO: mixing current and map's mapset at this point
        if '@' in map_name:
            map_name, src_mapset_name = map_name.split('@')
        else:
            # TODO: maybe mapset is mandatory for those out of current mapset?
            src_mapset_name = gs.gisenv()['MAPSET']
        image_file_name = pure_map_name + '.png'
        image_file_path = os.path.join(out_dir, image_file_name)
        # TODO: skip writing to file and extract the information from
        # function, or use object if function is so large
        wgs84_file = image_file_path + '.wgs84'
        export_png_in_projection(map_name=map_name,
                                 src_mapset_name=src_mapset_name,
                                 output_file=image_file_path,
                                 epsg_code=epsg,
                                 compression=compression,
                                 routpng_flags=routpng_flags,
                                 wgs84_file=wgs84_file,
                                 use_region=True)

        data_file.write(pure_map_name + ',' + image_file_name + '\n')

        # it doesn't matter in which location we are, it just uses the current
        # location, not tested for LL loc, assuming that to be nop.
        map_extent = get_map_extent_for_file(wgs84_file)
        bounds = map_extent_to_js_leaflet_list(map_extent)

        extra_attributes = []

        generate_infos(map_name=map_name,
                       projected_png_file=image_file_path,
                       required_infos=infos,
                       output_directory=out_dir,
                       attributes=extra_attributes)
        # http://www.w3schools.com/js/js_objects.asp
        js_data_file.write("""   {{title: "{title}", file: "{file_}","""
                           """ bounds: {bounds}, opacity: {opacity}"""
                           .format(title=pure_map_name,
                                   file_=image_file_name,
                                   bounds=bounds,
                                   opacity=opacities[i]))
        if extra_attributes:
            extra_js_attributes = [pair[0] + ': "' +
                                   escape_quotes(
                                       escape_endlines(
                                           escape_backslashes(
                                               pair[1]
                                           ))) + '"'
                                   for pair in extra_attributes]
            js_data_file.write(', ' + ', '.join(extra_js_attributes))
        js_data_file.write("""}\n""")
        # do not write after the last item
        if i < num_maps - 1:
            js_data_file.write(',')
    js_data_file.write('];\n')
    data_file.close()
Esempio n. 26
0
    # except:
    #    sys.exit(_("R is not installed. Install it and re-run, or modify environment variables."))

    # rpy2
    global robjects
    global rinterface
    grass.message(_('Loading dependencies, please wait...'))
    try:
        import rpy2.robjects as robjects
        import rpy2.rinterface as rinterface  # to speed up kriging? for plots.
    except ImportError:
        # ok for other OSes?
        grass.fatal(_("Python module 'Rpy2' not found. Please install it and re-run v.krige."))

    # R packages check. Will create one error message after check of all packages.
    missingPackagesList = []
    for each in ["rgeos", "gstat", "rgrass7", "maptools"]:
        if not robjects.r.require(each, quietly=True)[0]:
            missingPackagesList.append(each)
    if missingPackagesList:
        errorString = _("R package(s) ") + \
            ", ".join(map(str, missingPackagesList)) + \
            _(" missing. Install it/them and re-run v.krige.")
        grass.fatal(errorString)

if __name__ == '__main__':
    if len(sys.argv) > 1:
        sys.exit(main(argv=grass.parser()))
    else:
        main()
Esempio n. 27
0
def main():
    options, flags = gscript.parser()

    # import wx only after running parser
    # to avoid issues when only interface is needed
    import grass.temporal as tgis
    import wx

    from grass.script.setup import set_gui_path
    set_gui_path()

    from core.globalvar import CheckWxVersion
    from core.utils import _
    from core.giface import StandaloneGrassInterface
    from core.layerlist import LayerList
    from animation.frame import AnimationFrame, MAX_COUNT
    from animation.data import AnimLayer

    rast = options['raster']
    vect = options['vector']
    strds = options['strds']
    stvds = options['stvds']

    numInputs = 0

    if rast:
        numInputs += 1
    if vect:
        numInputs += 1
    if strds:
        numInputs += 1
    if stvds:
        numInputs += 1

    if numInputs > 1:
        gscript.fatal(_("%s=, %s=, %s= and %s= are mutually exclusive.") %
                       ("raster", "vector", "strds", "stvds"))

    if numInputs > 0:
        # We need to initialize the temporal framework in case
        # a space time dataset was set on the command line so that
        # the AnimLayer() class works correctly
        tgis.init()

    layerList = LayerList()
    if rast:
        layer = AnimLayer()
        layer.mapType = 'raster'
        layer.name = rast
        layer.cmd = ['d.rast', 'map={name}'.format(name=rast.split(',')[0])]
        layerList.AddLayer(layer)
    if vect:
        layer = AnimLayer()
        layer.mapType = 'vector'
        layer.name = vect
        layer.cmd = ['d.vect', 'map={name}'.format(name=vect.split(',')[0])]
        layerList.AddLayer(layer)
    if strds:
        layer = AnimLayer()
        layer.mapType = 'strds'
        layer.name = strds
        layer.cmd = ['d.rast', 'map=']
        layerList.AddLayer(layer)
    if stvds:
        layer = AnimLayer()
        layer.mapType = 'stvds'
        layer.name = stvds
        layer.cmd = ['d.vect', 'map=']
        layerList.AddLayer(layer)

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

    frame = AnimationFrame(parent=None, giface=StandaloneGrassInterface())
    frame.CentreOnScreen()
    frame.Show()
    if len(layerList) >= 1:
        # CallAfter added since it was crashing with wxPython 3 gtk
        wx.CallAfter(frame.SetAnimations,
                     [layerList] + [None] * (MAX_COUNT - 1))
    app.MainLoop()
Esempio n. 28
0
                'end': options['end'],
                'sortby': sortby,
                'asc': True if options['order'] == 'asc' else False,
                'relativeorbitnumber': options['relativeorbitnumber']
            }
            if options['datasource'] == 'ESA_COAH':
                downloader.filter(**filter_args)
            elif options['datasource'] == 'USGS_EE':
                downloader.filter_USGS(**filter_args)
    except Exception as e:
        gs.fatal(
            _('Unable to connect to {0}: {1}').format(options['datasource'],
                                                      e))

    if options['footprints']:
        downloader.save_footprints(options['footprints'])

    if flags['l']:
        downloader.list()
        return

    downloader.download(options['output'], options['sleep'],
                        int(options['retry']))

    return 0


if __name__ == "__main__":
    options, flags = gs.parser()
    sys.exit(main())
Esempio n. 29
0
    offset = 0
    offsets = []
    parms = {}
    for n, img in enumerate(images):
        offsets.append(offset)
        parms['image%d' % (n + 1)] = img
        parms['offset%d' % (n + 1)] = offset
        offset += get_limit(img) + 1

    gscript.message(_("Mosaicing %d images...") % count)

    gscript.mapcalc("$output = " + make_expression(1, count),
                    output=output, **parms)

    # modify the color table:
    p = gscript.feed_command('r.colors', map=output, rules='-')
    for img, offset in zip(images, offsets):
        print(img, offset)
        copy_colors(p.stdin, img, offset)
    p.stdin.close()
    p.wait()

    gscript.message(_("Done. Raster map <%s> created.") % output)

    # write cmd history:
    gscript.raster_history(output)

if __name__ == "__main__":
    options, flags = gscript.parser()
    main()
Esempio n. 30
0
                alayer = "1",
                atype = "auto",
                binput = "fp_65r_42@report",
                blayer = "1",
                btype = "area",
                operator = "or",
                output = "fp_pad42",
                olayer = "1,0,0",
                snap = 1e-8)

    run_command("v.db.addcolumn",
                map = "fp_pad42",
                layer = "1",
                columns = "subarea double precision")

    run_command("v.to.db",
                map = "fp_pad42",
                layer = "1",
                type = "point,line,boundary,centroid",
                option = "area",
                columns = "subarea",
                query_layer = "1",
                separator = "pipe")

    return 0

if __name__ == "__main__":
    options, flags = parser()
    atexit.register(cleanup)
    sys.exit(main())
Esempio n. 31
0
    
    Module('g.region',
           res=resolution,
           vector=['startp', 'endp'])
    Module('g.region',
           n='n+{}'.format(offset),
           s='s-{}'.format(offset),
           e='e+{}'.format(offset),
           w='w-{}'.format(offset))
    
    Module('r.cost',
           flags='k',
           input='rychlost_cas',
           output='rychlost_naklady',
           start_points='startp',
           overwrite=True)
    Module('r.drain',
           flags='n',
           input='rychlost_naklady',
           output=option['output'],
           start_points='endp')
    Module('r.to.vect',
           flags='s',
           input=option['output'],
           output=option['output'],
           type='line')

if __name__ == "__main__":
    option, flag = gscript.parser()
    main()
Esempio n. 32
0
def main():
    grass.set_raise_on_error(False)

    options, flags = grass.parser()

    # import wx only after running parser
    # to avoid issues with complex imports when only interface is needed
    import wx

    from grass.script.setup import set_gui_path
    set_gui_path()
    
    from core.globalvar import CheckWxVersion
    from core.utils import _
    from core.render import Map
    from mapdisp.frame import MapFrame
    from mapdisp.main import DMonGrassInterface
    from core.settings import UserSettings
    from vdigit.main import haveVDigit, errorMsg
    from grass.exceptions import CalledModuleError

    # define classes which needs imports as local
    # for longer definitions, a separate file would be a better option
    class VDigitMapFrame(MapFrame):
        def __init__(self, vectorMap):
            MapFrame.__init__(
                self, parent=None, Map=Map(), giface=DMonGrassInterface(None),
                title=_("GRASS GIS Vector Digitizer"), size=(850, 600))
            # this giface issue not solved yet, we must set mapframe aferwards
            self._giface._mapframe = self
            # load vector map
            mapLayer = self.GetMap().AddLayer(
                ltype='vector', name=vectorMap,
                command=['d.vect', 'map=%s' % vectorMap],
                active=True, hidden=False, opacity=1.0, render=True)

            # switch toolbar
            self.AddToolbar('vdigit', fixed=True)

            # start editing
            self.toolbars['vdigit'].StartEditing(mapLayer)

    if not haveVDigit:
        grass.fatal(_("Vector digitizer not available. %s") % errorMsg)

    if not grass.find_file(name=options['map'], element='vector',
                           mapset=grass.gisenv()['MAPSET'])['fullname']:
        if not flags['c']:
            grass.fatal(_("Vector map <%s> not found in current mapset. "
                          "New vector map can be created by providing '-c' flag.") % options['map'])
        else:
            grass.verbose(_("New vector map <%s> created") % options['map'])
            try:
                grass.run_command('v.edit', map=options['map'], tool='create', quiet=True)
            except CalledModuleError:
                grass.fatal(_("Unable to create new vector map <%s>") % options['map'])

    # allow immediate rendering
    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'

    app = wx.App()
    if not CheckWxVersion([2, 9]):
        wx.InitAllImageHandlers()
    frame = VDigitMapFrame(options['map'])
    frame.Show()

    app.MainLoop()
    ## Calculate final map statistics
    l_osm_proc = length(out)
    diff_osm = l_osm - l_osm_proc
    diff_p_osm = diff_osm/l_osm*100
    diff_new = l_ref - l_osm_proc
    diff_p_new = diff_new/l_ref*100

    ##  Write output file with statistics (if required)
    if len(out_file)>0:
        fil=open(out_file,"w")
        fil.write("REF dataset length: %s m\n"%(round(l_ref,1)))
        fil.write("Original OSM dataset length: %s m\n"%(round(l_osm,1)))
        fil.write("Processed OSM dataset length: %s m\n"%(round(l_osm_proc,1)))
        fil.write("Difference between OSM original and processed datasets length: %s m (%s%%)\n"%(round(diff_osm,1),round(diff_p_osm,1)))      
        fil.write("Difference between REF dataset and processed OSM dataset length: %s m (%s%%)\n"%(round(diff_new,1),round(diff_p_new,1)))   
        fil.close()   

    ## Print statistics
    print("#####################################################################\n")
    print("Original OSM dataset length: %s m\n"%(round(l_osm,1)))
    print("Processed OSM dataset length: %s m\n"%(round(l_osm_proc,1)))
    print("Difference between OSM original and processed datasets length: %s m (%s%%)\n"%(round(diff_osm,1),round(diff_p_osm,1)))
    print("Difference between REF dataset and processed OSM dataset length: %s m (%s%%)\n"%(round(diff_new,1),round(diff_p_new,1)))
    print("#####################################################################\n")
    


if __name__ == "__main__":
    options,flags = grass.parser()
    sys.exit(main())
        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


if __name__ == '__main__':
    options, flags = gs.parser()
    atexit.register(cleanup)
    main()
            self.process.wait()
            self.process = None
            if self.observer:
                try:
                    self.observer.stop()
                except TypeError:  # throws error on mac
                    pass
                self.observer.join()
        self.timer.Stop()
        self.status.SetLabel("Real-time scanning stopped.")

    def runImport(self):
        run_analyses(scan_params=self.scan, analysesFile=self.settings['tangible']['analyses']['file'])
        evt = updateGUIEvt(self.GetId())
        wx.PostEvent(self, evt)


def main(giface=None):
    global Observer, RasterChangeHandler
    from watchdog.observers import Observer
    from change_handler import RasterChangeHandler
    dlg = TangibleLandscapePlugin(giface, parent=None)
    dlg.Show()


if __name__ == '__main__':
    gscript.parser()
    from watchdog.observers import Observer
    from change_handler import RasterChangeHandler
    main()
Esempio n. 36
0
def main():
    """
    Build gravity reservoirs in GSFLOW: combines MODFLOW grid and HRU sub-basins
    These define the PRMS soil zone that connects to MODFLOW cells
    """

    ##################
    # OPTION PARSING #
    ##################

    # I/O
    options, flags = gscript.parser()

    # I/O
    HRUs = options['hru_input']
    grid = options['grid_input']
    segments = options['output']
    #col = options['col']
    gravity_reservoirs = options['output']

    ############
    # ANALYSIS #
    ############
    """
    # Basin areas
    v.db_addcolumn(map=basins, columns=col)
    v.to_db(map=basins, option='area', units='meters', columns=col)
    """

    # Create gravity reservoirs -- overlay cells=grid and HRUs
    v.overlay(ainput=HRUs,
              binput=grid,
              atype='area',
              btype='area',
              operator='and',
              output=gravity_reservoirs,
              overwrite=gscript.overwrite())
    v.db_dropcolumn(map=gravity_reservoirs,
                    columns='a_cat,a_label,b_cat',
                    quiet=True)
    # Cell and HRU ID's
    v.db_renamecolumn(map=gravity_reservoirs,
                      column=('a_id', 'gvr_hru_id'),
                      quiet=True)
    v.db_renamecolumn(map=gravity_reservoirs,
                      column=('b_id', 'gvr_cell_id'),
                      quiet=True)
    # Percent areas
    v.db_renamecolumn(map=gravity_reservoirs,
                      column=('a_hru_area_m2', 'hru_area_m2'),
                      quiet=True)
    v.db_renamecolumn(map=gravity_reservoirs,
                      column=('b_area_m2', 'cell_area_m2'),
                      quiet=True)
    v.db_addcolumn(map=gravity_reservoirs,
                   columns='area_m2 double precision',
                   quiet=True)
    v.to_db(map=gravity_reservoirs,
            option='area',
            units='meters',
            columns='area_m2',
            quiet=True)
    v.db_addcolumn(
        map=gravity_reservoirs,
        columns='gvr_cell_pct double precision, gvr_hru_pct double precision',
        quiet=True)
    v.db_update(map=gravity_reservoirs,
                column='gvr_cell_pct',
                query_column='100*area_m2/cell_area_m2',
                quiet=True)
    v.db_update(map=gravity_reservoirs,
                column='gvr_hru_pct',
                query_column='100*area_m2/hru_area_m2',
                quiet=True)
    v.extract(input=gravity_reservoirs,
              output='tmp_',
              where="gvr_cell_pct > 0.001",
              overwrite=True,
              quiet=True)
    g.rename(vector=('tmp_', gravity_reservoirs), overwrite=True, quiet=True)