Ejemplo n.º 1
0
def collectresults(task,proc):
    for i in task:
        #print(i)
        #print(proc)
        #print("combining outputs for point " + str(i) + " and for cpu " + str(proc))
        message = "Combining outputs for point %s and for cpu %s "
        gscript.message(message % (str(i),str(proc)))
        #updating the output layer of the angle
        #updating the output layer of the best angle of view among all the points in the path 
        Module("r.mapcalc", expression="{A} = if(isnull({I}) ||| {I}==0,{A},max({A},{I}))".format(A='xxtemp_a_'+str(proc),I='zzangle'+i), overwrite=True, quiet=True)
        #updating the output layer of the category of the point who has the higher angles with the considered cell
        Module("r.mapcalc", expression="{A} = if({I}==0 ||| isnull({I}),{A}, if({I}<{Z},{A},{cat}))".format(A='xxtemp_c_'+str(proc),I='zzangle'+i,Z='xxtemp_a_'+str(proc),cat=i), overwrite=True, quiet=True)
        Module("r.mapcalc", expression="{A} = if({I}==0 ||| isnull({I}),{A}, if({I}<{Z},{A},{I}))".format(A='xxmaxangle_'+str(proc),I='zzangle'+i,Z='xxtemp_a_'+str(proc)), overwrite=True, quiet=True)
	   #updating the output layer of the 3d distance
        #Module("r.mapcalc", expression="{A} = if(isnull({I}),{A}, min({I},{A}))".format(A='xxtemp_e_'+str(proc),I='distance'+i),overwrite=True, quiet=True)
        Module("r.mapcalc", expression="{A} = if(isnull({I}),{A}, if({A} != 0,min({I},{A}),{I}))".format(A='xxtemp_e_'+str(proc),I='zzdistance'+i),overwrite=True, quiet=True)
        #updating the output layer of the category of the point who has the higher solid angles with the considered cell
        Module("r.mapcalc", expression="{A} = if({I}==0 ||| isnull({I}),{A}, if({I}>{Z},{A},{cat}))".format(A='xxtemp_h_'+str(proc),I='zzdistance'+i,Z='xxtemp_e_'+str(proc),cat=i), overwrite=True, quiet=True)
        Module("r.mapcalc", expression="{A} = if({I}==0 ||| isnull({I}),{A}, if({I}>{Z},{A},{I}))".format(A='xxmin3ddistance_'+str(proc),I='zzdistance'+i,Z='xxtemp_e_'+str(proc)), overwrite=True, quiet=True)
        #updating the output layer of the solid angle
        #updating the output layer of the best solid angle of view among all the points in the path 
        Module("r.mapcalc", expression="{A} = if(isnull({I}) ||| {I}==0,{A},max({A},{I}))".format(A='xxtemp_f_'+str(proc),I='zzsangle'+i), overwrite=True, quiet=True)
        #updating the output layer of the category of the point who has the higher solid angles with the considered cell
        Module("r.mapcalc", expression="{A} = if({I}==0 ||| isnull({I}),{A}, if({I}<{Z},{A},{cat}))".format(A='xxtemp_g_'+str(proc),I='zzsangle'+i,Z='xxtemp_f_'+str(proc),cat=i), overwrite=True, quiet=True)
        Module("r.mapcalc", expression="{A} = if({I}==0 ||| isnull({I}),{A}, if({I}<{Z},{A},{I}))".format(A='xxmaxsangle_'+str(proc),I='zzsangle'+i,Z='xxtemp_f_'+str(proc)), overwrite=True, quiet=True)
        #updating the output layer of the number of points a pixel is visible from
        #updating the output layer of the number of points from which a cell is visible
        Module("r.mapcalc", expression="{A} = if(isnull({I}) ||| {I}==0,{A},{A}+1)".format(A='xxtemp_b_'+str(proc),I='zzangle'+i), overwrite=True, quiet=True)
Ejemplo n.º 2
0
    def getEPSG(self):
        proj=Module('g.proj',
                   flags='p',
                   quiet=True,
                   stdout_=PIPE)

        proj=proj.outputs.stdout
        lines=proj.splitlines()
        for e,line in enumerate(lines):
            if 'EPSG' in line:
                epsg=lines[e+1].split(':')[1].replace(' ','')
                return epsg

        proj=Module('g.proj',
                   flags='wf',
                   quiet=True,
                   stdout_=PIPE)
        proj=proj.outputs.stdout

        epsg = self.wkt2standards(proj)

        if not epsg:
            return None
        else:
            return epsg
