Ejemplo n.º 1
0
    def set_region_from_raster(self, raster):
        """Sets computational region for rendering.

        This functions sets computational region based on
        a raster map in the target environment.

        If user specified the name of saved region during object's initialization,
        the provided region is used. If it's not specified
        and use_region=True, current region is used.

        Also enlarges bounding box based on the raster.
        """
        if self._saved_region:
            self._src_env["GRASS_REGION"] = gs.region_env(
                region=self._saved_region, env=self._src_env)
        elif self._use_region:
            # use current
            self._set_bbox(self._src_env)
            return
        else:
            self._src_env["GRASS_REGION"] = gs.region_env(raster=raster,
                                                          env=self._src_env)
        region = get_region(env=self._src_env)
        from_proj = get_location_proj_string(self._src_env)
        to_proj = get_location_proj_string(env=self._tgt_env)
        new_region = reproject_region(region, from_proj, to_proj)
        gs.run_command(
            "g.region",
            n=new_region["north"],
            s=new_region["south"],
            e=new_region["east"],
            w=new_region["west"],
            env=self._tgt_env,
        )
        self._set_bbox(self._src_env)
Ejemplo n.º 2
0
    def set_region_from_timeseries(self, timeseries):
        """Sets computational region for rendering.

        This function sets the computation region from the extent of
        a space-time dataset by using its bounding box and resolution.

        If user specified the name of saved region during object's initialization,
        the provided region is used. If it's not specified
        and use_region=True, current region is used.
        """
        if self._saved_region:
            self._env["GRASS_REGION"] = gs.region_env(
                region=self._saved_region, env=self._env)
            return
        if self._use_region:
            # use current
            return
        # Get extent, resolution from space time dataset
        info = gs.parse_command("t.info",
                                input=timeseries,
                                flags="g",
                                env=self._env)
        # Set grass region from extent
        self._env["GRASS_REGION"] = gs.region_env(
            n=info["north"],
            s=info["south"],
            e=info["east"],
            w=info["west"],
            nsres=info["nsres_min"],
            ewres=info["ewres_min"],
        )
Ejemplo n.º 3
0
    def set_region_from_command(self, env, **kwargs):
        """Sets computational region for rendering.

        This functions identifies a raster map from m.nviz.image command
        and tries to set computational region based on that.

        If user specified the name of saved region during object's initialization,
        the provided region is used. If it's not specified
        and use_region=True, current region is used.
        """
        if self._saved_region:
            env["GRASS_REGION"] = gs.region_env(region=self._saved_region,
                                                env=env)
            self._region_set = True
            return
        if self._use_region:
            # use current
            return
        if self._region_set:
            return
        if "elevation_map" in kwargs:
            elev = kwargs["elevation_map"].split(",")[0]
            try:
                env["GRASS_REGION"] = gs.region_env(raster=elev, env=env)
                self._region_set = True
            except CalledModuleError:
                return
Ejemplo n.º 4
0
    def ImportMapIntoGRASS(self, raster):
        """!Import raster into GRASS.
        """
        # importing temp_map into GRASS
        try:
            # -o flag needed to overcome different ellipsoid representations
            grass.run_command('r.in.gdal', flags='o',
                              quiet=True, overwrite=True,
                              input=raster, output=self.opt_output)
        except CalledModuleError:
            grass.fatal(_('%s failed') % 'r.in.gdal')

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

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

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

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

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

        grass.message(_('<%s> created.') % self.opt_output)
Ejemplo n.º 5
0
    def OnReproject(self, event):
        cmd = []
        if self.etype == 'raster':
            cmd.append('r.proj')
            cmd.append('dbase=' + self.iGisdbase)
            cmd.append('location=' + self.iLocation)
            cmd.append('mapset=' + self.iMapset)
            cmd.append('input=' + self.iLayer)
            cmd.append('output=' + self.oLayer)
            cmd.append('method=' + self.resampling.GetStringSelection())

            self.oEnv['GRASS_REGION'] = region_env(n=self.params['n'], s=self.params['s'],
                                                   e=self.params['e'], w=self.params['w'],
                                                   flags='a', res=float(self.resolution.GetValue()),
                                                   env=self.oEnv)
        else:
            cmd.append('v.proj')
            cmd.append('dbase=' + self.iGisdbase)
            cmd.append('location=' + self.iLocation)
            cmd.append('mapset=' + self.iMapset)
            cmd.append('input=' + self.iLayer)
            cmd.append('output=' + self.oLayer)
            cmd.append('smax=' + self.vsplit.GetValue())

        self._giface.RunCmd(cmd, env=self.oEnv, compReg=False, addLayer=False,
                            onDone=self._onDone, userData=None,
                            notification=Notification.MAKE_VISIBLE)

        event.Skip()
Ejemplo n.º 6
0
def indicatrix(raster, size):
    env = os.environ.copy()
    env['GRASS_OVERWRITE'] = '1'
    env['GRASS_VERBOSE'] = '0'
    env['GRASS_REGION'] = gscript.region_env(raster=raster)
    info = gscript.raster_info(raster)
    number = [3, 5]
    ew = info['east'] - info['west']
    ns = info['north'] - info['south']
    ew_step = ew / float(number[0] + 1)
    ns_step = ns / float(number[1] + 1)
    name = raster + '_indicatrix'
    circle_tmp = 'tmp_circle'
    circle_tmp2 = 'tmp_circle2'
    gscript.mapcalc('{} = null()'.format(circle_tmp2), overwrite=True)
    for i in range(number[0]):
        for j in range(number[1] - 1):
            gscript.run_command('r.circle', output=circle_tmp, min=size, max=size + 1, flags='b',
                                coordinates=[info['west'] + (i + 1) * ew_step, info['south'] + (j + 1) * ns_step],
                                env=env)
            gscript.run_command('r.patch', input=[circle_tmp, circle_tmp2], output=name, env=env)
            gscript.run_command('g.copy', raster=[name, circle_tmp2], env=env)

    gscript.run_command('r.to.vect', input=name, output=name, type='line', flags='vt', env=env)
    gscript.run_command('g.remove', type='raster', flags='f', name=[circle_tmp, circle_tmp2], env=env)
    return name
Ejemplo n.º 7
0
 def set_bbox_vector(self, vector):
     """Enlarge bounding box based on vector"""
     if self._saved_region or self._use_region:
         return
     env = self._src_env.copy()
     env["GRASS_REGION"] = gs.region_env(vector=vector, env=env)
     self._set_bbox(env)
Ejemplo n.º 8
0
    def ImportMapIntoGRASS(self, raster): 
        """!Import raster into GRASS.
        """

        grass.message(_("Importing raster map into GRASS..."))

        if not raster:
            grass.warning(_("Nothing to import.\nNo data has been downloaded from wms server."))
            return

        # importing temp_map into GRASS
        if grass.run_command('r.in.gdal',
                             quiet = True,
                             input = raster,
                             output = self.opt_output) != 0:
            grass.fatal(_('%s failed') % 'r.in.gdal')
        
        # information for destructor to cleanup temp_layers, created
        # with r.in.gdal
        self.cleanup_layers = True
        
        # setting region for full extend of imported raster
        if grass.find_file(self.opt_output + '.red', element = 'cell', mapset = '.')['file']:
            region_map = self.opt_output + '.red'
        else:
            region_map = self.opt_output
        os.environ['GRASS_REGION'] = grass.region_env(rast = region_map)
          
        # mask created from alpha layer, which describes real extend
        # of warped layer (may not be a rectangle), also mask contains
        # transparent parts of raster
        if grass.find_file( self.opt_output + '.alpha', element = 'cell', mapset = '.' )['name']:
            # saving current mask (if exists) into temp raster
            if grass.find_file('MASK', element = 'cell', mapset = '.' )['name']:
                if grass.run_command('g.copy',
                                     quiet = True,
                                     rast = 'MASK,' + self.opt_output + self.original_mask_suffix) != 0:    
                    grass.fatal(_('%s failed') % 'g.copy')
            
            # info for destructor
            self.cleanup_mask = True
            if grass.run_command('r.mask',
                                 quiet = True,
                                 overwrite = True,
                                 maskcats = "0",
                                 flags = 'i',
                                 input = self.opt_output + '.alpha') != 0: 
                grass.fatal(_('%s failed') % 'r.mask')
        
        #TODO one band + alpha band?
        if grass.find_file(self.opt_output + '.red', element = 'cell', mapset = '.')['file']:
            if grass.run_command('r.composite',
                                 quiet = True,
                                 red = self.opt_output + '.red',
                                 green = self.opt_output +  '.green',
                                 blue = self.opt_output + '.blue',
                                 output = self.opt_output ) != 0:
                grass.fatal(_('%s failed') % 'r.composite')

        grass.message(_('<%s> created.') % self.opt_output)
Ejemplo n.º 9
0
    def set_region_from_raster(self, raster):
        """Sets computational region for rendering.

        This functions sets computational region based on
        a raster map in the target environment.

        If user specified the name of saved region during object's initialization,
        the provided region is used. If it's not specified
        and use_region=True, current region is used.

        Also enlarges bounding box based on the raster.
        """
        if self._use_region or self._saved_region:
            # target region and bbox already set
            return
        # set target location region extent
        self._src_env["GRASS_REGION"] = gs.region_env(raster=raster,
                                                      env=self._src_env)
        set_target_region(src_env=self._src_env, tgt_env=self._tgt_env)
        # set resolution based on r.proj estimate
        env_info = gs.gisenv(env=self._src_env)
        name, mapset = raster.split("@")
        self._resolution = estimate_resolution(
            raster=name,
            mapset=mapset,
            location=env_info["LOCATION_NAME"],
            dbase=env_info["GISDBASE"],
            env=self._tgt_env,
        )
        self._set_bbox(self._src_env)
Ejemplo n.º 10
0
    def __init__(self, use_region, saved_region, src_env, tgt_env):
        """Manages region during rendering for interactive map.

        :param use_region: if True, use either current or provided saved region,
                          else derive region from rendered layers
        :param saved_region: if name of saved_region is provided,
                            this region is then used for rendering
        :param src_env: source environment (original projection)
        :param tgt_env: target environment (pseudomercator)
        """
        self._use_region = use_region
        self._saved_region = saved_region
        self._src_env = src_env
        self._tgt_env = tgt_env
        self._resolution = None
        # [SW, NE]: inverted to easily expand based on data, see _set_bbox
        self._bbox = [[90, 180], [-90, -180]]
        if self._use_region:
            # tgt region already set, set resolution
            self._resolution = self._get_psmerc_region_resolution()
            self._set_bbox(self._src_env)
        if self._saved_region:
            self._src_env["GRASS_REGION"] = gs.region_env(
                region=self._saved_region, env=self._src_env)
            set_target_region(src_env=self._src_env, tgt_env=self._tgt_env)
            self._resolution = self._get_psmerc_region_resolution()
            self._set_bbox(self._src_env)
Ejemplo n.º 11
0
def function(elemns):
 elem = str(elemns)
 outf='res_'+str(elem)+'.txt'
 os.environ['GRASS_REGION'] = grass.region_env(res=elem)
 #varx = grass.read_command ('g.region',flags='g'). splitlines ()
 grass.run_command('r.univar',map='elevation',flags='g',out=outf,overwrite=True)
 os.environ.pop('GRASS_REGION')
Ejemplo n.º 12
0
    def ImportMapIntoGRASS(self, raster): 
        """!Import raster into GRASS.
        """
        # importing temp_map into GRASS
        try:
            grass.run_command('r.in.gdal',
                              quiet=True, overwrite=True,
                              input=raster, output=self.opt_output)
        except CalledModuleError:
            grass.fatal(_('%s failed') % 'r.in.gdal')

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

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

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

        grass.message(_('<%s> created.') % self.opt_output)
Ejemplo n.º 13
0
    def ImportMapIntoGRASS(self, raster):
        """!Import raster into GRASS.
        """
        # importing temp_map into GRASS
        if grass.run_command("r.in.gdal", quiet=True, overwrite=True, input=raster, output=self.opt_output) != 0:
            grass.fatal(_("%s failed") % "r.in.gdal")

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

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

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

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

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

        grass.message(_("<%s> created.") % self.opt_output)
