Ejemplo n.º 1
0
def setup_location(name, path, epsg, src_env):
    """Setup temporary location with different projection but
    same computational region as source location

    :param str name: name of new location
    :param path path: path to new location's database
    :param str epsg: EPSG code
    :param dict src_env: source environment

    :return str rcfile: name of new locations rcfile
    :return dict new_env: new environment
    """
    # Create new environment
    rcfile, new_env = gs.create_environment(path, name, "PERMANENT")
    # Location and mapset
    gs.create_location(path, name, epsg=epsg, overwrite=True)
    # Reproject region
    region = get_region(env=src_env)
    from_proj = get_location_proj_string(src_env)
    to_proj = get_location_proj_string(env=new_env)
    new_region = reproject_region(region, from_proj, to_proj)
    # Set region to match original region extent
    gs.run_command(
        "g.region",
        n=new_region["north"],
        s=new_region["south"],
        e=new_region["east"],
        w=new_region["west"],
        env=new_env,
    )
    return rcfile, new_env
Ejemplo n.º 2
0
 def OnDeleteMap(self, event):
     """Delete layer or mapset"""
     name = self.selected_layer.label
     gisrc, env = gscript.create_environment(
         gisenv()["GISDBASE"], self.selected_location.label, self.selected_mapset.label
     )
     if (
         self._confirmDialog(
             question=_(
                 "Do you really want to delete map <{m}> of type <{etype}> from mapset "
                 "<{mapset}> in location <{loc}>?"
             ).format(
                 m=name,
                 mapset=self.selected_mapset.label,
                 etype=self.selected_type.label,
                 loc=self.selected_location.label,
             ),
             title=_("Delete map"),
         )
         == wx.ID_YES
     ):
         label = _("Deleting {name}...").format(name=name)
         self.showNotification.emit(message=label)
         if self.selected_type.label == "vector":
             removed, cmd = self._runCommand("g.remove", flags="f", type="vector", name=name, env=env)
         elif self.selected_type.label == "raster":
             removed, cmd = self._runCommand("g.remove", flags="f", type="raster", name=name, env=env)
         else:
             removed, cmd = self._runCommand("g.remove", flags="f", type="raster_3d", name=name, env=env)
         if removed == 0:
             self._model.RemoveNode(self.selected_layer)
             self.RefreshNode(self.selected_type, recursive=True)
             Debug.msg(1, "LAYER " + name + " DELETED")
             self.showNotification.emit(message=_("g.remove completed").format(cmd=cmd))
     gscript.try_remove(gisrc)
Ejemplo n.º 3
0
def getLocationTree(gisdbase, location, queue, mapsets=None):
    """Creates dictionary with mapsets, elements, layers for given location.
    Returns tuple with the dictionary and error (or None)"""
    tmp_gisrc_file, env = gscript.create_environment(gisdbase, location,
                                                     'PERMANENT')
    env['GRASS_SKIP_MAPSET_OWNER_CHECK'] = '1'

    maps_dict = {}
    elements = ['raster', 'raster_3d', 'vector']
    try:
        if not mapsets:
            mapsets = gscript.read_command('g.mapsets',
                                           flags='l',
                                           separator='comma',
                                           quiet=True,
                                           env=env).strip()
    except CalledModuleError:
        queue.put((maps_dict,
                   _("Failed to read mapsets from location <{l}>.").format(
                       l=location)))
        gscript.try_remove(tmp_gisrc_file)
        return
    else:
        listOfMapsets = mapsets.split(',')
        Debug.msg(
            4,
            "Location <{0}>: {1} mapsets found".format(location,
                                                       len(listOfMapsets)))
        for each in listOfMapsets:
            maps_dict[each] = {}
            for elem in elements:
                maps_dict[each][elem] = []
    try:
        maplist = gscript.read_command('g.list',
                                       flags='mt',
                                       type=elements,
                                       mapset=','.join(listOfMapsets),
                                       quiet=True,
                                       env=env).strip()
    except CalledModuleError:
        queue.put(
            (maps_dict,
             _("Failed to read maps from location <{l}>.").format(l=location)))
        gscript.try_remove(tmp_gisrc_file)
        return
    else:
        # fill dictionary
        listOfMaps = maplist.splitlines()
        Debug.msg(
            4, "Location <{0}>: {1} maps found".format(location,
                                                       len(listOfMaps)))
        for each in listOfMaps:
            ltype, wholename = each.split('/')
            name, mapset = wholename.split('@')
            maps_dict[mapset][ltype].append(name)

    queue.put((maps_dict, None))
    gscript.try_remove(tmp_gisrc_file)