Ejemplo n.º 3
0
    def parseVect(self):
        '''Read metadata from v.info
        @var self.md_grass dictionary of metadata from v.info
        '''
        # parse md from v.info flags=-g -e -t
        vinfo = Module('v.info',
                       self.map,
                       flags='get',
                       quiet=True,
                       stdout_=PIPE)

        self.md_grass = parse_key_val(vinfo.outputs.stdout)

        # parse md from v.info flag=h (history of map in grass)
        rinfo_h = Module('v.info',
                         self.map,
                         flags='h',
                         quiet=True,
                         stdout_=PIPE)

        md_h_grass = rinfo_h.outputs.stdout
        buf = io.StringIO(md_h_grass)
        line = buf.readline().splitlines()
        while str(line) != '[]':
            if str(line[0]).strip() != "":
                self.md_vinfo_h += line[0] + '\n'
            line = buf.readline().splitlines()
        buf.close()

        # convert GRASS parsed date format to iso format
        # if date format is diverse from standard, use them
        self._createISODate('source_date')
Ejemplo n.º 4
0
    def parseTemporal(self):
        env = grass.gisenv()
        mapset = env['MAPSET']
        if self.map.find("@") < 0:
            self.map = "{}@{}".format(self.map, mapset)
        tinfo = Module('t.info',
                       self.map,
                       flags='g',
                       type=self.type,
                       stdout_=PIPE)

        self.md_grass = parse_key_val(tinfo.outputs.stdout)
        tinfoHist = Module('t.info',
                           input=self.map,
                           quiet=True,
                           flags='h',
                           type=self.type,
                           stdout_=PIPE)
        md_h_grass = tinfoHist.outputs.stdout
        buf = io.StringIO(md_h_grass)
        line = buf.readline().splitlines()

        while line:
            if str(line[0]).strip() != "":
                self.md_vinfo_h += line[0] + '\n'
            line = buf.readline().splitlines()
        buf.close()
Ejemplo n.º 5
0
 def test_resolutions(self):
     """Test that resolution tests runs without nprocs and plots to file"""
     benchmarks = [
         dict(
             module=Module("r.univar",
                           map="elevation",
                           stdout_=DEVNULL,
                           run_=False),
             label="Standard output",
         ),
         dict(
             module=Module("r.univar",
                           map="elevation",
                           flags="g",
                           stdout_=DEVNULL,
                           run_=False),
             label="Standard output",
         ),
     ]
     resolutions = [300, 200, 100]
     results = []
     for benchmark in benchmarks:
         results.append(
             benchmark_resolutions(
                 **benchmark,
                 resolutions=resolutions,
             ))
     plot_file = "test_res_plot.png"
     num_cells_plot(results, filename=plot_file)
     self.assertTrue(Path(plot_file).is_file())
Ejemplo n.º 6
0
def main():
    check_date(options['start'])
    check_date(options['end'])

    # be silent
    os.environ['GRASS_VERBOSE'] = '0'
    
    try:
        Module('t.rast.series',
               input=options['input'],
               output=output,
               method='average',
               where="start_time > '{start}' and start_time < '{end}'".format(
                   start=options['start'], end=options['end']
        ))
    except CalledModuleError:
        gs.fatal('Unable to compute statistics')
        
    ret = Module('r.univar',
                 flags='g',
                 map=output,
                 stdout_=PIPE
    )
    stats = gs.parse_key_val(ret.outputs.stdout)
    print('Min: {0:.1f}'.format(float(stats['min'])))
    print('Max: {0:.1f}'.format(float(stats['max'])))
    print('Mean: {0:.1f}'.format(float(stats['mean'])))
Ejemplo n.º 7
0
def grassEpsg():
    proj=Module('g.proj',
               flags='p',
               quiet=True,
               stdout_=PIPE)
    proj=proj.outputs.stdout
    lines=proj.splitlines()
    for e,line in enumerate(lines):
        if 'EPSG' in line:
            epsg=lines[e+1].split(':')[1].replace(' ','')
            print('epsg=%s' % epsg)
            if flags['s']:
                if isPermanent():
                    writeEPSGtoPEMANENT(epsg)
                else:
                    grass.warning("Unable to access PERMANENT mapset")
            return
    try:
        proj=Module('g.proj',
               flags='wf',
               quiet=True,
               stdout_=PIPE)
        proj=proj.outputs.stdout
        wkt2standards(proj)
    except:
        grass.error('WKT input error')