Ejemplo n.º 14
0
    def set_region_from_command(self, module, **kwargs):
        """Sets computational region for rendering.

        This functions identifies a raster/vector map from command
        and tries to set computational region based on that.
        It takes the extent from the first layer (raster or vector)
        and resolution and alignment from first raster layer.

        If user specified the name of saved region during object's initialization,
        the provided region is used. If it's not specified
        and use_region=True, current region is used.
        """
        if self._saved_region:
            self._env["GRASS_REGION"] = gs.region_env(
                region=self._saved_region, env=self._env)
            return
        if self._use_region:
            # use current
            return
        if self._resolution_set and self._extent_set:
            return
        name = get_map_name_from_d_command(module, **kwargs)
        if not name:
            return
        if len(name.split()) > 1:
            name = name.split()[0]
        try:
            if module.startswith("d.vect"):
                if not self._resolution_set and not self._extent_set:
                    self._env["GRASS_REGION"] = gs.region_env(vector=name,
                                                              env=self._env)
                    self._extent_set = True
            else:
                if not self._resolution_set and not self._extent_set:
                    self._env["GRASS_REGION"] = gs.region_env(raster=name,
                                                              env=self._env)
                    self._extent_set = True
                    self._resolution_set = True
                elif not self._resolution_set:
                    self._env["GRASS_REGION"] = gs.region_env(align=name,
                                                              env=self._env)
                    self._resolution_set = True
        except CalledModuleError:
            return
Ejemplo n.º 15
0
def function(elemns):
    elem = str(elemns)
    outf = 'res_' + str(elem) + '.txt'
    os.environ['GRASS_REGION'] = grass.region_env(res=elem)
    #varx = grass.read_command ('g.region',flags='g'). splitlines ()
    grass.run_command('r.univar',
                      map='elevation',
                      flags='g',
                      out=outf,
                      overwrite=True)
    os.environ.pop('GRASS_REGION')
Ejemplo n.º 16
0
def futures_process(params):
    repeat, seed, cat, options = params
    try:
        if cat:
            gscript.message(_("Running simulation {s}/{r} for subregion {sub}".format(s=seed, r=repeat, sub=cat)))
            env = os.environ.copy()
            env['GRASS_REGION'] = gscript.region_env(raster=PREFIX + cat, zoom=PREFIX + cat)
            gscript.run_command('r.futures.pga', env=env, **options)
        else:
            gscript.message(_("Running simulation {s}/{r}".format(s=seed, r=repeat)))
            gscript.run_command('r.futures.pga', **options)
    except (KeyboardInterrupt, CalledModuleError):
        return
Ejemplo n.º 17
0
def compute(params):
    env = os.environ.copy()
    region = params.pop("region")
    env["GRASS_REGION"] = gs.region_env(**region)
    results = gs.read_command("r.futures.validation",
                              format="json",
                              env=env,
                              quiet=True,
                              **params)
    results = json.loads(results)
    reg = gs.region(env=env)
    results["n"] = (reg["n"] + reg["s"]) / 2
    results["e"] = (reg["e"] + reg["w"]) / 2
    return results
Ejemplo n.º 18
0
def get_environment(**kwargs):
    """!Returns environment for running modules.
    All modules for which region is important should
    pass this environment into run_command or similar.

    @param tmp_regions a list of temporary regions
    @param kwargs arguments for g.region

    @return environment as a dictionary
    """
    env = os.environ.copy()
    env['GRASS_OVERWRITE'] = '1'
    env['GRASS_VERBOSE'] = '0'
    env['GRASS_MESSAGE_FORMAT'] = 'standard'
    env['GRASS_REGION'] = gscript.region_env(**kwargs)
    return env
def get_environment(**kwargs):
    """!Returns environment for running modules.
    All modules for which region is important should
    pass this environment into run_command or similar.

    @param tmp_regions a list of temporary regions
    @param kwargs arguments for g.region

    @return environment as a dictionary
    """
    env = os.environ.copy()
    env['GRASS_OVERWRITE'] = '1'
    env['GRASS_VERBOSE'] = '0'
    env['GRASS_MESSAGE_FORMAT'] = 'standard'
    env['GRASS_REGION'] = gscript.region_env(**kwargs)
    return env
def getEnvironment(gisdbase, location, mapset):
    """Creates an environment to be passed in run_command.
    Returns a tuple with a temporary file path and an environment.
    The user should delete this temporary file."""
    tmp_gisrc_file = gscript.tempfile()
    with open(tmp_gisrc_file, 'w') as f:
        f.write('MAPSET: {mapset}\n'.format(mapset=mapset))
        f.write('GISDBASE: {g}\n'.format(g=gisdbase))
        f.write('LOCATION_NAME: {l}\n'.format(l=location))
        f.write('GUI: text\n')
    env = os.environ.copy()
    env['GISRC'] = tmp_gisrc_file
    env['GRASS_REGION'] = gscript.region_env(raster=region, res=res)
    env['GRASS_OVERWRITE'] = '1'
    env['GRASS_VERBOSE'] = '0'
    env['GRASS_MESSAGE_FORMAT'] = 'standard'
    return tmp_gisrc_file, env
Ejemplo n.º 21
0
def getEnvironment(gisdbase, location, mapset):
    """Creates environment to be passed in run_command for example.
    Returns tuple with temporary file path and the environment. The user
    of this function is responsile for deleting the file."""
    tmp_gisrc_file = gscript.tempfile()
    with open(tmp_gisrc_file, 'w') as f:
        f.write('MAPSET: {mapset}\n'.format(mapset=mapset))
        f.write('GISDBASE: {g}\n'.format(g=gisdbase))
        f.write('LOCATION_NAME: {l}\n'.format(l=location))
        f.write('GUI: text\n')
    env = os.environ.copy()
    env['GISRC'] = tmp_gisrc_file
    env['GRASS_REGION'] = gscript.region_env(raster='elevation_2004@PERMANENT')
    env['GRASS_OVERWRITE'] = '1'
    env['GRASS_VERBOSE'] = '0'
    env['GRASS_MESSAGE_FORMAT'] = 'standard'
    return tmp_gisrc_file, env
Ejemplo n.º 22
0
def run_process(seg_cat, segments, nodes_by_id, railroads):
    cells = {}
    env = os.environ.copy()
    node_id = segments[seg_cat][0]
    print(seg_cat)
    gs.run_command(
        "v.to.rast",
        input=railroads + "_simplified",
        quiet=True,
        type="line",
        cats=seg_cat,
        output=railroads + "_segment_" + str(seg_cat),
        use="val",
    )
    gs.run_command(
        "r.patch",
        input=[railroads + "_segment_" + str(seg_cat), railroads + "_nodes"],
        output=railroads + "_" + str(seg_cat),
        quiet=True,
    )
    env["GRASS_REGION"] = gs.region_env(zoom=railroads + "_" + str(seg_cat))
    gs.run_command(
        "r.cost",
        flags="n",
        input=railroads + "_" + str(seg_cat),
        output=railroads + "_cumcost_" + str(seg_cat),
        start_coordinates=nodes_by_id[node_id],
        quiet=True,
        env=env,
    )
    stats = gs.read_command(
        "r.stats",
        output="-",
        flags="xn",
        quiet=True,
        input=railroads + "_cumcost_" + str(seg_cat),
    ).strip()
    cells[seg_cat] = []
    for line in stats.splitlines():
        row, col, cost = line.strip().split()
        row, col, cost = int(row), int(col), float(cost)
        cells[seg_cat].append((cost, row, col))
    cells[seg_cat].sort()
    return cells
Ejemplo n.º 23
0
    def _create_grass_region_env(self, bbox):

        r = self.an_data.GetRegion()
        new_r = {}

        if bbox["maxy"] <= r["s"]:
            return 0
        elif bbox["maxy"] >= r["n"]:
            new_r["n"] = bbox["maxy"]
        else:
            new_r["n"] = (ceil(
                (bbox["maxy"] - r["s"]) / r["nsres"]) * r["nsres"] + r["s"])

        if bbox["miny"] >= r["n"]:
            return 0
        elif bbox["miny"] <= r["s"]:
            new_r["s"] = bbox["miny"]
        else:
            new_r["s"] = (floor(
                (bbox["miny"] - r["s"]) / r["nsres"]) * r["nsres"] + r["s"])

        if bbox["maxx"] <= r["w"]:
            return 0
        elif bbox["maxx"] >= r["e"]:
            new_r["e"] = bbox["maxx"]
        else:
            new_r["e"] = (ceil(
                (bbox["maxx"] - r["w"]) / r["ewres"]) * r["ewres"] + r["w"])

        if bbox["minx"] >= r["e"]:
            return 0
        elif bbox["minx"] <= r["w"]:
            new_r["w"] = bbox["minx"]
        else:
            new_r["w"] = (floor(
                (bbox["minx"] - r["w"]) / r["ewres"]) * r["ewres"] + r["w"])

        # TODO check regions resolution
        new_r["nsres"] = r["nsres"]
        new_r["ewres"] = r["ewres"]

        return {"GRASS_REGION": grass.region_env(**new_r)}
Ejemplo n.º 24
0
    def _create_grass_region_env(self, bbox):

        r = self.an_data.GetRegion()
        new_r = {}

        if bbox["maxy"] <= r["s"]:
            return 0
        elif bbox["maxy"] >= r["n"]:
            new_r["n"] = bbox["maxy"]
        else:
            new_r["n"] = ceil(
                (bbox["maxy"] - r["s"]) / r["nsres"]) * r["nsres"] + r["s"]

        if bbox["miny"] >= r["n"]:
            return 0
        elif bbox["miny"] <= r["s"]:
            new_r["s"] = bbox["miny"]
        else:
            new_r["s"] = floor(
                (bbox["miny"] - r["s"]) / r["nsres"]) * r["nsres"] + r["s"]

        if bbox["maxx"] <= r["w"]:
            return 0
        elif bbox["maxx"] >= r["e"]:
            new_r["e"] = bbox["maxx"]
        else:
            new_r["e"] = ceil(
                (bbox["maxx"] - r["w"]) / r["ewres"]) * r["ewres"] + r["w"]

        if bbox["minx"] >= r["e"]:
            return 0
        elif bbox["minx"] <= r["w"]:
            new_r["w"] = bbox["minx"]
        else:
            new_r["w"] = floor(
                (bbox["minx"] - r["w"]) / r["ewres"]) * r["ewres"] + r["w"]

        # TODO check regions resolution
        new_r["nsres"] = r["nsres"]
        new_r["ewres"] = r["ewres"]

        return {"GRASS_REGION": grass.region_env(**new_r)}
Ejemplo n.º 25
0
    def OnReproject(self, event):
        cmd = []
        if self.etype == "raster":
            cmd.append("r.proj")
            cmd.append("dbase=" + self.iGisdbase)
            cmd.append("location=" + self.iLocation)
            cmd.append("mapset=" + self.iMapset)
            cmd.append("input=" + self.iLayer)
            cmd.append("output=" + self.oLayer)
            cmd.append("method=" + self.resampling.GetStringSelection())

            self.oEnv["GRASS_REGION"] = region_env(
                n=self.params["n"],
                s=self.params["s"],
                e=self.params["e"],
                w=self.params["w"],
                flags="a",
                res=float(self.resolution.GetValue()),
                env=self.oEnv,
            )
        else:
            cmd.append("v.proj")
            cmd.append("dbase=" + self.iGisdbase)
            cmd.append("location=" + self.iLocation)
            cmd.append("mapset=" + self.iMapset)
            cmd.append("input=" + self.iLayer)
            cmd.append("output=" + self.oLayer)
            cmd.append("smax=" + self.vsplit.GetValue())

        self._giface.RunCmd(
            cmd,
            env=self.oEnv,
            compReg=False,
            addLayer=False,
            onDone=self._onDone,
            userData=None,
            notification=Notification.MAKE_VISIBLE,
        )

        event.Skip()