Ejemplo n.º 4
0
    def OnReproject(self, event):
        cmd = self.getSettingsPageCmd()
        cmd.append('dbase=' + self.iGisdbase)
        cmd.append('location=' + self.iLocation)
        cmd.append('mapset=' + self.iMapset)
        cmd.append('input=' + self.iLayer)

        self.tmpfile, env = gscript.create_environment(self.oGisdbase, self.oLocation, self.oMapset)

        self._giface.RunCmd(cmd, env=env,
               onDone=self.OnDone, userData=None,
               notification=Notification.MAKE_VISIBLE)
Ejemplo n.º 5
0
 def OnRenameMap(self, event):
     """Rename layer with dialog"""
     old_name = self.selected_layer.label
     gisrc, env = gscript.create_environment(
         gisenv()['GISDBASE'],
         self.selected_location.label,
         mapset=self.selected_mapset.label)
     new_name = self._getNewMapName(_('New name'),
                                    _('Rename map'),
                                    old_name,
                                    env=env,
                                    mapset=self.selected_mapset.label,
                                    element=self.selected_type.label)
     if new_name:
         self.Rename(old_name, new_name)
Ejemplo n.º 6
0
 def OnRenameMap(self, event):
     """Rename layer with dialog"""
     old_name = self.selected_layer.label
     gisrc, env = gscript.create_environment(
         gisenv()["GISDBASE"], self.selected_location.label, mapset=self.selected_mapset.label
     )
     new_name = self._getNewMapName(
         _("New name"),
         _("Rename map"),
         old_name,
         env=env,
         mapset=self.selected_mapset.label,
         element=self.selected_type.label,
     )
     if new_name:
         self.Rename(old_name, new_name)
Ejemplo n.º 7
0
    def OnDeleteMap(self, event):
        """Delete layer or mapset"""
        names = [
            self.selected_layer[i].label + '@' + self.selected_mapset[i].label
            for i in range(len(self.selected_layer))
        ]
        if len(names) < 10:
            question = _("Do you really want to delete map(s) <{m}>?").format(
                m=', '.join(names))
        else:
            question = _("Do you really want to delete {n} maps?").format(
                n=len(names))
        if self._confirmDialog(question, title=_('Delete map')) == wx.ID_YES:
            label = _("Deleting {name}...").format(name=names)
            self.showNotification.emit(message=label)
            for i in range(len(self.selected_layer)):
                gisrc, env = gscript.create_environment(
                    gisenv()['GISDBASE'], self.selected_location[i].label,
                    self.selected_mapset[i].label)
                removed, cmd = self._runCommand(
                    'g.remove',
                    flags='f',
                    type=self.selected_type[i].label,
                    name=self.selected_layer[i].label,
                    env=env)
                if removed == 0:
                    self._model.RemoveNode(self.selected_layer[i])
                    self.RefreshNode(self.selected_type[i], recursive=True)
                    Debug.msg(
                        1,
                        "LAYER " + self.selected_layer[i].label + " DELETED")

                    # remove map layer from layer tree if exists
                    if not isinstance(self._giface, StandaloneGrassInterface):
                        name = self.selected_layer[
                            i].label + '@' + self.selected_mapset[i].label
                        layers = self._giface.GetLayerList().GetLayersByName(
                            name)
                        for layer in layers:
                            self._giface.GetLayerList().DeleteLayer(layer)

                gscript.try_remove(gisrc)
            self.UnselectAll()
            self.showNotification.emit(message=_("g.remove completed"))
