Vector

bbox

create a bounding box vector object or file.

boundary

Get the boundary of the largest geometry as new vector object.

centerdist

Get the center distance between two vector objects.

dissolve

dissolve the polygons of a vector file by an attribute field

feature2vector

create a Vector object from ogr features

intersect

intersect two Vector objects

set_field

Wrapper for setting a field.

Vector

This is intended as a vector meta information handler with options for reading and writing vector data in a convenient manner by simplifying the numerous options provided by the OGR python binding.

vectorize

Vectorization of an array using osgeo.gdal.Polygonize().

wkt2vector

convert well-known text geometries to a Vector object.

class spatialist.vector.Vector(filename=None, driver=None)[source]

Bases: object

This is intended as a vector meta information handler with options for reading and writing vector data in a convenient manner by simplifying the numerous options provided by the OGR python binding.

Parameters:
  • filename (str | None) –

    the vector file to read; if filename is None, a new in-memory Vector object is created. In this case driver is overridden and set to ‘MEM’. The following file extensions are auto-detected:

    • .geojson (GeoJSON)

    • .gpkg (GPKG)

    • .json (GeoJSON)

    • .kml (KML)

    • .shp (ESRI Shapefile)

  • driver (str | None) – the vector file format; needs to be defined if the format cannot be auto-detected from the filename extension

__getitem__(expression)[source]

subset the vector object by index or attribute.

Parameters:

expression (int | str) – the key or expression to be used for subsetting. See osgeo.ogr.Layer.SetAttributeFilter() for details on the expression syntax.

Returns:

a vector object matching the specified criteria

Return type:

Vector | None

Examples

Assuming we have a shapefile called testsites.shp, which has an attribute sitename, we can subset individual sites and write them to new files like so:

>>> from spatialist import Vector
>>> filename = 'testsites.shp'
>>> with Vector(filename)["sitename='site1'"] as site1:
>>>     site1.write('site1.shp')
addfeature(geometry, fields=None)[source]

add a feature to the vector object from a geometry

Parameters:
  • geometry (Geometry) – the geometry to add as a feature

  • fields (dict[str, Any] | None) – the field names and values to assign to the new feature

Return type:

None

addfield(name, type, width=10, values=None)[source]

add a field to the vector layer

Parameters:
  • name (str) – the field name

  • type (int) – the OGR Field Type (OFT), e.g. ogr.OFTString. See osgeo.ogr.FieldDefn.

  • width (int) – the width of the new field (only for ogr.OFTString fields)

  • values (list[Any] | None) – an optional list with values for each feature to assign to the new field. The length must be identical to the number of features.

Return type:

None

addlayer(name, srs, geomType)[source]

add a layer to the vector layer

Parameters:
Return type:

None

addvector(vec)[source]

add a vector object to the layer of the current Vector object

Parameters:
  • vec (Vector) – the vector object to add

  • merge (bool) – merge overlapping polygons?

Return type:

None

bbox(outname=None, driver=None, overwrite=True)[source]

create a bounding box from the extent of the Vector object

Parameters:
  • outname (str | None) – the name of the vector file to be written; if None, a Vector object is returned

  • driver (str | None) – the name of the file format to write

  • overwrite (bool) – overwrite an already existing file?

Return type:

Vector | None

Returns:

if outname is None, the bounding box Vector object

clone()[source]
Return type:

Vector

close()[source]

closes the OGR vector file connection

Return type:

None

convert2wkt(set3D=True)[source]

export the geometry of each feature as a wkt string

Parameters:

set3D (bool) – keep the third (height) dimension?

Return type:

list[str]

property extent: dict[str, float]

the extent of the vector object

Return type:

a dictionary with keys xmin, xmax, ymin, ymax

property fieldDefs: list[FieldDefn]
Return type:

the field definition for each field of the Vector object

property fieldnames: list[str]
Return type:

the names of the fields

filename: str | None
property geomType: int
Return type:

the layer geometry type

property geomTypes: list[str]
Return type:

the geometry type of each feature