Ejemplo n.º 26
0
def main():

    # Following declarations MAY will used in future for sure.
    global GISDBASE, LAYERCOUNT, LASTFILE

    # Check if ImageMagick is available since it is essential
    if os.name == 'nt':
        if grass.find_program('magick', '-version'):
            grass.verbose(_('printws: ImageMagick is available: OK!'))
        else:
            grass.fatal(
                'ImageMagick is not accessible. See documentation of m.printws module for details.'
            )
    else:
        if grass.find_program('convert', '-version'):
            grass.verbose(_('printws: ImageMagick is available: OK!'))
        else:
            grass.fatal(
                'ImageMagick is not accessible. See documentation of m.printws module for details.'
            )

    textmacros = {}
    # %nam% macros are kept for backward compatibility
    textmacros['%TIME24%'] = time.strftime("%H:%M:%S")
    textmacros['%DATEYMD%'] = time.strftime("%Y.%m.%d")
    textmacros['%DATEMDY%'] = time.strftime("%m/%d/%Y")
    if not hasPwd:
        textmacros['%USERNAME%'] = '(user unknown)'
    else:
        textmacros['%USERNAME%'] = pwd.getpwuid(os.getuid())[0]
    # using $ for macros in the future. New items should be created
    # exclusively as $macros later on
    textmacros['\$TIME24'] = textmacros['%TIME24%']
    textmacros['\$DATEYMD'] = textmacros['%DATEYMD%']
    textmacros['\$DATEMDY'] = textmacros['%DATEMDY%']
    textmacros['\$USERNAME'] = textmacros['%USERNAME%']

    textmacros[
        '\$SPC'] = u'\u00A0'  #?? d.text won't display this at string end hmmm

    # saves region for restoring at end
    # doing with official method:
    grass.use_temp_region()

    # getting/setting screen/print dpi ratio

    if len(options['dpi']) > 0:
        dpioption = float(options['dpi'])
    else:
        dpioption = 150.0

    if len(options['screendpi']) > 0:
        screendpioption = float(options['screendpi'])
    else:
        screendpioption = 100.0

    global UPSIZE
    UPSIZE = float(dpioption) / float(screendpioption)

    if len(options['input']) > 0:
        displays = readworkspace(options['input'])
    else:
        quit()

    textmacros['%GXW%'] = options['input']
    textmacros['\$GXW'] = textmacros['%GXW%']

    displaycounter = 0

    # there could be multiple displays in a workspace so we loop them
    # each display is a whole and independent file assembly
    for key in displays:
        textmacros['%DISPLAY%'] = key
        textmacros['\$DISPLAY'] = key
        grass.verbose(_('printws: rendering display: ' + key))
        displaycounter = displaycounter + 1
        layers = copy.deepcopy(displays[key])

        # extracting extent information from layers dic and erase the item
        # extents[0-5] w s e n minz maxz ;  extents [6-9] window x y w h
        extents = layers[0]
        grass.verbose("m.printws: EXTENTS from workspace:" +
                      str(extents))  # was debug message
        del layers[0]

        regionmode = ''
        if len(options['region']) > 0:
            grass.run_command("g.region", region=options['region'])
            regionmode = 'region'
        else:
            grass.run_command("g.region",
                              "",
                              w=extents[0],
                              s=extents[1],
                              e=extents[2],
                              n=extents[3])
            regionmode = 'window'

        # setting GRASS rendering environment

        # dummy file name is defined since the following lines
        # when switching on the cairo driver would create
        # an empty map.png in the current directory
        os.environ['GRASS_RENDER_FILE'] = os.path.join(
            TMPDIR,
            str(os.getpid()) + '_DIS_' + str(00) + '_GEN_' + str(00) + '.png')
        os.environ['GRASS_RENDER_IMMEDIATE'] = 'cairo'
        os.environ['GRASS_RENDER_FILE_READ'] = 'TRUE'
        os.environ['GRASS_RENDER_TRANSPARENT'] = 'TRUE'
        os.environ['GRASS_RENDER_FILE_COMPRESSION'] = '0'
        os.environ['GRASS_RENDER_FILE_MAPPED'] = 'TRUE'

        # reading further options and setting defaults

        if len(options['page']) > 0:
            pageoption = options['page']
        else:
            pageoption = 'A4landscape'

        # parsing titles, etc.
        if len(options['font']) > 0:
            isAsterisk = options['font'].find('*')
            if isAsterisk > 0:
                titlefont = getfontbypattern(options['font'].replace('*', ''))
            else:
                titlefont = options['font']
        else:
            titlefont = getfontbypattern('Open')  # try to find something UTF-8
        grass.verbose(_("printws: titlefont: " + titlefont))

        if len(options['titlecolor']) > 0:
            titlecolor = options['titlecolor']
        else:
            titlecolor = black

        if len(options['maintitlesize']) > 0:
            maintitlesize = converttommfrom(float(options['maintitlesize']),
                                            options['layunits'])
        else:
            maintitlesize = 10.0

        if len(options['subtitlesize']) > 0:
            subtitlesize = converttommfrom(float(options['subtitlesize']),
                                           options['layunits'])
        else:
            subtitlesize = 7.0

        if len(options['pssize']) > 0:
            pssize = converttommfrom(float(options['pssize']),
                                     options['layunits'])
        else:
            pssize = 5.0

        # Please fasten your seatbelts :) Calculations start here.
        # -------------------------------------------------------------------

        pagesizes = getpagesizes(pageoption)
        pagesizesindots = dictodots(pagesizes, dpioption)

        # Leave space for titles up and ps down - still in mm !!
        upperspace = 0
        subtitletop = 0
        titletop = 0
        if len(options['maintitle']) > 0:
            titletop = 0.4 * maintitlesize
            upperspace = upperspace + titletop + maintitlesize
        if len(options['subtitle']) > 0:
            subtitletop = upperspace + 0.4 * subtitlesize
            upperspace = subtitletop + subtitlesize + 1
        lowerspace = 0
        if (len(options['psundercentral']) > 0) or (len(
                options['psunderright']) > 0) or (len(options['psunderleft']) >
                                                  0):
            lowerspace = lowerspace + pssize + 2

        os.environ['GRASS_RENDER_WIDTH'] = str(pagesizesindots['w'])
        os.environ['GRASS_RENDER_HEIGHT'] = str(pagesizesindots['h'])

        pagemargins = getpagemargins(options['pagemargin'],
                                     options['layunits'])
        pagemarginsindots = dictodots(pagemargins, dpioption)

        # Getting max drawing area in dots
        mxfd = getmaxframeindots(pagemarginsindots, pagesizesindots)
        maxframe = str(mxfd['t']) + ',' + str(mxfd['b']) + \
            ',' + str(mxfd['l']) + ',' + str(mxfd['r'])

        # convert font size in mm to percentage for d.text
        mxfmm = dictomm(mxfd, dpioption)
        maintitlesize = float(maintitlesize) / (mxfmm['b'] -
                                                mxfmm['t']) * 100.0
        subtitlesize = float(subtitlesize) / (mxfmm['b'] - mxfmm['t']) * 100.0

        pssize = float(pssize) / (mxfmm['r'] - mxfmm['l']) * 100.0
        # subtitle location is another issue
        subtitletoppercent = 100.0 - subtitletop / \
            (mxfmm['b'] - mxfmm['t']) * 100.0
        titletoppercent = 100.0 - titletop / \
            (mxfmm['b'] - mxfmm['t']) * 100.0

        mapul = getmapUL(options['mapupperleft'], options['layunits'])
        mapulindots = dictodots(mapul, dpioption)

        mapsizes = getmapsizes(options['mapsize'], options['layunits'])
        mapsizesindots = dictodots(mapsizes, dpioption)

        # Correcting map area ratio to ratio of region edges
        # OR screen window edges depeding on "regionmode"
        # for later:     grass.use_temp_region()
        ISLATLONG = False
        s = grass.read_command("g.region", flags='p')
        kv = grass.parse_key_val(s, sep=':')
        regioncols = float(kv['cols'].strip())
        regionrows = float(kv['rows'].strip())
        ewrestemp = kv['ewres'].strip()
        nsrestemp = kv['nsres'].strip()
        if ewrestemp.find(':') > 0:
            ISLATLONG = True
            ewrestemp = ewrestemp.split(':')
            ewres = float(ewrestemp[0]) + float(ewrestemp[1]) / 60.0 + float(
                ewrestemp[2]) / 3600.0
            nsrestemp = nsrestemp.split(':')
            nsres = float(nsrestemp[0]) + float(nsrestemp[1]) / 60.0 + float(
                nsrestemp[2]) / 3600.0
        else:
            ewres = float(ewrestemp)
            nsres = float(nsrestemp)

        sizex = regioncols * ewres
        sizey = regionrows * nsres

        grass.verbose(_("printws: sizex " + str(sizex)))
        grass.verbose(_("printws: sizey " + str(sizey)))

        if regionmode == 'region':
            hregionratio = float(sizex) / float(sizey)
            grass.verbose(_("printws: REGION MODE -> region "))
        else:  # surprisingly doing the SAME
            # using screen window ratio for map area
            # next line was a test for this but didn't help on gadgets positioning
            #hregionratio = float(extents[8]) / float(extents[9])
            hregionratio = float(sizex) / float(sizey)
            grass.verbose(_("printws: REGION MODE -> window"))
        hmapratio = mapsizes['w'] / mapsizes['h']

        grass.verbose(_("printws: raw mapsizes: " + str(mapsizesindots)))
        grass.verbose(_("printws: hr: " + str(hregionratio)))
        grass.verbose(_("printws: hm: " + str(hmapratio)))
        if hregionratio > hmapratio:
            grass.verbose(
                _("printws: Map area height correction / " +
                  str(hregionratio)))
            mapsizes['h'] = mapsizes['w'] / hregionratio
        elif hregionratio < hmapratio:
            grass.verbose(
                _("printws: Map area width correction * " + str(hregionratio)))
            mapsizes['w'] = mapsizes['h'] * hregionratio
        mapsizesindots = dictodots(mapsizes, dpioption)

        # changing region resolution to match print resolution
        # to eliminate unnecessary CPU heating/data transfer
        # so as to make it faster
        # with only invisible detail loss.
        colsregiontomap = float(mapsizesindots['w']) / regioncols
        rowsregiontomap = float(mapsizesindots['h']) / regionrows

        newewres = ewres
        newnsres = nsres

        # if colsregiontomap < 1:
        # CHANGE: also enables raising of resolution to prevent
        # pixelation because of low resolution setting...
        newewres = ewres / colsregiontomap
        # if rowsregiontomap < 1:
        newnsres = nsres / rowsregiontomap

        # WOW - no necessary to convert back to DMS for nsres / ewres
        #if ISLATLONG:
        #    newewresstr=decdeg2dms(newewres)
        #    newnsresstr=decdeg2dms(newnsres)
        #else:
        newewresstr = str(newewres)
        newnsresstr = str(newnsres)

        grass.run_command("g.region", ewres=newewresstr, nsres=newnsresstr)

        # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        # it seems that d.wms uses the GRASS_REGION from region info
        # others may also do so we set it
        # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        kv2 = {}
        kv2['e'] = kv['east']
        kv2['n'] = kv['north']
        kv2['s'] = kv['south']
        kv2['w'] = kv['west']
        kv2['ewres'] = newewresstr
        kv2['nsres'] = newnsresstr
        #kv2['rows']    #- autocalculated to resolution - no need to set explicitly
        #kv2['cols']    #- autocalculated to resolution - no need to set explicitly
        #grass.message(str(kv2))
        #grass.message(grass.region_env(**kv2))
        #grass.message(s)
        os.environ['GRASS_REGION'] = grass.region_env(**kv2)

        # Getting mapping area in dots
        # Correcting mxfd to leave space for title and subscript
        pagemarginstitles = copy.deepcopy(pagemargins)
        pagemarginstitles['t'] = pagemarginstitles['t'] + upperspace
        pagemarginstitles['b'] = pagemarginstitles['b'] + lowerspace
        pagemarginsindotstitles = dictodots(pagemarginstitles, dpioption)
        mxfdtitles = getmaxframeindots(pagemarginsindotstitles,
                                       pagesizesindots)

        mpfd = getmapframeindots(mapulindots, mapsizesindots, mxfdtitles)
        if pageoption == 'Flexi':
            # For 'Flexi' page we modify the setup to create
            # a page containing only the map without margins
            grass.verbose(_("printws: pre Flexi mapframe: " + str(mpfd)))
            mpfd['b'] = mpfd['b'] - mpfd['t']
            mpfd['t'] = 0
            mpfd['r'] = mpfd['r'] - mpfd['l']
            mpfd['l'] = 0
            os.environ['GRASS_RENDER_WIDTH'] = str(mpfd['r'])
            os.environ['GRASS_RENDER_HEIGHT'] = str(mpfd['b'])
            grass.verbose(_("printws: post Flexi mapframe: " + str(mpfd)))
        mapframe = str(mpfd['t']) + ',' + str(mpfd['b']) + \
            ',' + str(mpfd['l']) + ',' + str(mpfd['r'])

        grass.verbose(_("printws: DOT VALUES ARE:"))
        grass.verbose(_("printws: maxframe: " + str(mxfd)))
        grass.verbose(_("printws: maxframe: " + maxframe))
        grass.verbose(_("printws: mapframe: " + str(mpfd)))
        grass.verbose(_("printws: mapframe: " + mapframe))
        grass.verbose(_("printws: page: " + str(pagesizesindots)))
        grass.verbose(_("printws: margins: " + str(pagemarginsindots)))
        grass.verbose(_("printws: mapUL: " + str(mapulindots)))
        grass.verbose(
            _("printws: mapsizes (corrected): " + str(mapsizesindots)))
        grass.verbose(_("printws: ewres (corrected): " + str(newewres)))
        grass.verbose(_("printws: nsres (corrected): " + str(newnsres)))

        # quit()

        # ------------------- INMAP -------------------

        # Do not limit -map. It was: -limit map 720000000 before...
        # So we can grow on disk as long as it lasts
        imcommand = 'convert  -limit memory 720000000 -units PixelsPerInch -density ' + \
            str(int(dpioption)) + ' '

        if os.name == 'nt':
            imcommand = 'magick ' + imcommand

        os.environ['GRASS_RENDER_FRAME'] = mapframe

        grass.verbose(_("printws: Rendering: the following layers: "))
        lastopacity = '-1'

        for lay in layers:
            grass.verbose(_(lay[1] + ' at: ' + lay[0] + ' opacity'))
            if lay[0] == '1':
                if lastopacity <> '1':
                    LASTFILE = os.path.join(TMPDIR, str(os.getpid()) + \
                        '_DIS_' + str(displaycounter) + '_GEN_' + \
                        str(LAYERCOUNT) + '.' + TMPFORMAT)
                    os.environ['GRASS_RENDER_FILE'] = LASTFILE
                    LAYERCOUNT = LAYERCOUNT + 2
                    imcommand = imcommand + ' ' + LASTFILE
                    lastopacity = '1'
                render(lay[1], lay[2], lay[3])
            else:
                lastopacity = lay[0]
                LASTFILE = os.path.join(
                    TMPDIR,
                    str(os.getpid()) + '_DIS_' + str(displaycounter) +
                    '_GEN_' + str(LAYERCOUNT) + '.' + TMPFORMAT)
                LAYERCOUNT = LAYERCOUNT + 2
                os.environ['GRASS_RENDER_FILE'] = LASTFILE
                grass.verbose("LAY: " + str(lay))
                render(lay[1], lay[2], lay[3])
                imcommand = imcommand + \
                    ' \( ' + LASTFILE + ' -channel a -evaluate multiply ' + \
                    lay[0] + ' +channel \)'

        # setting resolution back to pre-script state since map rendering is
        # finished
        # CHANGE: not necessary anymore since we use temp_region now
        # However, since we did set GRASS_REGION, let's redo it here

        os.environ.pop('GRASS_REGION')

        # ------------------- OUTSIDE MAP texts, etc -------------------
        if pageoption == 'Flexi':
            grass.verbose(
                _('m.printws: WARNING! Felxi mode, will not create titles, etc...'
                  ))
        else:
            os.environ['GRASS_RENDER_FRAME'] = maxframe

            dict = {}
            dict['task'] = "d.text"
            dict['color'] = titlecolor
            dict['font'] = titlefont
            dict['charset'] = "UTF-8"

            if len(options['maintitle']) > 1:
                dict['text'] = decodetextmacros(options['maintitle'],
                                                textmacros)
                dict['at'] = "50," + str(titletoppercent)
                dict['align'] = "uc"
                dict['size'] = str(maintitlesize)
                render(str(dict), dict, {})

            if len(options['subtitle']) > 1:
                dict['text'] = decodetextmacros(options['subtitle'],
                                                textmacros)
                dict['at'] = "50," + str(subtitletoppercent)
                dict['align'] = "uc"
                dict['size'] = str(subtitlesize)
                render(str(dict), dict, {})

            dict['size'] = str(pssize)

            if len(options['psundercentral']) > 1:
                dict['text'] = decodetextmacros(options['psundercentral'],
                                                textmacros)
                dict['at'] = "50,1"
                dict['align'] = "lc"
                render(str(dict), dict, {})
            if len(options['psunderleft']) > 1:
                dict['text'] = decodetextmacros(options['psunderleft'],
                                                textmacros)
                dict['at'] = "0,1"
                dict['align'] = "ll"
                render(str(dict), dict, {})
            if len(options['psunderright']) > 1:
                dict['text'] = decodetextmacros(options['psunderright'],
                                                textmacros)
                dict['at'] = "100,1"
                dict['align'] = "lr"
                render(str(dict), dict, {})

        # ------------------- GENERATING OUTPUT FILE -------------------

        if len(options['output']) > 1:
            output = options['output']
        else:
            output = 'map_' + str(os.getpid())

        # remove extension AND display number and naming if any
        output = os.path.splitext(output)[0]
        output = re.sub('_DISPLAY_[0-9]+_.*', '', output)

        if len(options['format']) > 1:
            extension = options['format']
        else:
            extension = 'pdf'

        displaypart = ''
        if len(displays) > 1:
            displaypart = '_DISPLAY_' + str(displaycounter) + '_' + key

        pagedata = getpagedata(pageoption)
        #params= ' -extent '+str(pagesizesindots['w'])+'x'+str(pagesizesindots['h'])+' -gravity center -compress jpeg -page '+pagedata['page']+' '+pagedata['parameters']+' -units PixelsPerInch -density '+str(dpioption)+'x'+str(dpioption)+' '
        params = ' -compress jpeg -quality 92 ' + \
            pagedata['parameters'] + ' -units PixelsPerInch -density ' + \
            str(int(dpioption)) + ' '

        imcommand = imcommand + ' -layers flatten ' + params + \
            '"' + output + displaypart + '.' + extension + '"'

        grass.verbose(
            _('printws: And the imagemagick command is... ' + imcommand))
        os.system(imcommand)

    if not flags['d']:
        grass.verbose(_('printws: Doing graceful cleanup...'))
        os.system('rm ' + os.path.join(TMPDIR, str(os.getpid()) + '*_GEN_*'))
        if REMOVE_TMPDIR:
            try_rmdir(TMPDIR)
        else:
            grass.message(
                "\n%s\n" %
                _("printws: Temp dir remove failed. Do it yourself, please:"))
            sys.stderr.write('%s\n' % TMPDIR % ' <---- this')

    # restoring pre-script region
    # - not necessary as we are using grass.use_temp_region() in the future

    return 0