Ejemplo n.º 8
0
def setup_location(name, path, epsg, src_env):
    """Setup temporary location with different projection but
    same computational region as source location

    :param str name: name of new location
    :param path path: path to new location's database
    :param str epsg: EPSG code
    :param dict src_env: source environment

    :return str rcfile: name of new locations rcfile
    :return dict new_env: new environment
    """
    # Create new environment
    rcfile, new_env = gs.create_environment(path, name, "PERMANENT")
    # Location and mapset
    gs.create_location(path, name, epsg=epsg, overwrite=True)
    # Reproject region
    set_target_region(src_env, new_env)
    return rcfile, new_env
Ejemplo n.º 9
0
    def OnMetadata(self, event):
        """Show metadata of any raster/vector/3draster"""
        def done(event):
            gscript.try_remove(gisrc)

        if self.selected_type.label == 'raster':
            cmd = ['r.info']
        elif self.selected_type.label == 'vector':
            cmd = ['v.info']
        elif self.selected_type.label == 'raster_3d':
            cmd = ['r3.info']
        cmd.append('map=%s@%s' %
                   (self.selected_layer.label, self.selected_mapset.label))

        gisrc, env = gscript.create_environment(gisenv()['GISDBASE'],
                                                self.selected_location.label,
                                                self.selected_mapset.label)
        # print output to command log area
        # temp gisrc file must be deleted onDone
        self._giface.RunCmd(cmd, env=env, onDone=done)
Ejemplo n.º 10
0
 def OnDeleteMap(self, event):
     """Delete layer or mapset"""
     name = self.selected_layer.label
     gisrc, env = gscript.create_environment(gisenv()['GISDBASE'],
                                             self.selected_location.label,
                                             self.selected_mapset.label)
     if self._confirmDialog(question=_(
             "Do you really want to delete map <{m}> of type <{etype}> from mapset "
             "<{mapset}> in location <{loc}>?").format(
                 m=name,
                 mapset=self.selected_mapset.label,
                 etype=self.selected_type.label,
                 loc=self.selected_location.label),
                            title=_('Delete map')) == wx.ID_YES:
         label = _("Deleting {name}...").format(name=name)
         self.showNotification.emit(message=label)
         if self.selected_type.label == 'vector':
             removed, cmd = self._runCommand('g.remove',
                                             flags='f',
                                             type='vector',
                                             name=name,
                                             env=env)
         elif self.selected_type.label == 'raster':
             removed, cmd = self._runCommand('g.remove',
                                             flags='f',
                                             type='raster',
                                             name=name,
                                             env=env)
         else:
             removed, cmd = self._runCommand('g.remove',
                                             flags='f',
                                             type='raster_3d',
                                             name=name,
                                             env=env)
         if removed == 0:
             self._model.RemoveNode(self.selected_layer)
             self.RefreshNode(self.selected_type, recursive=True)
             Debug.msg(1, "LAYER " + name + " DELETED")
             self.showNotification.emit(
                 message=_("g.remove completed").format(cmd=cmd))
     gscript.try_remove(gisrc)
Ejemplo n.º 11
0
def getLocationTree(gisdbase, location, queue, mapsets=None):
    """Creates dictionary with mapsets, elements, layers for given location.
    Returns tuple with the dictionary and error (or None)"""
    tmp_gisrc_file, env = gscript.create_environment(gisdbase, location, "PERMANENT")
    env["GRASS_SKIP_MAPSET_OWNER_CHECK"] = "1"

    maps_dict = {}
    elements = ["raster", "raster_3d", "vector"]
    try:
        if not mapsets:
            mapsets = gscript.read_command("g.mapsets", flags="l", separator="comma", quiet=True, env=env).strip()
    except CalledModuleError:
        queue.put((maps_dict, _("Failed to read mapsets from location <{l}>.").format(l=location)))
        gscript.try_remove(tmp_gisrc_file)
        return
    else:
        listOfMapsets = mapsets.split(",")
        Debug.msg(4, "Location <{}>: {} mapsets found".format(location, len(listOfMapsets)))
        for each in listOfMapsets:
            maps_dict[each] = {}
            for elem in elements:
                maps_dict[each][elem] = []
    try:
        maplist = gscript.read_command(
            "g.list", flags="mt", type=elements, mapset=",".join(listOfMapsets), quiet=True, env=env
        ).strip()
    except CalledModuleError:
        queue.put((maps_dict, _("Failed to read maps from location <{l}>.").format(l=location)))
        gscript.try_remove(tmp_gisrc_file)
        return
    else:
        # fill dictionary
        listOfMaps = maplist.splitlines()
        Debug.msg(4, "Location <{}>: {} maps found".format(location, len(listOfMaps)))
        for each in listOfMaps:
            ltype, wholename = each.split("/")
            name, mapset = wholename.split("@")
            maps_dict[mapset][ltype].append(name)

    queue.put((maps_dict, None))
    gscript.try_remove(tmp_gisrc_file)
