1. ========
    
  2. GDAL API
    
  3. ========
    
  4. 
    
  5. .. module:: django.contrib.gis.gdal
    
  6.     :synopsis: GeoDjango's high-level interface to the GDAL library.
    
  7. 
    
  8. `GDAL`__ stands for **Geospatial Data Abstraction Library**,
    
  9. and is a veritable "Swiss army knife" of GIS data functionality.  A subset
    
  10. of GDAL is the `OGR`__ Simple Features Library, which specializes
    
  11. in reading and writing vector geographic data in a variety of standard
    
  12. formats.
    
  13. 
    
  14. GeoDjango provides a high-level Python interface for some of the
    
  15. capabilities of OGR, including the reading and coordinate transformation
    
  16. of vector spatial data and minimal support for GDAL's features with respect
    
  17. to raster (image) data.
    
  18. 
    
  19. .. note::
    
  20. 
    
  21.     Although the module is named ``gdal``, GeoDjango only supports some of the
    
  22.     capabilities of OGR and GDAL's raster features at this time.
    
  23. 
    
  24. __ https://gdal.org/
    
  25. __ https://gdal.org/user/vector_data_model.html
    
  26. 
    
  27. Overview
    
  28. ========
    
  29. 
    
  30. .. _gdal_sample_data:
    
  31. 
    
  32. Sample Data
    
  33. -----------
    
  34. 
    
  35. The GDAL/OGR tools described here are designed to help you read in
    
  36. your geospatial data, in order for most of them to be useful you have
    
  37. to have some data to work with.  If you're starting out and don't yet
    
  38. have any data of your own to use, GeoDjango tests contain a number of
    
  39. data sets that you can use for testing. You can download them here::
    
  40. 
    
  41.     $ wget https://raw.githubusercontent.com/django/django/main/tests/gis_tests/data/cities/cities.{shp,prj,shx,dbf}
    
  42.     $ wget https://raw.githubusercontent.com/django/django/main/tests/gis_tests/data/rasters/raster.tif
    
  43. 
    
  44. Vector Data Source Objects
    
  45. ==========================
    
  46. 
    
  47. ``DataSource``
    
  48. --------------
    
  49. 
    
  50. :class:`DataSource` is a wrapper for the OGR data source object that
    
  51. supports reading data from a variety of OGR-supported geospatial file
    
  52. formats and data sources using a consistent interface.  Each
    
  53. data source is represented by a :class:`DataSource` object which contains
    
  54. one or more layers of data.  Each layer, represented by a :class:`Layer`
    
  55. object, contains some number of geographic features (:class:`Feature`),
    
  56. information about the type of features contained in that layer (e.g.
    
  57. points, polygons, etc.), as well as the names and types of any
    
  58. additional fields (:class:`Field`) of data that may be associated with
    
  59. each feature in that layer.
    
  60. 
    
  61. .. class:: DataSource(ds_input, encoding='utf-8')
    
  62. 
    
  63.     The constructor for ``DataSource`` only requires one parameter: the path of
    
  64.     the file you want to read. However, OGR also supports a variety of more
    
  65.     complex data sources, including databases, that may be accessed by passing
    
  66.     a special name string instead of a path. For more information, see the
    
  67.     `OGR Vector Formats`__ documentation. The :attr:`name` property of a
    
  68.     ``DataSource`` instance gives the OGR name of the underlying data source
    
  69.     that it is using.
    
  70. 
    
  71.     The optional ``encoding`` parameter allows you to specify a non-standard
    
  72.     encoding of the strings in the source. This is typically useful when you
    
  73.     obtain ``DjangoUnicodeDecodeError`` exceptions while reading field values.
    
  74. 
    
  75.     Once you've created your ``DataSource``, you can find out how many layers
    
  76.     of data it contains by accessing the :attr:`layer_count` property, or
    
  77.     (equivalently) by using the ``len()`` function. For information on
    
  78.     accessing the layers of data themselves, see the next section::
    
  79. 
    
  80.         >>> from django.contrib.gis.gdal import DataSource
    
  81.         >>> ds = DataSource('/path/to/your/cities.shp')
    
  82.         >>> ds.name
    
  83.         '/path/to/your/cities.shp'
    
  84.         >>> ds.layer_count                  # This file only contains one layer
    
  85.         1
    
  86. 
    
  87.     .. attribute:: layer_count
    
  88. 
    
  89.     Returns the number of layers in the data source.
    
  90. 
    
  91.     .. attribute:: name
    
  92. 
    
  93.     Returns the name of the data source.
    
  94. 
    
  95. __ https://gdal.org/drivers/vector/
    
  96. 
    
  97. ``Layer``
    
  98. ---------
    
  99. 
    
  100. .. class:: Layer
    
  101. 
    
  102.     ``Layer`` is a wrapper for a layer of data in a ``DataSource`` object. You
    
  103.     never create a ``Layer`` object directly. Instead, you retrieve them from
    
  104.     a :class:`DataSource` object, which is essentially a standard Python
    
  105.     container of ``Layer`` objects. For example, you can access a specific
    
  106.     layer by its index (e.g. ``ds[0]`` to access the first layer), or you can
    
  107.     iterate over all the layers in the container in a ``for`` loop. The
    
  108.     ``Layer`` itself acts as a container for geometric features.
    
  109. 
    
  110.     Typically, all the features in a given layer have the same geometry type.
    
  111.     The :attr:`geom_type` property of a layer is an :class:`OGRGeomType` that
    
  112.     identifies the feature type. We can use it to print out some basic
    
  113.     information about each layer in a :class:`DataSource`::
    
  114. 
    
  115.         >>> for layer in ds:
    
  116.         ...     print('Layer "%s": %i %ss' % (layer.name, len(layer), layer.geom_type.name))
    
  117.         ...
    
  118.         Layer "cities": 3 Points
    
  119. 
    
  120.     The example output is from the cities data source, loaded above, which
    
  121.     evidently contains one layer, called ``"cities"``, which contains three
    
  122.     point features. For simplicity, the examples below assume that you've
    
  123.     stored that layer in the variable ``layer``::
    
  124. 
    
  125.         >>> layer = ds[0]
    
  126. 
    
  127.     .. attribute:: name
    
  128. 
    
  129.     Returns the name of this layer in the data source.
    
  130. 
    
  131.         >>> layer.name
    
  132.         'cities'
    
  133. 
    
  134.     .. attribute:: num_feat
    
  135. 
    
  136.     Returns the number of features in the layer. Same as ``len(layer)``::
    
  137. 
    
  138.         >>> layer.num_feat
    
  139.         3
    
  140. 
    
  141.     .. attribute:: geom_type
    
  142. 
    
  143.     Returns the geometry type of the layer, as an :class:`OGRGeomType` object::
    
  144. 
    
  145.         >>> layer.geom_type.name
    
  146.         'Point'
    
  147. 
    
  148.     .. attribute:: num_fields
    
  149. 
    
  150.     Returns the number of fields in the layer, i.e the number of fields of
    
  151.     data associated with each feature in the layer::
    
  152. 
    
  153.         >>> layer.num_fields
    
  154.         4
    
  155. 
    
  156.     .. attribute:: fields
    
  157. 
    
  158.     Returns a list of the names of each of the fields in this layer::
    
  159. 
    
  160.         >>> layer.fields
    
  161.         ['Name', 'Population', 'Density', 'Created']
    
  162. 
    
  163.     .. attribute field_types
    
  164. 
    
  165.     Returns a list of the data types of each of the fields in this layer. These
    
  166.     are subclasses of ``Field``, discussed below::
    
  167. 
    
  168.         >>> [ft.__name__ for ft in layer.field_types]
    
  169.         ['OFTString', 'OFTReal', 'OFTReal', 'OFTDate']
    
  170. 
    
  171.     .. attribute:: field_widths
    
  172. 
    
  173.     Returns a list of the maximum field widths for each of the fields in this
    
  174.     layer::
    
  175. 
    
  176.         >>> layer.field_widths
    
  177.         [80, 11, 24, 10]
    
  178. 
    
  179.     .. attribute:: field_precisions
    
  180. 
    
  181.     Returns a list of the numeric precisions for each of the fields in this
    
  182.     layer. This is meaningless (and set to zero) for non-numeric fields::
    
  183. 
    
  184.         >>> layer.field_precisions
    
  185.         [0, 0, 15, 0]
    
  186. 
    
  187.     .. attribute:: extent
    
  188. 
    
  189.     Returns the spatial extent of this layer, as an :class:`Envelope` object::
    
  190. 
    
  191.         >>> layer.extent.tuple
    
  192.         (-104.609252, 29.763374, -95.23506, 38.971823)
    
  193. 
    
  194.     .. attribute:: srs
    
  195. 
    
  196.     Property that returns the :class:`SpatialReference` associated with this
    
  197.     layer::
    
  198. 
    
  199.         >>> print(layer.srs)
    
  200.         GEOGCS["GCS_WGS_1984",
    
  201.             DATUM["WGS_1984",
    
  202.                 SPHEROID["WGS_1984",6378137,298.257223563]],
    
  203.             PRIMEM["Greenwich",0],
    
  204.             UNIT["Degree",0.017453292519943295]]
    
  205. 
    
  206.     If the :class:`Layer` has no spatial reference information associated
    
  207.     with it, ``None`` is returned.
    
  208. 
    
  209.     .. attribute:: spatial_filter
    
  210. 
    
  211.     Property that may be used to retrieve or set a spatial filter for this
    
  212.     layer. A spatial filter can only be set with an :class:`OGRGeometry`
    
  213.     instance, a 4-tuple extent, or ``None``. When set with something other than
    
  214.     ``None``, only features that intersect the filter will be returned when
    
  215.     iterating over the layer::
    
  216. 
    
  217.         >>> print(layer.spatial_filter)
    
  218.         None
    
  219.         >>> print(len(layer))
    
  220.         3
    
  221.         >>> [feat.get('Name') for feat in layer]
    
  222.         ['Pueblo', 'Lawrence', 'Houston']
    
  223.         >>> ks_extent = (-102.051, 36.99, -94.59, 40.00) # Extent for state of Kansas
    
  224.         >>> layer.spatial_filter = ks_extent
    
  225.         >>> len(layer)
    
  226.         1
    
  227.         >>> [feat.get('Name') for feat in layer]
    
  228.         ['Lawrence']
    
  229.         >>> layer.spatial_filter = None
    
  230.         >>> len(layer)
    
  231.         3
    
  232. 
    
  233.     .. method:: get_fields()
    
  234. 
    
  235.     A method that returns a list of the values of a given field for each
    
  236.     feature in the layer::
    
  237. 
    
  238.         >>> layer.get_fields('Name')
    
  239.         ['Pueblo', 'Lawrence', 'Houston']
    
  240. 
    
  241.     .. method:: get_geoms(geos=False)
    
  242. 
    
  243.     A method that returns a list containing the geometry of each feature in the
    
  244.     layer. If the optional argument ``geos`` is set to ``True`` then the
    
  245.     geometries are converted to :class:`~django.contrib.gis.geos.GEOSGeometry`
    
  246.     objects. Otherwise, they are returned as :class:`OGRGeometry` objects::
    
  247. 
    
  248.         >>> [pt.tuple for pt in layer.get_geoms()]
    
  249.         [(-104.609252, 38.255001), (-95.23506, 38.971823), (-95.363151, 29.763374)]
    
  250. 
    
  251.     .. method:: test_capability(capability)
    
  252. 
    
  253.     Returns a boolean indicating whether this layer supports the given
    
  254.     capability (a string).  Examples of valid capability strings include:
    
  255.     ``'RandomRead'``, ``'SequentialWrite'``, ``'RandomWrite'``,
    
  256.     ``'FastSpatialFilter'``, ``'FastFeatureCount'``, ``'FastGetExtent'``,
    
  257.     ``'CreateField'``, ``'Transactions'``, ``'DeleteFeature'``, and
    
  258.     ``'FastSetNextByIndex'``.
    
  259. 
    
  260. ``Feature``
    
  261. -----------
    
  262. 
    
  263. .. class:: Feature
    
  264. 
    
  265.     ``Feature`` wraps an OGR feature. You never create a ``Feature`` object
    
  266.     directly. Instead, you retrieve them from a :class:`Layer` object. Each
    
  267.     feature consists of a geometry and a set of fields containing additional
    
  268.     properties. The geometry of a field is accessible via its ``geom`` property,
    
  269.     which returns an :class:`OGRGeometry` object. A ``Feature`` behaves like a
    
  270.     standard Python container for its fields, which it returns as :class:`Field`
    
  271.     objects: you can access a field directly by its index or name, or you can
    
  272.     iterate over a feature's fields, e.g. in a ``for`` loop.
    
  273. 
    
  274.     .. attribute:: geom
    
  275. 
    
  276.     Returns the geometry for this feature, as an ``OGRGeometry`` object::
    
  277. 
    
  278.         >>> city.geom.tuple
    
  279.         (-104.609252, 38.255001)
    
  280. 
    
  281.     .. attribute:: get
    
  282. 
    
  283.     A method that returns the value of the given field (specified by name)
    
  284.     for this feature, **not** a ``Field`` wrapper object::
    
  285. 
    
  286.         >>> city.get('Population')
    
  287.         102121
    
  288. 
    
  289.     .. attribute:: geom_type
    
  290. 
    
  291.     Returns the type of geometry for this feature, as an :class:`OGRGeomType`
    
  292.     object. This will be the same for all features in a given layer and is
    
  293.     equivalent to the :attr:`Layer.geom_type` property of the :class:`Layer`
    
  294.     object the feature came from.
    
  295. 
    
  296.     .. attribute:: num_fields
    
  297. 
    
  298.     Returns the number of fields of data associated with the feature. This will
    
  299.     be the same for all features in a given layer and is equivalent to the
    
  300.     :attr:`Layer.num_fields` property of the :class:`Layer` object the feature
    
  301.     came from.
    
  302. 
    
  303.     .. attribute:: fields
    
  304. 
    
  305.     Returns a list of the names of the fields of data associated with the
    
  306.     feature. This will be the same for all features in a given layer and is
    
  307.     equivalent to the :attr:`Layer.fields` property of the :class:`Layer`
    
  308.     object the feature came from.
    
  309. 
    
  310.     .. attribute:: fid
    
  311. 
    
  312.     Returns the feature identifier within the layer::
    
  313. 
    
  314.         >>> city.fid
    
  315.         0
    
  316. 
    
  317.     .. attribute:: layer_name
    
  318. 
    
  319.     Returns the name of the :class:`Layer` that the feature came from. This
    
  320.     will be the same for all features in a given layer::
    
  321. 
    
  322.         >>> city.layer_name
    
  323.         'cities'
    
  324. 
    
  325.     .. attribute:: index
    
  326. 
    
  327.     A method that returns the index of the given field name. This will be the
    
  328.     same for all features in a given layer::
    
  329. 
    
  330.         >>> city.index('Population')
    
  331.         1
    
  332. 
    
  333. ``Field``
    
  334. ---------
    
  335. 
    
  336. .. class:: Field
    
  337. 
    
  338.     .. attribute:: name
    
  339. 
    
  340.     Returns the name of this field::
    
  341. 
    
  342.         >>> city['Name'].name
    
  343.         'Name'
    
  344. 
    
  345.     .. attribute:: type
    
  346. 
    
  347.     Returns the OGR type of this field, as an integer. The ``FIELD_CLASSES``
    
  348.     dictionary maps these values onto subclasses of ``Field``::
    
  349. 
    
  350.         >>> city['Density'].type
    
  351.         2
    
  352. 
    
  353.     .. attribute:: type_name
    
  354. 
    
  355.     Returns a string with the name of the data type of this field::
    
  356. 
    
  357.         >>> city['Name'].type_name
    
  358.         'String'
    
  359. 
    
  360.     .. attribute:: value
    
  361. 
    
  362.     Returns the value of this field. The ``Field`` class itself returns the
    
  363.     value as a string, but each subclass returns the value in the most
    
  364.     appropriate form::
    
  365. 
    
  366.         >>> city['Population'].value
    
  367.         102121
    
  368. 
    
  369.     .. attribute:: width
    
  370. 
    
  371.     Returns the width of this field::
    
  372. 
    
  373.         >>> city['Name'].width
    
  374.         80
    
  375. 
    
  376.     .. attribute:: precision
    
  377. 
    
  378.     Returns the numeric precision of this field. This is meaningless (and set
    
  379.     to zero) for non-numeric fields::
    
  380. 
    
  381.         >>> city['Density'].precision
    
  382.         15
    
  383. 
    
  384.     .. method:: as_double()
    
  385. 
    
  386.     Returns the value of the field as a double (float)::
    
  387. 
    
  388.         >>> city['Density'].as_double()
    
  389.         874.7
    
  390. 
    
  391.     .. method:: as_int()
    
  392. 
    
  393.     Returns the value of the field as an integer::
    
  394. 
    
  395.         >>> city['Population'].as_int()
    
  396.         102121
    
  397. 
    
  398.     .. method:: as_string()
    
  399. 
    
  400.     Returns the value of the field as a string::
    
  401. 
    
  402.         >>> city['Name'].as_string()
    
  403.         'Pueblo'
    
  404. 
    
  405.     .. method:: as_datetime()
    
  406. 
    
  407.     Returns the value of the field as a tuple of date and time components::
    
  408. 
    
  409.         >>> city['Created'].as_datetime()
    
  410.         (c_long(1999), c_long(5), c_long(23), c_long(0), c_long(0), c_long(0), c_long(0))
    
  411. 
    
  412. ``Driver``
    
  413. ----------
    
  414. 
    
  415. .. class:: Driver(dr_input)
    
  416. 
    
  417.     The ``Driver`` class is used internally to wrap an OGR :class:`DataSource`
    
  418.     driver.
    
  419. 
    
  420.     .. attribute:: driver_count
    
  421. 
    
  422.     Returns the number of OGR vector drivers currently registered.
    
  423. 
    
  424. OGR Geometries
    
  425. ==============
    
  426. 
    
  427. ``OGRGeometry``
    
  428. ---------------
    
  429. 
    
  430. :class:`OGRGeometry` objects share similar functionality with
    
  431. :class:`~django.contrib.gis.geos.GEOSGeometry` objects and are thin wrappers
    
  432. around OGR's internal geometry representation. Thus, they allow for more
    
  433. efficient access to data when using :class:`DataSource`. Unlike its GEOS
    
  434. counterpart, :class:`OGRGeometry` supports spatial reference systems and
    
  435. coordinate transformation::
    
  436. 
    
  437.     >>> from django.contrib.gis.gdal import OGRGeometry
    
  438.     >>> polygon = OGRGeometry('POLYGON((0 0, 5 0, 5 5, 0 5))')
    
  439. 
    
  440. .. class:: OGRGeometry(geom_input, srs=None)
    
  441. 
    
  442.     This object is a wrapper for the `OGR Geometry`__ class. These objects are
    
  443.     instantiated directly from the given ``geom_input`` parameter, which may be
    
  444.     a string containing WKT, HEX, GeoJSON, a ``buffer`` containing WKB data, or
    
  445.     an :class:`OGRGeomType` object. These objects are also returned from the
    
  446.     :class:`Feature.geom` attribute, when reading vector data from
    
  447.     :class:`Layer` (which is in turn a part of a :class:`DataSource`).
    
  448. 
    
  449.     __ https://gdal.org/api/ogrgeometry_cpp.html#ogrgeometry-class
    
  450. 
    
  451.     .. classmethod:: from_gml(gml_string)
    
  452. 
    
  453.     Constructs an :class:`OGRGeometry` from the given GML string.
    
  454. 
    
  455.     .. classmethod:: from_bbox(bbox)
    
  456. 
    
  457.     Constructs a :class:`Polygon` from the given bounding-box (a 4-tuple).
    
  458. 
    
  459.     .. method:: __len__()
    
  460. 
    
  461.     Returns the number of points in a :class:`LineString`, the number of rings
    
  462.     in a :class:`Polygon`, or the number of geometries in a
    
  463.     :class:`GeometryCollection`. Not applicable to other geometry types.
    
  464. 
    
  465.     .. method:: __iter__()
    
  466. 
    
  467.     Iterates over the points in a :class:`LineString`, the rings in a
    
  468.     :class:`Polygon`, or the geometries in a :class:`GeometryCollection`.
    
  469.     Not applicable to other geometry types.
    
  470. 
    
  471.     .. method:: __getitem__()
    
  472. 
    
  473.     Returns the point at the specified index for a :class:`LineString`, the
    
  474.     interior ring at the specified index for a :class:`Polygon`, or the geometry
    
  475.     at the specified index in a :class:`GeometryCollection`. Not applicable to
    
  476.     other geometry types.
    
  477. 
    
  478.     .. attribute:: dimension
    
  479. 
    
  480.     Returns the number of coordinated dimensions of the geometry, i.e. 0
    
  481.     for points, 1 for lines, and so forth::
    
  482. 
    
  483.         >> polygon.dimension
    
  484.         2
    
  485. 
    
  486.     .. attribute:: coord_dim
    
  487. 
    
  488.     Returns or sets the coordinate dimension of this geometry. For example, the
    
  489.     value would be 2 for two-dimensional geometries.
    
  490. 
    
  491.     .. attribute:: geom_count
    
  492. 
    
  493.     Returns the number of elements in this geometry::
    
  494. 
    
  495.         >>> polygon.geom_count
    
  496.         1
    
  497. 
    
  498.     .. attribute:: point_count
    
  499. 
    
  500.     Returns the number of points used to describe this geometry::
    
  501. 
    
  502.         >>> polygon.point_count
    
  503.         4
    
  504. 
    
  505.     .. attribute:: num_points
    
  506. 
    
  507.     Alias for :attr:`point_count`.
    
  508. 
    
  509.     .. attribute:: num_coords
    
  510. 
    
  511.     Alias for :attr:`point_count`.
    
  512. 
    
  513.     .. attribute:: geom_type
    
  514. 
    
  515.     Returns the type of this geometry, as an :class:`OGRGeomType` object.
    
  516. 
    
  517.     .. attribute:: geom_name
    
  518. 
    
  519.     Returns the name of the type of this geometry::
    
  520. 
    
  521.         >>> polygon.geom_name
    
  522.         'POLYGON'
    
  523. 
    
  524.     .. attribute:: area
    
  525. 
    
  526.     Returns the area of this geometry, or 0 for geometries that do not contain
    
  527.     an area::
    
  528. 
    
  529.         >>> polygon.area
    
  530.         25.0
    
  531. 
    
  532.     .. attribute:: envelope
    
  533. 
    
  534.     Returns the envelope of this geometry, as an :class:`Envelope` object.
    
  535. 
    
  536.     .. attribute:: extent
    
  537. 
    
  538.     Returns the envelope of this geometry as a 4-tuple, instead of as an
    
  539.     :class:`Envelope` object::
    
  540. 
    
  541.         >>> point.extent
    
  542.         (0.0, 0.0, 5.0, 5.0)
    
  543. 
    
  544.     .. attribute:: srs
    
  545. 
    
  546.     This property controls the spatial reference for this geometry, or
    
  547.     ``None`` if no spatial reference system has been assigned to it.
    
  548.     If assigned, accessing this property returns a :class:`SpatialReference`
    
  549.     object.  It may be set with another :class:`SpatialReference` object,
    
  550.     or any input that :class:`SpatialReference` accepts. Example::
    
  551. 
    
  552.         >>> city.geom.srs.name
    
  553.         'GCS_WGS_1984'
    
  554. 
    
  555.     .. attribute:: srid
    
  556. 
    
  557.     Returns or sets the spatial reference identifier corresponding to
    
  558.     :class:`SpatialReference` of this geometry.  Returns ``None`` if
    
  559.     there is no spatial reference information associated with this
    
  560.     geometry, or if an SRID cannot be determined.
    
  561. 
    
  562.     .. attribute:: geos
    
  563. 
    
  564.     Returns a :class:`~django.contrib.gis.geos.GEOSGeometry` object
    
  565.     corresponding to this geometry.
    
  566. 
    
  567.     .. attribute:: gml
    
  568. 
    
  569.     Returns a string representation of this geometry in GML format::
    
  570. 
    
  571.         >>> OGRGeometry('POINT(1 2)').gml
    
  572.         '<gml:Point><gml:coordinates>1,2</gml:coordinates></gml:Point>'
    
  573. 
    
  574.     .. attribute:: hex
    
  575. 
    
  576.     Returns a string representation of this geometry in HEX WKB format::
    
  577. 
    
  578.         >>> OGRGeometry('POINT(1 2)').hex
    
  579.         '0101000000000000000000F03F0000000000000040'
    
  580. 
    
  581.     .. attribute:: json
    
  582. 
    
  583.     Returns a string representation of this geometry in JSON format::
    
  584. 
    
  585.         >>> OGRGeometry('POINT(1 2)').json
    
  586.         '{ "type": "Point", "coordinates": [ 1.000000, 2.000000 ] }'
    
  587. 
    
  588.     .. attribute:: kml
    
  589. 
    
  590.     Returns a string representation of this geometry in KML format.
    
  591. 
    
  592.     .. attribute:: wkb_size
    
  593. 
    
  594.     Returns the size of the WKB buffer needed to hold a WKB representation
    
  595.     of this geometry::
    
  596. 
    
  597.         >>> OGRGeometry('POINT(1 2)').wkb_size
    
  598.         21
    
  599. 
    
  600.     .. attribute:: wkb
    
  601. 
    
  602.     Returns a ``buffer`` containing a WKB representation of this geometry.
    
  603. 
    
  604.     .. attribute:: wkt
    
  605. 
    
  606.     Returns a string representation of this geometry in WKT format.
    
  607. 
    
  608.     .. attribute:: ewkt
    
  609. 
    
  610.     Returns the EWKT representation of this geometry.
    
  611. 
    
  612.     .. method:: clone()
    
  613. 
    
  614.     Returns a new :class:`OGRGeometry` clone of this geometry object.
    
  615. 
    
  616.     .. method:: close_rings()
    
  617. 
    
  618.     If there are any rings within this geometry that have not been closed,
    
  619.     this routine will do so by adding the starting point to the end::
    
  620. 
    
  621.         >>> triangle = OGRGeometry('LINEARRING (0 0,0 1,1 0)')
    
  622.         >>> triangle.close_rings()
    
  623.         >>> triangle.wkt
    
  624.         'LINEARRING (0 0,0 1,1 0,0 0)'
    
  625. 
    
  626.     .. method:: transform(coord_trans, clone=False)
    
  627. 
    
  628.     Transforms this geometry to a different spatial reference system. May take
    
  629.     a :class:`CoordTransform` object, a :class:`SpatialReference` object, or
    
  630.     any other input accepted by :class:`SpatialReference` (including spatial
    
  631.     reference WKT and PROJ strings, or an integer SRID).
    
  632. 
    
  633.     By default nothing is returned and the geometry is transformed in-place.
    
  634.     However, if the ``clone`` keyword is set to ``True`` then a transformed
    
  635.     clone of this geometry is returned instead.
    
  636. 
    
  637.     .. method:: intersects(other)
    
  638. 
    
  639.     Returns ``True`` if this geometry intersects the other, otherwise returns
    
  640.     ``False``.
    
  641. 
    
  642.     .. method:: equals(other)
    
  643. 
    
  644.     Returns ``True`` if this geometry is equivalent to the other, otherwise
    
  645.     returns ``False``.
    
  646. 
    
  647.     .. method:: disjoint(other)
    
  648. 
    
  649.     Returns ``True`` if this geometry is spatially disjoint to (i.e. does
    
  650.     not intersect) the other, otherwise returns ``False``.
    
  651. 
    
  652.     .. method:: touches(other)
    
  653. 
    
  654.     Returns ``True`` if this geometry touches the other, otherwise returns
    
  655.     ``False``.
    
  656. 
    
  657.     .. method:: crosses(other)
    
  658. 
    
  659.     Returns ``True`` if this geometry crosses the other, otherwise returns
    
  660.     ``False``.
    
  661. 
    
  662.     .. method:: within(other)
    
  663. 
    
  664.     Returns ``True`` if this geometry is contained within the other, otherwise
    
  665.     returns ``False``.
    
  666. 
    
  667.     .. method:: contains(other)
    
  668. 
    
  669.     Returns ``True`` if this geometry contains the other, otherwise returns
    
  670.     ``False``.
    
  671. 
    
  672.     .. method:: overlaps(other)
    
  673. 
    
  674.     Returns ``True`` if this geometry overlaps the other, otherwise returns
    
  675.     ``False``.
    
  676. 
    
  677.     .. method:: boundary()
    
  678. 
    
  679.     The boundary of this geometry, as a new :class:`OGRGeometry` object.
    
  680. 
    
  681.     .. attribute:: convex_hull
    
  682. 
    
  683.     The smallest convex polygon that contains this geometry, as a new
    
  684.     :class:`OGRGeometry` object.
    
  685. 
    
  686.     .. method:: difference()
    
  687. 
    
  688.     Returns the region consisting of the difference of this geometry and
    
  689.     the other, as a new :class:`OGRGeometry` object.
    
  690. 
    
  691.     .. method:: intersection()
    
  692. 
    
  693.     Returns the region consisting of the intersection of this geometry and
    
  694.     the other, as a new :class:`OGRGeometry` object.
    
  695. 
    
  696.     .. method:: sym_difference()
    
  697. 
    
  698.     Returns the region consisting of the symmetric difference of this
    
  699.     geometry and the other, as a new :class:`OGRGeometry` object.
    
  700. 
    
  701.     .. method:: union()
    
  702. 
    
  703.     Returns the region consisting of the union of this geometry and
    
  704.     the other, as a new :class:`OGRGeometry` object.
    
  705. 
    
  706.     .. attribute:: tuple
    
  707. 
    
  708.     Returns the coordinates of a point geometry as a tuple, the
    
  709.     coordinates of a line geometry as a tuple of tuples, and so forth::
    
  710. 
    
  711.         >>> OGRGeometry('POINT (1 2)').tuple
    
  712.         (1.0, 2.0)
    
  713.         >>> OGRGeometry('LINESTRING (1 2,3 4)').tuple
    
  714.         ((1.0, 2.0), (3.0, 4.0))
    
  715. 
    
  716.     .. attribute:: coords
    
  717. 
    
  718.     An alias for :attr:`tuple`.
    
  719. 
    
  720. .. class:: Point
    
  721. 
    
  722.     .. attribute:: x
    
  723. 
    
  724.     Returns the X coordinate of this point::
    
  725. 
    
  726.         >>> OGRGeometry('POINT (1 2)').x
    
  727.         1.0
    
  728. 
    
  729.     .. attribute:: y
    
  730. 
    
  731.     Returns the Y coordinate of this point::
    
  732. 
    
  733.         >>> OGRGeometry('POINT (1 2)').y
    
  734.         2.0
    
  735. 
    
  736.     .. attribute:: z
    
  737. 
    
  738.     Returns the Z coordinate of this point, or ``None`` if the point does not
    
  739.     have a Z coordinate::
    
  740. 
    
  741.         >>> OGRGeometry('POINT (1 2 3)').z
    
  742.         3.0
    
  743. 
    
  744. .. class:: LineString
    
  745. 
    
  746.     .. attribute:: x
    
  747. 
    
  748.     Returns a list of X coordinates in this line::
    
  749. 
    
  750.         >>> OGRGeometry('LINESTRING (1 2,3 4)').x
    
  751.         [1.0, 3.0]
    
  752. 
    
  753.     .. attribute:: y
    
  754. 
    
  755.     Returns a list of Y coordinates in this line::
    
  756. 
    
  757.         >>> OGRGeometry('LINESTRING (1 2,3 4)').y
    
  758.         [2.0, 4.0]
    
  759. 
    
  760.     .. attribute:: z
    
  761. 
    
  762.     Returns a list of Z coordinates in this line, or ``None`` if the line does
    
  763.     not have Z coordinates::
    
  764. 
    
  765.         >>> OGRGeometry('LINESTRING (1 2 3,4 5 6)').z
    
  766.         [3.0, 6.0]
    
  767. 
    
  768. 
    
  769. .. class:: Polygon
    
  770. 
    
  771.     .. attribute:: shell
    
  772. 
    
  773.     Returns the shell or exterior ring of this polygon, as a ``LinearRing``
    
  774.     geometry.
    
  775. 
    
  776.     .. attribute:: exterior_ring
    
  777. 
    
  778.     An alias for :attr:`shell`.
    
  779. 
    
  780.     .. attribute:: centroid
    
  781. 
    
  782.     Returns a :class:`Point` representing the centroid of this polygon.
    
  783. 
    
  784. .. class:: GeometryCollection
    
  785. 
    
  786.     .. method:: add(geom)
    
  787. 
    
  788.     Adds a geometry to this geometry collection. Not applicable to other
    
  789.     geometry types.
    
  790. 
    
  791. ``OGRGeomType``
    
  792. ---------------
    
  793. 
    
  794. .. class:: OGRGeomType(type_input)
    
  795. 
    
  796.     This class allows for the representation of an OGR geometry type
    
  797.     in any of several ways::
    
  798. 
    
  799.         >>> from django.contrib.gis.gdal import OGRGeomType
    
  800.         >>> gt1 = OGRGeomType(3)             # Using an integer for the type
    
  801.         >>> gt2 = OGRGeomType('Polygon')     # Using a string
    
  802.         >>> gt3 = OGRGeomType('POLYGON')     # It's case-insensitive
    
  803.         >>> print(gt1 == 3, gt1 == 'Polygon') # Equivalence works w/non-OGRGeomType objects
    
  804.         True True
    
  805. 
    
  806.     .. attribute:: name
    
  807. 
    
  808.     Returns a short-hand string form of the OGR Geometry type::
    
  809. 
    
  810.         >>> gt1.name
    
  811.         'Polygon'
    
  812. 
    
  813.     .. attribute:: num
    
  814. 
    
  815.     Returns the number corresponding to the OGR geometry type::
    
  816. 
    
  817.         >>> gt1.num
    
  818.         3
    
  819. 
    
  820.     .. attribute:: django
    
  821. 
    
  822.     Returns the Django field type (a subclass of GeometryField) to use for
    
  823.     storing this OGR type, or ``None`` if there is no appropriate Django type::
    
  824. 
    
  825.         >>> gt1.django
    
  826.         'PolygonField'
    
  827. 
    
  828. ``Envelope``
    
  829. ------------
    
  830. 
    
  831. .. class:: Envelope(*args)
    
  832. 
    
  833.     Represents an OGR Envelope structure that contains the minimum and maximum
    
  834.     X, Y coordinates for a rectangle bounding box. The naming of the variables
    
  835.     is compatible with the OGR Envelope C structure.
    
  836. 
    
  837.     .. attribute:: min_x
    
  838. 
    
  839.     The value of the minimum X coordinate.
    
  840. 
    
  841.     .. attribute:: min_y
    
  842. 
    
  843.     The value of the maximum X coordinate.
    
  844. 
    
  845.     .. attribute:: max_x
    
  846. 
    
  847.     The value of the minimum Y coordinate.
    
  848. 
    
  849.     .. attribute:: max_y
    
  850. 
    
  851.     The value of the maximum Y coordinate.
    
  852. 
    
  853.     .. attribute:: ur
    
  854. 
    
  855.     The upper-right coordinate, as a tuple.
    
  856. 
    
  857.     .. attribute:: ll
    
  858. 
    
  859.     The lower-left coordinate, as a tuple.
    
  860. 
    
  861.     .. attribute:: tuple
    
  862. 
    
  863.     A tuple representing the envelope.
    
  864. 
    
  865.     .. attribute:: wkt
    
  866. 
    
  867.     A string representing this envelope as a polygon in WKT format.
    
  868. 
    
  869.     .. method:: expand_to_include(*args)
    
  870. 
    
  871. Coordinate System Objects
    
  872. =========================
    
  873. 
    
  874. ``SpatialReference``
    
  875. --------------------
    
  876. 
    
  877. .. class:: SpatialReference(srs_input)
    
  878. 
    
  879.     Spatial reference objects are initialized on the given ``srs_input``,
    
  880.     which may be one of the following:
    
  881. 
    
  882.     * OGC Well Known Text (WKT) (a string)
    
  883.     * EPSG code (integer or string)
    
  884.     * PROJ string
    
  885.     * A shorthand string for well-known standards (``'WGS84'``, ``'WGS72'``,
    
  886.       ``'NAD27'``, ``'NAD83'``)
    
  887. 
    
  888.     Example::
    
  889. 
    
  890.         >>> wgs84 = SpatialReference('WGS84') # shorthand string
    
  891.         >>> wgs84 = SpatialReference(4326) # EPSG code
    
  892.         >>> wgs84 = SpatialReference('EPSG:4326') # EPSG string
    
  893.         >>> proj = '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs '
    
  894.         >>> wgs84 = SpatialReference(proj) # PROJ string
    
  895.         >>> wgs84 = SpatialReference("""GEOGCS["WGS 84",
    
  896.         DATUM["WGS_1984",
    
  897.              SPHEROID["WGS 84",6378137,298.257223563,
    
  898.                  AUTHORITY["EPSG","7030"]],
    
  899.              AUTHORITY["EPSG","6326"]],
    
  900.          PRIMEM["Greenwich",0,
    
  901.              AUTHORITY["EPSG","8901"]],
    
  902.          UNIT["degree",0.01745329251994328,
    
  903.              AUTHORITY["EPSG","9122"]],
    
  904.          AUTHORITY["EPSG","4326"]]""") # OGC WKT
    
  905. 
    
  906.     .. method:: __getitem__(target)
    
  907. 
    
  908.     Returns the value of the given string attribute node, ``None`` if the node
    
  909.     doesn't exist. Can also take a tuple as a parameter, (target, child), where
    
  910.     child is the index of the attribute in the WKT. For example::
    
  911. 
    
  912.         >>> wkt = 'GEOGCS["WGS 84", DATUM["WGS_1984, ... AUTHORITY["EPSG","4326"]]')
    
  913.         >>> srs = SpatialReference(wkt) # could also use 'WGS84', or 4326
    
  914.         >>> print(srs['GEOGCS'])
    
  915.         WGS 84
    
  916.         >>> print(srs['DATUM'])
    
  917.         WGS_1984
    
  918.         >>> print(srs['AUTHORITY'])
    
  919.         EPSG
    
  920.         >>> print(srs['AUTHORITY', 1]) # The authority value
    
  921.         4326
    
  922.         >>> print(srs['TOWGS84', 4]) # the fourth value in this wkt
    
  923.         0
    
  924.         >>> print(srs['UNIT|AUTHORITY']) # For the units authority, have to use the pipe symbol.
    
  925.         EPSG
    
  926.         >>> print(srs['UNIT|AUTHORITY', 1]) # The authority value for the units
    
  927.         9122
    
  928. 
    
  929.     .. method:: attr_value(target, index=0)
    
  930. 
    
  931.     The attribute value for the given target node (e.g. ``'PROJCS'``).
    
  932.     The index keyword specifies an index of the child node to return.
    
  933. 
    
  934.     .. method:: auth_name(target)
    
  935. 
    
  936.     Returns the authority name for the given string target node.
    
  937. 
    
  938.     .. method:: auth_code(target)
    
  939. 
    
  940.     Returns the authority code for the given string target node.
    
  941. 
    
  942.     .. method:: clone()
    
  943. 
    
  944.     Returns a clone of this spatial reference object.
    
  945. 
    
  946.     .. method:: identify_epsg()
    
  947. 
    
  948.     This method inspects the WKT of this ``SpatialReference`` and will add EPSG
    
  949.     authority nodes where an EPSG identifier is applicable.
    
  950. 
    
  951.     .. method:: from_esri()
    
  952. 
    
  953.     Morphs this SpatialReference from ESRI's format to EPSG
    
  954. 
    
  955.     .. method:: to_esri()
    
  956. 
    
  957.     Morphs this SpatialReference to ESRI's format.
    
  958. 
    
  959.     .. method:: validate()
    
  960. 
    
  961.     Checks to see if the given spatial reference is valid, if not
    
  962.     an exception will be raised.
    
  963. 
    
  964.     .. method:: import_epsg(epsg)
    
  965. 
    
  966.     Import spatial reference from EPSG code.
    
  967. 
    
  968.     .. method:: import_proj(proj)
    
  969. 
    
  970.     Import spatial reference from PROJ string.
    
  971. 
    
  972.     .. method:: import_user_input(user_input)
    
  973. 
    
  974.     .. method:: import_wkt(wkt)
    
  975. 
    
  976.     Import spatial reference from WKT.
    
  977. 
    
  978.     .. method:: import_xml(xml)
    
  979. 
    
  980.     Import spatial reference from XML.
    
  981. 
    
  982.     .. attribute:: name
    
  983. 
    
  984.     Returns the name of this Spatial Reference.
    
  985. 
    
  986.     .. attribute:: srid
    
  987. 
    
  988.     Returns the SRID of top-level authority, or ``None`` if undefined.
    
  989. 
    
  990.     .. attribute:: linear_name
    
  991. 
    
  992.     Returns the name of the linear units.
    
  993. 
    
  994.     .. attribute:: linear_units
    
  995. 
    
  996.     Returns the value of the linear units.
    
  997. 
    
  998.     .. attribute:: angular_name
    
  999. 
    
  1000.     Returns the name of the angular units."
    
  1001. 
    
  1002.     .. attribute:: angular_units
    
  1003. 
    
  1004.     Returns the value of the angular units.
    
  1005. 
    
  1006.     .. attribute:: units
    
  1007. 
    
  1008.     Returns a 2-tuple of the units value and the units name and will
    
  1009.     automatically determines whether to return the linear or angular units.
    
  1010. 
    
  1011.     .. attribute:: ellipsoid
    
  1012. 
    
  1013.     Returns a tuple of the ellipsoid parameters for this spatial reference:
    
  1014.     (semimajor axis, semiminor axis, and inverse flattening).
    
  1015. 
    
  1016.     .. attribute:: semi_major
    
  1017. 
    
  1018.     Returns the semi major axis of the ellipsoid for this spatial reference.
    
  1019. 
    
  1020.     .. attribute:: semi_minor
    
  1021. 
    
  1022.     Returns the semi minor axis of the ellipsoid for this spatial reference.
    
  1023. 
    
  1024.     .. attribute:: inverse_flattening
    
  1025. 
    
  1026.     Returns the inverse flattening of the ellipsoid for this spatial reference.
    
  1027. 
    
  1028.     .. attribute:: geographic
    
  1029. 
    
  1030.     Returns ``True`` if this spatial reference is geographic (root node is
    
  1031.     ``GEOGCS``).
    
  1032. 
    
  1033.     .. attribute:: local
    
  1034. 
    
  1035.     Returns ``True`` if this spatial reference is local (root node is
    
  1036.     ``LOCAL_CS``).
    
  1037. 
    
  1038.     .. attribute:: projected
    
  1039. 
    
  1040.     Returns ``True`` if this spatial reference is a projected coordinate system
    
  1041.     (root node is ``PROJCS``).
    
  1042. 
    
  1043.     .. attribute:: wkt
    
  1044. 
    
  1045.     Returns the WKT representation of this spatial reference.
    
  1046. 
    
  1047.     .. attribute:: pretty_wkt
    
  1048. 
    
  1049.     Returns the 'pretty' representation of the WKT.
    
  1050. 
    
  1051.     .. attribute:: proj
    
  1052. 
    
  1053.     Returns the PROJ representation for this spatial reference.
    
  1054. 
    
  1055.     .. attribute:: proj4
    
  1056. 
    
  1057.     Alias for :attr:`SpatialReference.proj`.
    
  1058. 
    
  1059.     .. attribute:: xml
    
  1060. 
    
  1061.     Returns the XML representation of this spatial reference.
    
  1062. 
    
  1063. ``CoordTransform``
    
  1064. ------------------
    
  1065. 
    
  1066. .. class:: CoordTransform(source, target)
    
  1067. 
    
  1068. Represents a coordinate system transform. It is initialized with two
    
  1069. :class:`SpatialReference`, representing the source and target coordinate
    
  1070. systems, respectively. These objects should be used when performing the same
    
  1071. coordinate transformation repeatedly on different geometries::
    
  1072. 
    
  1073.     >>> ct = CoordTransform(SpatialReference('WGS84'), SpatialReference('NAD83'))
    
  1074.     >>> for feat in layer:
    
  1075.     ...     geom = feat.geom # getting clone of feature geometry
    
  1076.     ...     geom.transform(ct) # transforming
    
  1077. 
    
  1078. .. _raster-data-source-objects:
    
  1079. 
    
  1080. Raster Data Objects
    
  1081. ===================
    
  1082. 
    
  1083. ``GDALRaster``
    
  1084. ----------------
    
  1085. 
    
  1086. :class:`GDALRaster` is a wrapper for the GDAL raster source object that
    
  1087. supports reading data from a variety of GDAL-supported geospatial file
    
  1088. formats and data sources using a consistent interface.  Each
    
  1089. data source is represented by a :class:`GDALRaster` object which contains
    
  1090. one or more layers of data named bands.  Each band, represented by a
    
  1091. :class:`GDALBand` object, contains georeferenced image data. For example, an RGB
    
  1092. image is represented as three bands: one for red, one for green, and one for
    
  1093. blue.
    
  1094. 
    
  1095. .. note::
    
  1096. 
    
  1097.     For raster data there is no difference between a raster instance and its
    
  1098.     data source. Unlike for the Geometry objects, :class:`GDALRaster` objects are
    
  1099.     always a data source. Temporary rasters can be instantiated in memory
    
  1100.     using the corresponding driver, but they will be of the same class as file-based
    
  1101.     raster sources.
    
  1102. 
    
  1103. .. class:: GDALRaster(ds_input, write=False)
    
  1104. 
    
  1105.     The constructor for ``GDALRaster`` accepts two parameters. The first
    
  1106.     parameter defines the raster source, and the second parameter defines if a
    
  1107.     raster should be opened in write mode. For newly-created rasters, the second
    
  1108.     parameter is ignored and the new raster is always created in write mode.
    
  1109. 
    
  1110.     The first parameter can take three forms: a string representing a file path
    
  1111.     (filesystem or GDAL virtual filesystem), a dictionary with values defining
    
  1112.     a new raster, or a bytes object representing a raster file.
    
  1113. 
    
  1114.     If the input is a file path, the raster is opened from there. If the input
    
  1115.     is raw data in a dictionary, the parameters ``width``, ``height``, and
    
  1116.     ``srid`` are required. If the input is a bytes object, it will be opened
    
  1117.     using a GDAL virtual filesystem.
    
  1118. 
    
  1119.     For a detailed description of how to create rasters using dictionary input,
    
  1120.     see :ref:`gdal-raster-ds-input`. For a detailed description of how to
    
  1121.     create rasters in the virtual filesystem, see :ref:`gdal-raster-vsimem`.
    
  1122. 
    
  1123.     The following example shows how rasters can be created from different input
    
  1124.     sources (using the sample data from the GeoDjango tests; see also the
    
  1125.     :ref:`gdal_sample_data` section).
    
  1126. 
    
  1127.         >>> from django.contrib.gis.gdal import GDALRaster
    
  1128.         >>> rst = GDALRaster('/path/to/your/raster.tif', write=False)
    
  1129.         >>> rst.name
    
  1130.         '/path/to/your/raster.tif'
    
  1131.         >>> rst.width, rst.height  # This file has 163 x 174 pixels
    
  1132.         (163, 174)
    
  1133.         >>> rst = GDALRaster({  # Creates an in-memory raster
    
  1134.         ...     'srid': 4326,
    
  1135.         ...     'width': 4,
    
  1136.         ...     'height': 4,
    
  1137.         ...     'datatype': 1,
    
  1138.         ...     'bands': [{
    
  1139.         ...         'data': (2, 3),
    
  1140.         ...         'offset': (1, 1),
    
  1141.         ...         'size': (2, 2),
    
  1142.         ...         'shape': (2, 1),
    
  1143.         ...         'nodata_value': 5,
    
  1144.         ...     }]
    
  1145.         ... })
    
  1146.         >>> rst.srs.srid
    
  1147.         4326
    
  1148.         >>> rst.width, rst.height
    
  1149.         (4, 4)
    
  1150.         >>> rst.bands[0].data()
    
  1151.         array([[5, 5, 5, 5],
    
  1152.                [5, 2, 3, 5],
    
  1153.                [5, 2, 3, 5],
    
  1154.                [5, 5, 5, 5]], dtype=uint8)
    
  1155.         >>> rst_file = open('/path/to/your/raster.tif', 'rb')
    
  1156.         >>> rst_bytes = rst_file.read()
    
  1157.         >>> rst = GDALRaster(rst_bytes)
    
  1158.         >>> rst.is_vsi_based
    
  1159.         True
    
  1160.         >>> rst.name  # Stored in a random path in the vsimem filesystem.
    
  1161.         '/vsimem/da300bdb-129d-49a8-b336-e410a9428dad'
    
  1162. 
    
  1163.     .. versionchanged:: 4.0
    
  1164. 
    
  1165.         Creating rasters in any GDAL virtual filesystem was allowed.
    
  1166. 
    
  1167.     .. attribute:: name
    
  1168. 
    
  1169.         The name of the source which is equivalent to the input file path or the name
    
  1170.         provided upon instantiation.
    
  1171. 
    
  1172.             >>> GDALRaster({'width': 10, 'height': 10, 'name': 'myraster', 'srid': 4326}).name
    
  1173.             'myraster'
    
  1174. 
    
  1175.     .. attribute:: driver
    
  1176. 
    
  1177.         The name of the GDAL driver used to handle the input file. For ``GDALRaster``\s created
    
  1178.         from a file, the driver type is detected automatically. The creation of rasters from
    
  1179.         scratch is an in-memory raster by default (``'MEM'``), but can be
    
  1180.         altered as needed. For instance, use ``GTiff`` for a ``GeoTiff`` file.
    
  1181.         For a list of file types, see also the `GDAL Raster Formats`__ list.
    
  1182. 
    
  1183.         __ https://gdal.org/drivers/raster/
    
  1184. 
    
  1185.         An in-memory raster is created through the following example:
    
  1186. 
    
  1187.             >>> GDALRaster({'width': 10, 'height': 10, 'srid': 4326}).driver.name
    
  1188.             'MEM'
    
  1189. 
    
  1190.         A file based GeoTiff raster is created through the following example:
    
  1191. 
    
  1192.             >>> import tempfile
    
  1193.             >>> rstfile = tempfile.NamedTemporaryFile(suffix='.tif')
    
  1194.             >>> rst = GDALRaster({'driver': 'GTiff', 'name': rstfile.name, 'srid': 4326,
    
  1195.             ...                   'width': 255, 'height': 255, 'nr_of_bands': 1})
    
  1196.             >>> rst.name
    
  1197.             '/tmp/tmp7x9H4J.tif'           # The exact filename will be different on your computer
    
  1198.             >>> rst.driver.name
    
  1199.             'GTiff'
    
  1200. 
    
  1201.     .. attribute:: width
    
  1202. 
    
  1203.         The width of the source in pixels (X-axis).
    
  1204. 
    
  1205.             >>> GDALRaster({'width': 10, 'height': 20, 'srid': 4326}).width
    
  1206.             10
    
  1207. 
    
  1208.     .. attribute:: height
    
  1209. 
    
  1210.         The height of the source in pixels (Y-axis).
    
  1211. 
    
  1212.             >>> GDALRaster({'width': 10, 'height': 20, 'srid': 4326}).height
    
  1213.             20
    
  1214. 
    
  1215.     .. attribute:: srs
    
  1216. 
    
  1217.         The spatial reference system of the raster, as a
    
  1218.         :class:`SpatialReference` instance. The SRS can be changed by
    
  1219.         setting it to an other :class:`SpatialReference` or providing any input
    
  1220.         that is accepted by the :class:`SpatialReference` constructor.
    
  1221. 
    
  1222.             >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})
    
  1223.             >>> rst.srs.srid
    
  1224.             4326
    
  1225.             >>> rst.srs = 3086
    
  1226.             >>> rst.srs.srid
    
  1227.             3086
    
  1228. 
    
  1229.     .. attribute:: srid
    
  1230. 
    
  1231.         The Spatial Reference System Identifier (SRID) of the raster. This
    
  1232.         property is a shortcut to getting or setting the SRID through the
    
  1233.         :attr:`srs` attribute.
    
  1234. 
    
  1235.             >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})
    
  1236.             >>> rst.srid
    
  1237.             4326
    
  1238.             >>> rst.srid = 3086
    
  1239.             >>> rst.srid
    
  1240.             3086
    
  1241.             >>> rst.srs.srid  # This is equivalent
    
  1242.             3086
    
  1243. 
    
  1244.     .. attribute:: geotransform
    
  1245. 
    
  1246.         The affine transformation matrix used to georeference the source, as a
    
  1247.         tuple of six coefficients which map pixel/line coordinates into
    
  1248.         georeferenced space using the following relationship::
    
  1249. 
    
  1250.             Xgeo = GT(0) + Xpixel*GT(1) + Yline*GT(2)
    
  1251.             Ygeo = GT(3) + Xpixel*GT(4) + Yline*GT(5)
    
  1252. 
    
  1253.         The same values can be retrieved by accessing the :attr:`origin`
    
  1254.         (indices 0 and 3), :attr:`scale` (indices 1 and 5) and :attr:`skew`
    
  1255.         (indices 2 and 4) properties.
    
  1256. 
    
  1257.         The default is ``[0.0, 1.0, 0.0, 0.0, 0.0, -1.0]``.
    
  1258. 
    
  1259.             >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})
    
  1260.             >>> rst.geotransform
    
  1261.             [0.0, 1.0, 0.0, 0.0, 0.0, -1.0]
    
  1262. 
    
  1263.     .. attribute:: origin
    
  1264. 
    
  1265.         Coordinates of the top left origin of the raster in the spatial
    
  1266.         reference system of the source, as a point object with ``x`` and ``y``
    
  1267.         members.
    
  1268. 
    
  1269.             >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})
    
  1270.             >>> rst.origin
    
  1271.             [0.0, 0.0]
    
  1272.             >>> rst.origin.x = 1
    
  1273.             >>> rst.origin
    
  1274.             [1.0, 0.0]
    
  1275. 
    
  1276.     .. attribute:: scale
    
  1277. 
    
  1278.         Pixel width and height used for georeferencing the raster, as a point
    
  1279.         object with ``x`` and ``y``  members. See :attr:`geotransform` for more
    
  1280.         information.
    
  1281. 
    
  1282.             >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})
    
  1283.             >>> rst.scale
    
  1284.             [1.0, -1.0]
    
  1285.             >>> rst.scale.x = 2
    
  1286.             >>> rst.scale
    
  1287.             [2.0, -1.0]
    
  1288. 
    
  1289.     .. attribute:: skew
    
  1290. 
    
  1291.         Skew coefficients used to georeference the raster, as a point object
    
  1292.         with ``x`` and ``y``  members. In case of north up images, these
    
  1293.         coefficients are both ``0``.
    
  1294. 
    
  1295.             >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})
    
  1296.             >>> rst.skew
    
  1297.             [0.0, 0.0]
    
  1298.             >>> rst.skew.x = 3
    
  1299.             >>> rst.skew
    
  1300.             [3.0, 0.0]
    
  1301. 
    
  1302.     .. attribute:: extent
    
  1303. 
    
  1304.         Extent (boundary values) of the raster source, as a 4-tuple
    
  1305.         ``(xmin, ymin, xmax, ymax)`` in the spatial reference system of the
    
  1306.         source.
    
  1307. 
    
  1308.             >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})
    
  1309.             >>> rst.extent
    
  1310.             (0.0, -20.0, 10.0, 0.0)
    
  1311.             >>> rst.origin.x = 100
    
  1312.             >>> rst.extent
    
  1313.             (100.0, -20.0, 110.0, 0.0)
    
  1314. 
    
  1315.     .. attribute:: bands
    
  1316. 
    
  1317.         List of all bands of the source, as :class:`GDALBand` instances.
    
  1318. 
    
  1319.             >>> rst = GDALRaster({"width": 1, "height": 2, 'srid': 4326,
    
  1320.             ...                   "bands": [{"data": [0, 1]}, {"data": [2, 3]}]})
    
  1321.             >>> len(rst.bands)
    
  1322.             2
    
  1323.             >>> rst.bands[1].data()
    
  1324.             array([[ 2.,  3.]], dtype=float32)
    
  1325. 
    
  1326.     .. method:: warp(ds_input, resampling='NearestNeighbour', max_error=0.0)
    
  1327. 
    
  1328.         Returns a warped version of this raster.
    
  1329. 
    
  1330.         The warping parameters can be specified through the ``ds_input``
    
  1331.         argument. The use of ``ds_input`` is analogous to the corresponding
    
  1332.         argument of the class constructor. It is a dictionary with the
    
  1333.         characteristics of the target raster. Allowed dictionary key values are
    
  1334.         width, height, SRID, origin, scale, skew, datatype, driver, and name
    
  1335.         (filename).
    
  1336. 
    
  1337.         By default, the warp functions keeps most parameters equal to the
    
  1338.         values of the original source raster, so only parameters that should be
    
  1339.         changed need to be specified. Note that this includes the driver, so
    
  1340.         for file-based rasters the warp function will create a new raster on
    
  1341.         disk.
    
  1342. 
    
  1343.         The only parameter that is set differently from the source raster is the
    
  1344.         name. The default value of the raster name is the name of the source
    
  1345.         raster appended with ``'_copy' + source_driver_name``. For file-based
    
  1346.         rasters it is recommended to provide the file path of the target raster.
    
  1347. 
    
  1348.         The resampling algorithm used for warping can be specified with the
    
  1349.         ``resampling`` argument. The default is ``NearestNeighbor``, and the
    
  1350.         other allowed values are ``Bilinear``, ``Cubic``, ``CubicSpline``,
    
  1351.         ``Lanczos``, ``Average``, and ``Mode``.
    
  1352. 
    
  1353.         The ``max_error`` argument can be used to specify the maximum error
    
  1354.         measured in input pixels that is allowed in approximating the
    
  1355.         transformation. The default is 0.0 for exact calculations.
    
  1356. 
    
  1357.         For users familiar with ``GDAL``, this function has a similar
    
  1358.         functionality to the ``gdalwarp`` command-line utility.
    
  1359. 
    
  1360.         For example, the warp function can be used for aggregating a raster to
    
  1361.         the double of its original pixel scale:
    
  1362. 
    
  1363.             >>> rst = GDALRaster({
    
  1364.             ...     "width": 6, "height": 6, "srid": 3086,
    
  1365.             ...     "origin": [500000, 400000],
    
  1366.             ...     "scale": [100, -100],
    
  1367.             ...     "bands": [{"data": range(36), "nodata_value": 99}]
    
  1368.             ... })
    
  1369.             >>> target = rst.warp({"scale": [200, -200], "width": 3, "height": 3})
    
  1370.             >>> target.bands[0].data()
    
  1371.             array([[  7.,   9.,  11.],
    
  1372.                    [ 19.,  21.,  23.],
    
  1373.                    [ 31.,  33.,  35.]], dtype=float32)
    
  1374. 
    
  1375.     .. method:: transform(srs, driver=None, name=None, resampling='NearestNeighbour', max_error=0.0)
    
  1376. 
    
  1377.         Transforms this raster to a different spatial reference system
    
  1378.         (``srs``), which may be a :class:`SpatialReference` object, or any
    
  1379.         other input accepted by :class:`SpatialReference` (including spatial
    
  1380.         reference WKT and PROJ strings, or an integer SRID).
    
  1381. 
    
  1382.         It calculates the bounds and scale of the current raster in the new
    
  1383.         spatial reference system and warps the raster using the
    
  1384.         :attr:`~GDALRaster.warp` function.
    
  1385. 
    
  1386.         By default, the driver of the source raster is used and the name of the
    
  1387.         raster is the original name appended with
    
  1388.         ``'_copy' + source_driver_name``. A different driver or name can be
    
  1389.         specified with the ``driver`` and ``name`` arguments.
    
  1390. 
    
  1391.         The default resampling algorithm is ``NearestNeighbour`` but can be
    
  1392.         changed using the ``resampling`` argument. The default maximum allowed
    
  1393.         error for resampling is 0.0 and can be changed using the ``max_error``
    
  1394.         argument. Consult the :attr:`~GDALRaster.warp` documentation for detail
    
  1395.         on those arguments.
    
  1396. 
    
  1397.             >>> rst = GDALRaster({
    
  1398.             ...     "width": 6, "height": 6, "srid": 3086,
    
  1399.             ...     "origin": [500000, 400000],
    
  1400.             ...     "scale": [100, -100],
    
  1401.             ...     "bands": [{"data": range(36), "nodata_value": 99}]
    
  1402.             ... })
    
  1403.             >>> target_srs = SpatialReference(4326)
    
  1404.             >>> target = rst.transform(target_srs)
    
  1405.             >>> target.origin
    
  1406.             [-82.98492744885776, 27.601924753080144]
    
  1407. 
    
  1408.     .. attribute:: info
    
  1409. 
    
  1410.         Returns a string with a summary of the raster. This is equivalent to
    
  1411.         the `gdalinfo`__ command line utility.
    
  1412. 
    
  1413.         __ https://gdal.org/programs/gdalinfo.html
    
  1414. 
    
  1415.     .. attribute:: metadata
    
  1416. 
    
  1417.         The metadata of this raster, represented as a nested dictionary. The
    
  1418.         first-level key is the metadata domain. The second-level contains the
    
  1419.         metadata item names and values from each domain.
    
  1420. 
    
  1421.         To set or update a metadata item, pass the corresponding metadata item
    
  1422.         to the method using the nested structure described above. Only keys
    
  1423.         that are in the specified dictionary are updated; the rest of the
    
  1424.         metadata remains unchanged.
    
  1425. 
    
  1426.         To remove a metadata item, use ``None`` as the metadata value.
    
  1427. 
    
  1428.             >>> rst = GDALRaster({'width': 10, 'height': 20, 'srid': 4326})
    
  1429.             >>> rst.metadata
    
  1430.             {}
    
  1431.             >>> rst.metadata = {'DEFAULT': {'OWNER': 'Django', 'VERSION': '1.0'}}
    
  1432.             >>> rst.metadata
    
  1433.             {'DEFAULT': {'OWNER': 'Django', 'VERSION': '1.0'}}
    
  1434.             >>> rst.metadata = {'DEFAULT': {'OWNER': None, 'VERSION': '2.0'}}
    
  1435.             >>> rst.metadata
    
  1436.             {'DEFAULT': {'VERSION': '2.0'}}
    
  1437. 
    
  1438.     .. attribute:: vsi_buffer
    
  1439. 
    
  1440.         A ``bytes`` representation of this raster. Returns ``None`` for rasters
    
  1441.         that are not stored in GDAL's virtual filesystem.
    
  1442. 
    
  1443.     .. attribute:: is_vsi_based
    
  1444. 
    
  1445.         A boolean indicating if this raster is stored in GDAL's virtual
    
  1446.         filesystem.
    
  1447. 
    
  1448. ``GDALBand``
    
  1449. ------------
    
  1450. 
    
  1451. .. class:: GDALBand
    
  1452. 
    
  1453.     ``GDALBand`` instances are not created explicitly, but rather obtained
    
  1454.     from a :class:`GDALRaster` object, through its :attr:`~GDALRaster.bands`
    
  1455.     attribute. The GDALBands contain the actual pixel values of the raster.
    
  1456. 
    
  1457.     .. attribute:: description
    
  1458. 
    
  1459.         The name or description of the band, if any.
    
  1460. 
    
  1461.     .. attribute:: width
    
  1462. 
    
  1463.         The width of the band in pixels (X-axis).
    
  1464. 
    
  1465.     .. attribute:: height
    
  1466. 
    
  1467.         The height of the band in pixels (Y-axis).
    
  1468. 
    
  1469.     .. attribute:: pixel_count
    
  1470. 
    
  1471.         The total number of pixels in this band. Is equal to ``width * height``.
    
  1472. 
    
  1473.     .. method:: statistics(refresh=False, approximate=False)
    
  1474. 
    
  1475.         Compute statistics on the pixel values of this band. The return value
    
  1476.         is a tuple with the following structure:
    
  1477.         ``(minimum, maximum, mean, standard deviation)``.
    
  1478. 
    
  1479.         If the ``approximate`` argument is set to ``True``, the statistics may
    
  1480.         be computed based on overviews or a subset of image tiles.
    
  1481. 
    
  1482.         If the ``refresh`` argument is set to ``True``, the statistics will be
    
  1483.         computed from the data directly, and the cache will be updated with the
    
  1484.         result.
    
  1485. 
    
  1486.         If a persistent cache value is found, that value is returned. For
    
  1487.         raster formats using Persistent Auxiliary Metadata (PAM) services, the
    
  1488.         statistics might be cached in an auxiliary file. In some cases this
    
  1489.         metadata might be out of sync with the pixel values or cause values
    
  1490.         from a previous call to be returned which don't reflect the value of
    
  1491.         the ``approximate`` argument. In such cases, use the ``refresh``
    
  1492.         argument to get updated values and store them in the cache.
    
  1493. 
    
  1494.         For empty bands (where all pixel values are "no data"), all statistics
    
  1495.         are returned as ``None``.
    
  1496. 
    
  1497.         The statistics can also be retrieved directly by accessing the
    
  1498.         :attr:`min`, :attr:`max`, :attr:`mean`, and :attr:`std` properties.
    
  1499. 
    
  1500.     .. attribute:: min
    
  1501. 
    
  1502.         The minimum pixel value of the band (excluding the "no data" value).
    
  1503. 
    
  1504.     .. attribute:: max
    
  1505. 
    
  1506.         The maximum pixel value of the band (excluding the "no data" value).
    
  1507. 
    
  1508.     .. attribute:: mean
    
  1509. 
    
  1510.         The mean of all pixel values of the band (excluding the "no data"
    
  1511.         value).
    
  1512. 
    
  1513.     .. attribute:: std
    
  1514. 
    
  1515.         The standard deviation of all pixel values of the band (excluding the
    
  1516.         "no data" value).
    
  1517. 
    
  1518.     .. attribute:: nodata_value
    
  1519. 
    
  1520.         The "no data" value for a band is generally a special marker value used
    
  1521.         to mark pixels that are not valid data. Such pixels should generally not
    
  1522.         be displayed, nor contribute to analysis operations.
    
  1523. 
    
  1524.         To delete an existing "no data" value, set this property to ``None``.
    
  1525. 
    
  1526.     .. method:: datatype(as_string=False)
    
  1527. 
    
  1528.         The data type contained in the band, as an integer constant between 0
    
  1529.         (Unknown) and 11. If ``as_string`` is ``True``, the data type is
    
  1530.         returned as a string with the following possible values:
    
  1531.         ``GDT_Unknown``, ``GDT_Byte``, ``GDT_UInt16``, ``GDT_Int16``,
    
  1532.         ``GDT_UInt32``, ``GDT_Int32``, ``GDT_Float32``, ``GDT_Float64``,
    
  1533.         ``GDT_CInt16``, ``GDT_CInt32``, ``GDT_CFloat32``, and ``GDT_CFloat64``.
    
  1534. 
    
  1535.     .. method:: color_interp(as_string=False)
    
  1536. 
    
  1537.         The color interpretation for the band, as an integer between 0and 16.
    
  1538.         If ``as_string`` is ``True``, the data type is returned as a string
    
  1539.         with the following possible values:
    
  1540.         ``GCI_Undefined``, ``GCI_GrayIndex``, ``GCI_PaletteIndex``,
    
  1541.         ``GCI_RedBand``, ``GCI_GreenBand``, ``GCI_BlueBand``, ``GCI_AlphaBand``,
    
  1542.         ``GCI_HueBand``, ``GCI_SaturationBand``, ``GCI_LightnessBand``,
    
  1543.         ``GCI_CyanBand``, ``GCI_MagentaBand``, ``GCI_YellowBand``,
    
  1544.         ``GCI_BlackBand``, ``GCI_YCbCr_YBand``, ``GCI_YCbCr_CbBand``, and
    
  1545.         ``GCI_YCbCr_CrBand``. ``GCI_YCbCr_CrBand`` also represents ``GCI_Max``
    
  1546.         because both correspond to the integer 16, but only ``GCI_YCbCr_CrBand``
    
  1547.         is returned as a string.
    
  1548. 
    
  1549.     .. method:: data(data=None, offset=None, size=None, shape=None)
    
  1550. 
    
  1551.         The accessor to the pixel values of the ``GDALBand``. Returns the complete
    
  1552.         data array if no parameters are provided. A subset of the pixel array can
    
  1553.         be requested by specifying an offset and block size as tuples.
    
  1554. 
    
  1555.         If NumPy is available, the data is returned as NumPy array. For performance
    
  1556.         reasons, it is highly recommended to use NumPy.
    
  1557. 
    
  1558.         Data is written to the ``GDALBand`` if the ``data`` parameter is provided.
    
  1559.         The input can be of one of the following types - packed string, buffer, list,
    
  1560.         array, and NumPy array. The number of items in the input should normally
    
  1561.         correspond to the total number of pixels in the band, or to the number
    
  1562.         of pixels for a specific block of pixel values if the ``offset`` and
    
  1563.         ``size`` parameters are provided.
    
  1564. 
    
  1565.         If the number of items in the input is different from the target pixel
    
  1566.         block, the ``shape`` parameter must be specified. The shape is a tuple
    
  1567.         that specifies the width and height of the input data in pixels. The
    
  1568.         data is then replicated to update the pixel values of the selected
    
  1569.         block. This is useful to fill an entire band with a single value, for
    
  1570.         instance.
    
  1571. 
    
  1572.         For example:
    
  1573. 
    
  1574.             >>> rst = GDALRaster({'width': 4, 'height': 4, 'srid': 4326, 'datatype': 1, 'nr_of_bands': 1})
    
  1575.             >>> bnd = rst.bands[0]
    
  1576.             >>> bnd.data(range(16))
    
  1577.             >>> bnd.data()
    
  1578.             array([[ 0,  1,  2,  3],
    
  1579.                    [ 4,  5,  6,  7],
    
  1580.                    [ 8,  9, 10, 11],
    
  1581.                    [12, 13, 14, 15]], dtype=int8)
    
  1582.             >>> bnd.data(offset=(1, 1), size=(2, 2))
    
  1583.             array([[ 5,  6],
    
  1584.                    [ 9, 10]], dtype=int8)
    
  1585.             >>> bnd.data(data=[-1, -2, -3, -4], offset=(1, 1), size=(2, 2))
    
  1586.             >>> bnd.data()
    
  1587.             array([[ 0,  1,  2,  3],
    
  1588.                    [ 4, -1, -2,  7],
    
  1589.                    [ 8, -3, -4, 11],
    
  1590.                    [12, 13, 14, 15]], dtype=int8)
    
  1591.             >>> bnd.data(data='\x9d\xa8\xb3\xbe', offset=(1, 1), size=(2, 2))
    
  1592.             >>> bnd.data()
    
  1593.             array([[  0,   1,   2,   3],
    
  1594.                    [  4, -99, -88,   7],
    
  1595.                    [  8, -77, -66,  11],
    
  1596.                    [ 12,  13,  14,  15]], dtype=int8)
    
  1597.             >>> bnd.data([1], shape=(1, 1))
    
  1598.             >>> bnd.data()
    
  1599.             array([[1, 1, 1, 1],
    
  1600.                    [1, 1, 1, 1],
    
  1601.                    [1, 1, 1, 1],
    
  1602.                    [1, 1, 1, 1]], dtype=uint8)
    
  1603.             >>> bnd.data(range(4), shape=(1, 4))
    
  1604.             array([[0, 0, 0, 0],
    
  1605.                    [1, 1, 1, 1],
    
  1606.                    [2, 2, 2, 2],
    
  1607.                    [3, 3, 3, 3]], dtype=uint8)
    
  1608. 
    
  1609.     .. attribute:: metadata
    
  1610. 
    
  1611.         The metadata of this band. The functionality is identical to
    
  1612.         :attr:`GDALRaster.metadata`.
    
  1613. 
    
  1614. .. _gdal-raster-ds-input:
    
  1615. 
    
  1616. Creating rasters from data
    
  1617. --------------------------
    
  1618. 
    
  1619. This section describes how to create rasters from scratch using the
    
  1620. ``ds_input`` parameter.
    
  1621. 
    
  1622. A new raster is created when a ``dict`` is passed to the :class:`GDALRaster`
    
  1623. constructor. The dictionary contains defining parameters of the new raster,
    
  1624. such as the origin, size, or spatial reference system. The dictionary can also
    
  1625. contain pixel data and information about the format of the new raster. The
    
  1626. resulting raster can therefore be file-based or memory-based, depending on the
    
  1627. driver specified.
    
  1628. 
    
  1629. There's no standard for describing raster data in a dictionary or JSON flavor.
    
  1630. The definition of the dictionary input to the :class:`GDALRaster` class is
    
  1631. therefore specific to Django. It's inspired by the `geojson`__ format, but the
    
  1632. ``geojson`` standard is currently limited to vector formats.
    
  1633. 
    
  1634. Examples of using the different keys when creating rasters can be found in the
    
  1635. documentation of the corresponding attributes and methods of the
    
  1636. :class:`GDALRaster` and :class:`GDALBand` classes.
    
  1637. 
    
  1638. __ https://geojson.org/
    
  1639. 
    
  1640. The ``ds_input`` dictionary
    
  1641. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
  1642. 
    
  1643. Only a few keys are required in the ``ds_input`` dictionary to create a raster:
    
  1644. ``width``, ``height``, and ``srid``. All other parameters have default values
    
  1645. (see the table below). The list of keys that can be passed in the ``ds_input``
    
  1646. dictionary is closely related but not identical to the :class:`GDALRaster`
    
  1647. properties. Many of the parameters are mapped directly to those properties;
    
  1648. the others are described below.
    
  1649. 
    
  1650. The following table describes all keys that can be set in the ``ds_input``
    
  1651. dictionary.
    
  1652. 
    
  1653. ================= ======== ==================================================
    
  1654. Key               Default  Usage
    
  1655. ================= ======== ==================================================
    
  1656. ``srid``          required Mapped to the :attr:`~GDALRaster.srid` attribute
    
  1657. ``width``         required Mapped to the :attr:`~GDALRaster.width` attribute
    
  1658. ``height``        required Mapped to the :attr:`~GDALRaster.height` attribute
    
  1659. ``driver``        ``MEM``  Mapped to the :attr:`~GDALRaster.driver` attribute
    
  1660. ``name``          ``''``   See below
    
  1661. ``origin``        ``0``    Mapped to the :attr:`~GDALRaster.origin` attribute
    
  1662. ``scale``         ``0``    Mapped to the :attr:`~GDALRaster.scale` attribute
    
  1663. ``skew``          ``0``    Mapped to the :attr:`~GDALRaster.width` attribute
    
  1664. ``bands``         ``[]``   See below
    
  1665. ``nr_of_bands``   ``0``    See below
    
  1666. ``datatype``      ``6``    See below
    
  1667. ``papsz_options`` ``{}``   See below
    
  1668. ================= ======== ==================================================
    
  1669. 
    
  1670. .. object:: name
    
  1671. 
    
  1672.     String representing the name of the raster. When creating a file-based
    
  1673.     raster, this parameter must be the file path for the new raster. If the
    
  1674.     name starts with ``/vsimem/``, the raster is created in GDAL's virtual
    
  1675.     filesystem.
    
  1676. 
    
  1677. .. object:: datatype
    
  1678. 
    
  1679.     Integer representing the data type for all the bands. Defaults to ``6``
    
  1680.     (Float32). All bands of a new raster are required to have the same datatype.
    
  1681.     The value mapping is:
    
  1682. 
    
  1683.     ===== =============== ===============================
    
  1684.     Value GDAL Pixel Type Description
    
  1685.     ===== =============== ===============================
    
  1686.     1     GDT_Byte        Eight bit unsigned integer
    
  1687.     2     GDT_UInt16      Sixteen bit unsigned integer
    
  1688.     3     GDT_Int16       Sixteen bit signed integer
    
  1689.     4     GDT_UInt32      Thirty-two bit unsigned integer
    
  1690.     5     GDT_Int32       Thirty-two bit signed integer
    
  1691.     6     GDT_Float32     Thirty-two bit floating point
    
  1692.     7     GDT_Float64     Sixty-four bit floating point
    
  1693.     ===== =============== ===============================
    
  1694. 
    
  1695. .. object:: nr_of_bands
    
  1696. 
    
  1697.     Integer representing the number of bands of the raster. A raster can be
    
  1698.     created without passing band data upon creation. If the number of bands
    
  1699.     isn't specified, it's automatically calculated from the length of the
    
  1700.     ``bands`` input. The number of bands can't be changed after creation.
    
  1701. 
    
  1702. .. object:: bands
    
  1703. 
    
  1704.     A list of ``band_input`` dictionaries with band input data. The resulting
    
  1705.     band indices are the same as in the list provided. The definition of the
    
  1706.     band input dictionary is given below. If band data isn't provided, the
    
  1707.     raster bands values are instantiated as an array of zeros and the "no
    
  1708.     data" value is set to ``None``.
    
  1709. 
    
  1710. .. object:: papsz_options
    
  1711. 
    
  1712.     A dictionary with raster creation options. The key-value pairs of the
    
  1713.     input dictionary are passed to the driver on creation of the raster.
    
  1714. 
    
  1715.     The available options are driver-specific and are described in the
    
  1716.     documentation of each driver.
    
  1717. 
    
  1718.     The values in the dictionary are not case-sensitive and are automatically
    
  1719.     converted to the correct string format upon creation.
    
  1720. 
    
  1721.     The following example uses some of the options available for the
    
  1722.     `GTiff driver`__. The result is a compressed signed byte raster with an
    
  1723.     internal tiling scheme. The internal tiles have a block size of 23 by 23::
    
  1724. 
    
  1725.         >>> GDALRaster({
    
  1726.         ...    'driver': 'GTiff',
    
  1727.         ...    'name': '/path/to/new/file.tif',
    
  1728.         ...    'srid': 4326,
    
  1729.         ...    'width': 255,
    
  1730.         ...    'height': 255,
    
  1731.         ...    'nr_of_bands': 1,
    
  1732.         ...    'papsz_options': {
    
  1733.         ...        'compress': 'packbits',
    
  1734.         ...        'pixeltype': 'signedbyte',
    
  1735.         ...        'tiled': 'yes',
    
  1736.         ...        'blockxsize': 23,
    
  1737.         ...        'blockysize': 23,
    
  1738.         ...    }
    
  1739.         ... })
    
  1740. 
    
  1741. __ https://gdal.org/drivers/raster/gtiff.html
    
  1742. 
    
  1743. The ``band_input`` dictionary
    
  1744. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
  1745. 
    
  1746. The ``bands`` key in the ``ds_input`` dictionary is a list of ``band_input``
    
  1747. dictionaries. Each ``band_input`` dictionary can contain pixel values and the
    
  1748. "no data" value to be set on the bands of the new raster. The data array can
    
  1749. have the full size of the new raster or be smaller. For arrays that are smaller
    
  1750. than the full raster, the ``size``, ``shape``, and ``offset`` keys  control the
    
  1751. pixel values. The corresponding keys are passed to the :meth:`~GDALBand.data`
    
  1752. method. Their functionality is the same as setting the band data with that
    
  1753. method. The following table describes the keys that can be used.
    
  1754. 
    
  1755. ================ ================================= ======================================================
    
  1756. Key              Default                           Usage
    
  1757. ================ ================================= ======================================================
    
  1758. ``nodata_value`` ``None``                          Mapped to the :attr:`~GDALBand.nodata_value` attribute
    
  1759. ``data``         Same as ``nodata_value`` or ``0`` Passed to the :meth:`~GDALBand.data` method
    
  1760. ``size``         ``(with, height)`` of raster      Passed to the :meth:`~GDALBand.data` method
    
  1761. ``shape``        Same as size                      Passed to the :meth:`~GDALBand.data` method
    
  1762. ``offset``       ``(0, 0)``                        Passed to the :meth:`~GDALBand.data` method
    
  1763. ================ ================================= ======================================================
    
  1764. 
    
  1765. .. _gdal-raster-vsimem:
    
  1766. 
    
  1767. Using GDAL's Virtual Filesystem
    
  1768. -------------------------------
    
  1769. 
    
  1770. GDAL can access files stored in the filesystem, but also supports virtual
    
  1771. filesystems to abstract accessing other kind of files, such as compressed,
    
  1772. encrypted, or remote files.
    
  1773. 
    
  1774. Using memory-based Virtual Filesystem
    
  1775. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
  1776. 
    
  1777. GDAL has an internal memory-based filesystem, which allows treating blocks of
    
  1778. memory as files. It can be used to read and write :class:`GDALRaster` objects
    
  1779. to and from binary file buffers.
    
  1780. 
    
  1781. This is useful in web contexts where rasters might be obtained as a buffer
    
  1782. from a remote storage or returned from a view without being written to disk.
    
  1783. 
    
  1784. :class:`GDALRaster` objects are created in the virtual filesystem when a
    
  1785. ``bytes`` object is provided as input, or when the file path starts with
    
  1786. ``/vsimem/``.
    
  1787. 
    
  1788. Input provided as ``bytes`` has to be a full binary representation of a file.
    
  1789. For instance::
    
  1790. 
    
  1791.     # Read a raster as a file object from a remote source.
    
  1792.     >>> from urllib.request import urlopen
    
  1793.     >>> dat = urlopen('http://example.com/raster.tif').read()
    
  1794.     # Instantiate a raster from the bytes object.
    
  1795.     >>> rst = GDALRaster(dat)
    
  1796.     # The name starts with /vsimem/, indicating that the raster lives in the
    
  1797.     # virtual filesystem.
    
  1798.     >>> rst.name
    
  1799.     '/vsimem/da300bdb-129d-49a8-b336-e410a9428dad'
    
  1800. 
    
  1801. To create a new virtual file-based raster from scratch, use the ``ds_input``
    
  1802. dictionary representation and provide a ``name`` argument that starts with
    
  1803. ``/vsimem/`` (for detail of the dictionary representation, see
    
  1804. :ref:`gdal-raster-ds-input`). For virtual file-based rasters, the
    
  1805. :attr:`~GDALRaster.vsi_buffer` attribute returns the ``bytes`` representation
    
  1806. of the raster.
    
  1807. 
    
  1808. Here's how to create a raster and return it as a file in an
    
  1809. :class:`~django.http.HttpResponse`::
    
  1810. 
    
  1811.     >>> from django.http import HttpResponse
    
  1812.     >>> rst = GDALRaster({
    
  1813.     ...     'name': '/vsimem/temporarymemfile',
    
  1814.     ...     'driver': 'tif',
    
  1815.     ...     'width': 6, 'height': 6, 'srid': 3086,
    
  1816.     ...     'origin': [500000, 400000],
    
  1817.     ...     'scale': [100, -100],
    
  1818.     ...     'bands': [{'data': range(36), 'nodata_value': 99}]
    
  1819.     ... })
    
  1820.     >>> HttpResponse(rast.vsi_buffer, 'image/tiff')
    
  1821. 
    
  1822. Using other Virtual Filesystems
    
  1823. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
  1824. 
    
  1825. .. versionadded:: 4.0
    
  1826. 
    
  1827. Depending on the local build of GDAL other virtual filesystems may be
    
  1828. supported. You can use them by prepending the provided path with the
    
  1829. appropriate ``/vsi*/`` prefix. See the `GDAL Virtual Filesystems
    
  1830. documentation`_ for more details.
    
  1831. 
    
  1832. .. warning:
    
  1833. 
    
  1834.     Rasters with names starting with `/vsi*/` will be treated as rasters from
    
  1835.     the GDAL virtual filesystems. Django doesn't perform any extra validation.
    
  1836. 
    
  1837. Compressed rasters
    
  1838. ^^^^^^^^^^^^^^^^^^
    
  1839. 
    
  1840. Instead decompressing the file and instantiating the resulting raster, GDAL can
    
  1841. directly access compressed files using the ``/vsizip/``, ``/vsigzip/``, or
    
  1842. ``/vsitar/`` virtual filesystems::
    
  1843. 
    
  1844.    >>> from django.contrib.gis.gdal import GDALRaster
    
  1845.    >>> rst = GDALRaster('/vsizip/path/to/your/file.zip/path/to/raster.tif')
    
  1846.    >>> rst = GDALRaster('/vsigzip/path/to/your/file.gz')
    
  1847.    >>> rst = GDALRaster('/vsitar/path/to/your/file.tar/path/to/raster.tif')
    
  1848. 
    
  1849. Network rasters
    
  1850. ^^^^^^^^^^^^^^^
    
  1851. 
    
  1852. GDAL can support online resources and storage providers transparently. As long
    
  1853. as it's built with such capabilities.
    
  1854. 
    
  1855. To access a public raster file with no authentication, you can use
    
  1856. ``/vsicurl/``::
    
  1857. 
    
  1858.    >>> from django.contrib.gis.gdal import GDALRaster
    
  1859.    >>> rst = GDALRaster('/vsicurl/https://example.com/raster.tif')
    
  1860.    >>> rst.name
    
  1861.    '/vsicurl/https://example.com/raster.tif'
    
  1862. 
    
  1863. For commercial storage providers (e.g. ``/vsis3/``) the system should be
    
  1864. previously configured for authentication and possibly other settings (see the
    
  1865. `GDAL Virtual Filesystems documentation`_ for available options).
    
  1866. 
    
  1867. .. _`GDAL Virtual Filesystems documentation`: https://gdal.org/user/virtual_file_systems.html
    
  1868. 
    
  1869. Settings
    
  1870. ========
    
  1871. 
    
  1872. .. setting:: GDAL_LIBRARY_PATH
    
  1873. 
    
  1874. ``GDAL_LIBRARY_PATH``
    
  1875. ---------------------
    
  1876. 
    
  1877. A string specifying the location of the GDAL library.  Typically,
    
  1878. this setting is only used if the GDAL library is in a non-standard
    
  1879. location (e.g., ``/home/john/lib/libgdal.so``).
    
  1880. 
    
  1881. Exceptions
    
  1882. ==========
    
  1883. 
    
  1884. .. exception:: GDALException
    
  1885. 
    
  1886.     The base GDAL exception, indicating a GDAL-related error.
    
  1887. 
    
  1888. .. exception:: SRSException
    
  1889. 
    
  1890.     An exception raised when an error occurs when constructing or using a
    
  1891.     spatial reference system object.