Ejemplo n.º 27
0
    def ImportMapIntoGRASS(self, raster):
        """!Import raster into GRASS."""
        # importing temp_map into GRASS
        try:
            # do not use -o flag !
            grass.run_command(
                "r.in.gdal",
                flags="o",
                quiet=True,
                overwrite=True,
                input=raster,
                output=self.opt_output,
            )
        except CalledModuleError:
            grass.fatal(_("%s failed") % "r.in.gdal")

        # information for destructor to cleanup temp_layers, created
        # with r.in.gdal

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

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

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

            if not self.cleanup_bands:
                # use the MASK to set NULL vlues
                for suffix in (".red", ".green", ".blue"):
                    rast = self.opt_output + suffix
                    if grass.find_file(rast, element="cell", mapset=".")["file"]:
                        grass.run_command(
                            "g.rename",
                            rast="%s,%s" % (rast, rast + "_null"),
                            quiet=True,
                        )
                        grass.run_command(
                            "r.mapcalc",
                            expression="%s = %s" % (rast, rast + "_null"),
                            quiet=True,
                        )
                        grass.run_command(
                            "g.remove",
                            type="raster",
                            name="%s" % (rast + "_null"),
                            flags="f",
                            quiet=True,
                        )

        # TODO one band + alpha band?
        if (
            grass.find_file(self.opt_output + ".red", element="cell", mapset=".")[
                "file"
            ]
            and self.cleanup_bands
        ):
            try:
                grass.run_command(
                    "r.composite",
                    quiet=True,
                    overwrite=True,
                    red=self.opt_output + ".red",
                    green=self.opt_output + ".green",
                    blue=self.opt_output + ".blue",
                    output=self.opt_output,
                )
            except CalledModuleError:
                grass.fatal(_("%s failed") % "r.composite")
Ejemplo n.º 28
0
def main():
    options, flags = gs.parser()
    simulated = options["simulated"]
    original = options["original"]
    reference = options["reference"]
    kappa = options["kappa"]
    kappasimulation = options["kappasimulation"]
    quantity_disagreement = options["quantity_disagreement"]
    allocation_disagreement = options["allocation_disagreement"]
    quantity_disagreement_basename = options["quantity_disagreement_basename"]
    allocation_disagreement_basename = options[
        "allocation_disagreement_basename"]
    input_region = options["region"]
    nprocs = int(options["nprocs"])

    current = gs.region()
    region = gs.parse_command("g.region", flags="pug", region=input_region)
    regions = []
    for row in range(int(region["rows"])):
        for col in range(int(region["cols"])):
            s = float(region["s"]) + row * float(region["nsres"])
            n = float(region["s"]) + (row + 1) * float(region["nsres"])
            w = float(region["w"]) + col * float(region["ewres"])
            e = float(region["w"]) + (col + 1) * float(region["ewres"])
            regions.append({
                "n": n,
                "s": s,
                "w": w,
                "e": e,
                "nsres": float(current["nsres"]),
                "ewres": float(current["ewres"]),
            })
    results = []
    params = []
    for each in regions:
        if original:
            params.append({
                "region": each,
                "simulated": simulated,
                "reference": reference,
                "original": original,
            })
        else:
            params.append({
                "region": each,
                "simulated": simulated,
                "reference": reference
            })

    with Pool(processes=nprocs) as pool:
        results = pool.map_async(compute, params).get()
    outputs = {}
    if kappa:
        outputs["kappa"] = {"name": kappa, "param": "kappa", "inp": ""}
    if kappasimulation:
        outputs["kappasim"] = {
            "name": kappasimulation,
            "param": "kappasimulation",
            "inp": "",
        }
    if quantity_disagreement:
        outputs["quantity_disagreement"] = {
            "name": quantity_disagreement,
            "param": "total_quantity",
            "inp": "",
        }
    if allocation_disagreement:
        outputs["allocation_disagreement"] = {
            "name": allocation_disagreement,
            "param": "total_allocation",
            "inp": "",
        }
    env = os.environ.copy()
    env["GRASS_REGION"] = gs.region_env(region=input_region)
    for r in results:
        for key in r.keys():
            if allocation_disagreement_basename and "allocation_class_" in key:
                cl = key.replace("allocation_class_", "")
                if cl not in outputs:
                    outputs[cl] = {
                        "name": allocation_disagreement_basename + "_" + cl,
                        "param": key,
                        "inp": "",
                    }
            if quantity_disagreement_basename and "quantity_class_" in key:
                cl = key.replace("quantity_class_", "")
                if cl not in outputs:
                    outputs[cl] = {
                        "name": quantity_disagreement_basename + "_" + cl,
                        "param": key,
                        "inp": "",
                    }
        for k in outputs:
            if outputs[k]["param"] in r and r[outputs[k]["param"]] is not None:
                outputs[k][
                    "inp"] += f"{r['e']},{r['n']},{r[outputs[k]['param']]}\n"
    for k in outputs:
        gs.write_command(
            "r.in.xyz",
            input="-",
            stdin=outputs[k]["inp"],
            output=outputs[k]["name"],
            method="mean",
            separator="comma",
            env=env,
            quiet=True,
        )
        gs.raster_history(outputs[k]["name"])
