コード例 #1
0
    def new_map(self, mapa, layer, tab_sufix, objs, values, tab_subname=''):
        """Return
        """
        map_out = VectorTopo(mapa)
        if objs == [] or objs is None:
            return None

        tab_sufix_out = OUT_TABLES_NAMES[tab_sufix]
        tab_name = self.road_name + tab_sufix_out + tab_subname

        columns = OUT_TABLES[tab_sufix]
        if layer == 1:
            map_out.open('w', layer=layer, with_z=True, tab_name=tab_name,
                         tab_cols=columns)
        else:
            map_out.open('rw')
            link = Link(layer, tab_name, tab_name, 'cat' + str(layer))
            map_out.dblinks.add(link)
            table = link.table()
            if not table.exist():
                table.create(columns)
            table.conn.commit()
            map_out.close()

            map_out.open('rw', layer=layer, with_z=True)
        for i, obj in enumerate(objs):
            map_out.write(obj, i + 1, values[i])
        map_out.table.conn.commit()
        map_out.close()
コード例 #2
0
def main(opt, flg):
    #
    # Set check variables
    #
    overwrite = True
    rasters = opt['rasters'].split(',') if opt['rasters'] else []
    rprefix = opt['rprefix'].split(',') if opt['rprefix'] else []

    def split(x): return x.split('@') if '@' in x else (x, '')

    vname, vmset = split(opt['vector'])
    shpcsv = opt['shpcsv'] if opt['shpcsv'] else vname + '.csv'
    rstcsv = (opt['rstcsv'].split(',') if opt['rstcsv']
              else [split(rst)[0] + '.csv' for rst in rasters])
    zones = opt['zones'] if opt['zones'] else vname + '_zones'
    nprocs = int(opt.get('nprocs', 1))
    if rasters:
        if rprefix and len(rasters) != len(rprefix):
            raise
        if len(rasters) != len(rstcsv):
            raise
        prefixes = rprefix if rprefix else rasters

    skipshp = opt['skipshape'].split(',') if opt['skipshape'] else []
    skiprst = opt['skipunivar'].split(',') if opt['skipunivar'] else []
    layer = int(opt['layer'])
    newlayer = int(opt['newlayer'])
    newlayername = (opt['newlayername'] if opt['newlayername']
                    else vname + '_stats')
    newtabname = opt['newtabname'] if opt['newtabname'] else vname + '_stats'
    rstpercentile = float(opt['rstpercentile'])
    separator = opt.get('separator', ';')

    #
    # compute
    #
    if not os.path.exists(shpcsv):
        get_shp_csv(opt['vector'], shpcsv, overwrite, separator)
    if not get_mapset_raster(zones):
        get_zones(opt['vector'], zones, layer)
    if not rstcsv or not os.path.exists(rstcsv[0]):
        get_rst_csv(rasters, zones, rstcsv, rstpercentile, overwrite,
                    nprocs, separator)

    newlink = Link(newlayer, newlayername, newtabname)
    newtab = newlink.table()
    with Vector(vname, vmset, mode='r', layer=layer) as vct:
        mode = 'r' if newlink in vct.dblinks else 'rw'

    with VectorTopo(vname, vmset, mode=mode, layer=layer) as vct:
        update_cols(newtab, shpcsv, rstcsv, prefixes, skipshp, skiprst, separator=separator)

        if mode == 'rw':
            # add the new link
            vct.dblinks.add(newlink)
            vct.build()
コード例 #3
0
ファイル: road_tables.py プロジェクト: lucadelu/grass-addons
    def _create_table(self):
        """Return"""
        link = Link(self.layer, self.tab_name, self.tab_name, "cat" + str(self.layer))
        self.polygon.dblinks.add(link)
        table = link.table()

        tab_sufix = self.name
        if self.name == "":
            tab_sufix = "first"
        TABLES[tab_sufix][0] = ("cat" + str(self.layer), "INTEGER PRIMARY KEY")
        if not table.exist():
            table.create(TABLES[tab_sufix])
            table.conn.commit()
コード例 #4
0
    def _create_table(self):
        """Return
        """
        link = Link(self.layer, self.tab_name, self.tab_name,
                    'cat' + str(self.layer))
        self.polygon.dblinks.add(link)
        table = link.table()

        tab_sufix = self.name
        if self.name == '':
            tab_sufix = 'first'
        TABLES[tab_sufix][0] = (u'cat' + str(self.layer),
                                u'INTEGER PRIMARY KEY')
        if not table.exist():
            table.create(TABLES[tab_sufix])
            table.conn.commit()
コード例 #5
0
 def create_db_links(self, vect_map, linking_elem):
     """vect_map an open vector map
     """
     dblinks = {}
     for layer_name, layer_dscr in linking_elem.iteritems():
         # Create DB links
         dblink = Link(layer=layer_dscr.layer_number,
                       name=layer_name,
                       table=vect_map.name + layer_dscr.table_suffix,
                       key='cat')
         # add link to vector map
         if dblink not in vect_map.dblinks:
             vect_map.dblinks.add(dblink)
         # create table
         dbtable = dblink.table()
         dbtable.create(layer_dscr.cols, overwrite=True)
         dblinks[layer_name] = self.LinkDescr(dblink.layer, dbtable)
     return dblinks
