示例#1
0
    def open(self, mode=None, mtype=None, overwrite=None):
        """Open the raster if exist or created a new one.

        :param str mode: Specify if the map will be open with read or write mode
                     ('r', 'w')
        :param str type: If a new map is open, specify the type of the map(`CELL`,
                     `FCELL`, `DCELL`)
        :param bool overwrite: Use this flag to set the overwrite mode of existing
                          raster maps

        if the map already exist, automatically check the type and set:

            * self.mtype

        Set all the privite, attributes:

            * self._fd;
            * self._gtype
            * self._rows and self._cols

        """
        self.mode = mode if mode else self.mode
        self.mtype = mtype if mtype else self.mtype
        self.overwrite = overwrite if overwrite is not None else self.overwrite

        if self.mode == "r":
            if self.exist():
                self.info.read()
                self.cats.mtype = self.mtype
                self.cats.read()
                self.hist.read()
                self._fd = libraster.Rast_open_old(self.name, self.mapset)
                self._gtype = libraster.Rast_get_map_type(self._fd)
                self.mtype = RTYPE_STR[self._gtype]
            else:
                str_err = _("The map does not exist, I can't open in 'r' mode")
                raise OpenError(str_err)
        elif self.mode == "w":
            if self.exist():
                if not self.overwrite:
                    str_err = _("Raster map <{0}> already exists"
                                " and will be not overwritten")
                    raise OpenError(str_err.format(self))
            if self._gtype is None:
                raise OpenError(_("Raster type not defined"))
            self._fd = libraster.Rast_open_new(self.name, self._gtype)
        else:
            raise OpenError("Open mode: %r not supported,"
                            " valid mode are: r, w")
        # read rows and cols from the active region
        self._rows = libraster.Rast_window_rows()
        self._cols = libraster.Rast_window_cols()
示例#2
0
def ReadEpsgCodes(path):
    """Read EPSG code from the file

    :param path: full path to the file with EPSG codes

    Raise OpenError on failure.

    :return: dictionary of EPSG code
    """
    epsgCodeDict = dict()
    try:
        try:
            f = open(path, "r")
        except IOError:
            raise OpenError(_("failed to open '{0}'").format(path))

        code = None
        for line in f.readlines():
            line = line.strip()
            if len(line) < 1:
                continue

            if line[0] == '#':
                descr = line[1:].strip()
            elif line[0] == '<':
                code, params = line.split(" ", 1)
                try:
                    code = int(code.replace('<', '').replace('>', ''))
                except ValueError as e:
                    raise OpenError('{0}'.format(e))

            if code is not None:
                epsgCodeDict[code] = (descr, params)
                code = None

        f.close()
    except Exception as e:
        raise OpenError('{0}'.format(e))

    return epsgCodeDict