Ejemplo n.º 8
0
def stats():
    print('-' * 80)
    print('NDVI class statistics')
    print('-' * 80)
    from subprocess import PIPE
    ret = Module('v.report',
                 map=options["output"],
                 option='area',
                 stdout_=PIPE)
    for line in ret.outputs.stdout.splitlines(
    )[1:]:  # skip first line (cat|label|area)
        # parse line (eg. 1||2712850)
        data = line.split('|')
        cat = data[0]
        area = float(data[-1])
        print('NDVI class {0}: {1:.1f} ha'.format(cat, area / 1e4))

    # v.to.rast: use -c flag for updating statistics if exists
    Module('v.rast.stats',
           flags='c',
           map=options["output"],
           raster='ndvi',
           column_prefix='ndvi',
           method=['minimum', 'maximum', 'average'])

    data = vector_db_select(options["output"])
    for vals in data['values'].itervalues():
        # unfortunately we need to cast values by float
        print('NDVI class {0}: {1:.4f} (min) {2:.4f} (max) {3:.4f} (mean)'.
              format(vals[0], float(vals[2]), float(vals[3]), float(vals[4])))
Ejemplo n.º 9
0
def main():
    #gscript.run_command('g.region', raster='dmt', flags='p')
    #gscript.run_command('r.univar', map='dmt')
    Module('g.region', raster='dmt', flags="p")
    print("-" * 60, "\n")
    Module("g.message", message="=" * 60)
    Module("r.univar", map="dmt")
Ejemplo n.º 10
0
def copy_vectors(vectors, gisrc_src, gisrc_dst):
    """Copy vectors from one mapset to another, crop the raster to the region.

    :param vectors: a list of strings with the vector map that must be copied
                    from a master to another.
    :type vectors: list
    :param gisrc_src: path of the GISRC file from where we want to copy the groups
    :type gisrc_src: str
    :param gisrc_dst: path of the GISRC file where the groups will be created
    :type gisrc_dst: str
    :returns: None
    """
    env = os.environ.copy()
    path_dst = os.path.join(*read_gisrc(gisrc_dst))
    nam = "copy%d__%s" % (id(gisrc_dst), "%s")

    # instantiate modules
    vpck = Module("v.pack")
    vupck = Module("v.unpack")
    remove = Module("g.remove")

    for vect in vectors:
        # change gisdbase to src
        env["GISRC"] = gisrc_src
        name = nam % vect
        file_dst = "%s.pack" % os.path.join(path_dst, name)
        vpck(input=name, output=file_dst, overwrite=True, env_=env)
        remove(flags="f", type="vector", name=name, env_=env)
        # change gisdbase to dst
        env["GISRC"] = gisrc_dst
        vupck(input=file_dst, output=vect, overwrite=True, env_=env)
        os.remove(file_dst)
Ejemplo n.º 11
0
def benchmark(memory, label, results, reference):

    slope = "benchmark_slope"
    aspect = "benchmark_aspect"
    pcurv = "benchmark_pcurv"
    tcurv = "benchmark_tcurv"

    module = Module(
        "r.slope.aspect",
        elevation=reference,
        slope=slope,
        aspect=aspect,
        pcurvature=pcurv,
        tcurvature=tcurv,
        run_=False,
        stdout_=DEVNULL,
        overwrite=True,
    )
    results.append(
        bm.benchmark_nprocs(module, label=label, max_nprocs=20, repeat=10))

    Module("g.remove", quiet=True, flags="f", type="raster", name=slope)
    Module("g.remove", quiet=True, flags="f", type="raster", name=aspect)
    Module("g.remove", quiet=True, flags="f", type="raster", name=pcurv)
    Module("g.remove", quiet=True, flags="f", type="raster", name=tcurv)