コード例 #6
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
        """
        with_z = libvect.WITH_Z if with_z else libvect.WITHOUT_Z
        # check if map exists or not
        if not self.exist() and 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 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 mode in ('r', 'rw'):
            # open in READ mode
            if mode == 'r':
                openvect = libvect.Vect_open_old2(self.c_mapinfo, self.name,
                                                  self.mapset, str(layer))
            # open in READ and WRITE mode
            elif 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 mode == 'w':
            openvect = libvect.Vect_open_new(self.c_mapinfo, self.name, with_z)
            self.dblinks = DBlinks(self.c_mapinfo)
            if 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)
                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)

        if len(self.dblinks) == 0:
            self.layer = layer
            self.table = None
            self.n_lines = 0
        else:
            self.layer = self.dblinks.by_layer(layer).layer
            self.table = self.dblinks.by_layer(layer).table()
            self.n_lines = self.table.n_rows()
        self.writable = self.mapset == functions.getenv("MAPSET")
        self.find = {
            'by_point': PointFinder(self.c_mapinfo, self.table, self.writable),
            'by_box': BboxFinder(self.c_mapinfo, self.table, self.writable),
            'by_polygon': PolygonFinder(self.c_mapinfo, self.table,
                                        self.writable),
        }
コード例 #7
0
ファイル: abstract.py プロジェクト: caomw/grass
    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
        """
        with_z = libvect.WITH_Z if with_z else libvect.WITHOUT_Z
        # check if map exists or not
        if not self.exist() and 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 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 mode in ('r', 'rw'):
            # open in READ mode
            if mode == 'r':
                openvect = libvect.Vect_open_old2(self.c_mapinfo, self.name,
                                                  self.mapset, str(layer))
            # open in READ and WRITE mode
            elif 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 mode == 'w':
            openvect = libvect.Vect_open_new(self.c_mapinfo, self.name, with_z)
            self.dblinks = DBlinks(self.c_mapinfo)
            if 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)
                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)

        if len(self.dblinks) == 0:
            self.layer = layer
            self.table = None
            self.n_lines = 0
        else:
            self.layer = self.dblinks.by_layer(layer).layer
            self.table = self.dblinks.by_layer(layer).table()
            self.n_lines = self.table.n_rows()
        self.writable = self.mapset == functions.getenv("MAPSET")
        self.find = {'by_point': PointFinder(self.c_mapinfo, self.table,
                                             self.writable),
                     'by_box': BboxFinder(self.c_mapinfo, self.table,
                                          self.writable),
                     'by_polygon': PolygonFinder(self.c_mapinfo, self.table,
                                                 self.writable), }
コード例 #8
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"]
コード例 #9
0
def main(opt, flg):
    #
    # Set check variables
    #
    overwrite = True
    rasters = opt["rasters"].split(",") if opt["rasters"] else []
    rprefix = opt["rprefix"].split(",") if opt["rprefix"] else []

    def split(x):
        return x.split("@") if "@" in x else (x, "")

    vname, vmset = split(opt["vector"])
    shpcsv = opt["shpcsv"] if opt["shpcsv"] else vname + ".csv"
    rstcsv = (opt["rstcsv"].split(",") if opt["rstcsv"] else
              [split(rst)[0] + ".csv" for rst in rasters])
    zones = opt["zones"] if opt["zones"] else vname + "_zones"
    nprocs = int(opt.get("nprocs", 1))
    if rasters:
        if rprefix and len(rasters) != len(rprefix):
            raise
        if len(rasters) != len(rstcsv):
            raise
        prefixes = rprefix if rprefix else rasters
    else:
        prefixes = None

    skipshp = opt["skipshape"].split(",") if opt["skipshape"] else []
    skiprst = opt["skipunivar"].split(",") if opt["skipunivar"] else []
    layer = int(opt["layer"])
    newlayer = int(opt["newlayer"])
    newlayername = opt["newlayername"] if opt[
        "newlayername"] else vname + "_stats"
    newtabname = opt["newtabname"] if opt["newtabname"] else vname + "_stats"
    rstpercentile = float(opt["rstpercentile"])
    separator = opt.get("separator", ";")

    #
    # compute
    #
    if not os.path.exists(shpcsv):
        get_shp_csv(opt["vector"], shpcsv, overwrite, separator)
    if not get_mapset_raster(zones):
        get_zones(opt["vector"], zones, layer)
    if not rstcsv or not os.path.exists(rstcsv[0]):
        get_rst_csv(rasters, zones, rstcsv, rstpercentile, overwrite, nprocs,
                    separator)

    newlink = Link(newlayer, newlayername, newtabname)
    newtab = newlink.table()
    with Vector(vname, vmset, mode="r", layer=layer) as vct:
        mode = "r" if newlink in vct.dblinks else "rw"

    with VectorTopo(vname, vmset, mode=mode, layer=layer) as vct:
        update_cols(newtab,
                    shpcsv,
                    rstcsv,
                    prefixes,
                    skipshp,
                    skiprst,
                    separator=separator)

        if mode == "rw":
            # add the new link
            vct.dblinks.add(newlink)
            vct.build()