示例#3
0
    def open(
        self,
        mode=None,
        layer=1,
        overwrite=None,
        with_z=None,
        # parameters valid only if mode == 'w'
        tab_name="",
        tab_cols=None,
        link_name=None,
        link_key="cat",
        link_db="$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db",
        link_driver="sqlite",
    ):
        """Open a Vector map.


        :param mode: open a vector map in ``r`` in reading, ``w`` in writing
                     and in ``rw`` read and write mode
        :type mode: str
        :param layer: specify the layer that you want to use
        :type layer: int
        :param overwrite: valid only for ``w`` mode
        :type overwrite: bool
        :param with_z: specify if vector map must be open with third dimension
                       enabled or not. Valid only for ``w`` mode,
                       default: False
        :type with_z: bool
        :param tab_name: define the name of the table that will be generate
        :type tab_name: str
        :param tab_cols: define the name and type of the columns of the
                         attribute table of the vecto map
        :type tab_cols: list of pairs
        :param link_name: define the name of the link connecttion with the
                          database
        :type link_name: str
        :param link_key: define the nema of the column that will be use as
                         vector category
        :type link_key: str
        :param link_db: define the database connection parameters
        :type link_db: str
        :param link_driver: define witch database driver will be used
        :param link_driver: str

        Some of the parameters are valid only with mode ``w`` or ``rw``

        See more examples in the documentation of the ``read`` and ``write``
        methods
        """
        self.mode = mode if mode else self.mode
        with_z = libvect.WITH_Z if with_z else libvect.WITHOUT_Z
        # check if map exists or not
        if not self.exist() and self.mode != "w":
            raise OpenError("Map <%s> not found." % self._name)
        if libvect.Vect_set_open_level(self._topo_level) != 0:
            raise OpenError("Invalid access level.")
        # update the overwrite attribute
        self.overwrite = overwrite if overwrite is not None else self.overwrite
        # check if the mode is valid
        if self.mode not in ("r", "rw", "w"):
            raise ValueError("Mode not supported. Use one of: 'r', 'rw', 'w'.")

        # check if the map exist
        if self.exist() and self.mode in ("r", "rw"):
            # open in READ mode
            if self.mode == "r":
                openvect = libvect.Vect_open_old2(self.c_mapinfo, self.name,
                                                  self.mapset, str(layer))
            # open in READ and WRITE mode
            elif self.mode == "rw":
                openvect = libvect.Vect_open_update2(self.c_mapinfo, self.name,
                                                     self.mapset, str(layer))

            # instantiate class attributes
            self.dblinks = DBlinks(self.c_mapinfo)

        # If it is opened in write mode
        if self.mode == "w":
            openvect = libvect.Vect_open_new(self.c_mapinfo, self.name, with_z)
            self.dblinks = DBlinks(self.c_mapinfo)

        if self.mode in ("w", "rw") and tab_cols:
            # create a link
            link = Link(
                layer,
                link_name if link_name else self.name,
                tab_name if tab_name else self.name,
                link_key,
                link_db,
                link_driver,
            )
            # add the new link
            self.dblinks.add(link)
            # create the table
            table = link.table()
            table.create(tab_cols, overwrite=overwrite)
            table.conn.commit()

        # check the C function result.
        if openvect == -1:
            str_err = "Not able to open the map, C function return %d."
            raise OpenError(str_err % openvect)

        # Load attribute table for selected layer.
        if len(self.dblinks) == 0:
            self.layer = layer
            self.table = None
            self.n_lines = 0
        else:
            layer_db_link = self.dblinks.by_layer(layer)
            if not layer_db_link:
                raise LookupError(
                    "There appears to be no database link for layer %d of <%s>."
                    % (layer, self.name))
            if layer_db_link.layer != layer:
                raise RuntimeError(
                    "The databse link for layer %d of <%s> references layer %d."
                    % (layer, self.name, layer_db_link.layer))
            self.layer = layer
            try:
                self.table = layer_db_link.table()
            except Exception as error:
                raise RuntimeError(
                    "Loading the attribute table for layer %d of <%s> failed."
                    % (layer, self.name)) from error
            self.n_lines = self.table.n_rows()

        self.writeable = self.mapset == utils.getenv("MAPSET")
        # Initialize the finder
        self.find = {
            "by_point":
            PointFinder(self.c_mapinfo, self.table, self.writeable),
            "by_bbox":
            BboxFinder(self.c_mapinfo, self.table, self.writeable),
            "by_polygon":
            PolygonFinder(self.c_mapinfo, self.table, self.writeable),
        }
        self.find_by_point = self.find["by_point"]
        self.find_by_bbox = self.find["by_bbox"]
        self.find_by_polygon = self.find["by_polygon"]
示例#4
0
    def open(self, mode=None, mtype=None, overwrite=None):
        """Open the map, if the map already exist: determine the map type
        and copy the map to the segment files;
        else, open a new segment map.

        :param mode: specify if the map will be open with read, write or
                     read/write mode ('r', 'w', 'rw')
        :type mode: str
        :param mtype: specify the map type, valid only for new maps: CELL,
                      FCELL, DCELL
        :type mtype: str
        :param overwrite: use this flag to set the overwrite mode of existing
                          raster maps
        :type overwrite: bool
        """
        # read rows and cols from the active region
        self._rows = libraster.Rast_window_rows()
        self._cols = libraster.Rast_window_cols()

        self.mode = mode if mode else self.mode
        self.mtype = mtype if mtype else self.mtype
        self.overwrite = overwrite if overwrite is not None else self.overwrite

        if self.exist():
            self.info.read()
            self.cats.mtype = self.mtype
            self.cats.read()
            self.hist.read()
            if (self.mode == "w"
                    or self.mode == "rw") and self.overwrite is False:
                str_err = _("Raster map <{0}> already exists. Use overwrite.")
                fatal(str_err.format(self))

            # We copy the raster map content into the segments
            if self.mode == "rw" or self.mode == "r":
                self._fd = libraster.Rast_open_old(self.name, self.mapset)
                self._gtype = libraster.Rast_get_map_type(self._fd)
                self.mtype = RTYPE_STR[self._gtype]
                # initialize the segment, I need to determine the mtype of the
                # map
                # before to open the segment
                self.segment.open(self)
                self.map2segment()
                self.segment.flush()
                self.cats.read()
                self.hist.read()

                if self.mode == "rw":
                    # warning(_(WARN_OVERWRITE.format(self)))
                    # Close the file descriptor and open it as new again
                    libraster.Rast_close(self._fd)
                    self._fd = libraster.Rast_open_new(self.name, self._gtype)
            # Here we simply overwrite the existing map without content copying
            elif self.mode == "w":
                # warning(_(WARN_OVERWRITE.format(self)))
                self._gtype = RTYPE[self.mtype]["grass type"]
                self.segment.open(self)
                self._fd = libraster.Rast_open_new(self.name, self._gtype)
        else:
            if self.mode == "r":
                str_err = _("Raster map <{0}> does not exist")
                raise OpenError(str_err.format(self.name))

            self._gtype = RTYPE[self.mtype]["grass type"]
            self.segment.open(self)
            self._fd = libraster.Rast_open_new(self.name, self._gtype)