Beispiel #1
0
def vector_info(map):
    """Return information about a vector map (interface to
    `v.info`). Example:

    >>> vector_info('geology') # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
    {'comment': '', 'projection': 'Lambert Conformal Conic' ... 'south': 10875.8272320917}

    :param str map: map name

    :return: parsed vector info
    """

    s = read_command('v.info', flags='get', map=map)

    kv = parse_key_val(s)
    for k in ['north', 'south', 'east', 'west', 'top', 'bottom']:
        kv[k] = float(kv[k])
    for k in ['level', 'num_dblinks']:
        kv[k] = int(kv[k])
    for k in ['nodes', 'points', 'lines', 'boundaries', 'centroids', 'areas',
              'islands', 'primitives']:
        kv[k] = int(kv[k])
    if 'map3d' in kv:
        kv['map3d'] = bool(int(kv['map3d']))
        if kv['map3d']:
            for k in ['faces', 'kernels', 'volumes', 'holes']:
                kv[k] = int(kv[k])

    return kv
Beispiel #2
0
def region(region3d=False, complete=False):
    """Returns the output from running "g.region -gu", as a
    dictionary. Example:

    :param bool region3d: True to get 3D region
    :param bool complete:

    >>> curent_region = region()
    >>> # obtain n, s, e and w values
    >>> [curent_region[key] for key in "nsew"]  # doctest: +ELLIPSIS
    [..., ..., ..., ...]
    >>> # obtain ns and ew resulutions
    >>> (curent_region['nsres'], curent_region['ewres'])  # doctest: +ELLIPSIS
    (..., ...)

    :return: dictionary of region values
    """
    flgs = 'gu'
    if region3d:
        flgs += '3'
    if complete:
        flgs += 'cep'

    s = read_command("g.region", flags=flgs)
    reg = parse_key_val(s, val_type=float)
    for k in ['rows',  'cols',  'cells',
              'rows3', 'cols3', 'cells3', 'depths']:
        if k not in reg:
            continue
        reg[k] = int(reg[k])

    return reg
Beispiel #3
0
def raster_info(map):
    """Return information about a raster map (interface to
    `r.info -gre`). Example:

    >>> raster_info('elevation') # doctest: +ELLIPSIS
    {'creator': '"helena"', 'cols': '1500' ... 'south': 215000.0}

    :param str map: map name

    :return: parsed raster info

    """

    def float_or_null(s):
        if s == 'NULL':
            return None
        else:
            return float(s)

    s = read_command('r.info', flags='gre', map=map)
    kv = parse_key_val(s)
    for k in ['min', 'max']:
        kv[k] = float_or_null(kv[k])
    for k in ['north', 'south', 'east', 'west']:
        kv[k] = float(kv[k])
    for k in ['nsres', 'ewres']:
        kv[k] = float_or_dms(kv[k])
    return kv
Beispiel #4
0
def region(region3d=False, complete=False):
    """Returns the output from running "g.region -gu", as a
    dictionary. Example:

    :param bool region3d: True to get 3D region
    :param bool complete:

    >>> curent_region = region()
    >>> # obtain n, s, e and w values
    >>> [curent_region[key] for key in "nsew"]  # doctest: +ELLIPSIS
    [..., ..., ..., ...]
    >>> # obtain ns and ew resulutions
    >>> (curent_region['nsres'], curent_region['ewres'])  # doctest: +ELLIPSIS
    (..., ...)

    :return: dictionary of region values
    """
    flgs = 'gu'
    if region3d:
        flgs += '3'
    if complete:
        flgs += 'cep'

    s = read_command("g.region", flags=flgs)
    reg = parse_key_val(s, val_type=float)
    for k in ['rows', 'cols', 'cells', 'rows3', 'cols3', 'cells3', 'depths']:
        if k not in reg:
            continue
        reg[k] = int(reg[k])

    return reg
Beispiel #5
0
def find_file(name, element='cell', mapset=None):
    """Returns the output from running g.findfile as a
    dictionary. Example:

    >>> result = find_file('elevation', element='cell')
    >>> print result['fullname']
    elevation@PERMANENT
    >>> print result['file']  # doctest: +ELLIPSIS
    /.../PERMANENT/cell/elevation


    :param str name: file name
    :param str element: element type (default 'cell')
    :param str mapset: mapset name (default all mapsets in search path)

    :return: parsed output of g.findfile
    """
    if element == 'raster' or element == 'rast':
        verbose(_('Element type should be "cell" and not "%s"') % element)
        element = 'cell'
    s = read_command("g.findfile",
                     flags='n',
                     element=element,
                     file=name,
                     mapset=mapset)
    return parse_key_val(s)