Ejemplo n.º 12
0
def main():
    mapset = Mapset()
    mapset.current()

    with open(options['output'], 'w') as fd:
        for rast in mapset.glist('raster', pattern='*_B04_10m'):
            items = rast.split('_')
            d = datetime.strptime(items[2], '%Y%m%dT%H%M%S')
            ## workaround
            dd = d + timedelta(seconds=1)

            vect = '{}_{}_MSK_CLOUDS'.format(items[1], items[2])
            mask_vect = '{}_{}'.format(vect, options['map'].split('@')[0])
            if Vector(vect).exist():
                Module('v.overlay',
                       ainput=options['map'],
                       binput=vect,
                       operator='not',
                       output=mask_vect)
            else:
                copy(options['map'], mask_vect, 'vector')
            Module('r.mask', vector=mask_vect, overwrite=True)
            Module('g.remove', flags='f', type='vector', name=mask_vect)
            Module('g.rename', raster=['MASK', mask_vect])
            fd.write("{0}|{1}|{2}{3}".format(mask_vect,
                                             d.strftime('%Y-%m-%d %H:%M:%S'),
                                             dd.strftime('%Y-%m-%d %H:%M:%S'),
                                             os.linesep))

    return 0
Ejemplo n.º 13
0
    def _handler(self, request, response):
        from subprocess import PIPE

        from grass.pygrass.modules import Module
        from grass.exceptions import CalledModuleError

        start = request.inputs['start'][0].data
        end = request.inputs['end'][0].data
        self.check_date(start)
        self.check_date(end)

        x, y = request.inputs['coords'][0].data.split(',')

        # be silent
        os.environ['GRASS_VERBOSE'] = '0'

        # need to set computation region (would be nice g.region strds or t.region)
        Module('g.region', raster='c_001')
        try:
            ret = Module(
                't.rast.what',
                stdout_=PIPE,
                strds='modis_c@PERMANENT',
                coordinates=[x, y],
                separator=',',
                where="start_time > '{start}' and start_time < '{end}'".format(
                    start=start, end=end))
        except CalledModuleError:
            raise Exception('Unable to compute statistics')

        tsum = 0
        stats = {
            'min': None,
            'max': None,
            'mean': None,
            'count': 0,
        }
        count = 0
        for line in ret.outputs.stdout.splitlines():
            items = line.split(',')
            if items[-1] == '*':  # no data
                continue
            val = float(items[-1])
            if stats['min'] is None:
                stats['min'] = stats['max'] = stats['mean'] = val
            else:
                if val < stats['min']:
                    stats['min'] = val
                if val > stats['max']:
                    stats['max'] = val
            tsum += val
            stats['count'] += 1

        stats['mean'] = tsum / stats['count']

        response.outputs['stats'].data = json.dumps(stats)

        return response
Ejemplo n.º 14
0
def patch_tiles(maps, output, resolution):
    gs.message("Patching tiles <{}>...".format(','.join(maps)))
    Module('g.region', raster=maps, res=resolution)
    Module('r.series',
           input=maps,
           output=output,
           method='average',
           overwrite=True)
    Module('r.colors', map=output, color='elevation')
Ejemplo n.º 15
0
def generate_map(rows, cols, fname):
    Module("g.region", flags="p", s=0, n=rows, w=0, e=cols, res=1)
    # Generate using r.random.surface if r.surf.fractal fails
    try:
        print("Generating reference map using r.surf.fractal...")
        Module("r.surf.fractal", output=fname)
    except CalledModuleError:
        print("r.surf.fractal fails, using r.random.surface instead...")
        Module("r.random.surface", output=fname)
Ejemplo n.º 16
0
def get_zones(vector, zones, layer=1, overwrite=False):
    v2rast = Module('v.to.rast',
                    input=vector,
                    layer=str(layer),
                    type='area',
                    output=zones,
                    overwrite=overwrite,
                    rows=65536,
                    use='cat')
    rclr = Module("r.colors", map=zones, color="random")