Ejemplo n.º 29
0
def function(pa):
 pa0 = 'v0_'+pa
 os.environ['GRASS_REGION'] = grass.region_env(vect=pa0,res=1000)
 #grass. message("omitting previous masks")
 grass.run_command('g.remove', rast='MASK') 

 if pa not in pa_list_done:

  opt1 = 'wdpa_id = '+pa
  #print px
  #print "Extracting PA:"+pa
  #grass.run_command('v.extract', input=source, out=pa0, where = opt1,overwrite=True)
  pa2 = pa+'v2'
  pa3 = pa+'v3'
  pa4 = 'paa_'+pa
  pa44 = 'pa_'+pa
  pa5 = pa4+'.txt'
  same = pa2+'= const'
  
  #grass. message ("setting up the working region")
  #grass.run_command('g.region',vect=pa0,res=1000)
  #grass.run_command('r.mask', vector=source, where=opt1)
  grass.run_command('r.mapcalc',expression='const = if(gcmask>=0,1,null())',overwrite=True)
  grass.run_command('r.mapcalc',expression=same,overwrite=True)
  a = grass.read_command('r.stats',input='const',flags='nc',separator='\n').splitlines()
  if len(a)==0: a = [1, 625]
  #grass.run_command('g.remove', rast='MASK')
  #print a
  minarea = np.sqrt(int(a[1]))#/1000
  #print minarea
  #grass. message ("segmenting the park")
  grass.run_command('i.segment', group='segm', output=pa2, threshold='0.7', method='region_growing', similarity='euclidean', minsize=minarea, memory='100000', iterations='20',overwrite=True)
  #grass. message ("cropping the segments")
  grass.run_command('r.mask', vector=source, where=opt1)
  opt2 = pa3+'='+pa2
  grass.run_command('r.mapcalc',expression=opt2,overwrite=True) # usar const como mapa para crear plantilla de PA con unos y ceros
  grass.run_command('g.remove', rast='MASK')
  #grass. message ("Number of cells per segment")
  grass.run_command('r.stats',input=pa3,out=pa5,overwrite=True) # flags='nc'
  #grass. message ("converting to vector")
  grass.run_command('r.to.vect', input=pa3,out=pa4,type ='area',flags='v',overwrite=True)
  #grass. message ("adding labels to segments")
  grass.run_command('v.db.addcolumn', map=pa4,col='wdpaid VARCHAR')
  grass.run_command('v.db.update', map=pa4,col='wdpaid',value=pa)
  #grass. message ("Checking shapefile")
  grass.run_command('v.clean', input=pa4,out=pa44,tool='rmarea',thres=minarea,overwrite=True)
  grass.run_command('v.db.addcolumn', map=pa44,col='wdpa_id VARCHAR')
  grass.run_command('v.db.update', map=pa44,col='wdpa_id',qcol='wdpaid || cat')
  #grass. message ("Exporting shapefile")
  #if pa == 0:
  # grass.run_command('v.out.ogr',input=pa44,ola='parks_segmented',dsn='.') 
  #else:
  grass.run_command('v.out.ogr',flags='a',input=pa44,ola='parks_segmented2',dsn='.') 
  #grass. message ("Deleting tmp layers") 
  #grass.run_command('g.mremove',rast='*v3',flags='f') 
  #grass.run_command('g.mremove',rast='*v2',flags='f') 
  #grass.run_command('g.mremove',rast='v0_*',flags='f') 
  #grass.run_command('g.mremove',rast='pa_*',flags='f') 
  #grass.run_command('g.mremove',vect='v0_*',flags='f') 
  ##grass.run_command('g.mremove',vect='pa_*',flags='f') 
  #grass.run_command('g.mremove',vect='paa_*',flags='f') 
  #grass. message ("Done")
  print "Done PA:"+pa
  wb = open(csvname1,'a')
  var = str(pa)
  wb.write(var)
  wb.write('\n')
  wb.close()
 os.environ.pop('GRASS_REGION')
Ejemplo n.º 30
0
def do_it_all(global_vars, target_pts_np):
    """Conduct weighted and parametrised partial viewshed and cummulate it with
    the previous partial viewsheds
    :param target_pts_np: Array of target points in global coordinate system
    :type target_pts_np: ndarray
    :return: 2D array of weighted parametrised cummulative viewshed
    :rtype: ndarray
    """
    # Set counter
    counter = 1

    # Get variables out of global_vars dictionary
    reg = global_vars["region"]
    exp_range = global_vars["range"]
    flagstring = global_vars["flagstring"]
    r_dsm = global_vars["r_dsm"]
    v_elevation = global_vars["observer_elevation"]
    refr_coeff = global_vars["refr_coeff"]
    memory = global_vars["memory"]
    parametrise_viewshed = global_vars["param_viewshed"]
    dsm_type = global_vars["dsm_type"]
    b_1 = global_vars["b_1"]
    cores = global_vars["cores"]
    tempname = global_vars["tempname"]

    # Create empty viewshed
    np_cum = np.empty((reg.rows, reg.cols), dtype=np.single)
    np_cum[:] = np.nan
    tmp_vs = "{}_{}".format(tempname, os.getpid())

    for target_pnt in target_pts_np:

        # Display a progress info message
        grass.percent(counter, len(target_pts_np), 1)
        grass.verbose("Processing point {i} ({p:.1%})".format(
            i=int(target_pnt[0]), p=counter / len(target_pts_np)))

        # Global coordinates and attributes of target point T
        t_glob = target_pnt[1:]

        # ======================================================================
        # 1. Set local computational region: +/- exp_range from target point
        # ======================================================================
        # compute position of target point within a pixel
        delta_n = math.ceil(
            (t_glob[1] - reg.south) / reg.nsres) * reg.nsres - (t_glob[1] -
                                                                reg.south)
        delta_s = (t_glob[1] - reg.south) - math.floor(
            (t_glob[1] - reg.south) / reg.nsres) * reg.nsres
        delta_e = math.ceil(
            (t_glob[0] - reg.west) / reg.ewres) * reg.ewres - (t_glob[0] -
                                                               reg.west)
        delta_w = (t_glob[0] - reg.west) - math.floor(
            (t_glob[0] - reg.west) / reg.ewres) * reg.ewres

        # ensure that local region doesn't exceed global region
        loc_reg_n = min(t_glob[1] + exp_range + delta_n, reg.north)
        loc_reg_s = max(t_glob[1] - exp_range - delta_s, reg.south)
        loc_reg_e = min(t_glob[0] + exp_range + delta_e, reg.east)
        loc_reg_w = max(t_glob[0] - exp_range - delta_w, reg.west)

        # pygrass sets region for pygrass tasks
        lreg = deepcopy(reg)
        lreg.set_bbox(Bbox(loc_reg_n, loc_reg_s, loc_reg_e, loc_reg_w))
        lreg.set_raster_region()

        # Create processing environment with region information
        c_env = os.environ.copy()
        c_env["GRASS_REGION"] = grass.region_env(n=loc_reg_n,
                                                 s=loc_reg_s,
                                                 e=loc_reg_e,
                                                 w=loc_reg_w)

        lreg_shape = [lreg.rows, lreg.cols]

        # ======================================================================
        # 2. Calculate binary viewshed and convert to numpy
        # ======================================================================
        vs = grass.pipe_command(
            "r.viewshed",
            flags="b" + flagstring,
            input=r_dsm,
            output=tmp_vs,
            coordinates="{},{}".format(t_glob[0], t_glob[1]),
            observer_elevation=0.0,
            target_elevation=v_elevation,
            max_distance=exp_range,
            refraction_coeff=refr_coeff,
            memory=int(round(memory / cores)),
            quiet=True,
            overwrite=True,
            env=c_env,
        )
        vs.communicate()
        # Workaround for https://github.com/OSGeo/grass/issues/1436
        clean_temp(vs.pid)

        # Read viewshed into numpy with single precision and replace NoData
        np_viewshed = raster2numpy(tmp_vs).astype(np.single)
        np_viewshed[np_viewshed == -2147483648] = np.nan

        # ======================================================================
        # 3. Prepare local coordinates and attributes of target point T
        # ======================================================================
        # Calculate how much of rows/cols of local region lies
        # outside global region
        o_1 = [
            max(t_glob[1] + exp_range + reg.nsres / 2 - reg.north, 0),
            max(reg.west - (t_glob[0] - exp_range - reg.ewres / 2), 0),
        ]

        t_loc = np.append(
            np.array([
                exp_range / reg.nsres + 0.5 - o_1[0] / reg.nsres,
                exp_range / reg.ewres + 0.5 - o_1[1] / reg.ewres,
            ]),
            t_glob[2:],
        )

        # ======================================================================
        # 4. Parametrise viewshed
        # ======================================================================
        np_viewshed = parametrise_viewshed(
            lreg_shape,
            t_loc,
            np_viewshed,
            reg,
            exp_range,
            r_dsm,
            dsm_type,
            v_elevation,
            b_1,
        ).astype(np.single)

        # ======================================================================
        # 5. Cummulate viewsheds
        # ======================================================================
        # Determine position of local parametrised viewshed within
        # global cummulative viewshed
        o_2 = [
            int(round((reg.north - loc_reg_n) / reg.nsres)),  # NS (rows)
            int(round((loc_reg_w - reg.west) / reg.ewres)),  # EW (cols)
        ]

        # Add local parametrised viewshed to global cummulative viewshed
        # replace nans with 0 in processed regions, keep nan where both are nan
        all_nan = np.all(
            np.isnan([
                np_cum[o_2[0]:o_2[0] + lreg_shape[0],
                       o_2[1]:o_2[1] + lreg_shape[1]],
                np_viewshed,
            ]),
            axis=0,
        )

        np_cum[o_2[0]:o_2[0] + lreg_shape[0],
               o_2[1]:o_2[1] + lreg_shape[1]] = np.nansum(
                   [
                       np_cum[o_2[0]:o_2[0] + lreg_shape[0],
                              o_2[1]:o_2[1] + lreg_shape[1]],
                       np_viewshed,
                   ],
                   axis=0,
               )

        np_cum[o_2[0]:o_2[0] + lreg_shape[0],
               o_2[1]:o_2[1] + lreg_shape[1]][all_nan] = np.nan

        counter += 1

    return np_cum