Ejemplo n.º 12
0
 def Rename(self, old, new):
     """Rename layer"""
     string = old + "," + new
     gisrc, env = gscript.create_environment(
         gisenv()["GISDBASE"], self.selected_location.label, self.selected_mapset.label
     )
     label = _("Renaming map <{name}>...").format(name=string)
     self.showNotification.emit(message=label)
     if self.selected_type.label == "vector":
         renamed, cmd = self._runCommand("g.rename", vector=string, env=env)
     elif self.selected_type.label == "raster":
         renamed, cmd = self._runCommand("g.rename", raster=string, env=env)
     else:
         renamed, cmd = self._runCommand("g.rename", raster3d=string, env=env)
     if renamed == 0:
         self.selected_layer.label = new
         self.selected_layer.data["name"] = new
         self.RefreshNode(self.selected_layer)
         self.showNotification.emit(message=_("{cmd} -- completed").format(cmd=cmd))
         Debug.msg(1, "LAYER RENAMED TO: " + new)
     gscript.try_remove(gisrc)
Ejemplo n.º 13
0
    def OnDeleteMap(self, event):
        """Delete layer or mapset"""
        name = self.selected_layer.label
        gisrc, env = gscript.create_environment(gisenv()['GISDBASE'],
                                                self.selected_location.label,
                                                self.selected_mapset.label)
        if self._confirmDialog(question=_(
                "Do you really want to delete map <{m}> of type <{etype}> from mapset "
                "<{mapset}> in location <{loc}>?").format(
                    m=name,
                    mapset=self.selected_mapset.label,
                    etype=self.selected_type.label,
                    loc=self.selected_location.label),
                               title=_('Delete map')) == wx.ID_YES:
            label = _("Deleting {name}...").format(name=name)
            self.showNotification.emit(message=label)

            removed, cmd = self._runCommand('g.remove',
                                            flags='f',
                                            type=self.selected_type.label,
                                            name=name,
                                            env=env)
            if removed == 0:
                self._model.RemoveNode(self.selected_layer)
                self.RefreshNode(self.selected_type, recursive=True)
                Debug.msg(1, "LAYER " + name + " DELETED")
                self.showNotification.emit(
                    message=_("g.remove completed").format(cmd=cmd))

                # remove map layer from layer tree if exists
                if not isinstance(self._giface, StandaloneGrassInterface):
                    name = self.selected_layer.label + '@' + self.selected_mapset.label
                    layers = self._giface.GetLayerList().GetLayersByName(name)
                    for layer in layers:
                        self._giface.GetLayerList().DeleteLayer(layer)

        gscript.try_remove(gisrc)
Ejemplo n.º 14
0
def get_reasons_location_not_removable(grassdb, location):
    """Get reasons why one location cannot be removed.

    Returns messages as list if there were any failed checks, otherwise empty list.
    """
    messages = []
    location_path = os.path.join(grassdb, location)

    # Check if location is current
    if is_location_current(grassdb, location):
        messages.append(
            _("Location <{location}> is the current location.").format(
                location=location_path
            )
        )
        return messages

    # Find mapsets in particular location
    tmp_gisrc_file, env = gs.create_environment(grassdb, location, "PERMANENT")
    env["GRASS_SKIP_MAPSET_OWNER_CHECK"] = "1"

    g_mapsets = (
        gs.read_command("g.mapsets", flags="l", separator="comma", quiet=True, env=env)
        .strip()
        .split(",")
    )

    # Append to the list of tuples
    mapsets = []
    for g_mapset in g_mapsets:
        mapsets.append((grassdb, location, g_mapset))

    # Concentenate both checks
    messages += get_reasons_mapsets_not_removable(mapsets, check_permanent=False)

    gs.try_remove(tmp_gisrc_file)
    return messages