Ejemplo n.º 17
0
    def _handler(self, request, response):
        from subprocess import PIPE

        import grass.script as gs
        from grass.pygrass.modules import Module
        from grass.exceptions import CalledModuleError

        start1 = request.inputs['start1'][0].data
        end1 = request.inputs['end1'][0].data
        self.check_date(start1)
        self.check_date(end1)

        start2 = request.inputs['start2'][0].data
        end2 = request.inputs['end2'][0].data
        self.check_date(start2)
        self.check_date(end2)

        output1 = 'stcVH'
        output2 = 'stcVV'

        # be silent
        os.environ['GRASS_VERBOSE'] = '0'

        try:
            Module(
                't.rast.series',
                input='stcubeVH@PERMANENT',
                output=output1,
                method='average',
                where="start_time > '{start}' and start_time < '{end}'".format(
                    start=start1, end=end1))
            Module(
                't.rast.series',
                input='stcubeVV@PERMANENT',
                output=output2,
                method='average',
                where="start_time > '{start}' and start_time < '{end}'".format(
                    start=start2, end=end2))

        except CalledModuleError:
            raise Exception('Unable to compute statistics')

        ret = Module('r.univar', flags='g', map=output1, stdout_=PIPE)
        ret2 = Module('r.univar', flags='g', map=output2, stdout_=PIPE)
        stats1 = gs.parse_key_val(ret.outputs.stdout)
        stats2 = gs.parse_key_val(ret2.outputs.stdout)

        outstr1 = 'Min1: {0:.1f};Max1: {1:.1f};Mean1: {2:.1f}'.format(
            float(stats1['min']), float(stats1['max']), float(stats1['mean']))
        outstr2 = 'Min2: {0:.1f};Max2: {1:.1f};Mean2: {2:.1f}'.format(
            float(stats2['min']), float(stats2['max']), float(stats2['mean']))
        response.outputs['stats1'].data = outstr1
        response.outputs['stats2'].data = outstr2

        return response
Ejemplo n.º 18
0
def viewshed(vrt,list_of_dicts,distance,point,
             observer_height,grassdb,burn_viewshed_rst,total_cells_output):
    ## deles op - foerste funktion
    with rasterio.open(vrt) as src_rst:

        dsm = src_rst.read()
        out_meta = src_rst.meta.copy()
        print(out_meta)
        out_meta.update(dtype=rasterio.int16,driver='GTiff') 
        mask = features.geometry_mask(
                                      [feature["feature"]["geometry"] for feature in
                                       list_of_dicts],
                                       src_rst.shape,
                                       transform=src_rst.transform,
                                       all_touched=True, 
                                       invert=True)
        new_dsm = np.copy(np.squeeze(dsm)) #Forstaer ikke hvorfor, men dsm'en har en ekstra dimension, 
                                           #som jeg fjerner med squeeze, saa den passer med result dsm'en
    ## deles op - anden funktion, maaske
        with rasterio.Env():
            result = features.rasterize(
                                        ((feature['feature']['geometry'],np.int(feature['feature']['properties']['hoejde'])
                                         * 1000)
                                          for feature in list_of_dicts), 
                                          out_shape=src_rst.shape,
                                          transform=src_rst.transform,
                                          all_touched=True)             
            new_dsm[mask] = result[mask] 

    ## deles op - tredje funktion
            with Session(gisdb=grassdb, location="test",create_opts=vrt):
                import grass.script.array as garray
                r_viewshed = Module('r.viewshed')
                r_out_gdal = Module('r.out.gdal')
                r_stats = Module('r.stats')
                r_univar = Module('r.univar')
                from_np_raster = garray.array()
                from_np_raster[...] = new_dsm
                from_np_raster.write('ny_rast',overwrite=True)
                print(from_np_raster)
                gcore.run_command('r.viewshed', overwrite=True, memory=2000, 
		input='ny_rast', output='viewshed', max_distance=distance, 
		coordinates=point, observer_elevation=observer_height)
                r_stats(flags='nc',overwrite=True,input='viewshed',output=total_cells_output)
                ## finde ud af hvordan r_stats kan outputte til noget som
                ## python kan laese direkte
                with open(total_cells_output) as tcls:
                    counts = []
                    for line in tcls:
                        nbr = int(line.split()[-1])
                        counts.append(nbr)
                # summary = r_univar(map='viewshed')
                #r_viewshed(input=from_np_raster, output='viewshed', max_distance=1000, memory=1424, coordinates=(701495,6201503), observer_elevation=500.0)
                r_out_gdal(overwrite=True, input='viewshed', output=burn_viewshed_rst)
    return sum(counts) #visible_cells