Ejemplo n.º 31
0
def main():
    """
    Gridded flexural isostatic solutions
    """

    options, flags = grass.parser()
    # if just interface description is requested, it will not get to this point
    # so gflex will not be needed

    # GFLEX
    # try to import gflex only after we know that
    # we will actually do the computation
    try:
        import gflex
    except:
        print("")
        print("MODULE IMPORT ERROR.")
        print("In order to run r.flexure or g.flexure, you must download and install")
        print("gFlex. The most recent development version is available from")
        print("https://github.com/awickert/gFlex.")
        print("Installation instructions are available on the page.")
        grass.fatal("Software dependency must be installed.")

    # This code is for 2D flexural isostasy
    flex = gflex.F2D()
    # And show that it is coming from GRASS GIS
    flex.grass = True

    # Flags
    latlon_override = flags["l"]

    # Inputs
    # Solution selection
    flex.Method = options["method"]
    if flex.Method == "FD":
        flex.Solver = options["solver"]
        if flex.Solver:
            flex.ConvergenceTolerance = options["tolerance"]
        # Always use the van Wees and Cloetingh (1994) solution type.
        # It is the best.
        flex.PlateSolutionType = "vWC1994"
    # Parameters that are often changed for the solution
    qs = options["input"]
    flex.qs = garray.array()
    flex.qs.read(qs)
    # Elastic thickness
    try:
        flex.Te = float(options["te"])
    except:
        flex.Te = garray.array()  # FlexureTe is the one that is used by Flexure
        flex.Te.read(options["te"])
        flex.Te = np.array(flex.Te)
    if options["te_units"] == "km":
        flex.Te *= 1000
    elif options["te_units"] == "m":
        pass
    # No "else"; shouldn't happen
    flex.rho_fill = float(options["rho_fill"])
    # Parameters that often stay at their default values
    flex.g = float(options["g"])
    flex.E = float(
        options["ym"]
    )  # Can't just use "E" because reserved for "east", I think
    flex.nu = float(options["nu"])
    flex.rho_m = float(options["rho_m"])
    # Solver type and iteration tolerance
    flex.Solver = options["solver"]
    flex.ConvergenceTolerance = float(options["tolerance"])
    # Boundary conditions
    flex.BC_N = options["northbc"]
    flex.BC_S = options["southbc"]
    flex.BC_W = options["westbc"]
    flex.BC_E = options["eastbc"]

    # Set verbosity
    if grass.verbosity() >= 2:
        flex.Verbose = True
    if grass.verbosity() >= 3:
        flex.Debug = True
    elif grass.verbosity() == 0:
        flex.Quiet = True

    # 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."
            )

    # Get grid spacing from GRASS
    # Check if lat/lon and proceed as directed
    if grass.region_env()[6] == "3":
        if latlon_override:
            if flex.Verbose:
                print("Latitude/longitude grid.")
                print("Based on r_Earth = 6371 km")
                print("Setting y-resolution [m] to 111,195 * [degrees]")
            flex.dy = grass.region()["nsres"] * 111195.0
            NSmid = (grass.region()["n"] + grass.region()["s"]) / 2.0
            dx_at_mid_latitude = (
                (3.14159 / 180.0) * 6371000.0 * np.cos(np.deg2rad(NSmid))
            )
            if flex.Verbose:
                print(
                    "Setting x-resolution [m] to "
                    + "%.2f" % dx_at_mid_latitude
                    + " * [degrees]"
                )
            flex.dx = grass.region()["ewres"] * dx_at_mid_latitude
        else:
            grass.fatal("Need the '-l' flag to enable lat/lon solution approximation.")
    # Otherwise straightforward
    else:
        flex.dx = grass.region()["ewres"]
        flex.dy = grass.region()["nsres"]

    # CALCULATE!
    flex.initialize()
    flex.run()
    flex.finalize()

    # Write to GRASS
    # Create a new garray buffer and write to it
    outbuffer = garray.array()  # Instantiate output buffer
    outbuffer[...] = flex.w
    outbuffer.write(
        options["output"], overwrite=grass.overwrite()
    )  # Write it with the desired name
    # And create a nice colormap!
    grass.run_command(
        "r.colors", map=options["output"], color="differences", quiet=True
    )
Ejemplo n.º 32
0
    def ImportMapIntoGRASS(self, raster):
        """!Import raster into GRASS.
        """
        # importing temp_map into GRASS
        try:
            # do not use -o flag !
            grass.run_command('r.in.gdal',
                              flags='o',
                              quiet=True,
                              overwrite=True,
                              input=raster,
                              output=self.opt_output)
        except CalledModuleError:
            grass.fatal(_('%s failed') % 'r.in.gdal')

        # information for destructor to cleanup temp_layers, created
        # with r.in.gdal

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

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

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

            if not self.cleanup_bands:
                # use the MASK to set NULL vlues
                for suffix in ('.red', '.green', '.blue'):
                    rast = self.opt_output + suffix
                    if grass.find_file(rast, element='cell',
                                       mapset='.')['file']:
                        grass.run_command('g.rename',
                                          rast='%s,%s' %
                                          (rast, rast + '_null'),
                                          quiet=True)
                        grass.run_command('r.mapcalc',
                                          expression='%s = %s' %
                                          (rast, rast + '_null'),
                                          quiet=True)
                        grass.run_command('g.remove',
                                          type='raster',
                                          name='%s' % (rast + '_null'),
                                          flags='f',
                                          quiet=True)

        # TODO one band + alpha band?
        if grass.find_file(self.opt_output + '.red',
                           element='cell',
                           mapset='.')['file'] and self.cleanup_bands:
            try:
                grass.run_command('r.composite',
                                  quiet=True,
                                  overwrite=True,
                                  red=self.opt_output + '.red',
                                  green=self.opt_output + '.green',
                                  blue=self.opt_output + '.blue',
                                  output=self.opt_output)
            except CalledModuleError:
                grass.fatal(_('%s failed') % 'r.composite')
Ejemplo n.º 33
0
def main():
    global TMPLOC, SRCGISRC, GISDBASE, TMP_REG_NAME

    GDALdatasource = options['input']
    output = options['output']
    method = options['resample']
    memory = options['memory']
    bands = options['band']
    tgtres = options['resolution']
    title = options["title"]
    if flags['e'] and not output:
        output = 'rimport_tmp'  # will be removed with the entire tmp location
    if options['resolution_value']:
        if tgtres != 'value':
            grass.fatal(
                _("To set custom resolution value, select 'value' in resolution option"
                  ))
        tgtres_value = float(options['resolution_value'])
        if tgtres_value <= 0:
            grass.fatal(_("Resolution value can't be smaller than 0"))
    elif tgtres == 'value':
        grass.fatal(
            _("Please provide the resolution for the imported dataset or change to 'estimated' resolution"
              ))

    # try r.in.gdal directly first
    additional_flags = 'l' if flags['l'] else ''
    if flags['o']:
        additional_flags += 'o'
    region_flag = ''
    if options['extent'] == 'region':
        region_flag += 'r'
    if flags['o'] or is_projection_matching(GDALdatasource):
        parameters = dict(input=GDALdatasource,
                          output=output,
                          memory=memory,
                          flags='ak' + additional_flags + region_flag)
        if bands:
            parameters['band'] = bands
        try:
            grass.run_command('r.in.gdal', **parameters)
            grass.verbose(
                _("Input <%s> successfully imported without reprojection") %
                GDALdatasource)
            return 0
        except CalledModuleError as e:
            grass.fatal(
                _("Unable to import GDAL dataset <%s>") % GDALdatasource)

    grassenv = grass.gisenv()
    tgtloc = grassenv['LOCATION_NAME']

    # make sure target is not xy
    if grass.parse_command('g.proj',
                           flags='g')['name'] == 'xy_location_unprojected':
        grass.fatal(
            _("Coordinate reference system not available for current location <%s>"
              ) % tgtloc)

    tgtmapset = grassenv['MAPSET']
    GISDBASE = grassenv['GISDBASE']

    TMPLOC = grass.append_node_pid("tmp_r_import_location")
    TMP_REG_NAME = grass.append_node_pid("tmp_r_import_region")

    SRCGISRC, src_env = grass.create_environment(GISDBASE, TMPLOC, 'PERMANENT')

    # create temp location from input without import
    grass.verbose(
        _("Creating temporary location for <%s>...") % GDALdatasource)
    # creating a new location with r.in.gdal requires a sanitized env
    env = os.environ.copy()
    env = grass.sanitize_mapset_environment(env)
    parameters = dict(input=GDALdatasource,
                      output=output,
                      memory=memory,
                      flags='c',
                      title=title,
                      location=TMPLOC,
                      quiet=True)
    if bands:
        parameters['band'] = bands
    try:
        grass.run_command('r.in.gdal', env=env, **parameters)
    except CalledModuleError:
        grass.fatal(_("Unable to read GDAL dataset <%s>") % GDALdatasource)

    # prepare to set region in temp location
    if 'r' in region_flag:
        tgtregion = TMP_REG_NAME
        grass.run_command('v.in.region', output=tgtregion, flags='d')

    # switch to temp location

    # print projection at verbose level
    grass.verbose(
        grass.read_command('g.proj', flags='p',
                           env=src_env).rstrip(os.linesep))

    # make sure input is not xy
    if grass.parse_command('g.proj', flags='g',
                           env=src_env)['name'] == 'xy_location_unprojected':
        grass.fatal(
            _("Coordinate reference system not available for input <%s>") %
            GDALdatasource)

    # import into temp location
    grass.verbose(
        _("Importing <%s> to temporary location...") % GDALdatasource)
    parameters = dict(input=GDALdatasource,
                      output=output,
                      memory=memory,
                      flags='ak' + additional_flags)
    if bands:
        parameters['band'] = bands
    if 'r' in region_flag:
        grass.run_command('v.proj',
                          location=tgtloc,
                          mapset=tgtmapset,
                          input=tgtregion,
                          output=tgtregion,
                          env=src_env)
        grass.run_command('g.region', vector=tgtregion, env=src_env)
        parameters['flags'] = parameters['flags'] + region_flag
    try:
        grass.run_command('r.in.gdal', env=src_env, **parameters)
    except CalledModuleError:
        grass.fatal(_("Unable to import GDAL dataset <%s>") % GDALdatasource)

    outfiles = grass.list_grouped('raster', env=src_env)['PERMANENT']

    # is output a group?
    group = False
    path = os.path.join(GISDBASE, TMPLOC, 'group', output)
    if os.path.exists(path):
        group = True
        path = os.path.join(GISDBASE, TMPLOC, 'group', output, 'POINTS')
        if os.path.exists(path):
            grass.fatal(_("Input contains GCPs, rectification is required"))

    if 'r' in region_flag:
        grass.run_command('g.remove',
                          type="vector",
                          flags="f",
                          name=tgtregion,
                          env=src_env)

    # switch to target location
    if 'r' in region_flag:
        grass.run_command('g.remove', type="vector", flags="f", name=tgtregion)

    region = grass.region()

    rflags = None
    if flags['n']:
        rflags = 'n'

    vreg = TMP_REG_NAME

    for outfile in outfiles:

        n = region['n']
        s = region['s']
        e = region['e']
        w = region['w']

        env = os.environ.copy()
        if options['extent'] == 'input':
            # r.proj -g
            try:
                tgtextents = grass.read_command('r.proj',
                                                location=TMPLOC,
                                                mapset='PERMANENT',
                                                input=outfile,
                                                flags='g',
                                                memory=memory,
                                                quiet=True)
            except CalledModuleError:
                grass.fatal(_("Unable to get reprojected map extent"))
            try:
                srcregion = grass.parse_key_val(tgtextents,
                                                val_type=float,
                                                vsep=' ')
                n = srcregion['n']
                s = srcregion['s']
                e = srcregion['e']
                w = srcregion['w']
            except ValueError:  # import into latlong, expect 53:39:06.894826N
                srcregion = grass.parse_key_val(tgtextents, vsep=' ')
                n = grass.float_or_dms(srcregion['n'][:-1]) * \
                    (-1 if srcregion['n'][-1] == 'S' else 1)
                s = grass.float_or_dms(srcregion['s'][:-1]) * \
                    (-1 if srcregion['s'][-1] == 'S' else 1)
                e = grass.float_or_dms(srcregion['e'][:-1]) * \
                    (-1 if srcregion['e'][-1] == 'W' else 1)
                w = grass.float_or_dms(srcregion['w'][:-1]) * \
                    (-1 if srcregion['w'][-1] == 'W' else 1)

            env['GRASS_REGION'] = grass.region_env(n=n, s=s, e=e, w=w)

        # v.in.region in tgt
        grass.run_command('v.in.region', output=vreg, quiet=True, env=env)

        # reproject to src
        # switch to temp location
        try:
            grass.run_command('v.proj',
                              input=vreg,
                              output=vreg,
                              location=tgtloc,
                              mapset=tgtmapset,
                              quiet=True,
                              env=src_env)
            # test if v.proj created a valid area
            if grass.vector_info_topo(vreg, env=src_env)['areas'] != 1:
                grass.fatal(_("Please check the 'extent' parameter"))
        except CalledModuleError:
            grass.fatal(_("Unable to reproject to source location"))

        # set region from region vector
        grass.run_command('g.region', raster=outfile, env=src_env)
        grass.run_command('g.region', vector=vreg, env=src_env)
        # align to first band
        grass.run_command('g.region', align=outfile, env=src_env)
        # get number of cells
        cells = grass.region(env=src_env)['cells']

        estres = math.sqrt((n - s) * (e - w) / cells)
        # remove from source location for multi bands import
        grass.run_command('g.remove',
                          type='vector',
                          name=vreg,
                          flags='f',
                          quiet=True,
                          env=src_env)

        # switch to target location
        grass.run_command('g.remove',
                          type='vector',
                          name=vreg,
                          flags='f',
                          quiet=True)

        grass.message(
            _("Estimated target resolution for input band <{out}>: {res}").
            format(out=outfile, res=estres))
        if flags['e']:
            continue

        env = os.environ.copy()

        if options['extent'] == 'input':
            env['GRASS_REGION'] = grass.region_env(n=n, s=s, e=e, w=w)

        res = None
        if tgtres == 'estimated':
            res = estres
        elif tgtres == 'value':
            res = tgtres_value
            grass.message(
                _("Using given resolution for input band <{out}>: {res}").
                format(out=outfile, res=res))
            # align to requested resolution
            env['GRASS_REGION'] = grass.region_env(res=res, flags='a', env=env)
        else:
            curr_reg = grass.region()
            grass.message(
                _("Using current region resolution for input band "
                  "<{out}>: nsres={ns}, ewres={ew}").format(
                      out=outfile, ns=curr_reg['nsres'], ew=curr_reg['ewres']))

        # r.proj
        grass.message(_("Reprojecting <%s>...") % outfile)
        try:
            grass.run_command('r.proj',
                              location=TMPLOC,
                              mapset='PERMANENT',
                              input=outfile,
                              method=method,
                              resolution=res,
                              memory=memory,
                              flags=rflags,
                              quiet=True,
                              env=env)
        except CalledModuleError:
            grass.fatal(_("Unable to to reproject raster <%s>") % outfile)

        if grass.raster_info(outfile)['min'] is None:
            grass.fatal(_("The reprojected raster <%s> is empty") % outfile)

    if flags['e']:
        return 0

    if group:
        grass.run_command('i.group', group=output, input=','.join(outfiles))

    # TODO: write metadata with r.support

    return 0