getArea()[source]
Return type:

float

Returns:

the area of the vector geometries

getFeatureByAttribute(fieldname, attribute)[source]

get features by field attribute

Parameters:
  • fieldname (str) – the name of the queried field

  • attribute (int | str) – the field value of interest

Return type:

Feature | list[Feature] | None

Returns:

the feature(s) matching the search query

getFeatureByIndex(index)[source]

get features by numerical (positional) index

Parameters:

index (int) – the queried index

Return type:

Feature | None

Returns:

the requested feature

getProjection(type)[source]

get the CRS of the Vector object. See spatialist.auxil.crsConvert().

Parameters:

type (str) – the type of projection required.

Return type:

int | str | SpatialReference

Returns:

the output CRS

getUniqueAttributes(fieldname)[source]
Parameters:

fieldname (str) – the name of the field of interest

Return type:

list[int | str]

Returns:

the unique attributes of the field

getfeatures()[source]
Return type:

list[Feature]

Returns:

a list of cloned features

init_features()[source]

delete all in-memory features

Return type:

None

init_layer()[source]

initialize a layer object

Return type:

None

property layerdef: FeatureDefn
Return type:

the layer’s feature definition

property layername: str
Return type:

the name of the layer

load()[source]

load all feature into memory

Return type:

None

property nfeatures: int
Return type:

the number of features

property nfields: int
Return type:

the number of fields

property nlayers: int
Return type:

the number of layers

property proj4: str
Return type:

the CRS in PRO4 format

reproject(projection)[source]

in-memory reprojection

Parameters:

projection (int | str | SpatialReference) – the target CRS. See spatialist.auxil.crsConvert().

Return type:

None

setCRS(crs)[source]

directly reset the spatial reference system of the vector object. This is not going to reproject the Vector object, see reproject() instead.

Parameters:

crs (int | str | SpatialReference) – the input CRS

Return type:

None

Example

>>> site = Vector('shape.shp')
>>> site.setCRS('+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs ')
property srs: SpatialReference
Return type:

the geometry’s spatial reference system

to_geopandas()[source]

Convert the object to a geopandas GeoDataFrame. DateTime fields are converted to pandas.Timestamp using pandas.to_datetime().

Return type:

GeoDataFrame

Returns:

the dataframe object

write(outfile, driver=None, overwrite=True)[source]

write the Vector object to a file

Parameters:
  • outfile (str) –

    the name of the file to write; the following extensions are automatically detected for determining the format driver:

    • .geojson (GeoJSON)

    • .gpkg (GPKG)

    • .json (GeoJSON)

    • .kml (KML)

    • .shp (ESRI Shapefile)

  • driver (str | None) – the output file format; default None: try to autodetect from the file name extension

  • overwrite (bool) – overwrite an already existing file?

Return type:

None

spatialist.vector.bbox(coordinates, crs, outname=None, driver=None, overwrite=True, buffer=None)[source]

create a bounding box vector object or file. The CRS can be in either WKT, EPSG or PROJ4 format

Parameters:
  • coordinates (dict[str, int | float]) – a dictionary containing numerical variables with keys xmin, xmax, ymin and ymax.

  • crs (int | str | SpatialReference) – the coordinate reference system of the coordinates. See crsConvert() for options.

  • outname (str | None) – the file to write to. If None, the bounding box is returned as Vector object.

  • driver (str | None) – the output file format; needs to be defined if the format cannot be auto-detected from the filename extension.

  • overwrite (bool) – overwrite an existing file?

  • buffer (int | float | tuple[int | float, int | float] | None) – a buffer to add around coordinates. Default None: do not add a buffer. A tuple is interpreted as (x buffer, y buffer).

Return type:

Vector | None

Returns:

the bounding box Vector object

spatialist.vector.boundary(vectorobject, expression=None, outname=None)[source]