Beispiel #6
0
def locn_is_latlong():
    """Tests if location is lat/long. Value is obtained
    by checking the "g.region -pu" projection code.

    :return: True for a lat/long region, False otherwise
    """
    s = read_command("g.region", flags='pu')
    kv = parse_key_val(s, ':')
    if kv['projection'].split(' ')[0] == '3':
        return True
    else:
        return False
Beispiel #7
0
def gisenv():
    """Returns the output from running g.gisenv (with no arguments), as a
    dictionary. Example:

    >>> env = gisenv()
    >>> print env['GISDBASE']  # doctest: +SKIP
    /opt/grass-data

    :return: list of GRASS variables
    """
    s = read_command("g.gisenv", flags='n')
    return parse_key_val(s)
Beispiel #8
0
def locn_is_latlong():
    """Tests if location is lat/long. Value is obtained
    by checking the "g.region -pu" projection code.

    :return: True for a lat/long region, False otherwise
    """
    s = read_command("g.region", flags='pu')
    kv = parse_key_val(s, ':')
    if kv['projection'].split(' ')[0] == '3':
        return True
    else:
        return False
Beispiel #9
0
def gisenv():
    """Returns the output from running g.gisenv (with no arguments), as a
    dictionary. Example:

    >>> env = gisenv()
    >>> print env['GISDBASE']  # doctest: +SKIP
    /opt/grass-data

    :return: list of GRASS variables
    """
    s = read_command("g.gisenv", flags='n')
    return parse_key_val(s)
Beispiel #10
0
def vector_info_topo(map):
    """Return information about a vector map (interface to `v.info -t`).
    Example:

    >>> vector_info_topo('geology') # doctest: +NORMALIZE_WHITESPACE
    {'lines': 0, 'centroids': 1832, 'boundaries': 3649, 'points': 0,
    'primitives': 5481, 'islands': 907, 'nodes': 2724, 'map3d': False,
    'areas': 1832}

    :param str map: map name

    :return: parsed output
    """
    s = read_command('v.info', flags='t', map=map)
    ret = parse_key_val(s, val_type=int)
    if 'map3d' in ret:
        ret['map3d'] = bool(ret['map3d'])

    return ret
Beispiel #11
0
def find_file(name, element='cell', mapset=None):
    """Returns the output from running g.findfile as a
    dictionary. Example:

    >>> result = find_file('elevation', element='cell')
    >>> print result['fullname']
    elevation@PERMANENT
    >>> print result['file']  # doctest: +ELLIPSIS
    /.../PERMANENT/cell/elevation


    :param str name: file name
    :param str element: element type (default 'cell')
    :param str mapset: mapset name (default all mapsets in search path)

    :return: parsed output of g.findfile
    """
    if element == 'raster' or element == 'rast':
        verbose(_('Element type should be "cell" and not "%s"') % element)
        element = 'cell'
    s = read_command("g.findfile", flags='n', element=element, file=name,
                     mapset=mapset)
    return parse_key_val(s)
Beispiel #12
0
def raster3d_info(map):
    """Return information about a raster3d map (interface to `r3.info`).
    Example:

    >>> mapcalc3d('volume = row() + col() + depth()')
    >>> raster3d_info('volume') # doctest: +ELLIPSIS
    {'vertical_units': '"units"', 'tbres': 1.0, ... 'south': 185000.0}
    >>> run_command('g.remove', flags='f', type='rast3d', pattern='volume')
    0

    :param str map: map name

    :return: parsed raster3d info
    """

    def float_or_null(s):
        if s == 'NULL':
            return None
        else:
            return float(s)

    s = read_command('r3.info', flags='rg', map=map)
    kv = parse_key_val(s)
    for k in ['min', 'max']:
        kv[k] = float_or_null(kv[k])
    for k in ['north', 'south', 'east', 'west', 'top', 'bottom']:
        kv[k] = float(kv[k])
    for k in ['nsres', 'ewres', 'tbres']:
        kv[k] = float_or_dms(kv[k])
    for k in ['rows', 'cols', 'depths']:
        kv[k] = int(kv[k])
    for k in ['tilenumx', 'tilenumy', 'tilenumz']:
        kv[k] = int(kv[k])
    for k in ['tiledimx', 'tiledimy', 'tiledimz']:
        kv[k] = int(kv[k])
    return kv