Ejemplo n.º 15
0
 def Rename(self, old, new):
     """Rename layer"""
     string = old + ',' + new
     gisrc, env = gscript.create_environment(gisenv()['GISDBASE'],
                                             self.selected_location.label,
                                             self.selected_mapset.label)
     label = _("Renaming map <{name}>...").format(name=string)
     self.showNotification.emit(message=label)
     if self.selected_type.label == 'vector':
         renamed, cmd = self._runCommand('g.rename', vector=string, env=env)
     elif self.selected_type.label == 'raster':
         renamed, cmd = self._runCommand('g.rename', raster=string, env=env)
     else:
         renamed, cmd = self._runCommand('g.rename',
                                         raster3d=string,
                                         env=env)
     if renamed == 0:
         self.selected_layer.label = new
         self.selected_layer.data['name'] = new
         self.RefreshNode(self.selected_layer)
         self.showNotification.emit(message=_("{cmd} -- completed").format(
             cmd=cmd))
         Debug.msg(1, "LAYER RENAMED TO: " + new)
     gscript.try_remove(gisrc)
Ejemplo n.º 16
0
    def OnPasteMap(self, event):
        # copying between mapsets of one location
        if not self.copy_layer:
            if self.copy_mode:
                GMessage(_("No map selected for copying."), parent=self)
            else:
                GMessage(_("No map selected for moving."), parent=self)
            return

        gisrc, env = gscript.create_environment(
            gisenv()['GISDBASE'],
            self.selected_location.label,
            mapset=self.selected_mapset.label)
        gisrc2, env2 = gscript.create_environment(
            gisenv()['GISDBASE'],
            self.copy_location.label,
            mapset=self.copy_mapset.label)
        new_name = self.copy_layer.label
        if self.selected_location == self.copy_location:
            # within one mapset
            if self.selected_mapset == self.copy_mapset:
                # ignore when just moves map
                if self.copy_mode is False:
                    return
                new_name = self._getNewMapName(
                    _('New name'),
                    _('Select new name'),
                    self.copy_layer.label,
                    env=env,
                    mapset=self.selected_mapset.label,
                    element=self.copy_type.label)
                if not new_name:
                    return
            # within one location, different mapsets
            else:
                if map_exists(new_name,
                              element=self.copy_type.label,
                              env=env,
                              mapset=self.selected_mapset.label):
                    new_name = self._getNewMapName(
                        _('New name'),
                        _('Select new name'),
                        self.copy_layer.label,
                        env=env,
                        mapset=self.selected_mapset.label,
                        element=self.copy_type.label)
                    if not new_name:
                        return

            string = self.copy_layer.label + '@' + self.copy_mapset.label + ',' + new_name
            pasted = 0
            if self.copy_mode:
                label = _("Copying <{name}>...").format(name=string)
            else:
                label = _("Moving <{name}>...").format(name=string)
            self.showNotification.emit(message=label)
            if self.copy_type.label == 'vector':
                pasted, cmd = self._runCommand('g.copy',
                                               vector=string,
                                               env=env)
                node = 'vector'
            elif self.copy_type.label == 'raster':
                pasted, cmd = self._runCommand('g.copy',
                                               raster=string,
                                               env=env)
                node = 'raster'
            else:
                pasted, cmd = self._runCommand('g.copy',
                                               raster_3d=string,
                                               env=env)
                node = 'raster_3d'
            if pasted == 0:
                self.InsertLayer(name=new_name,
                                 mapset_node=self.selected_mapset,
                                 element_name=node)
                Debug.msg(1, "COPIED TO: " + new_name)
                if self.copy_mode:
                    self.showNotification.emit(
                        message=_("g.copy completed").format(cmd=cmd))
                else:
                    self.showNotification.emit(
                        message=_("g.copy completed").format(cmd=cmd))

                # remove old
                if not self.copy_mode:
                    self._removeMapAfterCopy(env2)

            gscript.try_remove(gisrc)
            gscript.try_remove(gisrc2)
            # expand selected mapset
            self.ExpandNode(self.selected_mapset, recursive=True)
            self._initVariablesCatalog()
        else:
            if self.copy_type.label == 'raster_3d':
                GError(_("Reprojection is not implemented for 3D rasters"),
                       parent=self)
                return
            if map_exists(new_name,
                          element=self.copy_type.label,
                          env=env,
                          mapset=self.selected_mapset.label):
                new_name = self._getNewMapName(
                    _('New name'),
                    _('Select new name'),
                    self.copy_layer.label,
                    env=env,
                    mapset=self.selected_mapset.label,
                    element=self.copy_type.label)
                if not new_name:
                    return
            gisdbase = gisenv()['GISDBASE']
            callback = lambda: self._onDoneReprojection(
                iEnv=env2, iGisrc=gisrc2, oGisrc=gisrc)
            dlg = CatalogReprojectionDialog(
                self, self._giface, gisdbase, self.copy_location.label,
                self.copy_mapset.label, self.copy_layer.label, env2, gisdbase,
                self.selected_location.label, self.selected_mapset.label,
                new_name, self.copy_type.label, env, callback)
            dlg.ShowModal()
