========GDAL API========.. module:: django.contrib.gis.gdal:synopsis: GeoDjango's high-level interface to the GDAL library.`GDAL`__ stands for **Geospatial Data Abstraction Library**,and is a veritable "Swiss army knife" of GIS data functionality. A subsetof GDAL is the `OGR`__ Simple Features Library, which specializesin reading and writing vector geographic data in a variety of standardformats.GeoDjango provides a high-level Python interface for some of thecapabilities of OGR, including the reading and coordinate transformationof vector spatial data and minimal support for GDAL's features with respectto raster (image) data... note::Although the module is named ``gdal``, GeoDjango only supports some of thecapabilities of OGR and GDAL's raster features at this time.__ https://gdal.org/__ https://gdal.org/user/vector_data_model.htmlOverview========.. _gdal_sample_data:Sample Data-----------The GDAL/OGR tools described here are designed to help you read inyour geospatial data, in order for most of them to be useful you haveto have some data to work with. If you're starting out and don't yethave any data of your own to use, GeoDjango tests contain a number ofdata sets that you can use for testing. You can download them here::$ wget https://raw.githubusercontent.com/django/django/main/tests/gis_tests/data/cities/cities.{shp,prj,shx,dbf}$ wget https://raw.githubusercontent.com/django/django/main/tests/gis_tests/data/rasters/raster.tifVector Data Source Objects==========================``DataSource``--------------:class:`DataSource` is a wrapper for the OGR data source object thatsupports reading data from a variety of OGR-supported geospatial fileformats and data sources using a consistent interface. Eachdata source is represented by a :class:`DataSource` object which containsone or more layers of data. Each layer, represented by a :class:`Layer`object, contains some number of geographic features (:class:`Feature`),information about the type of features contained in that layer (e.g.points, polygons, etc.), as well as the names and types of anyadditional fields (:class:`Field`) of data that may be associated witheach feature in that layer... class:: DataSource(ds_input, encoding='utf-8')The constructor for ``DataSource`` only requires one parameter: the path ofthe file you want to read. However, OGR also supports a variety of morecomplex data sources, including databases, that may be accessed by passinga special name string instead of a path. For more information, see the`OGR Vector Formats`__ documentation. The :attr:`name` property of a``DataSource`` instance gives the OGR name of the underlying data sourcethat it is using.The optional ``encoding`` parameter allows you to specify a non-standardencoding of the strings in the source. This is typically useful when youobtain ``DjangoUnicodeDecodeError`` exceptions while reading field values.Once you've created your ``DataSource``, you can find out how many layersof data it contains by accessing the :attr:`layer_count` property, or(equivalently) by using the ``len()`` function. For information onaccessing the layers of data themselves, see the next section::>>> from django.contrib.gis.gdal import DataSource>>> ds = DataSource('/path/to/your/cities.shp')>>> ds.name'/path/to/your/cities.shp'>>> ds.layer_count # This file only contains one layer1.. attribute:: layer_countReturns the number of layers in the data source... attribute:: nameReturns the name of the data source.__ https://gdal.org/drivers/vector/``Layer``---------.. class:: Layer``Layer`` is a wrapper for a layer of data in a ``DataSource`` object. Younever create a ``Layer`` object directly. Instead, you retrieve them froma :class:`DataSource` object, which is essentially a standard Pythoncontainer of ``Layer`` objects. For example, you can access a specificlayer by its index (e.g. ``ds[0]`` to access the first layer), or you caniterate over all the layers in the container in a ``for`` loop. The``Layer`` itself acts as a container for geometric features.Typically, all the features in a given layer have the same geometry type.The :attr:`geom_type` property of a layer is an :class:`OGRGeomType` thatidentifies the feature type. We can use it to print out some basicinformation about each layer in a :class:`DataSource`::>>> for layer in ds:... print('Layer "%s": %i %ss' % (layer.name, len(layer), layer.geom_type.name))...Layer "cities": 3 PointsThe example output is from the cities data source, loaded above, whichevidently contains one layer, called ``"cities"``, which contains threepoint features. For simplicity, the examples below assume that you'vestored that layer in the variable ``layer``::>>> layer = ds[0].. attribute:: nameReturns the name of this layer in the data source.>>> layer.name'cities'.. attribute:: num_featReturns the number of features in the layer. Same as ``len(layer)``::>>> layer.num_feat3.. attribute:: geom_typeReturns the geometry type of the layer, as an :class:`OGRGeomType` object::>>> layer.geom_type.name'Point'.. attribute:: num_fieldsReturns the number of fields in the layer, i.e the number of fields ofdata associated with each feature in the layer::>>> layer.num_fields4.. attribute:: fieldsReturns a list of the names of each of the fields in this layer::>>> layer.fields['Name', 'Population', 'Density', 'Created'].. attribute field_typesReturns a list of the data types of each of the fields in this layer. Theseare subclasses of ``Field``, discussed below::>>> [ft.__name__ for ft in layer.field_types]['OFTString', 'OFTReal', 'OFTReal', 'OFTDate'].. attribute:: field_widthsReturns a list of the maximum field widths for each of the fields in thislayer::>>> layer.field_widths[80, 11, 24, 10].. attribute:: field_precisionsReturns a list of the numeric precisions for each of the fields in thislayer. This is meaningless (and set to zero) for non-numeric fields::>>> layer.field_precisions[0, 0, 15, 0].. attribute:: extentReturns the spatial extent of this layer, as an :class:`Envelope` object::>>> layer.extent.tuple(-104.609252, 29.763374, -95.23506, 38.971823).. attribute:: srsProperty that returns the :class:`SpatialReference` associated with thislayer::>>> print(layer.srs)GEOGCS["GCS_WGS_1984",DATUM["WGS_1984",SPHEROID["WGS_1984",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]]If the :class:`Layer` has no spatial reference information associatedwith it, ``None`` is returned... attribute:: spatial_filterProperty that may be used to retrieve or set a spatial filter for thislayer. A spatial filter can only be set with an :class:`OGRGeometry`instance, a 4-tuple extent, or ``None``. When set with something other than``None``, only features that intersect the filter will be returned wheniterating over the layer::>>> print(layer.spatial_filter)None>>> print(len(layer))3>>> [feat.get('Name') for feat in layer]['Pueblo', 'Lawrence', 'Houston']>>> ks_extent = (-102.051, 36.99, -94.59, 40.00) # Extent for state of Kansas>>> layer.spatial_filter = ks_extent>>> len(layer)1>>> [feat.get('Name') for feat in layer]['Lawrence']>>> layer.spatial_filter = None>>> len(layer)3.. method:: get_fields()A method that returns a list of the values of a given field for eachfeature in the layer::>>> layer.get_fields('Name')['Pueblo', 'Lawrence', 'Houston'].. method:: get_geoms(geos=False)A method that returns a list containing the geometry of each feature in thelayer. If the optional argument ``geos`` is set to ``True`` then thegeometries are converted to :class:`~django.contrib.gis.geos.GEOSGeometry`objects. Otherwise, they are returned as :class:`OGRGeometry` objects::>>> [pt.tuple for pt in layer.get_geoms()][(-104.609252, 38.255001), (-95.23506, 38.971823), (-95.363151, 29.763374)].. method:: test_capability(capability)Returns a boolean indicating whether this layer supports the givencapability (a string). Examples of valid capability strings include:``'RandomRead'``, ``'SequentialWrite'``, ``'RandomWrite'``,``'FastSpatialFilter'``, ``'FastFeatureCount'``, ``'FastGetExtent'``,``'CreateField'``, ``'Transactions'``, ``'DeleteFeature'``, and``'FastSetNextByIndex'``.``Feature``-----------.. class:: Feature``Feature`` wraps an OGR feature. You never create a ``Feature`` objectdirectly. Instead, you retrieve them from a :class:`Layer` object. Eachfeature consists of a geometry and a set of fields containing additionalproperties. The geometry of a field is accessible via its ``geom`` property,which returns an :class:`OGRGeometry` object. A ``Feature`` behaves like astandard Python container for its fields, which it returns as :class:`Field`objects: you can access a field directly by its index or name, or you caniterate over a feature's fields, e.g. in a ``for`` loop... attribute:: geomReturns the geometry for this feature, as an ``OGRGeometry`` object::>>> city.geom.tuple(-104.609252, 38.255001).. attribute:: getA method that returns the value of the given field (specified by name)for this feature, **not** a ``Field`` wrapper object::>>> city.get('Population')102121.. attribute:: geom_typeReturns the type of geometry for this feature, as an :class:`OGRGeomType`object. This will be the same for all features in a given layer and isequivalent to the :attr:`Layer.geom_type` property of the :class:`Layer`object the feature came from... attribute:: num_fieldsReturns the number of fields of data associated with the feature. This willbe the same for all features in a given layer and is equivalent to the:attr:`Layer.num_fields` property of the :class:`Layer` object the featurecame from... attribute:: fieldsReturns a list of the names of the fields of data associated with thefeature. This will be the same for all features in a given layer and isequivalent to the :attr:`Layer.fields` property of the :class:`Layer`object the feature came from... attribute:: fidReturns the feature identifier within the layer::>>> city.fid0.. attribute:: layer_nameReturns the name of the :class:`Layer` that the feature came from. Thiswill be the same for all features in a given layer::>>> city.layer_name'cities'.. attribute:: indexA method that returns the index of the given field name. This will be thesame for all features in a given layer::>>> city.index('Population')1``Field``---------.. class:: Field.. attribute:: nameReturns the name of this field::>>> city['Name'].name'Name'.. attribute:: typeReturns the OGR type of this field, as an integer. The ``FIELD_CLASSES``dictionary maps these values onto subclasses of ``Field``::>>> city['Density'].type2.. attribute:: type_nameReturns a string with the name of the data type of this field::>>> city['Name'].type_name'String'.. attribute:: valueReturns the value of this field. The ``Field`` class itself returns thevalue as a string, but each subclass returns the value in the mostappropriate form::>>> city['Population'].value102121.. attribute:: widthReturns the width of this field::>>> city['Name'].width80.. attribute:: precisionReturns the numeric precision of this field. This is meaningless (and setto zero) for non-numeric fields::>>> city['Density'].precision15.. method:: as_double()Returns the value of the field as a double (float)::>>> city['Density'].as_double()874.7.. method:: as_int()Returns the value of the field as an integer::>>> city['Population'].as_int()102121.. method:: as_string()Returns the value of the field as a string::>>> city['Name'].as_string()'Pueblo'.. method:: as_datetime()Returns the value of the field as a tuple of date and time components::>>> city['Created'].as_datetime()(c_long(1999), c_long(5), c_long(23), c_long(0), c_long(0), c_long(0), c_long(0))``Driver``----------.. class:: Driver(dr_input)The ``Driver`` class is used internally to wrap an OGR :class:`DataSource`driver... attribute:: driver_countReturns the number of OGR vector drivers currently registered.OGR Geometries==============``OGRGeometry``---------------:class:`OGRGeometry` objects share similar functionality with:class:`~django.contrib.gis.geos.GEOSGeometry` objects and are thin wrappersaround OGR's internal geometry representation. Thus, they allow for moreefficient access to data when using :class:`DataSource`. Unlike its GEOScounterpart, :class:`OGRGeometry` supports spatial reference systems andcoordinate transformation::>>> from django.contrib.gis.gdal import OGRGeometry>>> polygon = OGRGeometry('POLYGON((0 0, 5 0, 5 5, 0 5))').. class:: OGRGeometry(geom_input, srs=None)This object is a wrapper for the `OGR Geometry`__ class. These objects areinstantiated directly from the given ``geom_input`` parameter, which may bea string containing WKT, HEX, GeoJSON, a ``buffer`` containing WKB data, oran :class:`OGRGeomType` object. These objects are also returned from the:class:`Feature.geom` attribute, when reading vector data from:class:`Layer` (which is in turn a part of a :class:`DataSource`).__ https://gdal.org/api/ogrgeometry_cpp.html#ogrgeometry-class.. classmethod:: from_gml(gml_string)Constructs an :class:`OGRGeometry` from the given GML string... classmethod:: from_bbox(bbox)Constructs a :class:`Polygon` from the given bounding-box (a 4-tuple)... method:: __len__()Returns the number of points in a :class:`LineString`, the number of ringsin a :class:`Polygon`, or the number of geometries in a:class:`GeometryCollection`. Not applicable to other geometry types... method:: __iter__()Iterates over the points in a :class:`LineString`, the rings in a:class:`Polygon`, or the geometries in a :class:`GeometryCollection`.Not applicable to other geometry types... method:: __getitem__()Returns the point at the specified index for a :class:`LineString`, theinterior ring at the specified index for a :class:`Polygon`, or the geometryat the specified index in a :class:`GeometryCollection`. Not applicable toother geometry types... attribute:: dimensionReturns the number of coordinated dimensions of the geometry, i.e. 0for points, 1 for lines, and so forth::>> polygon.dimension2.. attribute:: coord_dimReturns or sets the coordinate dimension of this geometry. For example, thevalue would be 2 for two-dimensional geometries... attribute:: geom_countReturns the number of elements in this geometry::>>> polygon.geom_count1.. attribute:: point_countReturns the number of points used to describe this geometry::>>> polygon.point_count4.. attribute:: num_pointsAlias for :attr:`point_count`... attribute:: num_coordsAlias for :attr:`point_count`... attribute:: geom_typeReturns the type of this geometry, as an :class:`OGRGeomType` object... attribute:: geom_nameReturns the name of the type of this geometry::>>> polygon.geom_name'POLYGON'.. attribute:: areaReturns the area of this geometry, or 0 for geometries that do not containan area::>>> polygon.area25.0.. attribute:: envelopeReturns the envelope of this geometry, as an :class:`Envelope` object... attribute:: extentReturns the envelope of this geometry as a 4-tuple, instead of as an:class:`Envelope` object::>>> point.extent(0.0, 0.0, 5.0, 5.0).. attribute:: srsThis property controls the spatial reference for this geometry, or``None`` if no spatial reference system has been assigned to it.If assigned, accessing this property returns a :class:`SpatialReference`object. It may be set with another :class:`SpatialReference` object,or any input that :class:`SpatialReference` accepts. Example::>>> city.geom.srs.name'GCS_WGS_1984'.. attribute:: sridReturns or sets the spatial reference identifier corresponding to:class:`SpatialReference` of this geometry. Returns ``None`` ifthere is no spatial reference information associated with thisgeometry, or if an SRID cannot be determined... attribute:: geosReturns a :class:`~django.contrib.gis.geos.GEOSGeometry` objectcorresponding to this geometry... attribute:: gmlReturns a string representation of this geometry in GML format::>>> OGRGeometry('POINT(1 2)').gml'<gml:Point><gml:coordinates>1,2</gml:coordinates></gml:Point>'.. attribute:: hexReturns a string representation of this geometry in HEX WKB format::>>> OGRGeometry('POINT(1 2)').hex'0101000000000000000000F03F0000000000000040'.. attribute:: jsonReturns a string representation of this geometry in JSON format::>>> OGRGeometry('POINT(1 2)').json'{ "type": "Point", "coordinates": [ 1.000000, 2.000000 ] }'.. attribute:: kmlReturns a string representation of this geometry in KML format... attribute:: wkb_sizeReturns the size of the WKB buffer needed to hold a WKB representationof this geometry::>>> OGRGeometry('POINT(1 2)').wkb_size21.. attribute:: wkbReturns a ``buffer`` containing a WKB representation of this geometry... attribute:: wktReturns a string representation of this geometry in WKT format... attribute:: ewktReturns the EWKT representation of this geometry... method:: clone()Returns a new :class:`OGRGeometry` clone of this geometry object... method:: close_rings()If there are any rings within this geometry that have not been closed,this routine will do so by adding the starting point to the end::>>> triangle = OGRGeometry('LINEARRING (0 0,0 1,1 0)')>>> triangle.close_rings()>>> triangle.wkt'LINEARRING (0 0,0 1,1 0,0 0)'.. method:: transform(coord_trans, clone=False)Transforms this geometry to a different spatial reference system. May takea :class:`CoordTransform` object, a :class:`SpatialReference` object, orany other input accepted by :class:`SpatialReference` (including spatialreference WKT and PROJ strings, or an integer SRID).By default nothing is returned and the geometry is transformed in-place.However, if the ``clone`` keyword is set to ``True`` then a transformedclone of this geometry is returned instead... method:: intersects(other)Returns ``True`` if this geometry intersects the other, otherwise returns``False``... method:: equals(other)Returns ``True`` if this geometry is equivalent to the other, otherwisereturns ``False``... method:: disjoint(other)Returns ``True`` if this geometry is spatially disjoint to (i.e. doesnot intersect) the other, otherwise returns ``False``... method:: touches(other)Returns ``True`` if this geometry touches the other, otherwise returns``False``... method:: crosses(other)Returns ``True`` if this geometry crosses the other, otherwise returns``False``... method:: within(other)Returns ``True`` if this geometry is contained within the other, otherwisereturns ``False``... method:: contains(other)Returns ``True`` if this geometry contains the other, otherwise returns``False``... method:: overlaps(other)Returns ``True`` if this geometry overlaps the other, otherwise returns``False``... method:: boundary()The boundary of this geometry, as a new :class:`OGRGeometry` object... attribute:: convex_hullThe smallest convex polygon that contains this geometry, as a new:class:`OGRGeometry` object... method:: difference()Returns the region consisting of the difference of this geometry andthe other, as a new :class:`OGRGeometry` object... method:: intersection()Returns the region consisting of the intersection of this geometry andthe other, as a new :class:`OGRGeometry` object... method:: sym_difference()Returns the region consisting of the symmetric difference of thisgeometry and the other, as a new :class:`OGRGeometry` object... method:: union()Returns the region consisting of the union of this geometry andthe other, as a new :class:`OGRGeometry` object... attribute:: tupleReturns the coordinates of a point geometry as a tuple, thecoordinates of a line geometry as a tuple of tuples, and so forth::>>> OGRGeometry('POINT (1 2)').tuple(1.0, 2.0)>>> OGRGeometry('LINESTRING (1 2,3 4)').tuple((1.0, 2.0), (3.0, 4.0)).. attribute:: coordsAn alias for :attr:`tuple`... class:: Point.. attribute:: xReturns the X coordinate of this point::>>> OGRGeometry('POINT (1 2)').x1.0.. attribute:: yReturns the Y coordinate of this point::>>> OGRGeometry('POINT (1 2)').y2.0.. attribute:: zReturns the Z coordinate of this point, or ``None`` if the point does nothave a Z coordinate::>>> OGRGeometry('POINT (1 2 3)').z3.0.. class:: LineString.. attribute:: xReturns a list of X coordinates in this line::>>> OGRGeometry('LINESTRING (1 2,3 4)').x[1.0, 3.0].. attribute:: yReturns a list of Y coordinates in this line::>>> OGRGeometry('LINESTRING (1 2,3 4)').y[2.0, 4.0].. attribute:: zReturns a list of Z coordinates in this line, or ``None`` if the line doesnot have Z coordinates::>>> OGRGeometry('LINESTRING (1 2 3,4 5 6)').z[3.0, 6.0].. class:: Polygon.. attribute:: shellReturns the shell or exterior ring of this polygon, as a ``LinearRing``geometry... attribute:: exterior_ringAn alias for :attr:`shell`... attribute:: centroidReturns a :class:`Point` representing the centroid of this polygon... class:: GeometryCollection.. method:: add(geom)Adds a geometry to this geometry collection. Not applicable to othergeometry types.``OGRGeomType``---------------.. class:: OGRGeomType(type_input)This class allows for the representation of an OGR geometry typein any of several ways::>>> from django.contrib.gis.gdal import OGRGeomType>>> gt1 = OGRGeomType(3) # Using an integer for the type>>> gt2 = OGRGeomType('Polygon') # Using a string>>> gt3 = OGRGeomType('POLYGON') # It's case-insensitive>>> print(gt1 == 3, gt1 == 'Polygon') # Equivalence works w/non-OGRGeomType objectsTrue True.. attribute:: nameReturns a short-hand string form of the OGR Geometry type::>>> gt1.name'Polygon'.. attribute:: numReturns the number corresponding to the OGR geometry type::>>> gt1.num3.. attribute:: djangoReturns the Django field type (a subclass of GeometryField) to use forstoring this OGR type, or ``None`` if there is no appropriate Django type::>>> gt1.django'PolygonField'``Envelope``------------.. class:: Envelope(*args)Represents an OGR Envelope structure that contains the minimum and maximumX, Y coordinates for a rectangle bounding box. The naming of the variablesis compatible with the OGR Envelope C structure... attribute:: min_xThe value of the minimum X coordinate... attribute:: min_yThe value of the maximum X coordinate... attribute:: max_xThe value of the minimum Y coordinate... attribute:: max_yThe value of the maximum Y coordinate... attribute:: urThe upper-right coordinate, as a tuple... attribute:: llThe lower-left coordinate, as a tuple... attribute:: tupleA tuple representing the envelope... attribute:: wktA string representing this envelope as a polygon in WKT format... method:: expand_to_include(*args)Coordinate System Objects=========================``SpatialReference``--------------------.. class:: SpatialReference(srs_input)Spatial reference objects are initialized on the given ``srs_input``,which may be one of the following:* OGC Well Known Text (WKT) (a string)* EPSG code (integer or string)* PROJ string* A shorthand string for well-known standards (``'WGS84'``, ``'WGS72'``,``'NAD27'``, ``'NAD83'``)Example::>>> wgs84 = SpatialReference('WGS84') # shorthand string>>> wgs84 = SpatialReference(4326) # EPSG code>>> wgs84 = SpatialReference('EPSG:4326') # EPSG string>>> proj = '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs '>>> wgs84 = SpatialReference(proj) # PROJ string>>> wgs84 = SpatialReference("""GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]]""") # OGC WKT.. method:: __getitem__(target)Returns the value of the given string attribute node, ``None`` if the nodedoesn't exist. Can also take a tuple as a parameter, (target, child), wherechild is the index of the attribute in the WKT. For example::>>> wkt = 'GEOGCS["WGS 84", DATUM["WGS_1984, ... AUTHORITY["EPSG","4326"]]')>>> srs = SpatialReference(wkt) # could also use 'WGS84', or 4326>>> print(srs['GEOGCS'])WGS 84>>> print(srs['DATUM'])WGS_1984>>> print(srs['AUTHORITY'])EPSG>>> print(srs['AUTHORITY', 1]) # The authority value4326>>> print(srs['TOWGS84', 4]) # the fourth value in this wkt0>>> print(srs['UNIT|AUTHORITY']) # For the units authority, have to use the pipe symbol.EPSG>>> print(srs['UNIT|AUTHORITY', 1]) # The authority value for the units9122.. method:: attr_value(target, index=0)The attribute value for the given target node (e.g. ``'PROJCS'``).The index keyword specifies an index of the child node to return... method:: auth_name(target)Returns the authority name for the given string target node... method:: auth_code(target)Returns the authority code for the given string target node... method:: clone()Returns a clone of this spatial reference object... method:: identify_epsg()This method inspects the WKT of this ``SpatialReference`` and will add EPSGauthority nodes where an EPSG identifier is applicable... method:: from_esri()Morphs this SpatialReference from ESRI's format to EPSG.. method:: to_esri()Morphs this SpatialReference to ESRI's format... method:: validate()Checks to see if the given spatial reference is valid, if notan exception will be raised... method:: import_epsg(epsg)Import spatial reference from EPSG code... method:: import_proj(proj)Import spatial reference from PROJ string... method:: import_user_input(user_input).. method:: import_wkt(wkt)Import spatial reference from WKT... method:: import_xml(xml)Import spatial reference from XML... attribute:: nameReturns the name of this Spatial Reference... attribute:: sridReturns the SRID of top-level authority, or ``None`` if undefined... attribute:: linear_nameReturns the name of the linear units... attribute:: linear_unitsReturns the value of the linear units... attribute:: angular_nameReturns the name of the angular units.".. attribute:: angular_unitsReturns the value of the angular units... attribute:: unitsReturns a 2-tuple of the units value and the units name and willautomatically determines whether to return the linear or angular units... attribute:: ellipsoidReturns a tuple of the ellipsoid parameters for this spatial reference:(semimajor axis, semiminor axis, and inverse flattening)... attribute:: semi_majorReturns the semi major axis of the ellipsoid for this spatial reference... attribute:: semi_minorReturns the semi minor axis of the ellipsoid for this spatial reference... attribute:: inverse_flatteningReturns the inverse flattening of the ellipsoid for this spatial reference... attribute:: geographicReturns ``True`` if this spatial reference is geographic (root node is``GEOGCS``)... attribute:: localReturns ``True`` if this spatial reference is local (root node is``LOCAL_CS``)... attribute:: projectedReturns ``True`` if this spatial reference is a projected coordinate system(root node is ``PROJCS``)... attribute:: wktReturns the WKT representation of this spatial reference... attribute:: pretty_wktReturns the 'pretty' representation of the WKT... attribute:: projReturns the PROJ representation for this spatial reference... attribute:: proj4Alias for :attr:`SpatialReference.proj`... attribute:: xmlReturns the XML representation of this spatial reference.``CoordTransform``------------------.. class:: CoordTransform(source, target)Represents a coordinate system transform. It is initialized with two:class:`SpatialReference`, representing the source and target coordinatesystems, respectively. These objects should be used when performing the samecoordinate transformation repeatedly on different geometries::>>> ct = CoordTransform(SpatialReference('WGS84'), SpatialReference('NAD83'))>>> for feat in layer:... geom = feat.geom # getting clone of feature geometry... geom.transform(ct) # transforming.. _raster-data-source-objects:Raster Data Objects===================``GDALRaster``----------------:class:`GDALRaster` is a wrapper for the GDAL raster source object thatsupports reading data from a variety of GDAL-supported geospatial fileformats and data sources using a consistent interface. Eachdata source is represented by a :class:`GDALRaster` object which containsone or more layers of data named bands. Each band, represented by a:class:`GDALBand` object, contains georeferenced image data. For example, an RGBimage is represented as three bands: one for red, one for green, and one forblue... note::For raster data there is no difference between a raster instance and itsdata source. Unlike for the Geometry objects, :class:`GDALRaster` objects arealways a data source. Temporary rasters can be instantiated in memoryusing the corresponding driver, but they will be of the same class as file-basedraster sources... class:: GDALRaster(ds_input, write=False)The constructor for ``GDALRaster`` accepts two parameters. The firstparameter defines the raster source, and the second parameter defines if araster should be opened in write mode. For newly-created rasters, the secondparameter is ignored and the new raster is always created in write mode.The first parameter can take three forms: a string representing a file path(filesystem or GDAL virtual filesystem), a dictionary with values defininga new raster, or a bytes object representing a raster file.If the input is a file path, the raster is opened from there. If the inputis raw data in a dictionary, the parameters ``width``, ``height``, and``srid`` are required. If the input is a bytes object, it will be openedusing a GDAL virtual filesystem.For a detailed description of how to create rasters using dictionary input,see :ref:`gdal-raster-ds-input`. For a detailed description of how tocreate rasters in the virtual filesystem, see :ref:`gdal-raster-vsimem`.The following example shows how rasters can be created from different inputsources (using the sample data from the GeoDjango tests; see also the:ref:`gdal_sample_data` section).>>> from django.contrib.gis.gdal import GDALRaster>>> rst = GDALRaster('/path/to/your/raster.tif', write=False)>>> rst.name'/path/to/your/raster.tif'>>> rst.width, rst.height # This file has 163 x 174 pixels(163, 174)>>> rst = GDALRaster({ # Creates an in-memory raster... 'srid': 4326,... 'width': 4,... 'height': 4,... 'datatype': 1,... 'bands': [{... 'data': (2, 3),... 'offset': (1, 1),... 'size': (2, 2),... 'shape': (2, 1),... 'nodata_value': 5,... }]... })>>> rst.srs.srid4326>>> rst.width, rst.height(4, 4)>>> rst.bands[0].data()array([[5, 5, 5, 5],[5, 2, 3, 5],[5, 2, 3, 5],[5, 5, 5, 5]], dtype=uint8)>>> rst_file = open('/path/to/your/raster.tif', 'rb')>>> rst_bytes = rst_file.read()>>> rst = GDALRaster(rst_bytes)>>> rst.is_vsi_basedTrue>>> rst.name # Stored in a random path in the vsimem filesystem.'/vsimem/da300bdb-129d-49a8-b336-e410a9428dad'.. versionchanged:: 4.0Creating rasters in any GDAL virtual filesystem was allowed... attribute:: nameThe name of the source which is equivalent to the input file path or the nameprovided upon instantiation.>>> GDALRaster({'width': 10, 'height': 10, 'name': 'myraster', 'srid': 4326}).name'myraster'.. attribute:: driverThe name of the GDAL driver used to handle the input file. For ``GDALRaster``\s createdfrom a file, the driver type is detected automatically. The creation of rasters fromscratch is an in-memory raster by default (``'MEM'``), but can bealtered as needed. For instance, use ``GTiff`` for a ``GeoTiff`` file.For a list of file types, see also the `GDAL Raster Formats`__ list.__ https://gdal.org/drivers/raster/An in-memory raster is created through the following example:>>> GDALRaster({'width': 10, 'height': 10, 'srid': 4326}).driver.name'MEM'A file based GeoTiff raster is created through the following example:>>> import tempfile>>> rstfile = tempfile.NamedTemporaryFile(suffix='.tif')>>> rst = GDALRaster({'driver': 'GTiff', 'name': rstfile.name, 'srid': 4326,... 'width': 255, 'height': 255, 'nr_of_bands': 1})>>> rst.name'/tmp/tmp7x9H4J.tif' # The exact filename will be different on your computer>>> rst.driver.name'GTiff'.. attribute:: widthThe width of the source in pixels (X-axis).>>> GDALRaster({'width': 10, 'height': 20, 'srid': 4326}).width10.. attribute:: heightThe height of the source in pixels (Y-axis).>>> GDALRaster({'width': 10, 'height': 20, 'srid': 4326}).height20.. attribute:: srsThe spatial reference system of the raster, as a:class:`SpatialReference` instance. The SRS can be changed bysetting it to an other :class:`SpatialReference` or providing any inputthat is accepted by the :class:`SpatialReference` constructor.>>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})>>> rst.srs.srid4326>>> rst.srs = 3086>>> rst.srs.srid3086.. attribute:: sridThe Spatial Reference System Identifier (SRID) of the raster. Thisproperty is a shortcut to getting or setting the SRID through the:attr:`srs` attribute.>>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})>>> rst.srid4326>>> rst.srid = 3086>>> rst.srid3086>>> rst.srs.srid # This is equivalent3086.. attribute:: geotransformThe affine transformation matrix used to georeference the source, as atuple of six coefficients which map pixel/line coordinates intogeoreferenced space using the following relationship::Xgeo = GT(0) + Xpixel*GT(1) + Yline*GT(2)Ygeo = GT(3) + Xpixel*GT(4) + Yline*GT(5)The same values can be retrieved by accessing the :attr:`origin`(indices 0 and 3), :attr:`scale` (indices 1 and 5) and :attr:`skew`(indices 2 and 4) properties.The default is ``[0.0, 1.0, 0.0, 0.0, 0.0, -1.0]``.>>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})>>> rst.geotransform[0.0, 1.0, 0.0, 0.0, 0.0, -1.0].. attribute:: originCoordinates of the top left origin of the raster in the spatialreference system of the source, as a point object with ``x`` and ``y``members.>>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})>>> rst.origin[0.0, 0.0]>>> rst.origin.x = 1>>> rst.origin[1.0, 0.0].. attribute:: scalePixel width and height used for georeferencing the raster, as a pointobject with ``x`` and ``y`` members. See :attr:`geotransform` for moreinformation.>>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})>>> rst.scale[1.0, -1.0]>>> rst.scale.x = 2>>> rst.scale[2.0, -1.0].. attribute:: skewSkew coefficients used to georeference the raster, as a point objectwith ``x`` and ``y`` members. In case of north up images, thesecoefficients are both ``0``.>>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})>>> rst.skew[0.0, 0.0]>>> rst.skew.x = 3>>> rst.skew[3.0, 0.0].. attribute:: extentExtent (boundary values) of the raster source, as a 4-tuple``(xmin, ymin, xmax, ymax)`` in the spatial reference system of thesource.>>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})>>> rst.extent(0.0, -20.0, 10.0, 0.0)>>> rst.origin.x = 100>>> rst.extent(100.0, -20.0, 110.0, 0.0).. attribute:: bandsList of all bands of the source, as :class:`GDALBand` instances.>>> rst = GDALRaster({"width": 1, "height": 2, 'srid': 4326,... "bands": [{"data": [0, 1]}, {"data": [2, 3]}]})>>> len(rst.bands)2>>> rst.bands[1].data()array([[ 2., 3.]], dtype=float32).. method:: warp(ds_input, resampling='NearestNeighbour', max_error=0.0)Returns a warped version of this raster.The warping parameters can be specified through the ``ds_input``argument. The use of ``ds_input`` is analogous to the correspondingargument of the class constructor. It is a dictionary with thecharacteristics of the target raster. Allowed dictionary key values arewidth, height, SRID, origin, scale, skew, datatype, driver, and name(filename).By default, the warp functions keeps most parameters equal to thevalues of the original source raster, so only parameters that should bechanged need to be specified. Note that this includes the driver, sofor file-based rasters the warp function will create a new raster ondisk.The only parameter that is set differently from the source raster is thename. The default value of the raster name is the name of the sourceraster appended with ``'_copy' + source_driver_name``. For file-basedrasters it is recommended to provide the file path of the target raster.The resampling algorithm used for warping can be specified with the``resampling`` argument. The default is ``NearestNeighbor``, and theother allowed values are ``Bilinear``, ``Cubic``, ``CubicSpline``,``Lanczos``, ``Average``, and ``Mode``.The ``max_error`` argument can be used to specify the maximum errormeasured in input pixels that is allowed in approximating thetransformation. The default is 0.0 for exact calculations.For users familiar with ``GDAL``, this function has a similarfunctionality to the ``gdalwarp`` command-line utility.For example, the warp function can be used for aggregating a raster tothe double of its original pixel scale:>>> rst = GDALRaster({... "width": 6, "height": 6, "srid": 3086,... "origin": [500000, 400000],... "scale": [100, -100],... "bands": [{"data": range(36), "nodata_value": 99}]... })>>> target = rst.warp({"scale": [200, -200], "width": 3, "height": 3})>>> target.bands[0].data()array([[ 7., 9., 11.],[ 19., 21., 23.],[ 31., 33., 35.]], dtype=float32).. method:: transform(srs, driver=None, name=None, resampling='NearestNeighbour', max_error=0.0)Transforms this raster to a different spatial reference system(``srs``), which may be a :class:`SpatialReference` object, or anyother input accepted by :class:`SpatialReference` (including spatialreference WKT and PROJ strings, or an integer SRID).It calculates the bounds and scale of the current raster in the newspatial reference system and warps the raster using the:attr:`~GDALRaster.warp` function.By default, the driver of the source raster is used and the name of theraster is the original name appended with``'_copy' + source_driver_name``. A different driver or name can bespecified with the ``driver`` and ``name`` arguments.The default resampling algorithm is ``NearestNeighbour`` but can bechanged using the ``resampling`` argument. The default maximum allowederror for resampling is 0.0 and can be changed using the ``max_error``argument. Consult the :attr:`~GDALRaster.warp` documentation for detailon those arguments.>>> rst = GDALRaster({... "width": 6, "height": 6, "srid": 3086,... "origin": [500000, 400000],... "scale": [100, -100],... "bands": [{"data": range(36), "nodata_value": 99}]... })>>> target_srs = SpatialReference(4326)>>> target = rst.transform(target_srs)>>> target.origin[-82.98492744885776, 27.601924753080144].. attribute:: infoReturns a string with a summary of the raster. This is equivalent tothe `gdalinfo`__ command line utility.__ https://gdal.org/programs/gdalinfo.html.. attribute:: metadataThe metadata of this raster, represented as a nested dictionary. Thefirst-level key is the metadata domain. The second-level contains themetadata item names and values from each domain.To set or update a metadata item, pass the corresponding metadata itemto the method using the nested structure described above. Only keysthat are in the specified dictionary are updated; the rest of themetadata remains unchanged.To remove a metadata item, use ``None`` as the metadata value.>>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})>>> rst.metadata{}>>> rst.metadata = {'DEFAULT': {'OWNER': 'Django', 'VERSION': '1.0'}}>>> rst.metadata{'DEFAULT': {'OWNER': 'Django', 'VERSION': '1.0'}}>>> rst.metadata = {'DEFAULT': {'OWNER': None, 'VERSION': '2.0'}}>>> rst.metadata{'DEFAULT': {'VERSION': '2.0'}}.. attribute:: vsi_bufferA ``bytes`` representation of this raster. Returns ``None`` for rastersthat are not stored in GDAL's virtual filesystem... attribute:: is_vsi_basedA boolean indicating if this raster is stored in GDAL's virtualfilesystem.``GDALBand``------------.. class:: GDALBand``GDALBand`` instances are not created explicitly, but rather obtainedfrom a :class:`GDALRaster` object, through its :attr:`~GDALRaster.bands`attribute. The GDALBands contain the actual pixel values of the raster... attribute:: descriptionThe name or description of the band, if any... attribute:: widthThe width of the band in pixels (X-axis)... attribute:: heightThe height of the band in pixels (Y-axis)... attribute:: pixel_countThe total number of pixels in this band. Is equal to ``width * height``... method:: statistics(refresh=False, approximate=False)Compute statistics on the pixel values of this band. The return valueis a tuple with the following structure:``(minimum, maximum, mean, standard deviation)``.If the ``approximate`` argument is set to ``True``, the statistics maybe computed based on overviews or a subset of image tiles.If the ``refresh`` argument is set to ``True``, the statistics will becomputed from the data directly, and the cache will be updated with theresult.If a persistent cache value is found, that value is returned. Forraster formats using Persistent Auxiliary Metadata (PAM) services, thestatistics might be cached in an auxiliary file. In some cases thismetadata might be out of sync with the pixel values or cause valuesfrom a previous call to be returned which don't reflect the value ofthe ``approximate`` argument. In such cases, use the ``refresh``argument to get updated values and store them in the cache.For empty bands (where all pixel values are "no data"), all statisticsare returned as ``None``.The statistics can also be retrieved directly by accessing the:attr:`min`, :attr:`max`, :attr:`mean`, and :attr:`std` properties... attribute:: minThe minimum pixel value of the band (excluding the "no data" value)... attribute:: maxThe maximum pixel value of the band (excluding the "no data" value)... attribute:: meanThe mean of all pixel values of the band (excluding the "no data"value)... attribute:: stdThe standard deviation of all pixel values of the band (excluding the"no data" value)... attribute:: nodata_valueThe "no data" value for a band is generally a special marker value usedto mark pixels that are not valid data. Such pixels should generally notbe displayed, nor contribute to analysis operations.To delete an existing "no data" value, set this property to ``None``... method:: datatype(as_string=False)The data type contained in the band, as an integer constant between 0(Unknown) and 11. If ``as_string`` is ``True``, the data type isreturned as a string with the following possible values:``GDT_Unknown``, ``GDT_Byte``, ``GDT_UInt16``, ``GDT_Int16``,``GDT_UInt32``, ``GDT_Int32``, ``GDT_Float32``, ``GDT_Float64``,``GDT_CInt16``, ``GDT_CInt32``, ``GDT_CFloat32``, and ``GDT_CFloat64``... method:: color_interp(as_string=False)The color interpretation for the band, as an integer between 0and 16.If ``as_string`` is ``True``, the data type is returned as a stringwith the following possible values:``GCI_Undefined``, ``GCI_GrayIndex``, ``GCI_PaletteIndex``,``GCI_RedBand``, ``GCI_GreenBand``, ``GCI_BlueBand``, ``GCI_AlphaBand``,``GCI_HueBand``, ``GCI_SaturationBand``, ``GCI_LightnessBand``,``GCI_CyanBand``, ``GCI_MagentaBand``, ``GCI_YellowBand``,``GCI_BlackBand``, ``GCI_YCbCr_YBand``, ``GCI_YCbCr_CbBand``, and``GCI_YCbCr_CrBand``. ``GCI_YCbCr_CrBand`` also represents ``GCI_Max``because both correspond to the integer 16, but only ``GCI_YCbCr_CrBand``is returned as a string... method:: data(data=None, offset=None, size=None, shape=None)The accessor to the pixel values of the ``GDALBand``. Returns the completedata array if no parameters are provided. A subset of the pixel array canbe requested by specifying an offset and block size as tuples.If NumPy is available, the data is returned as NumPy array. For performancereasons, it is highly recommended to use NumPy.Data is written to the ``GDALBand`` if the ``data`` parameter is provided.The input can be of one of the following types - packed string, buffer, list,array, and NumPy array. The number of items in the input should normallycorrespond to the total number of pixels in the band, or to the numberof pixels for a specific block of pixel values if the ``offset`` and``size`` parameters are provided.If the number of items in the input is different from the target pixelblock, the ``shape`` parameter must be specified. The shape is a tuplethat specifies the width and height of the input data in pixels. Thedata is then replicated to update the pixel values of the selectedblock. This is useful to fill an entire band with a single value, forinstance.For example:>>> rst = GDALRaster({'width': 4, 'height': 4, 'srid': 4326, 'datatype': 1, 'nr_of_bands': 1})>>> bnd = rst.bands[0]>>> bnd.data(range(16))>>> bnd.data()array([[ 0, 1, 2, 3],[ 4, 5, 6, 7],[ 8, 9, 10, 11],[12, 13, 14, 15]], dtype=int8)>>> bnd.data(offset=(1, 1), size=(2, 2))array([[ 5, 6],[ 9, 10]], dtype=int8)>>> bnd.data(data=[-1, -2, -3, -4], offset=(1, 1), size=(2, 2))>>> bnd.data()array([[ 0, 1, 2, 3],[ 4, -1, -2, 7],[ 8, -3, -4, 11],[12, 13, 14, 15]], dtype=int8)>>> bnd.data(data='\x9d\xa8\xb3\xbe', offset=(1, 1), size=(2, 2))>>> bnd.data()array([[ 0, 1, 2, 3],[ 4, -99, -88, 7],[ 8, -77, -66, 11],[ 12, 13, 14, 15]], dtype=int8)>>> bnd.data([1], shape=(1, 1))>>> bnd.data()array([[1, 1, 1, 1],[1, 1, 1, 1],[1, 1, 1, 1],[1, 1, 1, 1]], dtype=uint8)>>> bnd.data(range(4), shape=(1, 4))array([[0, 0, 0, 0],[1, 1, 1, 1],[2, 2, 2, 2],[3, 3, 3, 3]], dtype=uint8).. attribute:: metadataThe metadata of this band. The functionality is identical to:attr:`GDALRaster.metadata`... _gdal-raster-ds-input:Creating rasters from data--------------------------This section describes how to create rasters from scratch using the``ds_input`` parameter.A new raster is created when a ``dict`` is passed to the :class:`GDALRaster`constructor. The dictionary contains defining parameters of the new raster,such as the origin, size, or spatial reference system. The dictionary can alsocontain pixel data and information about the format of the new raster. Theresulting raster can therefore be file-based or memory-based, depending on thedriver specified.There's no standard for describing raster data in a dictionary or JSON flavor.The definition of the dictionary input to the :class:`GDALRaster` class istherefore specific to Django. It's inspired by the `geojson`__ format, but the``geojson`` standard is currently limited to vector formats.Examples of using the different keys when creating rasters can be found in thedocumentation of the corresponding attributes and methods of the:class:`GDALRaster` and :class:`GDALBand` classes.__ https://geojson.org/The ``ds_input`` dictionary~~~~~~~~~~~~~~~~~~~~~~~~~~~Only a few keys are required in the ``ds_input`` dictionary to create a raster:``width``, ``height``, and ``srid``. All other parameters have default values(see the table below). The list of keys that can be passed in the ``ds_input``dictionary is closely related but not identical to the :class:`GDALRaster`properties. Many of the parameters are mapped directly to those properties;the others are described below.The following table describes all keys that can be set in the ``ds_input``dictionary.================= ======== ==================================================Key Default Usage================= ======== ==================================================``srid`` required Mapped to the :attr:`~GDALRaster.srid` attribute``width`` required Mapped to the :attr:`~GDALRaster.width` attribute``height`` required Mapped to the :attr:`~GDALRaster.height` attribute``driver`` ``MEM`` Mapped to the :attr:`~GDALRaster.driver` attribute``name`` ``''`` See below``origin`` ``0`` Mapped to the :attr:`~GDALRaster.origin` attribute``scale`` ``0`` Mapped to the :attr:`~GDALRaster.scale` attribute``skew`` ``0`` Mapped to the :attr:`~GDALRaster.width` attribute``bands`` ``[]`` See below``nr_of_bands`` ``0`` See below``datatype`` ``6`` See below``papsz_options`` ``{}`` See below================= ======== ==================================================.. object:: nameString representing the name of the raster. When creating a file-basedraster, this parameter must be the file path for the new raster. If thename starts with ``/vsimem/``, the raster is created in GDAL's virtualfilesystem... object:: datatypeInteger representing the data type for all the bands. Defaults to ``6``(Float32). All bands of a new raster are required to have the same datatype.The value mapping is:===== =============== ===============================Value GDAL Pixel Type Description===== =============== ===============================1 GDT_Byte Eight bit unsigned integer2 GDT_UInt16 Sixteen bit unsigned integer3 GDT_Int16 Sixteen bit signed integer4 GDT_UInt32 Thirty-two bit unsigned integer5 GDT_Int32 Thirty-two bit signed integer6 GDT_Float32 Thirty-two bit floating point7 GDT_Float64 Sixty-four bit floating point===== =============== ===============================.. object:: nr_of_bandsInteger representing the number of bands of the raster. A raster can becreated without passing band data upon creation. If the number of bandsisn't specified, it's automatically calculated from the length of the``bands`` input. The number of bands can't be changed after creation... object:: bandsA list of ``band_input`` dictionaries with band input data. The resultingband indices are the same as in the list provided. The definition of theband input dictionary is given below. If band data isn't provided, theraster bands values are instantiated as an array of zeros and the "nodata" value is set to ``None``... object:: papsz_optionsA dictionary with raster creation options. The key-value pairs of theinput dictionary are passed to the driver on creation of the raster.The available options are driver-specific and are described in thedocumentation of each driver.The values in the dictionary are not case-sensitive and are automaticallyconverted to the correct string format upon creation.The following example uses some of the options available for the`GTiff driver`__. The result is a compressed signed byte raster with aninternal tiling scheme. The internal tiles have a block size of 23 by 23::>>> GDALRaster({... 'driver': 'GTiff',... 'name': '/path/to/new/file.tif',... 'srid': 4326,... 'width': 255,... 'height': 255,... 'nr_of_bands': 1,... 'papsz_options': {... 'compress': 'packbits',... 'pixeltype': 'signedbyte',... 'tiled': 'yes',... 'blockxsize': 23,... 'blockysize': 23,... }... })__ https://gdal.org/drivers/raster/gtiff.htmlThe ``band_input`` dictionary~~~~~~~~~~~~~~~~~~~~~~~~~~~~~The ``bands`` key in the ``ds_input`` dictionary is a list of ``band_input``dictionaries. Each ``band_input`` dictionary can contain pixel values and the"no data" value to be set on the bands of the new raster. The data array canhave the full size of the new raster or be smaller. For arrays that are smallerthan the full raster, the ``size``, ``shape``, and ``offset`` keys control thepixel values. The corresponding keys are passed to the :meth:`~GDALBand.data`method. Their functionality is the same as setting the band data with thatmethod. The following table describes the keys that can be used.================ ================================= ======================================================Key Default Usage================ ================================= ======================================================``nodata_value`` ``None`` Mapped to the :attr:`~GDALBand.nodata_value` attribute``data`` Same as ``nodata_value`` or ``0`` Passed to the :meth:`~GDALBand.data` method``size`` ``(with, height)`` of raster Passed to the :meth:`~GDALBand.data` method``shape`` Same as size Passed to the :meth:`~GDALBand.data` method``offset`` ``(0, 0)`` Passed to the :meth:`~GDALBand.data` method================ ================================= ======================================================.. _gdal-raster-vsimem:Using GDAL's Virtual Filesystem-------------------------------GDAL can access files stored in the filesystem, but also supports virtualfilesystems to abstract accessing other kind of files, such as compressed,encrypted, or remote files.Using memory-based Virtual Filesystem~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~GDAL has an internal memory-based filesystem, which allows treating blocks ofmemory as files. It can be used to read and write :class:`GDALRaster` objectsto and from binary file buffers.This is useful in web contexts where rasters might be obtained as a bufferfrom a remote storage or returned from a view without being written to disk.:class:`GDALRaster` objects are created in the virtual filesystem when a``bytes`` object is provided as input, or when the file path starts with``/vsimem/``.Input provided as ``bytes`` has to be a full binary representation of a file.For instance::# Read a raster as a file object from a remote source.>>> from urllib.request import urlopen>>> dat = urlopen('http://example.com/raster.tif').read()# Instantiate a raster from the bytes object.>>> rst = GDALRaster(dat)# The name starts with /vsimem/, indicating that the raster lives in the# virtual filesystem.>>> rst.name'/vsimem/da300bdb-129d-49a8-b336-e410a9428dad'To create a new virtual file-based raster from scratch, use the ``ds_input``dictionary representation and provide a ``name`` argument that starts with``/vsimem/`` (for detail of the dictionary representation, see:ref:`gdal-raster-ds-input`). For virtual file-based rasters, the:attr:`~GDALRaster.vsi_buffer` attribute returns the ``bytes`` representationof the raster.Here's how to create a raster and return it as a file in an:class:`~django.http.HttpResponse`::>>> from django.http import HttpResponse>>> rst = GDALRaster({... 'name': '/vsimem/temporarymemfile',... 'driver': 'tif',... 'width': 6, 'height': 6, 'srid': 3086,... 'origin': [500000, 400000],... 'scale': [100, -100],... 'bands': [{'data': range(36), 'nodata_value': 99}]... })>>> HttpResponse(rast.vsi_buffer, 'image/tiff')Using other Virtual Filesystems~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~.. versionadded:: 4.0Depending on the local build of GDAL other virtual filesystems may besupported. You can use them by prepending the provided path with theappropriate ``/vsi*/`` prefix. See the `GDAL Virtual Filesystemsdocumentation`_ for more details... warning:Rasters with names starting with `/vsi*/` will be treated as rasters fromthe GDAL virtual filesystems. Django doesn't perform any extra validation.Compressed rasters^^^^^^^^^^^^^^^^^^Instead decompressing the file and instantiating the resulting raster, GDAL candirectly access compressed files using the ``/vsizip/``, ``/vsigzip/``, or``/vsitar/`` virtual filesystems::>>> from django.contrib.gis.gdal import GDALRaster>>> rst = GDALRaster('/vsizip/path/to/your/file.zip/path/to/raster.tif')>>> rst = GDALRaster('/vsigzip/path/to/your/file.gz')>>> rst = GDALRaster('/vsitar/path/to/your/file.tar/path/to/raster.tif')Network rasters^^^^^^^^^^^^^^^GDAL can support online resources and storage providers transparently. As longas it's built with such capabilities.To access a public raster file with no authentication, you can use``/vsicurl/``::>>> from django.contrib.gis.gdal import GDALRaster>>> rst = GDALRaster('/vsicurl/https://example.com/raster.tif')>>> rst.name'/vsicurl/https://example.com/raster.tif'For commercial storage providers (e.g. ``/vsis3/``) the system should bepreviously configured for authentication and possibly other settings (see the`GDAL Virtual Filesystems documentation`_ for available options)... _`GDAL Virtual Filesystems documentation`: https://gdal.org/user/virtual_file_systems.htmlSettings========.. setting:: GDAL_LIBRARY_PATH``GDAL_LIBRARY_PATH``---------------------A string specifying the location of the GDAL library. Typically,this setting is only used if the GDAL library is in a non-standardlocation (e.g., ``/home/john/lib/libgdal.so``).Exceptions==========.. exception:: GDALExceptionThe base GDAL exception, indicating a GDAL-related error... exception:: SRSExceptionAn exception raised when an error occurs when constructing or using aspatial reference system object.