Ejemplo n.º 34
0
def main():
    global TMPLOC, SRCGISRC, GISDBASE, TMP_REG_NAME

    GDALdatasource = options["input"]
    output = options["output"]
    method = options["resample"]
    memory = options["memory"]
    bands = options["band"]
    tgtres = options["resolution"]
    title = options["title"]
    if flags["e"] and not output:
        output = "rimport_tmp"  # will be removed with the entire tmp location
    if options["resolution_value"]:
        if tgtres != "value":
            grass.fatal(
                _("To set custom resolution value, select 'value' in resolution option"
                  ))
        tgtres_value = float(options["resolution_value"])
        if tgtres_value <= 0:
            grass.fatal(_("Resolution value can't be smaller than 0"))
    elif tgtres == "value":
        grass.fatal(
            _("Please provide the resolution for the imported dataset or change to 'estimated' resolution"
              ))

    # try r.in.gdal directly first
    additional_flags = "l" if flags["l"] else ""
    if flags["o"]:
        additional_flags += "o"
    region_flag = ""
    if options["extent"] == "region":
        region_flag += "r"
    if flags["o"] or is_projection_matching(GDALdatasource):
        parameters = dict(
            input=GDALdatasource,
            output=output,
            memory=memory,
            flags="ak" + additional_flags + region_flag,
        )
        if bands:
            parameters["band"] = bands
        try:
            grass.run_command("r.in.gdal", **parameters)
            grass.verbose(
                _("Input <%s> successfully imported without reprojection") %
                GDALdatasource)
            return 0
        except CalledModuleError:
            grass.fatal(
                _("Unable to import GDAL dataset <%s>") % GDALdatasource)

    grassenv = grass.gisenv()
    tgtloc = grassenv["LOCATION_NAME"]

    # make sure target is not xy
    if grass.parse_command("g.proj",
                           flags="g")["name"] == "xy_location_unprojected":
        grass.fatal(
            _("Coordinate reference system not available for current location <%s>"
              ) % tgtloc)

    tgtmapset = grassenv["MAPSET"]
    GISDBASE = grassenv["GISDBASE"]

    TMPLOC = grass.append_node_pid("tmp_r_import_location")
    TMP_REG_NAME = grass.append_node_pid("tmp_r_import_region")

    SRCGISRC, src_env = grass.create_environment(GISDBASE, TMPLOC, "PERMANENT")

    # create temp location from input without import
    grass.verbose(
        _("Creating temporary location for <%s>...") % GDALdatasource)
    # creating a new location with r.in.gdal requires a sanitized env
    env = os.environ.copy()
    env = grass.sanitize_mapset_environment(env)
    parameters = dict(
        input=GDALdatasource,
        output=output,
        memory=memory,
        flags="c",
        title=title,
        location=TMPLOC,
        quiet=True,
    )
    if bands:
        parameters["band"] = bands
    try:
        grass.run_command("r.in.gdal", env=env, **parameters)
    except CalledModuleError:
        grass.fatal(_("Unable to read GDAL dataset <%s>") % GDALdatasource)

    # prepare to set region in temp location
    if "r" in region_flag:
        tgtregion = TMP_REG_NAME
        grass.run_command("v.in.region", output=tgtregion, flags="d")

    # switch to temp location

    # print projection at verbose level
    grass.verbose(
        grass.read_command("g.proj", flags="p",
                           env=src_env).rstrip(os.linesep))

    # make sure input is not xy
    if (grass.parse_command("g.proj", flags="g",
                            env=src_env)["name"] == "xy_location_unprojected"):
        grass.fatal(
            _("Coordinate reference system not available for input <%s>") %
            GDALdatasource)

    # import into temp location
    grass.verbose(
        _("Importing <%s> to temporary location...") % GDALdatasource)
    parameters = dict(
        input=GDALdatasource,
        output=output,
        memory=memory,
        flags="ak" + additional_flags,
    )
    if bands:
        parameters["band"] = bands
    if "r" in region_flag:
        grass.run_command(
            "v.proj",
            location=tgtloc,
            mapset=tgtmapset,
            input=tgtregion,
            output=tgtregion,
            env=src_env,
        )
        grass.run_command("g.region", vector=tgtregion, env=src_env)
        parameters["flags"] = parameters["flags"] + region_flag
    try:
        grass.run_command("r.in.gdal", env=src_env, **parameters)
    except CalledModuleError:
        grass.fatal(_("Unable to import GDAL dataset <%s>") % GDALdatasource)

    outfiles = grass.list_grouped("raster", env=src_env)["PERMANENT"]

    # is output a group?
    group = False
    path = os.path.join(GISDBASE, TMPLOC, "group", output)
    if os.path.exists(path):
        group = True
        path = os.path.join(GISDBASE, TMPLOC, "group", output, "POINTS")
        if os.path.exists(path):
            grass.fatal(_("Input contains GCPs, rectification is required"))

    if "r" in region_flag:
        grass.run_command("g.remove",
                          type="vector",
                          flags="f",
                          name=tgtregion,
                          env=src_env)

    # switch to target location
    if "r" in region_flag:
        grass.run_command("g.remove", type="vector", flags="f", name=tgtregion)

    region = grass.region()

    rflags = None
    if flags["n"]:
        rflags = "n"

    vreg = TMP_REG_NAME

    for outfile in outfiles:

        n = region["n"]
        s = region["s"]
        e = region["e"]
        w = region["w"]

        env = os.environ.copy()
        if options["extent"] == "input":
            # r.proj -g
            try:
                tgtextents = grass.read_command(
                    "r.proj",
                    location=TMPLOC,
                    mapset="PERMANENT",
                    input=outfile,
                    flags="g",
                    memory=memory,
                    quiet=True,
                )
            except CalledModuleError:
                grass.fatal(_("Unable to get reprojected map extent"))
            try:
                srcregion = grass.parse_key_val(tgtextents,
                                                val_type=float,
                                                vsep=" ")
                n = srcregion["n"]
                s = srcregion["s"]
                e = srcregion["e"]
                w = srcregion["w"]
            except ValueError:  # import into latlong, expect 53:39:06.894826N
                srcregion = grass.parse_key_val(tgtextents, vsep=" ")
                n = grass.float_or_dms(srcregion["n"][:-1]) * (
                    -1 if srcregion["n"][-1] == "S" else 1)
                s = grass.float_or_dms(srcregion["s"][:-1]) * (
                    -1 if srcregion["s"][-1] == "S" else 1)
                e = grass.float_or_dms(srcregion["e"][:-1]) * (
                    -1 if srcregion["e"][-1] == "W" else 1)
                w = grass.float_or_dms(srcregion["w"][:-1]) * (
                    -1 if srcregion["w"][-1] == "W" else 1)

            env["GRASS_REGION"] = grass.region_env(n=n, s=s, e=e, w=w)

        # v.in.region in tgt
        grass.run_command("v.in.region", output=vreg, quiet=True, env=env)

        # reproject to src
        # switch to temp location
        try:
            grass.run_command(
                "v.proj",
                input=vreg,
                output=vreg,
                location=tgtloc,
                mapset=tgtmapset,
                quiet=True,
                env=src_env,
            )
            # test if v.proj created a valid area
            if grass.vector_info_topo(vreg, env=src_env)["areas"] != 1:
                grass.fatal(_("Please check the 'extent' parameter"))
        except CalledModuleError:
            grass.fatal(_("Unable to reproject to source location"))

        # set region from region vector
        grass.run_command("g.region", raster=outfile, env=src_env)
        grass.run_command("g.region", vector=vreg, env=src_env)
        # align to first band
        grass.run_command("g.region", align=outfile, env=src_env)
        # get number of cells
        cells = grass.region(env=src_env)["cells"]

        estres = math.sqrt((n - s) * (e - w) / cells)
        # remove from source location for multi bands import
        grass.run_command("g.remove",
                          type="vector",
                          name=vreg,
                          flags="f",
                          quiet=True,
                          env=src_env)

        # switch to target location
        grass.run_command("g.remove",
                          type="vector",
                          name=vreg,
                          flags="f",
                          quiet=True)

        grass.message(
            _("Estimated target resolution for input band <{out}>: {res}").
            format(out=outfile, res=estres))
        if flags["e"]:
            continue

        env = os.environ.copy()

        if options["extent"] == "input":
            env["GRASS_REGION"] = grass.region_env(n=n, s=s, e=e, w=w)

        res = None
        if tgtres == "estimated":
            res = estres
        elif tgtres == "value":
            res = tgtres_value
            grass.message(
                _("Using given resolution for input band <{out}>: {res}").
                format(out=outfile, res=res))
            # align to requested resolution
            env["GRASS_REGION"] = grass.region_env(res=res, flags="a", env=env)
        else:
            curr_reg = grass.region()
            grass.message(
                _("Using current region resolution for input band "
                  "<{out}>: nsres={ns}, ewres={ew}").format(
                      out=outfile, ns=curr_reg["nsres"], ew=curr_reg["ewres"]))

        # r.proj
        grass.message(_("Reprojecting <%s>...") % outfile)
        try:
            grass.run_command(
                "r.proj",
                location=TMPLOC,
                mapset="PERMANENT",
                input=outfile,
                method=method,
                resolution=res,
                memory=memory,
                flags=rflags,
                quiet=True,
                env=env,
            )
        except CalledModuleError:
            grass.fatal(_("Unable to to reproject raster <%s>") % outfile)

        if grass.raster_info(outfile)["min"] is None:
            grass.fatal(_("The reprojected raster <%s> is empty") % outfile)

    if flags["e"]:
        return 0

    if group:
        grass.run_command("i.group", group=output, input=",".join(outfiles))

    # TODO: write metadata with r.support

    return 0