Ejemplo n.º 17
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.º 18
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.º 19
0
    def OnPasteMap(self, event):
        """Paste layer"""
        # copying between mapsets of one location
        if not self.copy_layer:
            GMessage(_("No map selected for copying."), parent=self)
            return
        if self.selected_location == self.copy_location:
            gisrc, env = gscript.create_environment(
                gisenv()["GISDBASE"], self.selected_location.label, mapset=self.selected_mapset.label
            )
            new_name = self._getNewMapName(
                _("New name"),
                _("Copy map"),
                self.copy_layer.label,
                env=env,
                mapset=self.selected_mapset.label,
                element=self.copy_type.label,
            )
            if not new_name:
                return
            if map_exists(new_name, element=self.copy_type.label, env=env, mapset=self.selected_mapset.label):
                GMessage(_("Failed to copy map: new map has the same name"), parent=self)
                return

            if not self.selected_type:
                found = self._model.SearchNodes(parent=self.selected_mapset, type="element", name=self.copy_type.label)
                self.selected_type = found[0] if found else None

            overwrite = False
            if self.selected_type:
                found = self._model.SearchNodes(parent=self.selected_type, type=self.copy_type.label, name=new_name)
                if found and found[0]:
                    dlg = wx.MessageDialog(
                        parent=self,
                        message=_(
                            "Map <{map}> already exists " "in the current mapset. " "Do you want to overwrite it?"
                        ).format(map=new_name),
                        caption=_("Overwrite?"),
                        style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION,
                    )
                    ret = dlg.ShowModal()
                    dlg.Destroy()
                    if ret == wx.ID_YES:
                        overwrite = True

            string = self.copy_layer.label + "@" + self.copy_mapset.label + "," + new_name

            pasted = 0
            label = _("Copying <{name}>...").format(name=string)
            self.showNotification.emit(message=label)
            if self.copy_type.label == "vector":
                pasted, cmd = self._runCommand("g.copy", vector=string, overwrite=overwrite, env=env)
                node = "vector"
            elif self.copy_type.label == "raster":
                pasted, cmd = self._runCommand("g.copy", raster=string, overwrite=overwrite, env=env)
                node = "raster"
            else:
                pasted, cmd = self._runCommand("g.copy", raster_3d=string, overwrite=overwrite, env=env)
                node = "raster_3d"
            if pasted == 0:
                self.InsertLayer(name=new_name, mapset_node=self.selected_mapset, element_name=node)
                Debug.msg(1, "COPIED TO: " + new_name)
                self.showNotification.emit(message=_("g.copy completed").format(cmd=cmd))
            gscript.try_remove(gisrc)
        else:
            if self.copy_type.label == "raster_3d":
                GError(_("Reprojection is not implemented for 3D rasters"), parent=self)
                return
            gisdbase = gisenv()["GISDBASE"]
            dlg = CatalogReprojectionDialog(
                self,
                self._giface,
                gisdbase,
                self.copy_location.label,
                self.copy_mapset.label,
                self.copy_layer.label,
                gisdbase,
                self.selected_location.label,
                self.selected_mapset.label,
                etype=self.copy_type.label,
            )
            dlg.Show()

        # expand selected mapset
        self.ExpandNode(self.selected_mapset, recursive=True)