Ejemplo n.º 19
0
def load_tests(loader, tests, ignore):
    # TODO: this must be somewhere when doctest is called, not here
    # TODO: ultimate solution is not to use _ as a buildin in lib/python
    # for now it is the only place where it works
    grass.gunittest.utils.do_doctest_gettext_workaround()
    # this should be called at some top level

    from grass.pygrass.modules import Module

    Module("g.region", n=40, s=0, e=40, w=0, res=10)
    Module(
        "r.mapcalc",
        expression="%s = row() + (10 * col())" % (pgrass.test_raster_name),
        overwrite=True,
    )
    Module(
        "r.support",
        map=pgrass.test_raster_name,
        title="A test map",
        history="Generated by r.mapcalc",
        description="This is a test map",
    )
    cats = """11:A
            12:B
            13:C
            14:D
            21:E
            22:F
            23:G
            24:H
            31:I
            32:J
            33:K
            34:L
            41:M
            42:n
            43:O
            44:P"""
    Module("r.category",
           rules="-",
           map=pgrass.test_raster_name,
           stdin_=cats,
           separator=":")

    Module(
        "r.mapcalc",
        expression="%s = row() + (10 * col())" %
        (pgrass.abstract.test_raster_name),
        overwrite=True,
    )

    tests.addTests(doctest.DocTestSuite(pgrass))
    tests.addTests(doctest.DocTestSuite(pgrass.abstract))
    return tests
Ejemplo n.º 20
0
def clip(inFeat, clipFeat, outFeat, api_gis="grass", clip_by_region=None):
    """
    Clip Analysis
    
    api_gis Options:
    * grass
    * pygrass
    * ogr2ogr
    """

    if api_gis == "pygrass":
        from grass.pygrass.modules import Module

        if not clip_by_region:
            vclip = Module("v.clip",
                           input=inFeat,
                           clip=clipFeat,
                           output=outFeat,
                           overwrite=True,
                           run_=False,
                           quiet=True)
        else:
            vclip = Module("v.clip",
                           input=inFeat,
                           output=outFeat,
                           overwrite=True,
                           flags='r',
                           run_=False,
                           quiet=True)

        vclip()

    elif api_gis == "grass":
        from gasp import exec_cmd

        rcmd = exec_cmd(
            "v.clip input={}{} output={} {}--overwrite --quiet".format(
                inFeat, " clip={}".format(clipFeat) if clipFeat else "",
                outFeat, "-r " if not clipFeat else ""))

    elif api_gis == 'ogr2ogr':
        from gasp import exec_cmd
        from gasp.pyt.oss import fprop
        from gasp.gt.prop.ff import drv_name

        rcmd = exec_cmd(
            ("ogr2ogr -f \"{}\" {} {} -clipsrc {} -clipsrclayer {}").format(
                drv_name(outFeat), outFeat, inFeat, clipFeat,
                fprop(clipFeat, 'fn')))

    else:
        raise ValueError("{} is not available!".format(api_gis))

    return outFeat
Ejemplo n.º 21
0
def convert_maps(base, date=None, year=None, month=None, startnum=1, log=None):
    """Convert the data if needed, like temperature from kelvin to celsius"""
    if isinstance(date, datetime):
        mydat = deepcopy(date)
    elif year and month:
        mydat = datetime(year, month, 1, 0, 0)
    else:
        print("Please set date or year with or without month")
        sys.exit(1)
    if not date:
        date = datetime(year, month, 1, 0, 0)
    if log:
        fi = open(log, 'w')
    Module("g.region", raster="{ba}_{mo}.{im}".format(ba=base, im=startnum,
                                                      mo=date.strftime("%Y_%m")))
    for do in range(startnum, 745):
        out = "{ba}_{da}".format(ba=base, da=mydat.strftime("%Y_%m_%d_%H"))
        inn = "{ba}_{mo}.{im}".format(ba=base, mo=date.strftime("%Y_%m"),
                                      im=do)
        try:
            r = RasterRow(inn)
            r.open()
            r.close()
        except:
            continue
        if base == 'T_2M':
            try:
                mapc = Module("r.mapcalc", expression="{ou} = {inn} - "
                              "273.15".format(ou=out, inn=inn),
                              stdout_=PIPE, stderr_=PIPE)
                if log:
                    if mapc.outputs.stdout:
                        fi.write("{}\n".format(mapc.outputs.stdout))
                    if mapc.outputs.stderr:
                        fi.write("{}\n".format(mapc.outputs.stderr))
                Module("g.remove", type="raster", name=inn, flags="f")
            except CalledModuleError:
                continue
        elif base == 'TOT_PRECIP':
            try:
                mapc = Module("r.mapcalc", expression="{ou} = if({inn} < 0, 0,"
                              " {inn})".format(ou=out, inn=inn),
                              stdout_=PIPE, stderr_=PIPE)
                if log:
                    if mapc.outputs.stdout:
                        fi.write("{}\n".format(mapc.outputs.stdout))
                    if mapc.outputs.stderr:
                        fi.write("{}\n".format(mapc.outputs.stderr))
                Module("g.remove", type="raster", name=inn, flags="f")
            except CalledModuleError:
                continue
        mydat = mydat + timedelta(seconds=3600)
    if log:
        fi.close()