Get the boundary of the largest geometry as new vector object. The following steps are performed:

  • find the largest geometry matching the expression

  • compute the geometry’s boundary using osgeo.ogr.Geometry.Boundary(), returning a MULTILINE geometry

  • select the longest line of the MULTILINE geometry

  • create a closed linear ring from this longest line

  • create a polygon from this linear ring

  • create a new Vector object and add the newly created polygon

Parameters:
  • vectorobject (Vector) – the vector object containing multiple polygon geometries, e.g. all geometries with a certain value in one field.

  • expression (str | None) – the SQL expression to select the candidates for the largest geometry.

  • outname (str | None) – the name of the output vector file; if None, an in-memory object of type Vector is returned.

Return type:

Vector | None

Returns:

if outname is None, a vector object pointing to an in-memory dataset else None

spatialist.vector.centerdist(obj1, obj2)[source]

Get the center distance between two vector objects.

Parameters:
Return type:

float

Returns:

the distance in units of the source object’s CRS

spatialist.vector.dissolve(infile, outfile, field, layername=None)[source]

dissolve the polygons of a vector file by an attribute field

Parameters:
  • infile (str) – the input vector file

  • outfile (str) – the output shapefile

  • field (str) – the field name to merge the polygons by

  • layername (str | None) – the name of the output vector layer; If set to None the layername will be the basename of infile without extension

Return type:

None

spatialist.vector.feature2vector(feature, ref, layername=None)[source]

create a Vector object from ogr features

Parameters:
  • feature (Feature | list[Feature]) – a single feature or a list of features

  • ref (Vector) – a reference Vector object to retrieve geo information from

  • layername (str | None) – the name of the output layer; retrieved from ref if None

Return type:

Vector

Returns:

the new Vector object

spatialist.vector.intersect(obj1, obj2)[source]

intersect two Vector objects

Parameters:
  • obj1 (Vector) – the first vector object; this object is reprojected to the CRS of obj2 if necessary

  • obj2 (Vector) – the second vector object

Return type:

Vector | None

Returns:

the intersection of obj1 and obj2 if both intersect and None otherwise

spatialist.vector.set_field(target, name, type, width=10, values=None)[source]

Wrapper for setting a field. DateTime fields are rounded to milliseconds.

Parameters:
  • target (Vector | Feature) – the object for which to set the field

  • name (str) – the field name

  • type (int) – the OGR Field Type (OFT), e.g. ogr.OFTString. See osgeo.ogr.FieldDefn.

  • width (int) – the width of the new field (only for ogr.OFTString fields)

  • values (Any) – an optional list with values for each feature to assign to the new field. If target is of type Vector, the length must be identical to the number of features.

Return type:

None

spatialist.vector.vectorize(target, reference, outname=None, layername='layer', fieldname='value', driver=None)[source]

Vectorization of an array using osgeo.gdal.Polygonize().

Parameters:
  • target (ndarray[tuple[Any, ...], dtype[Any]]) – the input array. Each identified object of pixels with the same value will be converted into a vector feature.

  • reference (Raster) – a reference Raster object to retrieve geo information and extent from.

  • outname (str | None) – the name of the vector file. If None a vector object is returned.

  • layername (str) – the name of the vector object layer.

  • fieldname (str) – the name of the field to contain the raster value for the respective vector feature.

  • driver (str | None) – the vector file type of outname. Several extensions are read automatically (see Vector.write()). Is ignored if outname=None.

Return type:

Vector | None

spatialist.vector.wkt2vector(wkt, srs, layername='wkt')[source]

convert well-known text geometries to a Vector object.

Parameters:
Return type:

Vector

Returns:

the vector representation

Examples

>>> from spatialist.vector import wkt2vector
>>> wkt1 = 'POLYGON ((0. 0., 0. 1., 1. 1., 1. 0., 0. 0.))'
>>> with wkt2vector(wkt1, srs=4326) as vec:
>>>     print(vec.getArea())
1.0
>>> wkt2 = 'POLYGON ((1. 1., 1. 2., 2. 2., 2. 1., 1. 1.))'
>>> with wkt2vector([wkt1, wkt2], srs=4326) as vec:
>>>     print(vec.getArea())
2.0