Ejemplo n.º 35
0
def function(pa):
    pa0 = 'v0_' + pa
    os.environ['GRASS_REGION'] = grass.region_env(vect=pa0, res=1000)
    #grass. message("omitting previous masks")
    grass.run_command('g.remove', rast='MASK')

    if pa not in pa_list_done:

        opt1 = 'wdpa_id = ' + pa
        #print px
        #print "Extracting PA:"+pa
        #grass.run_command('v.extract', input=source, out=pa0, where = opt1,overwrite=True)
        pa2 = pa + 'v2'
        pa3 = pa + 'v3'
        pa4 = 'paa_' + pa
        pa44 = 'pa_' + pa
        pa5 = pa4 + '.txt'
        same = pa2 + '= const'

        #grass. message ("setting up the working region")
        #grass.run_command('g.region',vect=pa0,res=1000)
        #grass.run_command('r.mask', vector=source, where=opt1)
        grass.run_command('r.mapcalc',
                          expression='const = if(gcmask>=0,1,null())',
                          overwrite=True)
        grass.run_command('r.mapcalc', expression=same, overwrite=True)
        a = grass.read_command('r.stats',
                               input='const',
                               flags='nc',
                               separator='\n').splitlines()
        if len(a) == 0: a = [1, 625]
        #grass.run_command('g.remove', rast='MASK')
        #print a
        minarea = np.sqrt(int(a[1]))  #/1000
        #print minarea
        #grass. message ("segmenting the park")
        grass.run_command('i.segment',
                          group='segm',
                          output=pa2,
                          threshold='0.7',
                          method='region_growing',
                          similarity='euclidean',
                          minsize=minarea,
                          memory='100000',
                          iterations='20',
                          overwrite=True)
        #grass. message ("cropping the segments")
        grass.run_command('r.mask', vector=source, where=opt1)
        opt2 = pa3 + '=' + pa2
        grass.run_command(
            'r.mapcalc', expression=opt2, overwrite=True
        )  # usar const como mapa para crear plantilla de PA con unos y ceros
        grass.run_command('g.remove', rast='MASK')
        #grass. message ("Number of cells per segment")
        grass.run_command('r.stats', input=pa3, out=pa5,
                          overwrite=True)  # flags='nc'
        #grass. message ("converting to vector")
        grass.run_command('r.to.vect',
                          input=pa3,
                          out=pa4,
                          type='area',
                          flags='v',
                          overwrite=True)
        #grass. message ("adding labels to segments")
        grass.run_command('v.db.addcolumn', map=pa4, col='wdpaid VARCHAR')
        grass.run_command('v.db.update', map=pa4, col='wdpaid', value=pa)
        #grass. message ("Checking shapefile")
        grass.run_command('v.clean',
                          input=pa4,
                          out=pa44,
                          tool='rmarea',
                          thres=minarea,
                          overwrite=True)
        grass.run_command('v.db.addcolumn', map=pa44, col='wdpa_id VARCHAR')
        grass.run_command('v.db.update',
                          map=pa44,
                          col='wdpa_id',
                          qcol='wdpaid || cat')
        #grass. message ("Exporting shapefile")
        #if pa == 0:
        # grass.run_command('v.out.ogr',input=pa44,ola='parks_segmented',dsn='.')
        #else:
        grass.run_command('v.out.ogr',
                          flags='a',
                          input=pa44,
                          ola='parks_segmented2',
                          dsn='.')
        #grass. message ("Deleting tmp layers")
        #grass.run_command('g.mremove',rast='*v3',flags='f')
        #grass.run_command('g.mremove',rast='*v2',flags='f')
        #grass.run_command('g.mremove',rast='v0_*',flags='f')
        #grass.run_command('g.mremove',rast='pa_*',flags='f')
        #grass.run_command('g.mremove',vect='v0_*',flags='f')
        ##grass.run_command('g.mremove',vect='pa_*',flags='f')
        #grass.run_command('g.mremove',vect='paa_*',flags='f')
        #grass. message ("Done")
        print "Done PA:" + pa
        wb = open(csvname1, 'a')
        var = str(pa)
        wb.write(var)
        wb.write('\n')
        wb.close()
    os.environ.pop('GRASS_REGION')
Ejemplo n.º 36
0
def main():
    """
    Superposition of analytical solutions in gFlex for flexural isostasy in
    GRASS GIS
    """

    options, flags = grass.parser()
    # if just interface description is requested, it will not get to this point
    # so gflex will not be needed

    # GFLEX
    # try to import gflex only after we know that
    # we will actually do the computation
    try:
        import gflex
    except:
        print("")
        print("MODULE IMPORT ERROR.")
        print(
            "In order to run r.flexure or g.flexure, you must download and install"
        )
        print("gFlex. The most recent development version is available from")
        print("https://github.com/awickert/gFlex")
        print("Installation instructions are available on the page.")
        grass.fatal("Software dependency must be installed.")

    ##########
    # SET-UP #
    ##########

    # This code is for 2D flexural isostasy
    flex = gflex.F2D()
    # And show that it is coming from GRASS GIS
    flex.grass = True

    # Method
    flex.Method = 'SAS_NG'

    # Parameters that are often changed for the solution
    ######################################################

    # x, y, q
    flex.x, flex.y = get_points_xy(options['input'])
    # xw, yw: gridded output
    if len(
            grass.parse_command('g.list',
                                type='vect',
                                pattern=options['output'])):
        if not grass.overwrite():
            grass.fatal("Vector map '" + options['output'] +
                        "' already exists. Use '--o' to overwrite.")
    # Just check raster at the same time if it exists
    if len(
            grass.parse_command('g.list',
                                type='rast',
                                pattern=options['raster_output'])):
        if not grass.overwrite():
            grass.fatal("Raster map '" + options['raster_output'] +
                        "' already exists. Use '--o' to overwrite.")
    grass.run_command('v.mkgrid',
                      map=options['output'],
                      type='point',
                      overwrite=grass.overwrite(),
                      quiet=True)
    grass.run_command('v.db.addcolumn',
                      map=options['output'],
                      columns='w double precision',
                      quiet=True)
    flex.xw, flex.yw = get_points_xy(
        options['output'])  # gridded output coordinates
    vect_db = grass.vector_db_select(options['input'])
    col_names = np.array(vect_db['columns'])
    q_col = (col_names == options['column'])
    if np.sum(q_col):
        col_values = np.array(list(vect_db['values'].values())).astype(float)
        flex.q = col_values[:, q_col].squeeze(
        )  # Make it 1D for consistency w/ x, y
    else:
        grass.fatal("provided column name, " + options['column'] +
                    " does not match\nany column in " + options['q0'] + ".")
    # Elastic thickness
    flex.Te = float(options['te'])
    if options['te_units'] == 'km':
        flex.Te *= 1000
    elif options['te_units'] == 'm':
        pass
    else:
        grass.fatal(
            "Inappropriate te_units. How? Options should be limited by GRASS.")
    flex.rho_fill = float(options['rho_fill'])

    # Parameters that often stay at their default values
    ######################################################
    flex.g = float(options['g'])
    flex.E = float(options['ym']
                   )  # Can't just use "E" because reserved for "east", I think
    flex.nu = float(options['nu'])
    flex.rho_m = float(options['rho_m'])

    # Set verbosity
    if grass.verbosity() >= 2:
        flex.Verbose = True
    if grass.verbosity() >= 3:
        flex.Debug = True
    elif grass.verbosity() == 0:
        flex.Quiet = True

    # Check if lat/lon and let user know if verbosity is True
    if grass.region_env()[6] == '3':
        flex.latlon = True
        flex.PlanetaryRadius = float(
            grass.parse_command('g.proj', flags='j')['+a'])
        if flex.Verbose:
            print("Latitude/longitude grid.")
            print("Based on r_Earth = 6371 km")
            print(
                "Computing distances between load points using great circle paths"
            )

    ##########
    # SOLVE! #
    ##########

    flex.initialize()
    flex.run()
    flex.finalize()

    # Now to use lower-level GRASS vector commands to work with the database
    # table and update its entries
    # See for help:
    # http://nbviewer.ipython.org/github/zarch/workshop-pygrass/blob/master/02_Vector.ipynb
    w = vector.VectorTopo(options['output'])
    w.open('rw')  # Get ready to read and write
    wdb = w.dblinks[0]
    wtable = wdb.table()
    col = int((np.array(
        wtable.columns.names()) == 'w').nonzero()[0])  # update this column
    for i in range(1, len(w) + 1):
        # ignoring 1st column: assuming it will be category (always true here)
        wnewvalues = list(w[i].attrs.values())[1:col] + tuple(
            [flex.w[i - 1]]) + list(w[i].attrs.values())[col + 1:]
        wtable.update(key=i, values=wnewvalues)
    wtable.conn.commit()  # Save this
    w.close(build=False)  # don't build here b/c it is always verbose
    grass.run_command('v.build', map=options['output'], quiet=True)

    # And raster export
    # "w" vector defined by raster resolution, so can do direct v.to.rast
    # though if this option isn't selected, the user can do a finer-grained
    # interpolation, which shouldn't introduce much error so long as these
    # outputs are spaced at << 1 flexural wavelength.
    if options['raster_output']:
        grass.run_command('v.to.rast',
                          input=options['output'],
                          output=options['raster_output'],
                          use='attr',
                          attribute_column='w',
                          type='point',
                          overwrite=grass.overwrite(),
                          quiet=True)
        # And create a nice colormap!
        grass.run_command('r.colors',
                          map=options['raster_output'],
                          color='differences',
                          quiet=True)
Ejemplo n.º 37
0
 def _createOutputMap(self): 
     """!Import downloaded data into GRASS, reproject data if needed
     using gdalwarp
     """
     # reprojection of raster
     if self.proj_srs != self.proj_location: # TODO: do it better
         grass.message(_("Reprojecting raster..."))
         temp_warpmap = self._tempfile()
         
         if int(os.getenv('GRASS_VERBOSE', '2')) <= 2:
             nuldev = file(os.devnull, 'w+')
         else:
             nuldev = None
         
         # RGB rasters - alpha layer is added for cropping edges of projected raster
         if self.temp_map_bands_num == 3:
             ps = grass.Popen(['gdalwarp',
                               '-s_srs', '%s' % self.proj_srs,
                               '-t_srs', '%s' % self.proj_location,
                               '-r', self.o_method, '-dstalpha',
                               self.temp_map, temp_warpmap], stdout = nuldev)
         # RGBA rasters
         else:
             ps = grass.Popen(['gdalwarp',
                               '-s_srs', '%s' % self.proj_srs,
                               '-t_srs', '%s' % self.proj_location,
                               '-r', self.o_method,
                               self.temp_map, temp_warpmap], stdout = nuldev)
         ps.wait()
         
         if nuldev:
             nuldev.close()
         
         if ps.returncode != 0:
             grass.fatal(_('%s failed') % 'gdalwarp')
     # raster projection is same as projection of location
     else:
         temp_warpmap = self.temp_map
     
     grass.message(_("Importing raster map into GRASS..."))
     # importing temp_map into GRASS
     if grass.run_command('r.in.gdal',
                          quiet = True,
                          input = temp_warpmap,
                          output = self.o_output) != 0:
         grass.fatal(_('%s failed') % 'r.in.gdal')
     
     # information for destructor to cleanup temp_layers, created
     # with r.in.gdal
     self.cleanup_layers = True
     
     # setting region for full extend of imported raster
     os.environ['GRASS_REGION'] = grass.region_env(rast = self.o_output + '.red')
     
     # mask created from alpha layer, which describes real extend
     # of warped layer (may not be a rectangle), also mask contains
     # transparent parts of raster
     if grass.find_file( self.o_output + '.alpha', element = 'cell', mapset = '.' )['name']:
         # saving current mask (if exists) into temp raster
         if grass.find_file('MASK', element = 'cell', mapset = '.' )['name']:
             if grass.run_command('g.copy',
                                  quiet = True,
                                  rast = 'MASK,' + self.o_output + self.original_mask_suffix) != 0:    
                 grass.fatal(_('%s failed') % 'g.copy')
         
         # info for destructor
         self.cleanup_mask = True
         if grass.run_command('r.mask',
                              quiet = True,
                              overwrite = True,
                              maskcats = "0",
                              flags = 'i',
                              input = self.o_output + '.alpha') != 0: 
             grass.fatal(_('%s failed') % 'r.mask')
     
     if grass.run_command('r.composite',
                          quiet = True,
                          red = self.o_output + '.red',
                          green = self.o_output +  '.green',
                          blue = self.o_output + '.blue',
                          output = self.o_output ) != 0:
             grass.fatal(_('%s failed') % 'r.composite')
     
     grass.try_remove(temp_warpmap)
     grass.try_remove(self.temp_map)