Ejemplo n.º 22
0
def get_zones(vector, zones, layer=1, overwrite=False):
    v2rast = Module(
        "v.to.rast",
        input=vector,
        layer=str(layer),
        type="area",
        output=zones,
        overwrite=overwrite,
        use="cat",
    )
    rclr = Module("r.colors", map=zones, color="random")
Ejemplo n.º 23
0
    def _get_streamlist(self, stream):
        """Compute shape of stream.

        :param stream:
        """
        Module(
            'db.copy',
            from_table=self.tab_stream_shape,
            from_database='$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db',
            to_table='stream_shape')

        # TODO: (check if smoderp column exists)
        sfields = ["number", "shapetype", "b", "m", "roughness", "q365"]
        try:
            self._join_table(stream, self.tab_stream_shape_code,
                             'stream_shape', self.tab_stream_shape_code,
                             sfields)
        except:
            self._add_field(stream, "smoderp", "TEXT", "0")
            self._join_table(stream, self.tab_stream_shape_code,
                             'stream_shape', self.tab_stream_shape_code,
                             sfields)

        sfields.insert(1, "smoderp")
        # TODO: rewrite into pygrass syntax
        ret = Module('v.db.select',
                     flags='c',
                     map=stream,
                     columns=sfields,
                     stdout_=PIPE)
        for row in ret.outputs.stdout.splitlines():
            for value in row.split('|'):
                if value == '':
                    raise StreamPreparationError(
                        "Empty value in {} found.".format(stream))

        with Vector(stream) as data:
            self.field_names = data.table.columns.names()
        self.stream_tmp = [[] for field in self.field_names]

        # TODO: rewrite into pygrass syntax
        ret = Module('v.db.select',
                     flags='c',
                     map=stream,
                     columns=self.field_names,
                     stdout_=PIPE)
        for row in ret.outputs.stdout.splitlines():
            i = 0
            for val in row.split('|'):
                self.stream_tmp[i].append(float(val))
                i += 1

        self.streamlist = []
        self._streamlist()
Ejemplo n.º 24
0
def import_shapefile(path_to_shape, shapename, overwrite_bool):
    """
    imports the boundary of the area of investigation
    :param path_to_shape: string
        Path to folder, where the shapefile is
    :param overwrite_bool: bool
        Option of True or False, but True is strongly recommended!
    :return:
    """
    ogrimport = Module("v.in.ogr")
    ogrimport(path_to_shape, overwrite=overwrite_bool)

    showregion = Module("g.region")
    showregion(flags='p', overwrite=overwrite_bool, vector=shapename)
Ejemplo n.º 25
0
    def obce_psc(self, psc):
        map_name = 'obce_psc_{}'.format(psc)

        Module('v.extract',
               input='obce',
               output='obce1',
               where="psc = '{}'".format(psc))
        Module('v.select',
               ainput='obce',
               binput='obce1',
               output=map_name,
               operator='overlap',
               overwrite=True)

        return map_name
Ejemplo n.º 26
0
def benchmark(memory, label, results, reference):
    output = "benchmark_r_neighbors_nprocs"

    module = Module(
        "r.neighbors",
        input=reference,
        output=output,
        size=9,
        memory=memory,
        run_=False,
        stdout_=DEVNULL,
        overwrite=True,
    )
    results.append(bm.benchmark_nprocs(module, label=label, max_nprocs=16, repeat=3))
    Module("g.remove", quiet=True, flags="f", type="raster", name=output)