Beispiel #13
0
def region_env(region3d=False, **kwargs):
    """Returns region settings as a string which can used as
    GRASS_REGION environmental variable.

    If no 'kwargs' are given then the current region is used. Note
    that this function doesn't modify the current region!

    See also use_temp_region() for alternative method how to define
    temporary region used for raster-based computation.

    :param bool region3d: True to get 3D region
    :param kwargs: g.region's parameters like 'rast', 'vect' or 'region'

    ::

        os.environ['GRASS_REGION'] = grass.region_env(region='detail')
        grass.mapcalc('map=1', overwrite=True)
        os.environ.pop('GRASS_REGION')

    :return: string with region values
    :return: empty string on error
    """
    # read proj/zone from WIND file
    env = gisenv()
    windfile = os.path.join(env['GISDBASE'], env['LOCATION_NAME'],
                            env['MAPSET'], "WIND")
    fd = open(windfile, "r")
    grass_region = ''
    for line in fd.readlines():
        key, value = map(lambda x: x.strip(), line.split(":", 1))
        if kwargs and key not in ('proj', 'zone'):
            continue
        if not kwargs and not region3d and \
                key in ('top', 'bottom', 'cols3', 'rows3',
                        'depths', 'e-w resol3', 'n-s resol3', 't-b resol'):
            continue

        grass_region += '%s: %s;' % (key, value)

    if not kwargs:  # return current region
        return grass_region

    # read other values from `g.region -gu`
    flgs = 'ug'
    if region3d:
        flgs += '3'

    s = read_command('g.region', flags=flgs, **kwargs)
    if not s:
        return ''
    reg = parse_key_val(s)

    kwdata = [('north',     'n'),
              ('south',     's'),
              ('east',      'e'),
              ('west',      'w'),
              ('cols',      'cols'),
              ('rows',      'rows'),
              ('e-w resol', 'ewres'),
              ('n-s resol', 'nsres')]
    if region3d:
        kwdata += [('top',        't'),
                   ('bottom',     'b'),
                   ('cols3',      'cols3'),
                   ('rows3',      'rows3'),
                   ('depths',     'depths'),
                   ('e-w resol3', 'ewres3'),
                   ('n-s resol3', 'nsres3'),
                   ('t-b resol',  'tbres')]

    for wkey, rkey in kwdata:
        grass_region += '%s: %s;' % (wkey, reg[rkey])

    return grass_region
Beispiel #14
0
def region_env(region3d=False, **kwargs):
    """Returns region settings as a string which can used as
    GRASS_REGION environmental variable.

    If no 'kwargs' are given then the current region is used. Note
    that this function doesn't modify the current region!

    See also use_temp_region() for alternative method how to define
    temporary region used for raster-based computation.

    :param bool region3d: True to get 3D region
    :param kwargs: g.region's parameters like 'rast', 'vect' or 'region'

    ::

        os.environ['GRASS_REGION'] = grass.region_env(region='detail')
        grass.mapcalc('map=1', overwrite=True)
        os.environ.pop('GRASS_REGION')

    :return: string with region values
    :return: empty string on error
    """
    # read proj/zone from WIND file
    env = gisenv()
    windfile = os.path.join(env['GISDBASE'], env['LOCATION_NAME'],
                            env['MAPSET'], "WIND")
    fd = open(windfile, "r")
    grass_region = ''
    for line in fd.readlines():
        key, value = map(lambda x: x.strip(), line.split(":", 1))
        if kwargs and key not in ('proj', 'zone'):
            continue
        if not kwargs and not region3d and \
                key in ('top', 'bottom', 'cols3', 'rows3',
                        'depths', 'e-w resol3', 'n-s resol3', 't-b resol'):
            continue

        grass_region += '%s: %s;' % (key, value)

    if not kwargs:  # return current region
        return grass_region

    # read other values from `g.region -gu`
    flgs = 'ug'
    if region3d:
        flgs += '3'

    s = read_command('g.region', flags=flgs, **kwargs)
    if not s:
        return ''
    reg = parse_key_val(s)

    kwdata = [('north', 'n'), ('south', 's'), ('east', 'e'), ('west', 'w'),
              ('cols', 'cols'), ('rows', 'rows'), ('e-w resol', 'ewres'),
              ('n-s resol', 'nsres')]
    if region3d:
        kwdata += [('top', 't'), ('bottom', 'b'), ('cols3', 'cols3'),
                   ('rows3', 'rows3'), ('depths', 'depths'),
                   ('e-w resol3', 'ewres3'), ('n-s resol3', 'nsres3'),
                   ('t-b resol', 'tbres')]

    for wkey, rkey in kwdata:
        grass_region += '%s: %s;' % (wkey, reg[rkey])

    return grass_region