Ejemplo n.º 27
0
def convert(inLyr, outLyr, geom_type=None):
    """
    Add or export data from/to GRASS GIS
    """
    
    import os
    
    
    if os.path.splitext(inLyr)[1] in VectorialDrivers():
        inOrOut = 'import'
        data = 'vector'
    
    elif os.path.splitext(inLyr)[1] in RasterDrivers():
        inOrOut = 'import'
        data = 'raster'
    
    else:
        outFormat = os.path.splitext(outLyr)[1]
        inOrOut = 'export'
        if outFormat in VectorialDrivers():    
            data = 'vector'
        elif outFormat in RasterDrivers():
            data = 'raster'
        else:
            raise ValueError(
                "Not possible to identify if you want export or import data"
            )
    
    #*************************************************************************#
    if data == 'vector':
        if inOrOut == 'import':
            m = Module('v.in.ogr', input=inLyr, output=outLyr, flags='o',
                       overwrite=True, run_=False, quiet=True)
        elif inOrOut == 'export':
            m = Module('v.out.ogr', input=inLyr, type=geom_type, output=outLyr,
                       format=VectorialDrivers()[outFormat],
                       overwrite=True, run_=False, quiet=True)
    
    elif data == 'raster':
        if inOrOut == 'import':
            m = Module("r.in.gdal", input=inLyr, output=outLyr, flags='o',
                       overwrite=True, run_=False, quiet=True)
        elif inOrOut == 'export':
            m = Module("r.out.gdal", input=inLyr, output=outLyr,
                       format=RasterDrivers()[outFormat],
                       overwrite=True, run_=False, quiet=True)
    
    m()
Ejemplo n.º 28
0
Archivo: cp.py Proyecto: jasp382/glass
def copy_insame_vector(inShp,
                       colToBePopulated,
                       srcColumn,
                       destinyLayer,
                       geomType="point,line,boundary,centroid",
                       asCMD=None):
    """
    Copy Field values from one layer to another in the same GRASS Vector
    """

    if not asCMD:
        from grass.pygrass.modules import Module

        vtodb = Module("v.to.db",
                       map=inShp,
                       layer=destinyLayer,
                       type=geomType,
                       option="query",
                       columns=colToBePopulated,
                       query_column=srcColumn,
                       run_=False,
                       quiet=True)

        vtodb()

    else:
        from glass.pys import execmd

        rcmd = execmd(
            ("v.to.db map={} layer={} type={} option=query columns={} "
             "query_column={} --quiet").format(inShp, destinyLayer, geomType,
                                               colToBePopulated, srcColumn))
Ejemplo n.º 29
0
def stats(output, date, fd):
    fd.write('-' * 80)
    fd.write(os.linesep)
    fd.write('NDVI class statistics ({0}: {1})'.format(output, date))
    fd.write(os.linesep)
    fd.write('-' * 80)
    fd.write(os.linesep)
    from subprocess import PIPE
    ret = Module('v.report', map=output, option='area', stdout_=PIPE)
    for line in ret.outputs.stdout.splitlines(
    )[1:]:  # skip first line (cat|label|area)
        # parse line (eg. 1||2712850)
        data = line.split('|')
        cat = data[0]
        area = float(data[-1])
        fd.write('NDVI class {0}: {1:.1f} ha'.format(cat, area / 1e4))
        fd.write(os.linesep)

    data = vector_db_select(output)
    for vals in data['values'].values():
        # unfortunately we need to cast values by float
        fd.write('NDVI class {0}: {1:.4f} (min) {2:.4f} (max) {3:.4f} (mean)'.
                 format(vals[0], float(vals[2]), float(vals[3]),
                        float(vals[4])))
        fd.write(os.linesep)
Ejemplo n.º 30
0
def grs_to_rst(grsRst, rst, as_cmd=None, allBands=None):
    """
    GRASS Raster to Raster
    """
    
    from gasp.prop.ff import RasterDrivers
    from gasp.oss     import get_fileformat
    
    rstDrv = RasterDrivers()
    rstExt = get_fileformat(rst)
    
    if not as_cmd:
        from grass.pygrass.modules import Module
        
        m = Module(
            "r.out.gdal", input=grsRst, output=rst,
            format=rstDrv[rstExt], flags='c' if not allBands else '',
            createopt="INTERLEAVE=PIXEL,TFW=YES" if allBands else '',
            overwrite=True, run_=False, quiet=True
        )
        
        m()
    
    else:
        from gasp import exec_cmd
        
        rcmd = exec_cmd((
            "r.out.gdal input={} output={} format={} "
            "{} --overwrite --quiet"
        ).format(
            grsRst, rst, rstDrv[rstExt],
            "-c" if not allBands else "createopt=\"INTERLEAVE=PIXEL,TFW=YES\""
        ))
    
    return rst